diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 663ace48e9e80..9fd8054a12e46 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -23,3 +23,5 @@ b2d2184edea578109a48ec3d8decbee5948e8f35 # test directives migration 6e48b96692d63a79a14563f27fe5185f122434f8 ec2cc761bc7067712ecc7734502f703fe3b024c8 +# format use declarations +84ac80f1921afc243d71fd0caaa4f2838c294102 diff --git a/.gitignore b/.gitignore index 87d02563ed048..aabec0988a99e 100644 --- a/.gitignore +++ b/.gitignore @@ -48,6 +48,7 @@ build/ /dist/ /unicode-downloads /target +/library/target /src/bootstrap/target /src/tools/x/target # Created by default with `src/ci/docker/run.sh` diff --git a/.gitmodules b/.gitmodules index 9ad207a0d5226..b5250d493864e 100644 --- a/.gitmodules +++ b/.gitmodules @@ -33,7 +33,7 @@ [submodule "src/llvm-project"] path = src/llvm-project url = https://github.com/rust-lang/llvm-project.git - branch = rustc/18.1-2024-05-19 + branch = rustc/19.1-2024-07-30 shallow = true [submodule "src/doc/embedded-book"] path = src/doc/embedded-book diff --git a/.mailmap b/.mailmap index 33673244be6d0..4d93792422c23 100644 --- a/.mailmap +++ b/.mailmap @@ -435,7 +435,7 @@ Nick Platt Niclas Schwarzlose <15schnic@gmail.com> Nicolas Abram Nicole Mazzuca -Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> nils <48135649+Nilstrieb@users.noreply.github.com> +Noratrieb <48135649+Noratrieb@users.noreply.github.com> <48135649+Nilstrieb@users.noreply.github.com> Nif Ward Nika Layzell NODA Kai diff --git a/Cargo.lock b/Cargo.lock index 146070cf16713..a4b4e49f82c2e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11,27 +11,11 @@ dependencies = [ "gimli 0.28.1", ] -[[package]] -name = "addr2line" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" -dependencies = [ - "compiler_builtins", - "gimli 0.29.0", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - [[package]] name = "adler" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] [[package]] name = "aes" @@ -66,16 +50,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "alloc" -version = "0.0.0" -dependencies = [ - "compiler_builtins", - "core", - "rand", - "rand_xorshift", -] - [[package]] name = "allocator-api2" version = "0.2.18" @@ -256,7 +230,7 @@ version = "0.3.71" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d" dependencies = [ - "addr2line 0.21.0", + "addr2line", "cc", "cfg-if", "libc", @@ -455,10 +429,6 @@ 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 = "cfg_aliases" @@ -573,7 +543,7 @@ checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70" [[package]] name = "clippy" -version = "0.1.81" +version = "0.1.82" dependencies = [ "anstream", "clippy_config", @@ -594,13 +564,13 @@ dependencies = [ "termize", "tokio", "toml 0.7.8", - "ui_test 0.23.0", + "ui_test 0.24.0", "walkdir", ] [[package]] name = "clippy_config" -version = "0.1.81" +version = "0.1.82" dependencies = [ "rustc-semver", "serde", @@ -623,7 +593,7 @@ dependencies = [ [[package]] name = "clippy_lints" -version = "0.1.81" +version = "0.1.82" dependencies = [ "arrayvec", "cargo_metadata 0.18.1", @@ -648,7 +618,7 @@ dependencies = [ [[package]] name = "clippy_utils" -version = "0.1.81" +version = "0.1.82" dependencies = [ "arrayvec", "clippy_config", @@ -737,16 +707,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55b672471b4e9f9e95499ea597ff64941a309b2cdbffcc46f2cc5e2d971fd335" -[[package]] -name = "compiler_builtins" -version = "0.1.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f11973008a8cf741fe6d22f339eba21fd0ca81e2760a769ba8243ed6c21edd7e" -dependencies = [ - "cc", - "rustc-std-workspace-core", -] - [[package]] name = "compiletest" version = "0.0.0" @@ -771,7 +731,7 @@ dependencies = [ "tracing-subscriber", "unified-diff", "walkdir", - "windows", + "windows 0.52.0", ] [[package]] @@ -787,14 +747,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "core" -version = "0.0.0" -dependencies = [ - "rand", - "rand_xorshift", -] - [[package]] name = "core-foundation-sys" version = "0.8.6" @@ -969,7 +921,7 @@ dependencies = [ [[package]] name = "declare_clippy_lint" -version = "0.1.81" +version = "0.1.82" dependencies = [ "itertools", "quote", @@ -986,14 +938,14 @@ dependencies = [ ] [[package]] -name = "derivative" -version = "2.2.0" +name = "derive-where" +version = "1.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +checksum = "62d671cc41a825ebabc75757b62d3d168c577f9149b2d49ece1dad1f72119d25" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.67", ] [[package]] @@ -1134,19 +1086,6 @@ version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59f8e79d1fbf76bdfbde321e902714bf6c49df88a7dda6fc682fc2979226962d" -[[package]] -name = "dlmalloc" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3264b043b8e977326c1ee9e723da2c1f8d09a99df52cacf00b4dbce5ac54414d" -dependencies = [ - "cfg-if", - "compiler_builtins", - "libc", - "rustc-std-workspace-core", - "windows-sys 0.52.0", -] - [[package]] name = "either" version = "1.12.0" @@ -1348,16 +1287,6 @@ dependencies = [ "percent-encoding", ] -[[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 = "fs-err" version = "2.11.0" @@ -1504,8 +1433,6 @@ 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", ] @@ -1526,25 +1453,11 @@ version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" dependencies = [ - "compiler_builtins", "fallible-iterator", "indexmap", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", "stable_deref_trait", ] -[[package]] -name = "gimli" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - [[package]] name = "gimli" version = "0.31.0" @@ -1606,9 +1519,6 @@ checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ "ahash", "allocator-api2", - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", "serde", ] @@ -1630,17 +1540,6 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" -[[package]] -name = "hermit-abi" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - [[package]] name = "hex" version = "0.4.3" @@ -1713,7 +1612,7 @@ dependencies = [ "iana-time-zone-haiku", "js-sys", "wasm-bindgen", - "windows-core", + "windows-core 0.52.0", ] [[package]] @@ -2065,9 +1964,6 @@ name = "libc" version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" -dependencies = [ - "rustc-std-workspace-core", -] [[package]] name = "libdbus-sys" @@ -2299,10 +2195,6 @@ name = "memchr" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] [[package]] name = "memmap2" @@ -2357,9 +2249,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" dependencies = [ "adler", - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", ] [[package]] @@ -2393,6 +2282,7 @@ dependencies = [ "smallvec", "tempfile", "ui_test 0.21.2", + "windows-sys 0.52.0", ] [[package]] @@ -2436,15 +2326,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "ntapi" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8a3895c6391c39d7fe7ebc444a87eb2991b2a0bc718fdabd071eec617fc68e4" -dependencies = [ - "winapi", -] - [[package]] name = "nu-ansi-term" version = "0.46.0" @@ -2549,7 +2430,7 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ - "hermit-abi 0.3.9", + "hermit-abi", "libc", ] @@ -2571,18 +2452,6 @@ dependencies = [ "indexmap", "memchr", "ruzstd 0.5.0", - "wasmparser 0.118.2", -] - -[[package]] -name = "object" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7090bae93f8585aad99e595b7073c5de9ba89fbd6b4e9f0cdd7a10177273ac8" -dependencies = [ - "flate2", - "memchr", - "ruzstd 0.6.0", ] [[package]] @@ -2596,14 +2465,17 @@ dependencies = [ [[package]] name = "object" -version = "0.36.0" +version = "0.36.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "576dfe1fc8f9df304abb159d767a29d0476f7750fbf8aa7ad07816004a207434" +checksum = "3f203fa8daa7bb185f760ae12bd8e097f63d17041dcdcaf675ac54cdf863170e" dependencies = [ - "compiler_builtins", + "crc32fast", + "flate2", + "hashbrown", + "indexmap", "memchr", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", + "ruzstd 0.7.0", + "wasmparser 0.214.0", ] [[package]] @@ -2725,29 +2597,6 @@ dependencies = [ "unicode-width", ] -[[package]] -name = "panic_abort" -version = "0.0.0" -dependencies = [ - "alloc", - "cfg-if", - "compiler_builtins", - "core", - "libc", -] - -[[package]] -name = "panic_unwind" -version = "0.0.0" -dependencies = [ - "alloc", - "cfg-if", - "compiler_builtins", - "core", - "libc", - "unwind", -] - [[package]] name = "papergrid" version = "0.11.0" @@ -2977,6 +2826,16 @@ dependencies = [ "pad", ] +[[package]] +name = "prettydiff" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abec3fb083c10660b3854367697da94c674e9e82aa7511014dc958beeb7215e9" +dependencies = [ + "owo-colors", + "pad", +] + [[package]] name = "proc-macro-hack" version = "0.5.20+deprecated" @@ -2992,23 +2851,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "proc_macro" -version = "0.0.0" -dependencies = [ - "core", - "std", -] - -[[package]] -name = "profiler_builtins" -version = "0.0.0" -dependencies = [ - "cc", - "compiler_builtins", - "core", -] - [[package]] name = "psm" version = "0.1.21" @@ -3086,27 +2928,6 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "r-efi" -version = "4.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9e935efc5854715dfc0a4c9ef18dc69dee0ec3bf9cc3ab740db831c0fdd86a3" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "r-efi-alloc" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31d6f09fe2b6ad044bc3d2c34ce4979796581afd2f1ebc185837e02421e02fd7" -dependencies = [ - "compiler_builtins", - "r-efi", - "rustc-std-workspace-core", -] - [[package]] name = "rand" version = "0.8.5" @@ -3137,15 +2958,6 @@ dependencies = [ "getrandom", ] -[[package]] -name = "rand_xorshift" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f" -dependencies = [ - "rand_core", -] - [[package]] name = "rand_xoshiro" version = "0.6.0" @@ -3287,20 +3099,22 @@ dependencies = [ [[package]] name = "rinja" -version = "0.2.0" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2d47a46d7729e891c8accf260e9daa02ae6d570aa2a94fb1fb27eb5364a2323" +checksum = "6d3762e3740cdbf2fd2be465cc2c26d643ad17353cc2e0223d211c1b096118bd" dependencies = [ + "itoa", "rinja_derive", ] [[package]] name = "rinja_derive" -version = "0.2.0" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44dae9afe59d58ed8d988d67d1945f3638125d2fd2104058399382e11bd3ea2a" +checksum = "fd01fd8e15e7d19c8b8052c1d428325131e02ff1633cdcf695190c2e56ab682c" dependencies = [ "basic-toml", + "memchr", "mime", "mime_guess", "once_map", @@ -3313,10 +3127,11 @@ dependencies = [ [[package]] name = "rinja_parser" -version = "0.2.0" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b1771c78cd5d3b1646ef8d8f2ed100db936e8b291d3cc06e92a339ff346858c" +checksum = "a2f6bf7cef118c6de21206edf0b3f19f5ede60006be674a58ca21b6e003a1b57" dependencies = [ + "memchr", "nom", ] @@ -3334,17 +3149,17 @@ dependencies = [ "bstr", "build_helper", "gimli 0.31.0", - "object 0.34.0", + "object 0.36.2", "regex", "similar", - "wasmparser 0.118.2", + "wasmparser 0.214.0", ] [[package]] name = "rustc-build-sysroot" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa3ca63cc537c1cb69e4c2c0afc5fda2ccd36ac84c97d5a4ae05e69b1c834afb" +checksum = "2471f8f296262437d7e848e527b4210b44a96e53a3b4435b890227ce3e6da106" dependencies = [ "anyhow", "rustc_version", @@ -3357,10 +3172,6 @@ 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-hash" @@ -3421,27 +3232,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5c9f15eec8235d7cb775ee6f81891db79b98fd54ba1ad8fae565b88ef1ae4e2" -[[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 = "rustc_abi" version = "0.0.0" @@ -3643,7 +3433,7 @@ dependencies = [ "itertools", "libc", "measureme", - "object 0.32.2", + "object 0.36.2", "rustc-demangle", "rustc_ast", "rustc_attr", @@ -3682,7 +3472,7 @@ dependencies = [ "itertools", "jobserver", "libc", - "object 0.32.2", + "object 0.36.2", "pathdiff", "regex", "rustc_arena", @@ -3712,8 +3502,8 @@ dependencies = [ "thin-vec", "thorin-dwp", "tracing", - "wasm-encoder 0.200.0", - "windows", + "wasm-encoder 0.210.0", + "windows 0.52.0", ] [[package]] @@ -3770,7 +3560,7 @@ dependencies = [ "tempfile", "thin-vec", "tracing", - "windows", + "windows 0.52.0", ] [[package]] @@ -3831,7 +3621,7 @@ dependencies = [ "shlex", "time", "tracing", - "windows", + "windows 0.52.0", ] [[package]] @@ -3882,8 +3672,7 @@ dependencies = [ "termcolor", "termize", "tracing", - "unicode-width", - "windows", + "windows 0.52.0", ] [[package]] @@ -4249,7 +4038,7 @@ name = "rustc_middle" version = "0.0.0" dependencies = [ "bitflags 2.5.0", - "derivative", + "derive-where", "either", "field-offset", "gsgdt", @@ -4352,6 +4141,7 @@ dependencies = [ "rustc_span", "rustc_target", "rustc_trait_selection", + "rustc_type_ir", "smallvec", "tracing", ] @@ -4379,7 +4169,7 @@ name = "rustc_next_trait_solver" version = "0.0.0" dependencies = [ "bitflags 2.5.0", - "derivative", + "derive-where", "rustc_ast_ir", "rustc_data_structures", "rustc_index", @@ -4604,7 +4394,7 @@ dependencies = [ "smallvec", "termize", "tracing", - "windows", + "windows 0.52.0", ] [[package]] @@ -4629,7 +4419,7 @@ dependencies = [ name = "rustc_span" version = "0.0.0" dependencies = [ - "derivative", + "derive-where", "indexmap", "itoa", "md-5", @@ -4666,7 +4456,7 @@ name = "rustc_target" version = "0.0.0" dependencies = [ "bitflags 2.5.0", - "object 0.32.2", + "object 0.36.2", "rustc_abi", "rustc_data_structures", "rustc_feature", @@ -4769,7 +4559,7 @@ name = "rustc_type_ir" version = "0.0.0" dependencies = [ "bitflags 2.5.0", - "derivative", + "derive-where", "indexmap", "rustc_ast_ir", "rustc_data_structures", @@ -4823,6 +4613,7 @@ dependencies = [ "tracing", "tracing-subscriber", "tracing-tree", + "unicode-segmentation", ] [[package]] @@ -4951,12 +4742,11 @@ dependencies = [ [[package]] name = "ruzstd" -version = "0.6.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5174a470eeb535a721ae9fdd6e291c2411a906b96592182d05217591d5c5cf7b" +checksum = "5022b253619b1ba797f243056276bed8ed1a73b0f5a7ce7225d524067644bf8f" dependencies = [ "byteorder", - "derive_more", "twox-hash", ] @@ -5206,6 +4996,7 @@ name = "stable_mir" version = "0.1.0-preview" dependencies = [ "scoped-tls", + "serde", ] [[package]] @@ -5227,46 +5018,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" -[[package]] -name = "std" -version = "0.0.0" -dependencies = [ - "addr2line 0.22.0", - "alloc", - "cfg-if", - "compiler_builtins", - "core", - "dlmalloc", - "fortanix-sgx-abi", - "hashbrown", - "hermit-abi 0.4.0", - "libc", - "miniz_oxide", - "object 0.36.0", - "panic_abort", - "panic_unwind", - "profiler_builtins", - "r-efi", - "r-efi-alloc", - "rand", - "rand_xorshift", - "rustc-demangle", - "std_detect", - "unwind", - "wasi", -] - -[[package]] -name = "std_detect" -version = "0.1.5" -dependencies = [ - "cfg-if", - "compiler_builtins", - "libc", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - [[package]] name = "string_cache" version = "0.8.7" @@ -5361,25 +5112,13 @@ dependencies = [ [[package]] name = "sysinfo" -version = "0.30.12" +version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "732ffa00f53e6b2af46208fba5718d9662a421049204e156328b66791ffa15ae" +checksum = "d4115055da5f572fff541dd0c4e61b0262977f453cc9fe04be83aba25a89bdab" dependencies = [ - "cfg-if", "core-foundation-sys", "libc", - "ntapi", - "once_cell", - "windows", -] - -[[package]] -name = "sysroot" -version = "0.0.0" -dependencies = [ - "proc_macro", - "std", - "test", + "windows 0.57.0", ] [[package]] @@ -5466,16 +5205,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "test" -version = "0.0.0" -dependencies = [ - "core", - "getopts", - "libc", - "std", -] - [[package]] name = "test-float-parse" version = "0.1.0" @@ -5825,7 +5554,7 @@ dependencies = [ "indicatif", "lazy_static", "levenshtein", - "prettydiff", + "prettydiff 0.6.4", "regex", "rustc_version", "rustfix 0.6.1", @@ -5836,9 +5565,9 @@ dependencies = [ [[package]] name = "ui_test" -version = "0.23.0" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29e5f4ffcbab82453958fbf59990e981b8e8a177dcd60c2bd8f9b52c3036a6e1" +checksum = "bc1c6c78d55482388711c8d417b8e547263046a607512278fed274c54633bbe4" dependencies = [ "annotate-snippets 0.11.4", "anyhow", @@ -5852,14 +5581,13 @@ dependencies = [ "indicatif", "lazy_static", "levenshtein", - "prettydiff", + "prettydiff 0.7.0", "regex", "rustc_version", "rustfix 0.8.1", "serde", "serde_json", "spanned", - "tempfile", ] [[package]] @@ -5975,11 +5703,6 @@ name = "unicode-width" version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", - "rustc-std-workspace-std", -] [[package]] name = "unicode-xid" @@ -6004,28 +5727,6 @@ dependencies = [ "tidy", ] -[[package]] -name = "unwind" -version = "0.0.0" -dependencies = [ - "cfg-if", - "compiler_builtins", - "core", - "libc", - "unwinding", -] - -[[package]] -name = "unwinding" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37a19a21a537f635c16c7576f22d0f2f7d63353c1337ad4ce0d8001c7952a25b" -dependencies = [ - "compiler_builtins", - "gimli 0.28.1", - "rustc-std-workspace-core", -] - [[package]] name = "url" version = "2.5.2" @@ -6097,11 +5798,6 @@ 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 = "wasm-bindgen" @@ -6179,15 +5875,6 @@ dependencies = [ "wasm-component-ld", ] -[[package]] -name = "wasm-encoder" -version = "0.200.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e3fb0c8fbddd78aa6095b850dfeedbc7506cf5f81e633f69cf8f2333ab84b9" -dependencies = [ - "leb128", -] - [[package]] name = "wasm-encoder" version = "0.210.0" @@ -6224,26 +5911,26 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.118.2" +version = "0.210.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77f1154f1ab868e2a01d9834a805faca7bf8b50d041b4ca714d005d0dab1c50c" +checksum = "a7bbcd21e7581619d9f6ca00f8c4f08f1cacfe58bf63f83af57cd0476f1026f5" dependencies = [ + "ahash", + "bitflags 2.5.0", + "hashbrown", "indexmap", "semver", + "serde", ] [[package]] name = "wasmparser" -version = "0.210.0" +version = "0.214.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7bbcd21e7581619d9f6ca00f8c4f08f1cacfe58bf63f83af57cd0476f1026f5" +checksum = "5309c1090e3e84dad0d382f42064e9933fdaedb87e468cc239f0eabea73ddcb6" dependencies = [ - "ahash", "bitflags 2.5.0", - "hashbrown", "indexmap", - "semver", - "serde", ] [[package]] @@ -6305,7 +5992,17 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" dependencies = [ - "windows-core", + "windows-core 0.52.0", + "windows-targets 0.52.5", +] + +[[package]] +name = "windows" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143" +dependencies = [ + "windows-core 0.57.0", "windows-targets 0.52.5", ] @@ -6332,12 +6029,55 @@ dependencies = [ "windows-targets 0.52.5", ] +[[package]] +name = "windows-core" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-result", + "windows-targets 0.52.5", +] + +[[package]] +name = "windows-implement" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.67", +] + +[[package]] +name = "windows-interface" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.67", +] + [[package]] name = "windows-metadata" version = "0.58.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e837f3c3012cfe9e7086302a93f441a7999439be1ad4c530d55d2f6d2921809" +[[package]] +name = "windows-result" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" +dependencies = [ + "windows-targets 0.52.5", +] + [[package]] name = "windows-sys" version = "0.48.0" diff --git a/Cargo.toml b/Cargo.toml index 178a5ab940889..131feec70abcd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,8 +2,6 @@ resolver = "1" members = [ "compiler/rustc", - "library/std", - "library/sysroot", "src/etc/test-float-parse", "src/rustdoc-json-types", "src/tools/build_helper", @@ -61,23 +59,8 @@ exclude = [ # not all `Cargo.toml` files are available, so we exclude the `x` binary, # so it can be invoked before the current checkout is set up. "src/tools/x", - # stdarch has its own Cargo workspace - "library/stdarch", ] -[profile.release.package.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. -codegen-units = 10000 - [profile.release.package.rustc-rayon-core] # The rustc fork of Rayon has deadlock detection code which intermittently # causes overflows in the CI (see https://github.com/rust-lang/rust/issues/90227) @@ -85,19 +68,6 @@ codegen-units = 10000 # FIXME: This workaround should be removed once #90227 is fixed. overflow-checks = false -# These dependencies of the standard library implement symbolication for -# backtraces on most platforms. Their debuginfo causes both linking to be slower -# (more data to chew through) and binaries to be larger without really all that -# much benefit. This section turns them all to down to have no debuginfo which -# helps to improve link times a little bit. -[profile.release.package] -addr2line.debug = 0 -adler.debug = 0 -gimli.debug = 0 -miniz_oxide.debug = 0 -object.debug = 0 -rustc-demangle.debug = 0 - # These are very thin wrappers around executing lld with the right binary name. # Basically nothing within them can go wrong without having been explicitly logged anyway. # We ship these in every rustc tarball and even after compression they add up @@ -120,10 +90,3 @@ codegen-units = 1 # FIXME: LTO cannot be enabled for binaries in a workspace # # lto = true - -[patch.crates-io] -# See comments in `library/rustc-std-workspace-core/README.md` for what's going on -# here -rustc-std-workspace-core = { path = 'library/rustc-std-workspace-core' } -rustc-std-workspace-alloc = { path = 'library/rustc-std-workspace-alloc' } -rustc-std-workspace-std = { path = 'library/rustc-std-workspace-std' } diff --git a/RELEASES.md b/RELEASES.md index 0ecd472efb6e2..2c91ddf782674 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,4 +1,4 @@ -Version 1.80 (2024-07-25) +Version 1.80.0 (2024-07-25) ========================== diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index 197dd7f9c9e59..5160b4ed0a2ac 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -1,9 +1,7 @@ use std::borrow::{Borrow, Cow}; -use std::cmp; use std::fmt::{self, Write}; -use std::iter; -use std::ops::Bound; -use std::ops::Deref; +use std::ops::{Bound, Deref}; +use std::{cmp, iter}; use rustc_index::Idx; use tracing::debug; @@ -982,7 +980,8 @@ fn univariant< if repr.can_randomize_type_layout() && cfg!(feature = "randomize") { #[cfg(feature = "randomize")] { - use rand::{seq::SliceRandom, SeedableRng}; + use rand::seq::SliceRandom; + use rand::SeedableRng; // `ReprOptions.field_shuffle_seed` is a deterministic seed we can use to randomize field // ordering. let mut rng = diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 52ec41f643c0d..3dc548c4554a3 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -6,21 +6,20 @@ // tidy-alphabetical-end use std::fmt; +#[cfg(feature = "nightly")] +use std::iter::Step; use std::num::{NonZeroUsize, ParseIntError}; use std::ops::{Add, AddAssign, Mul, RangeInclusive, Sub}; use std::str::FromStr; use bitflags::bitflags; -use rustc_index::{Idx, IndexSlice, IndexVec}; - #[cfg(feature = "nightly")] use rustc_data_structures::stable_hasher::StableOrd; +use rustc_index::{Idx, IndexSlice, IndexVec}; #[cfg(feature = "nightly")] use rustc_macros::HashStable_Generic; #[cfg(feature = "nightly")] use rustc_macros::{Decodable_Generic, Encodable_Generic}; -#[cfg(feature = "nightly")] -use std::iter::Step; mod layout; #[cfg(test)] @@ -517,7 +516,7 @@ impl Size { /// Truncates `value` to `self` bits and then sign-extends it to 128 bits /// (i.e., if it is negative, fill with 1's on the left). #[inline] - pub fn sign_extend(self, value: u128) -> u128 { + pub fn sign_extend(self, value: u128) -> i128 { let size = self.bits(); if size == 0 { // Truncated until nothing is left. @@ -527,7 +526,7 @@ impl Size { let shift = 128 - size; // Shift the unsigned value to the left, then shift back to the right as signed // (essentially fills with sign bit on the left). - (((value << shift) as i128) >> shift) as u128 + ((value << shift) as i128) >> shift } /// Truncates `value` to `self` bits. @@ -545,7 +544,7 @@ impl Size { #[inline] pub fn signed_int_min(&self) -> i128 { - self.sign_extend(1_u128 << (self.bits() - 1)) as i128 + self.sign_extend(1_u128 << (self.bits() - 1)) } #[inline] diff --git a/compiler/rustc_arena/src/lib.rs b/compiler/rustc_arena/src/lib.rs index 810cb7a9f4598..f5f01348e4612 100644 --- a/compiler/rustc_arena/src/lib.rs +++ b/compiler/rustc_arena/src/lib.rs @@ -27,15 +27,14 @@ #![feature(strict_provenance)] // tidy-alphabetical-end -use smallvec::SmallVec; - use std::alloc::Layout; use std::cell::{Cell, RefCell}; use std::marker::PhantomData; use std::mem::{self, MaybeUninit}; use std::ptr::{self, NonNull}; -use std::slice; -use std::{cmp, intrinsics}; +use std::{cmp, intrinsics, slice}; + +use smallvec::SmallVec; /// This calls the passed function while ensuring it won't be inlined into the caller. #[inline(never)] diff --git a/compiler/rustc_arena/src/tests.rs b/compiler/rustc_arena/src/tests.rs index 49a070badc6de..9eaa292e9893c 100644 --- a/compiler/rustc_arena/src/tests.rs +++ b/compiler/rustc_arena/src/tests.rs @@ -1,8 +1,10 @@ extern crate test; -use super::TypedArena; use std::cell::Cell; + use test::Bencher; +use super::TypedArena; + #[allow(dead_code)] #[derive(Debug, Eq, PartialEq)] struct Point { diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 75c656973f963..fc1af3fc3dd11 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -18,15 +18,9 @@ //! - [`Attribute`]: Metadata associated with item. //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators. -pub use crate::format::*; -pub use crate::util::parser::ExprPrecedence; -pub use rustc_span::AttrId; -pub use GenericArgs::*; -pub use UnsafeSource::*; +use std::borrow::Cow; +use std::{cmp, fmt, mem}; -use crate::ptr::P; -use crate::token::{self, CommentKind, Delimiter}; -use crate::tokenstream::{DelimSpan, LazyAttrTokenStream, TokenStream}; pub use rustc_ast_ir::{Movability, Mutability}; use rustc_data_structures::packed::Pu128; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; @@ -35,11 +29,17 @@ use rustc_data_structures::sync::Lrc; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_span::source_map::{respan, Spanned}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; +pub use rustc_span::AttrId; use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; -use std::cmp; -use std::fmt; -use std::mem; use thin_vec::{thin_vec, ThinVec}; +pub use GenericArgs::*; +pub use UnsafeSource::*; + +pub use crate::format::*; +use crate::ptr::P; +use crate::token::{self, CommentKind, Delimiter}; +use crate::tokenstream::{DelimSpan, LazyAttrTokenStream, TokenStream}; +pub use crate::util::parser::ExprPrecedence; /// A "Label" is an identifier of some point in sources, /// e.g. in the following code: @@ -2264,6 +2264,47 @@ bitflags::bitflags! { } } +impl InlineAsmOptions { + pub const COUNT: usize = Self::all().bits().count_ones() as usize; + + pub const GLOBAL_OPTIONS: Self = Self::ATT_SYNTAX.union(Self::RAW); + pub const NAKED_OPTIONS: Self = Self::ATT_SYNTAX.union(Self::RAW).union(Self::NORETURN); + + pub fn human_readable_names(&self) -> Vec<&'static str> { + let mut options = vec![]; + + if self.contains(InlineAsmOptions::PURE) { + options.push("pure"); + } + if self.contains(InlineAsmOptions::NOMEM) { + options.push("nomem"); + } + if self.contains(InlineAsmOptions::READONLY) { + options.push("readonly"); + } + if self.contains(InlineAsmOptions::PRESERVES_FLAGS) { + options.push("preserves_flags"); + } + if self.contains(InlineAsmOptions::NORETURN) { + options.push("noreturn"); + } + if self.contains(InlineAsmOptions::NOSTACK) { + options.push("nostack"); + } + if self.contains(InlineAsmOptions::ATT_SYNTAX) { + options.push("att_syntax"); + } + if self.contains(InlineAsmOptions::RAW) { + options.push("raw"); + } + if self.contains(InlineAsmOptions::MAY_UNWIND) { + options.push("may_unwind"); + } + + options + } +} + impl std::fmt::Debug for InlineAsmOptions { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { bitflags::parser::to_writer(self, f) @@ -2272,7 +2313,7 @@ impl std::fmt::Debug for InlineAsmOptions { #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)] pub enum InlineAsmTemplatePiece { - String(String), + String(Cow<'static, str>), Placeholder { operand_idx: usize, modifier: Option, span: Span }, } @@ -3449,8 +3490,9 @@ pub type ForeignItem = Item; // Some nodes are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(AssocItem, 88); static_assert_size!(AssocItemKind, 16); diff --git a/compiler/rustc_ast/src/ast_traits.rs b/compiler/rustc_ast/src/ast_traits.rs index 7754ca0a0f503..6b95fb7dd36b8 100644 --- a/compiler/rustc_ast/src/ast_traits.rs +++ b/compiler/rustc_ast/src/ast_traits.rs @@ -2,16 +2,17 @@ //! typically those used in AST fragments during macro expansion. //! The traits are not implemented exhaustively, only when actually necessary. +use std::fmt; +use std::marker::PhantomData; + use crate::ptr::P; use crate::token::Nonterminal; use crate::tokenstream::LazyAttrTokenStream; -use crate::{Arm, Crate, ExprField, FieldDef, GenericParam, Param, PatField, Variant}; -use crate::{AssocItem, Expr, ForeignItem, Item, NodeId}; -use crate::{AttrItem, AttrKind, Block, Pat, Path, Ty, Visibility}; -use crate::{AttrVec, Attribute, Stmt, StmtKind}; - -use std::fmt; -use std::marker::PhantomData; +use crate::{ + Arm, AssocItem, AttrItem, AttrKind, AttrVec, Attribute, Block, Crate, Expr, ExprField, + FieldDef, ForeignItem, GenericParam, Item, NodeId, Param, Pat, PatField, Path, Stmt, StmtKind, + Ty, Variant, Visibility, +}; /// A utility trait to reduce boilerplate. /// Standard `Deref(Mut)` cannot be reused due to coherence. diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index d2c7b1c0753da..94a00ab1a047e 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -1,24 +1,24 @@ //! Functions dealing with attributes and meta items. +use std::iter; +use std::sync::atomic::{AtomicU32, Ordering}; + +use rustc_index::bit_set::GrowableBitSet; +use rustc_span::symbol::{sym, Ident, Symbol}; +use rustc_span::Span; +use smallvec::{smallvec, SmallVec}; +use thin_vec::{thin_vec, ThinVec}; + use crate::ast::{ - AttrArgs, AttrArgsEq, AttrId, AttrItem, AttrKind, AttrStyle, AttrVec, Attribute, Safety, + AttrArgs, AttrArgsEq, AttrId, AttrItem, AttrKind, AttrStyle, AttrVec, Attribute, DelimArgs, + Expr, ExprKind, LitKind, MetaItem, MetaItemKind, MetaItemLit, NestedMetaItem, NormalAttr, Path, + PathSegment, Safety, DUMMY_NODE_ID, }; -use crate::ast::{DelimArgs, Expr, ExprKind, LitKind, MetaItemLit}; -use crate::ast::{MetaItem, MetaItemKind, NestedMetaItem, NormalAttr}; -use crate::ast::{Path, PathSegment, DUMMY_NODE_ID}; use crate::ptr::P; use crate::token::{self, CommentKind, Delimiter, Token}; -use crate::tokenstream::{DelimSpan, Spacing, TokenTree}; -use crate::tokenstream::{LazyAttrTokenStream, TokenStream}; +use crate::tokenstream::{DelimSpan, LazyAttrTokenStream, Spacing, TokenStream, TokenTree}; use crate::util::comments; use crate::util::literal::escape_string_symbol; -use rustc_index::bit_set::GrowableBitSet; -use rustc_span::symbol::{sym, Ident, Symbol}; -use rustc_span::Span; -use smallvec::{smallvec, SmallVec}; -use std::iter; -use std::sync::atomic::{AtomicU32, Ordering}; -use thin_vec::{thin_vec, ThinVec}; pub struct MarkedAttrs(GrowableBitSet); diff --git a/compiler/rustc_ast/src/entry.rs b/compiler/rustc_ast/src/entry.rs index dd231e286d591..60a12614f06e8 100644 --- a/compiler/rustc_ast/src/entry.rs +++ b/compiler/rustc_ast/src/entry.rs @@ -1,7 +1,8 @@ -use crate::{attr, Attribute}; use rustc_span::symbol::sym; use rustc_span::Symbol; +use crate::{attr, Attribute}; + #[derive(Debug)] pub enum EntryPointType { /// This function is not an entrypoint. diff --git a/compiler/rustc_ast/src/expand/mod.rs b/compiler/rustc_ast/src/expand/mod.rs index 37caadd04143e..13413281bc7cc 100644 --- a/compiler/rustc_ast/src/expand/mod.rs +++ b/compiler/rustc_ast/src/expand/mod.rs @@ -1,7 +1,8 @@ //! Definitions shared by macros / syntax extensions and e.g. `rustc_middle`. use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use rustc_span::{def_id::DefId, symbol::Ident}; +use rustc_span::def_id::DefId; +use rustc_span::symbol::Ident; use crate::MetaItem; diff --git a/compiler/rustc_ast/src/format.rs b/compiler/rustc_ast/src/format.rs index 49910e2283dda..e72d32d9b752d 100644 --- a/compiler/rustc_ast/src/format.rs +++ b/compiler/rustc_ast/src/format.rs @@ -1,10 +1,11 @@ -use crate::ptr::P; -use crate::Expr; use rustc_data_structures::fx::FxHashMap; use rustc_macros::{Decodable, Encodable}; use rustc_span::symbol::{Ident, Symbol}; use rustc_span::Span; +use crate::ptr::P; +use crate::Expr; + // Definitions: // // format_args!("hello {abc:.xyz$}!!", abc="world"); diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs index 846a108091fcc..27e9f3d137ffd 100644 --- a/compiler/rustc_ast/src/lib.rs +++ b/compiler/rustc_ast/src/lib.rs @@ -43,11 +43,11 @@ pub mod token; pub mod tokenstream; pub mod visit; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; + pub use self::ast::*; pub use self::ast_traits::{AstDeref, AstNodeWrapper, HasAttrs, HasNodeId, HasTokens}; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; - /// Requirements for a `StableHashingContext` to be used in this crate. /// This is a hack to allow using the `HashStable_Generic` derive macro /// instead of implementing everything in `rustc_middle`. diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index 8387e4499ae3c..8a66894a35603 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -7,11 +7,8 @@ //! a `MutVisitor` renaming item names in a module will miss all of those //! that are created by the expansion of a macro. -use crate::ast::*; -use crate::ptr::P; -use crate::token::{self, Token}; -use crate::tokenstream::*; -use crate::visit::{AssocCtxt, BoundKind}; +use std::ops::DerefMut; +use std::panic; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_data_structures::stack::ensure_sufficient_stack; @@ -20,10 +17,14 @@ use rustc_span::source_map::Spanned; use rustc_span::symbol::Ident; use rustc_span::Span; use smallvec::{smallvec, Array, SmallVec}; -use std::ops::DerefMut; -use std::panic; use thin_vec::ThinVec; +use crate::ast::*; +use crate::ptr::P; +use crate::token::{self, Token}; +use crate::tokenstream::*; +use crate::visit::{AssocCtxt, BoundKind}; + pub trait ExpectOne { fn expect_one(self, err: &'static str) -> A::Item; } diff --git a/compiler/rustc_ast/src/node_id.rs b/compiler/rustc_ast/src/node_id.rs index 1cd2449530901..adca1844b61f8 100644 --- a/compiler/rustc_ast/src/node_id.rs +++ b/compiler/rustc_ast/src/node_id.rs @@ -1,6 +1,7 @@ -use rustc_span::LocalExpnId; use std::fmt; +use rustc_span::LocalExpnId; + rustc_index::newtype_index! { /// Identifies an AST node. /// diff --git a/compiler/rustc_ast/src/ptr.rs b/compiler/rustc_ast/src/ptr.rs index 34c539ea16b48..97c714df8fd2f 100644 --- a/compiler/rustc_ast/src/ptr.rs +++ b/compiler/rustc_ast/src/ptr.rs @@ -21,9 +21,8 @@ use std::fmt::{self, Debug, Display}; use std::ops::{Deref, DerefMut}; use std::{slice, vec}; -use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; - use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; /// An owned smart pointer. /// /// See the [module level documentation][crate::ptr] for details. diff --git a/compiler/rustc_ast/src/token.rs b/compiler/rustc_ast/src/token.rs index 9478da236c315..43d87b96ead90 100644 --- a/compiler/rustc_ast/src/token.rs +++ b/compiler/rustc_ast/src/token.rs @@ -1,3 +1,15 @@ +use std::borrow::Cow; +use std::fmt; + +use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::sync::Lrc; +use rustc_macros::{Decodable, Encodable, HashStable_Generic}; +use rustc_span::edition::Edition; +use rustc_span::symbol::{kw, sym}; +#[allow(clippy::useless_attribute)] // FIXME: following use of `hidden_glob_reexports` incorrectly triggers `useless_attribute` lint. +#[allow(hidden_glob_reexports)] +use rustc_span::symbol::{Ident, Symbol}; +use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; pub use BinOpToken::*; pub use LitKind::*; pub use Nonterminal::*; @@ -9,17 +21,6 @@ use crate::ast; use crate::ptr::P; use crate::util::case::Case; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc_data_structures::sync::Lrc; -use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use rustc_span::symbol::{kw, sym}; -#[allow(clippy::useless_attribute)] // FIXME: following use of `hidden_glob_reexports` incorrectly triggers `useless_attribute` lint. -#[allow(hidden_glob_reexports)] -use rustc_span::symbol::{Ident, Symbol}; -use rustc_span::{edition::Edition, ErrorGuaranteed, Span, DUMMY_SP}; -use std::borrow::Cow; -use std::fmt; - #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] pub enum CommentKind { Line, @@ -1062,8 +1063,9 @@ where // Some types are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(Lit, 12); static_assert_size!(LitKind, 2); diff --git a/compiler/rustc_ast/src/tokenstream.rs b/compiler/rustc_ast/src/tokenstream.rs index a92ef575777c7..057b4455dca89 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -13,10 +13,8 @@ //! and a borrowed `TokenStream` is sufficient to build an owned `TokenStream` without taking //! ownership of the original. -use crate::ast::{AttrStyle, StmtKind}; -use crate::ast_traits::{HasAttrs, HasTokens}; -use crate::token::{self, Delimiter, Nonterminal, Token, TokenKind}; -use crate::{AttrVec, Attribute}; +use std::borrow::Cow; +use std::{cmp, fmt, iter}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::{self, Lrc}; @@ -24,8 +22,10 @@ use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_serialize::{Decodable, Encodable}; use rustc_span::{sym, Span, SpanDecoder, SpanEncoder, Symbol, DUMMY_SP}; -use std::borrow::Cow; -use std::{cmp, fmt, iter}; +use crate::ast::{AttrStyle, StmtKind}; +use crate::ast_traits::{HasAttrs, HasTokens}; +use crate::token::{self, Delimiter, Nonterminal, Token, TokenKind}; +use crate::{AttrVec, Attribute}; /// Part of a `TokenStream`. #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] @@ -767,8 +767,9 @@ impl DelimSpacing { // Some types are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(AttrTokenStream, 8); static_assert_size!(AttrTokenTree, 32); diff --git a/compiler/rustc_ast/src/util/comments.rs b/compiler/rustc_ast/src/util/comments.rs index cbc1afc6bf1e8..f39142f08ba52 100644 --- a/compiler/rustc_ast/src/util/comments.rs +++ b/compiler/rustc_ast/src/util/comments.rs @@ -1,6 +1,7 @@ -use crate::token::CommentKind; use rustc_span::{BytePos, Symbol}; +use crate::token::CommentKind; + #[cfg(test)] mod tests; diff --git a/compiler/rustc_ast/src/util/comments/tests.rs b/compiler/rustc_ast/src/util/comments/tests.rs index 11d50603a1011..61bb2468e79b9 100644 --- a/compiler/rustc_ast/src/util/comments/tests.rs +++ b/compiler/rustc_ast/src/util/comments/tests.rs @@ -1,6 +1,7 @@ -use super::*; use rustc_span::create_default_session_globals_then; +use super::*; + #[test] fn test_block_doc_comment_1() { create_default_session_globals_then(|| { diff --git a/compiler/rustc_ast/src/util/literal.rs b/compiler/rustc_ast/src/util/literal.rs index cb73b7908c2e7..3bd2a80d361ee 100644 --- a/compiler/rustc_ast/src/util/literal.rs +++ b/compiler/rustc_ast/src/util/literal.rs @@ -1,15 +1,17 @@ //! Code related to parsing literals. -use crate::ast::{self, LitKind, MetaItemLit, StrStyle}; -use crate::token::{self, Token}; +use std::{ascii, fmt, str}; + use rustc_lexer::unescape::{ byte_from_char, unescape_byte, unescape_char, unescape_mixed, unescape_unicode, MixedUnit, Mode, }; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; -use std::{ascii, fmt, str}; use tracing::debug; +use crate::ast::{self, LitKind, MetaItemLit, StrStyle}; +use crate::token::{self, Token}; + // Escapes a string, represented as a symbol. Reuses the original symbol, // avoiding interning, if no changes are required. pub fn escape_string_symbol(symbol: Symbol) -> Symbol { diff --git a/compiler/rustc_ast/src/util/parser.rs b/compiler/rustc_ast/src/util/parser.rs index ad92bf2cd4071..8436c760d1642 100644 --- a/compiler/rustc_ast/src/util/parser.rs +++ b/compiler/rustc_ast/src/util/parser.rs @@ -1,6 +1,7 @@ +use rustc_span::symbol::kw; + use crate::ast::{self, BinOpKind}; use crate::token::{self, BinOpToken, Token}; -use rustc_span::symbol::kw; /// Associative operator with precedence. /// diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index f6929057bed13..fe07ec48f1f2b 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -13,14 +13,13 @@ //! instance, a walker looking for item names in a module will miss all of //! those that are created by the expansion of a macro. -use crate::ast::*; -use crate::ptr::P; - +pub use rustc_ast_ir::visit::VisitorResult; +pub use rustc_ast_ir::{try_visit, visit_opt, walk_list, walk_visitable_list}; use rustc_span::symbol::Ident; use rustc_span::Span; -pub use rustc_ast_ir::visit::VisitorResult; -pub use rustc_ast_ir::{try_visit, visit_opt, walk_list, walk_visitable_list}; +use crate::ast::*; +use crate::ptr::P; #[derive(Copy, Clone, Debug, PartialEq)] pub enum AssocCtxt { diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index de0874af934cf..ea7b8c114f490 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -1,13 +1,5 @@ -use crate::{ImplTraitContext, ImplTraitPosition, ParamMode, ResolverAstLoweringExt}; - -use super::errors::{ - AbiSpecifiedMultipleTimes, AttSyntaxOnlyX86, ClobberAbiNotSupported, - InlineAsmUnsupportedTarget, InvalidAbiClobberAbi, InvalidAsmTemplateModifierConst, - InvalidAsmTemplateModifierLabel, InvalidAsmTemplateModifierRegClass, - InvalidAsmTemplateModifierRegClassSub, InvalidAsmTemplateModifierSym, InvalidRegister, - InvalidRegisterClass, RegisterClassOnlyClobber, RegisterConflict, -}; -use super::LoweringContext; +use std::collections::hash_map::Entry; +use std::fmt::Write; use rustc_ast::ptr::P; use rustc_ast::*; @@ -18,8 +10,16 @@ use rustc_session::parse::feature_err; use rustc_span::symbol::kw; use rustc_span::{sym, Span}; use rustc_target::asm; -use std::collections::hash_map::Entry; -use std::fmt::Write; + +use super::errors::{ + AbiSpecifiedMultipleTimes, AttSyntaxOnlyX86, ClobberAbiNotSupported, + InlineAsmUnsupportedTarget, InvalidAbiClobberAbi, InvalidAsmTemplateModifierConst, + InvalidAsmTemplateModifierLabel, InvalidAsmTemplateModifierRegClass, + InvalidAsmTemplateModifierRegClassSub, InvalidAsmTemplateModifierSym, InvalidRegister, + InvalidRegisterClass, RegisterClassOnlyClobber, RegisterConflict, +}; +use super::LoweringContext; +use crate::{ImplTraitContext, ImplTraitPosition, ParamMode, ResolverAstLoweringExt}; impl<'a, 'hir> LoweringContext<'a, 'hir> { #[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable diff --git a/compiler/rustc_ast_lowering/src/block.rs b/compiler/rustc_ast_lowering/src/block.rs index e821a08bf1817..9d2b5690c23d9 100644 --- a/compiler/rustc_ast_lowering/src/block.rs +++ b/compiler/rustc_ast_lowering/src/block.rs @@ -1,9 +1,9 @@ -use crate::{ImplTraitContext, ImplTraitPosition, LoweringContext}; use rustc_ast::{Block, BlockCheckMode, Local, LocalKind, Stmt, StmtKind}; use rustc_hir as hir; - use smallvec::SmallVec; +use crate::{ImplTraitContext, ImplTraitPosition, LoweringContext}; + impl<'a, 'hir> LoweringContext<'a, 'hir> { pub(super) fn lower_block( &mut self, diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index 6df2c15ce60c0..6e8ff72cf8759 100644 --- a/compiler/rustc_ast_lowering/src/delegation.rs +++ b/compiler/rustc_ast_lowering/src/delegation.rs @@ -33,26 +33,26 @@ //! HIR ty lowering. //! //! Similarly generics, predicates and header are set to the "default" values. -//! In case of discrepancy with callee function the `NotSupportedDelegation` error will +//! In case of discrepancy with callee function the `UnsupportedDelegation` error will //! also be emitted during HIR ty lowering. -use crate::{ImplTraitPosition, ResolverAstLoweringExt}; - -use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs}; +use std::iter; use ast::visit::Visitor; use hir::def::{DefKind, PartialRes, Res}; use hir::{BodyId, HirId}; -use rustc_ast as ast; use rustc_ast::*; use rustc_errors::ErrorGuaranteed; -use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::span_bug; use rustc_middle::ty::{Asyncness, ResolverAstLowering}; -use rustc_span::{symbol::Ident, Span}; +use rustc_span::symbol::Ident; +use rustc_span::Span; use rustc_target::spec::abi; -use std::iter; +use {rustc_ast as ast, rustc_hir as hir}; + +use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs}; +use crate::{ImplTraitPosition, ResolverAstLoweringExt}; pub(crate) struct DelegationResults<'hir> { pub body_id: hir::BodyId, diff --git a/compiler/rustc_ast_lowering/src/errors.rs b/compiler/rustc_ast_lowering/src/errors.rs index 4c77892a6b753..7a6c9d8d0d375 100644 --- a/compiler/rustc_ast_lowering/src/errors.rs +++ b/compiler/rustc_ast_lowering/src/errors.rs @@ -1,8 +1,8 @@ -use rustc_errors::{ - codes::*, Diag, DiagArgFromDisplay, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic, -}; +use rustc_errors::codes::*; +use rustc_errors::{Diag, DiagArgFromDisplay, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_span::{symbol::Ident, Span, Symbol}; +use rustc_span::symbol::Ident; +use rustc_span::{Span, Symbol}; #[derive(Diagnostic)] #[diag(ast_lowering_generic_type_with_parentheses, code = E0214)] diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index d870f9fe0aef2..124fe6bd380d2 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -1,15 +1,5 @@ use std::assert_matches::assert_matches; -use super::errors::{ - AsyncCoroutinesNotSupported, AwaitOnlyInAsyncFnAndBlocks, BaseExpressionDoubleDot, - ClosureCannotBeStatic, CoroutineTooManyParameters, - FunctionalRecordUpdateDestructuringAssignment, InclusiveRangeWithNoEnd, MatchArmWithNoBody, - NeverPatternWithBody, NeverPatternWithGuard, UnderscoreExprLhsAssign, -}; -use super::ResolverAstLoweringExt; -use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs}; -use crate::errors::YieldInClosure; -use crate::{FnDeclKind, ImplTraitPosition}; use rustc_ast::ptr::P as AstP; use rustc_ast::*; use rustc_data_structures::stack::ensure_sufficient_stack; @@ -20,10 +10,21 @@ use rustc_middle::span_bug; use rustc_session::errors::report_lit_error; use rustc_span::source_map::{respan, Spanned}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::DUMMY_SP; -use rustc_span::{DesugaringKind, Span}; +use rustc_span::{DesugaringKind, Span, DUMMY_SP}; use thin_vec::{thin_vec, ThinVec}; +use super::errors::{ + AsyncCoroutinesNotSupported, AwaitOnlyInAsyncFnAndBlocks, BaseExpressionDoubleDot, + ClosureCannotBeStatic, CoroutineTooManyParameters, + FunctionalRecordUpdateDestructuringAssignment, InclusiveRangeWithNoEnd, MatchArmWithNoBody, + NeverPatternWithBody, NeverPatternWithGuard, UnderscoreExprLhsAssign, +}; +use super::{ + ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs, ResolverAstLoweringExt, +}; +use crate::errors::YieldInClosure; +use crate::{FnDeclKind, ImplTraitPosition}; + impl<'hir> LoweringContext<'_, 'hir> { fn lower_exprs(&mut self, exprs: &[AstP]) -> &'hir [hir::Expr<'hir>] { self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x))) diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index ca4604c60c580..bf40c9b66c68f 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -1,16 +1,14 @@ -use super::LoweringContext; use core::ops::ControlFlow; -use rustc_ast as ast; +use std::borrow::Cow; + use rustc_ast::visit::Visitor; use rustc_ast::*; use rustc_data_structures::fx::FxIndexMap; -use rustc_hir as hir; -use rustc_span::{ - sym, - symbol::{kw, Ident}, - Span, Symbol, -}; -use std::borrow::Cow; +use rustc_span::symbol::{kw, Ident}; +use rustc_span::{sym, Span, Symbol}; +use {rustc_ast as ast, rustc_hir as hir}; + +use super::LoweringContext; impl<'hir> LoweringContext<'_, 'hir> { pub(crate) fn lower_format_args(&mut self, sp: Span, fmt: &FormatArgs) -> hir::ExprKind<'hir> { diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index f990b4ba69b3f..1456890a0a233 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1,8 +1,3 @@ -use super::errors::{InvalidAbi, InvalidAbiReason, InvalidAbiSuggestion, MisplacedRelaxTraitBound}; -use super::ResolverAstLoweringExt; -use super::{AstOwner, ImplTraitContext, ImplTraitPosition}; -use super::{FnDeclKind, LoweringContext, ParamMode}; - use rustc_ast::ptr::P; use rustc_ast::visit::AssocCtxt; use rustc_ast::*; @@ -22,6 +17,12 @@ use smallvec::{smallvec, SmallVec}; use thin_vec::ThinVec; use tracing::instrument; +use super::errors::{InvalidAbi, InvalidAbiReason, InvalidAbiSuggestion, MisplacedRelaxTraitBound}; +use super::{ + AstOwner, FnDeclKind, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode, + ResolverAstLoweringExt, +}; + pub(super) struct ItemLowerer<'a, 'hir> { pub(super) tcx: TyCtxt<'hir>, pub(super) resolver: &'a mut ResolverAstLowering, @@ -172,7 +173,7 @@ impl<'hir> LoweringContext<'_, 'hir> { id: NodeId, hir_id: hir::HirId, ident: &mut Ident, - attrs: Option<&'hir [Attribute]>, + attrs: &'hir [Attribute], vis_span: Span, i: &ItemKind, ) -> hir::ItemKind<'hir> { @@ -488,7 +489,7 @@ impl<'hir> LoweringContext<'_, 'hir> { id: NodeId, vis_span: Span, ident: &mut Ident, - attrs: Option<&'hir [Attribute]>, + attrs: &'hir [Attribute], ) -> hir::ItemKind<'hir> { let path = &tree.prefix; let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect(); @@ -566,7 +567,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // `ItemLocalId` and the new owner. (See `lower_node_id`) let kind = this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs); - if let Some(attrs) = attrs { + if !attrs.is_empty() { this.attrs.insert(hir::ItemLocalId::ZERO, attrs); } @@ -1525,8 +1526,14 @@ impl<'hir> LoweringContext<'_, 'hir> { continue; } let is_param = *is_param.get_or_insert_with(compute_is_param); - if !is_param { - self.dcx().emit_err(MisplacedRelaxTraitBound { span: bound.span() }); + if !is_param && !self.tcx.features().more_maybe_bounds { + self.tcx + .sess + .create_feature_err( + MisplacedRelaxTraitBound { span: bound.span() }, + sym::more_maybe_bounds, + ) + .emit(); } } } diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 0f5f4d8023bd1..224787c335beb 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -39,7 +39,8 @@ #![feature(rustdoc_internals)] // tidy-alphabetical-end -use crate::errors::{AssocTyParentheses, AssocTyParenthesesSub, MisplacedImplTrait}; +use std::collections::hash_map::Entry; + use rustc_ast::node_id::NodeMap; use rustc_ast::ptr::P; use rustc_ast::{self as ast, *}; @@ -53,9 +54,9 @@ use rustc_data_structures::sync::Lrc; use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle, StashKey}; use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res}; use rustc_hir::def_id::{LocalDefId, LocalDefIdMap, CRATE_DEF_ID, LOCAL_CRATE}; -use rustc_hir::{self as hir}; use rustc_hir::{ - ConstArg, GenericArg, HirId, ItemLocalMap, MissingLifetimeKind, ParamName, TraitCandidate, + self as hir, ConstArg, GenericArg, HirId, ItemLocalMap, MissingLifetimeKind, ParamName, + TraitCandidate, }; use rustc_index::{Idx, IndexSlice, IndexVec}; use rustc_macros::extension; @@ -65,10 +66,11 @@ use rustc_session::parse::{add_feature_diagnostics, feature_err}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{DesugaringKind, Span, DUMMY_SP}; use smallvec::{smallvec, SmallVec}; -use std::collections::hash_map::Entry; use thin_vec::ThinVec; use tracing::{debug, instrument, trace}; +use crate::errors::{AssocTyParentheses, AssocTyParenthesesSub, MisplacedImplTrait}; + macro_rules! arena_vec { ($this:expr; $($x:expr),*) => ( $this.arena.alloc_from_iter([$($x),*]) @@ -913,15 +915,15 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ret } - fn lower_attrs(&mut self, id: HirId, attrs: &[Attribute]) -> Option<&'hir [Attribute]> { + fn lower_attrs(&mut self, id: HirId, attrs: &[Attribute]) -> &'hir [Attribute] { if attrs.is_empty() { - None + &[] } else { debug_assert_eq!(id.owner, self.current_hir_id_owner); let ret = self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a))); debug_assert!(!ret.is_empty()); self.attrs.insert(id.local_id, ret); - Some(ret) + ret } } @@ -1216,6 +1218,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { itctx, TraitBoundModifiers::NONE, ); + let bound = (bound, hir::TraitBoundModifier::None); let bounds = this.arena.alloc_from_iter([bound]); let lifetime_bound = this.elided_dyn_bound(t.span); (bounds, lifetime_bound) @@ -1348,21 +1351,17 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // We can safely ignore constness here since AST validation // takes care of rejecting invalid modifier combinations and // const trait bounds in trait object types. - GenericBound::Trait(ty, modifiers) => match modifiers.polarity { - BoundPolarity::Positive | BoundPolarity::Negative(_) => { - Some(this.lower_poly_trait_ref( - ty, - itctx, - // Still, don't pass along the constness here; we don't want to - // synthesize any host effect args, it'd only cause problems. - TraitBoundModifiers { - constness: BoundConstness::Never, - ..*modifiers - }, - )) - } - BoundPolarity::Maybe(_) => None, - }, + GenericBound::Trait(ty, modifiers) => { + // Still, don't pass along the constness here; we don't want to + // synthesize any host effect args, it'd only cause problems. + let modifiers = TraitBoundModifiers { + constness: BoundConstness::Never, + ..*modifiers + }; + let trait_ref = this.lower_poly_trait_ref(ty, itctx, modifiers); + let polarity = this.lower_trait_bound_modifiers(modifiers); + Some((trait_ref, polarity)) + } GenericBound::Outlives(lifetime) => { if lifetime_bound.is_none() { lifetime_bound = Some(this.lower_lifetime(lifetime)); @@ -2688,6 +2687,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { trait_ref: hir::TraitRef { path, hir_ref_id: hir_id }, span: self.lower_span(span), }; + let principal = (principal, hir::TraitBoundModifier::None); // The original ID is taken by the `PolyTraitRef`, // so the `Ty` itself needs a different one. diff --git a/compiler/rustc_ast_lowering/src/lifetime_collector.rs b/compiler/rustc_ast_lowering/src/lifetime_collector.rs index 5456abd489beb..77cc2a36a531d 100644 --- a/compiler/rustc_ast_lowering/src/lifetime_collector.rs +++ b/compiler/rustc_ast_lowering/src/lifetime_collector.rs @@ -1,4 +1,3 @@ -use super::ResolverAstLoweringExt; use rustc_ast::visit::{self, BoundKind, LifetimeCtxt, Visitor}; use rustc_ast::{GenericBounds, Lifetime, NodeId, PathSegment, PolyTraitRef, Ty, TyKind}; use rustc_data_structures::fx::FxIndexSet; @@ -8,6 +7,8 @@ use rustc_middle::ty::ResolverAstLowering; use rustc_span::symbol::{kw, Ident}; use rustc_span::Span; +use super::ResolverAstLoweringExt; + struct LifetimeCollectVisitor<'ast> { resolver: &'ast ResolverAstLowering, current_binders: Vec, diff --git a/compiler/rustc_ast_lowering/src/pat.rs b/compiler/rustc_ast_lowering/src/pat.rs index 32de07a0755e2..d82bdd526b707 100644 --- a/compiler/rustc_ast_lowering/src/pat.rs +++ b/compiler/rustc_ast_lowering/src/pat.rs @@ -1,17 +1,17 @@ -use super::errors::{ - ArbitraryExpressionInPattern, ExtraDoubleDot, MisplacedDoubleDot, SubTupleBinding, -}; -use super::ResolverAstLoweringExt; -use super::{ImplTraitContext, LoweringContext, ParamMode}; -use crate::ImplTraitPosition; - use rustc_ast::ptr::P; use rustc_ast::*; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir as hir; use rustc_hir::def::Res; +use rustc_span::source_map::Spanned; use rustc_span::symbol::Ident; -use rustc_span::{source_map::Spanned, Span}; +use rustc_span::Span; + +use super::errors::{ + ArbitraryExpressionInPattern, ExtraDoubleDot, MisplacedDoubleDot, SubTupleBinding, +}; +use super::{ImplTraitContext, LoweringContext, ParamMode, ResolverAstLoweringExt}; +use crate::ImplTraitPosition; impl<'a, 'hir> LoweringContext<'a, 'hir> { pub(crate) fn lower_pat(&mut self, pattern: &Pat) -> &'hir hir::Pat<'hir> { diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index 6303584bb7846..077b06acd7c8c 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -1,13 +1,3 @@ -use crate::ImplTraitPosition; - -use super::errors::{ - AsyncBoundNotOnTrait, AsyncBoundOnlyForFnTraits, BadReturnTypeNotation, - GenericTypeWithParentheses, UseAngleBrackets, -}; -use super::ResolverAstLoweringExt; -use super::{GenericArgsCtor, LifetimeRes, ParenthesizedGenericArgs}; -use super::{ImplTraitContext, LoweringContext, ParamMode}; - use rustc_ast::{self as ast, *}; use rustc_data_structures::sync::Lrc; use rustc_hir as hir; @@ -17,10 +7,19 @@ use rustc_hir::GenericArg; use rustc_middle::span_bug; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{BytePos, DesugaringKind, Span, Symbol, DUMMY_SP}; - use smallvec::{smallvec, SmallVec}; use tracing::{debug, instrument}; +use super::errors::{ + AsyncBoundNotOnTrait, AsyncBoundOnlyForFnTraits, BadReturnTypeNotation, + GenericTypeWithParentheses, UseAngleBrackets, +}; +use super::{ + GenericArgsCtor, ImplTraitContext, LifetimeRes, LoweringContext, ParamMode, + ParenthesizedGenericArgs, ResolverAstLoweringExt, +}; +use crate::ImplTraitPosition; + impl<'a, 'hir> LoweringContext<'a, 'hir> { #[instrument(level = "trace", skip(self))] pub(crate) fn lower_qpath( @@ -44,13 +43,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let mut res = self.lower_res(base_res); // When we have an `async` kw on a bound, map the trait it resolves to. - let mut bound_modifier_allowed_features = None; if let Some(TraitBoundModifiers { asyncness: BoundAsyncness::Async(_), .. }) = modifiers { match res { Res::Def(DefKind::Trait, def_id) => { - if let Some((async_def_id, features)) = self.map_trait_to_async_trait(def_id) { + if let Some(async_def_id) = self.map_trait_to_async_trait(def_id) { res = Res::Def(DefKind::Trait, async_def_id); - bound_modifier_allowed_features = Some(features); } else { self.dcx().emit_err(AsyncBoundOnlyForFnTraits { span: p.span }); } @@ -67,6 +64,16 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } } + // Ungate the `async_fn_traits` feature in the path if the trait is + // named via either `async Fn*()` or `AsyncFn*()`. + let bound_modifier_allowed_features = if let Res::Def(DefKind::Trait, async_def_id) = res + && self.tcx.async_fn_trait_kind_from_def_id(async_def_id).is_some() + { + Some(self.allow_async_fn_traits.clone()) + } else { + None + }; + let path_span_lo = p.span.shrink_to_lo(); let proj_start = p.segments.len() - unresolved_segments; let path = self.arena.alloc(hir::Path { @@ -506,14 +513,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { /// This only needs to be done until we unify `AsyncFn` and `Fn` traits into one /// that is generic over `async`ness, if that's ever possible, or modify the /// lowering of `async Fn()` bounds to desugar to another trait like `LendingFn`. - fn map_trait_to_async_trait(&self, def_id: DefId) -> Option<(DefId, Lrc<[Symbol]>)> { + fn map_trait_to_async_trait(&self, def_id: DefId) -> Option { let lang_items = self.tcx.lang_items(); if Some(def_id) == lang_items.fn_trait() { - Some((lang_items.async_fn_trait()?, self.allow_async_fn_traits.clone())) + lang_items.async_fn_trait() } else if Some(def_id) == lang_items.fn_mut_trait() { - Some((lang_items.async_fn_mut_trait()?, self.allow_async_fn_traits.clone())) + lang_items.async_fn_mut_trait() } else if Some(def_id) == lang_items.fn_once_trait() { - Some((lang_items.async_fn_once_trait()?, self.allow_async_fn_traits.clone())) + lang_items.async_fn_once_trait() } else { None } diff --git a/compiler/rustc_ast_passes/messages.ftl b/compiler/rustc_ast_passes/messages.ftl index ca0b7f2ac3a67..df5c639382f04 100644 --- a/compiler/rustc_ast_passes/messages.ftl +++ b/compiler/rustc_ast_passes/messages.ftl @@ -155,8 +155,6 @@ ast_passes_impl_trait_path = `impl Trait` is not allowed in path parameters ast_passes_incompatible_features = `{$f1}` and `{$f2}` are incompatible, using them at the same time is not allowed .help = remove one of these features -ast_passes_incompatible_trait_bound_modifiers = `{$left}` and `{$right}` are mutually exclusive - ast_passes_inherent_cannot_be = inherent impls cannot be {$annotation} .because = {$annotation} because of this .type = inherent impl for this type diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 34aac6e447304..a353c79f12d45 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -16,6 +16,9 @@ //! constructions produced by proc macros. This pass is only intended for simple checks that do not //! require name resolution or type checking, or other kinds of complex analysis. +use std::mem; +use std::ops::{Deref, DerefMut}; + use itertools::{Either, Itertools}; use rustc_ast::ptr::P; use rustc_ast::visit::{walk_list, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor}; @@ -34,8 +37,6 @@ use rustc_session::Session; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; use rustc_target::spec::abi; -use std::mem; -use std::ops::{Deref, DerefMut}; use thin_vec::thin_vec; use crate::errors::{self, TildeConstReason}; @@ -452,11 +453,6 @@ impl<'a> AstValidator<'a> { item_span: span, block: Some(self.current_extern_span().shrink_to_lo()), }); - } else if !self.features.unsafe_extern_blocks { - self.dcx().emit_err(errors::InvalidSafetyOnExtern { - item_span: span, - block: None, - }); } } } @@ -1053,32 +1049,19 @@ impl<'a> Visitor<'a> for AstValidator<'a> { errors::VisibilityNotPermittedNote::IndividualForeignItems, ); - if this.features.unsafe_extern_blocks { - if &Safety::Default == safety { - if item.span.at_least_rust_2024() { - this.dcx() - .emit_err(errors::MissingUnsafeOnExtern { span: item.span }); - } else { - this.lint_buffer.buffer_lint( - MISSING_UNSAFE_ON_EXTERN, - item.id, - item.span, - BuiltinLintDiag::MissingUnsafeOnExtern { - suggestion: item.span.shrink_to_lo(), - }, - ); - } + if &Safety::Default == safety { + if item.span.at_least_rust_2024() { + this.dcx().emit_err(errors::MissingUnsafeOnExtern { span: item.span }); + } else { + this.lint_buffer.buffer_lint( + MISSING_UNSAFE_ON_EXTERN, + item.id, + item.span, + BuiltinLintDiag::MissingUnsafeOnExtern { + suggestion: item.span.shrink_to_lo(), + }, + ); } - } else if let &Safety::Unsafe(span) = safety { - let mut diag = this - .dcx() - .create_err(errors::UnsafeItem { span, kind: "extern block" }); - rustc_session::parse::add_feature_diagnostics( - &mut diag, - self.session, - sym::unsafe_extern_blocks, - ); - diag.emit(); } if abi.is_none() { @@ -1345,14 +1328,28 @@ impl<'a> Visitor<'a> for AstValidator<'a> { match bound { GenericBound::Trait(trait_ref, modifiers) => { match (ctxt, modifiers.constness, modifiers.polarity) { - (BoundKind::SuperTraits, BoundConstness::Never, BoundPolarity::Maybe(_)) => { - self.dcx().emit_err(errors::OptionalTraitSupertrait { - span: trait_ref.span, - path_str: pprust::path_to_string(&trait_ref.trait_ref.path), - }); + (BoundKind::SuperTraits, BoundConstness::Never, BoundPolarity::Maybe(_)) + if !self.features.more_maybe_bounds => + { + self.session + .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(_)) => { - self.dcx().emit_err(errors::OptionalTraitObject { span: trait_ref.span }); + (BoundKind::TraitObject, BoundConstness::Never, BoundPolarity::Maybe(_)) + if !self.features.more_maybe_bounds => + { + self.session + .create_feature_err( + errors::OptionalTraitObject { span: trait_ref.span }, + sym::more_maybe_bounds, + ) + .emit(); } ( BoundKind::TraitObject, @@ -1366,17 +1363,6 @@ impl<'a> Visitor<'a> for AstValidator<'a> { { self.dcx().emit_err(errors::TildeConstDisallowed { span, reason }); } - ( - _, - BoundConstness::Always(_) | BoundConstness::Maybe(_), - BoundPolarity::Negative(_) | BoundPolarity::Maybe(_), - ) => { - self.dcx().emit_err(errors::IncompatibleTraitBoundModifiers { - span: bound.span(), - left: modifiers.constness.as_str(), - right: modifiers.polarity.as_str(), - }); - } _ => {} } diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 215ccd2ab4d9e..9e40368083729 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -1,11 +1,11 @@ //! Errors emitted by ast_passes. use rustc_ast::ParamKindOrd; -use rustc_errors::{ - codes::*, Applicability, Diag, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic, -}; +use rustc_errors::codes::*; +use rustc_errors::{Applicability, Diag, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_span::{symbol::Ident, Span, Symbol}; +use rustc_span::symbol::Ident; +use rustc_span::{Span, Symbol}; use crate::fluent_generated as fluent; @@ -656,15 +656,6 @@ pub enum TildeConstReason { Item, } -#[derive(Diagnostic)] -#[diag(ast_passes_incompatible_trait_bound_modifiers)] -pub struct IncompatibleTraitBoundModifiers { - #[primary_span] - pub span: Span, - pub left: &'static str, - pub right: &'static str, -} - #[derive(Diagnostic)] #[diag(ast_passes_const_and_async)] pub struct ConstAndAsync { diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index e91dfb2776662..3ceb8e0711a21 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -1,7 +1,6 @@ use rustc_ast as ast; use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor}; -use rustc_ast::{attr, NodeId}; -use rustc_ast::{token, PatKind}; +use rustc_ast::{attr, token, NodeId, PatKind}; use rustc_feature::{AttributeGate, BuiltinAttribute, Features, GateIssue, BUILTIN_ATTRIBUTE_MAP}; use rustc_session::parse::{feature_err, feature_err_issue, feature_warn}; use rustc_session::Session; @@ -561,10 +560,6 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) { gate_all!(precise_capturing, "precise captures on `impl Trait` are experimental"); gate_all!(global_registration, "global registration is experimental"); gate_all!(unsafe_attributes, "`#[unsafe()]` markers for attributes are experimental"); - gate_all!( - unsafe_extern_blocks, - "`unsafe extern {}` blocks and `safe` keyword are experimental" - ); gate_all!(return_type_notation, "return type notation is experimental"); if !visitor.features.never_patterns { diff --git a/compiler/rustc_ast_pretty/src/helpers.rs b/compiler/rustc_ast_pretty/src/helpers.rs index c3e0eccd3d404..34641ea2f5ae0 100644 --- a/compiler/rustc_ast_pretty/src/helpers.rs +++ b/compiler/rustc_ast_pretty/src/helpers.rs @@ -1,6 +1,7 @@ -use crate::pp::Printer; use std::borrow::Cow; +use crate::pp::Printer; + impl Printer { pub fn word_space>>(&mut self, w: W) { self.word(w); diff --git a/compiler/rustc_ast_pretty/src/pp.rs b/compiler/rustc_ast_pretty/src/pp.rs index 96f5eff68901f..e4fd7e94fde14 100644 --- a/compiler/rustc_ast_pretty/src/pp.rs +++ b/compiler/rustc_ast_pretty/src/pp.rs @@ -135,11 +135,11 @@ mod convenience; mod ring; -use ring::RingBuffer; use std::borrow::Cow; -use std::cmp; use std::collections::VecDeque; -use std::iter; +use std::{cmp, iter}; + +use ring::RingBuffer; /// How to break. Described in more detail in the module docs. #[derive(Clone, Copy, PartialEq)] diff --git a/compiler/rustc_ast_pretty/src/pp/convenience.rs b/compiler/rustc_ast_pretty/src/pp/convenience.rs index c4c4fdce7fef2..6d46c26311be3 100644 --- a/compiler/rustc_ast_pretty/src/pp/convenience.rs +++ b/compiler/rustc_ast_pretty/src/pp/convenience.rs @@ -1,6 +1,7 @@ -use crate::pp::{BeginToken, BreakToken, Breaks, IndentStyle, Printer, Token, SIZE_INFINITY}; use std::borrow::Cow; +use crate::pp::{BeginToken, BreakToken, Breaks, IndentStyle, Printer, Token, SIZE_INFINITY}; + impl Printer { /// "raw box" pub fn rbox(&mut self, indent: isize, breaks: Breaks) { diff --git a/compiler/rustc_ast_pretty/src/pprust/mod.rs b/compiler/rustc_ast_pretty/src/pprust/mod.rs index 83b7e13905aee..cfcc28ba76fdd 100644 --- a/compiler/rustc_ast_pretty/src/pprust/mod.rs +++ b/compiler/rustc_ast_pretty/src/pprust/mod.rs @@ -2,13 +2,12 @@ mod tests; pub mod state; -pub use state::{print_crate, AnnNode, Comments, PpAnn, PrintState, State}; +use std::borrow::Cow; use rustc_ast as ast; use rustc_ast::token::{Nonterminal, Token, TokenKind}; use rustc_ast::tokenstream::{TokenStream, TokenTree}; - -use std::borrow::Cow; +pub use state::{print_crate, AnnNode, Comments, PpAnn, PrintState, State}; pub fn nonterminal_to_string(nt: &Nonterminal) -> String { State::new().nonterminal_to_string(nt) diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 0568d368d8c4c..ee4514758c212 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -6,9 +6,8 @@ mod expr; mod fixup; mod item; -use crate::pp::Breaks::{Consistent, Inconsistent}; -use crate::pp::{self, Breaks}; -use crate::pprust::state::fixup::FixupContext; +use std::borrow::Cow; + use ast::TraitBoundModifiers; use rustc_ast::attr::AttrIdGenerator; use rustc_ast::ptr::P; @@ -16,18 +15,21 @@ use rustc_ast::token::{self, BinOpToken, CommentKind, Delimiter, Nonterminal, To use rustc_ast::tokenstream::{Spacing, TokenStream, TokenTree}; use rustc_ast::util::classify; use rustc_ast::util::comments::{Comment, CommentStyle}; -use rustc_ast::{self as ast, AttrArgs, AttrArgsEq, BlockCheckMode, PatKind, Safety}; -use rustc_ast::{attr, BindingMode, ByRef, DelimArgs, RangeEnd, RangeSyntax, Term}; -use rustc_ast::{GenericArg, GenericBound, SelfKind}; -use rustc_ast::{InlineAsmOperand, InlineAsmRegOrRegClass}; -use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; +use rustc_ast::{ + self as ast, attr, AttrArgs, AttrArgsEq, BindingMode, BlockCheckMode, ByRef, DelimArgs, + GenericArg, GenericBound, InlineAsmOperand, InlineAsmOptions, InlineAsmRegOrRegClass, + InlineAsmTemplatePiece, PatKind, RangeEnd, RangeSyntax, Safety, SelfKind, Term, +}; use rustc_span::edition::Edition; use rustc_span::source_map::{SourceMap, Spanned}; use rustc_span::symbol::{kw, sym, Ident, IdentPrinter, Symbol}; use rustc_span::{BytePos, CharPos, FileName, Pos, Span, DUMMY_SP}; -use std::borrow::Cow; use thin_vec::ThinVec; +use crate::pp::Breaks::{Consistent, Inconsistent}; +use crate::pp::{self, Breaks}; +use crate::pprust::state::fixup::FixupContext; + pub enum MacHeader<'a> { Path(&'a ast::Path), Keyword(&'static str), @@ -290,8 +292,7 @@ pub fn print_crate<'a>( fn space_between(tt1: &TokenTree, tt2: &TokenTree) -> bool { use token::*; use Delimiter::*; - use TokenTree::Delimited as Del; - use TokenTree::Token as Tok; + use TokenTree::{Delimited as Del, Token as Tok}; fn is_punct(tt: &TokenTree) -> bool { matches!(tt, TokenTree::Token(tok, _) if tok.is_punct()) @@ -1505,35 +1506,7 @@ impl<'a> State<'a> { AsmArg::Options(opts) => { s.word("options"); s.popen(); - let mut options = vec![]; - if opts.contains(InlineAsmOptions::PURE) { - options.push("pure"); - } - if opts.contains(InlineAsmOptions::NOMEM) { - options.push("nomem"); - } - if opts.contains(InlineAsmOptions::READONLY) { - options.push("readonly"); - } - if opts.contains(InlineAsmOptions::PRESERVES_FLAGS) { - options.push("preserves_flags"); - } - if opts.contains(InlineAsmOptions::NORETURN) { - options.push("noreturn"); - } - if opts.contains(InlineAsmOptions::NOSTACK) { - options.push("nostack"); - } - if opts.contains(InlineAsmOptions::ATT_SYNTAX) { - options.push("att_syntax"); - } - if opts.contains(InlineAsmOptions::RAW) { - options.push("raw"); - } - if opts.contains(InlineAsmOptions::MAY_UNWIND) { - options.push("may_unwind"); - } - s.commasep(Inconsistent, &options, |s, &opt| { + s.commasep(Inconsistent, &opts.human_readable_names(), |s, &opt| { s.word(opt); }); s.pclose(); diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs index 5b13858f83942..b13c89c435da7 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -1,19 +1,19 @@ -use crate::pp::Breaks::Inconsistent; -use crate::pprust::state::fixup::FixupContext; -use crate::pprust::state::{AnnNode, PrintState, State, INDENT_UNIT}; +use std::fmt::Write; + use ast::{ForLoopKind, MatchKind}; use itertools::{Itertools, Position}; use rustc_ast::ptr::P; -use rustc_ast::token; use rustc_ast::util::classify; use rustc_ast::util::literal::escape_byte_str_symbol; use rustc_ast::util::parser::{self, AssocOp, Fixity}; -use rustc_ast::{self as ast, BlockCheckMode}; use rustc_ast::{ - FormatAlignment, FormatArgPosition, FormatArgsPiece, FormatCount, FormatDebugHex, FormatSign, - FormatTrait, + self as ast, token, BlockCheckMode, FormatAlignment, FormatArgPosition, FormatArgsPiece, + FormatCount, FormatDebugHex, FormatSign, FormatTrait, }; -use std::fmt::Write; + +use crate::pp::Breaks::Inconsistent; +use crate::pprust::state::fixup::FixupContext; +use crate::pprust::state::{AnnNode, PrintState, State, INDENT_UNIT}; impl<'a> State<'a> { fn print_else(&mut self, els: Option<&ast::Expr>) { diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs index d8382057d3f64..56204d8835a33 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/item.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -1,7 +1,3 @@ -use crate::pp::Breaks::Inconsistent; -use crate::pprust::state::fixup::FixupContext; -use crate::pprust::state::{AnnNode, PrintState, State, INDENT_UNIT}; - use ast::StaticItem; use itertools::{Itertools, Position}; use rustc_ast as ast; @@ -9,6 +5,10 @@ use rustc_ast::ptr::P; use rustc_ast::ModKind; use rustc_span::symbol::Ident; +use crate::pp::Breaks::Inconsistent; +use crate::pprust::state::fixup::FixupContext; +use crate::pprust::state::{AnnNode, PrintState, State, INDENT_UNIT}; + enum DelegationKind<'a> { Single, List(&'a [(Ident, Option)]), diff --git a/compiler/rustc_ast_pretty/src/pprust/tests.rs b/compiler/rustc_ast_pretty/src/pprust/tests.rs index 5b5ffbc6f8821..3fefc523f8883 100644 --- a/compiler/rustc_ast_pretty/src/pprust/tests.rs +++ b/compiler/rustc_ast_pretty/src/pprust/tests.rs @@ -1,11 +1,10 @@ -use super::*; - use rustc_ast as ast; -use rustc_span::create_default_session_globals_then; use rustc_span::symbol::Ident; -use rustc_span::DUMMY_SP; +use rustc_span::{create_default_session_globals_then, DUMMY_SP}; use thin_vec::ThinVec; +use super::*; + fn fun_to_string( decl: &ast::FnDecl, header: ast::FnHeader, diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index 34c24a26f7b13..12a19ae5c3db9 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -1,8 +1,12 @@ //! Parsing and validation of builtin attributes +use std::num::NonZero; + use rustc_abi::Align; -use rustc_ast::{self as ast, attr}; -use rustc_ast::{Attribute, LitKind, MetaItem, MetaItemKind, MetaItemLit, NestedMetaItem, NodeId}; +use rustc_ast::{ + self as ast, attr, Attribute, LitKind, MetaItem, MetaItemKind, MetaItemLit, NestedMetaItem, + NodeId, +}; use rustc_ast_pretty::pprust; use rustc_errors::ErrorGuaranteed; use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg}; @@ -13,8 +17,8 @@ use rustc_session::lint::BuiltinLintDiag; use rustc_session::parse::feature_err; use rustc_session::{RustcVersion, Session}; use rustc_span::hygiene::Transparency; -use rustc_span::{symbol::sym, symbol::Symbol, Span}; -use std::num::NonZero; +use rustc_span::symbol::{sym, Symbol}; +use rustc_span::Span; use crate::session_diagnostics::{self, IncorrectReprFormatGenericCause}; @@ -574,7 +578,7 @@ fn gate_cfg(gated_cfg: &GatedCfg, cfg_span: Span, sess: &Session, features: &Fea /// Parse a rustc version number written inside string literal in an attribute, /// like appears in `since = "1.0.0"`. Suffixes like "-dev" and "-nightly" are /// not accepted in this position, unlike when parsing CFG_RELEASE. -fn parse_version(s: Symbol) -> Option { +pub fn parse_version(s: Symbol) -> Option { let mut components = s.as_str().split('-'); let d = components.next()?; if components.next().is_some() { diff --git a/compiler/rustc_attr/src/lib.rs b/compiler/rustc_attr/src/lib.rs index 9cc53ad7ad8c7..1ecfc42ec1df4 100644 --- a/compiler/rustc_attr/src/lib.rs +++ b/compiler/rustc_attr/src/lib.rs @@ -15,12 +15,10 @@ mod builtin; mod session_diagnostics; pub use builtin::*; +pub use rustc_ast::attr::*; +pub(crate) use rustc_session::HashStableContext; pub use IntType::*; pub use ReprAttr::*; pub use StabilityLevel::*; -pub use rustc_ast::attr::*; - -pub(crate) use rustc_session::HashStableContext; - rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_attr/src/session_diagnostics.rs b/compiler/rustc_attr/src/session_diagnostics.rs index 0cffeed0a7550..92a3a385a7441 100644 --- a/compiler/rustc_attr/src/session_diagnostics.rs +++ b/compiler/rustc_attr/src/session_diagnostics.rs @@ -1,13 +1,12 @@ use std::num::IntErrorKind; use rustc_ast as ast; -use rustc_errors::DiagCtxtHandle; -use rustc_errors::{codes::*, Applicability, Diag, Diagnostic, EmissionGuarantee, Level}; +use rustc_errors::codes::*; +use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level}; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Span, Symbol}; -use crate::fluent_generated as fluent; -use crate::UnsupportedLiteralReason; +use crate::{fluent_generated as fluent, UnsupportedLiteralReason}; #[derive(Diagnostic)] #[diag(attr_expected_one_cfg_pattern, code = E0536)] diff --git a/compiler/rustc_borrowck/src/borrow_set.rs b/compiler/rustc_borrowck/src/borrow_set.rs index 0bae1bd07a298..51b420c441a7c 100644 --- a/compiler/rustc_borrowck/src/borrow_set.rs +++ b/compiler/rustc_borrowck/src/borrow_set.rs @@ -1,16 +1,17 @@ -use crate::path_utils::allow_two_phase_borrow; -use crate::place_ext::PlaceExt; -use crate::BorrowIndex; +use std::fmt; +use std::ops::Index; + use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_index::bit_set::BitSet; -use rustc_middle::mir::traversal; use rustc_middle::mir::visit::{MutatingUseContext, NonUseContext, PlaceContext, Visitor}; -use rustc_middle::mir::{self, Body, Local, Location}; +use rustc_middle::mir::{self, traversal, Body, Local, Location}; use rustc_middle::span_bug; use rustc_middle::ty::{RegionVid, TyCtxt}; use rustc_mir_dataflow::move_paths::MoveData; -use std::fmt; -use std::ops::Index; + +use crate::path_utils::allow_two_phase_borrow; +use crate::place_ext::PlaceExt; +use crate::BorrowIndex; pub struct BorrowSet<'tcx> { /// The fundamental map relating bitvector indexes to the borrows diff --git a/compiler/rustc_borrowck/src/borrowck_errors.rs b/compiler/rustc_borrowck/src/borrowck_errors.rs index 80deea1468531..76e39fe94af43 100644 --- a/compiler/rustc_borrowck/src/borrowck_errors.rs +++ b/compiler/rustc_borrowck/src/borrowck_errors.rs @@ -1,8 +1,8 @@ #![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::untranslatable_diagnostic)] -use rustc_errors::Applicability; -use rustc_errors::{codes::*, struct_span_code_err, Diag, DiagCtxtHandle}; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, Applicability, Diag, DiagCtxtHandle}; use rustc_hir as hir; use rustc_middle::span_bug; use rustc_middle::ty::{self, Ty, TyCtxt}; diff --git a/compiler/rustc_borrowck/src/constraints/graph.rs b/compiler/rustc_borrowck/src/constraints/graph.rs index 540b466560c5d..0ae837898b9c0 100644 --- a/compiler/rustc_borrowck/src/constraints/graph.rs +++ b/compiler/rustc_borrowck/src/constraints/graph.rs @@ -4,11 +4,8 @@ use rustc_middle::mir::ConstraintCategory; use rustc_middle::ty::{RegionVid, VarianceDiagInfo}; use rustc_span::DUMMY_SP; -use crate::{ - constraints::OutlivesConstraintIndex, - constraints::{OutlivesConstraint, OutlivesConstraintSet}, - type_check::Locations, -}; +use crate::constraints::{OutlivesConstraint, OutlivesConstraintIndex, OutlivesConstraintSet}; +use crate::type_check::Locations; /// The construct graph organizes the constraints by their end-points. /// It can be used to view a `R1: R2` constraint as either an edge `R1 diff --git a/compiler/rustc_borrowck/src/constraints/mod.rs b/compiler/rustc_borrowck/src/constraints/mod.rs index bb2fc3b67e9d0..7062632de6645 100644 --- a/compiler/rustc_borrowck/src/constraints/mod.rs +++ b/compiler/rustc_borrowck/src/constraints/mod.rs @@ -1,12 +1,14 @@ -use crate::region_infer::{ConstraintSccs, RegionDefinition, RegionTracker}; -use crate::type_check::Locations; -use crate::universal_regions::UniversalRegions; +use std::fmt; +use std::ops::Index; + use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::mir::ConstraintCategory; use rustc_middle::ty::{RegionVid, TyCtxt, VarianceDiagInfo}; use rustc_span::Span; -use std::fmt; -use std::ops::Index; + +use crate::region_infer::{ConstraintSccs, RegionDefinition, RegionTracker}; +use crate::type_check::Locations; +use crate::universal_regions::UniversalRegions; pub(crate) mod graph; diff --git a/compiler/rustc_borrowck/src/consumers.rs b/compiler/rustc_borrowck/src/consumers.rs index b9fa46ea883ff..8f560635cb339 100644 --- a/compiler/rustc_borrowck/src/consumers.rs +++ b/compiler/rustc_borrowck/src/consumers.rs @@ -1,24 +1,22 @@ //! This file provides API for compiler consumers. +use std::rc::Rc; + use rustc_hir::def_id::LocalDefId; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::mir::{Body, Promoted}; use rustc_middle::ty::TyCtxt; -use std::rc::Rc; +pub use super::constraints::OutlivesConstraint; +pub use super::dataflow::{calculate_borrows_out_of_scope_at_location, BorrowIndex, Borrows}; +pub use super::facts::{AllFacts as PoloniusInput, RustcFacts}; +pub use super::location::{LocationTable, RichLocation}; +pub use super::nll::PoloniusOutput; +pub use super::place_ext::PlaceExt; +pub use super::places_conflict::{places_conflict, PlaceConflictBias}; +pub use super::region_infer::RegionInferenceContext; use crate::borrow_set::BorrowSet; -pub use super::{ - constraints::OutlivesConstraint, - dataflow::{calculate_borrows_out_of_scope_at_location, BorrowIndex, Borrows}, - facts::{AllFacts as PoloniusInput, RustcFacts}, - location::{LocationTable, RichLocation}, - nll::PoloniusOutput, - place_ext::PlaceExt, - places_conflict::{places_conflict, PlaceConflictBias}, - region_infer::RegionInferenceContext, -}; - /// Options determining the output behavior of [`get_body_with_borrowck_facts`]. /// /// If executing under `-Z polonius` the choice here has no effect, and everything as if diff --git a/compiler/rustc_borrowck/src/dataflow.rs b/compiler/rustc_borrowck/src/dataflow.rs index 59b3c6916cbdd..77794a8525f8d 100644 --- a/compiler/rustc_borrowck/src/dataflow.rs +++ b/compiler/rustc_borrowck/src/dataflow.rs @@ -1,16 +1,15 @@ +use std::fmt; + use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::graph; use rustc_index::bit_set::BitSet; use rustc_middle::mir::{ self, BasicBlock, Body, CallReturnPlaces, Location, Place, TerminatorEdges, }; -use rustc_middle::ty::RegionVid; -use rustc_middle::ty::TyCtxt; +use rustc_middle::ty::{RegionVid, TyCtxt}; +use rustc_mir_dataflow::fmt::DebugWithContext; use rustc_mir_dataflow::impls::{EverInitializedPlaces, MaybeUninitializedPlaces}; -use rustc_mir_dataflow::ResultsVisitable; -use rustc_mir_dataflow::{fmt::DebugWithContext, GenKill}; -use rustc_mir_dataflow::{Analysis, AnalysisDomain, Results}; -use std::fmt; +use rustc_mir_dataflow::{Analysis, AnalysisDomain, GenKill, Results, ResultsVisitable}; use crate::{places_conflict, BorrowSet, PlaceConflictBias, PlaceExt, RegionInferenceContext}; diff --git a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs index cbee01f2e2d0f..52eda72177392 100644 --- a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs @@ -1,17 +1,18 @@ +use std::fmt; +use std::rc::Rc; + use rustc_errors::Diag; use rustc_hir::def_id::LocalDefId; use rustc_infer::infer::canonical::Canonical; -use rustc_infer::infer::region_constraints::Constraint; -use rustc_infer::infer::region_constraints::RegionConstraintData; -use rustc_infer::infer::RegionVariableOrigin; -use rustc_infer::infer::{InferCtxt, RegionResolutionError, SubregionOrigin, TyCtxtInferExt as _}; +use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData}; +use rustc_infer::infer::{ + InferCtxt, RegionResolutionError, RegionVariableOrigin, SubregionOrigin, TyCtxtInferExt as _, +}; use rustc_infer::traits::ObligationCause; use rustc_middle::ty::error::TypeError; -use rustc_middle::ty::RePlaceholder; -use rustc_middle::ty::Region; -use rustc_middle::ty::RegionVid; -use rustc_middle::ty::UniverseIndex; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; +use rustc_middle::ty::{ + self, RePlaceholder, Region, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex, +}; use rustc_span::Span; use rustc_trait_selection::error_reporting::infer::nice_region_error::NiceRegionError; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; @@ -19,13 +20,10 @@ use rustc_trait_selection::traits::query::type_op; use rustc_trait_selection::traits::ObligationCtxt; use rustc_traits::{type_op_ascribe_user_type_with_span, type_op_prove_predicate_with_cause}; -use std::fmt; -use std::rc::Rc; - use crate::region_infer::values::RegionElement; -use crate::session_diagnostics::HigherRankedErrorCause; -use crate::session_diagnostics::HigherRankedLifetimeError; -use crate::session_diagnostics::HigherRankedSubtypeError; +use crate::session_diagnostics::{ + HigherRankedErrorCause, HigherRankedLifetimeError, HigherRankedSubtypeError, +}; use crate::MirBorrowckCtxt; #[derive(Clone)] diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index b147567001db1..7a925705806fc 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -3,25 +3,27 @@ #![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::untranslatable_diagnostic)] +use std::iter; +use std::ops::ControlFlow; + use either::Either; use hir::{ClosureKind, Path}; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexSet; -use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diag, MultiSpan}; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, Applicability, Diag, MultiSpan}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::{walk_block, walk_expr, Map, Visitor}; -use rustc_hir::{CoroutineDesugaring, PatField}; -use rustc_hir::{CoroutineKind, CoroutineSource, LangItem}; +use rustc_hir::{CoroutineDesugaring, CoroutineKind, CoroutineSource, LangItem, PatField}; use rustc_middle::bug; use rustc_middle::hir::nested_filter::OnlyBodies; use rustc_middle::mir::tcx::PlaceTy; -use rustc_middle::mir::VarDebugInfoContents; use rustc_middle::mir::{ self, AggregateKind, BindingForm, BorrowKind, CallSource, ClearCrossCrate, ConstraintCategory, FakeBorrowKind, FakeReadCause, LocalDecl, LocalInfo, LocalKind, Location, MutBorrowKind, Operand, Place, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, - TerminatorKind, VarBindingForm, + TerminatorKind, VarBindingForm, VarDebugInfoContents, }; use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::{ @@ -30,8 +32,7 @@ use rustc_middle::ty::{ }; use rustc_middle::util::CallKind; use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex}; -use rustc_span::def_id::DefId; -use rustc_span::def_id::LocalDefId; +use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::hygiene::DesugaringKind; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{BytePos, Span, Symbol}; @@ -39,22 +40,14 @@ use rustc_trait_selection::error_reporting::traits::FindExprBySpan; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{Obligation, ObligationCause, ObligationCtxt}; -use std::iter; -use std::ops::ControlFlow; -use crate::borrow_set::TwoPhaseActivation; -use crate::borrowck_errors; +use super::explain_borrow::{BorrowExplanation, LaterUseKind}; +use super::{DescribePlaceOpt, RegionName, RegionNameSource, UseSpans}; +use crate::borrow_set::{BorrowData, TwoPhaseActivation}; use crate::diagnostics::conflict_errors::StorageDeadOrDrop::LocalStorageDead; -use crate::diagnostics::{find_all_local_uses, CapturedMessageOpt}; -use crate::{ - borrow_set::BorrowData, diagnostics::Instance, prefixes::IsPrefixOf, - InitializationRequiringAction, MirBorrowckCtxt, WriteKind, -}; - -use super::{ - explain_borrow::{BorrowExplanation, LaterUseKind}, - DescribePlaceOpt, RegionName, RegionNameSource, UseSpans, -}; +use crate::diagnostics::{find_all_local_uses, CapturedMessageOpt, Instance}; +use crate::prefixes::IsPrefixOf; +use crate::{borrowck_errors, InitializationRequiringAction, MirBorrowckCtxt, WriteKind}; #[derive(Debug)] struct MoveSite { @@ -570,11 +563,11 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { } = move_spans && can_suggest_clone { - self.suggest_cloning(err, ty, expr, None, Some(move_spans)); + self.suggest_cloning(err, ty, expr, Some(move_spans)); } else if self.suggest_hoisting_call_outside_loop(err, expr) && can_suggest_clone { // The place where the type moves would be misleading to suggest clone. // #121466 - self.suggest_cloning(err, ty, expr, None, Some(move_spans)); + self.suggest_cloning(err, ty, expr, Some(move_spans)); } } @@ -1236,8 +1229,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { &self, err: &mut Diag<'_>, ty: Ty<'tcx>, - mut expr: &'tcx hir::Expr<'tcx>, - mut other_expr: Option<&'tcx hir::Expr<'tcx>>, + expr: &'tcx hir::Expr<'tcx>, use_spans: Option>, ) { if let hir::ExprKind::Struct(_, _, Some(_)) = expr.kind { @@ -1249,97 +1241,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { return; } - if let Some(some_other_expr) = other_expr - && let Some(parent_binop) = - self.infcx.tcx.hir().parent_iter(expr.hir_id).find_map(|n| { - if let (hir_id, hir::Node::Expr(e)) = n - && let hir::ExprKind::AssignOp(_binop, target, _arg) = e.kind - && target.hir_id == expr.hir_id - { - Some(hir_id) - } else { - None - } - }) - && let Some(other_parent_binop) = - self.infcx.tcx.hir().parent_iter(some_other_expr.hir_id).find_map(|n| { - if let (hir_id, hir::Node::Expr(expr)) = n - && let hir::ExprKind::AssignOp(..) = expr.kind - { - Some(hir_id) - } else { - None - } - }) - && parent_binop == other_parent_binop - { - // Explicitly look for `expr += other_expr;` and avoid suggesting - // `expr.clone() += other_expr;`, instead suggesting `expr += other_expr.clone();`. - other_expr = Some(expr); - expr = some_other_expr; - } - 'outer: { - if let ty::Ref(..) = ty.kind() { - // We check for either `let binding = foo(expr, other_expr);` or - // `foo(expr, other_expr);` and if so we don't suggest an incorrect - // `foo(expr, other_expr).clone()` - if let Some(other_expr) = other_expr - && let Some(parent_let) = - self.infcx.tcx.hir().parent_iter(expr.hir_id).find_map(|n| { - if let (hir_id, hir::Node::LetStmt(_) | hir::Node::Stmt(_)) = n { - Some(hir_id) - } else { - None - } - }) - && let Some(other_parent_let) = - self.infcx.tcx.hir().parent_iter(other_expr.hir_id).find_map(|n| { - if let (hir_id, hir::Node::LetStmt(_) | hir::Node::Stmt(_)) = n { - Some(hir_id) - } else { - None - } - }) - && parent_let == other_parent_let - { - // Explicitly check that we don't have `foo(&*expr, other_expr)`, as cloning the - // result of `foo(...)` won't help. - break 'outer; - } - - // We're suggesting `.clone()` on an borrowed value. See if the expression we have - // is an argument to a function or method call, and try to suggest cloning the - // *result* of the call, instead of the argument. This is closest to what people - // would actually be looking for in most cases, with maybe the exception of things - // like `fn(T) -> T`, but even then it is reasonable. - let typeck_results = self.infcx.tcx.typeck(self.mir_def_id()); - let mut prev = expr; - while let hir::Node::Expr(parent) = self.infcx.tcx.parent_hir_node(prev.hir_id) { - if let hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) = parent.kind - && let Some(call_ty) = typeck_results.node_type_opt(parent.hir_id) - && let call_ty = call_ty.peel_refs() - && (!call_ty - .walk() - .any(|t| matches!(t.unpack(), ty::GenericArgKind::Lifetime(_))) - || if let ty::Alias(ty::Projection, _) = call_ty.kind() { - // FIXME: this isn't quite right with lifetimes on assoc types, - // but ignore for now. We will only suggest cloning if - // `::Assoc: Clone`, which should keep false positives - // down to a managable ammount. - true - } else { - false - }) - && self.implements_clone(call_ty) - && self.suggest_cloning_inner(err, call_ty, parent) - { - return; - } - prev = parent; - } - } - } - let ty = ty.peel_refs(); if self.implements_clone(ty) { self.suggest_cloning_inner(err, ty, expr); } else if let ty::Adt(def, args) = ty.kind() @@ -1442,9 +1343,14 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { // See `tests/ui/moves/needs-clone-through-deref.rs` return false; } + // We don't want to suggest `.clone()` in a move closure, since the value has already been captured. if self.in_move_closure(expr) { return false; } + // We also don't want to suggest cloning a closure itself, since the value has already been captured. + if let hir::ExprKind::Closure(_) = expr.kind { + return false; + } // Try to find predicates on *generic params* that would allow copying `ty` let mut suggestion = if let Some(symbol) = tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { @@ -1606,10 +1512,27 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { ); self.suggest_copy_for_type_in_cloned_ref(&mut err, place); let typeck_results = self.infcx.tcx.typeck(self.mir_def_id()); - if let Some(expr) = self.find_expr(borrow_span) - && let Some(ty) = typeck_results.node_type_opt(expr.hir_id) - { - self.suggest_cloning(&mut err, ty, expr, self.find_expr(span), Some(move_spans)); + if let Some(expr) = self.find_expr(borrow_span) { + // This is a borrow span, so we want to suggest cloning the referent. + if let hir::ExprKind::AddrOf(_, _, borrowed_expr) = expr.kind + && let Some(ty) = typeck_results.expr_ty_opt(borrowed_expr) + { + self.suggest_cloning(&mut err, ty, borrowed_expr, Some(move_spans)); + } else if typeck_results.expr_adjustments(expr).first().is_some_and(|adj| { + matches!( + adj.kind, + ty::adjustment::Adjust::Borrow(ty::adjustment::AutoBorrow::Ref( + _, + ty::adjustment::AutoBorrowMutability::Not + | ty::adjustment::AutoBorrowMutability::Mut { + allow_two_phase_borrow: ty::adjustment::AllowTwoPhase::No + } + )) + ) + }) && let Some(ty) = typeck_results.expr_ty_opt(expr) + { + self.suggest_cloning(&mut err, ty, expr, Some(move_spans)); + } } self.buffer_error(err); } @@ -4304,17 +4227,35 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { // search for relevant arguments. let mut arguments = Vec::new(); for (index, argument) in sig.inputs().skip_binder().iter().enumerate() { - if let ty::Ref(argument_region, _, _) = argument.kind() { - if argument_region == return_region { - // Need to use the `rustc_middle::ty` types to compare against the - // `return_region`. Then use the `rustc_hir` type to get only - // the lifetime span. - if let hir::TyKind::Ref(lifetime, _) = &fn_decl.inputs[index].kind { + if let ty::Ref(argument_region, _, _) = argument.kind() + && argument_region == return_region + { + // Need to use the `rustc_middle::ty` types to compare against the + // `return_region`. Then use the `rustc_hir` type to get only + // the lifetime span. + match &fn_decl.inputs[index].kind { + hir::TyKind::Ref(lifetime, _) => { // With access to the lifetime, we can get // the span of it. arguments.push((*argument, lifetime.ident.span)); - } else { - bug!("ty type is a ref but hir type is not"); + } + // Resolve `self` whose self type is `&T`. + hir::TyKind::Path(hir::QPath::Resolved(None, path)) => { + if let Res::SelfTyAlias { alias_to, .. } = path.res + && let Some(alias_to) = alias_to.as_local() + && let hir::Impl { self_ty, .. } = self + .infcx + .tcx + .hir_node_by_def_id(alias_to) + .expect_item() + .expect_impl() + && let hir::TyKind::Ref(lifetime, _) = self_ty.kind + { + arguments.push((*argument, lifetime.ident.span)); + } + } + _ => { + // Don't ICE though. It might be a type alias. } } } diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index ffe52f939dd3b..3590e12274ca6 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -19,13 +19,11 @@ use rustc_span::symbol::{kw, Symbol}; use rustc_span::{sym, DesugaringKind, Span}; use rustc_trait_selection::error_reporting::traits::FindExprBySpan; -use crate::region_infer::{BlameConstraint, ExtraConstraintInfo}; -use crate::{ - borrow_set::BorrowData, nll::ConstraintDescription, region_infer::Cause, MirBorrowckCtxt, - WriteKind, -}; - use super::{find_use, RegionName, UseSpans}; +use crate::borrow_set::BorrowData; +use crate::nll::ConstraintDescription; +use crate::region_infer::{BlameConstraint, Cause, ExtraConstraintInfo}; +use crate::{MirBorrowckCtxt, WriteKind}; #[derive(Debug)] pub(crate) enum BorrowExplanation<'tcx> { diff --git a/compiler/rustc_borrowck/src/diagnostics/find_use.rs b/compiler/rustc_borrowck/src/diagnostics/find_use.rs index 94b17e0a2f99c..bea8d3bfdfbb1 100644 --- a/compiler/rustc_borrowck/src/diagnostics/find_use.rs +++ b/compiler/rustc_borrowck/src/diagnostics/find_use.rs @@ -1,15 +1,14 @@ use std::collections::VecDeque; use std::rc::Rc; -use crate::{ - def_use::{self, DefUse}, - region_infer::{Cause, RegionInferenceContext}, -}; use rustc_data_structures::fx::FxIndexSet; use rustc_middle::mir::visit::{MirVisitable, PlaceContext, Visitor}; use rustc_middle::mir::{self, Body, Local, Location}; use rustc_middle::ty::{RegionVid, TyCtxt}; +use crate::def_use::{self, DefUse}; +use crate::region_infer::{Cause, RegionInferenceContext}; + pub(crate) fn find<'tcx>( body: &Body<'tcx>, regioncx: &Rc>, diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index d505d9c004ef7..a2e5c7b85145a 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -1,14 +1,8 @@ //! Borrow checker diagnostics. -use crate::session_diagnostics::{ - CaptureArgLabel, CaptureReasonLabel, CaptureReasonNote, CaptureReasonSuggest, CaptureVarCause, - CaptureVarKind, CaptureVarPathUseCause, OnClosureNote, -}; -use rustc_errors::MultiSpan; -use rustc_errors::{Applicability, Diag}; +use rustc_errors::{Applicability, Diag, MultiSpan}; use rustc_hir::def::{CtorKind, Namespace}; -use rustc_hir::CoroutineKind; -use rustc_hir::{self as hir, LangItem}; +use rustc_hir::{self as hir, CoroutineKind, LangItem}; use rustc_index::IndexSlice; use rustc_infer::infer::BoundRegionConversionTime; use rustc_infer::traits::SelectionError; @@ -25,7 +19,8 @@ use rustc_middle::util::{call_kind, CallDesugaringKind}; use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult}; use rustc_span::def_id::LocalDefId; use rustc_span::source_map::Spanned; -use rustc_span::{symbol::sym, Span, Symbol, DUMMY_SP}; +use rustc_span::symbol::sym; +use rustc_span::{Span, Symbol, DUMMY_SP}; use rustc_target::abi::{FieldIdx, VariantIdx}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::InferCtxtExt; @@ -33,10 +28,13 @@ use rustc_trait_selection::traits::{ type_known_to_meet_bound_modulo_regions, FulfillmentErrorCode, }; -use crate::fluent_generated as fluent; - use super::borrow_set::BorrowData; use super::MirBorrowckCtxt; +use crate::fluent_generated as fluent; +use crate::session_diagnostics::{ + CaptureArgLabel, CaptureReasonLabel, CaptureReasonNote, CaptureReasonSuggest, CaptureVarCause, + CaptureVarKind, CaptureVarPathUseCause, OnClosureNote, +}; mod find_all_local_uses; mod find_use; @@ -599,8 +597,9 @@ impl UseSpans<'_> { err: &mut Diag<'_>, action: crate::InitializationRequiringAction, ) { - use crate::InitializationRequiringAction::*; use CaptureVarPathUseCause::*; + + use crate::InitializationRequiringAction::*; if let UseSpans::ClosureUse { closure_kind, path_span, .. } = self { match closure_kind { hir::ClosureKind::Coroutine(_) => { diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index fcf23aa478555..792f1548e081e 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -11,8 +11,7 @@ use rustc_mir_dataflow::move_paths::{LookupResult, MovePathIndex}; use rustc_span::{BytePos, ExpnKind, MacroKind, Span}; use rustc_trait_selection::error_reporting::traits::FindExprBySpan; -use crate::diagnostics::CapturedMessageOpt; -use crate::diagnostics::{DescribePlaceOpt, UseSpans}; +use crate::diagnostics::{CapturedMessageOpt, DescribePlaceOpt, UseSpans}; use crate::prefixes::PrefixSet; use crate::MirBorrowckCtxt; @@ -565,9 +564,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { fn add_move_hints(&self, error: GroupedMoveError<'tcx>, err: &mut Diag<'_>, span: Span) { match error { - GroupedMoveError::MovesFromPlace { - mut binds_to, move_from, span: other_span, .. - } => { + GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => { self.add_borrow_suggestions(err, span); if binds_to.is_empty() { let place_ty = move_from.ty(self.body, self.infcx.tcx).ty; @@ -577,7 +574,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { }; if let Some(expr) = self.find_expr(span) { - self.suggest_cloning(err, place_ty, expr, self.find_expr(other_span), None); + self.suggest_cloning(err, place_ty, expr, None); } err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { @@ -609,13 +606,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { }; if let Some(expr) = self.find_expr(use_span) { - self.suggest_cloning( - err, - place_ty, - expr, - self.find_expr(span), - Some(use_spans), - ); + self.suggest_cloning(err, place_ty, expr, Some(use_spans)); } err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { @@ -740,7 +731,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { let place_desc = &format!("`{}`", self.local_names[*local].unwrap()); if let Some(expr) = self.find_expr(binding_span) { - self.suggest_cloning(err, bind_to.ty, expr, None, None); + self.suggest_cloning(err, bind_to.ty, expr, None); } err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index a7bf6d636c1c1..0303b80cace45 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -2,17 +2,18 @@ #![allow(rustc::untranslatable_diagnostic)] use core::ops::ControlFlow; + use hir::{ExprKind, Param}; use rustc_errors::{Applicability, Diag}; use rustc_hir::intravisit::Visitor; use rustc_hir::{self as hir, BindingMode, ByRef, Node}; use rustc_middle::bug; -use rustc_middle::mir::{Mutability, Place, PlaceRef, ProjectionElem}; -use rustc_middle::ty::{self, InstanceKind, Ty, TyCtxt, Upcast}; -use rustc_middle::{ - hir::place::PlaceBase, - mir::{self, BindingForm, Local, LocalDecl, LocalInfo, LocalKind, Location}, +use rustc_middle::hir::place::PlaceBase; +use rustc_middle::mir::{ + self, BindingForm, Local, LocalDecl, LocalInfo, LocalKind, Location, Mutability, Place, + PlaceRef, ProjectionElem, }; +use rustc_middle::ty::{self, InstanceKind, Ty, TyCtxt, Upcast}; use rustc_span::symbol::{kw, Symbol}; use rustc_span::{sym, BytePos, DesugaringKind, Span}; use rustc_target::abi::FieldIdx; @@ -847,10 +848,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> { // Attempt to search similar mutable associated items for suggestion. // In the future, attempt in all path but initially for RHS of for_loop fn suggest_similar_mut_method_for_for_loop(&self, err: &mut Diag<'_>, span: Span) { - use hir::{ - BorrowKind, Expr, - ExprKind::{AddrOf, Block, Call, MethodCall}, - }; + use hir::ExprKind::{AddrOf, Block, Call, MethodCall}; + use hir::{BorrowKind, Expr}; let hir_map = self.infcx.tcx.hir(); struct Finder { diff --git a/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs b/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs index 082111a642c22..9356c24d018f7 100644 --- a/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs +++ b/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs @@ -4,15 +4,15 @@ #![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::untranslatable_diagnostic)] +use std::collections::BTreeMap; + use rustc_data_structures::fx::FxIndexSet; use rustc_errors::Diag; use rustc_middle::ty::RegionVid; use smallvec::SmallVec; -use std::collections::BTreeMap; - -use crate::MirBorrowckCtxt; use super::{ErrorConstraintInfo, RegionName, RegionNameSource}; +use crate::MirBorrowckCtxt; /// The different things we could suggest. enum SuggestedConstraint { diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 6b7bd7dc0d8bf..82df9760d8e7c 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -14,10 +14,7 @@ use rustc_infer::infer::{NllRegionVariableOrigin, RelateParamBound}; use rustc_middle::bug; use rustc_middle::hir::place::PlaceBase; use rustc_middle::mir::{ConstraintCategory, ReturnConstraint}; -use rustc_middle::ty::GenericArgs; -use rustc_middle::ty::TypeVisitor; -use rustc_middle::ty::{self, RegionVid, Ty}; -use rustc_middle::ty::{Region, TyCtxt}; +use rustc_middle::ty::{self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeVisitor}; use rustc_span::symbol::{kw, Ident}; use rustc_span::Span; use rustc_trait_selection::error_reporting::infer::nice_region_error::{ @@ -29,20 +26,16 @@ use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{Obligation, ObligationCtxt}; -use crate::borrowck_errors; +use super::{OutlivesSuggestionBuilder, RegionName, RegionNameSource}; +use crate::nll::ConstraintDescription; +use crate::region_infer::values::RegionElement; +use crate::region_infer::{BlameConstraint, ExtraConstraintInfo, TypeTest}; use crate::session_diagnostics::{ FnMutError, FnMutReturnTypeErr, GenericDoesNotLiveLongEnough, LifetimeOutliveErr, LifetimeReturnCategoryErr, RequireStaticErr, VarHereDenote, }; - -use super::{OutlivesSuggestionBuilder, RegionName, RegionNameSource}; -use crate::region_infer::{BlameConstraint, ExtraConstraintInfo}; -use crate::{ - nll::ConstraintDescription, - region_infer::{values::RegionElement, TypeTest}, - universal_regions::DefiningTy, - MirBorrowckCtxt, -}; +use crate::universal_regions::DefiningTy; +use crate::{borrowck_errors, MirBorrowckCtxt}; impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> { fn description(&self) -> &'static str { diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index 6443c5e92e8ab..12aedf6fe088b 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -9,14 +9,14 @@ use rustc_errors::Diag; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_middle::ty::print::RegionHighlightMode; -use rustc_middle::ty::{self, RegionVid, Ty}; -use rustc_middle::ty::{GenericArgKind, GenericArgsRef}; +use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, RegionVid, Ty}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::{Span, DUMMY_SP}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; -use crate::{universal_regions::DefiningTy, MirBorrowckCtxt}; +use crate::universal_regions::DefiningTy; +use crate::MirBorrowckCtxt; /// A name for a particular region used in emitting diagnostics. This name could be a generated /// name like `'1`, a name used by the user like `'a`, or a name like `'static`. diff --git a/compiler/rustc_borrowck/src/diagnostics/var_name.rs b/compiler/rustc_borrowck/src/diagnostics/var_name.rs index 0479cd8af35e2..3e9f975b66bb6 100644 --- a/compiler/rustc_borrowck/src/diagnostics/var_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/var_name.rs @@ -1,10 +1,11 @@ -use crate::region_infer::RegionInferenceContext; use rustc_index::IndexSlice; use rustc_middle::mir::{Body, Local}; use rustc_middle::ty::{self, RegionVid, TyCtxt}; use rustc_span::symbol::Symbol; use rustc_span::Span; +use crate::region_infer::RegionInferenceContext; + impl<'tcx> RegionInferenceContext<'tcx> { pub(crate) fn get_var_name_and_span_for_region( &self, diff --git a/compiler/rustc_borrowck/src/facts.rs b/compiler/rustc_borrowck/src/facts.rs index af96f11538503..94b5044857689 100644 --- a/compiler/rustc_borrowck/src/facts.rs +++ b/compiler/rustc_borrowck/src/facts.rs @@ -1,17 +1,18 @@ -use crate::location::{LocationIndex, LocationTable}; -use crate::BorrowIndex; -use polonius_engine::AllFacts as PoloniusFacts; -use polonius_engine::Atom; -use rustc_macros::extension; -use rustc_middle::mir::Local; -use rustc_middle::ty::{RegionVid, TyCtxt}; -use rustc_mir_dataflow::move_paths::MovePathIndex; use std::error::Error; use std::fmt::Debug; use std::fs::{self, File}; use std::io::{BufWriter, Write}; use std::path::Path; +use polonius_engine::{AllFacts as PoloniusFacts, Atom}; +use rustc_macros::extension; +use rustc_middle::mir::Local; +use rustc_middle::ty::{RegionVid, TyCtxt}; +use rustc_mir_dataflow::move_paths::MovePathIndex; + +use crate::location::{LocationIndex, LocationTable}; +use crate::BorrowIndex; + #[derive(Copy, Clone, Debug)] pub struct RustcFacts; diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 9ad941dabbe65..9c2a0036befa8 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -17,6 +17,13 @@ #[macro_use] extern crate tracing; +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::marker::PhantomData; +use std::ops::Deref; +use std::rc::Rc; + +use consumers::{BodyWithBorrowckFacts, ConsumerOptions}; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::graph::dominators::Dominators; use rustc_errors::Diag; @@ -24,40 +31,31 @@ use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_index::bit_set::{BitSet, ChunkedBitSet}; use rustc_index::{IndexSlice, IndexVec}; -use rustc_infer::infer::TyCtxtInferExt; -use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin}; +use rustc_infer::infer::{ + InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin, TyCtxtInferExt, +}; use rustc_middle::mir::tcx::PlaceTy; use rustc_middle::mir::*; use rustc_middle::query::Providers; use rustc_middle::ty::{self, ParamEnv, RegionVid, TyCtxt}; use rustc_middle::{bug, span_bug}; -use rustc_session::lint::builtin::UNUSED_MUT; -use rustc_span::{Span, Symbol}; -use rustc_target::abi::FieldIdx; - -use smallvec::SmallVec; -use std::cell::RefCell; -use std::collections::BTreeMap; -use std::marker::PhantomData; -use std::ops::Deref; -use std::rc::Rc; - use rustc_mir_dataflow::impls::{ EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces, }; -use rustc_mir_dataflow::move_paths::{InitIndex, MoveOutIndex, MovePathIndex}; -use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult, MoveData}; +use rustc_mir_dataflow::move_paths::{ + InitIndex, InitLocation, LookupResult, MoveData, MoveOutIndex, MovePathIndex, +}; use rustc_mir_dataflow::Analysis; -use rustc_mir_dataflow::MoveDataParamEnv; - -use crate::session_diagnostics::VarNeedNotMut; +use rustc_session::lint::builtin::UNUSED_MUT; +use rustc_span::{Span, Symbol}; +use rustc_target::abi::FieldIdx; +use smallvec::SmallVec; use self::diagnostics::{AccessKind, IllegalMoveOriginKind, MoveError, RegionName}; use self::location::LocationTable; -use self::prefixes::PrefixSet; -use consumers::{BodyWithBorrowckFacts, ConsumerOptions}; - use self::path_utils::*; +use self::prefixes::PrefixSet; +use crate::session_diagnostics::VarNeedNotMut; pub mod borrow_set; mod borrowck_errors; @@ -196,9 +194,7 @@ fn do_mir_borrowck<'tcx>( .iter_enumerated() .map(|(idx, body)| (idx, MoveData::gather_moves(body, tcx, param_env, |_| true))); - let mdpe = MoveDataParamEnv { move_data, param_env }; - - let mut flow_inits = MaybeInitializedPlaces::new(tcx, body, &mdpe) + let mut flow_inits = MaybeInitializedPlaces::new(tcx, body, &move_data) .into_engine(tcx, body) .pass_name("borrowck") .iterate_to_fixpoint() @@ -206,7 +202,7 @@ fn do_mir_borrowck<'tcx>( let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(def).is_fn_or_closure(); let borrow_set = - Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data)); + Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &move_data)); // Compute non-lexical lifetimes. let nll::NllOutput { @@ -224,7 +220,7 @@ fn do_mir_borrowck<'tcx>( &location_table, param_env, &mut flow_inits, - &mdpe.move_data, + &move_data, &borrow_set, tcx.closure_captures(def), consumer_options, @@ -256,11 +252,11 @@ fn do_mir_borrowck<'tcx>( .into_engine(tcx, body) .pass_name("borrowck") .iterate_to_fixpoint(); - let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe) + let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &move_data) .into_engine(tcx, body) .pass_name("borrowck") .iterate_to_fixpoint(); - let flow_ever_inits = EverInitializedPlaces::new(body, &mdpe) + let flow_ever_inits = EverInitializedPlaces::new(body, &move_data) .into_engine(tcx, body) .pass_name("borrowck") .iterate_to_fixpoint(); @@ -326,7 +322,7 @@ fn do_mir_borrowck<'tcx>( infcx: &infcx, param_env, body, - move_data: &mdpe.move_data, + move_data: &move_data, location_table: &location_table, movable_coroutine, locals_are_invalidated_at_exit, diff --git a/compiler/rustc_borrowck/src/member_constraints.rs b/compiler/rustc_borrowck/src/member_constraints.rs index 5129b32d492dd..499c32396d0ae 100644 --- a/compiler/rustc_borrowck/src/member_constraints.rs +++ b/compiler/rustc_borrowck/src/member_constraints.rs @@ -1,11 +1,12 @@ +use std::hash::Hash; +use std::ops::Index; + use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexMap; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::infer::MemberConstraint; use rustc_middle::ty::{self, Ty}; use rustc_span::Span; -use std::hash::Hash; -use std::ops::Index; /// Compactly stores a set of `R0 member of [R1...Rn]` constraints, /// indexed by the region `R0`. diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs index 2ffa9ba5b4d32..af37c028879d0 100644 --- a/compiler/rustc_borrowck/src/nll.rs +++ b/compiler/rustc_borrowck/src/nll.rs @@ -1,11 +1,18 @@ //! The entry point of the NLL borrow checker. +use std::path::PathBuf; +use std::rc::Rc; +use std::str::FromStr; +use std::{env, io}; + use polonius_engine::{Algorithm, Output}; use rustc_data_structures::fx::FxIndexMap; use rustc_hir::def_id::LocalDefId; use rustc_index::IndexSlice; -use rustc_middle::mir::{create_dump_file, dump_enabled, dump_mir, PassWhere}; -use rustc_middle::mir::{Body, ClosureOutlivesSubject, ClosureRegionRequirements, Promoted}; +use rustc_middle::mir::{ + create_dump_file, dump_enabled, dump_mir, Body, ClosureOutlivesSubject, + ClosureRegionRequirements, PassWhere, Promoted, +}; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self, OpaqueHiddenType, TyCtxt}; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; @@ -13,25 +20,16 @@ use rustc_mir_dataflow::move_paths::MoveData; use rustc_mir_dataflow::points::DenseLocationMap; use rustc_mir_dataflow::ResultsCursor; use rustc_span::symbol::sym; -use std::env; -use std::io; -use std::path::PathBuf; -use std::rc::Rc; -use std::str::FromStr; -use crate::{ - borrow_set::BorrowSet, - consumers::ConsumerOptions, - diagnostics::RegionErrors, - facts::{AllFacts, AllFactsExt, RustcFacts}, - location::LocationTable, - polonius, - region_infer::RegionInferenceContext, - renumber, - type_check::{self, MirTypeckRegionConstraints, MirTypeckResults}, - universal_regions::UniversalRegions, - BorrowckInferCtxt, -}; +use crate::borrow_set::BorrowSet; +use crate::consumers::ConsumerOptions; +use crate::diagnostics::RegionErrors; +use crate::facts::{AllFacts, AllFactsExt, RustcFacts}; +use crate::location::LocationTable; +use crate::region_infer::RegionInferenceContext; +use crate::type_check::{self, MirTypeckRegionConstraints, MirTypeckResults}; +use crate::universal_regions::UniversalRegions; +use crate::{polonius, renumber, BorrowckInferCtxt}; pub type PoloniusOutput = Output; diff --git a/compiler/rustc_borrowck/src/path_utils.rs b/compiler/rustc_borrowck/src/path_utils.rs index 88b20bba9fb03..4afb41be18f10 100644 --- a/compiler/rustc_borrowck/src/path_utils.rs +++ b/compiler/rustc_borrowck/src/path_utils.rs @@ -1,13 +1,11 @@ -use crate::borrow_set::{BorrowData, BorrowSet, TwoPhaseActivation}; -use crate::places_conflict; -use crate::AccessDepth; -use crate::BorrowIndex; use rustc_data_structures::graph::dominators::Dominators; -use rustc_middle::mir::BorrowKind; -use rustc_middle::mir::{BasicBlock, Body, Location, Place, PlaceRef, ProjectionElem}; +use rustc_middle::mir::{BasicBlock, Body, BorrowKind, Location, Place, PlaceRef, ProjectionElem}; use rustc_middle::ty::TyCtxt; use rustc_target::abi::FieldIdx; +use crate::borrow_set::{BorrowData, BorrowSet, TwoPhaseActivation}; +use crate::{places_conflict, AccessDepth, BorrowIndex}; + /// Returns `true` if the borrow represented by `kind` is /// allowed to be split into separate Reservation and /// Activation phases. diff --git a/compiler/rustc_borrowck/src/place_ext.rs b/compiler/rustc_borrowck/src/place_ext.rs index 0f806df9da1da..ce63d51682e5b 100644 --- a/compiler/rustc_borrowck/src/place_ext.rs +++ b/compiler/rustc_borrowck/src/place_ext.rs @@ -1,10 +1,10 @@ -use crate::borrow_set::LocalsStateAtExit; use rustc_hir as hir; use rustc_macros::extension; -use rustc_middle::mir::ProjectionElem; -use rustc_middle::mir::{Body, Mutability, Place}; +use rustc_middle::mir::{Body, Mutability, Place, ProjectionElem}; use rustc_middle::ty::{self, TyCtxt}; +use crate::borrow_set::LocalsStateAtExit; + #[extension(pub trait PlaceExt<'tcx>)] impl<'tcx> Place<'tcx> { /// Returns `true` if we can safely ignore borrows of this place. diff --git a/compiler/rustc_borrowck/src/places_conflict.rs b/compiler/rustc_borrowck/src/places_conflict.rs index ad3c3e6d07932..42d0c2038f8bb 100644 --- a/compiler/rustc_borrowck/src/places_conflict.rs +++ b/compiler/rustc_borrowck/src/places_conflict.rs @@ -50,17 +50,17 @@ //! and either equal or disjoint. //! - If we did run out of access, the borrow can access a part of it. -use crate::ArtificialField; -use crate::Overlap; -use crate::{AccessDepth, Deep, Shallow}; +use std::cmp::max; +use std::iter; + use rustc_hir as hir; use rustc_middle::bug; use rustc_middle::mir::{ Body, BorrowKind, FakeBorrowKind, MutBorrowKind, Place, PlaceElem, PlaceRef, ProjectionElem, }; use rustc_middle::ty::{self, TyCtxt}; -use std::cmp::max; -use std::iter; + +use crate::{AccessDepth, ArtificialField, Deep, Overlap, Shallow}; /// When checking if a place conflicts with another place, this enum is used to influence decisions /// where a place might be equal or disjoint with another place, such as if `a[i] == a[j]`. diff --git a/compiler/rustc_borrowck/src/polonius/loan_invalidations.rs b/compiler/rustc_borrowck/src/polonius/loan_invalidations.rs index 30dfc4c21b06a..f090da031a04b 100644 --- a/compiler/rustc_borrowck/src/polonius/loan_invalidations.rs +++ b/compiler/rustc_borrowck/src/polonius/loan_invalidations.rs @@ -2,17 +2,19 @@ use rustc_data_structures::graph::dominators::Dominators; use rustc_middle::bug; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::{ - self, BasicBlock, Body, FakeBorrowKind, Location, NonDivergingIntrinsic, Place, Rvalue, + self, BasicBlock, Body, BorrowKind, FakeBorrowKind, InlineAsmOperand, Location, Mutability, + NonDivergingIntrinsic, Operand, Place, Rvalue, Statement, StatementKind, Terminator, + TerminatorKind, }; -use rustc_middle::mir::{BorrowKind, Mutability, Operand}; -use rustc_middle::mir::{InlineAsmOperand, Terminator, TerminatorKind}; -use rustc_middle::mir::{Statement, StatementKind}; use rustc_middle::ty::TyCtxt; +use crate::borrow_set::BorrowSet; +use crate::facts::AllFacts; +use crate::location::LocationTable; +use crate::path_utils::*; use crate::{ - borrow_set::BorrowSet, facts::AllFacts, location::LocationTable, path_utils::*, AccessDepth, - Activation, ArtificialField, BorrowIndex, Deep, LocalMutationIsAllowed, Read, ReadKind, - ReadOrWrite, Reservation, Shallow, Write, WriteKind, + AccessDepth, Activation, ArtificialField, BorrowIndex, Deep, LocalMutationIsAllowed, Read, + ReadKind, ReadOrWrite, Reservation, Shallow, Write, WriteKind, }; /// Emit `loan_invalidated_at` facts. diff --git a/compiler/rustc_borrowck/src/polonius/loan_kills.rs b/compiler/rustc_borrowck/src/polonius/loan_kills.rs index 53adad5561e60..d85c2175bed59 100644 --- a/compiler/rustc_borrowck/src/polonius/loan_kills.rs +++ b/compiler/rustc_borrowck/src/polonius/loan_kills.rs @@ -5,7 +5,10 @@ use rustc_middle::mir::{ }; use rustc_middle::ty::TyCtxt; -use crate::{borrow_set::BorrowSet, facts::AllFacts, location::LocationTable, places_conflict}; +use crate::borrow_set::BorrowSet; +use crate::facts::AllFacts; +use crate::location::LocationTable; +use crate::places_conflict; /// Emit `loan_killed_at` and `cfg_edge` facts at the same time. pub(super) fn emit_loan_kills<'tcx>( diff --git a/compiler/rustc_borrowck/src/prefixes.rs b/compiler/rustc_borrowck/src/prefixes.rs index 5d3ac1c409a95..d3bfd1c418fe4 100644 --- a/compiler/rustc_borrowck/src/prefixes.rs +++ b/compiler/rustc_borrowck/src/prefixes.rs @@ -4,10 +4,10 @@ //! is borrowed. But: writing `a` is legal if `*a` is borrowed, //! whether or not `a` is a shared or mutable reference. [...] " -use super::MirBorrowckCtxt; - use rustc_middle::mir::{PlaceRef, ProjectionElem}; +use super::MirBorrowckCtxt; + pub trait IsPrefixOf<'tcx> { fn is_prefix_of(&self, other: PlaceRef<'tcx>) -> bool; } diff --git a/compiler/rustc_borrowck/src/region_infer/dump_mir.rs b/compiler/rustc_borrowck/src/region_infer/dump_mir.rs index 53541b33c41d1..6b8dd1a49e72d 100644 --- a/compiler/rustc_borrowck/src/region_infer/dump_mir.rs +++ b/compiler/rustc_borrowck/src/region_infer/dump_mir.rs @@ -3,11 +3,13 @@ //! state of region inference. This code handles emitting the region //! context internal state. -use super::{OutlivesConstraint, RegionInferenceContext}; -use crate::type_check::Locations; +use std::io::{self, Write}; + use rustc_infer::infer::NllRegionVariableOrigin; use rustc_middle::ty::TyCtxt; -use std::io::{self, Write}; + +use super::{OutlivesConstraint, RegionInferenceContext}; +use crate::type_check::Locations; // Room for "'_#NNNNr" before things get misaligned. // Easy enough to fix if this ever doesn't seem like diff --git a/compiler/rustc_borrowck/src/region_infer/graphviz.rs b/compiler/rustc_borrowck/src/region_infer/graphviz.rs index f145d30fe38a9..743864dd53505 100644 --- a/compiler/rustc_borrowck/src/region_infer/graphviz.rs +++ b/compiler/rustc_borrowck/src/region_infer/graphviz.rs @@ -5,11 +5,12 @@ use std::borrow::Cow; use std::io::{self, Write}; -use super::*; use itertools::Itertools; use rustc_graphviz as dot; use rustc_middle::ty::UniverseIndex; +use super::*; + fn render_outlives_constraint(constraint: &OutlivesConstraint<'_>) -> String { match constraint.locations { Locations::All(_) => "All(...)".to_string(), diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index 44a84fb9d7f1a..c8dc012de4a29 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -17,27 +17,25 @@ use rustc_middle::mir::{ ClosureRegionRequirements, ConstraintCategory, Local, Location, ReturnConstraint, TerminatorKind, }; -use rustc_middle::traits::ObligationCause; -use rustc_middle::traits::ObligationCauseCode; +use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex}; use rustc_mir_dataflow::points::DenseLocationMap; use rustc_span::Span; use crate::constraints::graph::{self, NormalConstraintGraph, RegionGraph}; +use crate::constraints::{ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet}; use crate::dataflow::BorrowIndex; -use crate::{ - constraints::{ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet}, - diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo}, - member_constraints::{MemberConstraintSet, NllMemberConstraintIndex}, - nll::PoloniusOutput, - region_infer::reverse_sccs::ReverseSccGraph, - region_infer::values::{ - LivenessValues, PlaceholderIndices, RegionElement, RegionValues, ToElementIndex, - }, - type_check::{free_region_relations::UniversalRegionRelations, Locations}, - universal_regions::UniversalRegions, - BorrowckInferCtxt, +use crate::diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo}; +use crate::member_constraints::{MemberConstraintSet, NllMemberConstraintIndex}; +use crate::nll::PoloniusOutput; +use crate::region_infer::reverse_sccs::ReverseSccGraph; +use crate::region_infer::values::{ + LivenessValues, PlaceholderIndices, RegionElement, RegionValues, ToElementIndex, }; +use crate::type_check::free_region_relations::UniversalRegionRelations; +use crate::type_check::Locations; +use crate::universal_regions::UniversalRegions; +use crate::BorrowckInferCtxt; mod dump_mir; mod graphviz; diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs index cf28ba224d6a5..8c9de5210cd38 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs @@ -3,22 +3,20 @@ use rustc_errors::ErrorGuaranteed; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::OpaqueTyOrigin; -use rustc_infer::infer::TyCtxtInferExt as _; -use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin}; +use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin, TyCtxtInferExt as _}; use rustc_infer::traits::{Obligation, ObligationCause}; use rustc_macros::extension; use rustc_middle::ty::visit::TypeVisitableExt; -use rustc_middle::ty::{self, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable}; -use rustc_middle::ty::{GenericArgKind, GenericArgs}; +use rustc_middle::ty::{ + self, GenericArgKind, GenericArgs, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, +}; use rustc_span::Span; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::ObligationCtxt; -use crate::session_diagnostics::LifetimeMismatchOpaqueParam; -use crate::session_diagnostics::NonGenericOpaqueTypeParam; -use crate::universal_regions::RegionClassification; - use super::RegionInferenceContext; +use crate::session_diagnostics::{LifetimeMismatchOpaqueParam, NonGenericOpaqueTypeParam}; +use crate::universal_regions::RegionClassification; impl<'tcx> RegionInferenceContext<'tcx> { /// Resolve any opaque types that were encountered while borrow checking diff --git a/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs b/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs index 97ddc45ee476d..3cc5fa4404e35 100644 --- a/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs +++ b/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs @@ -1,10 +1,12 @@ -use crate::constraints::ConstraintSccIndex; -use crate::RegionInferenceContext; +use std::ops::Range; + use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::graph; use rustc_data_structures::graph::vec_graph::VecGraph; use rustc_middle::ty::RegionVid; -use std::ops::Range; + +use crate::constraints::ConstraintSccIndex; +use crate::RegionInferenceContext; pub(crate) struct ReverseSccGraph { graph: VecGraph, diff --git a/compiler/rustc_borrowck/src/region_infer/values.rs b/compiler/rustc_borrowck/src/region_infer/values.rs index b1caaa6388186..1e91130bdc54e 100644 --- a/compiler/rustc_borrowck/src/region_infer/values.rs +++ b/compiler/rustc_borrowck/src/region_infer/values.rs @@ -1,14 +1,13 @@ -use rustc_data_structures::fx::FxHashSet; -use rustc_data_structures::fx::FxIndexSet; +use std::fmt::Debug; +use std::rc::Rc; + +use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_index::bit_set::SparseBitMatrix; -use rustc_index::interval::IntervalSet; -use rustc_index::interval::SparseIntervalMatrix; +use rustc_index::interval::{IntervalSet, SparseIntervalMatrix}; use rustc_index::Idx; use rustc_middle::mir::{BasicBlock, Location}; use rustc_middle::ty::{self, RegionVid}; use rustc_mir_dataflow::points::{DenseLocationMap, PointIndex}; -use std::fmt::Debug; -use std::rc::Rc; use crate::BorrowIndex; diff --git a/compiler/rustc_borrowck/src/renumber.rs b/compiler/rustc_borrowck/src/renumber.rs index 2858a407e098b..2a3b51532e542 100644 --- a/compiler/rustc_borrowck/src/renumber.rs +++ b/compiler/rustc_borrowck/src/renumber.rs @@ -1,12 +1,12 @@ -use crate::BorrowckInferCtxt; use rustc_index::IndexSlice; use rustc_infer::infer::NllRegionVariableOrigin; use rustc_middle::mir::visit::{MutVisitor, TyContext}; use rustc_middle::mir::{Body, ConstOperand, Location, Promoted}; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; +use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeFoldable}; use rustc_span::Symbol; +use crate::BorrowckInferCtxt; + /// Replaces all free regions appearing in the MIR with fresh /// inference variables, returning the number of variables created. #[instrument(skip(infcx, body, promoted), level = "debug")] diff --git a/compiler/rustc_borrowck/src/session_diagnostics.rs b/compiler/rustc_borrowck/src/session_diagnostics.rs index 40c2ef1c91e14..4a50b0f070408 100644 --- a/compiler/rustc_borrowck/src/session_diagnostics.rs +++ b/compiler/rustc_borrowck/src/session_diagnostics.rs @@ -1,4 +1,5 @@ -use rustc_errors::{codes::*, MultiSpan}; +use rustc_errors::codes::*; +use rustc_errors::MultiSpan; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::{GenericArg, Ty}; use rustc_span::Span; diff --git a/compiler/rustc_borrowck/src/type_check/canonical.rs b/compiler/rustc_borrowck/src/type_check/canonical.rs index 2dc2568cd47ca..86cd8b918fc6e 100644 --- a/compiler/rustc_borrowck/src/type_check/canonical.rs +++ b/compiler/rustc_borrowck/src/type_check/canonical.rs @@ -10,9 +10,8 @@ use rustc_span::Span; use rustc_trait_selection::traits::query::type_op::{self, TypeOpOutput}; use rustc_trait_selection::traits::ObligationCause; -use crate::diagnostics::ToUniverseInfo; - use super::{Locations, NormalizeLocation, TypeChecker}; +use crate::diagnostics::ToUniverseInfo; impl<'a, 'tcx> TypeChecker<'a, 'tcx> { /// Given some operation `op` that manipulates types, proves diff --git a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs index 0cb4b15b1271d..9876f44c002d4 100644 --- a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs +++ b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs @@ -14,12 +14,10 @@ use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp; use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput}; use rustc_trait_selection::traits::ScrubbedTraitError; -use crate::{ - constraints::OutlivesConstraint, - region_infer::TypeTest, - type_check::{Locations, MirTypeckRegionConstraints}, - universal_regions::UniversalRegions, -}; +use crate::constraints::OutlivesConstraint; +use crate::region_infer::TypeTest; +use crate::type_check::{Locations, MirTypeckRegionConstraints}; +use crate::universal_regions::UniversalRegions; pub(crate) struct ConstraintConversion<'a, 'tcx> { infcx: &'a InferCtxt<'tcx>, diff --git a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs index e4c2e0fced7c0..b7fb9964ce74f 100644 --- a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs +++ b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs @@ -1,11 +1,12 @@ +use std::rc::Rc; + use rustc_data_structures::frozen::Frozen; use rustc_data_structures::transitive_relation::{TransitiveRelation, TransitiveRelationBuilder}; use rustc_hir::def::DefKind; use rustc_infer::infer::canonical::QueryRegionConstraints; -use rustc_infer::infer::outlives; use rustc_infer::infer::outlives::env::RegionBoundPairs; use rustc_infer::infer::region_constraints::GenericKind; -use rustc_infer::infer::InferCtxt; +use rustc_infer::infer::{outlives, InferCtxt}; use rustc_middle::mir::ConstraintCategory; use rustc_middle::traits::query::OutlivesBound; use rustc_middle::traits::ObligationCause; @@ -14,14 +15,10 @@ use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::solve::deeply_normalize; use rustc_trait_selection::traits::query::type_op::{self, TypeOp}; -use std::rc::Rc; use type_op::TypeOpOutput; -use crate::{ - type_check::constraint_conversion, - type_check::{Locations, MirTypeckRegionConstraints}, - universal_regions::UniversalRegions, -}; +use crate::type_check::{constraint_conversion, Locations, MirTypeckRegionConstraints}; +use crate::universal_regions::UniversalRegions; #[derive(Debug)] pub(crate) struct UniversalRegionRelations<'tcx> { diff --git a/compiler/rustc_borrowck/src/type_check/input_output.rs b/compiler/rustc_borrowck/src/type_check/input_output.rs index 741ec05dc9a16..ba6030bdff772 100644 --- a/compiler/rustc_borrowck/src/type_check/input_output.rs +++ b/compiler/rustc_borrowck/src/type_check/input_output.rs @@ -16,11 +16,10 @@ use rustc_middle::mir::*; use rustc_middle::ty::{self, Ty}; use rustc_span::Span; +use super::{Locations, TypeChecker}; use crate::renumber::RegionCtxt; use crate::universal_regions::{DefiningTy, UniversalRegions}; -use super::{Locations, TypeChecker}; - impl<'a, 'tcx> TypeChecker<'a, 'tcx> { /// Check explicit closure signature annotation, /// e.g., `|x: FxIndexMap<_, &'static u32>| ...`. diff --git a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs index 6d6425b5f19f0..a320add0636af 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs @@ -1,3 +1,5 @@ +use std::rc::Rc; + use itertools::{Either, Itertools}; use rustc_data_structures::fx::FxHashSet; use rustc_middle::mir::visit::{TyContext, Visitor}; @@ -9,14 +11,11 @@ use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::move_paths::MoveData; use rustc_mir_dataflow::points::DenseLocationMap; use rustc_mir_dataflow::ResultsCursor; -use std::rc::Rc; - -use crate::{ - constraints::OutlivesConstraintSet, region_infer::values::LivenessValues, - universal_regions::UniversalRegions, -}; use super::TypeChecker; +use crate::constraints::OutlivesConstraintSet; +use crate::region_infer::values::LivenessValues; +use crate::universal_regions::UniversalRegions; mod local_use_map; mod polonius; diff --git a/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs b/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs index a009e28a0ddd0..8c13b166c0541 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs @@ -1,11 +1,11 @@ -use crate::def_use::{self, DefUse}; -use crate::location::{LocationIndex, LocationTable}; use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::{Body, Local, Location, Place}; use rustc_middle::ty::GenericArg; use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex}; use super::TypeChecker; +use crate::def_use::{self, DefUse}; +use crate::location::{LocationIndex, LocationTable}; type VarPointRelation = Vec<(Local, LocationIndex)>; type PathPointRelation = Vec<(MovePathIndex, LocationIndex)>; diff --git a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs index eb86c8d06f113..f0c521cdcfc5b 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs @@ -1,3 +1,5 @@ +use std::rc::Rc; + use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_index::bit_set::BitSet; use rustc_index::interval::IntervalSet; @@ -6,24 +8,19 @@ use rustc_infer::infer::outlives::for_liveness; use rustc_middle::mir::{BasicBlock, Body, ConstraintCategory, Local, Location}; use rustc_middle::traits::query::DropckOutlivesResult; use rustc_middle::ty::{Ty, TyCtxt, TypeVisitable, TypeVisitableExt}; +use rustc_mir_dataflow::impls::MaybeInitializedPlaces; +use rustc_mir_dataflow::move_paths::{HasMoveData, MoveData, MovePathIndex}; use rustc_mir_dataflow::points::{DenseLocationMap, PointIndex}; +use rustc_mir_dataflow::ResultsCursor; use rustc_span::DUMMY_SP; use rustc_trait_selection::traits::query::type_op::outlives::DropckOutlives; use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput}; -use std::rc::Rc; - -use rustc_mir_dataflow::impls::MaybeInitializedPlaces; -use rustc_mir_dataflow::move_paths::{HasMoveData, MoveData, MovePathIndex}; -use rustc_mir_dataflow::ResultsCursor; use crate::location::RichLocation; -use crate::{ - region_infer::values::{self, LiveLoans}, - type_check::liveness::local_use_map::LocalUseMap, - type_check::liveness::polonius, - type_check::NormalizeLocation, - type_check::TypeChecker, -}; +use crate::region_infer::values::{self, LiveLoans}; +use crate::type_check::liveness::local_use_map::LocalUseMap; +use crate::type_check::liveness::polonius; +use crate::type_check::{NormalizeLocation, TypeChecker}; /// This is the heart of the liveness computation. For each variable X /// that requires a liveness computation, it walks over all the uses diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index db4b5209145f0..b13773ffe1460 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -4,7 +4,6 @@ use std::rc::Rc; use std::{fmt, iter, mem}; use either::Either; - use rustc_data_structures::frozen::Frozen; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_errors::ErrorGuaranteed; @@ -28,44 +27,38 @@ use rustc_middle::ty::cast::CastTy; use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{ self, Binder, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, CoroutineArgsExt, - Dynamic, OpaqueHiddenType, OpaqueTypeKey, RegionVid, Ty, TyCtxt, UserType, - UserTypeAnnotationIndex, + Dynamic, GenericArgsRef, OpaqueHiddenType, OpaqueTypeKey, RegionVid, Ty, TyCtxt, UserArgs, + UserType, UserTypeAnnotationIndex, }; -use rustc_middle::ty::{GenericArgsRef, UserArgs}; use rustc_middle::{bug, span_bug}; +use rustc_mir_dataflow::impls::MaybeInitializedPlaces; +use rustc_mir_dataflow::move_paths::MoveData; use rustc_mir_dataflow::points::DenseLocationMap; +use rustc_mir_dataflow::ResultsCursor; use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::source_map::Spanned; use rustc_span::symbol::sym; -use rustc_span::Span; -use rustc_span::DUMMY_SP; +use rustc_span::{Span, DUMMY_SP}; use rustc_target::abi::{FieldIdx, FIRST_VARIANT}; -use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints; -use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp; +use rustc_trait_selection::traits::query::type_op::custom::{ + scrape_region_constraints, CustomTypeOp, +}; use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput}; - use rustc_trait_selection::traits::PredicateObligation; -use rustc_mir_dataflow::impls::MaybeInitializedPlaces; -use rustc_mir_dataflow::move_paths::MoveData; -use rustc_mir_dataflow::ResultsCursor; - +use crate::borrow_set::BorrowSet; +use crate::constraints::{OutlivesConstraint, OutlivesConstraintSet}; +use crate::diagnostics::UniverseInfo; +use crate::facts::AllFacts; +use crate::location::LocationTable; +use crate::member_constraints::MemberConstraintSet; +use crate::region_infer::values::{LivenessValues, PlaceholderIndex, PlaceholderIndices}; +use crate::region_infer::TypeTest; use crate::renumber::RegionCtxt; use crate::session_diagnostics::{MoveUnsized, SimdIntrinsicArgConst}; -use crate::{ - borrow_set::BorrowSet, - constraints::{OutlivesConstraint, OutlivesConstraintSet}, - diagnostics::UniverseInfo, - facts::AllFacts, - location::LocationTable, - member_constraints::MemberConstraintSet, - path_utils, - region_infer::values::{LivenessValues, PlaceholderIndex, PlaceholderIndices}, - region_infer::TypeTest, - type_check::free_region_relations::{CreateResult, UniversalRegionRelations}, - universal_regions::{DefiningTy, UniversalRegions}, - BorrowckInferCtxt, -}; +use crate::type_check::free_region_relations::{CreateResult, UniversalRegionRelations}; +use crate::universal_regions::{DefiningTy, UniversalRegions}; +use crate::{path_utils, BorrowckInferCtxt}; macro_rules! span_mirbug { ($context:expr, $elem:expr, $($message:tt)*) => ({ @@ -2337,10 +2330,16 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { match (cast_ty_from, cast_ty_to) { (Some(CastTy::Ptr(src)), Some(CastTy::Ptr(dst))) => { let mut normalize = |t| self.normalize(t, location); + + // N.B. `struct_tail_with_normalize` only "structurally resolves" + // the type. It is not fully normalized, so we have to normalize it + // afterwards. let src_tail = tcx.struct_tail_with_normalize(src.ty, &mut normalize, || ()); + let src_tail = normalize(src_tail); let dst_tail = tcx.struct_tail_with_normalize(dst.ty, &mut normalize, || ()); + let dst_tail = normalize(dst_tail); // This checks (lifetime part of) vtable validity for pointer casts, // which is irrelevant when there are aren't principal traits on both sides (aka only auto traits). diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index 9f5fb59e46c55..1ad80cb122ab6 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -15,6 +15,9 @@ #![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::untranslatable_diagnostic)] +use std::cell::Cell; +use std::iter; + use rustc_data_structures::fx::FxIndexMap; use rustc_errors::Diag; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -25,13 +28,12 @@ use rustc_infer::infer::NllRegionVariableOrigin; use rustc_macros::extension; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::{self, InlineConstArgs, InlineConstArgsParts, RegionVid, Ty, TyCtxt}; -use rustc_middle::ty::{GenericArgs, GenericArgsRef}; +use rustc_middle::ty::{ + self, GenericArgs, GenericArgsRef, InlineConstArgs, InlineConstArgsParts, RegionVid, Ty, TyCtxt, +}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::{kw, sym}; use rustc_span::{ErrorGuaranteed, Symbol}; -use std::cell::Cell; -use std::iter; use crate::renumber::RegionCtxt; use crate::BorrowckInferCtxt; diff --git a/compiler/rustc_borrowck/src/util/collect_writes.rs b/compiler/rustc_borrowck/src/util/collect_writes.rs index 8d92bb3593857..93c7810b54517 100644 --- a/compiler/rustc_borrowck/src/util/collect_writes.rs +++ b/compiler/rustc_borrowck/src/util/collect_writes.rs @@ -1,5 +1,4 @@ -use rustc_middle::mir::visit::PlaceContext; -use rustc_middle::mir::visit::Visitor; +use rustc_middle::mir::visit::{PlaceContext, Visitor}; use rustc_middle::mir::{Body, Local, Location}; pub trait FindAssignments { diff --git a/compiler/rustc_builtin_macros/messages.ftl b/compiler/rustc_builtin_macros/messages.ftl index b56bfa98357b3..9695df9c87e8a 100644 --- a/compiler/rustc_builtin_macros/messages.ftl +++ b/compiler/rustc_builtin_macros/messages.ftl @@ -115,9 +115,6 @@ builtin_macros_derive_path_args_list = traits in `#[derive(...)]` don't accept a builtin_macros_derive_path_args_value = traits in `#[derive(...)]` don't accept values .suggestion = remove the value -builtin_macros_derive_unsafe_path = traits in `#[derive(...)]` don't accept `unsafe(...)` - .suggestion = remove the `unsafe(...)` - builtin_macros_env_not_defined = environment variable `{$var}` not defined at compile time .cargo = Cargo sets build script variables at run time. Use `std::env::var({$var_expr})` instead .custom = use `std::env::var({$var_expr})` to read the variable at run time @@ -199,6 +196,13 @@ builtin_macros_format_use_positional = consider using a positional formatting ar builtin_macros_global_asm_clobber_abi = `clobber_abi` cannot be used with `global_asm!` +builtin_macros_global_asm_unsupported_operand = the `{$symbol}` operand cannot be used with `global_asm!` + .label = the `{$symbol}` operand is not meaningful for global-scoped inline assembly, remove it + +builtin_macros_global_asm_unsupported_option = the `{$symbol}` option cannot be used with `global_asm!` + .label = the `{$symbol}` option is not meaningful for global-scoped inline assembly + .suggestion = remove this option + builtin_macros_invalid_crate_attribute = invalid crate attribute builtin_macros_multiple_default_attrs = multiple `#[default]` attributes @@ -216,6 +220,11 @@ builtin_macros_multiple_defaults = multiple declared defaults .note = only one variant can be default .suggestion = make `{$ident}` default +builtin_macros_naked_functions_testing_attribute = + cannot use `#[naked]` with testing attributes + .label = function marked with testing attribute here + .naked_attribute = `#[naked]` is incompatible with testing attributes + builtin_macros_no_default_variant = no default declared .help = make a unit variant default by placing `#[default]` above it .suggestion = make `{$ident}` default diff --git a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs index 4721e74b9558b..1df2812e0c887 100644 --- a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs +++ b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs @@ -1,14 +1,15 @@ -use crate::errors; -use crate::util::check_builtin_macro_attribute; - use rustc_ast::ptr::P; -use rustc_ast::{self as ast, FnHeader, FnSig, Generics, StmtKind}; -use rustc_ast::{Fn, ItemKind, Safety, Stmt, TyKind}; +use rustc_ast::{ + self as ast, Fn, FnHeader, FnSig, Generics, ItemKind, Safety, Stmt, StmtKind, TyKind, +}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; use thin_vec::{thin_vec, ThinVec}; +use crate::errors; +use crate::util::check_builtin_macro_attribute; + pub(crate) fn expand( ecx: &mut ExtCtxt<'_>, _span: Span, @@ -79,7 +80,7 @@ fn generate_handler(cx: &ExtCtxt<'_>, handler: Ident, span: Span, sig_span: Span let params = thin_vec![cx.param(span, size, ty_usize.clone()), cx.param(span, align, ty_usize)]; let decl = cx.fn_decl(params, never); let header = FnHeader { safety: Safety::Unsafe(span), ..FnHeader::default() }; - let sig = FnSig { decl, header, span: span }; + let sig = FnSig { decl, header, span }; let body = Some(cx.block_expr(call)); let kind = ItemKind::Fn(Box::new(Fn { diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index dd0f9aaf22104..17439dd3e3eda 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -1,8 +1,5 @@ -use crate::errors; -use crate::util::expr_to_spanned_string; use ast::token::IdentIsRaw; use lint::BuiltinLintDiag; -use rustc_ast as ast; use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter}; use rustc_ast::tokenstream::TokenStream; @@ -11,13 +8,15 @@ use rustc_errors::PResult; use rustc_expand::base::*; use rustc_index::bit_set::GrowableBitSet; use rustc_parse::parser::Parser; -use rustc_parse_format as parse; use rustc_session::lint; -use rustc_span::symbol::Ident; -use rustc_span::symbol::{kw, sym, Symbol}; +use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{ErrorGuaranteed, InnerSpan, Span}; use rustc_target::asm::InlineAsmArch; use smallvec::smallvec; +use {rustc_ast as ast, rustc_parse_format as parse}; + +use crate::errors; +use crate::util::expr_to_spanned_string; pub struct AsmArgs { pub templates: Vec>, @@ -29,6 +28,29 @@ pub struct AsmArgs { pub options_spans: Vec, } +/// Used for better error messages when operand types are used that are not +/// supported by the current macro (e.g. `in` or `out` for `global_asm!`) +/// +/// returns +/// +/// - `Ok(true)` if the current token matches the keyword, and was expected +/// - `Ok(false)` if the current token does not match the keyword +/// - `Err(_)` if the current token matches the keyword, but was not expected +fn eat_operand_keyword<'a>(p: &mut Parser<'a>, symbol: Symbol, expect: bool) -> PResult<'a, bool> { + if expect { + Ok(p.eat_keyword(symbol)) + } else { + let span = p.token.span; + if p.eat_keyword_noexpect(symbol) { + // in gets printed as `r#in` otherwise + let symbol = if symbol == kw::In { "in" } else { symbol.as_str() }; + Err(p.dcx().create_err(errors::GlobalAsmUnsupportedOperand { span, symbol })) + } else { + Ok(false) + } + } +} + fn parse_args<'a>( ecx: &ExtCtxt<'a>, sp: Span, @@ -106,7 +128,7 @@ pub fn parse_asm_args<'a>( }; let mut explicit_reg = false; - let op = if !is_global_asm && p.eat_keyword(kw::In) { + let op = if eat_operand_keyword(p, kw::In, !is_global_asm)? { let reg = parse_reg(p, &mut explicit_reg)?; if p.eat_keyword(kw::Underscore) { let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span }); @@ -114,15 +136,15 @@ pub fn parse_asm_args<'a>( } let expr = p.parse_expr()?; ast::InlineAsmOperand::In { reg, expr } - } else if !is_global_asm && p.eat_keyword(sym::out) { + } else if eat_operand_keyword(p, sym::out, !is_global_asm)? { let reg = parse_reg(p, &mut explicit_reg)?; let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) }; ast::InlineAsmOperand::Out { reg, expr, late: false } - } else if !is_global_asm && p.eat_keyword(sym::lateout) { + } else if eat_operand_keyword(p, sym::lateout, !is_global_asm)? { let reg = parse_reg(p, &mut explicit_reg)?; let expr = if p.eat_keyword(kw::Underscore) { None } else { Some(p.parse_expr()?) }; ast::InlineAsmOperand::Out { reg, expr, late: true } - } else if !is_global_asm && p.eat_keyword(sym::inout) { + } else if eat_operand_keyword(p, sym::inout, !is_global_asm)? { let reg = parse_reg(p, &mut explicit_reg)?; if p.eat_keyword(kw::Underscore) { let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span }); @@ -136,7 +158,7 @@ pub fn parse_asm_args<'a>( } else { ast::InlineAsmOperand::InOut { reg, expr, late: false } } - } else if !is_global_asm && p.eat_keyword(sym::inlateout) { + } else if eat_operand_keyword(p, sym::inlateout, !is_global_asm)? { let reg = parse_reg(p, &mut explicit_reg)?; if p.eat_keyword(kw::Underscore) { let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span }); @@ -150,6 +172,9 @@ pub fn parse_asm_args<'a>( } else { ast::InlineAsmOperand::InOut { reg, expr, late: true } } + } else if eat_operand_keyword(p, sym::label, !is_global_asm)? { + let block = p.parse_block()?; + ast::InlineAsmOperand::Label { block } } else if p.eat_keyword(kw::Const) { let anon_const = p.parse_expr_anon_const()?; ast::InlineAsmOperand::Const { anon_const } @@ -165,9 +190,6 @@ pub fn parse_asm_args<'a>( path: path.clone(), }; ast::InlineAsmOperand::Sym { sym } - } else if !is_global_asm && p.eat_keyword(sym::label) { - let block = p.parse_block()?; - ast::InlineAsmOperand::Label { block } } else if allow_templates { let template = p.parse_expr()?; // If it can't possibly expand to a string, provide diagnostics here to include other @@ -310,6 +332,16 @@ fn err_duplicate_option(p: &Parser<'_>, symbol: Symbol, span: Span) { p.dcx().emit_err(errors::AsmOptAlreadyprovided { span, symbol, full_span }); } +/// Report an invalid option error. +/// +/// This function must be called immediately after the option token is parsed. +/// Otherwise, the suggestion will be incorrect. +fn err_unsupported_option(p: &Parser<'_>, symbol: Symbol, span: Span) { + // Tool-only output + let full_span = if p.token.kind == token::Comma { span.to(p.token.span) } else { span }; + p.dcx().emit_err(errors::GlobalAsmUnsupportedOption { span, symbol, full_span }); +} + /// Try to set the provided option in the provided `AsmArgs`. /// If it is already set, report a duplicate option error. /// @@ -318,13 +350,16 @@ fn err_duplicate_option(p: &Parser<'_>, symbol: Symbol, span: Span) { fn try_set_option<'a>( p: &Parser<'a>, args: &mut AsmArgs, + is_global_asm: bool, symbol: Symbol, option: ast::InlineAsmOptions, ) { - if !args.options.contains(option) { - args.options |= option; - } else { + if is_global_asm && !ast::InlineAsmOptions::GLOBAL_OPTIONS.contains(option) { + err_unsupported_option(p, symbol, p.prev_token.span); + } else if args.options.contains(option) { err_duplicate_option(p, symbol, p.prev_token.span); + } else { + args.options |= option; } } @@ -338,25 +373,33 @@ fn parse_options<'a>( p.expect(&token::OpenDelim(Delimiter::Parenthesis))?; while !p.eat(&token::CloseDelim(Delimiter::Parenthesis)) { - if !is_global_asm && p.eat_keyword(sym::pure) { - try_set_option(p, args, sym::pure, ast::InlineAsmOptions::PURE); - } else if !is_global_asm && p.eat_keyword(sym::nomem) { - try_set_option(p, args, sym::nomem, ast::InlineAsmOptions::NOMEM); - } else if !is_global_asm && p.eat_keyword(sym::readonly) { - try_set_option(p, args, sym::readonly, ast::InlineAsmOptions::READONLY); - } else if !is_global_asm && p.eat_keyword(sym::preserves_flags) { - try_set_option(p, args, sym::preserves_flags, ast::InlineAsmOptions::PRESERVES_FLAGS); - } else if !is_global_asm && p.eat_keyword(sym::noreturn) { - try_set_option(p, args, sym::noreturn, ast::InlineAsmOptions::NORETURN); - } else if !is_global_asm && p.eat_keyword(sym::nostack) { - try_set_option(p, args, sym::nostack, ast::InlineAsmOptions::NOSTACK); - } else if !is_global_asm && p.eat_keyword(sym::may_unwind) { - try_set_option(p, args, kw::Raw, ast::InlineAsmOptions::MAY_UNWIND); - } else if p.eat_keyword(sym::att_syntax) { - try_set_option(p, args, sym::att_syntax, ast::InlineAsmOptions::ATT_SYNTAX); - } else if p.eat_keyword(kw::Raw) { - try_set_option(p, args, kw::Raw, ast::InlineAsmOptions::RAW); - } else { + const OPTIONS: [(Symbol, ast::InlineAsmOptions); ast::InlineAsmOptions::COUNT] = [ + (sym::pure, ast::InlineAsmOptions::PURE), + (sym::nomem, ast::InlineAsmOptions::NOMEM), + (sym::readonly, ast::InlineAsmOptions::READONLY), + (sym::preserves_flags, ast::InlineAsmOptions::PRESERVES_FLAGS), + (sym::noreturn, ast::InlineAsmOptions::NORETURN), + (sym::nostack, ast::InlineAsmOptions::NOSTACK), + (sym::may_unwind, ast::InlineAsmOptions::MAY_UNWIND), + (sym::att_syntax, ast::InlineAsmOptions::ATT_SYNTAX), + (kw::Raw, ast::InlineAsmOptions::RAW), + ]; + + 'blk: { + for (symbol, option) in OPTIONS { + let kw_matched = + if !is_global_asm || ast::InlineAsmOptions::GLOBAL_OPTIONS.contains(option) { + p.eat_keyword(symbol) + } else { + p.eat_keyword_noexpect(symbol) + }; + + if kw_matched { + try_set_option(p, args, is_global_asm, symbol, option); + break 'blk; + } + } + return p.unexpected(); } @@ -459,7 +502,7 @@ fn expand_preparsed_asm( for (i, template_expr) in args.templates.into_iter().enumerate() { if i != 0 { - template.push(ast::InlineAsmTemplatePiece::String("\n".to_string())); + template.push(ast::InlineAsmTemplatePiece::String("\n".into())); } let msg = "asm template must be a string literal"; @@ -527,7 +570,7 @@ fn expand_preparsed_asm( // Don't treat raw asm as a format string. if args.options.contains(ast::InlineAsmOptions::RAW) { - template.push(ast::InlineAsmTemplatePiece::String(template_str.to_string())); + template.push(ast::InlineAsmTemplatePiece::String(template_str.to_string().into())); let template_num_lines = 1 + template_str.matches('\n').count(); line_spans.extend(std::iter::repeat(template_sp).take(template_num_lines)); continue; @@ -577,7 +620,7 @@ fn expand_preparsed_asm( for piece in unverified_pieces { match piece { parse::Piece::String(s) => { - template.push(ast::InlineAsmTemplatePiece::String(s.to_string())) + template.push(ast::InlineAsmTemplatePiece::String(s.to_string().into())) } parse::Piece::NextArgument(arg) => { let span = arg_spans.next().unwrap_or(template_sp); diff --git a/compiler/rustc_builtin_macros/src/assert.rs b/compiler/rustc_builtin_macros/src/assert.rs index c75050f270188..99f433c0851ad 100644 --- a/compiler/rustc_builtin_macros/src/assert.rs +++ b/compiler/rustc_builtin_macros/src/assert.rs @@ -1,12 +1,9 @@ mod context; -use crate::edition_panic::use_panic_2021; -use crate::errors; use rustc_ast::ptr::P; -use rustc_ast::token; use rustc_ast::token::Delimiter; use rustc_ast::tokenstream::{DelimSpan, TokenStream}; -use rustc_ast::{DelimArgs, Expr, ExprKind, MacCall, Path, PathSegment, UnOp}; +use rustc_ast::{token, DelimArgs, Expr, ExprKind, MacCall, Path, PathSegment, UnOp}; use rustc_ast_pretty::pprust; use rustc_errors::PResult; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; @@ -15,6 +12,9 @@ use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; use thin_vec::thin_vec; +use crate::edition_panic::use_panic_2021; +use crate::errors; + pub(crate) fn expand_assert<'cx>( cx: &'cx mut ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/assert/context.rs b/compiler/rustc_builtin_macros/src/assert/context.rs index c664891dad5ac..2cd5b9d68a012 100644 --- a/compiler/rustc_builtin_macros/src/assert/context.rs +++ b/compiler/rustc_builtin_macros/src/assert/context.rs @@ -1,17 +1,15 @@ +use rustc_ast::ptr::P; +use rustc_ast::token::{self, Delimiter, IdentIsRaw}; +use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree}; use rustc_ast::{ - ptr::P, - token::{self, Delimiter, IdentIsRaw}, - tokenstream::{DelimSpan, TokenStream, TokenTree}, BinOpKind, BorrowKind, DelimArgs, Expr, ExprKind, ItemKind, MacCall, MethodCall, Mutability, Path, PathSegment, Stmt, StructRest, UnOp, UseTree, UseTreeKind, DUMMY_NODE_ID, }; use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxHashSet; use rustc_expand::base::ExtCtxt; -use rustc_span::{ - symbol::{sym, Ident, Symbol}, - Span, -}; +use rustc_span::symbol::{sym, Ident, Symbol}; +use rustc_span::Span; use thin_vec::{thin_vec, ThinVec}; pub(super) struct Context<'cx, 'a> { diff --git a/compiler/rustc_builtin_macros/src/cfg.rs b/compiler/rustc_builtin_macros/src/cfg.rs index 827719d794493..de198115fa00b 100644 --- a/compiler/rustc_builtin_macros/src/cfg.rs +++ b/compiler/rustc_builtin_macros/src/cfg.rs @@ -2,14 +2,15 @@ //! a literal `true` or `false` based on whether the given cfg matches the //! current compilation environment. -use crate::errors; -use rustc_ast as ast; use rustc_ast::token; use rustc_ast::tokenstream::TokenStream; -use rustc_attr as attr; use rustc_errors::PResult; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; +use rustc_parse::parser::attr::AllowLeadingUnsafe; use rustc_span::Span; +use {rustc_ast as ast, rustc_attr as attr}; + +use crate::errors; pub(crate) fn expand_cfg( cx: &mut ExtCtxt<'_>, @@ -42,7 +43,7 @@ fn parse_cfg<'a>(cx: &ExtCtxt<'a>, span: Span, tts: TokenStream) -> PResult<'a, return Err(cx.dcx().create_err(errors::RequiresCfgPattern { span })); } - let cfg = p.parse_meta_item()?; + let cfg = p.parse_meta_item(AllowLeadingUnsafe::Yes)?; let _ = p.eat(&token::Comma); diff --git a/compiler/rustc_builtin_macros/src/cfg_accessible.rs b/compiler/rustc_builtin_macros/src/cfg_accessible.rs index 98c0ca3a526b8..006b6aa823fbf 100644 --- a/compiler/rustc_builtin_macros/src/cfg_accessible.rs +++ b/compiler/rustc_builtin_macros/src/cfg_accessible.rs @@ -1,6 +1,5 @@ //! Implementation of the `#[cfg_accessible(path)]` attribute macro. -use crate::errors; use rustc_ast as ast; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, Indeterminate, MultiItemModifier}; use rustc_feature::AttributeTemplate; @@ -8,6 +7,8 @@ use rustc_parse::validate_attr; use rustc_span::symbol::sym; use rustc_span::Span; +use crate::errors; + pub(crate) struct Expander; fn validate_input<'a>(ecx: &ExtCtxt<'_>, mi: &'a ast::MetaItem) -> Option<&'a ast::Path> { @@ -46,11 +47,13 @@ impl MultiItemModifier for Expander { ) -> ExpandResult, Annotatable> { let template = AttributeTemplate { list: Some("path"), ..Default::default() }; validate_attr::check_builtin_meta_item( + &ecx.ecfg.features, &ecx.sess.psess, meta_item, ast::AttrStyle::Outer, sym::cfg_accessible, template, + true, ); let Some(path) = validate_input(ecx, meta_item) else { diff --git a/compiler/rustc_builtin_macros/src/cfg_eval.rs b/compiler/rustc_builtin_macros/src/cfg_eval.rs index b3d252e06a587..4b05c144d37d7 100644 --- a/compiler/rustc_builtin_macros/src/cfg_eval.rs +++ b/compiler/rustc_builtin_macros/src/cfg_eval.rs @@ -1,13 +1,10 @@ -use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute}; - use core::ops::ControlFlow; + use rustc_ast as ast; use rustc_ast::mut_visit::MutVisitor; use rustc_ast::ptr::P; use rustc_ast::visit::{AssocCtxt, Visitor}; -use rustc_ast::NodeId; -use rustc_ast::{mut_visit, visit}; -use rustc_ast::{Attribute, HasAttrs, HasTokens}; +use rustc_ast::{mut_visit, visit, Attribute, HasAttrs, HasTokens, NodeId}; use rustc_errors::PResult; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_expand::config::StripUnconfigured; @@ -20,6 +17,8 @@ use rustc_span::Span; use smallvec::SmallVec; use tracing::instrument; +use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute}; + pub(crate) fn expand( ecx: &mut ExtCtxt<'_>, _span: Span, @@ -203,7 +202,7 @@ impl CfgEval<'_> { } // Now that we have our re-parsed `AttrTokenStream`, recursively configuring - // our attribute target will correctly the tokens as well. + // our attribute target will correctly configure the tokens as well. flat_map_annotatable(self, annotatable) } } diff --git a/compiler/rustc_builtin_macros/src/cmdline_attrs.rs b/compiler/rustc_builtin_macros/src/cmdline_attrs.rs index bffd5672b9b0c..66fa74da60d9f 100644 --- a/compiler/rustc_builtin_macros/src/cmdline_attrs.rs +++ b/compiler/rustc_builtin_macros/src/cmdline_attrs.rs @@ -1,14 +1,14 @@ //! Attributes injected into the crate root from command line using `-Z crate-attr`. -use crate::errors; use rustc_ast::attr::mk_attr; -use rustc_ast::token; -use rustc_ast::{self as ast, AttrItem, AttrStyle}; +use rustc_ast::{self as ast, token, AttrItem, AttrStyle}; use rustc_parse::parser::ForceCollect; use rustc_parse::{new_parser_from_source_str, unwrap_or_emit_fatal}; use rustc_session::parse::ParseSess; use rustc_span::FileName; +use crate::errors; + pub fn inject(krate: &mut ast::Crate, psess: &ParseSess, attrs: &[String]) { for raw_attr in attrs { let mut parser = unwrap_or_emit_fatal(new_parser_from_source_str( diff --git a/compiler/rustc_builtin_macros/src/compile_error.rs b/compiler/rustc_builtin_macros/src/compile_error.rs index a08e8b2819b56..7fc4b437c1d8d 100644 --- a/compiler/rustc_builtin_macros/src/compile_error.rs +++ b/compiler/rustc_builtin_macros/src/compile_error.rs @@ -1,10 +1,11 @@ // The compiler code necessary to support the compile_error! extension. -use crate::util::get_single_str_from_tts; use rustc_ast::tokenstream::TokenStream; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; use rustc_span::Span; +use crate::util::get_single_str_from_tts; + pub(crate) fn expand_compile_error<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, diff --git a/compiler/rustc_builtin_macros/src/concat.rs b/compiler/rustc_builtin_macros/src/concat.rs index 15af79ef67d4a..a28801f66dd10 100644 --- a/compiler/rustc_builtin_macros/src/concat.rs +++ b/compiler/rustc_builtin_macros/src/concat.rs @@ -1,11 +1,12 @@ -use crate::errors; -use crate::util::get_exprs_from_tts; use rustc_ast::tokenstream::TokenStream; use rustc_ast::{ExprKind, LitKind, UnOp}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; use rustc_session::errors::report_lit_error; use rustc_span::symbol::Symbol; +use crate::errors; +use crate::util::get_exprs_from_tts; + pub(crate) fn expand_concat( cx: &mut ExtCtxt<'_>, sp: rustc_span::Span, diff --git a/compiler/rustc_builtin_macros/src/concat_bytes.rs b/compiler/rustc_builtin_macros/src/concat_bytes.rs index 3130870df4105..196bf906dc028 100644 --- a/compiler/rustc_builtin_macros/src/concat_bytes.rs +++ b/compiler/rustc_builtin_macros/src/concat_bytes.rs @@ -1,10 +1,13 @@ -use crate::errors; -use crate::util::get_exprs_from_tts; -use rustc_ast::{ptr::P, token, tokenstream::TokenStream, ExprKind, LitIntType, LitKind, UintTy}; +use rustc_ast::ptr::P; +use rustc_ast::tokenstream::TokenStream; +use rustc_ast::{token, ExprKind, LitIntType, LitKind, UintTy}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; use rustc_session::errors::report_lit_error; use rustc_span::{ErrorGuaranteed, Span}; +use crate::errors; +use crate::util::get_exprs_from_tts; + /// Emits errors for literal expressions that are invalid inside and outside of an array. fn invalid_type_err( cx: &ExtCtxt<'_>, diff --git a/compiler/rustc_builtin_macros/src/derive.rs b/compiler/rustc_builtin_macros/src/derive.rs index b5cbfdf0ec6e4..57bddf0ab60ad 100644 --- a/compiler/rustc_builtin_macros/src/derive.rs +++ b/compiler/rustc_builtin_macros/src/derive.rs @@ -1,8 +1,5 @@ -use crate::cfg_eval::cfg_eval; -use crate::errors; - use rustc_ast as ast; -use rustc_ast::{GenericParamKind, ItemKind, MetaItemKind, NestedMetaItem, Safety, StmtKind}; +use rustc_ast::{GenericParamKind, ItemKind, MetaItemKind, NestedMetaItem, StmtKind}; use rustc_expand::base::{ Annotatable, DeriveResolution, ExpandResult, ExtCtxt, Indeterminate, MultiItemModifier, }; @@ -12,6 +9,9 @@ use rustc_session::Session; use rustc_span::symbol::{sym, Ident}; use rustc_span::{ErrorGuaranteed, Span}; +use crate::cfg_eval::cfg_eval; +use crate::errors; + pub(crate) struct Expander { pub is_const: bool, } @@ -38,11 +38,13 @@ impl MultiItemModifier for Expander { let template = AttributeTemplate { list: Some("Trait1, Trait2, ..."), ..Default::default() }; validate_attr::check_builtin_meta_item( + features, &sess.psess, meta_item, ast::AttrStyle::Outer, sym::derive, template, + true, ); let mut resolutions = match &meta_item.kind { @@ -60,7 +62,6 @@ impl MultiItemModifier for Expander { // Reject `#[derive(Debug = "value", Debug(abc))]`, but recover the // paths. report_path_args(sess, meta); - report_unsafe_args(sess, meta); meta.path.clone() }) .map(|path| DeriveResolution { @@ -160,13 +161,3 @@ fn report_path_args(sess: &Session, meta: &ast::MetaItem) { } } } - -fn report_unsafe_args(sess: &Session, meta: &ast::MetaItem) { - match meta.unsafety { - Safety::Unsafe(span) => { - sess.dcx().emit_err(errors::DeriveUnsafePath { span }); - } - Safety::Default => {} - Safety::Safe(_) => unreachable!(), - } -} diff --git a/compiler/rustc_builtin_macros/src/deriving/bounds.rs b/compiler/rustc_builtin_macros/src/deriving/bounds.rs index f6b5433582929..a98e9c6d1c7fc 100644 --- a/compiler/rustc_builtin_macros/src/deriving/bounds.rs +++ b/compiler/rustc_builtin_macros/src/deriving/bounds.rs @@ -1,10 +1,10 @@ -use crate::deriving::generic::*; -use crate::deriving::path_std; - use rustc_ast::MetaItem; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::Span; +use crate::deriving::generic::*; +use crate::deriving::path_std; + pub(crate) fn expand_deriving_copy( cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/clone.rs b/compiler/rustc_builtin_macros/src/deriving/clone.rs index abcb402a46f8e..22beca4ea9a06 100644 --- a/compiler/rustc_builtin_macros/src/deriving/clone.rs +++ b/compiler/rustc_builtin_macros/src/deriving/clone.rs @@ -1,6 +1,3 @@ -use crate::deriving::generic::ty::*; -use crate::deriving::generic::*; -use crate::deriving::path_std; use rustc_ast::{self as ast, Generics, ItemKind, MetaItem, VariantData}; use rustc_data_structures::fx::FxHashSet; use rustc_expand::base::{Annotatable, ExtCtxt}; @@ -8,6 +5,10 @@ use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; use thin_vec::{thin_vec, ThinVec}; +use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::path_std; + pub(crate) fn expand_deriving_clone( cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs index 53a1513160542..a5e1217479641 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs @@ -1,7 +1,3 @@ -use crate::deriving::generic::ty::*; -use crate::deriving::generic::*; -use crate::deriving::path_std; - use rustc_ast::{self as ast, MetaItem}; use rustc_data_structures::fx::FxHashSet; use rustc_expand::base::{Annotatable, ExtCtxt}; @@ -9,6 +5,10 @@ use rustc_span::symbol::sym; use rustc_span::Span; use thin_vec::{thin_vec, ThinVec}; +use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::path_std; + pub(crate) fn expand_deriving_eq( cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs index 8470d466a233c..705c41175e70f 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs @@ -1,12 +1,13 @@ -use crate::deriving::generic::ty::*; -use crate::deriving::generic::*; -use crate::deriving::path_std; use rustc_ast::MetaItem; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; use thin_vec::thin_vec; +use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::path_std; + pub(crate) fn expand_deriving_ord( cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs index a6457f4a433c4..f6299589e0f3e 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs @@ -1,6 +1,3 @@ -use crate::deriving::generic::ty::*; -use crate::deriving::generic::*; -use crate::deriving::{path_local, path_std}; use rustc_ast::ptr::P; use rustc_ast::{BinOpKind, BorrowKind, Expr, ExprKind, MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; @@ -8,6 +5,10 @@ use rustc_span::symbol::sym; use rustc_span::Span; use thin_vec::thin_vec; +use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::{path_local, path_std}; + pub(crate) fn expand_deriving_partial_eq( cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs index 006e5a3d268a6..a51f98f5396ce 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs @@ -1,12 +1,13 @@ -use crate::deriving::generic::ty::*; -use crate::deriving::generic::*; -use crate::deriving::{path_std, pathvec_std}; use rustc_ast::{ExprKind, ItemKind, MetaItem, PatKind}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; use thin_vec::thin_vec; +use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::{path_std, pathvec_std}; + pub(crate) fn expand_deriving_partial_ord( cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/debug.rs b/compiler/rustc_builtin_macros/src/deriving/debug.rs index 57ec0435e3e05..755e6ee0d3e08 100644 --- a/compiler/rustc_builtin_macros/src/deriving/debug.rs +++ b/compiler/rustc_builtin_macros/src/deriving/debug.rs @@ -1,13 +1,13 @@ -use crate::deriving::generic::ty::*; -use crate::deriving::generic::*; -use crate::deriving::path_std; - use rustc_ast::{self as ast, EnumDef, MetaItem}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; use thin_vec::{thin_vec, ThinVec}; +use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::path_std; + pub(crate) fn expand_deriving_debug( cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/decodable.rs b/compiler/rustc_builtin_macros/src/deriving/decodable.rs index e9851c87aeaef..89300a36d1b56 100644 --- a/compiler/rustc_builtin_macros/src/deriving/decodable.rs +++ b/compiler/rustc_builtin_macros/src/deriving/decodable.rs @@ -1,8 +1,5 @@ //! The compiler code necessary for `#[derive(RustcDecodable)]`. See encodable.rs for more. -use crate::deriving::generic::ty::*; -use crate::deriving::generic::*; -use crate::deriving::pathvec_std; use rustc_ast::ptr::P; use rustc_ast::{self as ast, Expr, MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; @@ -10,6 +7,10 @@ use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; use thin_vec::{thin_vec, ThinVec}; +use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::pathvec_std; + pub(crate) fn expand_deriving_rustc_decodable( cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/default.rs b/compiler/rustc_builtin_macros/src/deriving/default.rs index 7a65ed97f00c2..afc55ddd2302e 100644 --- a/compiler/rustc_builtin_macros/src/deriving/default.rs +++ b/compiler/rustc_builtin_macros/src/deriving/default.rs @@ -1,17 +1,18 @@ -use crate::deriving::generic::ty::*; -use crate::deriving::generic::*; -use crate::errors; use core::ops::ControlFlow; + use rustc_ast as ast; use rustc_ast::visit::visit_opt; use rustc_ast::{attr, EnumDef, VariantData}; use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt}; -use rustc_span::symbol::Ident; -use rustc_span::symbol::{kw, sym}; +use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{ErrorGuaranteed, Span}; use smallvec::SmallVec; use thin_vec::{thin_vec, ThinVec}; +use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::errors; + pub(crate) fn expand_deriving_default( cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/encodable.rs b/compiler/rustc_builtin_macros/src/deriving/encodable.rs index 3bd74d8d0198a..9c26d05f811d1 100644 --- a/compiler/rustc_builtin_macros/src/deriving/encodable.rs +++ b/compiler/rustc_builtin_macros/src/deriving/encodable.rs @@ -85,15 +85,16 @@ //! } //! ``` -use crate::deriving::generic::ty::*; -use crate::deriving::generic::*; -use crate::deriving::pathvec_std; use rustc_ast::{AttrVec, ExprKind, MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; use thin_vec::{thin_vec, ThinVec}; +use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::pathvec_std; + pub(crate) fn expand_deriving_rustc_encodable( cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index ba289f9552e22..c8ab8ed681c15 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -174,26 +174,25 @@ //! ) //! ``` -pub(crate) use StaticFields::*; -pub(crate) use SubstructureFields::*; +use std::cell::RefCell; +use std::ops::Not; +use std::{iter, vec}; -use crate::{deriving, errors}; use rustc_ast::ptr::P; use rustc_ast::{ self as ast, BindingMode, ByRef, EnumDef, Expr, GenericArg, GenericParamKind, Generics, - Mutability, PatKind, TyKind, VariantData, + Mutability, PatKind, VariantData, }; use rustc_attr as attr; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_session::lint::builtin::BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; -use std::cell::RefCell; -use std::iter; -use std::ops::Not; -use std::vec; use thin_vec::{thin_vec, ThinVec}; use ty::{Bounds, Path, Ref, Self_, Ty}; +pub(crate) use StaticFields::*; +pub(crate) use SubstructureFields::*; + +use crate::{deriving, errors}; pub(crate) mod ty; @@ -1599,52 +1598,11 @@ impl<'a> TraitDef<'a> { ), ); if is_packed { - // In general, fields in packed structs are copied via a - // block, e.g. `&{self.0}`. The two exceptions are `[u8]` - // and `str` fields, which cannot be copied and also never - // cause unaligned references. These exceptions are allowed - // to handle the `FlexZeroSlice` type in the `zerovec` - // crate within `icu4x-0.9.0`. - // - // Once use of `icu4x-0.9.0` has dropped sufficiently, this - // exception should be removed. - let is_simple_path = |ty: &P, sym| { - if let TyKind::Path(None, ast::Path { segments, .. }) = &ty.kind - && let [seg] = segments.as_slice() - && seg.ident.name == sym - && seg.args.is_none() - { - true - } else { - false - } - }; - - let exception = if let TyKind::Slice(ty) = &struct_field.ty.kind - && is_simple_path(ty, sym::u8) - { - Some("byte") - } else if is_simple_path(&struct_field.ty, sym::str) { - Some("string") - } else { - None - }; - - if let Some(ty) = exception { - cx.sess.psess.buffer_lint( - BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE, - sp, - ast::CRATE_NODE_ID, - rustc_lint_defs::BuiltinLintDiag::ByteSliceInPackedStructWithDerive { - ty: ty.to_string(), - }, - ); - } else { - // Wrap the expression in `{...}`, causing a copy. - field_expr = cx.expr_block( - cx.block(struct_field.span, thin_vec![cx.stmt_expr(field_expr)]), - ); - } + // Fields in packed structs are wrapped in a block, e.g. `&{self.0}`, + // causing a copy instead of a (potentially misaligned) reference. + field_expr = cx.expr_block( + cx.block(struct_field.span, thin_vec![cx.stmt_expr(field_expr)]), + ); } cx.expr_addr_of(sp, field_expr) }) diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs index f01d586033e09..747da2ee43bdf 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs @@ -1,8 +1,6 @@ //! A mini version of ast::Ty, which is easier to use, and features an explicit `Self` type to use //! when specifying impls to be derived. -pub(crate) use Ty::*; - use rustc_ast::ptr::P; use rustc_ast::{self as ast, Expr, GenericArg, GenericParamKind, Generics, SelfKind}; use rustc_expand::base::ExtCtxt; @@ -10,6 +8,7 @@ use rustc_span::source_map::respan; use rustc_span::symbol::{kw, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; use thin_vec::ThinVec; +pub(crate) use Ty::*; /// A path, e.g., `::std::option::Option::` (global). Has support /// for type parameters. diff --git a/compiler/rustc_builtin_macros/src/deriving/hash.rs b/compiler/rustc_builtin_macros/src/deriving/hash.rs index dcd9281986511..4fa6686b7b34b 100644 --- a/compiler/rustc_builtin_macros/src/deriving/hash.rs +++ b/compiler/rustc_builtin_macros/src/deriving/hash.rs @@ -1,12 +1,13 @@ -use crate::deriving::generic::ty::*; -use crate::deriving::generic::*; -use crate::deriving::{path_std, pathvec_std}; use rustc_ast::{MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::sym; use rustc_span::Span; use thin_vec::thin_vec; +use crate::deriving::generic::ty::*; +use crate::deriving::generic::*; +use crate::deriving::{path_std, pathvec_std}; + pub(crate) fn expand_deriving_hash( cx: &ExtCtxt<'_>, span: Span, diff --git a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs b/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs index bbc7cd3962720..7eb1f17a59ce3 100644 --- a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs +++ b/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs @@ -1,14 +1,16 @@ -use std::mem::swap; - +use ast::ptr::P; use ast::HasAttrs; +use rustc_ast::mut_visit::MutVisitor; +use rustc_ast::visit::BoundKind; use rustc_ast::{ self as ast, GenericArg, GenericBound, GenericParamKind, ItemKind, MetaItem, - TraitBoundModifiers, VariantData, + TraitBoundModifiers, VariantData, WherePredicate, }; use rustc_attr as attr; +use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident}; -use rustc_span::Span; +use rustc_span::{Span, Symbol}; use smallvec::{smallvec, SmallVec}; use thin_vec::{thin_vec, ThinVec}; @@ -141,33 +143,237 @@ pub fn expand_deriving_smart_ptr( alt_self_params[pointee_param_idx] = GenericArg::Type(s_ty.clone()); let alt_self_type = cx.ty_path(cx.path_all(span, false, vec![name_ident], alt_self_params)); + // # Add `Unsize<__S>` bound to `#[pointee]` at the generic parameter location + // // Find the `#[pointee]` parameter and add an `Unsize<__S>` bound to it. let mut impl_generics = generics.clone(); + let pointee_ty_ident = generics.params[pointee_param_idx].ident; + let mut self_bounds; { - let p = &mut impl_generics.params[pointee_param_idx]; + let pointee = &mut impl_generics.params[pointee_param_idx]; + self_bounds = pointee.bounds.clone(); + if !contains_maybe_sized_bound(&self_bounds) + && !contains_maybe_sized_bound_on_pointee( + &generics.where_clause.predicates, + pointee_ty_ident.name, + ) + { + cx.dcx() + .struct_span_err( + pointee_ty_ident.span, + format!( + "`derive(SmartPointer)` requires {} to be marked `?Sized`", + pointee_ty_ident.name + ), + ) + .emit(); + return; + } let arg = GenericArg::Type(s_ty.clone()); let unsize = cx.path_all(span, true, path!(span, core::marker::Unsize), vec![arg]); - p.bounds.push(cx.trait_bound(unsize, false)); - let mut attrs = thin_vec![]; - swap(&mut p.attrs, &mut attrs); - p.attrs = attrs.into_iter().filter(|attr| !attr.has_name(sym::pointee)).collect(); + pointee.bounds.push(cx.trait_bound(unsize, false)); + // Drop `#[pointee]` attribute since it should not be recognized outside `derive(SmartPointer)` + pointee.attrs.retain(|attr| !attr.has_name(sym::pointee)); + } + + // # Rewrite generic parameter bounds + // For each bound `U: ..` in `struct`, make a new bound with `__S` in place of `#[pointee]` + // Example: + // ``` + // struct< + // U: Trait, + // #[pointee] T: Trait + ?Sized, + // V: Trait> ... + // ``` + // ... generates this `impl` generic parameters + // ``` + // impl< + // U: Trait + Trait<__S>, + // T: Trait + ?Sized + Unsize<__S>, // (**) + // __S: Trait<__S> + ?Sized, // (*) + // V: Trait + Trait<__S>> ... + // ``` + // The new bound marked with (*) has to be done separately. + // See next section + for (idx, (params, orig_params)) in + impl_generics.params.iter_mut().zip(&generics.params).enumerate() + { + // Default type parameters are rejected for `impl` block. + // We should drop them now. + match &mut params.kind { + ast::GenericParamKind::Const { default, .. } => *default = None, + ast::GenericParamKind::Type { default } => *default = None, + ast::GenericParamKind::Lifetime => {} + } + // We CANNOT rewrite `#[pointee]` type parameter bounds. + // This has been set in stone. (**) + // So we skip over it. + // Otherwise, we push extra bounds involving `__S`. + if idx != pointee_param_idx { + for bound in &orig_params.bounds { + let mut bound = bound.clone(); + let mut substitution = TypeSubstitution { + from_name: pointee_ty_ident.name, + to_ty: &s_ty, + rewritten: false, + }; + substitution.visit_param_bound(&mut bound, BoundKind::Bound); + if substitution.rewritten { + // We found use of `#[pointee]` somewhere, + // so we make a new bound using `__S` in place of `#[pointee]` + params.bounds.push(bound); + } + } + } + } + + // # Insert `__S` type parameter + // + // We now insert `__S` with the missing bounds marked with (*) above. + // We should also write the bounds from `#[pointee]` to `__S` as required by `Unsize<__S>`. + { + let mut substitution = + TypeSubstitution { from_name: pointee_ty_ident.name, to_ty: &s_ty, rewritten: false }; + for bound in &mut self_bounds { + substitution.visit_param_bound(bound, BoundKind::Bound); + } + } + + // # Rewrite `where` clauses + // + // Move on to `where` clauses. + // Example: + // ``` + // struct MyPointer<#[pointee] T, ..> + // where + // U: Trait + Trait, + // Companion: Trait, + // T: Trait + ?Sized, + // { .. } + // ``` + // ... will have a impl prelude like so + // ``` + // impl<..> .. + // where + // U: Trait + Trait, + // U: Trait<__S>, + // Companion: Trait, + // Companion<__S>: Trait<__S>, + // T: Trait + ?Sized, + // __S: Trait<__S> + ?Sized, + // ``` + // + // We should also write a few new `where` bounds from `#[pointee] T` to `__S` + // as well as any bound that indirectly involves the `#[pointee] T` type. + for bound in &generics.where_clause.predicates { + if let ast::WherePredicate::BoundPredicate(bound) = bound { + let mut substitution = TypeSubstitution { + from_name: pointee_ty_ident.name, + to_ty: &s_ty, + rewritten: false, + }; + let mut predicate = ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { + span: bound.span, + bound_generic_params: bound.bound_generic_params.clone(), + bounded_ty: bound.bounded_ty.clone(), + bounds: bound.bounds.clone(), + }); + substitution.visit_where_predicate(&mut predicate); + if substitution.rewritten { + impl_generics.where_clause.predicates.push(predicate); + } + } } - // Add the `__S: ?Sized` extra parameter to the impl block. - let sized = cx.path_global(span, path!(span, core::marker::Sized)); - let bound = GenericBound::Trait( - cx.poly_trait_ref(span, sized), - TraitBoundModifiers { - polarity: ast::BoundPolarity::Maybe(span), - constness: ast::BoundConstness::Never, - asyncness: ast::BoundAsyncness::Normal, - }, - ); - let extra_param = cx.typaram(span, Ident::new(sym::__S, span), vec![bound], None); - impl_generics.params.push(extra_param); + let extra_param = cx.typaram(span, Ident::new(sym::__S, span), self_bounds, None); + impl_generics.params.insert(pointee_param_idx + 1, extra_param); // Add the impl blocks for `DispatchFromDyn` and `CoerceUnsized`. let gen_args = vec![GenericArg::Type(alt_self_type.clone())]; add_impl_block(impl_generics.clone(), sym::DispatchFromDyn, gen_args.clone()); add_impl_block(impl_generics.clone(), sym::CoerceUnsized, gen_args.clone()); } + +fn contains_maybe_sized_bound_on_pointee(predicates: &[WherePredicate], pointee: Symbol) -> bool { + for bound in predicates { + if let ast::WherePredicate::BoundPredicate(bound) = bound + && bound.bounded_ty.kind.is_simple_path().is_some_and(|name| name == pointee) + { + for bound in &bound.bounds { + if is_maybe_sized_bound(bound) { + return true; + } + } + } + } + false +} + +fn is_maybe_sized_bound(bound: &GenericBound) -> bool { + if let GenericBound::Trait( + trait_ref, + TraitBoundModifiers { polarity: ast::BoundPolarity::Maybe(_), .. }, + ) = bound + { + is_sized_marker(&trait_ref.trait_ref.path) + } else { + false + } +} + +fn contains_maybe_sized_bound(bounds: &[GenericBound]) -> bool { + bounds.iter().any(is_maybe_sized_bound) +} + +fn path_segment_is_exact_match(path_segments: &[ast::PathSegment], syms: &[Symbol]) -> bool { + path_segments.iter().zip(syms).all(|(segment, &symbol)| segment.ident.name == symbol) +} + +fn is_sized_marker(path: &ast::Path) -> bool { + const CORE_UNSIZE: [Symbol; 3] = [sym::core, sym::marker, sym::Sized]; + const STD_UNSIZE: [Symbol; 3] = [sym::std, sym::marker, sym::Sized]; + if path.segments.len() == 4 && path.is_global() { + path_segment_is_exact_match(&path.segments[1..], &CORE_UNSIZE) + || path_segment_is_exact_match(&path.segments[1..], &STD_UNSIZE) + } else if path.segments.len() == 3 { + path_segment_is_exact_match(&path.segments, &CORE_UNSIZE) + || path_segment_is_exact_match(&path.segments, &STD_UNSIZE) + } else { + *path == sym::Sized + } +} + +struct TypeSubstitution<'a> { + from_name: Symbol, + to_ty: &'a ast::Ty, + rewritten: bool, +} + +impl<'a> ast::mut_visit::MutVisitor for TypeSubstitution<'a> { + fn visit_ty(&mut self, ty: &mut P) { + if let Some(name) = ty.kind.is_simple_path() + && name == self.from_name + { + **ty = self.to_ty.clone(); + self.rewritten = true; + } else { + ast::mut_visit::walk_ty(self, ty); + } + } + + fn visit_where_predicate(&mut self, where_predicate: &mut ast::WherePredicate) { + match where_predicate { + rustc_ast::WherePredicate::BoundPredicate(bound) => { + bound + .bound_generic_params + .flat_map_in_place(|param| self.flat_map_generic_param(param)); + self.visit_ty(&mut bound.bounded_ty); + for bound in &mut bound.bounds { + self.visit_param_bound(bound, BoundKind::Bound) + } + } + rustc_ast::WherePredicate::RegionPredicate(_) + | rustc_ast::WherePredicate::EqPredicate(_) => {} + } + } +} diff --git a/compiler/rustc_builtin_macros/src/env.rs b/compiler/rustc_builtin_macros/src/env.rs index b03e14cf2630d..1a4fc65f0a8a6 100644 --- a/compiler/rustc_builtin_macros/src/env.rs +++ b/compiler/rustc_builtin_macros/src/env.rs @@ -3,18 +3,20 @@ // interface. // -use crate::errors; -use crate::util::{expr_to_string, get_exprs_from_tts, get_single_str_from_tts}; +use std::env; +use std::env::VarError; + use rustc_ast::token::{self, LitKind}; use rustc_ast::tokenstream::TokenStream; use rustc_ast::{AstDeref, ExprKind, GenericArg, Mutability}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; -use std::env; -use std::env::VarError; use thin_vec::thin_vec; +use crate::errors; +use crate::util::{expr_to_string, get_exprs_from_tts, get_single_str_from_tts}; + fn lookup_env<'cx>(cx: &'cx ExtCtxt<'_>, var: Symbol) -> Result { let var = var.as_str(); if let Some(value) = cx.sess.opts.logical_env.get(var) { diff --git a/compiler/rustc_builtin_macros/src/errors.rs b/compiler/rustc_builtin_macros/src/errors.rs index 49d640436c2f3..6ca43441e0582 100644 --- a/compiler/rustc_builtin_macros/src/errors.rs +++ b/compiler/rustc_builtin_macros/src/errors.rs @@ -1,9 +1,11 @@ +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, MultiSpan, - SingleLabelManySpans, SubdiagMessageOp, Subdiagnostic, + Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, MultiSpan, SingleLabelManySpans, + SubdiagMessageOp, Subdiagnostic, }; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_span::{symbol::Ident, Span, Symbol}; +use rustc_span::symbol::Ident; +use rustc_span::{Span, Symbol}; #[derive(Diagnostic)] #[diag(builtin_macros_requires_cfg_pattern)] @@ -295,13 +297,6 @@ pub(crate) struct DerivePathArgsValue { pub(crate) span: Span, } -#[derive(Diagnostic)] -#[diag(builtin_macros_derive_unsafe_path)] -pub(crate) struct DeriveUnsafePath { - #[primary_span] - pub(crate) span: Span, -} - #[derive(Diagnostic)] #[diag(builtin_macros_no_default_variant)] #[help] @@ -845,6 +840,26 @@ pub(crate) struct AsmOptAlreadyprovided { pub(crate) full_span: Span, } +#[derive(Diagnostic)] +#[diag(builtin_macros_global_asm_unsupported_option)] +pub(crate) struct GlobalAsmUnsupportedOption { + #[primary_span] + #[label] + pub(crate) span: Span, + pub(crate) symbol: Symbol, + #[suggestion(code = "", applicability = "machine-applicable", style = "tool-only")] + pub(crate) full_span: Span, +} + +#[derive(Diagnostic)] +#[diag(builtin_macros_global_asm_unsupported_operand)] +pub(crate) struct GlobalAsmUnsupportedOperand<'a> { + #[primary_span] + #[label] + pub(crate) span: Span, + pub(crate) symbol: &'a str, +} + #[derive(Diagnostic)] #[diag(builtin_macros_test_runner_invalid)] pub(crate) struct TestRunnerInvalid { @@ -912,3 +927,13 @@ pub(crate) struct ExpectedItem<'a> { pub span: Span, pub token: &'a str, } + +#[derive(Diagnostic)] +#[diag(builtin_macros_naked_functions_testing_attribute, code = E0736)] +pub struct NakedFunctionTestingAttribute { + #[primary_span] + #[label(builtin_macros_naked_attribute)] + pub naked_span: Span, + #[label] + pub testing_span: Span, +} diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index 5cb0407bd59e6..9c70f7ede8c7e 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -1,13 +1,10 @@ -use crate::errors; -use crate::util::expr_to_spanned_string; use parse::Position::ArgumentNamed; use rustc_ast::ptr::P; use rustc_ast::tokenstream::TokenStream; -use rustc_ast::{token, StmtKind}; use rustc_ast::{ - Expr, ExprKind, FormatAlignment, FormatArgPosition, FormatArgPositionKind, FormatArgs, + token, Expr, ExprKind, FormatAlignment, FormatArgPosition, FormatArgPositionKind, FormatArgs, FormatArgsPiece, FormatArgument, FormatArgumentKind, FormatArguments, FormatCount, - FormatDebugHex, FormatOptions, FormatPlaceholder, FormatSign, FormatTrait, Recovered, + FormatDebugHex, FormatOptions, FormatPlaceholder, FormatSign, FormatTrait, Recovered, StmtKind, }; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{Applicability, Diag, MultiSpan, PResult, SingleLabelManySpans}; @@ -18,6 +15,9 @@ use rustc_parse_format as parse; use rustc_span::symbol::{Ident, Symbol}; use rustc_span::{BytePos, ErrorGuaranteed, InnerSpan, Span}; +use crate::errors; +use crate::util::expr_to_spanned_string; + // The format_args!() macro is expanded in three steps: // 1. First, `parse_args` will parse the `(literal, arg, arg, name=arg, name=arg)` syntax, // but doesn't parse the template (the literal) itself. diff --git a/compiler/rustc_builtin_macros/src/format_foreign.rs b/compiler/rustc_builtin_macros/src/format_foreign.rs index bc2c6def68a9b..b52f606f342e2 100644 --- a/compiler/rustc_builtin_macros/src/format_foreign.rs +++ b/compiler/rustc_builtin_macros/src/format_foreign.rs @@ -1,7 +1,8 @@ pub(crate) mod printf { - use super::strcursor::StrCursor as Cur; use rustc_span::InnerSpan; + use super::strcursor::StrCursor as Cur; + /// Represents a single `printf`-style substitution. #[derive(Clone, PartialEq, Debug)] pub enum Substitution<'a> { @@ -615,9 +616,10 @@ pub(crate) mod printf { } pub mod shell { - use super::strcursor::StrCursor as Cur; use rustc_span::InnerSpan; + use super::strcursor::StrCursor as Cur; + #[derive(Clone, PartialEq, Debug)] pub enum Substitution<'a> { Ordinal(u8, (usize, usize)), diff --git a/compiler/rustc_builtin_macros/src/global_allocator.rs b/compiler/rustc_builtin_macros/src/global_allocator.rs index b44ff979303d1..734da318ac1bb 100644 --- a/compiler/rustc_builtin_macros/src/global_allocator.rs +++ b/compiler/rustc_builtin_macros/src/global_allocator.rs @@ -1,17 +1,19 @@ -use crate::util::check_builtin_macro_attribute; - -use crate::errors; use rustc_ast::expand::allocator::{ global_fn_name, AllocatorMethod, AllocatorMethodInput, AllocatorTy, ALLOCATOR_METHODS, }; use rustc_ast::ptr::P; -use rustc_ast::{self as ast, AttrVec, Expr, FnHeader, FnSig, Generics, Param, StmtKind}; -use rustc_ast::{Fn, ItemKind, Mutability, Safety, Stmt, Ty, TyKind}; +use rustc_ast::{ + self as ast, AttrVec, Expr, Fn, FnHeader, FnSig, Generics, ItemKind, Mutability, Param, Safety, + Stmt, StmtKind, Ty, TyKind, +}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; use thin_vec::{thin_vec, ThinVec}; +use crate::errors; +use crate::util::check_builtin_macro_attribute; + pub(crate) fn expand( ecx: &mut ExtCtxt<'_>, _span: Span, diff --git a/compiler/rustc_builtin_macros/src/lib.rs b/compiler/rustc_builtin_macros/src/lib.rs index c77ff9eb13cdc..a9ba7334d930e 100644 --- a/compiler/rustc_builtin_macros/src/lib.rs +++ b/compiler/rustc_builtin_macros/src/lib.rs @@ -5,7 +5,6 @@ #![allow(internal_features)] #![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::untranslatable_diagnostic)] -#![cfg_attr(bootstrap, feature(lint_reasons))] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![doc(rust_logo)] #![feature(assert_matches)] @@ -21,11 +20,12 @@ extern crate proc_macro; -use crate::deriving::*; use rustc_expand::base::{MacroExpanderFn, ResolverExpand, SyntaxExtensionKind}; use rustc_expand::proc_macro::BangProcMacro; use rustc_span::symbol::sym; +use crate::deriving::*; + mod alloc_error_handler; mod assert; mod cfg; diff --git a/compiler/rustc_builtin_macros/src/pattern_type.rs b/compiler/rustc_builtin_macros/src/pattern_type.rs index 31f5656df135e..869d203f68eba 100644 --- a/compiler/rustc_builtin_macros/src/pattern_type.rs +++ b/compiler/rustc_builtin_macros/src/pattern_type.rs @@ -1,4 +1,6 @@ -use rustc_ast::{ast, ptr::P, tokenstream::TokenStream, Pat, Ty}; +use rustc_ast::ptr::P; +use rustc_ast::tokenstream::TokenStream; +use rustc_ast::{ast, Pat, Ty}; use rustc_errors::PResult; use rustc_expand::base::{self, DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; use rustc_span::{sym, Span}; @@ -22,7 +24,7 @@ fn parse_pat_ty<'a>(cx: &mut ExtCtxt<'a>, stream: TokenStream) -> PResult<'a, (P let mut parser = cx.new_parser_from_tts(stream); let ty = parser.parse_ty()?; - parser.eat_keyword(sym::is); + parser.expect_keyword(sym::is)?; let pat = parser.parse_pat_no_top_alt(None, None)?; Ok((ty, pat)) diff --git a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs index a8a595ea5796f..6b2b2b90457c5 100644 --- a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs +++ b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs @@ -1,4 +1,5 @@ -use crate::errors; +use std::mem; + use rustc_ast::ptr::P; use rustc_ast::visit::{self, Visitor}; use rustc_ast::{self as ast, attr, NodeId}; @@ -13,9 +14,10 @@ use rustc_span::source_map::SourceMap; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; use smallvec::smallvec; -use std::mem; use thin_vec::{thin_vec, ThinVec}; +use crate::errors; + struct ProcMacroDerive { id: NodeId, trait_name: Symbol, diff --git a/compiler/rustc_builtin_macros/src/source_util.rs b/compiler/rustc_builtin_macros/src/source_util.rs index 44db12cf69502..9554d97829e21 100644 --- a/compiler/rustc_builtin_macros/src/source_util.rs +++ b/compiler/rustc_builtin_macros/src/source_util.rs @@ -1,7 +1,6 @@ -use crate::errors; -use crate::util::{ - check_zero_tts, get_single_str_from_tts, get_single_str_spanned_from_tts, parse_expr, -}; +use std::path::{Path, PathBuf}; +use std::rc::Rc; + use rustc_ast as ast; use rustc_ast::ptr::P; use rustc_ast::token; @@ -20,8 +19,11 @@ use rustc_span::source_map::SourceMap; use rustc_span::symbol::Symbol; use rustc_span::{Pos, Span}; use smallvec::SmallVec; -use std::path::{Path, PathBuf}; -use std::rc::Rc; + +use crate::errors; +use crate::util::{ + check_zero_tts, get_single_str_from_tts, get_single_str_spanned_from_tts, parse_expr, +}; // These macros all relate to the file system; they either return // the column/row/filename of the expression, or they include @@ -71,7 +73,8 @@ pub(crate) fn expand_file( let topmost = cx.expansion_cause().unwrap_or(sp); let loc = cx.source_map().lookup_char_pos(topmost.lo()); - use rustc_session::{config::RemapPathScopeComponents, RemapFileNameExt}; + use rustc_session::config::RemapPathScopeComponents; + use rustc_session::RemapFileNameExt; ExpandResult::Ready(MacEager::expr(cx.expr_str( topmost, Symbol::intern( diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index c0310a2f4b003..1b76a5f3234a2 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -1,8 +1,9 @@ //! The expansion from a test function to the appropriate test struct for libtest //! Ideally, this code would be in libtest but for efficiency and error messages it lives here. -use crate::errors; -use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute}; +use std::assert_matches::assert_matches; +use std::iter; + use rustc_ast::ptr::P; use rustc_ast::{self as ast, attr, GenericParamKind}; use rustc_ast_pretty::pprust; @@ -10,11 +11,12 @@ use rustc_errors::{Applicability, Diag, Level}; use rustc_expand::base::*; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::{ErrorGuaranteed, FileNameDisplayPreference, Span}; -use std::assert_matches::assert_matches; -use std::iter; use thin_vec::{thin_vec, ThinVec}; use tracing::debug; +use crate::errors; +use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute}; + /// #[test_case] is used by custom test authors to mark tests /// When building for test, it needs to make the item public and gensym the name /// Otherwise, we'll omit the item. This behavior means that any item annotated @@ -133,6 +135,14 @@ pub(crate) fn expand_test_or_bench( }; }; + if let Some(attr) = attr::find_by_name(&item.attrs, sym::naked) { + cx.dcx().emit_err(errors::NakedFunctionTestingAttribute { + testing_span: attr_sp, + naked_span: attr.span, + }); + return vec![Annotatable::Item(item)]; + } + // check_*_signature will report any errors in the type so compilation // will fail. We shouldn't try to expand in this case because the errors // would be spurious. diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index bbafb0ac299c6..a9e4434581163 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -1,5 +1,7 @@ // Code that generates a test runner to run all the tests in a crate +use std::{iter, mem}; + use rustc_ast as ast; use rustc_ast::entry::EntryPointType; use rustc_ast::mut_visit::*; @@ -21,8 +23,6 @@ use smallvec::{smallvec, SmallVec}; use thin_vec::{thin_vec, ThinVec}; use tracing::debug; -use std::{iter, mem}; - use crate::errors; #[derive(Clone)] diff --git a/compiler/rustc_builtin_macros/src/trace_macros.rs b/compiler/rustc_builtin_macros/src/trace_macros.rs index 4833ec32f76e1..bd9ebc355e158 100644 --- a/compiler/rustc_builtin_macros/src/trace_macros.rs +++ b/compiler/rustc_builtin_macros/src/trace_macros.rs @@ -1,9 +1,10 @@ -use crate::errors; use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; use rustc_span::symbol::kw; use rustc_span::Span; +use crate::errors; + pub(crate) fn expand_trace_macros( cx: &mut ExtCtxt<'_>, sp: Span, diff --git a/compiler/rustc_builtin_macros/src/util.rs b/compiler/rustc_builtin_macros/src/util.rs index fabcb6a4b7068..73cc8ff547d51 100644 --- a/compiler/rustc_builtin_macros/src/util.rs +++ b/compiler/rustc_builtin_macros/src/util.rs @@ -1,24 +1,29 @@ -use crate::errors; +use rustc_ast::ptr::P; use rustc_ast::tokenstream::TokenStream; -use rustc_ast::{self as ast, attr, ptr::P, token, AttrStyle, Attribute, MetaItem}; +use rustc_ast::{self as ast, attr, token, AttrStyle, Attribute, MetaItem}; use rustc_errors::{Applicability, Diag, ErrorGuaranteed}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt}; use rustc_expand::expand::AstFragment; use rustc_feature::AttributeTemplate; -use rustc_lint_defs::{builtin::DUPLICATE_MACRO_ATTRIBUTES, BuiltinLintDiag}; +use rustc_lint_defs::builtin::DUPLICATE_MACRO_ATTRIBUTES; +use rustc_lint_defs::BuiltinLintDiag; use rustc_parse::{parser, validate_attr}; use rustc_session::errors::report_lit_error; use rustc_span::{BytePos, Span, Symbol}; +use crate::errors; + pub(crate) fn check_builtin_macro_attribute(ecx: &ExtCtxt<'_>, meta_item: &MetaItem, name: Symbol) { // All the built-in macro attributes are "words" at the moment. let template = AttributeTemplate { word: true, ..Default::default() }; validate_attr::check_builtin_meta_item( + &ecx.ecfg.features, &ecx.sess.psess, meta_item, AttrStyle::Outer, name, template, + true, ); } diff --git a/compiler/rustc_codegen_cranelift/build_system/abi_cafe.rs b/compiler/rustc_codegen_cranelift/build_system/abi_cafe.rs index ecf303c30b6c3..75f9f233cb33d 100644 --- a/compiler/rustc_codegen_cranelift/build_system/abi_cafe.rs +++ b/compiler/rustc_codegen_cranelift/build_system/abi_cafe.rs @@ -1,8 +1,7 @@ -use crate::build_sysroot; use crate::path::Dirs; use crate::prepare::GitRepo; use crate::utils::{spawn_and_wait, CargoProject, Compiler}; -use crate::{CodegenBackend, SysrootKind}; +use crate::{build_sysroot, CodegenBackend, SysrootKind}; static ABI_CAFE_REPO: GitRepo = GitRepo::github( "Gankra", diff --git a/compiler/rustc_codegen_cranelift/build_system/build_sysroot.rs b/compiler/rustc_codegen_cranelift/build_system/build_sysroot.rs index dfbe0f51e7be2..ed8b5b906d28f 100644 --- a/compiler/rustc_codegen_cranelift/build_system/build_sysroot.rs +++ b/compiler/rustc_codegen_cranelift/build_system/build_sysroot.rs @@ -1,7 +1,6 @@ -use std::env; -use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; +use std::{env, fs}; use crate::path::{Dirs, RelPath}; use crate::rustc_info::get_file_name; @@ -272,7 +271,7 @@ fn build_clif_sysroot_for_triple( if channel == "release" { build_cmd.arg("--release"); } - build_cmd.arg("--features").arg("backtrace panic-unwind"); + build_cmd.arg("--features").arg("backtrace panic-unwind compiler-builtins-no-f16-f128"); build_cmd.env("CARGO_PROFILE_RELEASE_DEBUG", "true"); build_cmd.env("__CARGO_DEFAULT_LIB_METADATA", "cg_clif"); if compiler.triple.contains("apple") { diff --git a/compiler/rustc_codegen_cranelift/build_system/config.rs b/compiler/rustc_codegen_cranelift/build_system/config.rs index c31784e1097dc..ef540cf1f822b 100644 --- a/compiler/rustc_codegen_cranelift/build_system/config.rs +++ b/compiler/rustc_codegen_cranelift/build_system/config.rs @@ -1,5 +1,4 @@ -use std::fs; -use std::process; +use std::{fs, process}; fn load_config_file() -> Vec<(String, Option)> { fs::read_to_string("config.txt") diff --git a/compiler/rustc_codegen_cranelift/build_system/main.rs b/compiler/rustc_codegen_cranelift/build_system/main.rs index 7dbf608f991e4..9ddeda583afd1 100644 --- a/compiler/rustc_codegen_cranelift/build_system/main.rs +++ b/compiler/rustc_codegen_cranelift/build_system/main.rs @@ -2,9 +2,8 @@ #![warn(unused_lifetimes)] #![warn(unreachable_pub)] -use std::env; use std::path::PathBuf; -use std::process; +use std::{env, process}; use self::utils::Compiler; diff --git a/compiler/rustc_codegen_cranelift/build_system/tests.rs b/compiler/rustc_codegen_cranelift/build_system/tests.rs index 790d9cbd9fc59..afc8a923863a2 100644 --- a/compiler/rustc_codegen_cranelift/build_system/tests.rs +++ b/compiler/rustc_codegen_cranelift/build_system/tests.rs @@ -3,14 +3,12 @@ use std::fs; use std::path::PathBuf; use std::process::Command; -use crate::build_sysroot; -use crate::config; use crate::path::{Dirs, RelPath}; use crate::prepare::{apply_patches, GitRepo}; use crate::rustc_info::get_default_sysroot; use crate::shared_utils::rustflags_from_env; use crate::utils::{spawn_and_wait, CargoProject, Compiler, LogGroup}; -use crate::{CodegenBackend, SysrootKind}; +use crate::{build_sysroot, config, CodegenBackend, SysrootKind}; static BUILD_EXAMPLE_OUT_DIR: RelPath = RelPath::BUILD.join("example"); diff --git a/compiler/rustc_codegen_cranelift/build_system/utils.rs b/compiler/rustc_codegen_cranelift/build_system/utils.rs index 9f95122b341c5..3c4b45e02cc25 100644 --- a/compiler/rustc_codegen_cranelift/build_system/utils.rs +++ b/compiler/rustc_codegen_cranelift/build_system/utils.rs @@ -1,9 +1,7 @@ -use std::env; -use std::fs; -use std::io; use std::path::{Path, PathBuf}; use std::process::{self, Command}; use std::sync::atomic::{AtomicBool, Ordering}; +use std::{env, fs, io}; use crate::path::{Dirs, RelPath}; use crate::shared_utils::rustflags_to_cmd_env; diff --git a/compiler/rustc_codegen_cranelift/example/alloc_system.rs b/compiler/rustc_codegen_cranelift/example/alloc_system.rs index 441f3cd298743..2884c9c32ae4d 100644 --- a/compiler/rustc_codegen_cranelift/example/alloc_system.rs +++ b/compiler/rustc_codegen_cranelift/example/alloc_system.rs @@ -8,8 +8,7 @@ pub struct System; #[cfg(any(windows, unix, target_os = "redox"))] mod realloc_fallback { use core::alloc::{GlobalAlloc, Layout}; - use core::cmp; - use core::ptr; + use core::{cmp, ptr}; impl super::System { pub(crate) unsafe fn realloc_fallback( &self, @@ -34,6 +33,7 @@ mod platform { use core::alloc::{GlobalAlloc, Layout}; use core::ffi::c_void; use core::ptr; + use System; extern "C" { fn posix_memalign(memptr: *mut *mut c_void, align: usize, size: usize) -> i32; @@ -71,6 +71,7 @@ mod platform { #[allow(nonstandard_style)] mod platform { use core::alloc::{GlobalAlloc, Layout}; + use System; type LPVOID = *mut u8; type HANDLE = LPVOID; diff --git a/compiler/rustc_codegen_cranelift/example/arbitrary_self_types_pointers_and_wrappers.rs b/compiler/rustc_codegen_cranelift/example/arbitrary_self_types_pointers_and_wrappers.rs index f7edfa960a229..5479b0c617bfb 100644 --- a/compiler/rustc_codegen_cranelift/example/arbitrary_self_types_pointers_and_wrappers.rs +++ b/compiler/rustc_codegen_cranelift/example/arbitrary_self_types_pointers_and_wrappers.rs @@ -2,10 +2,8 @@ #![feature(arbitrary_self_types, unsize, coerce_unsized, dispatch_from_dyn)] -use std::{ - marker::Unsize, - ops::{CoerceUnsized, Deref, DispatchFromDyn}, -}; +use std::marker::Unsize; +use std::ops::{CoerceUnsized, Deref, DispatchFromDyn}; struct Ptr(Box); diff --git a/compiler/rustc_codegen_cranelift/example/std_example.rs b/compiler/rustc_codegen_cranelift/example/std_example.rs index 6cedd84adfe52..e99763e272233 100644 --- a/compiler/rustc_codegen_cranelift/example/std_example.rs +++ b/compiler/rustc_codegen_cranelift/example/std_example.rs @@ -3,7 +3,6 @@ coroutines, stmt_expr_attributes, coroutine_trait, - is_sorted, repr_simd, tuple_trait, unboxed_closures diff --git a/compiler/rustc_codegen_cranelift/rustfmt.toml b/compiler/rustc_codegen_cranelift/rustfmt.toml index 6f4d4413c25d0..d9e6ac3d543c9 100644 --- a/compiler/rustc_codegen_cranelift/rustfmt.toml +++ b/compiler/rustc_codegen_cranelift/rustfmt.toml @@ -6,3 +6,5 @@ ignore = [ version = "Two" use_small_heuristics = "Max" merge_derives = false +group_imports = "StdExternalCrate" +imports_granularity = "Module" diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs index eebd181341d08..ac7dd0bd46329 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs @@ -1,7 +1,8 @@ //! Unwind info generation (`.eh_frame`) use cranelift_codegen::ir::Endianness; -use cranelift_codegen::isa::{unwind::UnwindInfo, TargetIsa}; +use cranelift_codegen::isa::unwind::UnwindInfo; +use cranelift_codegen::isa::TargetIsa; use cranelift_object::ObjectProduct; use gimli::write::{CieId, EhFrame, FrameTable, Section}; use gimli::RunTimeEndian; diff --git a/compiler/rustc_codegen_cranelift/src/driver/aot.rs b/compiler/rustc_codegen_cranelift/src/driver/aot.rs index 763d9a484077e..b6fee1bf24a78 100644 --- a/compiler/rustc_codegen_cranelift/src/driver/aot.rs +++ b/compiler/rustc_codegen_cranelift/src/driver/aot.rs @@ -11,8 +11,9 @@ use rustc_codegen_ssa::assert_module_sources::CguReuse; use rustc_codegen_ssa::back::link::ensure_removed; use rustc_codegen_ssa::back::metadata::create_compressed_metadata_file; use rustc_codegen_ssa::base::determine_cgu_reuse; -use rustc_codegen_ssa::errors as ssa_errors; -use rustc_codegen_ssa::{CodegenResults, CompiledModule, CrateInfo, ModuleKind}; +use rustc_codegen_ssa::{ + errors as ssa_errors, CodegenResults, CompiledModule, CrateInfo, ModuleKind, +}; use rustc_data_structures::profiling::SelfProfilerRef; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::{par_map, IntoDynSyncSend}; @@ -26,8 +27,9 @@ use rustc_session::Session; use crate::concurrency_limiter::{ConcurrencyLimiter, ConcurrencyLimiterToken}; use crate::debuginfo::TypeDebugContext; use crate::global_asm::GlobalAsmConfig; +use crate::prelude::*; use crate::unwind_module::UnwindModule; -use crate::{prelude::*, BackendConfig}; +use crate::BackendConfig; struct ModuleCodegenResult { module_regular: CompiledModule, diff --git a/compiler/rustc_codegen_cranelift/src/driver/jit.rs b/compiler/rustc_codegen_cranelift/src/driver/jit.rs index dfee8e714e64a..12e860f676d05 100644 --- a/compiler/rustc_codegen_cranelift/src/driver/jit.rs +++ b/compiler/rustc_codegen_cranelift/src/driver/jit.rs @@ -14,9 +14,9 @@ use rustc_session::Session; use rustc_span::Symbol; use crate::debuginfo::TypeDebugContext; +use crate::prelude::*; use crate::unwind_module::UnwindModule; -use crate::{prelude::*, BackendConfig}; -use crate::{CodegenCx, CodegenMode}; +use crate::{BackendConfig, CodegenCx, CodegenMode}; struct JitState { jit_module: UnwindModule, diff --git a/compiler/rustc_codegen_cranelift/src/inline_asm.rs b/compiler/rustc_codegen_cranelift/src/inline_asm.rs index c88230c936056..16edec47e1029 100644 --- a/compiler/rustc_codegen_cranelift/src/inline_asm.rs +++ b/compiler/rustc_codegen_cranelift/src/inline_asm.rs @@ -46,9 +46,7 @@ pub(crate) fn codegen_inline_asm_terminator<'tcx>( // Used by panic_abort on Windows, but uses a syntax which only happens to work with // asm!() by accident and breaks with the GNU assembler as well as global_asm!() for // the LLVM backend. - if template.len() == 1 - && template[0] == InlineAsmTemplatePiece::String("int $$0x29".to_string()) - { + if template.len() == 1 && template[0] == InlineAsmTemplatePiece::String("int $$0x29".into()) { fx.bcx.ins().trap(TrapCode::User(1)); return; } diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs index e1896138e487b..a20faa2cad3a8 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs @@ -40,7 +40,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( shl rdx, 32 or rax, rdx " - .to_string(), + .into(), )], &[ CInlineAsmOperand::In { @@ -471,7 +471,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( // into 0x80000000 for which Cranelift doesn't have a native instruction. codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String(format!("cvtps2dq xmm0, xmm0"))], + &[InlineAsmTemplatePiece::String("cvtps2dq xmm0, xmm0".into())], &[CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm0)), _late: true, @@ -875,7 +875,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String(asm.to_string())], + &[InlineAsmTemplatePiece::String(asm.into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::ax)), @@ -914,7 +914,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String(format!("pcmpestri xmm0, xmm1, {imm8}"))], + &[InlineAsmTemplatePiece::String(format!("pcmpestri xmm0, xmm1, {imm8}").into())], &[ CInlineAsmOperand::In { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm0)), @@ -967,7 +967,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String(format!("pcmpestrm xmm0, xmm1, {imm8}"))], + &[InlineAsmTemplatePiece::String(format!("pcmpestrm xmm0, xmm1, {imm8}").into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm0)), @@ -1015,7 +1015,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String(format!("pclmulqdq xmm0, xmm1, {imm8}"))], + &[InlineAsmTemplatePiece::String(format!("pclmulqdq xmm0, xmm1, {imm8}").into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm0)), @@ -1052,7 +1052,9 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String(format!("aeskeygenassist xmm0, xmm0, {imm8}"))], + &[InlineAsmTemplatePiece::String( + format!("aeskeygenassist xmm0, xmm0, {imm8}").into(), + )], &[CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm0)), _late: true, @@ -1071,7 +1073,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("aesimc xmm0, xmm0".to_string())], + &[InlineAsmTemplatePiece::String("aesimc xmm0, xmm0".into())], &[CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm0)), _late: true, @@ -1091,7 +1093,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("aesenc xmm0, xmm1".to_string())], + &[InlineAsmTemplatePiece::String("aesenc xmm0, xmm1".into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm0)), @@ -1117,7 +1119,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("aesenclast xmm0, xmm1".to_string())], + &[InlineAsmTemplatePiece::String("aesenclast xmm0, xmm1".into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm0)), @@ -1143,7 +1145,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("aesdec xmm0, xmm1".to_string())], + &[InlineAsmTemplatePiece::String("aesdec xmm0, xmm1".into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm0)), @@ -1169,7 +1171,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("aesdeclast xmm0, xmm1".to_string())], + &[InlineAsmTemplatePiece::String("aesdeclast xmm0, xmm1".into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm0)), @@ -1207,7 +1209,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String(format!("sha1rnds4 xmm1, xmm2, {func}"))], + &[InlineAsmTemplatePiece::String(format!("sha1rnds4 xmm1, xmm2, {func}").into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm1)), @@ -1233,7 +1235,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("sha1msg1 xmm1, xmm2".to_string())], + &[InlineAsmTemplatePiece::String("sha1msg1 xmm1, xmm2".into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm1)), @@ -1259,7 +1261,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("sha1msg2 xmm1, xmm2".to_string())], + &[InlineAsmTemplatePiece::String("sha1msg2 xmm1, xmm2".into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm1)), @@ -1285,7 +1287,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("sha1nexte xmm1, xmm2".to_string())], + &[InlineAsmTemplatePiece::String("sha1nexte xmm1, xmm2".into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm1)), @@ -1312,7 +1314,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("sha256rnds2 xmm1, xmm2".to_string())], + &[InlineAsmTemplatePiece::String("sha256rnds2 xmm1, xmm2".into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm1)), @@ -1343,7 +1345,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("sha256msg1 xmm1, xmm2".to_string())], + &[InlineAsmTemplatePiece::String("sha256msg1 xmm1, xmm2".into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm1)), @@ -1369,7 +1371,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("sha256msg2 xmm1, xmm2".to_string())], + &[InlineAsmTemplatePiece::String("sha256msg2 xmm1, xmm2".into())], &[ CInlineAsmOperand::InOut { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::xmm1)), @@ -1435,7 +1437,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( let edx_place = res_place.place_field(fx, FieldIdx::new(1)); codegen_inline_asm_inner( fx, - &[InlineAsmTemplatePiece::String("rdtsc".to_string())], + &[InlineAsmTemplatePiece::String("rdtsc".into())], &[ CInlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(InlineAsmReg::X86(X86InlineAsmReg::ax)), diff --git a/compiler/rustc_codegen_cranelift/src/lib.rs b/compiler/rustc_codegen_cranelift/src/lib.rs index 8d3d5ac98e1e5..9d46d8d6dac35 100644 --- a/compiler/rustc_codegen_cranelift/src/lib.rs +++ b/compiler/rustc_codegen_cranelift/src/lib.rs @@ -85,10 +85,9 @@ mod vtable; mod prelude { pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC}; pub(crate) use cranelift_codegen::ir::function::Function; - pub(crate) use cranelift_codegen::ir::types; pub(crate) use cranelift_codegen::ir::{ - AbiParam, Block, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc, StackSlot, - StackSlotData, StackSlotKind, TrapCode, Type, Value, + types, AbiParam, Block, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc, + StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value, }; pub(crate) use cranelift_codegen::Context; pub(crate) use cranelift_module::{self, DataDescription, FuncId, Linkage, Module}; diff --git a/compiler/rustc_codegen_cranelift/src/main_shim.rs b/compiler/rustc_codegen_cranelift/src/main_shim.rs index fe0a15514190c..ba20a750d2b35 100644 --- a/compiler/rustc_codegen_cranelift/src/main_shim.rs +++ b/compiler/rustc_codegen_cranelift/src/main_shim.rs @@ -1,7 +1,6 @@ use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; use rustc_hir::LangItem; -use rustc_middle::ty::AssocKind; -use rustc_middle::ty::GenericArg; +use rustc_middle::ty::{AssocKind, GenericArg}; use rustc_session::config::{sigpipe, EntryFnType}; use rustc_span::symbol::Ident; use rustc_span::DUMMY_SP; diff --git a/compiler/rustc_codegen_cranelift/src/optimize/peephole.rs b/compiler/rustc_codegen_cranelift/src/optimize/peephole.rs index 26327dca299b9..c93fe93521033 100644 --- a/compiler/rustc_codegen_cranelift/src/optimize/peephole.rs +++ b/compiler/rustc_codegen_cranelift/src/optimize/peephole.rs @@ -1,6 +1,7 @@ //! Peephole optimizations that can be performed while creating clif ir. -use cranelift_codegen::ir::{condcodes::IntCC, InstructionData, Opcode, Value, ValueDef}; +use cranelift_codegen::ir::condcodes::IntCC; +use cranelift_codegen::ir::{InstructionData, Opcode, Value, ValueDef}; use cranelift_frontend::FunctionBuilder; /// If the given value was produced by the lowering of `Rvalue::Not` return the input and true, diff --git a/compiler/rustc_codegen_gcc/build_system/src/build.rs b/compiler/rustc_codegen_gcc/build_system/src/build.rs index d465ab7e50662..8d9518653c5c5 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/build.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/build.rs @@ -1,12 +1,13 @@ -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, -}; use std::collections::HashMap; use std::ffi::OsStr; use std::fs; 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, +}; + #[derive(Default)] struct BuildArg { flags: Vec, @@ -141,7 +142,14 @@ pub fn build_sysroot(env: &HashMap, config: &ConfigInfo) -> Resu rustflags.push_str(" -Csymbol-mangling-version=v0"); } - let mut args: Vec<&dyn AsRef> = vec![&"cargo", &"build", &"--target", &config.target]; + let mut args: Vec<&dyn AsRef> = vec![ + &"cargo", + &"build", + &"--target", + &config.target, + &"--features", + &"compiler-builtins-no-f16-f128", + ]; if config.no_default_features { rustflags.push_str(" -Csymbol-mangling-version=v0"); diff --git a/compiler/rustc_codegen_gcc/build_system/src/clean.rs b/compiler/rustc_codegen_gcc/build_system/src/clean.rs index 55f55acf73ea0..768a78e789e16 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/clean.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/clean.rs @@ -1,8 +1,8 @@ -use crate::utils::{get_sysroot_dir, remove_file, run_command}; - use std::fs::remove_dir_all; use std::path::Path; +use crate::utils::{get_sysroot_dir, remove_file, run_command}; + #[derive(Default)] enum CleanArg { /// `clean all` diff --git a/compiler/rustc_codegen_gcc/build_system/src/clone_gcc.rs b/compiler/rustc_codegen_gcc/build_system/src/clone_gcc.rs index cbf590c0c321a..e28ee873eb6be 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/clone_gcc.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/clone_gcc.rs @@ -1,8 +1,8 @@ +use std::path::{Path, PathBuf}; + use crate::config::ConfigInfo; use crate::utils::{git_clone, run_command_with_output}; -use std::path::{Path, PathBuf}; - fn show_usage() { println!( r#" diff --git a/compiler/rustc_codegen_gcc/build_system/src/config.rs b/compiler/rustc_codegen_gcc/build_system/src/config.rs index bbb711c8428b6..15ba1612167e4 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/config.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/config.rs @@ -1,14 +1,15 @@ -use crate::utils::{ - create_dir, create_symlink, get_os_name, get_sysroot_dir, run_command_with_output, - rustc_version_info, split_args, -}; use std::collections::HashMap; -use std::env as std_env; use std::ffi::OsStr; -use std::fs; use std::path::{Path, PathBuf}; +use std::{env as std_env, fs}; + +use boml::types::TomlValue; +use boml::Toml; -use boml::{types::TomlValue, Toml}; +use crate::utils::{ + create_dir, create_symlink, get_os_name, get_sysroot_dir, run_command_with_output, + rustc_version_info, split_args, +}; #[derive(Default, PartialEq, Eq, Clone, Copy, Debug)] pub enum Channel { diff --git a/compiler/rustc_codegen_gcc/build_system/src/fmt.rs b/compiler/rustc_codegen_gcc/build_system/src/fmt.rs index 43644ba19b38a..de310a6a30fe4 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/fmt.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/fmt.rs @@ -1,7 +1,8 @@ -use crate::utils::run_command_with_output; use std::ffi::OsStr; use std::path::Path; +use crate::utils::run_command_with_output; + fn show_usage() { println!( r#" diff --git a/compiler/rustc_codegen_gcc/build_system/src/main.rs b/compiler/rustc_codegen_gcc/build_system/src/main.rs index d678fd75344d5..3a860e2b1360c 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/main.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/main.rs @@ -1,5 +1,4 @@ -use std::env; -use std::process; +use std::{env, process}; mod build; mod clean; diff --git a/compiler/rustc_codegen_gcc/build_system/src/prepare.rs b/compiler/rustc_codegen_gcc/build_system/src/prepare.rs index 00aa632165e22..d14639afee5a5 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/prepare.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/prepare.rs @@ -1,12 +1,12 @@ +use std::fs; +use std::path::{Path, PathBuf}; + use crate::rustc_info::get_rustc_path; use crate::utils::{ cargo_install, create_dir, get_sysroot_dir, git_clone_root_dir, remove_file, run_command, run_command_with_output, walk_dir, }; -use std::fs; -use std::path::{Path, PathBuf}; - fn prepare_libcore( sysroot_path: &Path, libgccjit12_patches: bool, diff --git a/compiler/rustc_codegen_gcc/build_system/src/rust_tools.rs b/compiler/rustc_codegen_gcc/build_system/src/rust_tools.rs index 242fa7ef94982..105f5eebe2403 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/rust_tools.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/rust_tools.rs @@ -1,13 +1,13 @@ +use std::collections::HashMap; +use std::ffi::OsStr; +use std::path::PathBuf; + use crate::config::ConfigInfo; use crate::utils::{ get_toolchain, run_command_with_output_and_env_no_err, rustc_toolchain_version_info, rustc_version_info, }; -use std::collections::HashMap; -use std::ffi::OsStr; -use std::path::PathBuf; - fn args(command: &str) -> Result>, String> { // We skip the binary and the "cargo"/"rustc" option. if let Some("--help") = std::env::args().skip(2).next().as_deref() { diff --git a/compiler/rustc_codegen_gcc/build_system/src/test.rs b/compiler/rustc_codegen_gcc/build_system/src/test.rs index 06f28d13fb3ab..dabf6c5aa3ee4 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/test.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/test.rs @@ -1,3 +1,10 @@ +use std::collections::HashMap; +use std::ffi::OsStr; +use std::fs::{remove_dir_all, File}; +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + use crate::build; use crate::config::{Channel, ConfigInfo}; use crate::utils::{ @@ -6,13 +13,6 @@ use crate::utils::{ split_args, walk_dir, }; -use std::collections::HashMap; -use std::ffi::OsStr; -use std::fs::{remove_dir_all, File}; -use std::io::{BufRead, BufReader}; -use std::path::{Path, PathBuf}; -use std::str::FromStr; - type Env = HashMap; type Runner = fn(&Env, &TestArg) -> Result<(), String>; type Runners = HashMap<&'static str, (&'static str, Runner)>; diff --git a/compiler/rustc_codegen_gcc/example/std_example.rs b/compiler/rustc_codegen_gcc/example/std_example.rs index 8ab8fcc525e5c..9e43b4635f0d3 100644 --- a/compiler/rustc_codegen_gcc/example/std_example.rs +++ b/compiler/rustc_codegen_gcc/example/std_example.rs @@ -1,5 +1,5 @@ #![allow(internal_features)] -#![feature(core_intrinsics, coroutines, coroutine_trait, is_sorted, stmt_expr_attributes)] +#![feature(core_intrinsics, coroutines, coroutine_trait, stmt_expr_attributes)] #[cfg(feature="master")] #[cfg(target_arch="x86_64")] diff --git a/compiler/rustc_codegen_gcc/src/archive.rs b/compiler/rustc_codegen_gcc/src/archive.rs index 21676f5dbb6a3..36f5e0f8094e8 100644 --- a/compiler/rustc_codegen_gcc/src/archive.rs +++ b/compiler/rustc_codegen_gcc/src/archive.rs @@ -3,9 +3,8 @@ use std::path::{Path, PathBuf}; use rustc_codegen_ssa::back::archive::{ ArArchiveBuilder, ArchiveBuilder, ArchiveBuilderBuilder, DEFAULT_OBJECT_READER, }; -use rustc_session::Session; - use rustc_session::cstore::DllImport; +use rustc_session::Session; pub(crate) struct ArArchiveBuilderBuilder; diff --git a/compiler/rustc_codegen_gcc/src/asm.rs b/compiler/rustc_codegen_gcc/src/asm.rs index 1da691252ab94..7c135289958fe 100644 --- a/compiler/rustc_codegen_gcc/src/asm.rs +++ b/compiler/rustc_codegen_gcc/src/asm.rs @@ -1,3 +1,5 @@ +use std::borrow::Cow; + use gccjit::{LValue, RValue, ToRValue, Type}; use rustc_ast::ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_codegen_ssa::mir::operand::OperandValue; @@ -6,13 +8,11 @@ use rustc_codegen_ssa::traits::{ AsmBuilderMethods, AsmMethods, BaseTypeMethods, BuilderMethods, GlobalAsmOperandRef, InlineAsmOperandRef, }; - -use rustc_middle::{bug, ty::Instance}; +use rustc_middle::bug; +use rustc_middle::ty::Instance; use rustc_span::Span; use rustc_target::asm::*; -use std::borrow::Cow; - use crate::builder::Builder; use crate::callee::get_fn; use crate::context::CodegenCx; diff --git a/compiler/rustc_codegen_gcc/src/attributes.rs b/compiler/rustc_codegen_gcc/src/attributes.rs index 27f21107eda70..e521551304ef8 100644 --- a/compiler/rustc_codegen_gcc/src/attributes.rs +++ b/compiler/rustc_codegen_gcc/src/attributes.rs @@ -9,8 +9,9 @@ use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::ty; use rustc_span::symbol::sym; +use crate::context::CodegenCx; +use crate::errors::TiedTargetFeatures; use crate::gcc_util::{check_tied_features, to_gcc_features}; -use crate::{context::CodegenCx, errors::TiedTargetFeatures}; /// Get GCC attribute for the provided inline heuristic. #[cfg(feature = "master")] diff --git a/compiler/rustc_codegen_gcc/src/base.rs b/compiler/rustc_codegen_gcc/src/base.rs index be149ffe5a16f..4940a7fa2051f 100644 --- a/compiler/rustc_codegen_gcc/src/base.rs +++ b/compiler/rustc_codegen_gcc/src/base.rs @@ -19,8 +19,7 @@ use rustc_target::spec::PanicStrategy; use crate::builder::Builder; use crate::context::CodegenCx; -use crate::{gcc_util, new_context, LockedTargetInfo}; -use crate::{GccContext, SyncContext}; +use crate::{gcc_util, new_context, GccContext, LockedTargetInfo, SyncContext}; #[cfg(feature = "master")] pub fn visibility_to_gcc(linkage: Visibility) -> gccjit::Visibility { diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index b9e4bd79fe1e6..a64371a3d891e 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -28,9 +28,8 @@ use rustc_middle::ty::layout::{ use rustc_middle::ty::{Instance, ParamEnv, Ty, TyCtxt}; use rustc_span::def_id::DefId; use rustc_span::Span; -use rustc_target::abi::{ - self, call::FnAbi, Align, HasDataLayout, Size, TargetDataLayout, WrappingRange, -}; +use rustc_target::abi::call::FnAbi; +use rustc_target::abi::{self, Align, HasDataLayout, Size, TargetDataLayout, WrappingRange}; use rustc_target::spec::{HasTargetSpec, HasWasmCAbiOpt, Target, WasmCAbi}; use crate::common::{type_is_pointer, SignType, TypeReflection}; diff --git a/compiler/rustc_codegen_gcc/src/common.rs b/compiler/rustc_codegen_gcc/src/common.rs index 70f0dc37e39da..7a456e1c5d64a 100644 --- a/compiler/rustc_codegen_gcc/src/common.rs +++ b/compiler/rustc_codegen_gcc/src/common.rs @@ -1,5 +1,4 @@ -use gccjit::LValue; -use gccjit::{RValue, ToRValue, Type}; +use gccjit::{LValue, RValue, ToRValue, Type}; use rustc_codegen_ssa::traits::{BaseTypeMethods, ConstMethods, MiscMethods, StaticMethods}; use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, Scalar}; use rustc_middle::mir::Mutability; diff --git a/compiler/rustc_codegen_gcc/src/consts.rs b/compiler/rustc_codegen_gcc/src/consts.rs index ba7e08e33efa3..e5673cddc4a4f 100644 --- a/compiler/rustc_codegen_gcc/src/consts.rs +++ b/compiler/rustc_codegen_gcc/src/consts.rs @@ -3,14 +3,13 @@ use gccjit::{FnAttribute, VarAttribute, Visibility}; use gccjit::{Function, GlobalKind, LValue, RValue, ToRValue, Type}; use rustc_codegen_ssa::traits::{BaseTypeMethods, ConstMethods, StaticMethods}; use rustc_hir::def::DefKind; -use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs}; use rustc_middle::mir::interpret::{ self, read_target_uint, ConstAllocation, ErrorHandled, Scalar as InterpScalar, }; -use rustc_middle::span_bug; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, Instance}; +use rustc_middle::{bug, span_bug}; use rustc_span::def_id::DefId; use rustc_target::abi::{self, Align, HasDataLayout, Primitive, Size, WrappingRange}; diff --git a/compiler/rustc_codegen_gcc/src/context.rs b/compiler/rustc_codegen_gcc/src/context.rs index 86a5000a72325..e330102fbd84b 100644 --- a/compiler/rustc_codegen_gcc/src/context.rs +++ b/compiler/rustc_codegen_gcc/src/context.rs @@ -6,8 +6,7 @@ use gccjit::{ use rustc_codegen_ssa::base::wants_msvc_seh; use rustc_codegen_ssa::errors as ssa_errors; use rustc_codegen_ssa::traits::{BackendTypes, BaseTypeMethods, MiscMethods}; -use rustc_data_structures::base_n::ToBaseN; -use rustc_data_structures::base_n::ALPHANUMERIC_ONLY; +use rustc_data_structures::base_n::{ToBaseN, ALPHANUMERIC_ONLY}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_middle::mir::mono::CodegenUnit; use rustc_middle::span_bug; @@ -17,10 +16,10 @@ use rustc_middle::ty::layout::{ }; use rustc_middle::ty::{self, Instance, ParamEnv, PolyExistentialTraitRef, Ty, TyCtxt}; use rustc_session::Session; -use rustc_span::{source_map::respan, Span, DUMMY_SP}; -use rustc_target::abi::{ - call::FnAbi, HasDataLayout, PointeeInfo, Size, TargetDataLayout, VariantIdx, -}; +use rustc_span::source_map::respan; +use rustc_span::{Span, DUMMY_SP}; +use rustc_target::abi::call::FnAbi; +use rustc_target::abi::{HasDataLayout, PointeeInfo, Size, TargetDataLayout, VariantIdx}; use rustc_target::spec::{HasTargetSpec, HasWasmCAbiOpt, Target, TlsModel, WasmCAbi}; use crate::callee::get_fn; diff --git a/compiler/rustc_codegen_gcc/src/debuginfo.rs b/compiler/rustc_codegen_gcc/src/debuginfo.rs index 3d9ea278a6399..d770da5a8c44f 100644 --- a/compiler/rustc_codegen_gcc/src/debuginfo.rs +++ b/compiler/rustc_codegen_gcc/src/debuginfo.rs @@ -1,3 +1,5 @@ +use std::ops::Range; + use gccjit::{Location, RValue}; use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext, VariableKind}; use rustc_codegen_ssa::traits::{DebugInfoBuilderMethods, DebugInfoMethods}; @@ -10,7 +12,6 @@ use rustc_session::config::DebugInfo; use rustc_span::{BytePos, Pos, SourceFile, SourceFileAndLine, Span, Symbol}; use rustc_target::abi::call::FnAbi; use rustc_target::abi::Size; -use std::ops::Range; use crate::builder::Builder; use crate::context::CodegenCx; diff --git a/compiler/rustc_codegen_gcc/src/gcc_util.rs b/compiler/rustc_codegen_gcc/src/gcc_util.rs index 53877e8ff7fad..8bb90efe6fb7c 100644 --- a/compiler/rustc_codegen_gcc/src/gcc_util.rs +++ b/compiler/rustc_codegen_gcc/src/gcc_util.rs @@ -1,11 +1,10 @@ #[cfg(feature = "master")] use gccjit::Context; -use smallvec::{smallvec, SmallVec}; - use rustc_data_structures::fx::FxHashMap; use rustc_middle::bug; use rustc_session::Session; use rustc_target::target_features::RUSTC_SPECIFIC_FEATURES; +use smallvec::{smallvec, SmallVec}; use crate::errors::{ PossibleFeature, TargetFeatureDisableOrEnable, UnknownCTargetFeature, diff --git a/compiler/rustc_codegen_gcc/src/int.rs b/compiler/rustc_codegen_gcc/src/int.rs index e4c5eb9137317..92d5c1cbbb80a 100644 --- a/compiler/rustc_codegen_gcc/src/int.rs +++ b/compiler/rustc_codegen_gcc/src/int.rs @@ -6,18 +6,13 @@ use gccjit::{BinaryOp, ComparisonOp, FunctionType, Location, RValue, ToRValue, T use rustc_codegen_ssa::common::{IntPredicate, TypeKind}; use rustc_codegen_ssa::traits::{BackendTypes, BaseTypeMethods, BuilderMethods, OverflowOp}; use rustc_middle::ty::{ParamEnv, Ty}; -use rustc_target::abi::{ - call::{ArgAbi, ArgAttributes, Conv, FnAbi, PassMode}, - Endian, -}; +use rustc_target::abi::call::{ArgAbi, ArgAttributes, Conv, FnAbi, PassMode}; +use rustc_target::abi::Endian; use rustc_target::spec; -use crate::builder::ToGccComp; -use crate::{ - builder::Builder, - common::{SignType, TypeReflection}, - context::CodegenCx, -}; +use crate::builder::{Builder, ToGccComp}; +use crate::common::{SignType, TypeReflection}; +use crate::context::CodegenCx; impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { pub fn gcc_urem(&self, a: RValue<'gcc>, b: RValue<'gcc>) -> RValue<'gcc> { @@ -266,7 +261,9 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { lhs: ::Value, rhs: ::Value, ) -> (::Value, ::Value) { - use rustc_middle::ty::{Int, IntTy::*, Uint, UintTy::*}; + use rustc_middle::ty::IntTy::*; + use rustc_middle::ty::UintTy::*; + use rustc_middle::ty::{Int, Uint}; let new_kind = match *typ.kind() { Int(t @ Isize) => Int(t.normalize(self.tcx.sess.target.pointer_width)), diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs b/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs index a127048221901..554e57250e6d8 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs @@ -3,7 +3,8 @@ use std::borrow::Cow; use gccjit::{Function, FunctionPtrType, RValue, ToRValue, UnaryOp}; use rustc_codegen_ssa::traits::BuilderMethods; -use crate::{builder::Builder, context::CodegenCx}; +use crate::builder::Builder; +use crate::context::CodegenCx; pub fn adjust_intrinsic_arguments<'a, 'b, 'gcc, 'tcx>( builder: &Builder<'a, 'gcc, 'tcx>, diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs index ba214a9c24cff..8da1df3be1534 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs @@ -1,10 +1,8 @@ use std::iter::FromIterator; -use gccjit::ToRValue; -use gccjit::{BinaryOp, RValue, Type}; +use gccjit::{BinaryOp, RValue, ToRValue, Type}; #[cfg(feature = "master")] use gccjit::{ComparisonOp, UnaryOp}; - use rustc_codegen_ssa::base::compare_simd_types; use rustc_codegen_ssa::common::{IntPredicate, TypeKind}; #[cfg(feature = "master")] diff --git a/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs index 1132b0cd2f5ab..cd63a405b67b1 100644 --- a/compiler/rustc_codegen_gcc/src/lib.rs +++ b/compiler/rustc_codegen_gcc/src/lib.rs @@ -79,14 +79,11 @@ use std::ops::Deref; use std::sync::atomic::AtomicBool; #[cfg(not(feature = "master"))] use std::sync::atomic::Ordering; -use std::sync::Arc; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; -use back::lto::ThinBuffer; -use back::lto::ThinData; +use back::lto::{ThinBuffer, ThinData}; use errors::LTONotSupported; -use gccjit::CType; -use gccjit::{Context, OptimizationLevel}; +use gccjit::{CType, Context, OptimizationLevel}; #[cfg(feature = "master")] use gccjit::{TargetInfo, Version}; use rustc_ast::expand::allocator::AllocatorKind; diff --git a/compiler/rustc_codegen_gcc/src/mono_item.rs b/compiler/rustc_codegen_gcc/src/mono_item.rs index 44657ad4f6e25..e6b22d5187147 100644 --- a/compiler/rustc_codegen_gcc/src/mono_item.rs +++ b/compiler/rustc_codegen_gcc/src/mono_item.rs @@ -9,10 +9,9 @@ use rustc_middle::mir::mono::{Linkage, Visibility}; use rustc_middle::ty::layout::{FnAbiOf, LayoutOf}; use rustc_middle::ty::{self, Instance, TypeVisitableExt}; -use crate::attributes; -use crate::base; use crate::context::CodegenCx; use crate::type_of::LayoutGccExt; +use crate::{attributes, base}; impl<'gcc, 'tcx> PreDefineMethods<'tcx> for CodegenCx<'gcc, 'tcx> { #[cfg_attr(not(feature = "master"), allow(unused_variables))] diff --git a/compiler/rustc_codegen_llvm/Cargo.toml b/compiler/rustc_codegen_llvm/Cargo.toml index bb5045ec87241..dad4722d620f3 100644 --- a/compiler/rustc_codegen_llvm/Cargo.toml +++ b/compiler/rustc_codegen_llvm/Cargo.toml @@ -12,7 +12,7 @@ bitflags = "2.4.1" itertools = "0.12" libc = "0.2" measureme = "11" -object = { version = "0.32.0", default-features = false, features = ["std", "read"] } +object = { version = "0.36.2", default-features = false, features = ["std", "read"] } rustc-demangle = "0.1.21" rustc_ast = { path = "../rustc_ast" } rustc_attr = { path = "../rustc_attr" } diff --git a/compiler/rustc_codegen_llvm/src/abi.rs b/compiler/rustc_codegen_llvm/src/abi.rs index d034f9b525690..b8f4203126381 100644 --- a/compiler/rustc_codegen_llvm/src/abi.rs +++ b/compiler/rustc_codegen_llvm/src/abi.rs @@ -1,12 +1,6 @@ -use crate::attributes; -use crate::builder::Builder; -use crate::context::CodegenCx; -use crate::llvm::{self, Attribute, AttributePlace}; -use crate::llvm_util; -use crate::type_::Type; -use crate::type_of::LayoutLlvmExt; -use crate::value::Value; +use std::cmp; +use libc::c_uint; use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue}; use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue}; use rustc_codegen_ssa::traits::*; @@ -20,11 +14,15 @@ pub use rustc_target::abi::call::*; use rustc_target::abi::{self, HasDataLayout, Int, Size}; pub use rustc_target::spec::abi::Abi; use rustc_target::spec::SanitizerSet; - -use libc::c_uint; use smallvec::SmallVec; -use std::cmp; +use crate::builder::Builder; +use crate::context::CodegenCx; +use crate::llvm::{self, Attribute, AttributePlace}; +use crate::type_::Type; +use crate::type_of::LayoutLlvmExt; +use crate::value::Value; +use crate::{attributes, llvm_util}; pub trait ArgAttributesExt { fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value); @@ -121,8 +119,10 @@ impl LlvmType for Reg { match self.kind { RegKind::Integer => cx.type_ix(self.size.bits()), RegKind::Float => match self.size.bits() { + 16 => cx.type_f16(), 32 => cx.type_f32(), 64 => cx.type_f64(), + 128 => cx.type_f128(), _ => bug!("unsupported float: {:?}", self), }, RegKind::Vector => cx.type_vector(cx.type_i8(), self.size.bytes()), diff --git a/compiler/rustc_codegen_llvm/src/allocator.rs b/compiler/rustc_codegen_llvm/src/allocator.rs index 5969d9b914403..8fb3108279391 100644 --- a/compiler/rustc_codegen_llvm/src/allocator.rs +++ b/compiler/rustc_codegen_llvm/src/allocator.rs @@ -1,4 +1,3 @@ -use crate::attributes; use libc::c_uint; use rustc_ast::expand::allocator::{ alloc_error_handler_name, default_fn_name, global_fn_name, AllocatorKind, AllocatorTy, @@ -8,9 +7,8 @@ use rustc_middle::bug; use rustc_middle::ty::TyCtxt; use rustc_session::config::{DebugInfo, OomStrategy}; -use crate::debuginfo; use crate::llvm::{self, Context, False, Module, True, Type}; -use crate::ModuleLlvm; +use crate::{attributes, debuginfo, ModuleLlvm}; pub(crate) unsafe fn codegen( tcx: TyCtxt<'_>, diff --git a/compiler/rustc_codegen_llvm/src/asm.rs b/compiler/rustc_codegen_llvm/src/asm.rs index 597ebd9736561..aea8395441a86 100644 --- a/compiler/rustc_codegen_llvm/src/asm.rs +++ b/compiler/rustc_codegen_llvm/src/asm.rs @@ -1,25 +1,24 @@ -use crate::attributes; -use crate::builder::Builder; -use crate::common::Funclet; -use crate::context::CodegenCx; -use crate::llvm; -use crate::type_::Type; -use crate::type_of::LayoutLlvmExt; -use crate::value::Value; - +use libc::{c_char, c_uint}; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_codegen_ssa::mir::operand::OperandValue; use rustc_codegen_ssa::traits::*; use rustc_data_structures::fx::FxHashMap; use rustc_middle::ty::layout::TyAndLayout; -use rustc_middle::{bug, span_bug, ty::Instance}; +use rustc_middle::ty::Instance; +use rustc_middle::{bug, span_bug}; use rustc_span::{sym, Pos, Span, Symbol}; use rustc_target::abi::*; use rustc_target::asm::*; +use smallvec::SmallVec; use tracing::debug; -use libc::{c_char, c_uint}; -use smallvec::SmallVec; +use crate::builder::Builder; +use crate::common::Funclet; +use crate::context::CodegenCx; +use crate::type_::Type; +use crate::type_of::LayoutLlvmExt; +use crate::value::Value; +use crate::{attributes, llvm}; impl<'ll, 'tcx> AsmBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { fn codegen_inline_asm( diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index 3877460fcdb0d..ad38814a68b6d 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -1,23 +1,21 @@ //! Set and unset common attributes on LLVM values. +pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr}; use rustc_codegen_ssa::traits::*; use rustc_hir::def_id::DefId; use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, PatchableFunctionEntry}; use rustc_middle::ty::{self, TyCtxt}; -use rustc_session::config::{FunctionReturn, OptLevel}; +use rustc_session::config::{BranchProtection, FunctionReturn, OptLevel, PAuthKey, PacRet}; use rustc_span::symbol::sym; use rustc_target::spec::{FramePointer, SanitizerSet, StackProbeType, StackProtector}; use smallvec::SmallVec; -use crate::attributes; +use crate::context::CodegenCx; use crate::errors::{MissingFeatures, SanitizerMemtagRequiresMte, TargetFeatureDisableOrEnable}; use crate::llvm::AttributePlace::Function; use crate::llvm::{self, AllocKindFlags, Attribute, AttributeKind, AttributePlace, MemoryEffects}; -use crate::llvm_util; -pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr}; - -use crate::context::CodegenCx; use crate::value::Value; +use crate::{attributes, llvm_util}; pub fn apply_to_llfn(llfn: &Value, idx: AttributePlace, attrs: &[&Attribute]) { if !attrs.is_empty() { @@ -407,8 +405,33 @@ pub fn from_fn_attrs<'ll, 'tcx>( // And it is a module-level attribute, so the alternative is pulling naked functions into new LLVM modules. // Otherwise LLVM's "naked" functions come with endbr prefixes per https://github.com/rust-lang/rust/issues/98768 to_add.push(AttributeKind::NoCfCheck.create_attr(cx.llcx)); - // Need this for AArch64. - to_add.push(llvm::CreateAttrStringValue(cx.llcx, "branch-target-enforcement", "false")); + if llvm_util::get_version() < (19, 0, 0) { + // Prior to LLVM 19, branch-target-enforcement was disabled by setting the attribute to + // the string "false". Now it is disabled by absence of the attribute. + to_add.push(llvm::CreateAttrStringValue(cx.llcx, "branch-target-enforcement", "false")); + } + } else if llvm_util::get_version() >= (19, 0, 0) { + // For non-naked functions, set branch protection attributes on aarch64. + if let Some(BranchProtection { bti, pac_ret }) = + cx.sess().opts.unstable_opts.branch_protection + { + assert!(cx.sess().target.arch == "aarch64"); + if bti { + to_add.push(llvm::CreateAttrString(cx.llcx, "branch-target-enforcement")); + } + if let Some(PacRet { leaf, key }) = pac_ret { + to_add.push(llvm::CreateAttrStringValue( + cx.llcx, + "sign-return-address", + if leaf { "all" } else { "non-leaf" }, + )); + to_add.push(llvm::CreateAttrStringValue( + cx.llcx, + "sign-return-address-key", + if key == PAuthKey::A { "a_key" } else { "b_key" }, + )); + } + } } if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) || codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR_ZEROED) diff --git a/compiler/rustc_codegen_llvm/src/back/archive.rs b/compiler/rustc_codegen_llvm/src/back/archive.rs index f46c6b1c49800..2f5a864d70eaf 100644 --- a/compiler/rustc_codegen_llvm/src/back/archive.rs +++ b/compiler/rustc_codegen_llvm/src/back/archive.rs @@ -1,27 +1,23 @@ //! A helper class for dealing with static archives -use std::env; use std::ffi::{c_char, c_void, CStr, CString, OsString}; -use std::io; -use std::mem; use std::path::{Path, PathBuf}; -use std::ptr; -use std::str; +use std::{env, io, mem, ptr, str}; -use crate::common; -use crate::errors::{ - DlltoolFailImportLibrary, ErrorCallingDllTool, ErrorCreatingImportLibrary, ErrorWritingDEFFile, -}; -use crate::llvm::archive_ro::{ArchiveRO, Child}; -use crate::llvm::{self, ArchiveKind, LLVMMachineType, LLVMRustCOFFShortExport}; use rustc_codegen_ssa::back::archive::{ try_extract_macho_fat_archive, ArArchiveBuilder, ArchiveBuildFailure, ArchiveBuilder, ArchiveBuilderBuilder, ObjectReader, UnknownArchiveKind, DEFAULT_OBJECT_READER, }; -use tracing::trace; - use rustc_session::cstore::DllImport; use rustc_session::Session; +use tracing::trace; + +use crate::common; +use crate::errors::{ + DlltoolFailImportLibrary, ErrorCallingDllTool, ErrorCreatingImportLibrary, ErrorWritingDEFFile, +}; +use crate::llvm::archive_ro::{ArchiveRO, Child}; +use crate::llvm::{self, ArchiveKind, LLVMMachineType, LLVMRustCOFFShortExport}; /// Helper for adding many files to an archive. #[must_use = "must call build() to finish building the archive"] @@ -101,7 +97,9 @@ impl<'a> ArchiveBuilder for LlvmArchiveBuilder<'a> { fn build(mut self: Box, output: &Path) -> bool { match self.build_with_llvm(output) { Ok(any_members) => any_members, - Err(e) => self.sess.dcx().emit_fatal(ArchiveBuildFailure { error: e }), + Err(error) => { + self.sess.dcx().emit_fatal(ArchiveBuildFailure { path: output.to_owned(), error }) + } } } } diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index aef672631c813..f68155f523a6e 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -1,11 +1,11 @@ -use crate::back::write::{ - self, bitcode_section_name, save_temp_bitcode, CodegenDiagnosticsStage, DiagnosticHandlers, -}; -use crate::errors::{ - DynamicLinkingWithLTO, LlvmError, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib, LtoProcMacro, -}; -use crate::llvm::{self, build_string}; -use crate::{LlvmCodegenBackend, ModuleLlvm}; +use std::collections::BTreeMap; +use std::ffi::{CStr, CString}; +use std::fs::File; +use std::mem::ManuallyDrop; +use std::path::Path; +use std::sync::Arc; +use std::{io, iter, slice}; + use object::read::archive::ArchiveFile; use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule, ThinShared}; use rustc_codegen_ssa::back::symbol_export; @@ -22,15 +22,14 @@ use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel use rustc_session::config::{self, CrateType, Lto}; use tracing::{debug, info}; -use std::collections::BTreeMap; -use std::ffi::{CStr, CString}; -use std::fs::File; -use std::io; -use std::iter; -use std::mem::ManuallyDrop; -use std::path::Path; -use std::slice; -use std::sync::Arc; +use crate::back::write::{ + self, bitcode_section_name, save_temp_bitcode, CodegenDiagnosticsStage, DiagnosticHandlers, +}; +use crate::errors::{ + DynamicLinkingWithLTO, LlvmError, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib, LtoProcMacro, +}; +use crate::llvm::{self, build_string}; +use crate::{LlvmCodegenBackend, ModuleLlvm}; /// We keep track of the computed LTO cache keys from the previous /// session to determine which CGUs we can reuse. 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 b72636a62248e..681ac75c8772a 100644 --- a/compiler/rustc_codegen_llvm/src/back/owned_target_machine.rs +++ b/compiler/rustc_codegen_llvm/src/back/owned_target_machine.rs @@ -1,13 +1,12 @@ -use std::{ - ffi::{c_char, CStr}, - marker::PhantomData, - ops::Deref, - ptr::NonNull, -}; +use std::ffi::{c_char, CStr}; +use std::marker::PhantomData; +use std::ops::Deref; +use std::ptr::NonNull; use rustc_data_structures::small_c_str::SmallCStr; -use crate::{errors::LlvmError, llvm}; +use crate::errors::LlvmError; +use crate::llvm; /// Responsible for safely creating and disposing llvm::TargetMachine via ffi functions. /// Not cloneable as there is no clone function for llvm::TargetMachine. diff --git a/compiler/rustc_codegen_llvm/src/back/profiling.rs b/compiler/rustc_codegen_llvm/src/back/profiling.rs index 2eee9f8c5a3ec..26fb4a96f846b 100644 --- a/compiler/rustc_codegen_llvm/src/back/profiling.rs +++ b/compiler/rustc_codegen_llvm/src/back/profiling.rs @@ -1,9 +1,11 @@ -use measureme::{event_id::SEPARATOR_BYTE, EventId, StringComponent, StringId}; -use rustc_data_structures::profiling::{SelfProfiler, TimingGuard}; use std::ffi::{c_void, CStr}; use std::os::raw::c_char; use std::sync::Arc; +use measureme::event_id::SEPARATOR_BYTE; +use measureme::{EventId, StringComponent, StringId}; +use rustc_data_structures::profiling::{SelfProfiler, TimingGuard}; + fn llvm_args_to_string_id(profiler: &SelfProfiler, pass_name: &str, ir_name: &str) -> EventId { let pass_name = profiler.get_or_alloc_cached_string(pass_name); let mut components = vec![StringComponent::Ref(pass_name)]; diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index ddd52e80edff1..5a7909d151139 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -1,19 +1,10 @@ -use crate::back::lto::ThinBuffer; -use crate::back::owned_target_machine::OwnedTargetMachine; -use crate::back::profiling::{ - selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler, -}; -use crate::base; -use crate::common; -use crate::errors::{ - CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, UnknownCompression, - WithLlvmError, WriteBytecode, -}; -use crate::llvm::{self, DiagnosticInfo, PassManager}; -use crate::llvm_util; -use crate::type_::Type; -use crate::LlvmCodegenBackend; -use crate::ModuleLlvm; +use std::ffi::CString; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::{fs, slice, str}; + +use libc::{c_char, c_int, c_void, size_t}; use llvm::{ LLVMRustLLVMHasZlibCompressionForDebugSymbols, LLVMRustLLVMHasZstdCompressionForDebugSymbols, }; @@ -29,23 +20,28 @@ use rustc_data_structures::small_c_str::SmallCStr; use rustc_errors::{DiagCtxtHandle, FatalError, Level}; use rustc_fs_util::{link_or_copy, path_to_c_string}; use rustc_middle::ty::TyCtxt; -use rustc_session::config::{self, Lto, OutputType, Passes}; -use rustc_session::config::{RemapPathScopeComponents, SplitDwarfKind, SwitchWithOptPath}; +use rustc_session::config::{ + self, Lto, OutputType, Passes, RemapPathScopeComponents, SplitDwarfKind, SwitchWithOptPath, +}; use rustc_session::Session; use rustc_span::symbol::sym; use rustc_span::InnerSpan; use rustc_target::spec::{CodeModel, RelocModel, SanitizerSet, SplitDebuginfo, TlsModel}; use tracing::debug; +use crate::back::lto::ThinBuffer; +use crate::back::owned_target_machine::OwnedTargetMachine; +use crate::back::profiling::{ + selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler, +}; +use crate::errors::{ + CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, UnknownCompression, + WithLlvmError, WriteBytecode, +}; use crate::llvm::diagnostic::OptimizationDiagnosticKind; -use libc::{c_char, c_int, c_void, size_t}; -use std::ffi::CString; -use std::fs; -use std::io::{self, Write}; -use std::path::{Path, PathBuf}; -use std::slice; -use std::str; -use std::sync::Arc; +use crate::llvm::{self, DiagnosticInfo, PassManager}; +use crate::type_::Type; +use crate::{base, common, llvm_util, LlvmCodegenBackend, ModuleLlvm}; pub fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> FatalError { match llvm::last_error() { diff --git a/compiler/rustc_codegen_llvm/src/base.rs b/compiler/rustc_codegen_llvm/src/base.rs index 5dc271ccddb7c..e8236b45c8966 100644 --- a/compiler/rustc_codegen_llvm/src/base.rs +++ b/compiler/rustc_codegen_llvm/src/base.rs @@ -11,13 +11,7 @@ //! [`Ty`]: rustc_middle::ty::Ty //! [`val_ty`]: crate::common::val_ty -use super::ModuleLlvm; - -use crate::attributes; -use crate::builder::Builder; -use crate::context::CodegenCx; -use crate::llvm; -use crate::value::Value; +use std::time::Instant; use rustc_codegen_ssa::base::maybe_create_entry_wrapper; use rustc_codegen_ssa::mono_item::MonoItemExt; @@ -32,7 +26,11 @@ use rustc_session::config::DebugInfo; use rustc_span::symbol::Symbol; use rustc_target::spec::SanitizerSet; -use std::time::Instant; +use super::ModuleLlvm; +use crate::builder::Builder; +use crate::context::CodegenCx; +use crate::value::Value; +use crate::{attributes, llvm}; pub struct ValueIter<'ll> { cur: Option<&'ll Value>, diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 72ff9ea118e28..77e51f941508c 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -1,12 +1,7 @@ -use crate::abi::FnAbiLlvmExt; -use crate::attributes; -use crate::common::Funclet; -use crate::context::CodegenCx; -use crate::llvm::{self, AtomicOrdering, AtomicRmwBinOp, BasicBlock, False, True}; -use crate::llvm_util; -use crate::type_::Type; -use crate::type_of::LayoutLlvmExt; -use crate::value::Value; +use std::borrow::Cow; +use std::ops::Deref; +use std::{iter, ptr}; + use libc::{c_char, c_uint}; use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind}; use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue}; @@ -23,15 +18,21 @@ use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_sanitizers::{cfi, kcfi}; use rustc_session::config::OptLevel; use rustc_span::Span; -use rustc_target::abi::{self, call::FnAbi, Align, Size, WrappingRange}; +use rustc_target::abi::call::FnAbi; +use rustc_target::abi::{self, Align, Size, WrappingRange}; use rustc_target::spec::{HasTargetSpec, SanitizerSet, Target}; use smallvec::SmallVec; -use std::borrow::Cow; -use std::iter; -use std::ops::Deref; -use std::ptr; use tracing::{debug, instrument}; +use crate::abi::FnAbiLlvmExt; +use crate::common::Funclet; +use crate::context::CodegenCx; +use crate::llvm::{self, AtomicOrdering, AtomicRmwBinOp, BasicBlock, False, True}; +use crate::type_::Type; +use crate::type_of::LayoutLlvmExt; +use crate::value::Value; +use crate::{attributes, llvm_util}; + // All Builders must have an llfn associated with them #[must_use] pub struct Builder<'a, 'll, 'tcx> { @@ -390,8 +391,9 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { lhs: Self::Value, rhs: Self::Value, ) -> (Self::Value, Self::Value) { + use rustc_middle::ty::IntTy::*; + use rustc_middle::ty::UintTy::*; use rustc_middle::ty::{Int, Uint}; - use rustc_middle::ty::{IntTy::*, UintTy::*}; let new_kind = match ty.kind() { Int(t @ Isize) => Int(t.normalize(self.tcx.sess.target.pointer_width)), @@ -1353,6 +1355,16 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { } } + pub fn set_unpredictable(&mut self, inst: &'ll Value) { + unsafe { + llvm::LLVMSetMetadata( + inst, + llvm::MD_unpredictable as c_uint, + llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0), + ); + } + } + pub fn minnum(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value { unsafe { llvm::LLVMRustBuildMinNum(self.llbuilder, lhs, rhs) } } diff --git a/compiler/rustc_codegen_llvm/src/callee.rs b/compiler/rustc_codegen_llvm/src/callee.rs index 659c6ae0d8630..c913bdebaaa7c 100644 --- a/compiler/rustc_codegen_llvm/src/callee.rs +++ b/compiler/rustc_codegen_llvm/src/callee.rs @@ -4,16 +4,14 @@ //! and methods are represented as just a fn ptr and not a full //! closure. -use crate::attributes; -use crate::common; -use crate::context::CodegenCx; -use crate::llvm; -use crate::value::Value; - use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt}; use rustc_middle::ty::{self, Instance, TypeVisitableExt}; use tracing::debug; +use crate::context::CodegenCx; +use crate::value::Value; +use crate::{attributes, common, llvm}; + /// Codegens a reference to a fn/method item, monomorphizing and /// inlining as it goes. /// diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index fe64649cf70fb..197bbb9ddbf9e 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -1,11 +1,8 @@ //! Code that is useful in various codegen modules. -use crate::consts::const_alloc_to_llvm; -pub use crate::context::CodegenCx; -use crate::llvm::{self, BasicBlock, Bool, ConstantInt, False, OperandBundleDef, True}; -use crate::type_::Type; -use crate::value::Value; +use std::fmt::Write; +use libc::{c_char, c_uint}; use rustc_ast::Mutability; use rustc_codegen_ssa::traits::*; use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher}; @@ -16,11 +13,14 @@ use rustc_middle::ty::TyCtxt; use rustc_session::cstore::{DllCallingConvention, DllImport, PeImportNameType}; use rustc_target::abi::{self, AddressSpace, HasDataLayout, Pointer}; use rustc_target::spec::Target; - -use libc::{c_char, c_uint}; -use std::fmt::Write; use tracing::debug; +use crate::consts::const_alloc_to_llvm; +pub use crate::context::CodegenCx; +use crate::llvm::{self, BasicBlock, Bool, ConstantInt, False, OperandBundleDef, True}; +use crate::type_::Type; +use crate::value::Value; + /* * A note on nomenclature of linking: "extern", "foreign", and "upcall". * diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 164d1681a3670..c3ea4a18a71bd 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -1,13 +1,5 @@ -use crate::base; -use crate::common::{self, CodegenCx}; -use crate::debuginfo; -use crate::errors::{ - InvalidMinimumAlignmentNotPowerOfTwo, InvalidMinimumAlignmentTooLarge, SymbolAlreadyDefined, -}; -use crate::llvm::{self, True}; -use crate::type_::Type; -use crate::type_of::LayoutLlvmExt; -use crate::value::Value; +use std::ops::Range; + use rustc_codegen_ssa::traits::*; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; @@ -24,9 +16,18 @@ use rustc_session::config::Lto; use rustc_target::abi::{ Align, AlignFromBytesError, HasDataLayout, Primitive, Scalar, Size, WrappingRange, }; -use std::ops::Range; use tracing::{debug, instrument, trace}; +use crate::common::{self, CodegenCx}; +use crate::errors::{ + InvalidMinimumAlignmentNotPowerOfTwo, InvalidMinimumAlignmentTooLarge, SymbolAlreadyDefined, +}; +use crate::llvm::{self, True}; +use crate::type_::Type; +use crate::type_of::LayoutLlvmExt; +use crate::value::Value; +use crate::{base, debuginfo}; + pub fn const_alloc_to_llvm<'ll>( cx: &CodegenCx<'ll, '_>, alloc: ConstAllocation<'_>, @@ -330,7 +331,7 @@ impl<'ll> CodegenCx<'ll, '_> { // If this assertion triggers, there's something wrong with commandline // argument validation. - debug_assert!( + assert!( !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled() && self.tcx.sess.target.is_like_windows && self.tcx.sess.opts.cg.prefer_dynamic) diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 49677dcf12f73..ea930421b5869 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -1,19 +1,13 @@ -use crate::attributes; -use crate::back::write::to_llvm_code_model; -use crate::callee::get_fn; -use crate::coverageinfo; -use crate::debuginfo; -use crate::debuginfo::metadata::apply_vcall_visibility_metadata; -use crate::llvm; -use crate::llvm_util; -use crate::type_::Type; -use crate::value::Value; +use std::borrow::Borrow; +use std::cell::{Cell, RefCell}; +use std::ffi::CStr; +use std::str; +use libc::c_uint; use rustc_codegen_ssa::base::{wants_msvc_seh, wants_wasm_eh}; use rustc_codegen_ssa::errors as ssa_errors; use rustc_codegen_ssa::traits::*; -use rustc_data_structures::base_n::ToBaseN; -use rustc_data_structures::base_n::ALPHANUMERIC_ONLY; +use rustc_data_structures::base_n::{ToBaseN, ALPHANUMERIC_ONLY}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::small_c_str::SmallCStr; use rustc_hir::def_id::DefId; @@ -24,20 +18,23 @@ use rustc_middle::ty::layout::{ }; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; -use rustc_session::config::{BranchProtection, CFGuard, CFProtection}; -use rustc_session::config::{CrateType, DebugInfo, PAuthKey, PacRet}; +use rustc_session::config::{ + BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, PAuthKey, PacRet, +}; use rustc_session::Session; use rustc_span::source_map::Spanned; use rustc_span::{Span, DUMMY_SP}; -use rustc_target::abi::{call::FnAbi, HasDataLayout, TargetDataLayout, VariantIdx}; +use rustc_target::abi::call::FnAbi; +use rustc_target::abi::{HasDataLayout, TargetDataLayout, VariantIdx}; use rustc_target::spec::{HasTargetSpec, RelocModel, Target, TlsModel}; use smallvec::SmallVec; -use libc::c_uint; -use std::borrow::Borrow; -use std::cell::{Cell, RefCell}; -use std::ffi::CStr; -use std::str; +use crate::back::write::to_llvm_code_model; +use crate::callee::get_fn; +use crate::debuginfo::metadata::apply_vcall_visibility_metadata; +use crate::type_::Type; +use crate::value::Value; +use crate::{attributes, coverageinfo, debuginfo, llvm, llvm_util}; /// There is one `CodegenCx` per compilation unit. Each one has its own LLVM /// `llvm::Context` so that several compilation units may be optimized in parallel. diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs index 14a9446858709..9433385c23a5b 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs @@ -1,5 +1,3 @@ -use crate::coverageinfo::ffi::{Counter, CounterExpression, ExprKind}; - use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexSet; use rustc_index::bit_set::BitSet; @@ -11,6 +9,8 @@ use rustc_middle::ty::Instance; use rustc_span::Symbol; use tracing::{debug, instrument}; +use crate::coverageinfo::ffi::{Counter, CounterExpression, ExprKind}; + /// Holds all of the coverage mapping data associated with a function instance, /// collected during traversal of `Coverage` statements in the function's MIR. #[derive(Debug)] diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index d2c0f20c285b4..f8929a26011ab 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -1,21 +1,19 @@ -use crate::common::CodegenCx; -use crate::coverageinfo; -use crate::coverageinfo::ffi::CounterMappingRegion; -use crate::coverageinfo::map_data::{FunctionCoverage, FunctionCoverageCollector}; -use crate::llvm; - use itertools::Itertools as _; use rustc_codegen_ssa::traits::{BaseTypeMethods, ConstMethods}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_index::IndexVec; -use rustc_middle::bug; -use rustc_middle::mir; use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::{bug, mir}; use rustc_span::def_id::DefIdSet; use rustc_span::Symbol; use tracing::debug; +use crate::common::CodegenCx; +use crate::coverageinfo::ffi::CounterMappingRegion; +use crate::coverageinfo::map_data::{FunctionCoverage, FunctionCoverageCollector}; +use crate::{coverageinfo, llvm}; + /// Generates and exports the Coverage Map. /// /// Rust Coverage Map generation supports LLVM Coverage Mapping Format versions diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index 7b7f8c885bbb1..20a713b856419 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -1,9 +1,4 @@ -use crate::llvm; - -use crate::builder::Builder; -use crate::common::CodegenCx; -use crate::coverageinfo::ffi::{CounterExpression, CounterMappingRegion}; -use crate::coverageinfo::map_data::FunctionCoverageCollector; +use std::cell::RefCell; use libc::c_uint; use rustc_codegen_ssa::traits::{ @@ -19,7 +14,11 @@ use rustc_middle::ty::Instance; use rustc_target::abi::{Align, Size}; use tracing::{debug, instrument}; -use std::cell::RefCell; +use crate::builder::Builder; +use crate::common::CodegenCx; +use crate::coverageinfo::ffi::{CounterExpression, CounterMappingRegion}; +use crate::coverageinfo::map_data::FunctionCoverageCollector; +use crate::llvm; pub(crate) mod ffi; pub(crate) mod map_data; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs b/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs index 6a63eda4b993d..efe616838bfe4 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs @@ -1,18 +1,17 @@ -use super::metadata::file_metadata; -use super::utils::DIB; use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext}; use rustc_codegen_ssa::traits::*; - -use crate::common::CodegenCx; -use crate::llvm; -use crate::llvm::debuginfo::{DILocation, DIScope}; +use rustc_index::bit_set::BitSet; +use rustc_index::Idx; use rustc_middle::mir::{Body, SourceScope}; use rustc_middle::ty::layout::FnAbiOf; use rustc_middle::ty::{self, Instance}; use rustc_session::config::DebugInfo; -use rustc_index::bit_set::BitSet; -use rustc_index::Idx; +use super::metadata::file_metadata; +use super::utils::DIB; +use crate::common::CodegenCx; +use crate::llvm; +use crate::llvm::debuginfo::{DILocation, DIScope}; /// Produces DIScope DIEs for each MIR Scope which has variables defined in it. // FIXME(eddyb) almost all of this should be in `rustc_codegen_ssa::mir::debuginfo`. diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs index d82b1e1e721ba..5a08f2f00e5be 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs @@ -1,18 +1,19 @@ // .debug_gdb_scripts binary section. -use crate::llvm; - -use crate::builder::Builder; -use crate::common::CodegenCx; -use crate::value::Value; use rustc_ast::attr; use rustc_codegen_ssa::base::collect_debugger_visualizers_transitive; use rustc_codegen_ssa::traits::*; use rustc_hir::def_id::LOCAL_CRATE; -use rustc_middle::{bug, middle::debugger_visualizer::DebuggerVisualizerType}; +use rustc_middle::bug; +use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerType; use rustc_session::config::{CrateType, DebugInfo}; use rustc_span::symbol::sym; +use crate::builder::Builder; +use crate::common::CodegenCx; +use crate::llvm; +use crate::value::Value; + /// Inserts a side-effect free instruction sequence that makes sure that the /// .debug_gdb_scripts global is referenced, so it isn't removed by the linker. pub fn insert_reference_to_gdb_debug_scripts_section_global(bx: &mut Builder<'_, '_, '_>) { diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 851a4c42e99b4..ad63858861261 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -1,32 +1,14 @@ -use self::type_map::DINodeCreationResult; -use self::type_map::Stub; -use self::type_map::UniqueTypeId; - -use super::namespace::mangled_name_of_instance; -use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_name}; -use super::utils::{ - create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB, -}; -use super::CodegenUnitDebugContext; - -use crate::abi; -use crate::common::CodegenCx; -use crate::debuginfo::metadata::type_map::build_type_with_children; -use crate::debuginfo::utils::fat_pointer_kind; -use crate::debuginfo::utils::FatPtrKind; -use crate::llvm; -use crate::llvm::debuginfo::{ - DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType, DebugEmissionKind, - DebugNameTableKind, -}; -use crate::value::Value; +use std::borrow::Cow; +use std::fmt::{self, Write}; +use std::hash::{Hash, Hasher}; +use std::path::{Path, PathBuf}; +use std::{iter, ptr}; -use rustc_codegen_ssa::debuginfo::type_names::cpp_like_debuginfo; -use rustc_codegen_ssa::debuginfo::type_names::VTableNameKind; +use libc::{c_char, c_longlong, c_uint}; +use rustc_codegen_ssa::debuginfo::type_names::{cpp_like_debuginfo, VTableNameKind}; use rustc_codegen_ssa::traits::*; use rustc_fs_util::path_to_c_string; -use rustc_hir::def::CtorKind; -use rustc_hir::def::DefKind; +use rustc_hir::def::{CtorKind, DefKind}; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_middle::bug; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; @@ -36,21 +18,29 @@ use rustc_middle::ty::{ }; use rustc_session::config::{self, DebugInfo, Lto}; use rustc_span::symbol::Symbol; -use rustc_span::{hygiene, FileName, DUMMY_SP}; -use rustc_span::{FileNameDisplayPreference, SourceFile}; +use rustc_span::{hygiene, FileName, FileNameDisplayPreference, SourceFile, DUMMY_SP}; use rustc_symbol_mangling::typeid_for_trait_ref; use rustc_target::abi::{Align, Size}; use rustc_target::spec::DebuginfoKind; use smallvec::smallvec; use tracing::{debug, instrument}; -use libc::{c_char, c_longlong, c_uint}; -use std::borrow::Cow; -use std::fmt::{self, Write}; -use std::hash::{Hash, Hasher}; -use std::iter; -use std::path::{Path, PathBuf}; -use std::ptr; +use self::type_map::{DINodeCreationResult, Stub, UniqueTypeId}; +use super::namespace::mangled_name_of_instance; +use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_name}; +use super::utils::{ + create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB, +}; +use super::CodegenUnitDebugContext; +use crate::common::CodegenCx; +use crate::debuginfo::metadata::type_map::build_type_with_children; +use crate::debuginfo::utils::{fat_pointer_kind, FatPtrKind}; +use crate::llvm::debuginfo::{ + DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType, DebugEmissionKind, + DebugNameTableKind, +}; +use crate::value::Value; +use crate::{abi, llvm}; impl PartialEq for llvm::Metadata { fn eq(&self, other: &Self) -> bool { @@ -170,7 +160,7 @@ fn build_pointer_or_reference_di_node<'ll, 'tcx>( ) -> DINodeCreationResult<'ll> { // The debuginfo generated by this function is only valid if `ptr_type` is really just // a (fat) pointer. Make sure it is not called for e.g. `Box`. - debug_assert_eq!( + assert_eq!( cx.size_and_align_of(ptr_type), cx.size_and_align_of(Ty::new_mut_ptr(cx.tcx, pointee_type)) ); @@ -185,7 +175,7 @@ fn build_pointer_or_reference_di_node<'ll, 'tcx>( match fat_pointer_kind(cx, pointee_type) { None => { // This is a thin pointer. Create a regular pointer type and give it the correct name. - debug_assert_eq!( + assert_eq!( (data_layout.pointer_size, data_layout.pointer_align.abi), cx.size_and_align_of(ptr_type), "ptr_type={ptr_type}, pointee_type={pointee_type}", @@ -240,8 +230,8 @@ fn build_pointer_or_reference_di_node<'ll, 'tcx>( FatPtrKind::Slice => ("data_ptr", "length"), }; - debug_assert_eq!(abi::FAT_PTR_ADDR, 0); - debug_assert_eq!(abi::FAT_PTR_EXTRA, 1); + assert_eq!(abi::FAT_PTR_ADDR, 0); + assert_eq!(abi::FAT_PTR_EXTRA, 1); // The data pointer type is a regular, thin pointer, regardless of whether this // is a slice or a trait object. @@ -498,7 +488,7 @@ pub fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll D } }; - debug_assert_eq!(di_node_for_uid as *const _, di_node as *const _); + assert_eq!(di_node_for_uid as *const _, di_node as *const _); } else { debug_context(cx).type_map.insert(unique_type_id, di_node); } @@ -874,7 +864,8 @@ pub fn build_compile_unit_di_node<'ll, 'tcx>( codegen_unit_name: &str, debug_context: &CodegenUnitDebugContext<'ll, 'tcx>, ) -> &'ll DIDescriptor { - use rustc_session::{config::RemapPathScopeComponents, RemapFileNameExt}; + use rustc_session::config::RemapPathScopeComponents; + use rustc_session::RemapFileNameExt; let mut name_in_debuginfo = tcx .sess .local_crate_source_file() @@ -1060,7 +1051,7 @@ fn build_struct_type_di_node<'ll, 'tcx>( let ty::Adt(adt_def, _) = struct_type.kind() else { bug!("build_struct_type_di_node() called with non-struct-type: {:?}", struct_type); }; - debug_assert!(adt_def.is_struct()); + assert!(adt_def.is_struct()); let containing_scope = get_namespace_for_item(cx, adt_def.did()); let struct_type_and_layout = cx.layout_of(struct_type); let variant_def = adt_def.non_enum_variant(); @@ -1130,7 +1121,7 @@ fn build_upvar_field_di_nodes<'ll, 'tcx>( } }; - debug_assert!( + assert!( up_var_tys.iter().all(|t| t == cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t)) ); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs index 12f98eef97d43..13006638bb3a3 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs @@ -1,41 +1,27 @@ use std::borrow::Cow; use libc::c_uint; -use rustc_codegen_ssa::{ - debuginfo::{type_names::compute_debuginfo_type_name, wants_c_like_enum_debuginfo}, - traits::ConstMethods, -}; - +use rustc_codegen_ssa::debuginfo::type_names::compute_debuginfo_type_name; +use rustc_codegen_ssa::debuginfo::wants_c_like_enum_debuginfo; +use rustc_codegen_ssa::traits::ConstMethods; use rustc_index::IndexVec; -use rustc_middle::{ - bug, - ty::{ - self, - layout::{LayoutOf, TyAndLayout}, - AdtDef, CoroutineArgs, CoroutineArgsExt, Ty, - }, -}; +use rustc_middle::bug; +use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; +use rustc_middle::ty::{self, AdtDef, CoroutineArgs, CoroutineArgsExt, Ty}; use rustc_target::abi::{Align, Endian, Size, TagEncoding, VariantIdx, Variants}; use smallvec::smallvec; -use crate::{ - common::CodegenCx, - debuginfo::{ - metadata::{ - build_field_di_node, - enums::{tag_base_type, DiscrResult}, - file_metadata, size_and_align_of, type_di_node, - type_map::{self, Stub, UniqueTypeId}, - unknown_file_metadata, visibility_di_flags, DINodeCreationResult, SmallVec, - NO_GENERICS, NO_SCOPE_METADATA, UNKNOWN_LINE_NUMBER, - }, - utils::DIB, - }, - llvm::{ - self, - debuginfo::{DIFile, DIFlags, DIType}, - }, +use crate::common::CodegenCx; +use crate::debuginfo::metadata::enums::{tag_base_type, DiscrResult}; +use crate::debuginfo::metadata::type_map::{self, Stub, UniqueTypeId}; +use crate::debuginfo::metadata::{ + build_field_di_node, file_metadata, size_and_align_of, type_di_node, unknown_file_metadata, + visibility_di_flags, DINodeCreationResult, SmallVec, NO_GENERICS, NO_SCOPE_METADATA, + UNKNOWN_LINE_NUMBER, }; +use crate::debuginfo::utils::DIB; +use crate::llvm::debuginfo::{DIFile, DIFlags, DIType}; +use crate::llvm::{self}; // The names of the associated constants in each variant wrapper struct. // These have to match up with the names being used in `intrinsic.natvis`. @@ -204,7 +190,7 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( let enum_type_and_layout = cx.layout_of(enum_type); let enum_type_name = compute_debuginfo_type_name(cx.tcx, enum_type, false); - debug_assert!(!wants_c_like_enum_debuginfo(enum_type_and_layout)); + assert!(!wants_c_like_enum_debuginfo(enum_type_and_layout)); type_map::build_type_with_children( cx, @@ -279,7 +265,7 @@ pub(super) fn build_coroutine_di_node<'ll, 'tcx>( let coroutine_type_and_layout = cx.layout_of(coroutine_type); let coroutine_type_name = compute_debuginfo_type_name(cx.tcx, coroutine_type, false); - debug_assert!(!wants_c_like_enum_debuginfo(coroutine_type_and_layout)); + assert!(!wants_c_like_enum_debuginfo(coroutine_type_and_layout)); type_map::build_type_with_children( cx, @@ -517,7 +503,7 @@ fn build_variant_struct_wrapper_type_di_node<'ll, 'tcx>( if is_128_bits { DiscrKind::Exact128(discr_val) } else { - debug_assert_eq!(discr_val, discr_val as u64 as u128); + assert_eq!(discr_val, discr_val as u64 as u128); DiscrKind::Exact(discr_val as u64) } } @@ -526,8 +512,8 @@ fn build_variant_struct_wrapper_type_di_node<'ll, 'tcx>( if is_128_bits { DiscrKind::Range128(min, max) } else { - debug_assert_eq!(min, min as u64 as u128); - debug_assert_eq!(max, max as u64 as u128); + assert_eq!(min, min as u64 as u128); + assert_eq!(max, max as u64 as u128); DiscrKind::Range(min as u64, max as u64) } } @@ -815,7 +801,7 @@ fn build_union_fields_for_direct_tag_enum_or_coroutine<'ll, 'tcx>( } })); - debug_assert_eq!( + assert_eq!( cx.size_and_align_of(enum_type_and_layout.field(cx, tag_field).ty), cx.size_and_align_of(super::tag_base_type(cx, enum_type_and_layout)) ); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs index 2b00bb14593e4..fc3adaf068111 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs @@ -1,45 +1,29 @@ -use rustc_codegen_ssa::debuginfo::{ - type_names::{compute_debuginfo_type_name, cpp_like_debuginfo}, - wants_c_like_enum_debuginfo, -}; +use std::borrow::Cow; + +use rustc_codegen_ssa::debuginfo::type_names::{compute_debuginfo_type_name, cpp_like_debuginfo}; +use rustc_codegen_ssa::debuginfo::wants_c_like_enum_debuginfo; use rustc_hir::def::CtorKind; use rustc_index::IndexSlice; -use rustc_middle::{ - bug, - mir::CoroutineLayout, - ty::{ - self, - layout::{IntegerExt, LayoutOf, PrimitiveExt, TyAndLayout}, - AdtDef, CoroutineArgs, CoroutineArgsExt, Ty, VariantDef, - }, -}; +use rustc_middle::bug; +use rustc_middle::mir::CoroutineLayout; +use rustc_middle::ty::layout::{IntegerExt, LayoutOf, PrimitiveExt, TyAndLayout}; +use rustc_middle::ty::{self, AdtDef, CoroutineArgs, CoroutineArgsExt, Ty, VariantDef}; use rustc_span::Symbol; use rustc_target::abi::{ FieldIdx, HasDataLayout, Integer, Primitive, TagEncoding, VariantIdx, Variants, }; -use std::borrow::Cow; - -use crate::{ - common::CodegenCx, - debuginfo::{ - metadata::{ - build_field_di_node, build_generic_type_param_di_nodes, type_di_node, - type_map::{self, Stub}, - unknown_file_metadata, UNKNOWN_LINE_NUMBER, - }, - utils::{create_DIArray, get_namespace_for_item, DIB}, - }, - llvm::{ - self, - debuginfo::{DIFlags, DIType}, - }, -}; -use super::{ - size_and_align_of, - type_map::{DINodeCreationResult, UniqueTypeId}, - SmallVec, +use super::type_map::{DINodeCreationResult, UniqueTypeId}; +use super::{size_and_align_of, SmallVec}; +use crate::common::CodegenCx; +use crate::debuginfo::metadata::type_map::{self, Stub}; +use crate::debuginfo::metadata::{ + build_field_di_node, build_generic_type_param_di_nodes, type_di_node, unknown_file_metadata, + UNKNOWN_LINE_NUMBER, }; +use crate::debuginfo::utils::{create_DIArray, get_namespace_for_item, DIB}; +use crate::llvm::debuginfo::{DIFlags, DIType}; +use crate::llvm::{self}; mod cpp_like; mod native; @@ -106,7 +90,7 @@ fn tag_base_type<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, enum_type_and_layout: TyAndLayout<'tcx>, ) -> Ty<'tcx> { - debug_assert!(match enum_type_and_layout.ty.kind() { + assert!(match enum_type_and_layout.ty.kind() { ty::Coroutine(..) => true, ty::Adt(adt_def, _) => adt_def.is_enum(), _ => false, @@ -251,7 +235,7 @@ fn build_enum_variant_struct_type_di_node<'ll, 'tcx>( variant_layout: TyAndLayout<'tcx>, di_flags: DIFlags, ) -> &'ll DIType { - debug_assert_eq!(variant_layout.ty, enum_type_and_layout.ty); + assert_eq!(variant_layout.ty, enum_type_and_layout.ty); type_map::build_type_with_children( cx, diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs index 115d5187eafa8..d7e3b47e0bd5b 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs @@ -1,37 +1,26 @@ use std::borrow::Cow; -use crate::{ - common::CodegenCx, - debuginfo::{ - metadata::{ - enums::tag_base_type, - file_metadata, size_and_align_of, type_di_node, - type_map::{self, Stub, StubInfo, UniqueTypeId}, - unknown_file_metadata, visibility_di_flags, DINodeCreationResult, SmallVec, - NO_GENERICS, UNKNOWN_LINE_NUMBER, - }, - utils::{create_DIArray, get_namespace_for_item, DIB}, - }, - llvm::{ - self, - debuginfo::{DIFile, DIFlags, DIType}, - }, -}; use libc::c_uint; -use rustc_codegen_ssa::{ - debuginfo::{type_names::compute_debuginfo_type_name, wants_c_like_enum_debuginfo}, - traits::ConstMethods, -}; -use rustc_middle::{ - bug, - ty::{ - self, - layout::{LayoutOf, TyAndLayout}, - }, -}; +use rustc_codegen_ssa::debuginfo::type_names::compute_debuginfo_type_name; +use rustc_codegen_ssa::debuginfo::wants_c_like_enum_debuginfo; +use rustc_codegen_ssa::traits::ConstMethods; +use rustc_middle::bug; +use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; +use rustc_middle::ty::{self}; use rustc_target::abi::{Size, TagEncoding, VariantIdx, Variants}; use smallvec::smallvec; +use crate::common::CodegenCx; +use crate::debuginfo::metadata::enums::tag_base_type; +use crate::debuginfo::metadata::type_map::{self, Stub, StubInfo, UniqueTypeId}; +use crate::debuginfo::metadata::{ + file_metadata, size_and_align_of, type_di_node, unknown_file_metadata, visibility_di_flags, + DINodeCreationResult, SmallVec, NO_GENERICS, UNKNOWN_LINE_NUMBER, +}; +use crate::debuginfo::utils::{create_DIArray, get_namespace_for_item, DIB}; +use crate::llvm::debuginfo::{DIFile, DIFlags, DIType}; +use crate::llvm::{self}; + /// Build the debuginfo node for an enum type. The listing below shows how such a /// type looks like at the LLVM IR/DWARF level. It is a `DW_TAG_structure_type` /// with a single `DW_TAG_variant_part` that in turn contains a `DW_TAG_variant` @@ -65,7 +54,7 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( let visibility_flags = visibility_di_flags(cx, enum_adt_def.did(), enum_adt_def.did()); - debug_assert!(!wants_c_like_enum_debuginfo(enum_type_and_layout)); + assert!(!wants_c_like_enum_debuginfo(enum_type_and_layout)); type_map::build_type_with_children( cx, @@ -142,7 +131,7 @@ pub(super) fn build_coroutine_di_node<'ll, 'tcx>( let containing_scope = get_namespace_for_item(cx, coroutine_def_id); let coroutine_type_and_layout = cx.layout_of(coroutine_type); - debug_assert!(!wants_c_like_enum_debuginfo(coroutine_type_and_layout)); + assert!(!wants_c_like_enum_debuginfo(coroutine_type_and_layout)); let coroutine_type_name = compute_debuginfo_type_name(cx.tcx, coroutine_type, false); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs index e521d5e259caa..25b2df9c52c3a 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs @@ -1,27 +1,18 @@ use std::cell::RefCell; -use rustc_data_structures::{ - fingerprint::Fingerprint, - fx::FxHashMap, - stable_hasher::{HashStable, StableHasher}, -}; +use rustc_data_structures::fingerprint::Fingerprint; +use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_macros::HashStable; -use rustc_middle::{ - bug, - ty::{ParamEnv, PolyExistentialTraitRef, Ty, TyCtxt}, -}; +use rustc_middle::bug; +use rustc_middle::ty::{ParamEnv, PolyExistentialTraitRef, Ty, TyCtxt}; use rustc_target::abi::{Align, Size, VariantIdx}; -use crate::{ - common::CodegenCx, - debuginfo::utils::{create_DIArray, debug_context, DIB}, - llvm::{ - self, - debuginfo::{DIFlags, DIScope, DIType}, - }, -}; - use super::{unknown_file_metadata, SmallVec, UNKNOWN_LINE_NUMBER}; +use crate::common::CodegenCx; +use crate::debuginfo::utils::{create_DIArray, debug_context, DIB}; +use crate::llvm::debuginfo::{DIFlags, DIScope, DIType}; +use crate::llvm::{self}; mod private { use rustc_macros::HashStable; @@ -36,7 +27,7 @@ mod private { /// A unique identifier for anything that we create a debuginfo node for. /// The types it contains are expected to already be normalized (which -/// is debug_asserted in the constructors). +/// is asserted in the constructors). /// /// Note that there are some things that only show up in debuginfo, like /// the separate type descriptions for each enum variant. These get an ID @@ -58,12 +49,12 @@ pub(super) enum UniqueTypeId<'tcx> { impl<'tcx> UniqueTypeId<'tcx> { pub fn for_ty(tcx: TyCtxt<'tcx>, t: Ty<'tcx>) -> Self { - debug_assert_eq!(t, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t)); + assert_eq!(t, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t)); UniqueTypeId::Ty(t, private::HiddenZst) } pub fn for_enum_variant_part(tcx: TyCtxt<'tcx>, enum_ty: Ty<'tcx>) -> Self { - debug_assert_eq!(enum_ty, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), enum_ty)); + assert_eq!(enum_ty, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), enum_ty)); UniqueTypeId::VariantPart(enum_ty, private::HiddenZst) } @@ -72,7 +63,7 @@ impl<'tcx> UniqueTypeId<'tcx> { enum_ty: Ty<'tcx>, variant_idx: VariantIdx, ) -> Self { - debug_assert_eq!(enum_ty, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), enum_ty)); + assert_eq!(enum_ty, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), enum_ty)); UniqueTypeId::VariantStructType(enum_ty, variant_idx, private::HiddenZst) } @@ -81,7 +72,7 @@ impl<'tcx> UniqueTypeId<'tcx> { enum_ty: Ty<'tcx>, variant_idx: VariantIdx, ) -> Self { - debug_assert_eq!(enum_ty, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), enum_ty)); + assert_eq!(enum_ty, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), enum_ty)); UniqueTypeId::VariantStructTypeCppLikeWrapper(enum_ty, variant_idx, private::HiddenZst) } @@ -90,11 +81,8 @@ impl<'tcx> UniqueTypeId<'tcx> { self_type: Ty<'tcx>, implemented_trait: Option>, ) -> Self { - debug_assert_eq!( - self_type, - tcx.normalize_erasing_regions(ParamEnv::reveal_all(), self_type) - ); - debug_assert_eq!( + assert_eq!(self_type, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), self_type)); + assert_eq!( implemented_trait, tcx.normalize_erasing_regions(ParamEnv::reveal_all(), implemented_trait) ); @@ -252,10 +240,7 @@ pub(super) fn build_type_with_children<'ll, 'tcx>( members: impl FnOnce(&CodegenCx<'ll, 'tcx>, &'ll DIType) -> SmallVec<&'ll DIType>, generics: impl FnOnce(&CodegenCx<'ll, 'tcx>) -> SmallVec<&'ll DIType>, ) -> DINodeCreationResult<'ll> { - debug_assert_eq!( - debug_context(cx).type_map.di_node_for_unique_id(stub_info.unique_type_id), - None - ); + assert_eq!(debug_context(cx).type_map.di_node_for_unique_id(stub_info.unique_type_id), None); debug_context(cx).type_map.insert(stub_info.unique_type_id, stub_info.metadata); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index 3486ce4becb46..b23e05182ca1b 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -1,33 +1,21 @@ #![doc = include_str!("doc.md")] -use rustc_codegen_ssa::mir::debuginfo::VariableKind::*; -use rustc_data_structures::unord::UnordMap; - -use self::metadata::{file_metadata, type_di_node}; -use self::metadata::{UNKNOWN_COLUMN_NUMBER, UNKNOWN_LINE_NUMBER}; -use self::namespace::mangled_name_of_instance; -use self::utils::{create_DIArray, is_node_local_to_unit, DIB}; - -use crate::abi::FnAbi; -use crate::builder::Builder; -use crate::common::CodegenCx; -use crate::llvm; -use crate::llvm::debuginfo::{ - DIArray, DIBuilder, DIFile, DIFlags, DILexicalBlock, DILocation, DISPFlags, DIScope, DIType, - DIVariable, -}; -use crate::value::Value; +use std::cell::{OnceCell, RefCell}; +use std::iter; +use std::ops::Range; +use libc::c_uint; use rustc_codegen_ssa::debuginfo::type_names; +use rustc_codegen_ssa::mir::debuginfo::VariableKind::*; use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext, VariableKind}; use rustc_codegen_ssa::traits::*; use rustc_data_structures::sync::Lrc; +use rustc_data_structures::unord::UnordMap; use rustc_hir::def_id::{DefId, DefIdMap}; use rustc_index::IndexVec; use rustc_middle::mir; use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, Instance, ParamEnv, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self, GenericArgsRef, Instance, ParamEnv, Ty, TypeVisitableExt}; use rustc_session::config::{self, DebugInfo}; use rustc_session::Session; use rustc_span::symbol::Symbol; @@ -35,15 +23,22 @@ use rustc_span::{ BytePos, Pos, SourceFile, SourceFileAndLine, SourceFileHash, Span, StableSourceFileId, }; use rustc_target::abi::Size; - -use libc::c_uint; use smallvec::SmallVec; -use std::cell::OnceCell; -use std::cell::RefCell; -use std::iter; -use std::ops::Range; use tracing::debug; +use self::metadata::{file_metadata, type_di_node, UNKNOWN_COLUMN_NUMBER, UNKNOWN_LINE_NUMBER}; +use self::namespace::mangled_name_of_instance; +use self::utils::{create_DIArray, is_node_local_to_unit, DIB}; +use crate::abi::FnAbi; +use crate::builder::Builder; +use crate::common::CodegenCx; +use crate::llvm; +use crate::llvm::debuginfo::{ + DIArray, DIBuilder, DIFile, DIFlags, DILexicalBlock, DILocation, DISPFlags, DIScope, DIType, + DIVariable, +}; +use crate::value::Value; + mod create_scope_map; pub mod gdb; pub mod metadata; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs b/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs index fa61c7dde18b4..5c4f8fe99e3d9 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs @@ -1,13 +1,13 @@ // Namespace Handling. -use super::utils::{debug_context, DIB}; use rustc_codegen_ssa::debuginfo::type_names; +use rustc_hir::def_id::DefId; use rustc_middle::ty::{self, Instance}; +use super::utils::{debug_context, DIB}; use crate::common::CodegenCx; use crate::llvm; use crate::llvm::debuginfo::DIScope; -use rustc_hir::def_id::DefId; pub fn mangled_name_of_instance<'a, 'tcx>( cx: &CodegenCx<'a, 'tcx>, diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs b/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs index 155e7a89fd8b9..d51e15d12e2fc 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs @@ -1,13 +1,12 @@ // Utility Functions. -use super::namespace::item_namespace; -use super::CodegenUnitDebugContext; - use rustc_hir::def_id::DefId; use rustc_middle::ty::layout::{HasParamEnv, LayoutOf}; use rustc_middle::ty::{self, Ty}; use tracing::trace; +use super::namespace::item_namespace; +use super::CodegenUnitDebugContext; use crate::common::CodegenCx; use crate::llvm; use crate::llvm::debuginfo::{DIArray, DIBuilder, DIDescriptor, DIScope}; @@ -81,7 +80,7 @@ pub(crate) fn fat_pointer_kind<'ll, 'tcx>( ty::Dynamic(..) => Some(FatPtrKind::Dyn), ty::Foreign(_) => { // Assert that pointers to foreign types really are thin: - debug_assert_eq!( + assert_eq!( cx.size_of(Ty::new_imm_ptr(cx.tcx, pointee_tail_ty)), cx.size_of(Ty::new_imm_ptr(cx.tcx, cx.tcx.types.u8)) ); diff --git a/compiler/rustc_codegen_llvm/src/declare.rs b/compiler/rustc_codegen_llvm/src/declare.rs index bf86d0e0569b1..c4887464e19c2 100644 --- a/compiler/rustc_codegen_llvm/src/declare.rs +++ b/compiler/rustc_codegen_llvm/src/declare.rs @@ -11,13 +11,6 @@ //! * Use define_* family of methods when you might be defining the Value. //! * When in doubt, define. -use crate::abi::{FnAbi, FnAbiLlvmExt}; -use crate::attributes; -use crate::context::CodegenCx; -use crate::llvm; -use crate::llvm::AttributePlace::Function; -use crate::type_::Type; -use crate::value::Value; use itertools::Itertools; use rustc_codegen_ssa::traits::TypeMembershipMethods; use rustc_data_structures::fx::FxIndexSet; @@ -26,6 +19,13 @@ use rustc_sanitizers::{cfi, kcfi}; use smallvec::SmallVec; use tracing::debug; +use crate::abi::{FnAbi, FnAbiLlvmExt}; +use crate::context::CodegenCx; +use crate::llvm::AttributePlace::Function; +use crate::type_::Type; +use crate::value::Value; +use crate::{attributes, llvm}; + /// Declare a function. /// /// If there’s a value with the same name already declared, the function will diff --git a/compiler/rustc_codegen_llvm/src/errors.rs b/compiler/rustc_codegen_llvm/src/errors.rs index 40ac2f9c8babf..a3957bc52a508 100644 --- a/compiler/rustc_codegen_llvm/src/errors.rs +++ b/compiler/rustc_codegen_llvm/src/errors.rs @@ -2,12 +2,13 @@ use std::borrow::Cow; use std::ffi::CString; use std::path::Path; -use crate::fluent_generated as fluent; use rustc_data_structures::small_c_str::SmallCStr; use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level}; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::Span; +use crate::fluent_generated as fluent; + #[derive(Diagnostic)] #[diag(codegen_llvm_unknown_ctarget_feature_prefix)] #[note] diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 68c3d47e826bf..040de1c7dd715 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -1,17 +1,10 @@ -use crate::abi::{Abi, FnAbi, FnAbiLlvmExt, LlvmType, PassMode}; -use crate::builder::Builder; -use crate::context::CodegenCx; -use crate::llvm; -use crate::type_::Type; -use crate::type_of::LayoutLlvmExt; -use crate::va_arg::emit_va_arg; -use crate::value::Value; +use std::cmp::Ordering; use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh}; use rustc_codegen_ssa::common::{IntPredicate, TypeKind}; use rustc_codegen_ssa::errors::{ExpectedPointerMutability, InvalidMonomorphization}; use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue}; -use rustc_codegen_ssa::mir::place::PlaceRef; +use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue}; use rustc_codegen_ssa::traits::*; use rustc_hir as hir; use rustc_middle::mir::BinOp; @@ -23,7 +16,14 @@ use rustc_target::abi::{self, Align, Float, HasDataLayout, Primitive, Size}; use rustc_target::spec::{HasTargetSpec, PanicStrategy}; use tracing::debug; -use std::cmp::Ordering; +use crate::abi::{Abi, FnAbi, FnAbiLlvmExt, LlvmType, PassMode}; +use crate::builder::Builder; +use crate::context::CodegenCx; +use crate::llvm; +use crate::type_::Type; +use crate::type_of::LayoutLlvmExt; +use crate::va_arg::emit_va_arg; +use crate::value::Value; fn get_simple_intrinsic<'ll>( cx: &CodegenCx<'ll, '_>, @@ -203,6 +203,35 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> { } sym::unlikely => self .call_intrinsic("llvm.expect.i1", &[args[0].immediate(), self.const_bool(false)]), + sym::select_unpredictable => { + let cond = args[0].immediate(); + assert_eq!(args[1].layout, args[2].layout); + let select = |bx: &mut Self, true_val, false_val| { + let result = bx.select(cond, true_val, false_val); + bx.set_unpredictable(&result); + result + }; + match (args[1].val, args[2].val) { + (OperandValue::Ref(true_val), OperandValue::Ref(false_val)) => { + assert!(true_val.llextra.is_none()); + assert!(false_val.llextra.is_none()); + assert_eq!(true_val.align, false_val.align); + let ptr = select(self, true_val.llval, false_val.llval); + let selected = + OperandValue::Ref(PlaceValue::new_sized(ptr, true_val.align)); + selected.store(self, result); + return Ok(()); + } + (OperandValue::Immediate(_), OperandValue::Immediate(_)) + | (OperandValue::Pair(_, _), OperandValue::Pair(_, _)) => { + let true_val = args[1].immediate_or_packed_pair(self); + let false_val = args[2].immediate_or_packed_pair(self); + select(self, true_val, false_val) + } + (OperandValue::ZeroSized, OperandValue::ZeroSized) => return Ok(()), + _ => span_bug!(span, "Incompatible OperandValue for select_unpredictable"), + } + } sym::catch_unwind => { catch_unwind_intrinsic( self, diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index a96993b9aba74..41e9cfd1066b9 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -17,9 +17,13 @@ #![feature(rustdoc_internals)] // tidy-alphabetical-end +use std::any::Any; +use std::ffi::CStr; +use std::io::Write; +use std::mem::ManuallyDrop; + use back::owned_target_machine::OwnedTargetMachine; use back::write::{create_informational_target_machine, create_target_machine}; - use errors::ParseTargetMachineConfig; pub use llvm_util::target_features; use rustc_ast::expand::allocator::AllocatorKind; @@ -28,8 +32,7 @@ use rustc_codegen_ssa::back::write::{ CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn, }; use rustc_codegen_ssa::traits::*; -use rustc_codegen_ssa::ModuleCodegen; -use rustc_codegen_ssa::{CodegenResults, CompiledModule}; +use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen}; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, FatalError}; use rustc_metadata::EncodedMetadata; @@ -40,11 +43,6 @@ use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest}; use rustc_session::Session; use rustc_span::symbol::Symbol; -use std::any::Any; -use std::ffi::CStr; -use std::io::Write; -use std::mem::ManuallyDrop; - mod back { pub mod archive; pub mod lto; @@ -394,9 +392,10 @@ impl CodegenBackend for LlvmCodegenBackend { codegen_results: CodegenResults, outputs: &OutputFilenames, ) -> Result<(), ErrorGuaranteed> { - use crate::back::archive::LlvmArchiveBuilderBuilder; use rustc_codegen_ssa::back::link::link_binary; + use crate::back::archive::LlvmArchiveBuilderBuilder; + // Run the linker on any artifacts that resulted from the LLVM run. // This should produce either a finished executable or library. link_binary(sess, &LlvmArchiveBuilderBuilder, &codegen_results, outputs) diff --git a/compiler/rustc_codegen_llvm/src/llvm/archive_ro.rs b/compiler/rustc_codegen_llvm/src/llvm/archive_ro.rs index 7d94897022345..4dabde55e9897 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/archive_ro.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/archive_ro.rs @@ -1,9 +1,9 @@ //! A wrapper around LLVM's archive (.a) code -use rustc_fs_util::path_to_c_string; use std::path::Path; -use std::slice; -use std::str; +use std::{slice, str}; + +use rustc_fs_util::path_to_c_string; pub struct ArchiveRO { pub raw: &'static mut super::Archive, diff --git a/compiler/rustc_codegen_llvm/src/llvm/diagnostic.rs b/compiler/rustc_codegen_llvm/src/llvm/diagnostic.rs index 73e1b08a3d77a..a4cb5a25d1b36 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/diagnostic.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/diagnostic.rs @@ -1,13 +1,12 @@ //! LLVM diagnostic reports. -pub use self::Diagnostic::*; -pub use self::OptimizationDiagnosticKind::*; - -use crate::value::Value; use libc::c_uint; +use rustc_span::InnerSpan; +pub use self::Diagnostic::*; +pub use self::OptimizationDiagnosticKind::*; use super::{DiagnosticInfo, SMDiagnostic}; -use rustc_span::InnerSpan; +use crate::value::Value; #[derive(Copy, Clone, Debug)] pub enum OptimizationDiagnosticKind { diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index ae46200d3f554..80b13c0e1d4b9 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -1,18 +1,16 @@ #![allow(non_camel_case_types)] #![allow(non_upper_case_globals)] +use std::marker::PhantomData; + +use libc::{c_char, c_int, c_uint, c_ulonglong, c_void, size_t}; + use super::debuginfo::{ DIArray, DIBasicType, DIBuilder, DICompositeType, DIDerivedType, DIDescriptor, DIEnumerator, DIFile, DIFlags, DIGlobalVariableExpression, DILexicalBlock, DILocation, DINameSpace, DISPFlags, DIScope, DISubprogram, DISubrange, DITemplateTypeParameter, DIType, DIVariable, DebugEmissionKind, DebugNameTableKind, }; - -use libc::{c_char, c_int, c_uint, size_t}; -use libc::{c_ulonglong, c_void}; - -use std::marker::PhantomData; - use super::RustString; pub type Bool = c_uint; @@ -305,7 +303,6 @@ pub enum TypeKind { Pointer = 12, Vector = 13, Metadata = 14, - X86_MMX = 15, Token = 16, ScalableVector = 17, BFloat = 18, @@ -330,7 +327,6 @@ impl TypeKind { TypeKind::Pointer => rustc_codegen_ssa::common::TypeKind::Pointer, TypeKind::Vector => rustc_codegen_ssa::common::TypeKind::Vector, TypeKind::Metadata => rustc_codegen_ssa::common::TypeKind::Metadata, - TypeKind::X86_MMX => rustc_codegen_ssa::common::TypeKind::X86_MMX, TypeKind::Token => rustc_codegen_ssa::common::TypeKind::Token, TypeKind::ScalableVector => rustc_codegen_ssa::common::TypeKind::ScalableVector, TypeKind::BFloat => rustc_codegen_ssa::common::TypeKind::BFloat, @@ -430,6 +426,7 @@ pub enum MetadataType { MD_nontemporal = 9, MD_mem_parallel_loop_access = 10, MD_nonnull = 11, + MD_unpredictable = 15, MD_align = 17, MD_type = 19, MD_vcall_visibility = 28, @@ -699,9 +696,10 @@ pub type DiagnosticHandlerTy = unsafe extern "C" fn(&DiagnosticInfo, *mut c_void pub type InlineAsmDiagHandlerTy = unsafe extern "C" fn(&SMDiagnostic, *const c_void, c_uint); pub mod debuginfo { - use super::{InvariantOpaque, Metadata}; use bitflags::bitflags; + use super::{InvariantOpaque, Metadata}; + #[repr(C)] pub struct DIBuilder<'a>(InvariantOpaque<'a>); diff --git a/compiler/rustc_codegen_llvm/src/llvm/mod.rs b/compiler/rustc_codegen_llvm/src/llvm/mod.rs index 6ab1eea959761..72691907c0d91 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/mod.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/mod.rs @@ -1,5 +1,15 @@ #![allow(non_snake_case)] +use std::cell::RefCell; +use std::ffi::{CStr, CString}; +use std::str::FromStr; +use std::string::FromUtf8Error; + +use libc::c_uint; +use rustc_data_structures::small_c_str::SmallCStr; +use rustc_llvm::RustString; +use rustc_target::abi::Align; + pub use self::AtomicRmwBinOp::*; pub use self::CallConv::*; pub use self::CodeGenOptSize::*; @@ -8,15 +18,6 @@ pub use self::Linkage::*; pub use self::MetadataType::*; pub use self::RealPredicate::*; -use libc::c_uint; -use rustc_data_structures::small_c_str::SmallCStr; -use rustc_llvm::RustString; -use rustc_target::abi::Align; -use std::cell::RefCell; -use std::ffi::{CStr, CString}; -use std::str::FromStr; -use std::string::FromUtf8Error; - pub mod archive_ro; pub mod diagnostic; mod ffi; diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index 4d56d1d3b1afa..af8a9be1ccbfd 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -1,9 +1,9 @@ -use crate::back::write::create_informational_target_machine; -use crate::errors::{ - FixedX18InvalidArch, InvalidTargetFeaturePrefix, PossibleFeature, TargetFeatureDisableOrEnable, - UnknownCTargetFeature, UnknownCTargetFeaturePrefix, UnstableCTargetFeature, -}; -use crate::llvm; +use std::ffi::{c_char, c_void, CStr, CString}; +use std::fmt::Write; +use std::path::Path; +use std::sync::Once; +use std::{ptr, slice, str}; + use libc::c_int; use rustc_codegen_ssa::base::wants_wasm_eh; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; @@ -16,13 +16,12 @@ use rustc_span::symbol::Symbol; use rustc_target::spec::{MergeFunctions, PanicStrategy}; use rustc_target::target_features::{RUSTC_SPECIAL_FEATURES, RUSTC_SPECIFIC_FEATURES}; -use std::ffi::{c_char, c_void, CStr, CString}; -use std::fmt::Write; -use std::path::Path; -use std::ptr; -use std::slice; -use std::str; -use std::sync::Once; +use crate::back::write::create_informational_target_machine; +use crate::errors::{ + FixedX18InvalidArch, InvalidTargetFeaturePrefix, PossibleFeature, TargetFeatureDisableOrEnable, + UnknownCTargetFeature, UnknownCTargetFeaturePrefix, UnstableCTargetFeature, +}; +use crate::llvm; static INIT: Once = Once::new(); @@ -647,6 +646,22 @@ pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec, which didn't make + // it into a released version of LLVM yet. + // + // This doesn't use the "implicit target feature" system because it is only + // used for function attributes in other targets, which fixes this bug as + // well on the function attribute level. + if sess.target.families.contains(&"wasm".into()) { + if features.iter().any(|f| f == "+relaxed-simd") + && !features.iter().any(|f| f == "+simd128") + { + features.push("+simd128".into()); + } + } + if diagnostics && let Some(f) = check_tied_features(sess, &featsmap) { sess.dcx().emit_err(TargetFeatureDisableOrEnable { features: f, diff --git a/compiler/rustc_codegen_llvm/src/mono_item.rs b/compiler/rustc_codegen_llvm/src/mono_item.rs index 282a186be99ac..d59eaae1ba9b8 100644 --- a/compiler/rustc_codegen_llvm/src/mono_item.rs +++ b/compiler/rustc_codegen_llvm/src/mono_item.rs @@ -1,9 +1,3 @@ -use crate::attributes; -use crate::base; -use crate::context::CodegenCx; -use crate::errors::SymbolAlreadyDefined; -use crate::llvm; -use crate::type_of::LayoutLlvmExt; use rustc_codegen_ssa::traits::*; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; @@ -15,6 +9,11 @@ use rustc_session::config::CrateType; use rustc_target::spec::RelocModel; use tracing::debug; +use crate::context::CodegenCx; +use crate::errors::SymbolAlreadyDefined; +use crate::type_of::LayoutLlvmExt; +use crate::{attributes, base, llvm}; + impl<'tcx> PreDefineMethods<'tcx> for CodegenCx<'_, 'tcx> { fn predefine_static( &self, diff --git a/compiler/rustc_codegen_llvm/src/type_.rs b/compiler/rustc_codegen_llvm/src/type_.rs index f1141c57cedd7..7e3ab19898d36 100644 --- a/compiler/rustc_codegen_llvm/src/type_.rs +++ b/compiler/rustc_codegen_llvm/src/type_.rs @@ -1,12 +1,6 @@ -pub use crate::llvm::Type; +use std::{fmt, ptr}; -use crate::abi::{FnAbiLlvmExt, LlvmType}; -use crate::common; -use crate::context::CodegenCx; -use crate::llvm; -use crate::llvm::{Bool, False, True}; -use crate::type_of::LayoutLlvmExt; -use crate::value::Value; +use libc::{c_char, c_uint}; use rustc_codegen_ssa::common::TypeKind; use rustc_codegen_ssa::traits::*; use rustc_data_structures::small_c_str::SmallCStr; @@ -16,10 +10,13 @@ use rustc_middle::ty::{self, Ty}; use rustc_target::abi::call::{CastTarget, FnAbi, Reg}; use rustc_target::abi::{AddressSpace, Align, Integer, Size}; -use std::fmt; -use std::ptr; - -use libc::{c_char, c_uint}; +use crate::abi::{FnAbiLlvmExt, LlvmType}; +use crate::context::CodegenCx; +pub use crate::llvm::Type; +use crate::llvm::{Bool, False, True}; +use crate::type_of::LayoutLlvmExt; +use crate::value::Value; +use crate::{common, llvm}; impl PartialEq for Type { fn eq(&self, other: &Self) -> bool { diff --git a/compiler/rustc_codegen_llvm/src/type_of.rs b/compiler/rustc_codegen_llvm/src/type_of.rs index 7be941ed74980..4755fa08afb7c 100644 --- a/compiler/rustc_codegen_llvm/src/type_of.rs +++ b/compiler/rustc_codegen_llvm/src/type_of.rs @@ -1,16 +1,15 @@ -use crate::common::*; -use crate::type_::Type; +use std::fmt::Write; + use rustc_codegen_ssa::traits::*; use rustc_middle::bug; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; use rustc_middle::ty::{self, CoroutineArgsExt, Ty, TypeVisitableExt}; -use rustc_target::abi::{Abi, Align, FieldsShape}; -use rustc_target::abi::{Float, Int, Pointer}; -use rustc_target::abi::{Scalar, Size, Variants}; +use rustc_target::abi::{Abi, Align, FieldsShape, Float, Int, Pointer, Scalar, Size, Variants}; use tracing::debug; -use std::fmt::Write; +use crate::common::*; +use crate::type_::Type; fn uncached_llvm_type<'a, 'tcx>( cx: &CodegenCx<'a, 'tcx>, diff --git a/compiler/rustc_codegen_llvm/src/va_arg.rs b/compiler/rustc_codegen_llvm/src/va_arg.rs index 220bb77d3fda3..94e77c5bd70d6 100644 --- a/compiler/rustc_codegen_llvm/src/va_arg.rs +++ b/compiler/rustc_codegen_llvm/src/va_arg.rs @@ -1,16 +1,15 @@ -use crate::builder::Builder; -use crate::type_::Type; -use crate::type_of::LayoutLlvmExt; -use crate::value::Value; +use rustc_codegen_ssa::common::IntPredicate; use rustc_codegen_ssa::mir::operand::OperandRef; -use rustc_codegen_ssa::{ - common::IntPredicate, - traits::{BaseTypeMethods, BuilderMethods, ConstMethods}, -}; +use rustc_codegen_ssa::traits::{BaseTypeMethods, BuilderMethods, ConstMethods}; use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf}; use rustc_middle::ty::Ty; use rustc_target::abi::{Align, Endian, HasDataLayout, Size}; +use crate::builder::Builder; +use crate::type_::Type; +use crate::type_of::LayoutLlvmExt; +use crate::value::Value; + fn round_pointer_up_to_alignment<'ll>( bx: &mut Builder<'_, 'll, '_>, addr: &'ll Value, diff --git a/compiler/rustc_codegen_llvm/src/value.rs b/compiler/rustc_codegen_llvm/src/value.rs index 1338a229566c8..6295b0de35649 100644 --- a/compiler/rustc_codegen_llvm/src/value.rs +++ b/compiler/rustc_codegen_llvm/src/value.rs @@ -1,10 +1,8 @@ -pub use crate::llvm::Value; +use std::hash::{Hash, Hasher}; +use std::{fmt, ptr}; use crate::llvm; - -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::ptr; +pub use crate::llvm::Value; impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { diff --git a/compiler/rustc_codegen_ssa/Cargo.toml b/compiler/rustc_codegen_ssa/Cargo.toml index f7b5b0f310b67..2767ad5ec9ce6 100644 --- a/compiler/rustc_codegen_ssa/Cargo.toml +++ b/compiler/rustc_codegen_ssa/Cargo.toml @@ -41,7 +41,7 @@ tempfile = "3.2" thin-vec = "0.2.12" thorin-dwp = "0.7" tracing = "0.1" -wasm-encoder = "0.200.0" +wasm-encoder = "0.210.0" # tidy-alphabetical-end [target.'cfg(unix)'.dependencies] @@ -50,7 +50,7 @@ libc = "0.2.50" # tidy-alphabetical-end [dependencies.object] -version = "0.32.1" +version = "0.36.2" default-features = false features = ["read_core", "elf", "macho", "pe", "xcoff", "unaligned", "archive", "write", "wasm"] diff --git a/compiler/rustc_codegen_ssa/messages.ftl b/compiler/rustc_codegen_ssa/messages.ftl index 000fe2e3ce0f5..57d789aef80ca 100644 --- a/compiler/rustc_codegen_ssa/messages.ftl +++ b/compiler/rustc_codegen_ssa/messages.ftl @@ -4,8 +4,7 @@ codegen_ssa_add_native_library = failed to add native library {$library_path}: { codegen_ssa_apple_sdk_error_sdk_path = failed to get {$sdk_name} SDK path: {$error} -codegen_ssa_archive_build_failure = - failed to build archive: {$error} +codegen_ssa_archive_build_failure = failed to build archive at `{$path}`: {$error} codegen_ssa_atomic_compare_exchange = Atomic compare-exchange intrinsic missing failure memory ordering @@ -198,7 +197,7 @@ codegen_ssa_read_file = failed to read file: {$message} codegen_ssa_repair_vs_build_tools = the Visual Studio build tools may need to be repaired using the Visual Studio installer -codegen_ssa_rlib_archive_build_failure = failed to build archive from rlib: {$error} +codegen_ssa_rlib_archive_build_failure = failed to build archive from rlib at `{$path}`: {$error} codegen_ssa_rlib_incompatible_dependency_formats = `{$ty1}` and `{$ty2}` do not have equivalent dependency formats (`{$list1}` vs `{$list2}`) diff --git a/compiler/rustc_codegen_ssa/src/assert_module_sources.rs b/compiler/rustc_codegen_ssa/src/assert_module_sources.rs index 6e7d736eb29d3..11bcd727501c9 100644 --- a/compiler/rustc_codegen_ssa/src/assert_module_sources.rs +++ b/compiler/rustc_codegen_ssa/src/assert_module_sources.rs @@ -23,10 +23,11 @@ //! allows for doing a more fine-grained check to see if pre- or post-lto data //! was re-used. -use crate::errors; +use std::borrow::Cow; +use std::fmt; + use rustc_ast as ast; -use rustc_data_structures::unord::UnordMap; -use rustc_data_structures::unord::UnordSet; +use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::{DiagArgValue, IntoDiagArg}; use rustc_hir::def_id::LOCAL_CRATE; use rustc_middle::mir::mono::CodegenUnitNameBuilder; @@ -34,11 +35,11 @@ use rustc_middle::ty::TyCtxt; use rustc_session::Session; use rustc_span::symbol::sym; use rustc_span::{Span, Symbol}; -use std::borrow::Cow; -use std::fmt; use thin_vec::ThinVec; use tracing::debug; +use crate::errors; + #[allow(missing_docs)] pub fn assert_module_sources(tcx: TyCtxt<'_>, set_reuse: &dyn Fn(&mut CguReuseTracker)) { tcx.dep_graph.with_ignore(|| { diff --git a/compiler/rustc_codegen_ssa/src/back/archive.rs b/compiler/rustc_codegen_ssa/src/back/archive.rs index ae649cd77c420..4f93b7b23c6e6 100644 --- a/compiler/rustc_codegen_ssa/src/back/archive.rs +++ b/compiler/rustc_codegen_ssa/src/back/archive.rs @@ -1,22 +1,20 @@ -use rustc_data_structures::fx::FxIndexSet; -use rustc_data_structures::memmap::Mmap; -use rustc_session::cstore::DllImport; -use rustc_session::Session; -use rustc_span::symbol::Symbol; - -use super::metadata::search_for_section; +use std::error::Error; +use std::fs::{self, File}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; use ar_archive_writer::{write_archive_to_stream, ArchiveKind, NewArchiveMember}; pub use ar_archive_writer::{ObjectReader, DEFAULT_OBJECT_READER}; use object::read::archive::ArchiveFile; use object::read::macho::FatArch; +use rustc_data_structures::fx::FxIndexSet; +use rustc_data_structures::memmap::Mmap; +use rustc_session::cstore::DllImport; +use rustc_session::Session; +use rustc_span::symbol::Symbol; use tempfile::Builder as TempFileBuilder; -use std::error::Error; -use std::fs::{self, File}; -use std::io::{self, Write}; -use std::path::{Path, PathBuf}; - +use super::metadata::search_for_section; // Re-exporting for rustc_codegen_llvm::back::archive pub use crate::errors::{ArchiveBuildFailure, ExtractBundledLibsError, UnknownArchiveKind}; @@ -110,13 +108,11 @@ impl<'a> ArArchiveBuilder<'a> { } fn try_filter_fat_archs( - archs: object::read::Result<&[impl FatArch]>, + archs: &[impl FatArch], target_arch: object::Architecture, archive_path: &Path, archive_map_data: &[u8], ) -> io::Result> { - let archs = archs.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; - let desired = match archs.iter().find(|a| a.architecture() == target_arch) { Some(a) => a, None => return Ok(None), @@ -146,17 +142,15 @@ pub fn try_extract_macho_fat_archive( _ => return Ok(None), }; - match object::macho::FatHeader::parse(&*archive_map) { - Ok(h) if h.magic.get(object::endian::BigEndian) == object::macho::FAT_MAGIC => { - let archs = object::macho::FatHeader::parse_arch32(&*archive_map); - try_filter_fat_archs(archs, target_arch, archive_path, &*archive_map) - } - Ok(h) if h.magic.get(object::endian::BigEndian) == object::macho::FAT_MAGIC_64 => { - let archs = object::macho::FatHeader::parse_arch64(&*archive_map); - try_filter_fat_archs(archs, target_arch, archive_path, &*archive_map) - } + if let Ok(h) = object::read::macho::MachOFatFile32::parse(&*archive_map) { + let archs = h.arches(); + try_filter_fat_archs(archs, target_arch, archive_path, &*archive_map) + } else if let Ok(h) = object::read::macho::MachOFatFile64::parse(&*archive_map) { + let archs = h.arches(); + try_filter_fat_archs(archs, target_arch, archive_path, &*archive_map) + } else { // Not a FatHeader at all, just return None. - _ => Ok(None), + Ok(None) } } @@ -213,7 +207,9 @@ impl<'a> ArchiveBuilder for ArArchiveBuilder<'a> { let sess = self.sess; match self.build_inner(output) { Ok(any_members) => any_members, - Err(e) => sess.dcx().emit_fatal(ArchiveBuildFailure { error: e }), + Err(error) => { + sess.dcx().emit_fatal(ArchiveBuildFailure { path: output.to_owned(), error }) + } } } } @@ -224,11 +220,7 @@ impl<'a> ArArchiveBuilder<'a> { "gnu" => ArchiveKind::Gnu, "bsd" => ArchiveKind::Bsd, "darwin" => ArchiveKind::Darwin, - "coff" => { - // FIXME: ar_archive_writer doesn't support COFF archives yet. - // https://github.com/rust-lang/ar_archive_writer/issues/9 - ArchiveKind::Gnu - } + "coff" => ArchiveKind::Coff, "aix_big" => ArchiveKind::AixBig, kind => { self.sess.dcx().emit_fatal(UnknownArchiveKind { kind }); diff --git a/compiler/rustc_codegen_ssa/src/back/command.rs b/compiler/rustc_codegen_ssa/src/back/command.rs index 3a89be89951b8..95c4af2e59ea9 100644 --- a/compiler/rustc_codegen_ssa/src/back/command.rs +++ b/compiler/rustc_codegen_ssa/src/back/command.rs @@ -2,10 +2,8 @@ //! read the arguments that are built up. use std::ffi::{OsStr, OsString}; -use std::fmt; -use std::io; -use std::mem; use std::process::{self, Output}; +use std::{fmt, io, mem}; use rustc_target::spec::LldFlavor; diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 8c582fac0d824..653895380bebc 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -1,3 +1,15 @@ +use std::collections::BTreeSet; +use std::ffi::OsString; +use std::fs::{read, File, OpenOptions}; +use std::io::{BufWriter, Write}; +use std::ops::Deref; +use std::path::{Path, PathBuf}; +use std::process::{ExitStatus, Output, Stdio}; +use std::{env, fmt, fs, io, mem, str}; + +use cc::windows_registry; +use itertools::Itertools; +use regex::Regex; use rustc_arena::TypedArena; use rustc_ast::CRATE_NODE_ID; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; @@ -12,9 +24,10 @@ use rustc_middle::bug; use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile; use rustc_middle::middle::dependency_format::Linkage; use rustc_middle::middle::exported_symbols::SymbolExportKind; -use rustc_session::config::LinkerFeaturesCli; -use rustc_session::config::{self, CFGuard, CrateType, DebugInfo, OutFileName, Strip}; -use rustc_session::config::{OutputFilenames, OutputType, PrintKind, SplitDwarfKind}; +use rustc_session::config::{ + self, CFGuard, CrateType, DebugInfo, LinkerFeaturesCli, OutFileName, OutputFilenames, + OutputType, PrintKind, SplitDwarfKind, Strip, +}; use rustc_session::cstore::DllImport; use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename}; use rustc_session::search_paths::PathKind; @@ -24,11 +37,13 @@ use rustc_session::utils::NativeLibKind; use rustc_session::{filesearch, Session}; use rustc_span::symbol::Symbol; use rustc_target::spec::crt_objects::CrtObjects; -use rustc_target::spec::LinkSelfContainedDefault; -use rustc_target::spec::LinkerFlavorCli; -use rustc_target::spec::{Cc, LinkOutputKind, LinkerFlavor, Lld, PanicStrategy}; -use rustc_target::spec::{LinkSelfContainedComponents, LinkerFeatures}; -use rustc_target::spec::{RelocModel, RelroLevel, SanitizerSet, SplitDebuginfo}; +use rustc_target::spec::{ + Cc, LinkOutputKind, LinkSelfContainedComponents, LinkSelfContainedDefault, LinkerFeatures, + LinkerFlavor, LinkerFlavorCli, Lld, PanicStrategy, RelocModel, RelroLevel, SanitizerSet, + SplitDebuginfo, +}; +use tempfile::Builder as TempFileBuilder; +use tracing::{debug, info, warn}; use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder}; use super::command::Command; @@ -39,21 +54,6 @@ use crate::{ errors, looks_like_rust_object_file, CodegenResults, CompiledModule, CrateInfo, NativeLib, }; -use cc::windows_registry; -use regex::Regex; -use tempfile::Builder as TempFileBuilder; - -use itertools::Itertools; -use std::collections::BTreeSet; -use std::ffi::OsString; -use std::fs::{read, File, OpenOptions}; -use std::io::{BufWriter, Write}; -use std::ops::Deref; -use std::path::{Path, PathBuf}; -use std::process::{ExitStatus, Output, Stdio}; -use std::{env, fmt, fs, io, mem, str}; -use tracing::{debug, info, warn}; - pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) { if let Err(e) = fs::remove_file(path) { if e.kind() != io::ErrorKind::NotFound { @@ -700,7 +700,7 @@ fn link_dwarf_object(sess: &Session, cg_results: &CodegenResults, executable_out .truncate(true) .open(dwp_out_filename)?, ); - let mut output_stream = object::write::StreamingBuffer::new(output_stream); + let mut output_stream = thorin::object::write::StreamingBuffer::new(output_stream); package.finish()?.emit(&mut output_stream)?; output_stream.result()?; output_stream.into_inner().flush()?; @@ -2065,17 +2065,61 @@ fn add_local_crate_metadata_objects( } /// Add sysroot and other globally set directories to the directory search list. -fn add_library_search_dirs(cmd: &mut dyn Linker, sess: &Session, self_contained: bool) { - // The default library location, we need this to find the runtime. - // The location of crates will be determined as needed. - let lib_path = sess.target_filesearch(PathKind::All).get_lib_path(); - cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path)); +fn add_library_search_dirs( + cmd: &mut dyn Linker, + sess: &Session, + self_contained_components: LinkSelfContainedComponents, + apple_sdk_root: Option<&Path>, +) { + if !sess.opts.unstable_opts.link_native_libraries { + return; + } - // Special directory with libraries used only in self-contained linkage mode - if self_contained { - let lib_path = sess.target_filesearch(PathKind::All).get_self_contained_lib_path(); + // Library search paths explicitly supplied by user (`-L` on the command line). + for search_path in sess.target_filesearch(PathKind::Native).cli_search_paths() { + cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir)); + } + for search_path in sess.target_filesearch(PathKind::Framework).cli_search_paths() { + // Contrary to the `-L` docs only framework-specific paths are considered here. + if search_path.kind != PathKind::All { + cmd.framework_path(&search_path.dir); + } + } + + // The toolchain ships some native library components and self-contained linking was enabled. + // Add the self-contained library directory to search paths. + if self_contained_components.intersects( + LinkSelfContainedComponents::LIBC + | LinkSelfContainedComponents::UNWIND + | LinkSelfContainedComponents::MINGW, + ) { + let lib_path = sess.target_filesearch(PathKind::Native).get_self_contained_lib_path(); + cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path)); + } + + // Toolchains for some targets may ship `libunwind.a`, but place it into the main sysroot + // library directory instead of the self-contained directories. + // Sanitizer libraries have the same issue and are also linked by name on Apple targets. + // The targets here should be in sync with `copy_third_party_objects` in bootstrap. + // FIXME: implement `-Clink-self-contained=+/-unwind,+/-sanitizers`, move the shipped libunwind + // and sanitizers to self-contained directory, and stop adding this search path. + if sess.target.vendor == "fortanix" + || sess.target.os == "linux" + || sess.target.os == "fuchsia" + || sess.target.is_like_osx && !sess.opts.unstable_opts.sanitizer.is_empty() + { + let lib_path = sess.target_filesearch(PathKind::Native).get_lib_path(); cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path)); } + + // Mac Catalyst uses the macOS SDK, but to link to iOS-specific frameworks + // we must have the support library stubs in the library search path (#121430). + if let Some(sdk_root) = apple_sdk_root + && sess.target.llvm_target.contains("macabi") + { + cmd.include_path(&sdk_root.join("System/iOSSupport/usr/lib")); + cmd.framework_path(&sdk_root.join("System/iOSSupport/System/Library/Frameworks")); + } } /// Add options making relocation sections in the produced ELF files read-only @@ -2367,7 +2411,7 @@ fn add_order_independent_options( // Take care of the flavors and CLI options requesting the `lld` linker. add_lld_args(cmd, sess, flavor, self_contained_components); - add_apple_sdk(cmd, sess, flavor); + let apple_sdk_root = add_apple_sdk(cmd, sess, flavor); add_link_script(cmd, sess, tmpdir, crate_type); @@ -2423,7 +2467,7 @@ fn add_order_independent_options( cmd.linker_plugin_lto(); - add_library_search_dirs(cmd, sess, self_contained_components.are_any_components_enabled()); + add_library_search_dirs(cmd, sess, self_contained_components, apple_sdk_root.as_deref()); cmd.output_filename(out_filename); @@ -2637,19 +2681,6 @@ fn add_local_native_libraries( tmpdir: &Path, link_output_kind: LinkOutputKind, ) { - if sess.opts.unstable_opts.link_native_libraries { - // User-supplied library search paths (-L on the command line). These are the same paths - // used to find Rust crates, so some of them may have been added already by the previous - // crate linking code. This only allows them to be found at compile time so it is still - // entirely up to outside forces to make sure that library can be found at runtime. - for search_path in sess.target_filesearch(PathKind::All).search_paths() { - match search_path.kind { - PathKind::Framework => cmd.framework_path(&search_path.dir), - _ => cmd.include_path(&fix_windows_verbatim_for_gcc(&search_path.dir)), - } - } - } - // All static and dynamic native library dependencies are linked to the local crate. let link_static = true; let link_dynamic = true; @@ -2911,7 +2942,8 @@ fn add_static_crate( false }), ) { - sess.dcx().emit_fatal(errors::RlibArchiveBuildFailure { error }); + sess.dcx() + .emit_fatal(errors::RlibArchiveBuildFailure { path: cratepath.clone(), error }); } if archive.build(&dst) { link_upstream(&dst); @@ -2943,7 +2975,7 @@ pub(crate) fn are_upstream_rust_objects_already_included(sess: &Session) -> bool } } -fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) { +fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) -> Option { let arch = &sess.target.arch; let os = &sess.target.os; let llvm_target = &sess.target.llvm_target; @@ -2951,11 +2983,11 @@ fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) { || !matches!(os.as_ref(), "ios" | "tvos" | "watchos" | "visionos" | "macos") || !matches!(flavor, LinkerFlavor::Darwin(..)) { - return; + return None; } if os == "macos" && !matches!(flavor, LinkerFlavor::Darwin(Cc::No, _)) { - return; + return None; } let sdk_name = match (arch.as_ref(), os.as_ref()) { @@ -2979,14 +3011,14 @@ fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) { (_, "macos") => "macosx", _ => { sess.dcx().emit_err(errors::UnsupportedArch { arch, os }); - return; + return None; } }; let sdk_root = match get_apple_sdk_root(sdk_name) { Ok(s) => s, Err(e) => { sess.dcx().emit_err(e); - return; + return None; } }; @@ -3006,16 +3038,7 @@ fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) { _ => unreachable!(), } - if llvm_target.contains("macabi") { - // Mac Catalyst uses the macOS SDK, but to link to iOS-specific - // frameworks, we must have the support library stubs in the library - // search path. - - // The flags are called `-L` and `-F` both in Clang, ld64 and ldd. - let sdk_root = Path::new(&sdk_root); - cmd.include_path(&sdk_root.join("System/iOSSupport/usr/lib")); - cmd.framework_path(&sdk_root.join("System/iOSSupport/System/Library/Frameworks")); - } + Some(sdk_root.into()) } fn get_apple_sdk_root(sdk_name: &str) -> Result> { diff --git a/compiler/rustc_codegen_ssa/src/back/linker.rs b/compiler/rustc_codegen_ssa/src/back/linker.rs index dd134ebbe6b18..febeb7093a332 100644 --- a/compiler/rustc_codegen_ssa/src/back/linker.rs +++ b/compiler/rustc_codegen_ssa/src/back/linker.rs @@ -1,8 +1,3 @@ -use super::command::Command; -use super::symbol_export; -use crate::errors; -use rustc_span::symbol::sym; - use std::ffi::{OsStr, OsString}; use std::fs::{self, File}; use std::io::prelude::*; @@ -10,6 +5,7 @@ use std::io::{self, BufWriter}; use std::path::{Path, PathBuf}; use std::{env, iter, mem, str}; +use cc::windows_registry; use rustc_hir::def_id::{CrateNum, LOCAL_CRATE}; use rustc_metadata::find_native_static_library; use rustc_middle::bug; @@ -19,11 +15,14 @@ use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo, S use rustc_middle::ty::TyCtxt; use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel, Strip}; use rustc_session::Session; +use rustc_span::symbol::sym; use rustc_target::spec::{Cc, LinkOutputKind, LinkerFlavor, Lld}; - -use cc::windows_registry; use tracing::{debug, warn}; +use super::command::Command; +use super::symbol_export; +use crate::errors; + /// Disables non-English messages from localized linkers. /// Such messages may cause issues with text encoding on Windows (#35785) /// and prevent inspection of linker output in case of errors, which we occasionally do. diff --git a/compiler/rustc_codegen_ssa/src/back/lto.rs b/compiler/rustc_codegen_ssa/src/back/lto.rs index 5291cad148e26..8b6f6b5a220a4 100644 --- a/compiler/rustc_codegen_ssa/src/back/lto.rs +++ b/compiler/rustc_codegen_ssa/src/back/lto.rs @@ -1,12 +1,12 @@ -use super::write::CodegenContext; -use crate::traits::*; -use crate::ModuleCodegen; +use std::ffi::CString; +use std::sync::Arc; use rustc_data_structures::memmap::Mmap; use rustc_errors::FatalError; -use std::ffi::CString; -use std::sync::Arc; +use super::write::CodegenContext; +use crate::traits::*; +use crate::ModuleCodegen; pub struct ThinModule { pub shared: Arc>, diff --git a/compiler/rustc_codegen_ssa/src/back/metadata.rs b/compiler/rustc_codegen_ssa/src/back/metadata.rs index 264a98844ad67..19394029c949a 100644 --- a/compiler/rustc_codegen_ssa/src/back/metadata.rs +++ b/compiler/rustc_codegen_ssa/src/back/metadata.rs @@ -10,7 +10,6 @@ use object::{ elf, pe, xcoff, Architecture, BinaryFormat, Endianness, FileFlags, Object, ObjectSection, ObjectSymbol, SectionFlags, SectionKind, SubArchitecture, SymbolFlags, SymbolKind, SymbolScope, }; - use rustc_data_structures::memmap::Mmap; use rustc_data_structures::owned_slice::{try_slice_owned, OwnedSlice}; use rustc_metadata::creader::MetadataLoader; @@ -656,7 +655,13 @@ pub fn create_metadata_file_for_wasm(sess: &Session, data: &[u8], section_name: imports.import( "env", "__linear_memory", - wasm_encoder::MemoryType { minimum: 0, maximum: None, memory64: true, shared: false }, + wasm_encoder::MemoryType { + minimum: 0, + maximum: None, + memory64: true, + shared: false, + page_size_log2: None, + }, ); } diff --git a/compiler/rustc_codegen_ssa/src/back/rpath.rs b/compiler/rustc_codegen_ssa/src/back/rpath.rs index 82070d4453b28..42f8c3114ff50 100644 --- a/compiler/rustc_codegen_ssa/src/back/rpath.rs +++ b/compiler/rustc_codegen_ssa/src/back/rpath.rs @@ -1,8 +1,9 @@ +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + use pathdiff::diff_paths; use rustc_data_structures::fx::FxHashSet; use rustc_fs_util::try_canonicalize; -use std::ffi::OsString; -use std::path::{Path, PathBuf}; use tracing::debug; pub struct RPathConfig<'a> { diff --git a/compiler/rustc_codegen_ssa/src/back/rpath/tests.rs b/compiler/rustc_codegen_ssa/src/back/rpath/tests.rs index c620e92db1f08..0de0b8a52b192 100644 --- a/compiler/rustc_codegen_ssa/src/back/rpath/tests.rs +++ b/compiler/rustc_codegen_ssa/src/back/rpath/tests.rs @@ -1,8 +1,8 @@ -use super::RPathConfig; -use super::{get_rpath_relative_to_output, minimize_rpaths, rpaths_to_flags}; use std::ffi::OsString; use std::path::{Path, PathBuf}; +use super::{get_rpath_relative_to_output, minimize_rpaths, rpaths_to_flags, RPathConfig}; + #[test] fn test_rpaths_to_flags() { let flags = rpaths_to_flags(vec!["path1".into(), "path2".into()]); diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs index 6abe4fa1c3809..d2f11d48140c9 100644 --- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs +++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs @@ -1,5 +1,3 @@ -use crate::base::allocator_kind_for_codegen; - use std::collections::hash_map::Entry::*; use rustc_ast::expand::allocator::{ALLOCATOR_METHODS, NO_ALLOC_SHIM_IS_UNSTABLE}; @@ -12,14 +10,14 @@ use rustc_middle::middle::exported_symbols::{ metadata_symbol_name, ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel, }; use rustc_middle::query::LocalCrate; -use rustc_middle::ty::Instance; -use rustc_middle::ty::{self, SymbolName, TyCtxt}; -use rustc_middle::ty::{GenericArgKind, GenericArgsRef}; +use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, Instance, SymbolName, TyCtxt}; use rustc_middle::util::Providers; use rustc_session::config::{CrateType, OomStrategy}; use rustc_target::spec::{SanitizerSet, TlsModel}; use tracing::debug; +use crate::base::allocator_kind_for_codegen; + pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel { crates_export_threshold(tcx.crate_types()) } @@ -352,7 +350,7 @@ fn exported_symbols_provider_local( } MonoItem::Fn(Instance { def: InstanceKind::DropGlue(def_id, Some(ty)), args }) => { // A little sanity-check - debug_assert_eq!( + assert_eq!( args.non_erasable_generics(tcx, def_id).next(), Some(GenericArgKind::Type(ty)) ); @@ -370,7 +368,7 @@ fn exported_symbols_provider_local( args, }) => { // A little sanity-check - debug_assert_eq!( + assert_eq!( args.non_erasable_generics(tcx, def_id).next(), Some(GenericArgKind::Type(ty)) ); @@ -462,7 +460,7 @@ fn upstream_monomorphizations_for_provider( tcx: TyCtxt<'_>, def_id: DefId, ) -> Option<&UnordMap, CrateNum>> { - debug_assert!(!def_id.is_local()); + assert!(!def_id.is_local()); tcx.upstream_monomorphizations(()).get(&def_id) } diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 0e48eee3dd57b..bea12747a5199 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -1,12 +1,10 @@ -use super::link::{self, ensure_removed}; -use super::lto::{self, SerializedModule}; -use super::symbol_export::symbol_name_for_instance_in_crate; +use std::any::Any; +use std::marker::PhantomData; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::Arc; +use std::{fs, io, mem, str, thread}; -use crate::errors; -use crate::traits::*; -use crate::{ - CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind, -}; use jobserver::{Acquired, Client}; use rustc_ast::attr; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; @@ -30,26 +28,25 @@ use rustc_middle::bug; use rustc_middle::dep_graph::{WorkProduct, WorkProductId}; use rustc_middle::middle::exported_symbols::SymbolExportInfo; use rustc_middle::ty::TyCtxt; -use rustc_session::config::{self, CrateType, Lto, OutFileName, OutputFilenames, OutputType}; -use rustc_session::config::{Passes, SwitchWithOptPath}; +use rustc_session::config::{ + self, CrateType, Lto, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath, +}; use rustc_session::Session; use rustc_span::source_map::SourceMap; use rustc_span::symbol::sym; use rustc_span::{BytePos, FileName, InnerSpan, Pos, Span}; use rustc_target::spec::{MergeFunctions, SanitizerSet}; +use tracing::debug; +use super::link::{self, ensure_removed}; +use super::lto::{self, SerializedModule}; +use super::symbol_export::symbol_name_for_instance_in_crate; use crate::errors::ErrorCreatingRemarkDir; -use std::any::Any; -use std::fs; -use std::io; -use std::marker::PhantomData; -use std::mem; -use std::path::{Path, PathBuf}; -use std::str; -use std::sync::mpsc::{channel, Receiver, Sender}; -use std::sync::Arc; -use std::thread; -use tracing::debug; +use crate::traits::*; +use crate::{ + errors, CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, + ModuleKind, +}; const PRE_LTO_BC_EXT: &str = "pre-lto.bc"; @@ -1512,7 +1509,7 @@ fn start_executing_work( // We reduce the `running` counter by one. The // `tokens.truncate()` below will take care of // giving the Token back. - debug_assert!(running_with_own_token > 0); + assert!(running_with_own_token > 0); running_with_own_token -= 1; main_thread_state = MainThreadState::Lending; } diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 399ac4858505e..f4e44e63d73cc 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -1,19 +1,8 @@ -use crate::assert_module_sources::CguReuse; -use crate::back::link::are_upstream_rust_objects_already_included; -use crate::back::metadata::create_compressed_metadata_file; -use crate::back::write::{ - compute_per_cgu_lto_type, start_async_codegen, submit_codegened_module_to_llvm, - submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, ComputedLtoType, OngoingCodegen, -}; -use crate::common::{self, IntPredicate, RealPredicate, TypeKind}; -use crate::errors; -use crate::meth; -use crate::mir; -use crate::mir::operand::OperandValue; -use crate::mir::place::PlaceRef; -use crate::traits::*; -use crate::{CachedModuleCodegen, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind}; +use std::cmp; +use std::collections::BTreeSet; +use std::time::{Duration, Instant}; +use itertools::Itertools; use rustc_ast::expand::allocator::{global_fn_name, AllocatorKind, ALLOCATOR_METHODS}; use rustc_attr as attr; use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; @@ -26,9 +15,8 @@ use rustc_metadata::EncodedMetadata; use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::middle::debugger_visualizer::{DebuggerVisualizerFile, DebuggerVisualizerType}; -use rustc_middle::middle::exported_symbols; use rustc_middle::middle::exported_symbols::SymbolExportKind; -use rustc_middle::middle::lang_items; +use rustc_middle::middle::{exported_symbols, lang_items}; use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem}; use rustc_middle::mir::BinOp; use rustc_middle::query::Providers; @@ -39,14 +27,23 @@ use rustc_session::Session; use rustc_span::symbol::sym; use rustc_span::{Symbol, DUMMY_SP}; use rustc_target::abi::FIRST_VARIANT; - -use std::cmp; -use std::collections::BTreeSet; -use std::time::{Duration, Instant}; - -use itertools::Itertools; use tracing::{debug, info}; +use crate::assert_module_sources::CguReuse; +use crate::back::link::are_upstream_rust_objects_already_included; +use crate::back::metadata::create_compressed_metadata_file; +use crate::back::write::{ + compute_per_cgu_lto_type, start_async_codegen, submit_codegened_module_to_llvm, + submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, ComputedLtoType, OngoingCodegen, +}; +use crate::common::{self, IntPredicate, RealPredicate, TypeKind}; +use crate::mir::operand::OperandValue; +use crate::mir::place::PlaceRef; +use crate::traits::*; +use crate::{ + errors, meth, mir, CachedModuleCodegen, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind, +}; + pub fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate { match op { BinOp::Eq => IntPredicate::IntEQ, diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index bfa4c683d56ed..4ab20c154ccd0 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -1,17 +1,20 @@ use rustc_ast::{ast, attr, MetaItemKind, NestedMetaItem}; use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr}; -use rustc_errors::{codes::*, struct_span_code_err, DiagMessage, SubdiagMessage}; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, DiagMessage, SubdiagMessage}; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; -use rustc_hir::{lang_items, weak_lang_items::WEAK_LANG_ITEMS, LangItem}; +use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS; +use rustc_hir::{lang_items, LangItem}; use rustc_middle::middle::codegen_fn_attrs::{ CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, }; use rustc_middle::mir::mono::Linkage; use rustc_middle::query::Providers; use rustc_middle::ty::{self as ty, TyCtxt}; -use rustc_session::{lint, parse::feature_err}; +use rustc_session::lint; +use rustc_session::parse::feature_err; use rustc_span::symbol::Ident; use rustc_span::{sym, Span}; use rustc_target::spec::{abi, SanitizerSet}; diff --git a/compiler/rustc_codegen_ssa/src/common.rs b/compiler/rustc_codegen_ssa/src/common.rs index 27b0f127e9262..a972c0cd99d10 100644 --- a/compiler/rustc_codegen_ssa/src/common.rs +++ b/compiler/rustc_codegen_ssa/src/common.rs @@ -1,15 +1,14 @@ #![allow(non_camel_case_types)] use rustc_hir::LangItem; -use rustc_middle::mir; -use rustc_middle::ty::Instance; -use rustc_middle::ty::{self, layout::TyAndLayout, TyCtxt}; -use rustc_middle::{bug, span_bug}; +use rustc_middle::ty::layout::TyAndLayout; +use rustc_middle::ty::{self, Instance, TyCtxt}; +use rustc_middle::{bug, mir, span_bug}; use rustc_span::Span; use crate::traits::*; -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Debug)] pub enum IntPredicate { IntEQ, IntNE, @@ -23,7 +22,7 @@ pub enum IntPredicate { IntSLE, } -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Debug)] pub enum RealPredicate { RealPredicateFalse, RealOEQ, @@ -43,7 +42,7 @@ pub enum RealPredicate { RealPredicateTrue, } -#[derive(Copy, Clone, PartialEq)] +#[derive(Copy, Clone, PartialEq, Debug)] pub enum AtomicRmwBinOp { AtomicXchg, AtomicAdd, @@ -58,7 +57,7 @@ pub enum AtomicRmwBinOp { AtomicUMin, } -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Debug)] pub enum AtomicOrdering { Unordered, Relaxed, @@ -68,7 +67,7 @@ pub enum AtomicOrdering { SequentiallyConsistent, } -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Debug)] pub enum SynchronizationScope { SingleThread, CrossThread, @@ -91,7 +90,6 @@ pub enum TypeKind { Pointer, Vector, Metadata, - X86_MMX, Token, ScalableVector, BFloat, @@ -107,9 +105,10 @@ pub enum TypeKind { // for now we content ourselves with providing a no-op HashStable // implementation for CGUs. mod temp_stable_hash_impls { - use crate::ModuleCodegen; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; + use crate::ModuleCodegen; + impl HashStable for ModuleCodegen { fn hash_stable(&self, _: &mut HCX, _: &mut StableHasher) { // do nothing diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/mod.rs b/compiler/rustc_codegen_ssa/src/debuginfo/mod.rs index 60e9b40e8fb40..1eaf593a6d77b 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/mod.rs @@ -1,4 +1,5 @@ -use rustc_middle::ty::{self, layout::TyAndLayout}; +use rustc_middle::ty::layout::TyAndLayout; +use rustc_middle::ty::{self}; use rustc_target::abi::Size; // FIXME(eddyb) find a place for this (or a way to replace it). diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index c4e5c8582404b..2755803892751 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -11,6 +11,8 @@ // within the brackets). // * `"` is treated as the start of a string. +use std::fmt::Write; + use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher}; use rustc_hir::def_id::DefId; @@ -18,14 +20,13 @@ use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathD use rustc_hir::{CoroutineDesugaring, CoroutineKind, CoroutineSource, Mutability}; use rustc_middle::bug; use rustc_middle::ty::layout::{IntegerExt, TyAndLayout}; -use rustc_middle::ty::{self, ExistentialProjection, ParamEnv, Ty, TyCtxt}; -use rustc_middle::ty::{GenericArgKind, GenericArgsRef}; +use rustc_middle::ty::{ + self, ExistentialProjection, GenericArgKind, GenericArgsRef, ParamEnv, Ty, TyCtxt, +}; use rustc_span::DUMMY_SP; use rustc_target::abi::Integer; use smallvec::SmallVec; -use std::fmt::Write; - use crate::debuginfo::wants_c_like_enum_debuginfo; /// Compute the name of the type as it should be stored in debuginfo. Does not do @@ -459,7 +460,7 @@ fn push_debuginfo_type_name<'tcx>( output: &mut String, visited: &mut FxHashSet>, ) { - debug_assert!(!wants_c_like_enum_debuginfo(ty_and_layout)); + assert!(!wants_c_like_enum_debuginfo(ty_and_layout)); output.push_str("enum2$<"); push_inner(output, visited); push_close_angle_bracket(true, output); @@ -660,7 +661,7 @@ fn push_generic_params_internal<'tcx>( output: &mut String, visited: &mut FxHashSet>, ) -> bool { - debug_assert_eq!(args, tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), args)); + assert_eq!(args, tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), args)); let mut args = args.non_erasable_generics(tcx, def_id).peekable(); if args.peek().is_none() { return false; diff --git a/compiler/rustc_codegen_ssa/src/errors.rs b/compiler/rustc_codegen_ssa/src/errors.rs index e9d31db92541b..2d1eae630cf16 100644 --- a/compiler/rustc_codegen_ssa/src/errors.rs +++ b/compiler/rustc_codegen_ssa/src/errors.rs @@ -1,20 +1,23 @@ //! Errors emitted by codegen_ssa -use crate::assert_module_sources::CguReuse; -use crate::back::command::Command; -use crate::fluent_generated as fluent; +use std::borrow::Cow; +use std::io::Error; +use std::path::{Path, PathBuf}; +use std::process::ExitStatus; + +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level, + Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level, }; use rustc_macros::Diagnostic; use rustc_middle::ty::layout::LayoutError; use rustc_middle::ty::Ty; use rustc_span::{Span, Symbol}; use rustc_type_ir::FloatTy; -use std::borrow::Cow; -use std::io::Error; -use std::path::{Path, PathBuf}; -use std::process::ExitStatus; + +use crate::assert_module_sources::CguReuse; +use crate::back::command::Command; +use crate::fluent_generated as fluent; #[derive(Diagnostic)] #[diag(codegen_ssa_incorrect_cgu_reuse_type)] @@ -497,6 +500,7 @@ pub struct UnableToWriteDebuggerVisualizer { #[derive(Diagnostic)] #[diag(codegen_ssa_rlib_archive_build_failure)] pub struct RlibArchiveBuildFailure { + pub path: PathBuf, pub error: Error, } @@ -554,6 +558,7 @@ pub struct UnsupportedLinkSelfContained; #[diag(codegen_ssa_archive_build_failure)] // Public for rustc_codegen_llvm::back::archive pub struct ArchiveBuildFailure { + pub path: PathBuf, pub error: std::io::Error, } diff --git a/compiler/rustc_codegen_ssa/src/lib.rs b/compiler/rustc_codegen_ssa/src/lib.rs index e801af4001415..1b029660433bd 100644 --- a/compiler/rustc_codegen_ssa/src/lib.rs +++ b/compiler/rustc_codegen_ssa/src/lib.rs @@ -17,9 +17,12 @@ //! The backend-agnostic functions of this crate use functions defined in various traits that //! have to be implemented by each backend. +use std::collections::BTreeSet; +use std::io; +use std::path::{Path, PathBuf}; + use rustc_ast as ast; -use rustc_data_structures::fx::FxHashSet; -use rustc_data_structures::fx::FxIndexMap; +use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::sync::Lrc; use rustc_data_structures::unord::UnordMap; use rustc_hir::def_id::CrateNum; @@ -36,9 +39,6 @@ use rustc_session::cstore::{self, CrateSource}; use rustc_session::utils::NativeLibKind; use rustc_session::Session; use rustc_span::symbol::Symbol; -use std::collections::BTreeSet; -use std::io; -use std::path::{Path, PathBuf}; pub mod assert_module_sources; pub mod back; diff --git a/compiler/rustc_codegen_ssa/src/meth.rs b/compiler/rustc_codegen_ssa/src/meth.rs index febc8ee2be248..c9602d9cdae1e 100644 --- a/compiler/rustc_codegen_ssa/src/meth.rs +++ b/compiler/rustc_codegen_ssa/src/meth.rs @@ -1,5 +1,3 @@ -use crate::traits::*; - use rustc_middle::bug; use rustc_middle::ty::{self, GenericArgKind, Ty}; use rustc_session::config::Lto; @@ -7,6 +5,8 @@ use rustc_symbol_mangling::typeid_for_trait_ref; use rustc_target::abi::call::FnAbi; use tracing::{debug, instrument}; +use crate::traits::*; + #[derive(Copy, Clone, Debug)] pub struct VirtualIndex(u64); diff --git a/compiler/rustc_codegen_ssa/src/mir/analyze.rs b/compiler/rustc_codegen_ssa/src/mir/analyze.rs index ac2b6ca4e9520..6794365c9beef 100644 --- a/compiler/rustc_codegen_ssa/src/mir/analyze.rs +++ b/compiler/rustc_codegen_ssa/src/mir/analyze.rs @@ -1,18 +1,18 @@ //! An analysis to determine which locals require allocas and //! which do not. -use super::FunctionCx; -use crate::traits::*; use rustc_data_structures::graph::dominators::Dominators; use rustc_index::bit_set::BitSet; use rustc_index::{IndexSlice, IndexVec}; -use rustc_middle::mir::traversal; use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor}; -use rustc_middle::mir::{self, DefLocation, Location, TerminatorKind}; +use rustc_middle::mir::{self, traversal, DefLocation, Location, TerminatorKind}; use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf}; use rustc_middle::{bug, span_bug}; use tracing::debug; +use super::FunctionCx; +use crate::traits::*; + pub fn non_ssa_locals<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( fx: &FunctionCx<'a, 'tcx, Bx>, ) -> BitSet { diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index c9c8f02c491bd..bc3076528da24 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -1,14 +1,4 @@ -use super::operand::OperandRef; -use super::operand::OperandValue::{Immediate, Pair, Ref, ZeroSized}; -use super::place::{PlaceRef, PlaceValue}; -use super::{CachedLlbb, FunctionCx, LocalRef}; - -use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization}; -use crate::common::{self, IntPredicate}; -use crate::errors::CompilerBuiltinsCannotCall; -use crate::meth; -use crate::traits::*; -use crate::MemFlags; +use std::cmp; use rustc_ast as ast; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; @@ -19,13 +9,22 @@ use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; use rustc_middle::ty::{self, Instance, Ty}; use rustc_middle::{bug, span_bug}; use rustc_session::config::OptLevel; -use rustc_span::{source_map::Spanned, sym, Span}; +use rustc_span::source_map::Spanned; +use rustc_span::{sym, Span}; use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode, Reg}; use rustc_target::abi::{self, HasDataLayout, WrappingRange}; use rustc_target::spec::abi::Abi; use tracing::{debug, info}; -use std::cmp; +use super::operand::OperandRef; +use super::operand::OperandValue::{Immediate, Pair, Ref, ZeroSized}; +use super::place::{PlaceRef, PlaceValue}; +use super::{CachedLlbb, FunctionCx, LocalRef}; +use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization}; +use crate::common::{self, IntPredicate}; +use crate::errors::CompilerBuiltinsCannotCall; +use crate::traits::*; +use crate::{meth, MemFlags}; // Indicates if we are in the middle of merging a BB's successor into it. This // can happen when BB jumps directly to its successor and the successor has no @@ -84,7 +83,7 @@ impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> { } if is_cleanupret { // Cross-funclet jump - need a trampoline - debug_assert!(base::wants_new_eh_instructions(fx.cx.tcx().sess)); + assert!(base::wants_new_eh_instructions(fx.cx.tcx().sess)); debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target); let name = &format!("{:?}_cleanup_trampoline_{:?}", self.bb, target); let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name); diff --git a/compiler/rustc_codegen_ssa/src/mir/constant.rs b/compiler/rustc_codegen_ssa/src/mir/constant.rs index 35e9a3b7dc206..f4d974f70362e 100644 --- a/compiler/rustc_codegen_ssa/src/mir/constant.rs +++ b/compiler/rustc_codegen_ssa/src/mir/constant.rs @@ -1,14 +1,13 @@ -use crate::errors; -use crate::mir::operand::OperandRef; -use crate::traits::*; -use rustc_middle::mir; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::layout::HasTyCtxt; use rustc_middle::ty::{self, Ty}; -use rustc_middle::{bug, span_bug}; +use rustc_middle::{bug, mir, span_bug}; use rustc_target::abi::Abi; use super::FunctionCx; +use crate::errors; +use crate::mir::operand::OperandRef; +use crate::traits::*; impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { pub fn eval_mir_constant_to_operand( diff --git a/compiler/rustc_codegen_ssa/src/mir/coverageinfo.rs b/compiler/rustc_codegen_ssa/src/mir/coverageinfo.rs index 721872772287b..67f1ef5d9449c 100644 --- a/compiler/rustc_codegen_ssa/src/mir/coverageinfo.rs +++ b/compiler/rustc_codegen_ssa/src/mir/coverageinfo.rs @@ -1,9 +1,8 @@ -use crate::traits::*; - use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::mir::SourceScope; use super::FunctionCx; +use crate::traits::*; impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { pub fn codegen_coverage(&self, bx: &mut Bx, kind: &CoverageKind, scope: SourceScope) { diff --git a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs index 6b89636b6540c..0e495973a01d9 100644 --- a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs +++ b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs @@ -1,13 +1,11 @@ -use crate::traits::*; +use std::ops::Range; + use rustc_data_structures::fx::FxHashMap; use rustc_index::IndexVec; -use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use rustc_middle::mir; -use rustc_middle::ty; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; -use rustc_middle::ty::Instance; -use rustc_middle::ty::Ty; +use rustc_middle::ty::{Instance, Ty}; +use rustc_middle::{bug, mir, ty}; use rustc_session::config::DebugInfo; use rustc_span::symbol::{kw, Symbol}; use rustc_span::{hygiene, BytePos, Span}; @@ -16,8 +14,7 @@ use rustc_target::abi::{Abi, FieldIdx, FieldsShape, Size, VariantIdx}; use super::operand::{OperandRef, OperandValue}; use super::place::{PlaceRef, PlaceValue}; use super::{FunctionCx, LocalRef}; - -use std::ops::Range; +use crate::traits::*; pub struct FunctionDebugContext<'tcx, S, L> { /// Maps from source code to the corresponding debug info scope. @@ -194,7 +191,7 @@ fn calculate_debuginfo_offset< } _ => { // Sanity check for `can_use_in_debuginfo`. - debug_assert!(!elem.can_use_in_debuginfo()); + assert!(!elem.can_use_in_debuginfo()); bug!("unsupported var debuginfo projection `{:?}`", projection) } } @@ -502,7 +499,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let DebugInfoOffset { direct_offset, indirect_offsets, result: fragment_layout } = calculate_debuginfo_offset(bx, &fragment.projection, var_layout); - debug_assert!(indirect_offsets.is_empty()); + assert!(indirect_offsets.is_empty()); if fragment_layout.size == Size::ZERO { // Fragment is a ZST, so does not represent anything. Avoid generating anything diff --git a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs index f88deaa7abca6..4acbc04c505e8 100644 --- a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs @@ -1,21 +1,16 @@ +use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::{bug, span_bug}; +use rustc_session::config::OptLevel; +use rustc_span::{sym, Span}; +use rustc_target::abi::call::{FnAbi, PassMode}; +use rustc_target::abi::WrappingRange; + use super::operand::OperandRef; use super::place::PlaceRef; use super::FunctionCx; -use crate::errors; use crate::errors::InvalidMonomorphization; -use crate::meth; -use crate::size_of_val; use crate::traits::*; -use crate::MemFlags; - -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_middle::{bug, span_bug}; -use rustc_session::config::OptLevel; -use rustc_span::{sym, Span}; -use rustc_target::abi::{ - call::{FnAbi, PassMode}, - WrappingRange, -}; +use crate::{errors, meth, size_of_val, MemFlags}; fn copy_intrinsic<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( bx: &mut Bx, diff --git a/compiler/rustc_codegen_ssa/src/mir/locals.rs b/compiler/rustc_codegen_ssa/src/mir/locals.rs index 5190021c005b4..93f0ab36f2a2f 100644 --- a/compiler/rustc_codegen_ssa/src/mir/locals.rs +++ b/compiler/rustc_codegen_ssa/src/mir/locals.rs @@ -2,14 +2,16 @@ //! be careful wrt to subtyping. To deal with this we only allow updates by using //! `FunctionCx::overwrite_local` which handles it automatically. -use crate::mir::{FunctionCx, LocalRef}; -use crate::traits::BuilderMethods; +use std::ops::{Index, IndexMut}; + use rustc_index::IndexVec; use rustc_middle::mir; use rustc_middle::ty::print::with_no_trimmed_paths; -use std::ops::{Index, IndexMut}; use tracing::{debug, warn}; +use crate::mir::{FunctionCx, LocalRef}; +use crate::traits::BuilderMethods; + pub(super) struct Locals<'tcx, V> { values: IndexVec>, } diff --git a/compiler/rustc_codegen_ssa/src/mir/mod.rs b/compiler/rustc_codegen_ssa/src/mir/mod.rs index 61f57c9030a1a..4ce07269cd2c1 100644 --- a/compiler/rustc_codegen_ssa/src/mir/mod.rs +++ b/compiler/rustc_codegen_ssa/src/mir/mod.rs @@ -1,18 +1,17 @@ -use crate::base; -use crate::traits::*; +use std::iter; + use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use rustc_middle::mir; -use rustc_middle::mir::traversal; -use rustc_middle::mir::UnwindTerminateReason; +use rustc_middle::mir::{traversal, UnwindTerminateReason}; use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, TyAndLayout}; use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; -use rustc_middle::{bug, span_bug}; +use rustc_middle::{bug, mir, span_bug}; use rustc_target::abi::call::{FnAbi, PassMode}; use tracing::{debug, instrument}; -use std::iter; +use crate::base; +use crate::traits::*; mod analyze; mod block; diff --git a/compiler/rustc_codegen_ssa/src/mir/operand.rs b/compiler/rustc_codegen_ssa/src/mir/operand.rs index cc0e913965067..2bc2d0f70bfaf 100644 --- a/compiler/rustc_codegen_ssa/src/mir/operand.rs +++ b/compiler/rustc_codegen_ssa/src/mir/operand.rs @@ -1,23 +1,20 @@ -use super::place::{PlaceRef, PlaceValue}; -use super::{FunctionCx, LocalRef}; - -use crate::size_of_val; -use crate::traits::*; -use crate::MemFlags; +use std::fmt; +use arrayvec::ArrayVec; +use either::Either; use rustc_middle::bug; use rustc_middle::mir::interpret::{alloc_range, Pointer, Scalar}; use rustc_middle::mir::{self, ConstValue}; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::ty::Ty; use rustc_target::abi::{self, Abi, Align, Size}; - -use std::fmt; - -use arrayvec::ArrayVec; -use either::Either; use tracing::debug; +use super::place::{PlaceRef, PlaceValue}; +use super::{FunctionCx, LocalRef}; +use crate::traits::*; +use crate::{size_of_val, MemFlags}; + /// The representation of a Rust value. The enum variant is in fact /// uniquely determined by the value's type, but is kept as a /// safety check. @@ -565,7 +562,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { for elem in place_ref.projection.iter() { match elem { mir::ProjectionElem::Field(ref f, _) => { - debug_assert!( + assert!( !o.layout.ty.is_any_ptr(), "Bad PlaceRef: destructing pointers should use cast/PtrMetadata, \ but tried to access field {f:?} of pointer {o:?}", diff --git a/compiler/rustc_codegen_ssa/src/mir/place.rs b/compiler/rustc_codegen_ssa/src/mir/place.rs index 97d5bb8312891..0fad4d169edd5 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -1,19 +1,18 @@ +use rustc_middle::mir::tcx::PlaceTy; +use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout}; +use rustc_middle::ty::{self, Ty}; +use rustc_middle::{bug, mir}; +use rustc_target::abi::{ + Align, FieldsShape, Int, Pointer, Size, TagEncoding, VariantIdx, Variants, +}; +use tracing::{debug, instrument}; + use super::operand::OperandValue; use super::{FunctionCx, LocalRef}; - use crate::common::IntPredicate; use crate::size_of_val; use crate::traits::*; -use rustc_middle::bug; -use rustc_middle::mir; -use rustc_middle::mir::tcx::PlaceTy; -use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout}; -use rustc_middle::ty::{self, Ty}; -use rustc_target::abi::{Align, FieldsShape, Int, Pointer, Size, TagEncoding}; -use rustc_target::abi::{VariantIdx, Variants}; -use tracing::{debug, instrument}; - /// The location and extra runtime properties of the place. /// /// Typically found in a [`PlaceRef`] or an [`OperandValue::Ref`]. @@ -55,7 +54,7 @@ impl PlaceValue { /// Creates a `PlaceRef` to this location with the given type. pub fn with_type<'tcx>(self, layout: TyAndLayout<'tcx>) -> PlaceRef<'tcx, V> { - debug_assert!( + assert!( layout.is_unsized() || layout.abi.is_uninhabited() || self.llextra.is_none(), "Had pointer metadata {:?} for sized type {layout:?}", self.llextra, @@ -488,7 +487,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { cg_base = match *elem { mir::ProjectionElem::Deref => bx.load_operand(cg_base).deref(bx.cx()), mir::ProjectionElem::Field(ref field, _) => { - debug_assert!( + assert!( !cg_base.layout.ty.is_any_ptr(), "Bad PlaceRef: destructing pointers should use cast/PtrMetadata, \ but tried to access field {field:?} of pointer {cg_base:?}", diff --git a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs index f9e928a84a78e..d91a118bc71a3 100644 --- a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs +++ b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs @@ -1,24 +1,20 @@ -use super::operand::{OperandRef, OperandValue}; -use super::place::PlaceRef; -use super::{FunctionCx, LocalRef}; - -use crate::base; -use crate::common::IntPredicate; -use crate::traits::*; -use crate::MemFlags; - -use rustc_middle::mir; -use rustc_middle::ty::cast::{CastTy, IntTy}; +use arrayvec::ArrayVec; +use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout}; -use rustc_middle::ty::{self, adjustment::PointerCoercion, Instance, Ty, TyCtxt}; -use rustc_middle::{bug, span_bug}; +use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; +use rustc_middle::{bug, mir, span_bug}; use rustc_session::config::OptLevel; use rustc_span::{Span, DUMMY_SP}; use rustc_target::abi::{self, FieldIdx, FIRST_VARIANT}; - -use arrayvec::ArrayVec; use tracing::{debug, instrument}; +use super::operand::{OperandRef, OperandValue}; +use super::place::PlaceRef; +use super::{FunctionCx, LocalRef}; +use crate::common::IntPredicate; +use crate::traits::*; +use crate::{base, MemFlags}; + impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { #[instrument(level = "trace", skip(self, bx))] pub fn codegen_rvalue( @@ -168,8 +164,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { dst: PlaceRef<'tcx, Bx::Value>, ) { // The MIR validator enforces no unsized transmutes. - debug_assert!(src.layout.is_sized()); - debug_assert!(dst.layout.is_sized()); + assert!(src.layout.is_sized()); + assert!(dst.layout.is_sized()); if let Some(val) = self.codegen_transmute_operand(bx, src, dst.layout) { val.store(bx, dst); @@ -223,8 +219,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { match operand.val { OperandValue::Ref(source_place_val) => { - debug_assert_eq!(source_place_val.llextra, None); - debug_assert!(matches!(operand_kind, OperandValueKind::Ref)); + assert_eq!(source_place_val.llextra, None); + assert!(matches!(operand_kind, OperandValueKind::Ref)); Some(bx.load_operand(source_place_val.with_type(cast)).val) } OperandValue::ZeroSized => { @@ -238,21 +234,21 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } } OperandValue::Immediate(imm) => { - let OperandValueKind::Immediate(in_scalar) = operand_kind else { + let OperandValueKind::Immediate(from_scalar) = operand_kind else { bug!("Found {operand_kind:?} for operand {operand:?}"); }; - if let OperandValueKind::Immediate(out_scalar) = cast_kind - && in_scalar.size(self.cx) == out_scalar.size(self.cx) + if let OperandValueKind::Immediate(to_scalar) = cast_kind + && from_scalar.size(self.cx) == to_scalar.size(self.cx) { - let operand_bty = bx.backend_type(operand.layout); - let cast_bty = bx.backend_type(cast); + let from_backend_ty = bx.backend_type(operand.layout); + let to_backend_ty = bx.backend_type(cast); Some(OperandValue::Immediate(self.transmute_immediate( bx, imm, - in_scalar, - operand_bty, - out_scalar, - cast_bty, + from_scalar, + from_backend_ty, + to_scalar, + to_backend_ty, ))) } else { None @@ -281,6 +277,58 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } } + /// Cast one of the immediates from an [`OperandValue::Immediate`] + /// or an [`OperandValue::Pair`] to an immediate of the target type. + /// + /// Returns `None` if the cast is not possible. + fn cast_immediate( + &self, + bx: &mut Bx, + mut imm: Bx::Value, + from_scalar: abi::Scalar, + from_backend_ty: Bx::Type, + to_scalar: abi::Scalar, + to_backend_ty: Bx::Type, + ) -> Option { + use abi::Primitive::*; + + // When scalars are passed by value, there's no metadata recording their + // valid ranges. For example, `char`s are passed as just `i32`, with no + // way for LLVM to know that they're 0x10FFFF at most. Thus we assume + // the range of the input value too, not just the output range. + self.assume_scalar_range(bx, imm, from_scalar, from_backend_ty); + + imm = match (from_scalar.primitive(), to_scalar.primitive()) { + (Int(_, is_signed), Int(..)) => bx.intcast(imm, to_backend_ty, is_signed), + (Float(_), Float(_)) => { + let srcsz = bx.cx().float_width(from_backend_ty); + let dstsz = bx.cx().float_width(to_backend_ty); + if dstsz > srcsz { + bx.fpext(imm, to_backend_ty) + } else if srcsz > dstsz { + bx.fptrunc(imm, to_backend_ty) + } else { + imm + } + } + (Int(_, is_signed), Float(_)) => { + if is_signed { + bx.sitofp(imm, to_backend_ty) + } else { + bx.uitofp(imm, to_backend_ty) + } + } + (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty), + (Int(_, is_signed), Pointer(..)) => { + let usize_imm = bx.intcast(imm, bx.cx().type_isize(), is_signed); + bx.inttoptr(usize_imm, to_backend_ty) + } + (Float(_), Int(_, is_signed)) => bx.cast_float_to_int(is_signed, imm, to_backend_ty), + _ => return None, + }; + Some(imm) + } + /// Transmutes one of the immediates from an [`OperandValue::Immediate`] /// or an [`OperandValue::Pair`] to an immediate of the target type. /// @@ -295,7 +343,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { to_scalar: abi::Scalar, to_backend_ty: Bx::Type, ) -> Bx::Value { - debug_assert_eq!(from_scalar.size(self.cx), to_scalar.size(self.cx)); + assert_eq!(from_scalar.size(self.cx), to_scalar.size(self.cx)); use abi::Primitive::*; imm = bx.from_immediate(imm); @@ -487,62 +535,33 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { | mir::CastKind::IntToFloat | mir::CastKind::PtrToPtr | mir::CastKind::FnPtrToPtr - // Since int2ptr can have arbitrary integer types as input (so we have to do // sign extension and all that), it is currently best handled in the same code // path as the other integer-to-X casts. | mir::CastKind::PointerWithExposedProvenance => { + let imm = operand.immediate(); + let operand_kind = self.value_kind(operand.layout); + let OperandValueKind::Immediate(from_scalar) = operand_kind else { + bug!("Found {operand_kind:?} for operand {operand:?}"); + }; + let from_backend_ty = bx.cx().immediate_backend_type(operand.layout); + assert!(bx.cx().is_backend_immediate(cast)); - let ll_t_out = bx.cx().immediate_backend_type(cast); + let to_backend_ty = bx.cx().immediate_backend_type(cast); if operand.layout.abi.is_uninhabited() { - let val = OperandValue::Immediate(bx.cx().const_poison(ll_t_out)); + let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty)); return OperandRef { val, layout: cast }; } - let r_t_in = - CastTy::from_ty(operand.layout.ty).expect("bad input type for cast"); - let r_t_out = CastTy::from_ty(cast.ty).expect("bad output type for cast"); - let ll_t_in = bx.cx().immediate_backend_type(operand.layout); - let llval = operand.immediate(); - - let newval = match (r_t_in, r_t_out) { - (CastTy::Int(i), CastTy::Int(_)) => { - bx.intcast(llval, ll_t_out, i.is_signed()) - } - (CastTy::Float, CastTy::Float) => { - let srcsz = bx.cx().float_width(ll_t_in); - let dstsz = bx.cx().float_width(ll_t_out); - if dstsz > srcsz { - bx.fpext(llval, ll_t_out) - } else if srcsz > dstsz { - bx.fptrunc(llval, ll_t_out) - } else { - llval - } - } - (CastTy::Int(i), CastTy::Float) => { - if i.is_signed() { - bx.sitofp(llval, ll_t_out) - } else { - bx.uitofp(llval, ll_t_out) - } - } - (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Ptr(_)) => { - bx.pointercast(llval, ll_t_out) - } - (CastTy::Int(i), CastTy::Ptr(_)) => { - let usize_llval = - bx.intcast(llval, bx.cx().type_isize(), i.is_signed()); - bx.inttoptr(usize_llval, ll_t_out) - } - (CastTy::Float, CastTy::Int(IntTy::I)) => { - bx.cast_float_to_int(true, llval, ll_t_out) - } - (CastTy::Float, CastTy::Int(_)) => { - bx.cast_float_to_int(false, llval, ll_t_out) - } - _ => bug!("unsupported cast: {:?} to {:?}", operand.layout.ty, cast.ty), + let cast_kind = self.value_kind(cast); + let OperandValueKind::Immediate(to_scalar) = cast_kind else { + bug!("Found {cast_kind:?} for operand {cast:?}"); }; - OperandValue::Immediate(newval) + + self.cast_immediate(bx, imm, from_scalar, from_backend_ty, to_scalar, to_backend_ty) + .map(OperandValue::Immediate) + .unwrap_or_else(|| { + bug!("Unsupported cast of {operand:?} to {cast:?}"); + }) } mir::CastKind::Transmute => { self.codegen_transmute_operand(bx, operand, cast).unwrap_or_else(|| { @@ -639,9 +658,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { (OperandValue::Immediate(llval), operand.layout) } mir::UnOp::PtrMetadata => { - debug_assert!( - operand.layout.ty.is_unsafe_ptr() || operand.layout.ty.is_ref(), - ); + assert!(operand.layout.ty.is_unsafe_ptr() || operand.layout.ty.is_ref(),); let (_, meta) = operand.val.pointer_parts(); assert_eq!(operand.layout.fields.count() > 1, meta.is_some()); if let Some(meta) = meta { @@ -651,7 +668,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } } }; - debug_assert!( + assert!( val.is_expected_variant_for_type(self.cx, layout), "Made wrong variant {val:?} for type {layout:?}", ); @@ -742,7 +759,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bug!("Field {field_idx:?} is {p:?} making {layout:?}"); }); let scalars = self.value_kind(op.layout).scalars().unwrap(); - debug_assert_eq!(values.len(), scalars.len()); + assert_eq!(values.len(), scalars.len()); inputs.extend(values); input_scalars.extend(scalars); } @@ -760,7 +777,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { ); let val = OperandValue::from_immediates(inputs); - debug_assert!( + assert!( val.is_expected_variant_for_type(self.cx, layout), "Made wrong variant {val:?} for type {layout:?}", ); @@ -805,7 +822,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let val = cg_place.val.address(); let ty = cg_place.layout.ty; - debug_assert!( + assert!( if bx.cx().type_has_metadata(ty) { matches!(val, OperandValue::Pair(..)) } else { @@ -927,7 +944,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } mir::BinOp::Cmp => { use std::cmp::Ordering; - debug_assert!(!is_float); + assert!(!is_float); let pred = |op| base::bin_op_to_icmp_predicate(op, is_signed); if bx.cx().tcx().sess.opts.optimize == OptLevel::No { // FIXME: This actually generates tighter assembly, and is a classic trick @@ -1111,7 +1128,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { if layout.is_zst() { OperandValueKind::ZeroSized } else if self.cx.is_backend_immediate(layout) { - debug_assert!(!self.cx.is_backend_scalar_pair(layout)); + assert!(!self.cx.is_backend_scalar_pair(layout)); OperandValueKind::Immediate(match layout.abi { abi::Abi::Scalar(s) => s, abi::Abi::Vector { element, .. } => element, diff --git a/compiler/rustc_codegen_ssa/src/mir/statement.rs b/compiler/rustc_codegen_ssa/src/mir/statement.rs index 27494f48b099b..2ef860fc336d6 100644 --- a/compiler/rustc_codegen_ssa/src/mir/statement.rs +++ b/compiler/rustc_codegen_ssa/src/mir/statement.rs @@ -3,8 +3,7 @@ use rustc_middle::span_bug; use rustc_session::config::OptLevel; use tracing::instrument; -use super::FunctionCx; -use super::LocalRef; +use super::{FunctionCx, LocalRef}; use crate::traits::*; impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { diff --git a/compiler/rustc_codegen_ssa/src/mono_item.rs b/compiler/rustc_codegen_ssa/src/mono_item.rs index 559ec400577f8..64fcefdc860cd 100644 --- a/compiler/rustc_codegen_ssa/src/mono_item.rs +++ b/compiler/rustc_codegen_ssa/src/mono_item.rs @@ -1,16 +1,14 @@ -use crate::base; -use crate::common; -use crate::traits::*; use rustc_hir as hir; use rustc_middle::mir::interpret::ErrorHandled; -use rustc_middle::mir::mono::MonoItem; -use rustc_middle::mir::mono::{Linkage, Visibility}; -use rustc_middle::span_bug; -use rustc_middle::ty; +use rustc_middle::mir::mono::{Linkage, MonoItem, Visibility}; use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf}; use rustc_middle::ty::Instance; +use rustc_middle::{span_bug, ty}; use tracing::debug; +use crate::traits::*; +use crate::{base, common}; + pub trait MonoItemExt<'a, 'tcx> { fn define>(&self, cx: &'a Bx::CodegenCx); fn predefine>( diff --git a/compiler/rustc_codegen_ssa/src/size_of_val.rs b/compiler/rustc_codegen_ssa/src/size_of_val.rs index 130fe2eaf2feb..933904f984505 100644 --- a/compiler/rustc_codegen_ssa/src/size_of_val.rs +++ b/compiler/rustc_codegen_ssa/src/size_of_val.rs @@ -1,9 +1,5 @@ //! Computing the size and alignment of a value. -use crate::common; -use crate::common::IntPredicate; -use crate::meth; -use crate::traits::*; use rustc_hir::LangItem; use rustc_middle::bug; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; @@ -11,6 +7,10 @@ use rustc_middle::ty::{self, Ty}; use rustc_target::abi::WrappingRange; use tracing::{debug, trace}; +use crate::common::IntPredicate; +use crate::traits::*; +use crate::{common, meth}; + pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( bx: &mut Bx, t: Ty<'tcx>, diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index e7cee5220d620..127244a34f8f0 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -1,21 +1,19 @@ -use crate::errors; use rustc_ast::ast; use rustc_attr::InstructionSetAttr; use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::unord::UnordMap; use rustc_errors::Applicability; use rustc_hir::def::DefKind; -use rustc_hir::def_id::DefId; -use rustc_hir::def_id::LocalDefId; -use rustc_hir::def_id::LOCAL_CRATE; +use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; use rustc_middle::bug; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::parse::feature_err; -use rustc_span::symbol::sym; -use rustc_span::symbol::Symbol; +use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use crate::errors; + pub fn from_target_feature( tcx: TyCtxt<'_>, attr: &ast::Attribute, @@ -80,6 +78,7 @@ pub fn from_target_feature( Some(sym::loongarch_target_feature) => rust_features.loongarch_target_feature, Some(sym::lahfsahf_target_feature) => rust_features.lahfsahf_target_feature, Some(sym::prfchw_target_feature) => rust_features.prfchw_target_feature, + Some(sym::sha512_sm_x86) => rust_features.sha512_sm_x86, Some(sym::x86_amx_intrinsics) => rust_features.x86_amx_intrinsics, Some(sym::xop_target_feature) => rust_features.xop_target_feature, Some(sym::s390x_target_feature) => rust_features.s390x_target_feature, @@ -98,6 +97,14 @@ pub fn from_target_feature( Some(Symbol::intern(feature)) })); } + + for (feature, requires) in tcx.sess.target.implicit_target_features() { + if target_features.iter().any(|f| f.as_str() == *feature) + && !target_features.iter().any(|f| f.as_str() == *requires) + { + target_features.push(Symbol::intern(requires)); + } + } } /// Computes the set of target features used in a function for the purposes of diff --git a/compiler/rustc_codegen_ssa/src/traits/asm.rs b/compiler/rustc_codegen_ssa/src/traits/asm.rs index 8d67b626bbdb5..162141a106bcc 100644 --- a/compiler/rustc_codegen_ssa/src/traits/asm.rs +++ b/compiler/rustc_codegen_ssa/src/traits/asm.rs @@ -1,12 +1,13 @@ -use super::BackendTypes; -use crate::mir::operand::OperandRef; -use crate::mir::place::PlaceRef; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_hir::def_id::DefId; use rustc_middle::ty::Instance; use rustc_span::Span; use rustc_target::asm::InlineAsmRegOrRegClass; +use super::BackendTypes; +use crate::mir::operand::OperandRef; +use crate::mir::place::PlaceRef; + #[derive(Debug)] pub enum InlineAsmOperandRef<'tcx, B: BackendTypes + ?Sized> { In { diff --git a/compiler/rustc_codegen_ssa/src/traits/backend.rs b/compiler/rustc_codegen_ssa/src/traits/backend.rs index 3770bd11cf9b2..81e96413a9f34 100644 --- a/compiler/rustc_codegen_ssa/src/traits/backend.rs +++ b/compiler/rustc_codegen_ssa/src/traits/backend.rs @@ -1,10 +1,5 @@ use std::any::Any; -use super::write::WriteBackendMethods; -use super::CodegenObject; -use crate::back::write::TargetMachineFactoryFn; -use crate::{CodegenResults, ModuleCodegen}; - use rustc_ast::expand::allocator::AllocatorKind; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::sync::{DynSend, DynSync}; @@ -15,13 +10,16 @@ use rustc_middle::dep_graph::{WorkProduct, WorkProductId}; use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, LayoutOf, TyAndLayout}; use rustc_middle::ty::{Ty, TyCtxt}; use rustc_middle::util::Providers; -use rustc_session::{ - config::{self, OutputFilenames, PrintRequest}, - Session, -}; +use rustc_session::config::{self, OutputFilenames, PrintRequest}; +use rustc_session::Session; use rustc_span::symbol::Symbol; use rustc_target::abi::call::FnAbi; +use super::write::WriteBackendMethods; +use super::CodegenObject; +use crate::back::write::TargetMachineFactoryFn; +use crate::{CodegenResults, ModuleCodegen}; + pub trait BackendTypes { type Value: CodegenObject; type Function: CodegenObject; diff --git a/compiler/rustc_codegen_ssa/src/traits/builder.rs b/compiler/rustc_codegen_ssa/src/traits/builder.rs index 2f0daefa46a62..2b802240e03b9 100644 --- a/compiler/rustc_codegen_ssa/src/traits/builder.rs +++ b/compiler/rustc_codegen_ssa/src/traits/builder.rs @@ -1,3 +1,12 @@ +use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; +use rustc_middle::ty::layout::{HasParamEnv, TyAndLayout}; +use rustc_middle::ty::{Instance, Ty}; +use rustc_session::config::OptLevel; +use rustc_span::Span; +use rustc_target::abi::call::FnAbi; +use rustc_target::abi::{Abi, Align, Scalar, Size, WrappingRange}; +use rustc_target::spec::HasTargetSpec; + use super::abi::AbiBuilderMethods; use super::asm::AsmBuilderMethods; use super::consts::ConstMethods; @@ -7,7 +16,6 @@ use super::intrinsic::IntrinsicCallMethods; use super::misc::MiscMethods; use super::type_::{ArgAbiMethods, BaseTypeMethods, LayoutTypeMethods}; use super::{HasCodegen, StaticBuilderMethods}; - use crate::common::{ AtomicOrdering, AtomicRmwBinOp, IntPredicate, RealPredicate, SynchronizationScope, TypeKind, }; @@ -15,16 +23,7 @@ use crate::mir::operand::{OperandRef, OperandValue}; use crate::mir::place::{PlaceRef, PlaceValue}; use crate::MemFlags; -use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; -use rustc_middle::ty::layout::{HasParamEnv, TyAndLayout}; -use rustc_middle::ty::{Instance, Ty}; -use rustc_session::config::OptLevel; -use rustc_span::Span; -use rustc_target::abi::call::FnAbi; -use rustc_target::abi::{Abi, Align, Scalar, Size, WrappingRange}; -use rustc_target::spec::HasTargetSpec; - -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Debug)] pub enum OverflowOp { Add, Sub, @@ -165,7 +164,7 @@ pub trait BuilderMethods<'a, 'tcx>: size: Size, ) -> Self::Value; fn load_from_place(&mut self, ty: Self::Type, place: PlaceValue) -> Self::Value { - debug_assert_eq!(place.llextra, None); + assert_eq!(place.llextra, None); self.load(ty, place.llval, place.align) } fn load_operand(&mut self, place: PlaceRef<'tcx, Self::Value>) @@ -184,7 +183,7 @@ pub trait BuilderMethods<'a, 'tcx>: fn store(&mut self, val: Self::Value, ptr: Self::Value, align: Align) -> Self::Value; fn store_to_place(&mut self, val: Self::Value, place: PlaceValue) -> Self::Value { - debug_assert_eq!(place.llextra, None); + assert_eq!(place.llextra, None); self.store(val, place.llval, place.align) } fn store_with_flags( @@ -200,7 +199,7 @@ pub trait BuilderMethods<'a, 'tcx>: place: PlaceValue, flags: MemFlags, ) -> Self::Value { - debug_assert_eq!(place.llextra, None); + assert_eq!(place.llextra, None); self.store_with_flags(val, place.llval, place.align, flags) } fn atomic_store( @@ -320,9 +319,9 @@ pub trait BuilderMethods<'a, 'tcx>: layout: TyAndLayout<'tcx>, flags: MemFlags, ) { - debug_assert!(layout.is_sized(), "cannot typed-copy an unsigned type"); - debug_assert!(src.llextra.is_none(), "cannot directly copy from unsized values"); - debug_assert!(dst.llextra.is_none(), "cannot directly copy into unsized values"); + assert!(layout.is_sized(), "cannot typed-copy an unsigned type"); + assert!(src.llextra.is_none(), "cannot directly copy from unsized values"); + assert!(dst.llextra.is_none(), "cannot directly copy into unsized values"); if flags.contains(MemFlags::NONTEMPORAL) { // HACK(nox): This is inefficient but there is no nontemporal memcpy. let ty = self.backend_type(layout); diff --git a/compiler/rustc_codegen_ssa/src/traits/consts.rs b/compiler/rustc_codegen_ssa/src/traits/consts.rs index 3da732602c520..d93b3e06ca6f1 100644 --- a/compiler/rustc_codegen_ssa/src/traits/consts.rs +++ b/compiler/rustc_codegen_ssa/src/traits/consts.rs @@ -1,7 +1,8 @@ -use super::BackendTypes; use rustc_middle::mir::interpret::{ConstAllocation, Scalar}; use rustc_target::abi; +use super::BackendTypes; + pub trait ConstMethods<'tcx>: BackendTypes { // Constant constructors fn const_null(&self, t: Self::Type) -> Self::Value; diff --git a/compiler/rustc_codegen_ssa/src/traits/coverageinfo.rs b/compiler/rustc_codegen_ssa/src/traits/coverageinfo.rs index 906d8b87d3bc9..0b1645c66edca 100644 --- a/compiler/rustc_codegen_ssa/src/traits/coverageinfo.rs +++ b/compiler/rustc_codegen_ssa/src/traits/coverageinfo.rs @@ -1,7 +1,8 @@ -use super::BackendTypes; use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::ty::Instance; +use super::BackendTypes; + pub trait CoverageInfoBuilderMethods<'tcx>: BackendTypes { /// Performs any start-of-function codegen needed for coverage instrumentation. /// diff --git a/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs b/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs index 4acc0ea076c13..31104e5749b30 100644 --- a/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs +++ b/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs @@ -1,12 +1,13 @@ -use super::BackendTypes; -use crate::mir::debuginfo::{FunctionDebugContext, VariableKind}; +use std::ops::Range; + use rustc_middle::mir; use rustc_middle::ty::{Instance, PolyExistentialTraitRef, Ty}; use rustc_span::{SourceFile, Span, Symbol}; use rustc_target::abi::call::FnAbi; use rustc_target::abi::Size; -use std::ops::Range; +use super::BackendTypes; +use crate::mir::debuginfo::{FunctionDebugContext, VariableKind}; pub trait DebugInfoMethods<'tcx>: BackendTypes { fn create_vtable_debuginfo( diff --git a/compiler/rustc_codegen_ssa/src/traits/declare.rs b/compiler/rustc_codegen_ssa/src/traits/declare.rs index 655afcd17f0da..792d2b04ed6a6 100644 --- a/compiler/rustc_codegen_ssa/src/traits/declare.rs +++ b/compiler/rustc_codegen_ssa/src/traits/declare.rs @@ -1,8 +1,9 @@ -use super::BackendTypes; use rustc_hir::def_id::DefId; use rustc_middle::mir::mono::{Linkage, Visibility}; use rustc_middle::ty::Instance; +use super::BackendTypes; + pub trait PreDefineMethods<'tcx>: BackendTypes { fn predefine_static( &self, diff --git a/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs index 502f0b3fcb510..172004a9cc774 100644 --- a/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs @@ -1,9 +1,10 @@ -use super::BackendTypes; -use crate::mir::operand::OperandRef; use rustc_middle::ty::{self, Ty}; use rustc_span::Span; use rustc_target::abi::call::FnAbi; +use super::BackendTypes; +use crate::mir::operand::OperandRef; + pub trait IntrinsicCallMethods<'tcx>: BackendTypes { /// Remember to add all intrinsics here, in `compiler/rustc_hir_analysis/src/check/mod.rs`, /// and in `library/core/src/intrinsics.rs`; if you need access to any LLVM intrinsics, diff --git a/compiler/rustc_codegen_ssa/src/traits/misc.rs b/compiler/rustc_codegen_ssa/src/traits/misc.rs index 0ace28ed3ba5e..40a49b3e1b578 100644 --- a/compiler/rustc_codegen_ssa/src/traits/misc.rs +++ b/compiler/rustc_codegen_ssa/src/traits/misc.rs @@ -1,9 +1,11 @@ -use super::BackendTypes; +use std::cell::RefCell; + use rustc_data_structures::fx::FxHashMap; use rustc_middle::mir::mono::CodegenUnit; use rustc_middle::ty::{self, Instance, Ty}; use rustc_session::Session; -use std::cell::RefCell; + +use super::BackendTypes; pub trait MiscMethods<'tcx>: BackendTypes { fn vtables( diff --git a/compiler/rustc_codegen_ssa/src/traits/mod.rs b/compiler/rustc_codegen_ssa/src/traits/mod.rs index 8cb58bd4c704d..9ac923bef880c 100644 --- a/compiler/rustc_codegen_ssa/src/traits/mod.rs +++ b/compiler/rustc_codegen_ssa/src/traits/mod.rs @@ -28,6 +28,11 @@ mod statics; mod type_; mod write; +use std::fmt; + +use rustc_middle::ty::layout::{HasParamEnv, HasTyCtxt}; +use rustc_target::spec::HasTargetSpec; + pub use self::abi::AbiBuilderMethods; pub use self::asm::{AsmBuilderMethods, AsmMethods, GlobalAsmOperandRef, InlineAsmOperandRef}; pub use self::backend::{Backend, BackendTypes, CodegenBackend, ExtraBackendMethods}; @@ -45,11 +50,6 @@ pub use self::type_::{ }; pub use self::write::{ModuleBufferMethods, ThinBufferMethods, WriteBackendMethods}; -use rustc_middle::ty::layout::{HasParamEnv, HasTyCtxt}; -use rustc_target::spec::HasTargetSpec; - -use std::fmt; - pub trait CodegenObject: Copy + PartialEq + fmt::Debug {} impl CodegenObject for T {} diff --git a/compiler/rustc_codegen_ssa/src/traits/statics.rs b/compiler/rustc_codegen_ssa/src/traits/statics.rs index 737d93fd80ab0..b418199e61636 100644 --- a/compiler/rustc_codegen_ssa/src/traits/statics.rs +++ b/compiler/rustc_codegen_ssa/src/traits/statics.rs @@ -1,7 +1,8 @@ -use super::BackendTypes; use rustc_hir::def_id::DefId; use rustc_target::abi::Align; +use super::BackendTypes; + pub trait StaticMethods: BackendTypes { fn static_addr_of(&self, cv: Self::Value, align: Align, kind: Option<&str>) -> Self::Value; fn codegen_static(&self, def_id: DefId); diff --git a/compiler/rustc_codegen_ssa/src/traits/type_.rs b/compiler/rustc_codegen_ssa/src/traits/type_.rs index b1bad6cfa6f58..80dad79179a36 100644 --- a/compiler/rustc_codegen_ssa/src/traits/type_.rs +++ b/compiler/rustc_codegen_ssa/src/traits/type_.rs @@ -1,14 +1,14 @@ -use super::misc::MiscMethods; -use super::Backend; -use super::HasCodegen; -use crate::common::TypeKind; -use crate::mir::place::PlaceRef; use rustc_middle::bug; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{self, Ty}; use rustc_target::abi::call::{ArgAbi, CastTarget, FnAbi, Reg}; use rustc_target::abi::{AddressSpace, Float, Integer}; +use super::misc::MiscMethods; +use super::{Backend, HasCodegen}; +use crate::common::TypeKind; +use crate::mir::place::PlaceRef; + // This depends on `Backend` and not `BackendTypes`, because consumers will probably want to use // `LayoutOf` or `HasTyCtxt`. This way, they don't have to add a constraint on it themselves. pub trait BaseTypeMethods<'tcx>: Backend<'tcx> { diff --git a/compiler/rustc_codegen_ssa/src/traits/write.rs b/compiler/rustc_codegen_ssa/src/traits/write.rs index f4b1421a5329b..aabe9e33c4aa1 100644 --- a/compiler/rustc_codegen_ssa/src/traits/write.rs +++ b/compiler/rustc_codegen_ssa/src/traits/write.rs @@ -1,10 +1,10 @@ +use rustc_errors::{DiagCtxtHandle, FatalError}; +use rustc_middle::dep_graph::WorkProduct; + use crate::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule}; use crate::back::write::{CodegenContext, FatLtoInput, ModuleConfig}; use crate::{CompiledModule, ModuleCodegen}; -use rustc_errors::{DiagCtxtHandle, FatalError}; -use rustc_middle::dep_graph::WorkProduct; - pub trait WriteBackendMethods: 'static + Sized + Clone { type Module: Send + Sync; type TargetMachine; diff --git a/compiler/rustc_const_eval/messages.ftl b/compiler/rustc_const_eval/messages.ftl index cd269810741e7..c64c73b232340 100644 --- a/compiler/rustc_const_eval/messages.ftl +++ b/compiler/rustc_const_eval/messages.ftl @@ -45,9 +45,9 @@ const_eval_copy_nonoverlapping_overlapping = `copy_nonoverlapping` called on overlapping ranges const_eval_dangling_int_pointer = - {$bad_pointer_message}: {$pointer} is a dangling pointer (it has no provenance) + {$bad_pointer_message}: {const_eval_expected_inbounds_pointer}, but got {$pointer} which is a dangling pointer (it has no provenance) const_eval_dangling_null_pointer = - {$bad_pointer_message}: null pointer is a dangling pointer (it has no provenance) + {$bad_pointer_message}: {const_eval_expected_inbounds_pointer}, but got a null pointer const_eval_dangling_ptr_in_final = encountered dangling pointer in final value of {const_eval_intern_kind} const_eval_dead_local = @@ -87,6 +87,21 @@ const_eval_error = {$error_kind -> const_eval_exact_div_has_remainder = exact_div: {$a} cannot be divided by {$b} without remainder +const_eval_expected_inbounds_pointer = + expected a pointer to {$inbounds_size_abs -> + [0] some allocation + *[x] {$inbounds_size_is_neg -> + [false] {$inbounds_size_abs -> + [1] 1 byte of memory + *[x] {$inbounds_size_abs} bytes of memory + } + *[true] the end of {$inbounds_size_abs -> + [1] 1 byte of memory + *[x] {$inbounds_size_abs} bytes of memory + } + } + } + const_eval_extern_static = cannot access extern static ({$did}) const_eval_extern_type_field = `extern type` field does not have a known offset @@ -233,16 +248,17 @@ const_eval_nullary_intrinsic_fail = const_eval_offset_from_different_allocations = `{$name}` called on pointers into different allocations -const_eval_offset_from_different_integers = - `{$name}` called on different pointers without provenance (i.e., without an associated allocation) const_eval_offset_from_overflow = `{$name}` called when first pointer is too far ahead of second const_eval_offset_from_test = - out-of-bounds `offset_from` + out-of-bounds `offset_from` origin const_eval_offset_from_underflow = `{$name}` called when first pointer is too far before second const_eval_offset_from_unsigned_overflow = - `ptr_offset_from_unsigned` called when first pointer has smaller offset than second: {$a_offset} < {$b_offset} + `ptr_offset_from_unsigned` called when first pointer has smaller {$is_addr -> + [true] address + *[false] offset + } than second: {$a_offset} < {$b_offset} const_eval_operator_non_const = cannot call non-const operator in {const_eval_const_context}s @@ -261,13 +277,26 @@ const_eval_partial_pointer_copy = const_eval_partial_pointer_overwrite = unable to overwrite parts of a pointer in memory at {$ptr} const_eval_pointer_arithmetic_overflow = - overflowing in-bounds pointer arithmetic + overflowing pointer arithmetic: the total offset in bytes does not fit in an `isize` const_eval_pointer_arithmetic_test = out-of-bounds pointer arithmetic const_eval_pointer_out_of_bounds = - {$bad_pointer_message}: {$alloc_id} has size {$alloc_size}, so pointer to {$ptr_size} {$ptr_size -> - [1] byte - *[many] bytes - } starting at offset {$ptr_offset} is out-of-bounds + {$bad_pointer_message}: {const_eval_expected_inbounds_pointer}, but got {$pointer} {$ptr_offset_is_neg -> + [true] which points to before the beginning of the allocation + *[false] {$inbounds_size_is_neg -> + [true] {$ptr_offset_abs -> + [0] which is at the beginning of the allocation + *[other] which does not have enough space to the beginning of the allocation + } + *[false] {$alloc_size_minus_ptr_offset -> + [0] which is at or beyond the end of the allocation of size {$alloc_size -> + [1] 1 byte + *[x] {$alloc_size} bytes + } + [1] which is only 1 byte from the end of the allocation + *[x] which is only {$alloc_size_minus_ptr_offset} bytes from the end of the allocation + } + } + } const_eval_pointer_use_after_free = {$bad_pointer_message}: {$alloc_id} has been freed, so this pointer is dangling const_eval_ptr_as_bytes_1 = @@ -287,9 +316,6 @@ const_eval_range_upper = less or equal to {$hi} const_eval_range_wrapping = less or equal to {$hi}, or greater or equal to {$lo} const_eval_raw_bytes = the raw bytes of the constant (size: {$size}, align: {$align}) {"{"}{$bytes}{"}"} -const_eval_raw_eq_with_provenance = - `raw_eq` on bytes with provenance - const_eval_raw_ptr_comparison = pointers cannot be reliably compared during const eval .note = see issue #53020 for more information @@ -465,5 +491,3 @@ const_eval_write_through_immutable_pointer = const_eval_write_to_read_only = writing to {$allocation} which is read-only -const_eval_zst_pointer_out_of_bounds = - {$bad_pointer_message}: {$alloc_id} has size {$alloc_size}, so pointer at offset {$ptr_offset} is out-of-bounds diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 8700ec4c21045..3ded81b90ffc1 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -1,5 +1,8 @@ //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations. +use std::mem; +use std::ops::Deref; + use rustc_errors::{Diag, ErrorGuaranteed}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, LangItem}; @@ -9,17 +12,13 @@ use rustc_infer::traits::ObligationCause; use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; use rustc_middle::span_bug; -use rustc_middle::ty::{self, adjustment::PointerCoercion, Ty, TyCtxt}; -use rustc_middle::ty::{Instance, InstanceKind, TypeVisitableExt}; +use rustc_middle::ty::adjustment::PointerCoercion; +use rustc_middle::ty::{self, Instance, InstanceKind, Ty, TyCtxt, TypeVisitableExt}; use rustc_mir_dataflow::Analysis; use rustc_span::{sym, Span, Symbol, DUMMY_SP}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt}; use rustc_type_ir::visit::{TypeSuperVisitable, TypeVisitor}; - -use std::mem; -use std::ops::Deref; - use tracing::{debug, instrument, trace}; use super::ops::{self, NonConstOp, Status}; @@ -635,10 +634,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { trace!( "visit_projection_elem: place_ref={:?} elem={:?} \ context={:?} location={:?}", - place_ref, - elem, - context, - location, + place_ref, elem, context, location, ); self.super_projection_elem(place_ref, elem, context, location); diff --git a/compiler/rustc_const_eval/src/check_consts/mod.rs b/compiler/rustc_const_eval/src/check_consts/mod.rs index ac8f0d842ee41..15ac4cedcc328 100644 --- a/compiler/rustc_const_eval/src/check_consts/mod.rs +++ b/compiler/rustc_const_eval/src/check_consts/mod.rs @@ -4,14 +4,12 @@ //! has interior mutability or needs to be dropped, as well as the visitor that emits errors when //! it finds operations that are invalid in a certain context. -use rustc_attr as attr; use rustc_errors::DiagCtxtHandle; -use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_middle::bug; -use rustc_middle::mir; use rustc_middle::ty::{self, PolyFnSig, TyCtxt}; +use rustc_middle::{bug, mir}; use rustc_span::Symbol; +use {rustc_attr as attr, rustc_hir as hir}; pub use self::qualifs::Qualif; diff --git a/compiler/rustc_const_eval/src/check_consts/ops.rs b/compiler/rustc_const_eval/src/check_consts/ops.rs index 55432e63ef9d7..f47a2ec8f7598 100644 --- a/compiler/rustc_const_eval/src/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/check_consts/ops.rs @@ -2,7 +2,8 @@ use hir::def_id::LocalDefId; use hir::{ConstContext, LangItem}; -use rustc_errors::{codes::*, Diag}; +use rustc_errors::codes::*; +use rustc_errors::Diag; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_infer::infer::TyCtxtInferExt; diff --git a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs index f5e745454ab84..c4f06e5af0be5 100644 --- a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs +++ b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs @@ -1,7 +1,8 @@ use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::{self, BasicBlock, Location}; use rustc_middle::ty::{Ty, TyCtxt}; -use rustc_span::{symbol::sym, Span}; +use rustc_span::symbol::sym; +use rustc_span::Span; use tracing::trace; use super::check::Qualifs; diff --git a/compiler/rustc_const_eval/src/check_consts/qualifs.rs b/compiler/rustc_const_eval/src/check_consts/qualifs.rs index 9fd7219499b27..c0f2d113c7e31 100644 --- a/compiler/rustc_const_eval/src/check_consts/qualifs.rs +++ b/compiler/rustc_const_eval/src/check_consts/qualifs.rs @@ -5,11 +5,10 @@ use rustc_errors::ErrorGuaranteed; use rustc_hir::LangItem; use rustc_infer::infer::TyCtxtInferExt; -use rustc_middle::bug; -use rustc_middle::mir; use rustc_middle::mir::*; use rustc_middle::traits::BuiltinImplSource; use rustc_middle::ty::{self, AdtDef, GenericArgsRef, Ty}; +use rustc_middle::{bug, mir}; use rustc_trait_selection::traits::{ ImplSource, Obligation, ObligationCause, ObligationCtxt, SelectionContext, }; @@ -100,7 +99,33 @@ impl Qualif for HasMutInterior { } fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { - !ty.is_freeze(cx.tcx, cx.param_env) + // Avoid selecting for simple cases, such as builtin types. + if ty.is_trivially_freeze() { + return false; + } + + // We do not use `ty.is_freeze` here, because that requires revealing opaque types, which + // requires borrowck, which in turn will invoke mir_const_qualifs again, causing a cycle error. + // Instead we invoke an obligation context manually, and provide the opaque type inference settings + // that allow the trait solver to just error out instead of cycling. + let freeze_def_id = cx.tcx.require_lang_item(LangItem::Freeze, Some(cx.body.span)); + + let obligation = Obligation::new( + cx.tcx, + ObligationCause::dummy_with_span(cx.body.span), + cx.param_env, + ty::TraitRef::new(cx.tcx, freeze_def_id, [ty::GenericArg::from(ty)]), + ); + + let infcx = cx + .tcx + .infer_ctxt() + .with_opaque_type_inference(cx.body.source.def_id().expect_local()) + .build(); + let ocx = ObligationCtxt::new(&infcx); + ocx.register_obligation(obligation); + let errors = ocx.select_all_or_error(); + !errors.is_empty() } fn in_adt_inherently<'tcx>( diff --git a/compiler/rustc_const_eval/src/check_consts/resolver.rs b/compiler/rustc_const_eval/src/check_consts/resolver.rs index 011341472b433..ea3a5264357c9 100644 --- a/compiler/rustc_const_eval/src/check_consts/resolver.rs +++ b/compiler/rustc_const_eval/src/check_consts/resolver.rs @@ -2,17 +2,16 @@ //! //! This contains the dataflow analysis used to track `Qualif`s on complex control-flow graphs. +use std::fmt; +use std::marker::PhantomData; + use rustc_index::bit_set::BitSet; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::{ self, BasicBlock, CallReturnPlaces, Local, Location, Statement, StatementKind, TerminatorEdges, }; use rustc_mir_dataflow::fmt::DebugWithContext; -use rustc_mir_dataflow::JoinSemiLattice; -use rustc_mir_dataflow::{Analysis, AnalysisDomain}; - -use std::fmt; -use std::marker::PhantomData; +use rustc_mir_dataflow::{Analysis, AnalysisDomain, JoinSemiLattice}; use super::{qualifs, ConstCx, Qualif}; diff --git a/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs b/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs index 9a98677a84482..aa7449e8ad269 100644 --- a/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs @@ -1,14 +1,14 @@ -use crate::interpret::{ - self, throw_machine_stop, HasStaticRootDefId, ImmTy, Immediate, InterpCx, PointerArithmetic, -}; use rustc_middle::mir::interpret::{AllocId, ConstAllocation, InterpResult}; use rustc_middle::mir::*; use rustc_middle::query::TyCtxtAt; -use rustc_middle::ty; use rustc_middle::ty::layout::TyAndLayout; -use rustc_middle::{bug, span_bug}; +use rustc_middle::{bug, span_bug, ty}; use rustc_span::def_id::DefId; +use crate::interpret::{ + self, throw_machine_stop, HasStaticRootDefId, ImmTy, Immediate, InterpCx, PointerArithmetic, +}; + /// Macro for machine-specific `InterpError` without allocation. /// (These will never be shown to the user, but they help diagnose ICEs.) pub macro throw_machine_stop_str($($tt:tt)*) {{ diff --git a/compiler/rustc_const_eval/src/const_eval/error.rs b/compiler/rustc_const_eval/src/const_eval/error.rs index b17dc7f3ddde6..00bbd9337f7e1 100644 --- a/compiler/rustc_const_eval/src/const_eval/error.rs +++ b/compiler/rustc_const_eval/src/const_eval/error.rs @@ -4,14 +4,15 @@ use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage, Diagnostic, IntoDiagA use rustc_middle::mir::interpret::{Provenance, ReportedErrorInfo}; use rustc_middle::mir::AssertKind; use rustc_middle::query::TyCtxtAt; -use rustc_middle::ty::TyCtxt; -use rustc_middle::ty::{layout::LayoutError, 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::{err_inval, err_machine_stop}; -use crate::interpret::{ErrorHandled, Frame, InterpError, InterpErrorInfo, MachineStopType}; +use crate::interpret::{ + err_inval, err_machine_stop, ErrorHandled, Frame, InterpError, InterpErrorInfo, MachineStopType, +}; /// The CTFE machine has some custom error kinds. #[derive(Clone, Debug)] @@ -25,8 +26,9 @@ pub enum ConstEvalErrKind { impl MachineStopType for ConstEvalErrKind { fn diagnostic_message(&self) -> DiagMessage { - use crate::fluent_generated::*; use ConstEvalErrKind::*; + + use crate::fluent_generated::*; match self { ConstAccessesMutGlobal => const_eval_const_accesses_mut_global, ModifiedGlobal => const_eval_modified_global, 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 d8efaa66415fb..6d5bca5731331 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -1,8 +1,6 @@ use std::sync::atomic::Ordering::Relaxed; use either::{Left, Right}; -use tracing::{debug, instrument, trace}; - use rustc_hir::def::DefKind; use rustc_middle::bug; use rustc_middle::mir::interpret::{AllocId, ErrorHandled, InterpErrorInfo}; @@ -16,17 +14,16 @@ use rustc_session::lint; use rustc_span::def_id::LocalDefId; use rustc_span::{Span, DUMMY_SP}; use rustc_target::abi::{self, Abi}; +use tracing::{debug, instrument, trace}; use super::{CanAccessMutGlobal, CompileTimeInterpCx, CompileTimeMachine}; use crate::const_eval::CheckAlignment; -use crate::errors::ConstEvalError; -use crate::errors::{self, DanglingPtrInFinal}; +use crate::errors::{self, ConstEvalError, DanglingPtrInFinal}; use crate::interpret::{ - create_static_alloc, intern_const_alloc_recursive, CtfeValidationMode, GlobalId, Immediate, - InternKind, InterpCx, InterpError, InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking, - StackPopCleanup, + create_static_alloc, eval_nullary_intrinsic, intern_const_alloc_recursive, throw_exhaust, + CtfeValidationMode, GlobalId, Immediate, InternKind, InternResult, InterpCx, InterpError, + InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking, StackPopCleanup, }; -use crate::interpret::{eval_nullary_intrinsic, throw_exhaust, InternResult}; use crate::CTRL_C_RECEIVED; // Returns a pointer to where the result lives @@ -399,7 +396,7 @@ fn const_validate_mplace<'tcx>( let alloc_id = mplace.ptr().provenance.unwrap().alloc_id(); let mut ref_tracking = RefTracking::new(mplace.clone()); let mut inner = false; - while let Some((mplace, path)) = ref_tracking.todo.pop() { + while let Some((mplace, path)) = ref_tracking.next() { let mode = match ecx.tcx.static_mutability(cid.instance.def_id()) { _ if cid.promoted.is_some() => CtfeValidationMode::Promoted, Some(mutbl) => CtfeValidationMode::Static { mutbl }, // a `static` diff --git a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs index 7acd08e0cceb6..ca0993f05802c 100644 --- a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs @@ -1,10 +1,9 @@ -use rustc_attr as attr; -use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::Symbol; +use {rustc_attr as attr, rustc_hir as hir}; /// Whether the `def_id` is an unstable const fn and what feature gate(s) are necessary to enable /// it. diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 17e1d8566c26c..79e8e2127765a 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -4,18 +4,14 @@ use std::hash::Hash; use std::ops::ControlFlow; use rustc_ast::Mutability; -use rustc_data_structures::fx::FxIndexMap; -use rustc_data_structures::fx::IndexEntry; -use rustc_hir::def_id::DefId; -use rustc_hir::def_id::LocalDefId; -use rustc_hir::LangItem; -use rustc_hir::{self as hir, CRATE_HIR_ID}; -use rustc_middle::bug; -use rustc_middle::mir; +use rustc_data_structures::fx::{FxIndexMap, IndexEntry}; +use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::{self as hir, LangItem, CRATE_HIR_ID}; use rustc_middle::mir::AssertMessage; use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::layout::{FnAbiOf, TyAndLayout}; use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::{bug, mir}; use rustc_session::lint::builtin::WRITES_THROUGH_IMMUTABLE_POINTER; use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; @@ -23,6 +19,7 @@ use rustc_target::abi::{Align, Size}; use rustc_target::spec::abi::Abi as CallAbi; use tracing::debug; +use super::error::*; use crate::errors::{LongRunning, LongRunningWarn}; use crate::fluent_generated as fluent; use crate::interpret::{ @@ -31,8 +28,6 @@ use crate::interpret::{ GlobalAlloc, ImmTy, InterpCx, InterpResult, MPlaceTy, OpTy, Pointer, PointerArithmetic, Scalar, }; -use super::error::*; - /// When hitting this many interpreted terminators we emit a deny by default lint /// that notfies the user that their constant takes a long time to evaluate. If that's /// what they intended, they can just allow the lint. @@ -201,7 +196,8 @@ impl<'tcx> CompileTimeInterpCx<'tcx> { let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo()); - use rustc_session::{config::RemapPathScopeComponents, RemapFileNameExt}; + use rustc_session::config::RemapPathScopeComponents; + use rustc_session::RemapFileNameExt; ( Symbol::intern( &caller @@ -299,7 +295,7 @@ impl<'tcx> CompileTimeInterpCx<'tcx> { ); } - match self.ptr_try_get_alloc_id(ptr) { + match self.ptr_try_get_alloc_id(ptr, 0) { Ok((alloc_id, offset, _extra)) => { let (_size, alloc_align, _kind) = self.get_alloc_info(alloc_id); @@ -462,7 +458,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { _unwind: mir::UnwindAction, ) -> InterpResult<'tcx, Option>> { // Shared intrinsics. - if ecx.emulate_intrinsic(instance, args, dest, target)? { + if ecx.eval_intrinsic(instance, args, dest, target)? { return Ok(None); } let intrinsic_name = ecx.tcx.item_name(instance.def_id()); @@ -514,7 +510,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { // If an allocation is created in an another const, // we don't deallocate it. - let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr)?; + let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr, 0)?; let is_allocated_in_another_const = matches!( ecx.tcx.try_get_global_alloc(alloc_id), Some(interpret::GlobalAlloc::Memory(_)) diff --git a/compiler/rustc_const_eval/src/const_eval/mod.rs b/compiler/rustc_const_eval/src/const_eval/mod.rs index 3a6dc81eff11f..8add23ed22fb3 100644 --- a/compiler/rustc_const_eval/src/const_eval/mod.rs +++ b/compiler/rustc_const_eval/src/const_eval/mod.rs @@ -1,10 +1,9 @@ // Not in interpret to make sure we do not use private implementation details -use rustc_middle::bug; -use rustc_middle::mir; use rustc_middle::mir::interpret::InterpErrorInfo; use rustc_middle::query::{Key, TyCtxtAt}; use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::{bug, mir}; use rustc_target::abi::VariantIdx; use tracing::instrument; diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index 3bc01510730b4..8227c04594883 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -1,9 +1,8 @@ use rustc_data_structures::stack::ensure_sufficient_stack; -use rustc_middle::bug; -use rustc_middle::mir; use rustc_middle::mir::interpret::{EvalToValTreeResult, GlobalId}; use rustc_middle::ty::layout::{LayoutCx, LayoutOf, TyAndLayout}; use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt}; +use rustc_middle::{bug, mir}; use rustc_span::DUMMY_SP; use rustc_target::abi::{Abi, VariantIdx}; use tracing::{debug, instrument, trace}; @@ -13,10 +12,9 @@ use super::machine::CompileTimeInterpCx; use super::{ValTreeCreationError, ValTreeCreationResult, VALTREE_MAX_NODES}; use crate::const_eval::CanAccessMutGlobal; use crate::errors::MaxNumNodesInConstErr; -use crate::interpret::MPlaceTy; use crate::interpret::{ - intern_const_alloc_recursive, ImmTy, Immediate, InternKind, MemPlaceMeta, MemoryKind, PlaceTy, - Projectable, Scalar, + intern_const_alloc_recursive, ImmTy, Immediate, InternKind, MPlaceTy, MemPlaceMeta, MemoryKind, + PlaceTy, Projectable, Scalar, }; #[instrument(skip(ecx), level = "debug")] diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/errors.rs index 292d6ba9d08a4..7afb92c08ec9a 100644 --- a/compiler/rustc_const_eval/src/errors.rs +++ b/compiler/rustc_const_eval/src/errors.rs @@ -1,20 +1,22 @@ use std::borrow::Cow; +use std::fmt::Write; use either::Either; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, Diag, DiagArgValue, DiagCtxtHandle, DiagMessage, Diagnostic, EmissionGuarantee, Level, + Diag, DiagArgValue, DiagCtxtHandle, DiagMessage, Diagnostic, EmissionGuarantee, Level, }; use rustc_hir::ConstContext; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::mir::interpret::{ - CheckInAllocMsg, ExpectedKind, InterpError, InvalidMetaKind, InvalidProgramInfo, Misalignment, - PointerKind, ResourceExhaustionInfo, UndefinedBehaviorInfo, UnsupportedOpInfo, - ValidationErrorInfo, + CheckInAllocMsg, CtfeProvenance, ExpectedKind, InterpError, InvalidMetaKind, + InvalidProgramInfo, Misalignment, Pointer, PointerKind, ResourceExhaustionInfo, + UndefinedBehaviorInfo, UnsupportedOpInfo, ValidationErrorInfo, }; use rustc_middle::ty::{self, Mutability, Ty}; use rustc_span::Span; use rustc_target::abi::call::AdjustForForeignAbiError; -use rustc_target::abi::{Size, WrappingRange}; +use rustc_target::abi::WrappingRange; use crate::interpret::InternKind; @@ -468,8 +470,9 @@ fn bad_pointer_message(msg: CheckInAllocMsg, dcx: DiagCtxtHandle<'_>) -> String impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> { fn diagnostic_message(&self) -> DiagMessage { - use crate::fluent_generated::*; use UndefinedBehaviorInfo::*; + + use crate::fluent_generated::*; match self { Ub(msg) => msg.clone().into(), Custom(x) => (x.msg)(), @@ -488,10 +491,9 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> { InvalidMeta(InvalidMetaKind::TooBig) => const_eval_invalid_meta, UnterminatedCString(_) => const_eval_unterminated_c_string, PointerUseAfterFree(_, _) => const_eval_pointer_use_after_free, - PointerOutOfBounds { ptr_size: Size::ZERO, .. } => const_eval_zst_pointer_out_of_bounds, PointerOutOfBounds { .. } => const_eval_pointer_out_of_bounds, - DanglingIntPointer(0, _) => const_eval_dangling_null_pointer, - DanglingIntPointer(_, _) => const_eval_dangling_int_pointer, + DanglingIntPointer { addr: 0, .. } => const_eval_dangling_null_pointer, + DanglingIntPointer { .. } => const_eval_dangling_int_pointer, AlignmentCheckFailed { .. } => const_eval_alignment_check_failed, WriteToReadOnly(_) => const_eval_write_to_read_only, DerefFunctionPointer(_) => const_eval_deref_function_pointer, @@ -573,18 +575,37 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> { diag.arg("alloc_id", alloc_id) .arg("bad_pointer_message", bad_pointer_message(msg, dcx)); } - PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, ptr_size, msg } => { - diag.arg("alloc_id", alloc_id) - .arg("alloc_size", alloc_size.bytes()) - .arg("ptr_offset", ptr_offset) - .arg("ptr_size", ptr_size.bytes()) - .arg("bad_pointer_message", bad_pointer_message(msg, dcx)); + PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, inbounds_size, msg } => { + diag.arg("alloc_size", alloc_size.bytes()); + diag.arg("bad_pointer_message", bad_pointer_message(msg, dcx)); + diag.arg("pointer", { + let mut out = format!("{:?}", alloc_id); + if ptr_offset > 0 { + write!(out, "+{:#x}", ptr_offset).unwrap(); + } else if ptr_offset < 0 { + write!(out, "-{:#x}", ptr_offset.unsigned_abs()).unwrap(); + } + out + }); + diag.arg("inbounds_size_is_neg", inbounds_size < 0); + diag.arg("inbounds_size_abs", inbounds_size.unsigned_abs()); + diag.arg("ptr_offset_is_neg", ptr_offset < 0); + diag.arg("ptr_offset_abs", ptr_offset.unsigned_abs()); + diag.arg( + "alloc_size_minus_ptr_offset", + alloc_size.bytes().saturating_sub(ptr_offset as u64), + ); } - DanglingIntPointer(ptr, msg) => { - if ptr != 0 { - diag.arg("pointer", format!("{ptr:#x}[noalloc]")); + DanglingIntPointer { addr, inbounds_size, msg } => { + if addr != 0 { + diag.arg( + "pointer", + Pointer::>::from_addr_invalid(addr).to_string(), + ); } + diag.arg("inbounds_size_is_neg", inbounds_size < 0); + diag.arg("inbounds_size_abs", inbounds_size.unsigned_abs()); diag.arg("bad_pointer_message", bad_pointer_message(msg, dcx)); } AlignmentCheckFailed(Misalignment { required, has }, msg) => { @@ -630,8 +651,9 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> { impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> { fn diagnostic_message(&self) -> DiagMessage { - use crate::fluent_generated::*; use rustc_middle::mir::interpret::ValidationErrorKind::*; + + use crate::fluent_generated::*; match self.kind { PtrToUninhabited { ptr_kind: PointerKind::Box, .. } => { const_eval_validation_box_to_uninhabited @@ -702,9 +724,10 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> { } fn add_args(self, err: &mut Diag<'_, G>) { - use crate::fluent_generated as fluent; use rustc_middle::mir::interpret::ValidationErrorKind::*; + use crate::fluent_generated as fluent; + if let PointerAsInt { .. } | PartialPointer = self.kind { err.help(fluent::const_eval_ptr_as_bytes_1); err.help(fluent::const_eval_ptr_as_bytes_2); @@ -835,9 +858,9 @@ impl ReportErrorExt for UnsupportedOpInfo { } } fn add_args(self, diag: &mut Diag<'_, G>) { - use crate::fluent_generated::*; - use UnsupportedOpInfo::*; + + use crate::fluent_generated::*; if let ReadPointerAsInt(_) | OverwritePartialPointer(_) | ReadPartialPointer(_) = self { diag.help(const_eval_ptr_as_bytes_1); diag.help(const_eval_ptr_as_bytes_2); diff --git a/compiler/rustc_const_eval/src/interpret/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index bd2a5812cfad2..b2f07de0ac4e2 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -12,11 +12,10 @@ use rustc_target::abi::Integer; use rustc_type_ir::TyKind::*; use tracing::trace; +use super::util::ensure_monomorphic_enough; use super::{ - err_inval, throw_ub, throw_ub_custom, util::ensure_monomorphic_enough, FnVal, ImmTy, Immediate, - InterpCx, Machine, OpTy, PlaceTy, + err_inval, throw_ub, throw_ub_custom, FnVal, ImmTy, Immediate, InterpCx, Machine, OpTy, PlaceTy, }; - use crate::fluent_generated as fluent; impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { diff --git a/compiler/rustc_const_eval/src/interpret/discriminant.rs b/compiler/rustc_const_eval/src/interpret/discriminant.rs index 181c71153866c..0008a15722bde 100644 --- a/compiler/rustc_const_eval/src/interpret/discriminant.rs +++ b/compiler/rustc_const_eval/src/interpret/discriminant.rs @@ -1,11 +1,9 @@ //! Functions for reading and writing discriminants of multi-variant layouts (enums and coroutines). -use rustc_middle::mir; -use rustc_middle::span_bug; use rustc_middle::ty::layout::{LayoutOf, PrimitiveExt}; use rustc_middle::ty::{self, CoroutineArgsExt, ScalarInt, Ty}; -use rustc_target::abi::{self, TagEncoding}; -use rustc_target::abi::{VariantIdx, Variants}; +use rustc_middle::{mir, span_bug}; +use rustc_target::abi::{self, TagEncoding, VariantIdx, Variants}; use tracing::{instrument, trace}; use super::{ diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 9fddeec2973a5..18d585e4a7a7e 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -2,16 +2,14 @@ use std::cell::Cell; use std::{fmt, mem}; use either::{Either, Left, Right}; -use rustc_infer::infer::at::ToTrace; -use rustc_infer::traits::ObligationCause; -use rustc_trait_selection::traits::ObligationCtxt; -use tracing::{debug, info, info_span, instrument, trace}; - use rustc_errors::DiagCtxtHandle; -use rustc_hir::{self as hir, def_id::DefId, definitions::DefPathData}; +use rustc_hir::def_id::DefId; +use rustc_hir::definitions::DefPathData; +use rustc_hir::{self as hir}; use rustc_index::IndexVec; +use rustc_infer::infer::at::ToTrace; use rustc_infer::infer::TyCtxtInferExt; -use rustc_middle::mir; +use rustc_infer::traits::ObligationCause; use rustc_middle::mir::interpret::{ CtfeProvenance, ErrorHandled, InvalidMetaKind, ReportedErrorInfo, }; @@ -21,11 +19,14 @@ use rustc_middle::ty::layout::{ TyAndLayout, }; use rustc_middle::ty::{self, GenericArgsRef, ParamEnv, Ty, TyCtxt, TypeFoldable, Variance}; -use rustc_middle::{bug, span_bug}; +use rustc_middle::{bug, mir, span_bug}; use rustc_mir_dataflow::storage::always_storage_live_locals; use rustc_session::Limit; use rustc_span::Span; -use rustc_target::abi::{call::FnAbi, Align, HasDataLayout, Size, TargetDataLayout}; +use rustc_target::abi::call::FnAbi; +use rustc_target::abi::{Align, HasDataLayout, Size, TargetDataLayout}; +use rustc_trait_selection::traits::ObligationCtxt; +use tracing::{debug, info, info_span, instrument, trace}; use super::{ err_inval, throw_inval, throw_ub, throw_ub_custom, throw_unsup, GlobalId, Immediate, @@ -33,9 +34,7 @@ use super::{ OpTy, Operand, Place, PlaceTy, Pointer, PointerArithmetic, Projectable, Provenance, ReturnAction, Scalar, }; -use crate::errors; -use crate::util; -use crate::{fluent_generated as fluent, ReportErrorExt}; +use crate::{errors, fluent_generated as fluent, util, ReportErrorExt}; pub struct InterpCx<'tcx, M: Machine<'tcx>> { /// Stores the `Machine` instance. @@ -561,17 +560,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { self.frame().body } - #[inline(always)] - pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 { - assert!(ty.abi.is_signed()); - ty.size.sign_extend(value) - } - - #[inline(always)] - pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 { - ty.size.truncate(value) - } - #[inline] pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool { ty.is_freeze(*self.tcx, self.param_env) @@ -889,7 +877,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { body: &'tcx mir::Body<'tcx>, ) -> InterpResult<'tcx> { // Make sure all the constants required by this frame evaluate successfully (post-monomorphization check). - for &const_ in &body.required_consts { + for &const_ in body.required_consts() { let c = self.instantiate_from_current_frame_and_normalize_erasing_regions(const_.const_)?; c.eval(*self.tcx, self.param_env, const_.span).map_err(|err| { diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index b227565f8f91a..9210ec4e16fd0 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -3,26 +3,21 @@ //! and miri. use rustc_hir::def_id::DefId; -use rustc_middle::ty; -use rustc_middle::ty::layout::{LayoutOf as _, ValidityRequirement}; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{Ty, TyCtxt}; -use rustc_middle::{ - bug, - mir::{self, BinOp, ConstValue, NonDivergingIntrinsic}, - ty::layout::TyAndLayout, -}; +use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic}; +use rustc_middle::ty::layout::{LayoutOf as _, TyAndLayout, ValidityRequirement}; +use rustc_middle::ty::{GenericArgsRef, Ty, TyCtxt}; +use rustc_middle::{bug, ty}; use rustc_span::symbol::{sym, Symbol}; use rustc_target::abi::Size; use tracing::trace; +use super::memory::MemoryKind; +use super::util::ensure_monomorphic_enough; use super::{ - err_inval, err_ub_custom, err_unsup_format, memory::MemoryKind, throw_inval, throw_ub_custom, - throw_ub_format, util::ensure_monomorphic_enough, Allocation, CheckInAllocMsg, ConstAllocation, - GlobalId, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, Pointer, PointerArithmetic, - Provenance, Scalar, + err_inval, err_ub_custom, err_unsup_format, throw_inval, throw_ub_custom, throw_ub_format, + Allocation, CheckInAllocMsg, ConstAllocation, GlobalId, ImmTy, InterpCx, InterpResult, + MPlaceTy, Machine, OpTy, Pointer, PointerArithmetic, Provenance, Scalar, }; - use crate::fluent_generated as fluent; /// Directly returns an `Allocation` containing an absolute path representation of the given type. @@ -102,7 +97,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// Returns `true` if emulation happened. /// Here we implement the intrinsics that are common to all Miri instances; individual machines can add their own /// intrinsic handling. - pub fn emulate_intrinsic( + pub fn eval_intrinsic( &mut self, instance: ty::Instance<'tcx>, args: &[OpTy<'tcx, M::Provenance>], @@ -211,7 +206,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } else { (val_bits >> shift_bits) | (val_bits << inv_shift_bits) }; - let truncated_bits = self.truncate(result_bits, layout_val); + let truncated_bits = layout_val.size.truncate(result_bits); let result = Scalar::from_uint(truncated_bits, layout_val.size); self.write_scalar(result, dest)?; } @@ -243,36 +238,22 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { let isize_layout = self.layout_of(self.tcx.types.isize)?; // Get offsets for both that are at least relative to the same base. - let (a_offset, b_offset) = - match (self.ptr_try_get_alloc_id(a), self.ptr_try_get_alloc_id(b)) { + // With `OFFSET_IS_ADDR` this is trivial; without it we need either + // two integers or two pointers into the same allocation. + let (a_offset, b_offset, is_addr) = if M::Provenance::OFFSET_IS_ADDR { + (a.addr().bytes(), b.addr().bytes(), /*is_addr*/ true) + } else { + match (self.ptr_try_get_alloc_id(a, 0), self.ptr_try_get_alloc_id(b, 0)) { (Err(a), Err(b)) => { - // Neither pointer points to an allocation. - // This is okay only if they are the same. - if a != b { - // We'd catch this below in the "dereferenceable" check, but - // show a nicer error for this particular case. - throw_ub_custom!( - fluent::const_eval_offset_from_different_integers, - name = intrinsic_name, - ); - } - // This will always return 0. - (a, b) + // Neither pointer points to an allocation, so they are both absolute. + (a, b, /*is_addr*/ true) } - _ if M::Provenance::OFFSET_IS_ADDR && a.addr() == b.addr() => { - // At least one of the pointers has provenance, but they also point to - // the same address so it doesn't matter; this is fine. `(0, 0)` means - // we pass all the checks below and return 0. - (0, 0) - } - // From here onwards, the pointers are definitely for different addresses - // (or we can't determine their absolute address). (Ok((a_alloc_id, a_offset, _)), Ok((b_alloc_id, b_offset, _))) if a_alloc_id == b_alloc_id => { // Found allocation for both, and it's the same. // Use these offsets for distance calculation. - (a_offset.bytes(), b_offset.bytes()) + (a_offset.bytes(), b_offset.bytes(), /*is_addr*/ false) } _ => { // Not into the same allocation -- this is UB. @@ -281,9 +262,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { name = intrinsic_name, ); } - }; + } + }; - // Compute distance. + // Compute distance: a - b. let dist = { // Addresses are unsigned, so this is a `usize` computation. We have to do the // overflow check separately anyway. @@ -300,6 +282,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { fluent::const_eval_offset_from_unsigned_overflow, a_offset = a_offset, b_offset = b_offset, + is_addr = is_addr, ); } // The signed form of the intrinsic allows this. If we interpret the @@ -328,14 +311,23 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } }; - // Check that the range between them is dereferenceable ("in-bounds or one past the - // end of the same allocation"). This is like the check in ptr_offset_inbounds. - let min_ptr = if dist >= 0 { b } else { a }; - self.check_ptr_access( - min_ptr, - Size::from_bytes(dist.unsigned_abs()), + // Check that the memory between them is dereferenceable at all, starting from the + // origin pointer: `dist` is `a - b`, so it is based on `b`. + self.check_ptr_access_signed(b, dist, CheckInAllocMsg::OffsetFromTest)?; + // Then check that this is also dereferenceable from `a`. This ensures that they are + // derived from the same allocation. + self.check_ptr_access_signed( + a, + dist.checked_neg().unwrap(), // i64::MIN is impossible as no allocation can be that large CheckInAllocMsg::OffsetFromTest, - )?; + ) + .map_err(|_| { + // Make the error more specific. + err_ub_custom!( + fluent::const_eval_offset_from_different_allocations, + name = intrinsic_name, + ) + })?; // Perform division by size to compute return value. let ret_layout = if intrinsic_name == sym::ptr_offset_from_unsigned { @@ -455,7 +447,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { Ok(true) } - pub(super) fn emulate_nondiverging_intrinsic( + pub(super) fn eval_nondiverging_intrinsic( &mut self, intrinsic: &NonDivergingIntrinsic<'tcx>, ) -> InterpResult<'tcx> { @@ -582,27 +574,16 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its - /// allocation. For integer pointers, we consider each of them their own tiny allocation of size - /// 0, so offset-by-0 (and only 0) is okay -- except that null cannot be offset by _any_ value. + /// allocation. pub fn ptr_offset_inbounds( &self, ptr: Pointer>, offset_bytes: i64, ) -> InterpResult<'tcx, Pointer>> { - // The offset being in bounds cannot rely on "wrapping around" the address space. - // So, first rule out overflows in the pointer arithmetic. - let offset_ptr = ptr.signed_offset(offset_bytes, self)?; - // ptr and offset_ptr must be in bounds of the same allocated object. This means all of the - // memory between these pointers must be accessible. Note that we do not require the - // pointers to be properly aligned (unlike a read/write operation). - let min_ptr = if offset_bytes >= 0 { ptr } else { offset_ptr }; - // This call handles checking for integer/null pointers. - self.check_ptr_access( - min_ptr, - Size::from_bytes(offset_bytes.unsigned_abs()), - CheckInAllocMsg::PointerArithmeticTest, - )?; - Ok(offset_ptr) + // The offset must be in bounds starting from `ptr`. + self.check_ptr_access_signed(ptr, offset_bytes, CheckInAllocMsg::PointerArithmeticTest)?; + // This also implies that there is no overflow, so we are done. + Ok(ptr.wrapping_signed_offset(offset_bytes, self)) } /// Copy `count*size_of::()` many bytes from `*src` to `*dst`. @@ -709,9 +690,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // zero-sized access return Ok(&[]); }; - if alloc_ref.has_provenance() { - throw_ub_custom!(fluent::const_eval_raw_eq_with_provenance); - } alloc_ref.get_bytes_strip_provenance() }; diff --git a/compiler/rustc_const_eval/src/interpret/machine.rs b/compiler/rustc_const_eval/src/interpret/machine.rs index 7f2e9ce06a5a0..bdce8253b2e76 100644 --- a/compiler/rustc_const_eval/src/interpret/machine.rs +++ b/compiler/rustc_const_eval/src/interpret/machine.rs @@ -8,10 +8,9 @@ use std::hash::Hash; use rustc_apfloat::{Float, FloatConvert}; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; -use rustc_middle::mir; use rustc_middle::query::TyCtxtAt; -use rustc_middle::ty; use rustc_middle::ty::layout::TyAndLayout; +use rustc_middle::{mir, ty}; use rustc_span::def_id::DefId; use rustc_span::Span; use rustc_target::abi::{Align, Size}; @@ -166,6 +165,13 @@ pub trait Machine<'tcx>: Sized { /// Whether to enforce the validity invariant for a specific layout. fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool; + /// Whether to enforce the validity invariant *recursively*. + fn enforce_validity_recursively( + _ecx: &InterpCx<'tcx, Self>, + _layout: TyAndLayout<'tcx>, + ) -> bool { + false + } /// Whether function calls should be [ABI](CallAbi)-checked. fn enforce_abi(_ecx: &InterpCx<'tcx, Self>) -> bool { @@ -322,15 +328,21 @@ pub trait Machine<'tcx>: Sized { ptr: Pointer, ) -> InterpResult<'tcx>; - /// Convert a pointer with provenance into an allocation-offset pair - /// and extra provenance info. + /// Convert a pointer with provenance into an allocation-offset pair and extra provenance info. + /// `size` says how many bytes of memory are expected at that pointer. The *sign* of `size` can + /// be used to disambiguate situations where a wildcard pointer sits right in between two + /// allocations. /// - /// The returned `AllocId` must be the same as `ptr.provenance.get_alloc_id()`. + /// If `ptr.provenance.get_alloc_id()` is `Some(p)`, the returned `AllocId` must be `p`. + /// The resulting `AllocId` will just be used for that one step and the forgotten again + /// (i.e., we'll never turn the data returned here back into a `Pointer` that might be + /// stored in machine state). /// /// When this fails, that means the pointer does not point to a live allocation. fn ptr_get_alloc( ecx: &InterpCx<'tcx, Self>, ptr: Pointer, + size: i64, ) -> Option<(AllocId, Size, Self::ProvenanceExtra)>; /// Called to adjust global allocations to the Provenance and AllocExtra of this machine. @@ -659,6 +671,7 @@ pub macro compile_time_machine(<$tcx: lifetime>) { fn ptr_get_alloc( _ecx: &InterpCx<$tcx, Self>, ptr: Pointer, + _size: i64, ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> { // We know `offset` is relative to the allocation, so we can use `into_parts`. let (prov, offset) = ptr.into_parts(); diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index 36fe8dfdd29b7..2e5d0ae773654 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -10,8 +10,7 @@ use std::assert_matches::assert_matches; use std::borrow::Cow; use std::cell::Cell; use std::collections::VecDeque; -use std::fmt; -use std::ptr; +use std::{fmt, ptr}; use rustc_ast::Mutability; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; @@ -20,17 +19,15 @@ use rustc_middle::bug; use rustc_middle::mir::display_allocation; use rustc_middle::ty::{self, Instance, ParamEnv, Ty, TyCtxt}; use rustc_target::abi::{Align, HasDataLayout, Size}; - use tracing::{debug, instrument, trace}; -use crate::fluent_generated as fluent; - use super::{ alloc_range, err_ub, err_ub_custom, throw_ub, throw_ub_custom, throw_unsup, throw_unsup_format, AllocBytes, AllocId, AllocMap, AllocRange, Allocation, CheckAlignMsg, CheckInAllocMsg, CtfeProvenance, GlobalAlloc, InterpCx, InterpResult, Machine, MayLeak, Misalignment, Pointer, PointerArithmetic, Provenance, Scalar, }; +use crate::fluent_generated as fluent; #[derive(Debug, PartialEq, Copy, Clone)] pub enum MemoryKind { @@ -264,7 +261,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { new_align: Align, kind: MemoryKind, ) -> InterpResult<'tcx, Pointer> { - let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr)?; + let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr, 0)?; if offset.bytes() != 0 { throw_ub_custom!( fluent::const_eval_realloc_or_alloc_with_offset, @@ -294,7 +291,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { old_size_and_align: Option<(Size, Align)>, kind: MemoryKind, ) -> InterpResult<'tcx> { - let (alloc_id, offset, prov) = self.ptr_get_alloc_id(ptr)?; + let (alloc_id, offset, prov) = self.ptr_get_alloc_id(ptr, 0)?; trace!("deallocating: {alloc_id:?}"); if offset.bytes() != 0 { @@ -386,6 +383,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ptr: Pointer>, size: Size, ) -> InterpResult<'tcx, Option<(AllocId, Size, M::ProvenanceExtra)>> { + let size = i64::try_from(size.bytes()).unwrap(); // it would be an error to even ask for more than isize::MAX bytes self.check_and_deref_ptr( ptr, size, @@ -406,6 +404,23 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ptr: Pointer>, size: Size, msg: CheckInAllocMsg, + ) -> InterpResult<'tcx> { + let size = i64::try_from(size.bytes()).unwrap(); // it would be an error to even ask for more than isize::MAX bytes + self.check_and_deref_ptr(ptr, size, msg, |alloc_id, _, _| { + let (size, align) = self.get_live_alloc_size_and_align(alloc_id, msg)?; + Ok((size, align, ())) + })?; + Ok(()) + } + + /// Check whether the given pointer points to live memory for a signed amount of bytes. + /// A negative amounts means that the given range of memory to the left of the pointer + /// needs to be dereferenceable. + pub fn check_ptr_access_signed( + &self, + ptr: Pointer>, + size: i64, + msg: CheckInAllocMsg, ) -> InterpResult<'tcx> { self.check_and_deref_ptr(ptr, size, msg, |alloc_id, _, _| { let (size, align) = self.get_live_alloc_size_and_align(alloc_id, msg)?; @@ -416,7 +431,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// Low-level helper function to check if a ptr is in-bounds and potentially return a reference /// to the allocation it points to. Supports both shared and mutable references, as the actual - /// checking is offloaded to a helper closure. + /// checking is offloaded to a helper closure. Supports signed sizes for checks "to the left" of + /// a pointer. /// /// `alloc_size` will only get called for non-zero-sized accesses. /// @@ -424,7 +440,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { fn check_and_deref_ptr( &self, ptr: Pointer>, - size: Size, + size: i64, msg: CheckInAllocMsg, alloc_size: impl FnOnce( AllocId, @@ -433,25 +449,32 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ) -> InterpResult<'tcx, (Size, Align, T)>, ) -> InterpResult<'tcx, Option> { // Everything is okay with size 0. - if size.bytes() == 0 { + if size == 0 { return Ok(None); } - Ok(match self.ptr_try_get_alloc_id(ptr) { + Ok(match self.ptr_try_get_alloc_id(ptr, size) { Err(addr) => { // We couldn't get a proper allocation. - throw_ub!(DanglingIntPointer(addr, msg)); + throw_ub!(DanglingIntPointer { addr, inbounds_size: size, msg }); } Ok((alloc_id, offset, prov)) => { let (alloc_size, _alloc_align, ret_val) = alloc_size(alloc_id, offset, prov)?; - // Test bounds. - // It is sufficient to check this for the end pointer. Also check for overflow! - if offset.checked_add(size, &self.tcx).is_none_or(|end| end > alloc_size) { + let offset = offset.bytes(); + // Compute absolute begin and end of the range. + let (begin, end) = if size >= 0 { + (Some(offset), offset.checked_add(size as u64)) + } else { + (offset.checked_sub(size.unsigned_abs()), Some(offset)) + }; + // Ensure both are within bounds. + let in_bounds = begin.is_some() && end.is_some_and(|e| e <= alloc_size.bytes()); + if !in_bounds { throw_ub!(PointerOutOfBounds { alloc_id, alloc_size, - ptr_offset: self.target_usize_to_isize(offset.bytes()), - ptr_size: size, + ptr_offset: self.sign_extend_to_target_isize(offset), + inbounds_size: size, msg, }) } @@ -482,7 +505,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } #[inline] - fn offset_misalignment(offset: u64, align: Align) -> Option { + fn is_offset_misaligned(offset: u64, align: Align) -> Option { if offset % align.bytes() == 0 { None } else { @@ -492,8 +515,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } - match self.ptr_try_get_alloc_id(ptr) { - Err(addr) => offset_misalignment(addr, align), + match self.ptr_try_get_alloc_id(ptr, 0) { + Err(addr) => is_offset_misaligned(addr, align), Ok((alloc_id, offset, _prov)) => { let (_size, alloc_align, kind) = self.get_alloc_info(alloc_id); if let Some(misalign) = @@ -501,14 +524,13 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { { Some(misalign) } else if M::Provenance::OFFSET_IS_ADDR { - // `use_addr_for_alignment_check` can only be true if `OFFSET_IS_ADDR` is true. - offset_misalignment(ptr.addr().bytes(), align) + is_offset_misaligned(ptr.addr().bytes(), align) } else { // Check allocation alignment and offset alignment. if alloc_align.bytes() < align.bytes() { Some(Misalignment { has: alloc_align, required: align }) } else { - offset_misalignment(offset.bytes(), align) + is_offset_misaligned(offset.bytes(), align) } } } @@ -644,9 +666,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { size: Size, ) -> InterpResult<'tcx, Option>> { + let size_i64 = i64::try_from(size.bytes()).unwrap(); // it would be an error to even ask for more than isize::MAX bytes let ptr_and_alloc = self.check_and_deref_ptr( ptr, - size, + size_i64, CheckInAllocMsg::MemoryAccessTest, |alloc_id, offset, prov| { let alloc = self.get_alloc_raw(alloc_id)?; @@ -657,7 +680,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // accesses. That means we cannot rely on the closure above or the `Some` branch below. We // do this after `check_and_deref_ptr` to ensure some basic sanity has already been checked. if !self.memory.validation_in_progress.get() { - if let Ok((alloc_id, ..)) = self.ptr_try_get_alloc_id(ptr) { + if let Ok((alloc_id, ..)) = self.ptr_try_get_alloc_id(ptr, size_i64) { M::before_alloc_read(self, alloc_id)?; } } @@ -878,7 +901,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ptr: Pointer>, ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> { trace!("get_ptr_fn({:?})", ptr); - let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr)?; + let (alloc_id, offset, _prov) = self.ptr_get_alloc_id(ptr, 0)?; if offset.bytes() != 0 { throw_ub!(InvalidFunctionPointer(Pointer::new(alloc_id, offset))) } @@ -894,7 +917,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { expected_trait: Option<&'tcx ty::List>>, ) -> InterpResult<'tcx, Ty<'tcx>> { trace!("get_ptr_vtable({:?})", ptr); - let (alloc_id, offset, _tag) = self.ptr_get_alloc_id(ptr)?; + let (alloc_id, offset, _tag) = self.ptr_get_alloc_id(ptr, 0)?; if offset.bytes() != 0 { throw_ub!(InvalidVTablePointer(Pointer::new(alloc_id, offset))) } @@ -983,8 +1006,11 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { }) } - /// Runs the close in "validation" mode, which means the machine's memory read hooks will be + /// Runs the closure in "validation" mode, which means the machine's memory read hooks will be /// suppressed. Needless to say, this must only be set with great care! Cannot be nested. + /// + /// We do this so Miri's allocation access tracking does not show the validation + /// reads as spurious accesses. pub(super) fn run_for_validation(&self, f: impl FnOnce() -> R) -> R { // This deliberately uses `==` on `bool` to follow the pattern // `assert!(val.replace(new) == old)`. @@ -1375,7 +1401,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { Err(_) => { // Can only happen during CTFE. let ptr = scalar.to_pointer(self)?; - match self.ptr_try_get_alloc_id(ptr) { + match self.ptr_try_get_alloc_id(ptr, 0) { Ok((alloc_id, offset, _)) => { let (size, _align, _kind) = self.get_alloc_info(alloc_id); // If the pointer is out-of-bounds, it may be null. @@ -1391,6 +1417,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// Turning a "maybe pointer" into a proper pointer (and some information /// about where it points), or an absolute address. /// + /// `size` says how many bytes of memory are expected at that pointer. This is largely only used + /// for error messages; however, the *sign* of `size` can be used to disambiguate situations + /// where a wildcard pointer sits right in between two allocations. + /// It is almost always okay to just set the size to 0; this will be treated like a positive size + /// for handling wildcard pointers. + /// /// The result must be used immediately; it is not allowed to convert /// the returned data back into a `Pointer` and store that in machine state. /// (In fact that's not even possible since `M::ProvenanceExtra` is generic and @@ -1398,9 +1430,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { pub fn ptr_try_get_alloc_id( &self, ptr: Pointer>, + size: i64, ) -> Result<(AllocId, Size, M::ProvenanceExtra), u64> { match ptr.into_pointer_or_addr() { - Ok(ptr) => match M::ptr_get_alloc(self, ptr) { + Ok(ptr) => match M::ptr_get_alloc(self, ptr, size) { Some((alloc_id, offset, extra)) => Ok((alloc_id, offset, extra)), None => { assert!(M::Provenance::OFFSET_IS_ADDR); @@ -1414,6 +1447,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// Turning a "maybe pointer" into a proper pointer (and some information about where it points). /// + /// `size` says how many bytes of memory are expected at that pointer. This is largely only used + /// for error messages; however, the *sign* of `size` can be used to disambiguate situations + /// where a wildcard pointer sits right in between two allocations. + /// It is almost always okay to just set the size to 0; this will be treated like a positive size + /// for handling wildcard pointers. + /// /// The result must be used immediately; it is not allowed to convert /// the returned data back into a `Pointer` and store that in machine state. /// (In fact that's not even possible since `M::ProvenanceExtra` is generic and @@ -1422,9 +1461,15 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { pub fn ptr_get_alloc_id( &self, ptr: Pointer>, + size: i64, ) -> InterpResult<'tcx, (AllocId, Size, M::ProvenanceExtra)> { - self.ptr_try_get_alloc_id(ptr).map_err(|offset| { - err_ub!(DanglingIntPointer(offset, CheckInAllocMsg::InboundsTest)).into() + self.ptr_try_get_alloc_id(ptr, size).map_err(|offset| { + err_ub!(DanglingIntPointer { + addr: offset, + inbounds_size: size, + msg: CheckInAllocMsg::InboundsTest + }) + .into() }) } } diff --git a/compiler/rustc_const_eval/src/interpret/mod.rs b/compiler/rustc_const_eval/src/interpret/mod.rs index f703c6fbe3ea3..afa2303e38715 100644 --- a/compiler/rustc_const_eval/src/interpret/mod.rs +++ b/compiler/rustc_const_eval/src/interpret/mod.rs @@ -18,6 +18,7 @@ mod util; mod validity; mod visitor; +use eval_context::{from_known_layout, mir_assign_valid_types}; #[doc(no_inline)] pub use rustc_middle::mir::interpret::*; // have all the `interpret` symbols in one place: here @@ -26,20 +27,15 @@ pub use self::intern::{ intern_const_alloc_for_constprop, intern_const_alloc_recursive, HasStaticRootDefId, InternKind, InternResult, }; +pub(crate) use self::intrinsics::eval_nullary_intrinsic; pub use self::machine::{compile_time_machine, AllocMap, Machine, MayLeak, ReturnAction}; pub use self::memory::{AllocKind, AllocRef, AllocRefMut, FnVal, Memory, MemoryKind}; +use self::operand::Operand; pub use self::operand::{ImmTy, Immediate, OpTy, Readable}; pub use self::place::{MPlaceTy, MemPlaceMeta, PlaceTy, Writeable}; +use self::place::{MemPlace, Place}; pub use self::projection::{OffsetMode, Projectable}; pub use self::terminator::FnArg; +pub(crate) use self::util::create_static_alloc; pub use self::validity::{CtfeValidationMode, RefTracking}; pub use self::visitor::ValueVisitor; - -use self::{ - operand::Operand, - place::{MemPlace, Place}, -}; - -pub(crate) use self::intrinsics::eval_nullary_intrinsic; -pub(crate) use self::util::create_static_alloc; -use eval_context::{from_known_layout, mir_assign_valid_types}; diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 0a7e9853763fa..d4559e1e8c64e 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -4,16 +4,14 @@ use std::assert_matches::assert_matches; use either::{Either, Left, Right}; -use tracing::trace; - use rustc_hir::def::Namespace; use rustc_middle::mir::interpret::ScalarSizeMismatch; use rustc_middle::ty::layout::{HasParamEnv, HasTyCtxt, LayoutOf, TyAndLayout}; use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter}; use rustc_middle::ty::{ConstInt, ScalarInt, Ty, TyCtxt}; -use rustc_middle::{bug, span_bug}; -use rustc_middle::{mir, ty}; +use rustc_middle::{bug, mir, span_bug, ty}; use rustc_target::abi::{self, Abi, HasDataLayout, Size}; +use tracing::trace; use super::{ alloc_range, err_ub, from_known_layout, mir_assign_valid_types, throw_ub, CtfeProvenance, @@ -835,8 +833,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // Some nodes are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(Immediate, 48); static_assert_size!(ImmTy<'_>, 64); diff --git a/compiler/rustc_const_eval/src/interpret/operator.rs b/compiler/rustc_const_eval/src/interpret/operator.rs index 2723507397eeb..2f860f9f942b2 100644 --- a/compiler/rustc_const_eval/src/interpret/operator.rs +++ b/compiler/rustc_const_eval/src/interpret/operator.rs @@ -1,15 +1,14 @@ use either::Either; - use rustc_apfloat::{Float, FloatConvert}; -use rustc_middle::mir; use rustc_middle::mir::interpret::{InterpResult, Scalar}; +use rustc_middle::mir::NullOp; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; -use rustc_middle::ty::{self, FloatTy, ScalarInt}; -use rustc_middle::{bug, span_bug}; +use rustc_middle::ty::{self, FloatTy, ScalarInt, Ty}; +use rustc_middle::{bug, mir, span_bug}; use rustc_span::symbol::sym; use tracing::trace; -use super::{err_ub, throw_ub, ImmTy, InterpCx, Machine, MemPlaceMeta}; +use super::{throw_ub, ImmTy, InterpCx, Machine, MemPlaceMeta}; impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { fn three_way_compare(&self, lhs: T, rhs: T) -> ImmTy<'tcx, M::Provenance> { @@ -300,17 +299,23 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // Pointer ops that are always supported. Offset => { let ptr = left.to_scalar().to_pointer(self)?; - let offset_count = right.to_scalar().to_target_isize(self)?; let pointee_ty = left.layout.ty.builtin_deref(true).unwrap(); + let pointee_layout = self.layout_of(pointee_ty)?; + assert!(pointee_layout.abi.is_sized()); // We cannot overflow i64 as a type's size must be <= isize::MAX. - let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap(); - // The computed offset, in bytes, must not overflow an isize. - // `checked_mul` enforces a too small bound, but no actual allocation can be big enough for - // the difference to be noticeable. - let offset_bytes = - offset_count.checked_mul(pointee_size).ok_or(err_ub!(PointerArithOverflow))?; + let pointee_size = i64::try_from(pointee_layout.size.bytes()).unwrap(); + let pointee_size = ImmTy::from_int(pointee_size, right.layout); + // Multiply element size and element count. + let (val, overflowed) = self + .binary_op(mir::BinOp::MulWithOverflow, right, &pointee_size)? + .to_scalar_pair(); + // This must not overflow. + if overflowed.to_bool()? { + throw_ub!(PointerArithOverflow) + } + let offset_bytes = val.to_target_isize(self)?; let offset_ptr = self.ptr_offset_inbounds(ptr, offset_bytes)?; Ok(ImmTy::from_scalar(Scalar::from_maybe_pointer(offset_ptr, self), left.layout)) } @@ -331,11 +336,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> { trace!( "Running binary op {:?}: {:?} ({}), {:?} ({})", - bin_op, - *left, - left.layout.ty, - *right, - right.layout.ty + bin_op, *left, left.layout.ty, *right, right.layout.ty ); match left.layout.ty.kind() { @@ -480,4 +481,38 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } } + + pub fn nullary_op( + &self, + null_op: NullOp<'tcx>, + arg_ty: Ty<'tcx>, + ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> { + use rustc_middle::mir::NullOp::*; + + let layout = self.layout_of(arg_ty)?; + let usize_layout = || self.layout_of(self.tcx.types.usize).unwrap(); + + Ok(match null_op { + SizeOf => { + if !layout.abi.is_sized() { + span_bug!(self.cur_span(), "unsized type for `NullaryOp::SizeOf`"); + } + let val = layout.size.bytes(); + ImmTy::from_uint(val, usize_layout()) + } + AlignOf => { + if !layout.abi.is_sized() { + span_bug!(self.cur_span(), "unsized type for `NullaryOp::AlignOf`"); + } + let val = layout.align.abi.bytes(); + ImmTy::from_uint(val, usize_layout()) + } + OffsetOf(fields) => { + let val = + self.tcx.offset_of_subfield(self.param_env, layout, fields.iter()).bytes(); + ImmTy::from_uint(val, usize_layout()) + } + UbChecks => ImmTy::from_bool(self.tcx.sess.ub_checks(), *self.tcx), + }) + } } diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index 33c25b746ccc6..470a62026b943 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -5,20 +5,17 @@ use std::assert_matches::assert_matches; use either::{Either, Left, Right}; -use tracing::{instrument, trace}; - use rustc_ast::Mutability; -use rustc_middle::mir; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::ty::Ty; -use rustc_middle::{bug, span_bug}; +use rustc_middle::{bug, mir, span_bug}; use rustc_target::abi::{Abi, Align, HasDataLayout, Size}; +use tracing::{instrument, trace}; use super::{ - alloc_range, mir_assign_valid_types, throw_ub, AllocRef, AllocRefMut, CheckAlignMsg, - CtfeProvenance, ImmTy, Immediate, InterpCx, InterpResult, Machine, MemoryKind, Misalignment, - OffsetMode, OpTy, Operand, Pointer, PointerArithmetic, Projectable, Provenance, Readable, - Scalar, + alloc_range, mir_assign_valid_types, AllocRef, AllocRefMut, CheckAlignMsg, CtfeProvenance, + ImmTy, Immediate, InterpCx, InterpResult, Machine, MemoryKind, Misalignment, OffsetMode, OpTy, + Operand, Pointer, Projectable, Provenance, Readable, Scalar, }; #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)] @@ -87,9 +84,6 @@ impl MemPlace { !meta.has_meta() || self.meta.has_meta(), "cannot use `offset_with_meta` to add metadata to a place" ); - if offset > ecx.data_layout().max_size_of_val() { - throw_ub!(PointerArithOverflow); - } let ptr = match mode { OffsetMode::Inbounds => { ecx.ptr_offset_inbounds(self.ptr, offset.bytes().try_into().unwrap())? @@ -291,10 +285,8 @@ impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for PlaceTy<'tcx, Prov> { // projections are type-checked and bounds-checked. assert!(offset + layout.size <= self.layout.size); - let new_offset = Size::from_bytes( - ecx.data_layout() - .offset(old_offset.unwrap_or(Size::ZERO).bytes(), offset.bytes())?, - ); + // Size `+`, ensures no overflow. + let new_offset = old_offset.unwrap_or(Size::ZERO) + offset; PlaceTy { place: Place::Local { local, offset: Some(new_offset), locals_addr }, @@ -580,7 +572,10 @@ where if M::enforce_validity(self, dest.layout()) { // Data got changed, better make sure it matches the type! - self.validate_operand(&dest.to_op(self)?)?; + self.validate_operand( + &dest.to_op(self)?, + M::enforce_validity_recursively(self, dest.layout()), + )?; } Ok(()) @@ -819,7 +814,10 @@ where // Generally for transmutation, data must be valid both at the old and new type. // But if the types are the same, the 2nd validation below suffices. if src.layout().ty != dest.layout().ty && M::enforce_validity(self, src.layout()) { - self.validate_operand(&src.to_op(self)?)?; + self.validate_operand( + &src.to_op(self)?, + M::enforce_validity_recursively(self, src.layout()), + )?; } // Do the actual copy. @@ -827,7 +825,10 @@ where if validate_dest && M::enforce_validity(self, dest.layout()) { // Data got changed, better make sure it matches the type! - self.validate_operand(&dest.to_op(self)?)?; + self.validate_operand( + &dest.to_op(self)?, + M::enforce_validity_recursively(self, dest.layout()), + )?; } Ok(()) @@ -1034,8 +1035,9 @@ where // Some nodes are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(MemPlace, 48); static_assert_size!(MemPlaceMeta, 24); diff --git a/compiler/rustc_const_eval/src/interpret/projection.rs b/compiler/rustc_const_eval/src/interpret/projection.rs index cfa814c810aff..dd8dd21e0e8b9 100644 --- a/compiler/rustc_const_eval/src/interpret/projection.rs +++ b/compiler/rustc_const_eval/src/interpret/projection.rs @@ -10,14 +10,10 @@ use std::marker::PhantomData; use std::ops::Range; -use rustc_middle::mir; -use rustc_middle::ty; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::ty::Ty; -use rustc_middle::{bug, span_bug}; -use rustc_target::abi::Size; -use rustc_target::abi::{self, VariantIdx}; - +use rustc_middle::{bug, mir, span_bug, ty}; +use rustc_target::abi::{self, Size, VariantIdx}; use tracing::{debug, instrument}; use super::{ diff --git a/compiler/rustc_const_eval/src/interpret/step.rs b/compiler/rustc_const_eval/src/interpret/step.rs index b3124dfdfbc01..28cf1068f4081 100644 --- a/compiler/rustc_const_eval/src/interpret/step.rs +++ b/compiler/rustc_const_eval/src/interpret/step.rs @@ -3,13 +3,10 @@ //! The main entry point is the `step` method. use either::Either; -use tracing::{info, instrument, trace}; - use rustc_index::IndexSlice; -use rustc_middle::mir; -use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::{bug, span_bug}; +use rustc_middle::{bug, mir}; use rustc_target::abi::{FieldIdx, FIRST_VARIANT}; +use tracing::{info, instrument, trace}; use super::{ ImmTy, Immediate, InterpCx, InterpResult, Machine, MemPlaceMeta, PlaceTy, Projectable, Scalar, @@ -96,7 +93,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { M::retag_place_contents(self, *kind, &dest)?; } - Intrinsic(box intrinsic) => self.emulate_nondiverging_intrinsic(intrinsic)?, + Intrinsic(box intrinsic) => self.eval_nondiverging_intrinsic(intrinsic)?, // Evaluate the place expression, without reading from it. PlaceMention(box place) => { @@ -181,6 +178,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { self.write_immediate(*result, &dest)?; } + NullaryOp(null_op, ty) => { + let ty = self.instantiate_from_current_frame_and_normalize_erasing_regions(ty)?; + let val = self.nullary_op(null_op, ty)?; + self.write_immediate(*val, &dest)?; + } + Aggregate(box ref kind, ref operands) => { self.write_aggregate(kind, operands, &dest)?; } @@ -232,38 +235,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { self.write_immediate(*val, &dest)?; } - NullaryOp(ref null_op, ty) => { - let ty = self.instantiate_from_current_frame_and_normalize_erasing_regions(ty)?; - let layout = self.layout_of(ty)?; - if let mir::NullOp::SizeOf | mir::NullOp::AlignOf = null_op - && layout.is_unsized() - { - span_bug!( - self.frame().current_span(), - "{null_op:?} MIR operator called for unsized type {ty}", - ); - } - let val = match null_op { - mir::NullOp::SizeOf => { - let val = layout.size.bytes(); - Scalar::from_target_usize(val, self) - } - mir::NullOp::AlignOf => { - let val = layout.align.abi.bytes(); - Scalar::from_target_usize(val, self) - } - mir::NullOp::OffsetOf(fields) => { - let val = self - .tcx - .offset_of_subfield(self.param_env, layout, fields.iter()) - .bytes(); - Scalar::from_target_usize(val, self) - } - mir::NullOp::UbChecks => Scalar::from_bool(self.tcx.sess.ub_checks()), - }; - self.write_scalar(val, &dest)?; - } - ShallowInitBox(ref operand, _) => { let src = self.eval_operand(operand, None)?; let v = self.read_immediate(&src)?; @@ -364,7 +335,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // of the first element. let elem_size = first.layout.size; let first_ptr = first.ptr(); - let rest_ptr = first_ptr.offset(elem_size, self)?; + let rest_ptr = first_ptr.wrapping_offset(elem_size, self); // No alignment requirement since `copy_op` above already checked it. self.mem_copy_repeatedly( first_ptr, diff --git a/compiler/rustc_const_eval/src/interpret/terminator.rs b/compiler/rustc_const_eval/src/interpret/terminator.rs index 56d3dc9410412..47d0e22b527d3 100644 --- a/compiler/rustc_const_eval/src/interpret/terminator.rs +++ b/compiler/rustc_const_eval/src/interpret/terminator.rs @@ -1,33 +1,24 @@ use std::borrow::Cow; use either::Either; -use tracing::trace; - -use rustc_middle::{ - bug, mir, span_bug, - ty::{ - self, - layout::{FnAbiOf, IntegerExt, LayoutOf, TyAndLayout}, - AdtDef, Instance, Ty, - }, -}; -use rustc_span::{source_map::Spanned, sym}; -use rustc_target::abi::{self, FieldIdx}; -use rustc_target::abi::{ - call::{ArgAbi, FnAbi, PassMode}, - Integer, -}; +use rustc_middle::ty::layout::{FnAbiOf, IntegerExt, LayoutOf, TyAndLayout}; +use rustc_middle::ty::{self, AdtDef, Instance, Ty}; +use rustc_middle::{bug, mir, span_bug}; +use rustc_span::source_map::Spanned; +use rustc_span::sym; +use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode}; +use rustc_target::abi::{self, FieldIdx, Integer}; use rustc_target::spec::abi::Abi; +use tracing::trace; use super::{ throw_ub, throw_ub_custom, throw_unsup_format, CtfeProvenance, FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, Projectable, Provenance, Scalar, StackPopCleanup, }; -use crate::{ - fluent_generated as fluent, - interpret::{eval_context::StackPopInfo, ReturnAction}, -}; +use crate::fluent_generated as fluent; +use crate::interpret::eval_context::StackPopInfo; +use crate::interpret::ReturnAction; /// An argment passed to a function. #[derive(Clone, Debug)] @@ -440,8 +431,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } else { trace!( "check_argument_compat: incompatible ABIs:\ncaller: {:?}\ncallee: {:?}", - caller_abi, - callee_abi + caller_abi, callee_abi ); return Ok(false); } diff --git a/compiler/rustc_const_eval/src/interpret/util.rs b/compiler/rustc_const_eval/src/interpret/util.rs index bbe5e5fe3edbb..6f5bcebbbb66f 100644 --- a/compiler/rustc_const_eval/src/interpret/util.rs +++ b/compiler/rustc_const_eval/src/interpret/util.rs @@ -1,4 +1,5 @@ -use crate::const_eval::{CompileTimeInterpCx, CompileTimeMachine, InterpretationResult}; +use std::ops::ControlFlow; + use rustc_hir::def_id::LocalDefId; use rustc_middle::mir; use rustc_middle::mir::interpret::{Allocation, InterpResult, Pointer}; @@ -6,10 +7,10 @@ use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{ self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, }; -use std::ops::ControlFlow; use tracing::debug; use super::{throw_inval, InterpCx, MPlaceTy, MemPlaceMeta, MemoryKind}; +use crate::const_eval::{CompileTimeInterpCx, CompileTimeMachine, InterpretationResult}; /// Checks whether a type contains generic parameters which must be instantiated. /// diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 4da7e233889f0..460f5448634b5 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -9,17 +9,15 @@ use std::hash::Hash; use std::num::NonZero; use either::{Left, Right}; -use tracing::trace; - use hir::def::DefKind; use rustc_ast::Mutability; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_middle::bug; +use rustc_middle::mir::interpret::ValidationErrorKind::{self, *}; use rustc_middle::mir::interpret::{ ExpectedKind, InterpError, InvalidMetaKind, Misalignment, PointerKind, Provenance, UnsupportedOpInfo, ValidationErrorInfo, - ValidationErrorKind::{self, *}, }; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::ty::{self, Ty}; @@ -27,13 +25,17 @@ use rustc_span::symbol::{sym, Symbol}; use rustc_target::abi::{ Abi, FieldIdx, Scalar as ScalarAbi, Size, VariantIdx, Variants, WrappingRange, }; +use tracing::trace; +use super::machine::AllocMap; use super::{ - err_ub, format_interp_error, machine::AllocMap, throw_ub, AllocId, AllocKind, CheckInAllocMsg, - GlobalAlloc, ImmTy, Immediate, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy, - Pointer, Projectable, Scalar, ValueVisitor, + err_ub, format_interp_error, throw_ub, AllocId, AllocKind, CheckInAllocMsg, GlobalAlloc, ImmTy, + Immediate, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy, Pointer, Projectable, + Scalar, ValueVisitor, }; +// for the validation errors +#[rustfmt::skip] use super::InterpError::UndefinedBehavior as Ub; use super::InterpError::Unsupported as Unsup; use super::UndefinedBehaviorInfo::*; @@ -153,8 +155,8 @@ impl CtfeValidationMode { /// State for tracking recursive validation of references pub struct RefTracking { - pub seen: FxHashSet, - pub todo: Vec<(T, PATH)>, + seen: FxHashSet, + todo: Vec<(T, PATH)>, } impl RefTracking { @@ -167,8 +169,11 @@ impl RefTracking ref_tracking_for_consts.seen.insert(op); ref_tracking_for_consts } + pub fn next(&mut self) -> Option<(T, PATH)> { + self.todo.pop() + } - pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) { + fn track(&mut self, op: T, path: impl FnOnce() -> PATH) { if self.seen.insert(op.clone()) { trace!("Recursing below ptr {:#?}", op); let path = path(); @@ -346,7 +351,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { try_validation!( self.ecx.get_ptr_vtable_ty(vtable, Some(data)), self.path, - Ub(DanglingIntPointer(..) | InvalidVTablePointer(..)) => + Ub(DanglingIntPointer{ .. } | InvalidVTablePointer(..)) => InvalidVTablePtr { value: format!("{vtable}") }, Ub(InvalidVTableTrait { expected_trait, vtable_trait }) => { InvalidMetaWrongTrait { expected_trait, vtable_trait: *vtable_trait } @@ -403,8 +408,8 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { CheckInAllocMsg::InboundsTest, // will anyway be replaced by validity message ), self.path, - Ub(DanglingIntPointer(0, _)) => NullPtr { ptr_kind }, - Ub(DanglingIntPointer(i, _)) => DanglingPtrNoProvenance { + Ub(DanglingIntPointer { addr: 0, .. }) => NullPtr { ptr_kind }, + Ub(DanglingIntPointer { addr: i, .. }) => DanglingPtrNoProvenance { ptr_kind, // FIXME this says "null pointer" when null but we need translate pointer: format!("{}", Pointer::>::from_addr_invalid(*i)) @@ -433,88 +438,96 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { if self.ecx.scalar_may_be_null(Scalar::from_maybe_pointer(place.ptr(), self.ecx))? { throw_validation_failure!(self.path, NullPtr { ptr_kind }) } - // Do not allow pointers to uninhabited types. + // Do not allow references to uninhabited types. if place.layout.abi.is_uninhabited() { let ty = place.layout.ty; throw_validation_failure!(self.path, PtrToUninhabited { ptr_kind, ty }) } // Recursive checking if let Some(ref_tracking) = self.ref_tracking.as_deref_mut() { - // Determine whether this pointer expects to be pointing to something mutable. - let ptr_expected_mutbl = match ptr_kind { - PointerKind::Box => Mutability::Mut, - PointerKind::Ref(mutbl) => { - // We do not take into account interior mutability here since we cannot know if - // there really is an `UnsafeCell` inside `Option` -- so we check - // that in the recursive descent behind this reference (controlled by - // `allow_immutable_unsafe_cell`). - mutbl - } - }; // Proceed recursively even for ZST, no reason to skip them! // `!` is a ZST and we want to validate it. - if let Ok((alloc_id, _offset, _prov)) = self.ecx.ptr_try_get_alloc_id(place.ptr()) { + if let Some(ctfe_mode) = self.ctfe_mode { let mut skip_recursive_check = false; - if let Some(GlobalAlloc::Static(did)) = self.ecx.tcx.try_get_global_alloc(alloc_id) + // CTFE imposes restrictions on what references can point to. + if let Ok((alloc_id, _offset, _prov)) = + self.ecx.ptr_try_get_alloc_id(place.ptr(), 0) { - let DefKind::Static { nested, .. } = self.ecx.tcx.def_kind(did) else { bug!() }; - // Special handling for pointers to statics (irrespective of their type). - assert!(!self.ecx.tcx.is_thread_local_static(did)); - assert!(self.ecx.tcx.is_static(did)); - // Mode-specific checks - match self.ctfe_mode { - Some( - CtfeValidationMode::Static { .. } | CtfeValidationMode::Promoted { .. }, - ) => { - // We skip recursively checking other statics. These statics must be sound by - // themselves, and the only way to get broken statics here is by using - // unsafe code. - // The reasons we don't check other statics is twofold. For one, in all - // sound cases, the static was already validated on its own, and second, we - // trigger cycle errors if we try to compute the value of the other static - // and that static refers back to us (potentially through a promoted). - // This could miss some UB, but that's fine. - // We still walk nested allocations, as they are fundamentally part of this validation run. - // This means we will also recurse into nested statics of *other* - // statics, even though we do not recurse into other statics directly. - // That's somewhat inconsistent but harmless. - skip_recursive_check = !nested; - } - Some(CtfeValidationMode::Const { .. }) => { - // We can't recursively validate `extern static`, so we better reject them. - if self.ecx.tcx.is_foreign_item(did) { - throw_validation_failure!(self.path, ConstRefToExtern); + if let Some(GlobalAlloc::Static(did)) = + self.ecx.tcx.try_get_global_alloc(alloc_id) + { + let DefKind::Static { nested, .. } = self.ecx.tcx.def_kind(did) else { + bug!() + }; + // Special handling for pointers to statics (irrespective of their type). + assert!(!self.ecx.tcx.is_thread_local_static(did)); + assert!(self.ecx.tcx.is_static(did)); + // Mode-specific checks + match ctfe_mode { + CtfeValidationMode::Static { .. } + | CtfeValidationMode::Promoted { .. } => { + // We skip recursively checking other statics. These statics must be sound by + // themselves, and the only way to get broken statics here is by using + // unsafe code. + // The reasons we don't check other statics is twofold. For one, in all + // sound cases, the static was already validated on its own, and second, we + // trigger cycle errors if we try to compute the value of the other static + // and that static refers back to us (potentially through a promoted). + // This could miss some UB, but that's fine. + // We still walk nested allocations, as they are fundamentally part of this validation run. + // This means we will also recurse into nested statics of *other* + // statics, even though we do not recurse into other statics directly. + // That's somewhat inconsistent but harmless. + skip_recursive_check = !nested; + } + CtfeValidationMode::Const { .. } => { + // We can't recursively validate `extern static`, so we better reject them. + if self.ecx.tcx.is_foreign_item(did) { + throw_validation_failure!(self.path, ConstRefToExtern); + } } } - None => {} } - } - // Dangling and Mutability check. - let (size, _align, alloc_kind) = self.ecx.get_alloc_info(alloc_id); - if alloc_kind == AllocKind::Dead { - // This can happen for zero-sized references. We can't have *any* references to non-existing - // allocations though, interning rejects them all as the rest of rustc isn't happy with them... - // so we throw an error, even though this isn't really UB. - // A potential future alternative would be to resurrect this as a zero-sized allocation - // (which codegen will then compile to an aligned dummy pointer anyway). - throw_validation_failure!(self.path, DanglingPtrUseAfterFree { ptr_kind }); - } - // If this allocation has size zero, there is no actual mutability here. - if size != Size::ZERO { - let alloc_actual_mutbl = mutability(self.ecx, alloc_id); - // Mutable pointer to immutable memory is no good. - if ptr_expected_mutbl == Mutability::Mut - && alloc_actual_mutbl == Mutability::Not - { - throw_validation_failure!(self.path, MutableRefToImmutable); + // Dangling and Mutability check. + let (size, _align, alloc_kind) = self.ecx.get_alloc_info(alloc_id); + if alloc_kind == AllocKind::Dead { + // This can happen for zero-sized references. We can't have *any* references to + // non-existing allocations in const-eval though, interning rejects them all as + // the rest of rustc isn't happy with them... so we throw an error, even though + // this isn't really UB. + // A potential future alternative would be to resurrect this as a zero-sized allocation + // (which codegen will then compile to an aligned dummy pointer anyway). + throw_validation_failure!(self.path, DanglingPtrUseAfterFree { ptr_kind }); } - // In a const, everything must be completely immutable. - if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. })) { + // If this allocation has size zero, there is no actual mutability here. + if size != Size::ZERO { + // Determine whether this pointer expects to be pointing to something mutable. + let ptr_expected_mutbl = match ptr_kind { + PointerKind::Box => Mutability::Mut, + PointerKind::Ref(mutbl) => { + // We do not take into account interior mutability here since we cannot know if + // there really is an `UnsafeCell` inside `Option` -- so we check + // that in the recursive descent behind this reference (controlled by + // `allow_immutable_unsafe_cell`). + mutbl + } + }; + // Determine what it actually points to. + let alloc_actual_mutbl = mutability(self.ecx, alloc_id); + // Mutable pointer to immutable memory is no good. if ptr_expected_mutbl == Mutability::Mut - || alloc_actual_mutbl == Mutability::Mut + && alloc_actual_mutbl == Mutability::Not { - throw_validation_failure!(self.path, ConstRefToMutable); + throw_validation_failure!(self.path, MutableRefToImmutable); + } + // In a const, everything must be completely immutable. + if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. })) { + if ptr_expected_mutbl == Mutability::Mut + || alloc_actual_mutbl == Mutability::Mut + { + throw_validation_failure!(self.path, ConstRefToMutable); + } } } } @@ -522,6 +535,15 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { if skip_recursive_check { return Ok(()); } + } else { + // This is not CTFE, so it's Miri with recursive checking. + // FIXME: we do *not* check behind boxes, since creating a new box first creates it uninitialized + // and then puts the value in there, so briefly we have a box with uninit contents. + // FIXME: should we also skip `UnsafeCell` behind shared references? Currently that is not + // needed since validation reads bypass Stacked Borrows and data race checks. + if matches!(ptr_kind, PointerKind::Box) { + return Ok(()); + } } let path = &self.path; ref_tracking.track(place, || { @@ -603,7 +625,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { let _fn = try_validation!( self.ecx.get_ptr_fn(ptr), self.path, - Ub(DanglingIntPointer(..) | InvalidFunctionPointer(..)) => + Ub(DanglingIntPointer{ .. } | InvalidFunctionPointer(..)) => InvalidFnPtr { value: format!("{ptr}") }, ); // FIXME: Check if the signature matches @@ -1070,11 +1092,23 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// `op` is assumed to cover valid memory if it is an indirect operand. /// It will error if the bits at the destination do not match the ones described by the layout. #[inline(always)] - pub fn validate_operand(&self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx> { + pub fn validate_operand( + &self, + op: &OpTy<'tcx, M::Provenance>, + recursive: bool, + ) -> InterpResult<'tcx> { // Note that we *could* actually be in CTFE here with `-Zextra-const-ub-checks`, but it's // still correct to not use `ctfe_mode`: that mode is for validation of the final constant - // value, it rules out things like `UnsafeCell` in awkward places. It also can make checking - // recurse through references which, for now, we don't want here, either. - self.validate_operand_internal(op, vec![], None, None) + // value, it rules out things like `UnsafeCell` in awkward places. + if !recursive { + return self.validate_operand_internal(op, vec![], None, None); + } + // Do a recursive check. + let mut ref_tracking = RefTracking::empty(); + self.validate_operand_internal(op, vec![], Some(&mut ref_tracking), None)?; + while let Some((mplace, path)) = ref_tracking.todo.pop() { + self.validate_operand_internal(&mplace.into(), path, Some(&mut ref_tracking), None)?; + } + Ok(()) } } diff --git a/compiler/rustc_const_eval/src/interpret/visitor.rs b/compiler/rustc_const_eval/src/interpret/visitor.rs index 71c057e549b41..fd649d608c691 100644 --- a/compiler/rustc_const_eval/src/interpret/visitor.rs +++ b/compiler/rustc_const_eval/src/interpret/visitor.rs @@ -1,15 +1,14 @@ //! Visitor for a run-time value with a given layout: Traverse enums, structs and other compound //! types until we arrive at the leaves, with custom handling for primitive types. +use std::num::NonZero; + use rustc_index::IndexVec; use rustc_middle::mir::interpret::InterpResult; use rustc_middle::ty::{self, Ty}; -use rustc_target::abi::FieldIdx; -use rustc_target::abi::{FieldsShape, VariantIdx, Variants}; +use rustc_target::abi::{FieldIdx, FieldsShape, VariantIdx, Variants}; use tracing::trace; -use std::num::NonZero; - use super::{throw_inval, InterpCx, MPlaceTy, Machine, Projectable}; /// How to traverse a value and what to do when we are at the leaves. diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs index 50a4d0612ccd3..780404212c341 100644 --- a/compiler/rustc_const_eval/src/lib.rs +++ b/compiler/rustc_const_eval/src/lib.rs @@ -26,8 +26,8 @@ pub mod util; use std::sync::atomic::AtomicBool; pub use errors::ReportErrorExt; - -use rustc_middle::{ty, util::Providers}; +use rustc_middle::ty; +use rustc_middle::util::Providers; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_const_eval/src/util/caller_location.rs b/compiler/rustc_const_eval/src/util/caller_location.rs index 3b07bee2d9c27..eb185bee5c07b 100644 --- a/compiler/rustc_const_eval/src/util/caller_location.rs +++ b/compiler/rustc_const_eval/src/util/caller_location.rs @@ -1,9 +1,8 @@ use rustc_hir::LangItem; -use rustc_middle::bug; -use rustc_middle::mir; use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, Mutability}; +use rustc_middle::{bug, mir}; use rustc_span::symbol::Symbol; use tracing::trace; diff --git a/compiler/rustc_const_eval/src/util/check_validity_requirement.rs b/compiler/rustc_const_eval/src/util/check_validity_requirement.rs index daf57285ebe6d..4b6b1e453b82e 100644 --- a/compiler/rustc_const_eval/src/util/check_validity_requirement.rs +++ b/compiler/rustc_const_eval/src/util/check_validity_requirement.rs @@ -67,7 +67,7 @@ fn might_permit_raw_init_strict<'tcx>( // This does *not* actually check that references are dereferenceable, but since all types that // require dereferenceability also require non-null, we don't actually get any false negatives // due to this. - Ok(cx.validate_operand(&ot).is_ok()) + Ok(cx.validate_operand(&ot, /*recursive*/ false).is_ok()) } /// Implements the 'lax' (default) version of the `might_permit_raw_init` checks; see that function for diff --git a/compiler/rustc_const_eval/src/util/type_name.rs b/compiler/rustc_const_eval/src/util/type_name.rs index 01e517250f77e..3aa3b3b74e053 100644 --- a/compiler/rustc_const_eval/src/util/type_name.rs +++ b/compiler/rustc_const_eval/src/util/type_name.rs @@ -1,13 +1,11 @@ +use std::fmt::Write; + use rustc_data_structures::intern::Interned; use rustc_hir::def_id::CrateNum; use rustc_hir::definitions::DisambiguatedDefPathData; use rustc_middle::bug; -use rustc_middle::ty::{ - self, - print::{PrettyPrinter, Print, PrintError, Printer}, - GenericArg, GenericArgKind, Ty, TyCtxt, -}; -use std::fmt::Write; +use rustc_middle::ty::print::{PrettyPrinter, Print, PrintError, Printer}; +use rustc_middle::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt}; struct AbsolutePathPrinter<'tcx> { tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_data_structures/src/base_n.rs b/compiler/rustc_data_structures/src/base_n.rs index 80810df14d018..1c2321623e491 100644 --- a/compiler/rustc_data_structures/src/base_n.rs +++ b/compiler/rustc_data_structures/src/base_n.rs @@ -1,8 +1,7 @@ //! Converts unsigned integers into a string representation with some base. //! Bases up to and including 36 can be used for case-insensitive things. -use std::ascii; -use std::fmt; +use std::{ascii, fmt}; #[cfg(test)] mod tests; diff --git a/compiler/rustc_data_structures/src/fingerprint.rs b/compiler/rustc_data_structures/src/fingerprint.rs index 30e3d6aa86ce9..efc56dc93373b 100644 --- a/compiler/rustc_data_structures/src/fingerprint.rs +++ b/compiler/rustc_data_structures/src/fingerprint.rs @@ -1,8 +1,11 @@ -use crate::stable_hasher::impl_stable_traits_for_trivial_type; -use crate::stable_hasher::{FromStableHash, Hash64, StableHasherHash}; -use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use std::hash::{Hash, Hasher}; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; + +use crate::stable_hasher::{ + impl_stable_traits_for_trivial_type, FromStableHash, Hash64, StableHasherHash, +}; + #[cfg(test)] mod tests; diff --git a/compiler/rustc_data_structures/src/flat_map_in_place.rs b/compiler/rustc_data_structures/src/flat_map_in_place.rs index f58844f281794..e66b00b755760 100644 --- a/compiler/rustc_data_structures/src/flat_map_in_place.rs +++ b/compiler/rustc_data_structures/src/flat_map_in_place.rs @@ -1,5 +1,6 @@ -use smallvec::{Array, SmallVec}; use std::ptr; + +use smallvec::{Array, SmallVec}; use thin_vec::ThinVec; pub trait FlatMapInPlace: Sized { diff --git a/compiler/rustc_data_structures/src/flock/unix.rs b/compiler/rustc_data_structures/src/flock/unix.rs index eff9e8f838fe7..12b8b41210d1c 100644 --- a/compiler/rustc_data_structures/src/flock/unix.rs +++ b/compiler/rustc_data_structures/src/flock/unix.rs @@ -1,8 +1,7 @@ use std::fs::{File, OpenOptions}; -use std::io; -use std::mem; use std::os::unix::prelude::*; use std::path::Path; +use std::{io, mem}; #[derive(Debug)] pub struct Lock { diff --git a/compiler/rustc_data_structures/src/flock/windows.rs b/compiler/rustc_data_structures/src/flock/windows.rs index 7dc72661939be..0d76df27a0a39 100644 --- a/compiler/rustc_data_structures/src/flock/windows.rs +++ b/compiler/rustc_data_structures/src/flock/windows.rs @@ -2,16 +2,14 @@ use std::fs::{File, OpenOptions}; use std::io; use std::os::windows::prelude::*; use std::path::Path; -use tracing::debug; -use windows::{ - Win32::Foundation::{ERROR_INVALID_FUNCTION, HANDLE}, - Win32::Storage::FileSystem::{ - LockFileEx, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, LOCKFILE_EXCLUSIVE_LOCK, - LOCKFILE_FAIL_IMMEDIATELY, LOCK_FILE_FLAGS, - }, - Win32::System::IO::OVERLAPPED, +use tracing::debug; +use windows::Win32::Foundation::{ERROR_INVALID_FUNCTION, HANDLE}; +use windows::Win32::Storage::FileSystem::{ + LockFileEx, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, LOCKFILE_EXCLUSIVE_LOCK, + LOCKFILE_FAIL_IMMEDIATELY, LOCK_FILE_FLAGS, }; +use windows::Win32::System::IO::OVERLAPPED; #[derive(Debug)] pub struct Lock { diff --git a/compiler/rustc_data_structures/src/graph/dominators/mod.rs b/compiler/rustc_data_structures/src/graph/dominators/mod.rs index d1d2de670b82d..7cb013fdbd837 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/mod.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/mod.rs @@ -9,10 +9,11 @@ //! Thomas Lengauer and Robert Endre Tarjan. //! -use super::ControlFlowGraph; +use std::cmp::Ordering; + use rustc_index::{Idx, IndexSlice, IndexVec}; -use std::cmp::Ordering; +use super::ControlFlowGraph; #[cfg(test)] mod tests; diff --git a/compiler/rustc_data_structures/src/graph/dominators/tests.rs b/compiler/rustc_data_structures/src/graph/dominators/tests.rs index 39725ba4301be..6c078ca7c6ee4 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/tests.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/tests.rs @@ -1,6 +1,5 @@ -use super::*; - use super::super::tests::TestGraph; +use super::*; #[test] fn diamond() { diff --git a/compiler/rustc_data_structures/src/graph/implementation/mod.rs b/compiler/rustc_data_structures/src/graph/implementation/mod.rs index 8cf4b4153db2f..43fdfe6ee0d73 100644 --- a/compiler/rustc_data_structures/src/graph/implementation/mod.rs +++ b/compiler/rustc_data_structures/src/graph/implementation/mod.rs @@ -20,8 +20,9 @@ //! the field `next_edge`). Each of those fields is an array that should //! be indexed by the direction (see the type `Direction`). -use rustc_index::bit_set::BitSet; use std::fmt::Debug; + +use rustc_index::bit_set::BitSet; use tracing::debug; #[cfg(test)] diff --git a/compiler/rustc_data_structures/src/graph/implementation/tests.rs b/compiler/rustc_data_structures/src/graph/implementation/tests.rs index b4dbd65db940b..32a6d9ec881a9 100644 --- a/compiler/rustc_data_structures/src/graph/implementation/tests.rs +++ b/compiler/rustc_data_structures/src/graph/implementation/tests.rs @@ -1,6 +1,7 @@ -use crate::graph::implementation::*; use tracing::debug; +use crate::graph::implementation::*; + type TestGraph = Graph<&'static str, &'static str>; fn create_graph() -> TestGraph { diff --git a/compiler/rustc_data_structures/src/graph/iterate/mod.rs b/compiler/rustc_data_structures/src/graph/iterate/mod.rs index 6fca57d32f771..cbc6664d853a1 100644 --- a/compiler/rustc_data_structures/src/graph/iterate/mod.rs +++ b/compiler/rustc_data_structures/src/graph/iterate/mod.rs @@ -1,7 +1,9 @@ -use super::{DirectedGraph, StartNode, Successors}; +use std::ops::ControlFlow; + use rustc_index::bit_set::BitSet; use rustc_index::{IndexSlice, IndexVec}; -use std::ops::ControlFlow; + +use super::{DirectedGraph, StartNode, Successors}; #[cfg(test)] mod tests; diff --git a/compiler/rustc_data_structures/src/graph/iterate/tests.rs b/compiler/rustc_data_structures/src/graph/iterate/tests.rs index c498c289337f1..eb7d0bd14b6b0 100644 --- a/compiler/rustc_data_structures/src/graph/iterate/tests.rs +++ b/compiler/rustc_data_structures/src/graph/iterate/tests.rs @@ -1,5 +1,4 @@ use super::super::tests::TestGraph; - use super::*; #[test] diff --git a/compiler/rustc_data_structures/src/graph/scc/mod.rs b/compiler/rustc_data_structures/src/graph/scc/mod.rs index 8b96b36a8512a..96fc8ae3887f5 100644 --- a/compiler/rustc_data_structures/src/graph/scc/mod.rs +++ b/compiler/rustc_data_structures/src/graph/scc/mod.rs @@ -8,14 +8,16 @@ //! Typical examples would include: minimum element in SCC, maximum element //! reachable from it, etc. -use crate::fx::FxHashSet; -use crate::graph::vec_graph::VecGraph; -use crate::graph::{DirectedGraph, NumEdges, Successors}; -use rustc_index::{Idx, IndexSlice, IndexVec}; use std::fmt::Debug; use std::ops::Range; + +use rustc_index::{Idx, IndexSlice, IndexVec}; use tracing::{debug, instrument}; +use crate::fx::FxHashSet; +use crate::graph::vec_graph::VecGraph; +use crate::graph::{DirectedGraph, NumEdges, Successors}; + #[cfg(test)] mod tests; diff --git a/compiler/rustc_data_structures/src/graph/tests.rs b/compiler/rustc_data_structures/src/graph/tests.rs index 85c2703cc2538..b69b9dbc4a8e6 100644 --- a/compiler/rustc_data_structures/src/graph/tests.rs +++ b/compiler/rustc_data_structures/src/graph/tests.rs @@ -1,7 +1,7 @@ -use crate::fx::FxHashMap; use std::cmp::max; use super::*; +use crate::fx::FxHashMap; pub struct TestGraph { num_nodes: usize, diff --git a/compiler/rustc_data_structures/src/graph/vec_graph/mod.rs b/compiler/rustc_data_structures/src/graph/vec_graph/mod.rs index 120244c8918a0..96784c2540aa3 100644 --- a/compiler/rustc_data_structures/src/graph/vec_graph/mod.rs +++ b/compiler/rustc_data_structures/src/graph/vec_graph/mod.rs @@ -1,6 +1,7 @@ -use crate::graph::{DirectedGraph, NumEdges, Predecessors, Successors}; use rustc_index::{Idx, IndexVec}; +use crate::graph::{DirectedGraph, NumEdges, Predecessors, Successors}; + #[cfg(test)] mod tests; diff --git a/compiler/rustc_data_structures/src/graph/vec_graph/tests.rs b/compiler/rustc_data_structures/src/graph/vec_graph/tests.rs index a077d9d081364..78caf75f5b4e4 100644 --- a/compiler/rustc_data_structures/src/graph/vec_graph/tests.rs +++ b/compiler/rustc_data_structures/src/graph/vec_graph/tests.rs @@ -1,6 +1,5 @@ -use crate::graph; - use super::*; +use crate::graph; fn create_graph() -> VecGraph { // Create a simple graph diff --git a/compiler/rustc_data_structures/src/hashes.rs b/compiler/rustc_data_structures/src/hashes.rs index ef5d2e845ef07..f98c8de1eb097 100644 --- a/compiler/rustc_data_structures/src/hashes.rs +++ b/compiler/rustc_data_structures/src/hashes.rs @@ -11,11 +11,13 @@ //! connect the fact that they can only be produced by a `StableHasher` to their //! `Encode`/`Decode` impls. -use crate::stable_hasher::{FromStableHash, StableHasherHash}; -use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use std::fmt; use std::ops::BitXorAssign; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; + +use crate::stable_hasher::{FromStableHash, StableHasherHash}; + #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] pub struct Hash64 { inner: u64, diff --git a/compiler/rustc_data_structures/src/intern.rs b/compiler/rustc_data_structures/src/intern.rs index e0f8c350c2a86..850b052f564b7 100644 --- a/compiler/rustc_data_structures/src/intern.rs +++ b/compiler/rustc_data_structures/src/intern.rs @@ -1,10 +1,11 @@ -use crate::stable_hasher::{HashStable, StableHasher}; use std::cmp::Ordering; use std::fmt::{self, Debug}; use std::hash::{Hash, Hasher}; use std::ops::Deref; use std::ptr; +use crate::stable_hasher::{HashStable, StableHasher}; + mod private { #[derive(Clone, Copy, Debug)] pub struct PrivateZst; diff --git a/compiler/rustc_data_structures/src/jobserver.rs b/compiler/rustc_data_structures/src/jobserver.rs index 89088bc5c1b87..d09f7efc8ffff 100644 --- a/compiler/rustc_data_structures/src/jobserver.rs +++ b/compiler/rustc_data_structures/src/jobserver.rs @@ -1,9 +1,8 @@ -pub use jobserver_crate::Client; +use std::sync::{LazyLock, OnceLock}; +pub use jobserver_crate::Client; use jobserver_crate::{FromEnv, FromEnvErrorKind}; -use std::sync::{LazyLock, OnceLock}; - // We can only call `from_env_ext` once per process // We stick this in a global because there could be multiple rustc instances diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index 3f18b036940bf..403136e78f4eb 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -10,7 +10,6 @@ #![allow(internal_features)] #![allow(rustc::default_hash_types)] #![allow(rustc::potential_query_instability)] -#![cfg_attr(bootstrap, feature(lint_reasons))] #![cfg_attr(not(parallel_compiler), feature(cell_leak))] #![deny(unsafe_op_in_unsafe_fn)] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] @@ -39,14 +38,12 @@ #![feature(unwrap_infallible)] // tidy-alphabetical-end +use std::fmt; + pub use atomic_ref::AtomicRef; -pub use ena::snapshot_vec; -pub use ena::undo_log; -pub use ena::unify; +pub use ena::{snapshot_vec, undo_log, unify}; pub use rustc_index::static_assert_size; -use std::fmt; - pub mod aligned; pub mod base_n; pub mod binary_search_util; diff --git a/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs b/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs index 4b6aa116520df..60cde9a52b411 100644 --- a/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs +++ b/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs @@ -1,11 +1,12 @@ -use crate::obligation_forest::{ForestObligation, ObligationForest}; -use rustc_graphviz as dot; use std::env::var_os; use std::fs::File; use std::io::BufWriter; use std::path::Path; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use rustc_graphviz as dot; + +use crate::obligation_forest::{ForestObligation, ObligationForest}; impl ObligationForest { /// Creates a graphviz representation of the obligation forest. Given a directory this will diff --git a/compiler/rustc_data_structures/src/obligation_forest/mod.rs b/compiler/rustc_data_structures/src/obligation_forest/mod.rs index 3883b0736db07..cfe7dd13e80b2 100644 --- a/compiler/rustc_data_structures/src/obligation_forest/mod.rs +++ b/compiler/rustc_data_structures/src/obligation_forest/mod.rs @@ -69,14 +69,16 @@ //! step, we compress the vector to remove completed and error nodes, which //! aren't needed anymore. -use crate::fx::{FxHashMap, FxHashSet}; use std::cell::Cell; use std::collections::hash_map::Entry; use std::fmt::Debug; use std::hash; use std::marker::PhantomData; + use tracing::debug; +use crate::fx::{FxHashMap, FxHashSet}; + mod graphviz; #[cfg(test)] diff --git a/compiler/rustc_data_structures/src/obligation_forest/tests.rs b/compiler/rustc_data_structures/src/obligation_forest/tests.rs index d09c8e54436e6..a58c6ee1bccb6 100644 --- a/compiler/rustc_data_structures/src/obligation_forest/tests.rs +++ b/compiler/rustc_data_structures/src/obligation_forest/tests.rs @@ -1,7 +1,7 @@ -use super::*; - use std::fmt; +use super::*; + impl<'a> super::ForestObligation for &'a str { type CacheKey = &'a str; diff --git a/compiler/rustc_data_structures/src/owned_slice.rs b/compiler/rustc_data_structures/src/owned_slice.rs index bb6647958606c..bbe6691e548d0 100644 --- a/compiler/rustc_data_structures/src/owned_slice.rs +++ b/compiler/rustc_data_structures/src/owned_slice.rs @@ -1,10 +1,11 @@ -use std::{borrow::Borrow, ops::Deref}; +use std::borrow::Borrow; +use std::ops::Deref; -use crate::sync::Lrc; // Use our fake Send/Sync traits when on not parallel compiler, // so that `OwnedSlice` only implements/requires Send/Sync // for parallel compiler builds. use crate::sync; +use crate::sync::Lrc; /// An owned slice. /// diff --git a/compiler/rustc_data_structures/src/owned_slice/tests.rs b/compiler/rustc_data_structures/src/owned_slice/tests.rs index 520871a12be99..324b8ecf2d393 100644 --- a/compiler/rustc_data_structures/src/owned_slice/tests.rs +++ b/compiler/rustc_data_structures/src/owned_slice/tests.rs @@ -1,15 +1,9 @@ -use std::{ - ops::Deref, - sync::{ - atomic::{self, AtomicBool}, - Arc, - }, -}; - -use crate::{ - defer, - owned_slice::{slice_owned, try_slice_owned, OwnedSlice}, -}; +use std::ops::Deref; +use std::sync::atomic::{self, AtomicBool}; +use std::sync::Arc; + +use crate::defer; +use crate::owned_slice::{slice_owned, try_slice_owned, OwnedSlice}; #[test] fn smoke() { diff --git a/compiler/rustc_data_structures/src/packed.rs b/compiler/rustc_data_structures/src/packed.rs index 0a392d91988f0..f54b12b5b532d 100644 --- a/compiler/rustc_data_structures/src/packed.rs +++ b/compiler/rustc_data_structures/src/packed.rs @@ -1,8 +1,10 @@ -use crate::stable_hasher::{HashStable, StableHasher}; -use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use std::cmp::Ordering; use std::fmt; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; + +use crate::stable_hasher::{HashStable, StableHasher}; + /// A packed 128-bit integer. Useful for reducing the size of structures in /// some cases. #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] diff --git a/compiler/rustc_data_structures/src/profiling.rs b/compiler/rustc_data_structures/src/profiling.rs index 240f2671c3b2d..19050746c2f18 100644 --- a/compiler/rustc_data_structures/src/profiling.rs +++ b/compiler/rustc_data_structures/src/profiling.rs @@ -81,19 +81,15 @@ //! //! [mm]: https://github.com/rust-lang/measureme/ -use crate::fx::FxHashMap; -use crate::outline; - use std::borrow::Borrow; use std::collections::hash_map::Entry; use std::error::Error; use std::fmt::Display; -use std::fs; use std::intrinsics::unlikely; use std::path::Path; -use std::process; use std::sync::Arc; use std::time::{Duration, Instant}; +use std::{fs, process}; pub use measureme::EventId; use measureme::{EventIdBuilder, Profiler, SerializableString, StringId}; @@ -101,6 +97,9 @@ use parking_lot::RwLock; use smallvec::SmallVec; use tracing::warn; +use crate::fx::FxHashMap; +use crate::outline; + bitflags::bitflags! { #[derive(Clone, Copy)] struct EventFilter: u16 { diff --git a/compiler/rustc_data_structures/src/sharded.rs b/compiler/rustc_data_structures/src/sharded.rs index 4b02b18346069..03aa1d8f67862 100644 --- a/compiler/rustc_data_structures/src/sharded.rs +++ b/compiler/rustc_data_structures/src/sharded.rs @@ -1,14 +1,15 @@ +use std::borrow::Borrow; +use std::collections::hash_map::RawEntryMut; +use std::hash::{Hash, Hasher}; +use std::{iter, mem}; + +#[cfg(parallel_compiler)] +use either::Either; + use crate::fx::{FxHashMap, FxHasher}; #[cfg(parallel_compiler)] use crate::sync::{is_dyn_thread_safe, CacheAligned}; use crate::sync::{Lock, LockGuard, Mode}; -#[cfg(parallel_compiler)] -use either::Either; -use std::borrow::Borrow; -use std::collections::hash_map::RawEntryMut; -use std::hash::{Hash, Hasher}; -use std::iter; -use std::mem; // 32 shards is sufficient to reduce contention on an 8-core Ryzen 7 1700, // but this should be tested on higher core count CPUs. How the `Sharded` type gets used diff --git a/compiler/rustc_data_structures/src/snapshot_map/mod.rs b/compiler/rustc_data_structures/src/snapshot_map/mod.rs index 8a50179cd3b64..d50365b6b0698 100644 --- a/compiler/rustc_data_structures/src/snapshot_map/mod.rs +++ b/compiler/rustc_data_structures/src/snapshot_map/mod.rs @@ -1,11 +1,11 @@ -use crate::fx::FxHashMap; -use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog}; use std::borrow::{Borrow, BorrowMut}; use std::hash::Hash; use std::marker::PhantomData; use std::ops; +use crate::fx::FxHashMap; pub use crate::undo_log::Snapshot; +use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog}; #[cfg(test)] mod tests; diff --git a/compiler/rustc_data_structures/src/sorted_map.rs b/compiler/rustc_data_structures/src/sorted_map.rs index 885f023122ab5..066ea03b4ace4 100644 --- a/compiler/rustc_data_structures/src/sorted_map.rs +++ b/compiler/rustc_data_structures/src/sorted_map.rs @@ -1,10 +1,12 @@ -use crate::stable_hasher::{HashStable, StableHasher, StableOrd}; -use rustc_macros::{Decodable_Generic, Encodable_Generic}; use std::borrow::Borrow; use std::fmt::Debug; use std::mem; use std::ops::{Bound, Index, IndexMut, RangeBounds}; +use rustc_macros::{Decodable_Generic, Encodable_Generic}; + +use crate::stable_hasher::{HashStable, StableHasher, StableOrd}; + mod index_map; pub use index_map::SortedIndexMultiMap; diff --git a/compiler/rustc_data_structures/src/sorted_map/index_map.rs b/compiler/rustc_data_structures/src/sorted_map/index_map.rs index c172ee1c97066..e9a5fb5197548 100644 --- a/compiler/rustc_data_structures/src/sorted_map/index_map.rs +++ b/compiler/rustc_data_structures/src/sorted_map/index_map.rs @@ -2,9 +2,10 @@ use std::hash::{Hash, Hasher}; -use crate::stable_hasher::{HashStable, StableHasher}; use rustc_index::{Idx, IndexVec}; +use crate::stable_hasher::{HashStable, StableHasher}; + /// An indexed multi-map that preserves insertion order while permitting both *O*(log *n*) lookup of /// an item by key and *O*(1) lookup by index. /// diff --git a/compiler/rustc_data_structures/src/sso/map.rs b/compiler/rustc_data_structures/src/sso/map.rs index 2ef4a2ccd8476..3200249a2dc4c 100644 --- a/compiler/rustc_data_structures/src/sso/map.rs +++ b/compiler/rustc_data_structures/src/sso/map.rs @@ -1,10 +1,12 @@ -use crate::fx::FxHashMap; -use arrayvec::ArrayVec; -use either::Either; use std::fmt; use std::hash::Hash; use std::ops::Index; +use arrayvec::ArrayVec; +use either::Either; + +use crate::fx::FxHashMap; + /// For pointer-sized arguments arrays /// are faster than set/map for up to 64 /// arguments. diff --git a/compiler/rustc_data_structures/src/stable_hasher.rs b/compiler/rustc_data_structures/src/stable_hasher.rs index 83883eeba9ca0..9673f94d7a433 100644 --- a/compiler/rustc_data_structures/src/stable_hasher.rs +++ b/compiler/rustc_data_structures/src/stable_hasher.rs @@ -1,19 +1,20 @@ -use rustc_index::bit_set::{self, BitSet}; -use rustc_index::{Idx, IndexSlice, IndexVec}; -use smallvec::SmallVec; use std::hash::{BuildHasher, Hash, Hasher}; use std::marker::PhantomData; use std::mem; use std::num::NonZero; +use rustc_index::bit_set::{self, BitSet}; +use rustc_index::{Idx, IndexSlice, IndexVec}; +use smallvec::SmallVec; + #[cfg(test)] mod tests; -pub use crate::hashes::{Hash128, Hash64}; +pub use rustc_stable_hash::{ + FromStableHash, SipHasher128Hash as StableHasherHash, StableSipHasher128 as StableHasher, +}; -pub use rustc_stable_hash::FromStableHash; -pub use rustc_stable_hash::SipHasher128Hash as StableHasherHash; -pub use rustc_stable_hash::StableSipHasher128 as StableHasher; +pub use crate::hashes::{Hash128, Hash64}; /// Something that implements `HashStable` can be hashed in a way that is /// stable across multiple compilation sessions. diff --git a/compiler/rustc_data_structures/src/svh.rs b/compiler/rustc_data_structures/src/svh.rs index 38629ea9801d9..391a7c9f30dbf 100644 --- a/compiler/rustc_data_structures/src/svh.rs +++ b/compiler/rustc_data_structures/src/svh.rs @@ -5,10 +5,12 @@ //! mismatches where we have two versions of the same crate that were //! compiled from distinct sources. +use std::fmt; + +use rustc_macros::{Decodable_Generic, Encodable_Generic}; + use crate::fingerprint::Fingerprint; use crate::stable_hasher; -use rustc_macros::{Decodable_Generic, Encodable_Generic}; -use std::fmt; #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable_Generic, Decodable_Generic, Hash)] pub struct Svh { diff --git a/compiler/rustc_data_structures/src/sync.rs b/compiler/rustc_data_structures/src/sync.rs index 058a675c40d7b..6df94bc0e9444 100644 --- a/compiler/rustc_data_structures/src/sync.rs +++ b/compiler/rustc_data_structures/src/sync.rs @@ -41,10 +41,11 @@ //! //! [^2]: `MTRef`, `MTLockRef` are type aliases. -pub use crate::marker::*; use std::collections::HashMap; use std::hash::{BuildHasher, Hash}; +pub use crate::marker::*; + mod lock; #[doc(no_inline)] pub use lock::{Lock, LockGuard, Mode}; @@ -56,7 +57,6 @@ mod parallel; #[cfg(parallel_compiler)] pub use parallel::scope; pub use parallel::{join, par_for_each_in, par_map, parallel_guard, try_par_for_each_in}; - pub use vec::{AppendOnlyIndexVec, AppendOnlyVec}; mod vec; diff --git a/compiler/rustc_data_structures/src/sync/freeze.rs b/compiler/rustc_data_structures/src/sync/freeze.rs index 466c44f59bbc8..fad5f583d1ce4 100644 --- a/compiler/rustc_data_structures/src/sync/freeze.rs +++ b/compiler/rustc_data_structures/src/sync/freeze.rs @@ -1,14 +1,13 @@ +use std::cell::UnsafeCell; +use std::intrinsics::likely; +use std::marker::PhantomData; +use std::ops::{Deref, DerefMut}; +use std::ptr::NonNull; +use std::sync::atomic::Ordering; + use crate::sync::{AtomicBool, ReadGuard, RwLock, WriteGuard}; #[cfg(parallel_compiler)] use crate::sync::{DynSend, DynSync}; -use std::{ - cell::UnsafeCell, - intrinsics::likely, - marker::PhantomData, - ops::{Deref, DerefMut}, - ptr::NonNull, - sync::atomic::Ordering, -}; /// A type which allows mutation using a lock until /// the value is frozen and can be accessed lock-free. diff --git a/compiler/rustc_data_structures/src/sync/lock.rs b/compiler/rustc_data_structures/src/sync/lock.rs index 780be77394581..7cf942685e3e1 100644 --- a/compiler/rustc_data_structures/src/sync/lock.rs +++ b/compiler/rustc_data_structures/src/sync/lock.rs @@ -19,19 +19,20 @@ pub enum Mode { } mod maybe_sync { - use super::Mode; - use crate::sync::mode; - #[cfg(parallel_compiler)] - use crate::sync::{DynSend, DynSync}; - use parking_lot::lock_api::RawMutex as _; - use parking_lot::RawMutex; - use std::cell::Cell; - use std::cell::UnsafeCell; + use std::cell::{Cell, UnsafeCell}; use std::intrinsics::unlikely; use std::marker::PhantomData; use std::mem::ManuallyDrop; use std::ops::{Deref, DerefMut}; + use parking_lot::lock_api::RawMutex as _; + use parking_lot::RawMutex; + + use super::Mode; + use crate::sync::mode; + #[cfg(parallel_compiler)] + use crate::sync::{DynSend, DynSync}; + /// A guard holding mutable access to a `Lock` which is in a locked state. #[must_use = "if unused the Lock will immediately unlock"] pub struct LockGuard<'a, T> { @@ -186,12 +187,12 @@ mod maybe_sync { } mod no_sync { - use super::Mode; use std::cell::RefCell; - #[doc(no_inline)] pub use std::cell::RefMut as LockGuard; + use super::Mode; + pub struct Lock(RefCell); impl Lock { diff --git a/compiler/rustc_data_structures/src/sync/parallel.rs b/compiler/rustc_data_structures/src/sync/parallel.rs index 7783de57fba7f..2b89431c2ed79 100644 --- a/compiler/rustc_data_structures/src/sync/parallel.rs +++ b/compiler/rustc_data_structures/src/sync/parallel.rs @@ -3,9 +3,6 @@ #![allow(dead_code)] -use crate::sync::IntoDynSyncSend; -use crate::FatalErrorMarker; -use parking_lot::Mutex; use std::any::Any; use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe}; @@ -13,6 +10,10 @@ use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe}; pub use disabled::*; #[cfg(parallel_compiler)] pub use enabled::*; +use parking_lot::Mutex; + +use crate::sync::IntoDynSyncSend; +use crate::FatalErrorMarker; /// A guard used to hold panics that occur during a parallel section to later by unwound. /// This is used for the parallel compiler to prevent fatal errors from non-deterministically diff --git a/compiler/rustc_data_structures/src/sync/worker_local.rs b/compiler/rustc_data_structures/src/sync/worker_local.rs index 07a361ba26088..4950481d311f0 100644 --- a/compiler/rustc_data_structures/src/sync/worker_local.rs +++ b/compiler/rustc_data_structures/src/sync/worker_local.rs @@ -1,11 +1,10 @@ -use parking_lot::Mutex; -use std::cell::Cell; -use std::cell::OnceCell; +use std::cell::{Cell, OnceCell}; use std::num::NonZero; use std::ops::Deref; use std::ptr; use std::sync::Arc; +use parking_lot::Mutex; #[cfg(parallel_compiler)] use {crate::outline, crate::sync::CacheAligned}; diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 8b9e834b60b0d..25e107b0f413c 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -1,5 +1,3 @@ -use super::{Pointer, Tag}; -use crate::stable_hasher::{HashStable, StableHasher}; use std::fmt; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; @@ -8,6 +6,9 @@ use std::num::NonZero; use std::ops::{Deref, DerefMut}; use std::ptr::NonNull; +use super::{Pointer, Tag}; +use crate::stable_hasher::{HashStable, StableHasher}; + /// A [`Copy`] tagged pointer. /// /// This is essentially `{ pointer: P, tag: T }` packed in a single pointer. diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs index 4e42b5b4afe8a..319a8cdd3990a 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs @@ -2,8 +2,7 @@ use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::{Deref, DerefMut}; -use super::CopyTaggedPtr; -use super::{Pointer, Tag}; +use super::{CopyTaggedPtr, Pointer, Tag}; use crate::stable_hasher::{HashStable, StableHasher}; /// A tagged pointer that supports pointers that implement [`Drop`]. diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs index 2c17d678d3aa0..4d342c72cc52a 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs @@ -1,4 +1,5 @@ -use std::{ptr, sync::Arc}; +use std::ptr; +use std::sync::Arc; use crate::tagged_ptr::{Pointer, Tag, Tag2, TaggedPtr}; diff --git a/compiler/rustc_data_structures/src/temp_dir.rs b/compiler/rustc_data_structures/src/temp_dir.rs index 621d3011a2aa1..4dbe11d707d77 100644 --- a/compiler/rustc_data_structures/src/temp_dir.rs +++ b/compiler/rustc_data_structures/src/temp_dir.rs @@ -1,5 +1,6 @@ use std::mem::ManuallyDrop; use std::path::Path; + use tempfile::TempDir; /// This is used to avoid TempDir being dropped on error paths unintentionally. diff --git a/compiler/rustc_data_structures/src/transitive_relation.rs b/compiler/rustc_data_structures/src/transitive_relation.rs index cd391fe357a6f..26b00e0af3a8a 100644 --- a/compiler/rustc_data_structures/src/transitive_relation.rs +++ b/compiler/rustc_data_structures/src/transitive_relation.rs @@ -1,11 +1,13 @@ -use crate::frozen::Frozen; -use crate::fx::{FxHashSet, FxIndexSet}; -use rustc_index::bit_set::BitMatrix; use std::fmt::Debug; use std::hash::Hash; use std::mem; use std::ops::Deref; +use rustc_index::bit_set::BitMatrix; + +use crate::frozen::Frozen; +use crate::fx::{FxHashSet, FxIndexSet}; + #[cfg(test)] mod tests; diff --git a/compiler/rustc_data_structures/src/unord.rs b/compiler/rustc_data_structures/src/unord.rs index 1ccd22a56c959..bafb16a8b5e67 100644 --- a/compiler/rustc_data_structures/src/unord.rs +++ b/compiler/rustc_data_structures/src/unord.rs @@ -2,21 +2,17 @@ //! ordering. This is a useful property for deterministic computations, such //! as required by the query system. +use std::borrow::{Borrow, BorrowMut}; +use std::collections::hash_map::{Entry, OccupiedError}; +use std::hash::Hash; +use std::iter::{Product, Sum}; +use std::ops::Index; + use rustc_hash::{FxHashMap, FxHashSet}; use rustc_macros::{Decodable_Generic, Encodable_Generic}; -use std::collections::hash_map::OccupiedError; -use std::{ - borrow::{Borrow, BorrowMut}, - collections::hash_map::Entry, - hash::Hash, - iter::{Product, Sum}, - ops::Index, -}; - -use crate::{ - fingerprint::Fingerprint, - stable_hasher::{HashStable, StableCompare, StableHasher, ToStableHashKey}, -}; + +use crate::fingerprint::Fingerprint; +use crate::stable_hasher::{HashStable, StableCompare, StableHasher, ToStableHashKey}; /// `UnordItems` is the order-less version of `Iterator`. It only contains methods /// that don't (easily) expose an ordering of the underlying items. diff --git a/compiler/rustc_data_structures/src/work_queue.rs b/compiler/rustc_data_structures/src/work_queue.rs index 9db6b6f20bede..490d7d3ddd57c 100644 --- a/compiler/rustc_data_structures/src/work_queue.rs +++ b/compiler/rustc_data_structures/src/work_queue.rs @@ -1,6 +1,7 @@ +use std::collections::VecDeque; + use rustc_index::bit_set::BitSet; use rustc_index::Idx; -use std::collections::VecDeque; /// A work queue is a handy data structure for tracking work left to /// do. (For example, basic blocks left to process.) It is basically a diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index ad2acb03b3f67..627a0ebb4e5e3 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -17,8 +17,23 @@ #![feature(rustdoc_internals)] // tidy-alphabetical-end +use std::cmp::max; +use std::collections::BTreeMap; +use std::ffi::OsString; +use std::fmt::Write as _; +use std::fs::{self, File}; +use std::io::{self, IsTerminal, Read, Write}; +use std::panic::{self, catch_unwind, PanicHookInfo}; +use std::path::PathBuf; +use std::process::{self, Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, OnceLock}; +use std::time::{Duration, Instant, SystemTime}; +use std::{env, str}; + use rustc_ast as ast; -use rustc_codegen_ssa::{traits::CodegenBackend, CodegenErrors, CodegenResults}; +use rustc_codegen_ssa::traits::CodegenBackend; +use rustc_codegen_ssa::{CodegenErrors, CodegenResults}; use rustc_const_eval::CTRL_C_RECEIVED; use rustc_data_structures::profiling::{ get_resident_set_size, print_time_passes_entry, TimePassesFormat, @@ -35,8 +50,9 @@ use rustc_lint::unerased_lint_store; use rustc_metadata::creader::MetadataLoader; use rustc_metadata::locator; use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal}; -use rustc_session::config::{nightly_options, CG_OPTIONS, Z_OPTIONS}; -use rustc_session::config::{ErrorOutputType, Input, OutFileName, OutputType}; +use rustc_session::config::{ + nightly_options, ErrorOutputType, Input, OutFileName, OutputType, CG_OPTIONS, Z_OPTIONS, +}; use rustc_session::getopts::{self, Matches}; use rustc_session::lint::{Lint, LintId}; use rustc_session::output::collect_crate_types; @@ -46,20 +62,6 @@ use rustc_span::symbol::sym; use rustc_span::FileName; use rustc_target::json::ToJson; use rustc_target::spec::{Target, TargetTriple}; -use std::cmp::max; -use std::collections::BTreeMap; -use std::env; -use std::ffi::OsString; -use std::fmt::Write as _; -use std::fs::{self, File}; -use std::io::{self, IsTerminal, Read, Write}; -use std::panic::{self, catch_unwind, PanicHookInfo}; -use std::path::PathBuf; -use std::process::{self, Command, Stdio}; -use std::str; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, OnceLock}; -use std::time::{Duration, Instant, SystemTime}; use time::OffsetDateTime; use tracing::trace; @@ -689,7 +691,6 @@ fn print_crate_info( parse_attrs: bool, ) -> Compilation { use rustc_session::config::PrintKind::*; - // This import prevents the following code from using the printing macros // used by the rest of the module. Within this function, we only write to // the output specified by `sess.io.output_file`. @@ -908,6 +909,15 @@ pub fn version_at_macro_invocation( ) { let verbose = matches.opt_present("verbose"); + let mut version = version; + let mut release = release; + let tmp; + if let Ok(force_version) = std::env::var("RUSTC_OVERRIDE_VERSION_STRING") { + tmp = force_version; + version = &tmp; + release = &tmp; + } + safe_println!("{binary} {version}"); if verbose { diff --git a/compiler/rustc_driver_impl/src/pretty.rs b/compiler/rustc_driver_impl/src/pretty.rs index 31de0a747b24f..c973fcec0e19a 100644 --- a/compiler/rustc_driver_impl/src/pretty.rs +++ b/compiler/rustc_driver_impl/src/pretty.rs @@ -1,9 +1,10 @@ //! The various pretty-printing routines. -use rustc_ast as ast; +use std::cell::Cell; +use std::fmt::Write; + use rustc_ast_pretty::pprust as pprust_ast; use rustc_errors::FatalError; -use rustc_hir_pretty as pprust_hir; use rustc_middle::bug; use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty}; use rustc_middle::ty::{self, TyCtxt}; @@ -12,9 +13,8 @@ use rustc_session::Session; use rustc_smir::rustc_internal::pretty::write_smir_pretty; use rustc_span::symbol::Ident; use rustc_span::FileName; -use std::cell::Cell; -use std::fmt::Write; use tracing::debug; +use {rustc_ast as ast, rustc_hir_pretty as pprust_hir}; pub use self::PpMode::*; pub use self::PpSourceMode::*; diff --git a/compiler/rustc_driver_impl/src/signal_handler.rs b/compiler/rustc_driver_impl/src/signal_handler.rs index 441219eec90dc..51f2a508cf90c 100644 --- a/compiler/rustc_driver_impl/src/signal_handler.rs +++ b/compiler/rustc_driver_impl/src/signal_handler.rs @@ -1,10 +1,11 @@ //! Signal handler for rustc //! Primarily used to extract a backtrace from stack overflow -use rustc_interface::util::{DEFAULT_STACK_SIZE, STACK_SIZE}; use std::alloc::{alloc, Layout}; use std::{fmt, mem, ptr}; +use rustc_interface::util::{DEFAULT_STACK_SIZE, STACK_SIZE}; + extern "C" { fn backtrace_symbols_fd(buffer: *const *mut libc::c_void, size: libc::c_int, fd: libc::c_int); } diff --git a/compiler/rustc_error_codes/src/error_codes/E0736.md b/compiler/rustc_error_codes/src/error_codes/E0736.md index 0f3d41ba66dc4..cb7633b7068a3 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0736.md +++ b/compiler/rustc_error_codes/src/error_codes/E0736.md @@ -1,14 +1,20 @@ -`#[track_caller]` and `#[naked]` cannot both be applied to the same function. +Functions marked with the `#[naked]` attribute are restricted in what other +attributes they may be marked with. + +Notable attributes that are incompatible with `#[naked]` are: + +* `#[inline]` +* `#[track_caller]` +* `#[test]`, `#[ignore]`, `#[should_panic]` Erroneous code example: ```compile_fail,E0736 +#[inline] #[naked] -#[track_caller] fn foo() {} ``` -This is primarily due to ABI incompatibilities between the two attributes. -See [RFC 2091] for details on this and other limitations. - -[RFC 2091]: https://github.com/rust-lang/rfcs/blob/master/text/2091-inline-semantic.md +These incompatibilities are due to the fact that naked functions deliberately +impose strict restrictions regarding the code that the compiler is +allowed to produce for this function. diff --git a/compiler/rustc_error_codes/src/error_codes/E0739.md b/compiler/rustc_error_codes/src/error_codes/E0739.md index 8d9039bef93f6..406d3d52779db 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0739.md +++ b/compiler/rustc_error_codes/src/error_codes/E0739.md @@ -1,4 +1,4 @@ -`#[track_caller]` can not be applied on struct. +`#[track_caller]` must be applied to a function Erroneous code example: diff --git a/compiler/rustc_error_codes/src/error_codes/E0795.md b/compiler/rustc_error_codes/src/error_codes/E0795.md index ad77d72c913a8..69e61f7738f79 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0795.md +++ b/compiler/rustc_error_codes/src/error_codes/E0795.md @@ -3,7 +3,7 @@ Invalid argument for the `offset_of!` macro. Erroneous code example: ```compile_fail,E0795 -#![feature(offset_of_enum, offset_of_nested)] +#![feature(offset_of_enum)] let x = std::mem::offset_of!(Option, Some); ``` @@ -16,7 +16,7 @@ The offset of the contained `u8` in the `Option` can be found by specifying the field name `0`: ``` -#![feature(offset_of_enum, offset_of_nested)] +#![feature(offset_of_enum)] let x: usize = std::mem::offset_of!(Option, Some.0); ``` diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index 26a68454ab3b1..87dee2898daf0 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -6,31 +6,28 @@ #![feature(type_alias_impl_trait)] // tidy-alphabetical-end -use fluent_bundle::FluentResource; -use fluent_syntax::parser::ParserError; -use icu_provider_adapters::fallback::{LocaleFallbackProvider, LocaleFallbacker}; -use rustc_data_structures::sync::{IntoDynSyncSend, Lrc}; -use rustc_macros::{Decodable, Encodable}; -use rustc_span::Span; use std::borrow::Cow; -use std::error::Error; -use std::fmt; -use std::fs; -use std::io; -use std::path::{Path, PathBuf}; -use tracing::{instrument, trace}; - #[cfg(not(parallel_compiler))] use std::cell::LazyCell as Lazy; +use std::error::Error; +use std::path::{Path, PathBuf}; #[cfg(parallel_compiler)] use std::sync::LazyLock as Lazy; +use std::{fmt, fs, io}; +pub use fluent_bundle::types::FluentType; +use fluent_bundle::FluentResource; +pub use fluent_bundle::{self, FluentArgs, FluentError, FluentValue}; +use fluent_syntax::parser::ParserError; +use icu_provider_adapters::fallback::{LocaleFallbackProvider, LocaleFallbacker}; #[cfg(parallel_compiler)] use intl_memoizer::concurrent::IntlLangMemoizer; #[cfg(not(parallel_compiler))] use intl_memoizer::IntlLangMemoizer; - -pub use fluent_bundle::{self, types::FluentType, FluentArgs, FluentError, FluentValue}; +use rustc_data_structures::sync::{IntoDynSyncSend, Lrc}; +use rustc_macros::{Decodable, Encodable}; +use rustc_span::Span; +use tracing::{instrument, trace}; pub use unic_langid::{langid, LanguageIdentifier}; pub type FluentBundle = diff --git a/compiler/rustc_errors/Cargo.toml b/compiler/rustc_errors/Cargo.toml index cc114fdcd8c35..2fff9f2de50fb 100644 --- a/compiler/rustc_errors/Cargo.toml +++ b/compiler/rustc_errors/Cargo.toml @@ -26,7 +26,6 @@ serde_json = "1.0.59" termcolor = "1.2.0" termize = "0.1.1" tracing = "0.1" -unicode-width = "0.1.4" # tidy-alphabetical-end [target.'cfg(windows)'.dependencies.windows] diff --git a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs index b71b93cc67c16..df4e9792f9538 100644 --- a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs +++ b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs @@ -5,6 +5,12 @@ //! //! [annotate_snippets]: https://docs.rs/crate/annotate-snippets/ +use annotate_snippets::{Annotation, AnnotationType, Renderer, Slice, Snippet, SourceAnnotation}; +use rustc_data_structures::sync::Lrc; +use rustc_error_messages::FluentArgs; +use rustc_span::source_map::SourceMap; +use rustc_span::SourceFile; + use crate::emitter::FileWithAnnotatedLines; use crate::snippet::Line; use crate::translation::{to_fluent_args, Translate}; @@ -12,11 +18,6 @@ use crate::{ CodeSuggestion, DiagInner, DiagMessage, Emitter, ErrCode, FluentBundle, LazyFallbackBundle, Level, MultiSpan, Style, Subdiag, }; -use annotate_snippets::{Annotation, AnnotationType, Renderer, Slice, Snippet, SourceAnnotation}; -use rustc_data_structures::sync::Lrc; -use rustc_error_messages::FluentArgs; -use rustc_span::source_map::SourceMap; -use rustc_span::SourceFile; /// Generates diagnostics using annotate-snippet pub struct AnnotateSnippetEmitter { diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index d500f6d88a01b..e1dcbf5b2805b 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -1,16 +1,3 @@ -use crate::snippet::Style; -use crate::{ - CodeSuggestion, DiagCtxtHandle, DiagMessage, ErrCode, ErrorGuaranteed, ExplicitBug, Level, - MultiSpan, StashKey, SubdiagMessage, Substitution, SubstitutionPart, SuggestionStyle, -}; -use rustc_data_structures::fx::FxIndexMap; -use rustc_error_messages::fluent_value_from_str_list_sep_by_and; -use rustc_error_messages::FluentValue; -use rustc_lint_defs::{Applicability, LintExpectationId}; -use rustc_macros::{Decodable, Encodable}; -use rustc_span::source_map::Spanned; -use rustc_span::symbol::Symbol; -use rustc_span::{Span, DUMMY_SP}; use std::borrow::Cow; use std::fmt::{self, Debug}; use std::hash::{Hash, Hasher}; @@ -18,8 +5,22 @@ use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::panic; use std::thread::panicking; + +use rustc_data_structures::fx::FxIndexMap; +use rustc_error_messages::{fluent_value_from_str_list_sep_by_and, FluentValue}; +use rustc_lint_defs::{Applicability, LintExpectationId}; +use rustc_macros::{Decodable, Encodable}; +use rustc_span::source_map::Spanned; +use rustc_span::symbol::Symbol; +use rustc_span::{Span, DUMMY_SP}; use tracing::debug; +use crate::snippet::Style; +use crate::{ + CodeSuggestion, DiagCtxtHandle, DiagMessage, ErrCode, ErrorGuaranteed, ExplicitBug, Level, + MultiSpan, StashKey, SubdiagMessage, Substitution, SubstitutionPart, SuggestionStyle, +}; + /// Error type for `DiagInner`'s `suggestions` field, indicating that /// `.disable_suggestions()` was called on the `DiagInner`. #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)] diff --git a/compiler/rustc_errors/src/diagnostic_impls.rs b/compiler/rustc_errors/src/diagnostic_impls.rs index e6ca1bf7bc45f..3e22786a01f7a 100644 --- a/compiler/rustc_errors/src/diagnostic_impls.rs +++ b/compiler/rustc_errors/src/diagnostic_impls.rs @@ -1,12 +1,11 @@ -use crate::diagnostic::DiagLocation; -use crate::{fluent_generated as fluent, DiagCtxtHandle, Subdiagnostic}; -use crate::{ - Diag, DiagArgValue, Diagnostic, EmissionGuarantee, ErrCode, IntoDiagArg, Level, - SubdiagMessageOp, -}; -use rustc_ast as ast; +use std::backtrace::Backtrace; +use std::borrow::Cow; +use std::fmt; +use std::num::ParseIntError; +use std::path::{Path, PathBuf}; +use std::process::ExitStatus; + use rustc_ast_pretty::pprust; -use rustc_hir as hir; use rustc_macros::Subdiagnostic; use rustc_span::edition::Edition; use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent, Symbol}; @@ -14,12 +13,13 @@ use rustc_span::Span; use rustc_target::abi::TargetDataLayoutErrors; use rustc_target::spec::{PanicStrategy, SplitDebuginfo, StackProtector, TargetTriple}; use rustc_type_ir::{ClosureKind, FloatTy}; -use std::backtrace::Backtrace; -use std::borrow::Cow; -use std::fmt; -use std::num::ParseIntError; -use std::path::{Path, PathBuf}; -use std::process::ExitStatus; +use {rustc_ast as ast, rustc_hir as hir}; + +use crate::diagnostic::DiagLocation; +use crate::{ + fluent_generated as fluent, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, + ErrCode, IntoDiagArg, Level, SubdiagMessageOp, Subdiagnostic, +}; pub struct DiagArgFromDisplay<'a>(pub &'a dyn fmt::Display); diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index aa47ca166764b..483b757f20c18 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -7,35 +7,35 @@ //! //! The output types are defined in `rustc_session::config::ErrorOutputType`. +use std::borrow::Cow; +use std::cmp::{max, min, Reverse}; +use std::error::Report; +use std::io::prelude::*; +use std::io::{self, IsTerminal}; +use std::iter; +use std::path::Path; + +use derive_setters::Setters; +use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; +use rustc_data_structures::sync::{DynSend, IntoDynSyncSend, Lrc}; +use rustc_error_messages::{FluentArgs, SpanLabel}; +use rustc_lint_defs::pluralize; +use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::source_map::SourceMap; -use rustc_span::{FileLines, FileName, SourceFile, Span}; +use rustc_span::{char_width, FileLines, FileName, SourceFile, Span}; +use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; +use tracing::{debug, instrument, trace, warn}; +use crate::diagnostic::DiagLocation; use crate::snippet::{ Annotation, AnnotationColumn, AnnotationType, Line, MultilineAnnotation, Style, StyledString, }; use crate::styled_buffer::StyledBuffer; use crate::translation::{to_fluent_args, Translate}; use crate::{ - diagnostic::DiagLocation, CodeSuggestion, DiagCtxt, DiagInner, DiagMessage, ErrCode, - FluentBundle, LazyFallbackBundle, Level, MultiSpan, Subdiag, SubstitutionHighlight, - SuggestionStyle, TerminalUrl, + CodeSuggestion, DiagCtxt, DiagInner, DiagMessage, ErrCode, FluentBundle, LazyFallbackBundle, + Level, MultiSpan, Subdiag, SubstitutionHighlight, SuggestionStyle, TerminalUrl, }; -use derive_setters::Setters; -use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; -use rustc_data_structures::sync::{DynSend, IntoDynSyncSend, Lrc}; -use rustc_error_messages::{FluentArgs, SpanLabel}; -use rustc_lint_defs::pluralize; -use rustc_span::hygiene::{ExpnKind, MacroKind}; -use std::borrow::Cow; -use std::cmp::{max, min, Reverse}; -use std::error::Report; -use std::io::prelude::*; -use std::io::{self, IsTerminal}; -use std::iter; -use std::path::Path; -use termcolor::{Buffer, BufferWriter, ColorChoice, ColorSpec, StandardStream}; -use termcolor::{Color, WriteColor}; -use tracing::{debug, instrument, trace, warn}; /// Default column width, used in tests and when terminal dimensions cannot be determined. const DEFAULT_COLUMN_WIDTH: usize = 140; @@ -677,10 +677,7 @@ impl HumanEmitter { .skip(left) .take_while(|ch| { // Make sure that the trimming on the right will fall within the terminal width. - // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` - // is. For now, just accept that sometimes the code line will be longer than - // desired. - let next = unicode_width::UnicodeWidthChar::width(*ch).unwrap_or(1); + let next = char_width(*ch); if taken + next > right - left { return false; } @@ -742,11 +739,7 @@ impl HumanEmitter { let left = margin.left(source_string.len()); // Account for unicode characters of width !=0 that were removed. - let left = source_string - .chars() - .take(left) - .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1)) - .sum(); + let left = source_string.chars().take(left).map(|ch| char_width(ch)).sum(); self.draw_line( buffer, @@ -1353,10 +1346,11 @@ impl HumanEmitter { buffer.append(0, ": ", header_style); label_width += 2; } + let mut line = 0; for (text, _) in msgs.iter() { let text = self.translate_message(text, args).map_err(Report::new).unwrap(); // Account for newlines to align output to its label. - for (line, text) in normalize_whitespace(&text).lines().enumerate() { + for text in normalize_whitespace(&text).lines() { buffer.append( line, &format!( @@ -1366,6 +1360,25 @@ impl HumanEmitter { ), header_style, ); + line += 1; + } + } + if self.short_message { + let labels = msp + .span_labels() + .into_iter() + .filter_map(|label| match label.label { + Some(msg) if label.is_primary => { + let text = self.translate_message(&msg, args).ok()?; + if !text.trim().is_empty() { Some(text.to_string()) } else { None } + } + _ => None, + }) + .collect::>() + .join(", "); + if !labels.is_empty() { + buffer.append(line, ": ", Style::NoStyle); + buffer.append(line, &labels, Style::NoStyle); } } } @@ -1774,7 +1787,10 @@ impl HumanEmitter { debug!(?suggestions); if suggestions.is_empty() { - // Suggestions coming from macros can have malformed spans. This is a heavy handed + // Here we check if there are suggestions that have actual code changes. We sometimes + // suggest the same code that is already there, instead of changing how we produce the + // suggestions and filtering there, we just don't emit the suggestion. + // Suggestions coming from macros can also have malformed spans. This is a heavy handed // approach to avoid ICEs by ignoring the suggestion outright. return Ok(()); } @@ -2039,7 +2055,7 @@ impl HumanEmitter { let sub_len: usize = if is_whitespace_addition { &part.snippet } else { part.snippet.trim() } .chars() - .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1)) + .map(|ch| char_width(ch)) .sum(); let offset: isize = offsets @@ -2053,7 +2069,9 @@ impl HumanEmitter { assert!(underline_start >= 0 && underline_end >= 0); let padding: usize = max_line_num_len + 3; for p in underline_start..underline_end { - if let DisplaySuggestion::Underline = show_code_change { + if let DisplaySuggestion::Underline = show_code_change + && is_different(sm, &part.snippet, part.span) + { // If this is a replacement, underline with `~`, if this is an addition // underline with `+`. buffer.putc( @@ -2076,11 +2094,8 @@ impl HumanEmitter { } // length of the code after substitution - let full_sub_len = part - .snippet - .chars() - .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1)) - .sum::() as isize; + let full_sub_len = + part.snippet.chars().map(|ch| char_width(ch)).sum::() as isize; // length of the code to be substituted let snippet_len = span_end_pos as isize - span_start_pos as isize; @@ -2568,26 +2583,69 @@ fn num_decimal_digits(num: usize) -> usize { } // We replace some characters so the CLI output is always consistent and underlines aligned. +// Keep the following list in sync with `rustc_span::char_width`. +// ATTENTION: keep lexicografically sorted so that the binary search will work const OUTPUT_REPLACEMENTS: &[(char, &str)] = &[ - ('\t', " "), // We do our own tab replacement - ('\u{200D}', ""), // Replace ZWJ with nothing for consistent terminal output of grapheme clusters. - ('\u{202A}', ""), // The following unicode text flow control characters are inconsistently - ('\u{202B}', ""), // supported across CLIs and can cause confusion due to the bytes on disk - ('\u{202D}', ""), // not corresponding to the visible source code, so we replace them always. - ('\u{202E}', ""), - ('\u{2066}', ""), - ('\u{2067}', ""), - ('\u{2068}', ""), - ('\u{202C}', ""), - ('\u{2069}', ""), + // tidy-alphabetical-start + // In terminals without Unicode support the following will be garbled, but in *all* terminals + // the underlying codepoint will be as well. We could gate this replacement behind a "unicode + // support" gate. + ('\0', "␀"), + ('\u{0001}', "␁"), + ('\u{0002}', "␂"), + ('\u{0003}', "␃"), + ('\u{0004}', "␄"), + ('\u{0005}', "␅"), + ('\u{0006}', "␆"), + ('\u{0007}', "␇"), + ('\u{0008}', "␈"), + ('\u{0009}', " "), // We do our own tab replacement + ('\u{000b}', "␋"), + ('\u{000c}', "␌"), + ('\u{000d}', "␍"), + ('\u{000e}', "␎"), + ('\u{000f}', "␏"), + ('\u{0010}', "␐"), + ('\u{0011}', "␑"), + ('\u{0012}', "␒"), + ('\u{0013}', "␓"), + ('\u{0014}', "␔"), + ('\u{0015}', "␕"), + ('\u{0016}', "␖"), + ('\u{0017}', "␗"), + ('\u{0018}', "␘"), + ('\u{0019}', "␙"), + ('\u{001a}', "␚"), + ('\u{001b}', "␛"), + ('\u{001c}', "␜"), + ('\u{001d}', "␝"), + ('\u{001e}', "␞"), + ('\u{001f}', "␟"), + ('\u{007f}', "␡"), + ('\u{200d}', ""), // Replace ZWJ for consistent terminal output of grapheme clusters. + ('\u{202a}', "�"), // The following unicode text flow control characters are inconsistently + ('\u{202b}', "�"), // supported across CLIs and can cause confusion due to the bytes on disk + ('\u{202c}', "�"), // not corresponding to the visible source code, so we replace them always. + ('\u{202d}', "�"), + ('\u{202e}', "�"), + ('\u{2066}', "�"), + ('\u{2067}', "�"), + ('\u{2068}', "�"), + ('\u{2069}', "�"), + // tidy-alphabetical-end ]; -fn normalize_whitespace(str: &str) -> String { - let mut s = str.to_string(); - for (c, replacement) in OUTPUT_REPLACEMENTS { - s = s.replace(*c, replacement); - } - s +fn normalize_whitespace(s: &str) -> String { + // Scan the input string for a character in the ordered table above. If it's present, replace + // it with it's alternative string (it can be more than 1 char!). Otherwise, retain the input + // char. At the end, allocate all chars into a string in one operation. + s.chars().fold(String::with_capacity(s.len()), |mut s, c| { + match OUTPUT_REPLACEMENTS.binary_search_by_key(&c, |(k, _)| *k) { + Ok(i) => s.push_str(OUTPUT_REPLACEMENTS[i].1), + _ => s.push(c), + } + s + }) } fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) { @@ -2799,6 +2857,18 @@ impl Style { } } +/// Whether the original and suggested code are the same. +pub fn is_different(sm: &SourceMap, suggested: &str, sp: Span) -> bool { + let found = match sm.span_to_snippet(sp) { + Ok(snippet) => snippet, + Err(e) => { + warn!(error = ?e, "Invalid span {:?}", sp); + return true; + } + }; + found != suggested +} + /// Whether the original and suggested code are visually similar enough to warrant extra wording. pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool { // FIXME: this should probably be extended to also account for `FO0` → `FOO` and unicode. diff --git a/compiler/rustc_errors/src/error.rs b/compiler/rustc_errors/src/error.rs index ca818a4d832d1..462467d9fa0bf 100644 --- a/compiler/rustc_errors/src/error.rs +++ b/compiler/rustc_errors/src/error.rs @@ -1,11 +1,10 @@ -use rustc_error_messages::{ - fluent_bundle::resolver::errors::{ReferenceKind, ResolverError}, - FluentArgs, FluentError, -}; use std::borrow::Cow; use std::error::Error; use std::fmt; +use rustc_error_messages::fluent_bundle::resolver::errors::{ReferenceKind, ResolverError}; +use rustc_error_messages::{FluentArgs, FluentError}; + #[derive(Debug)] pub enum TranslateError<'args> { One { diff --git a/compiler/rustc_errors/src/json.rs b/compiler/rustc_errors/src/json.rs index 764134d5335fd..42a28bc789013 100644 --- a/compiler/rustc_errors/src/json.rs +++ b/compiler/rustc_errors/src/json.rs @@ -9,16 +9,12 @@ // FIXME: spec the JSON output properly. -use crate::emitter::{ - should_show_source_code, ColorConfig, Destination, Emitter, HumanEmitter, - HumanReadableErrorType, -}; -use crate::registry::Registry; -use crate::translation::{to_fluent_args, Translate}; -use crate::{ - diagnostic::IsLint, CodeSuggestion, FluentBundle, LazyFallbackBundle, MultiSpan, SpanLabel, - Subdiag, TerminalUrl, -}; +use std::error::Report; +use std::io::{self, Write}; +use std::path::Path; +use std::sync::{Arc, Mutex}; +use std::vec; + use derive_setters::Setters; use rustc_data_structures::sync::{IntoDynSyncSend, Lrc}; use rustc_error_messages::FluentArgs; @@ -27,13 +23,19 @@ use rustc_span::hygiene::ExpnData; use rustc_span::source_map::SourceMap; use rustc_span::Span; use serde::Serialize; -use std::error::Report; -use std::io::{self, Write}; -use std::path::Path; -use std::sync::{Arc, Mutex}; -use std::vec; use termcolor::{ColorSpec, WriteColor}; +use crate::diagnostic::IsLint; +use crate::emitter::{ + should_show_source_code, ColorConfig, Destination, Emitter, HumanEmitter, + HumanReadableErrorType, +}; +use crate::registry::Registry; +use crate::translation::{to_fluent_args, Translate}; +use crate::{ + CodeSuggestion, FluentBundle, LazyFallbackBundle, MultiSpan, SpanLabel, Subdiag, TerminalUrl, +}; + #[cfg(test)] mod tests; diff --git a/compiler/rustc_errors/src/json/tests.rs b/compiler/rustc_errors/src/json/tests.rs index e4b29fc9103d6..e3549fc3aa537 100644 --- a/compiler/rustc_errors/src/json/tests.rs +++ b/compiler/rustc_errors/src/json/tests.rs @@ -1,13 +1,12 @@ -use super::*; +use std::str; -use crate::DiagCtxt; use rustc_span::source_map::FilePathMapping; use rustc_span::BytePos; - -use std::str; - use serde::Deserialize; +use super::*; +use crate::DiagCtxt; + #[derive(Deserialize, Debug, PartialEq, Eq)] struct TestData { spans: Vec, diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 2a850d9303c71..ceebcd46a6f7f 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -28,6 +28,17 @@ extern crate self as rustc_errors; +use std::backtrace::{Backtrace, BacktraceStatus}; +use std::borrow::Cow; +use std::cell::Cell; +use std::error::Report; +use std::hash::Hash; +use std::io::Write; +use std::num::NonZero; +use std::ops::DerefMut; +use std::path::{Path, PathBuf}; +use std::{fmt, panic}; + pub use codes::*; pub use diagnostic::{ BugAbort, Diag, DiagArg, DiagArgMap, DiagArgName, DiagArgValue, DiagInner, DiagStyledString, @@ -39,42 +50,28 @@ pub use diagnostic_impls::{ IndicateAnonymousLifetime, SingleLabelManySpans, }; pub use emitter::ColorConfig; +use emitter::{is_case_difference, is_different, DynEmitter, Emitter}; +use registry::Registry; +use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; +use rustc_data_structures::stable_hasher::{Hash128, StableHasher}; +use rustc_data_structures::sync::{Lock, Lrc}; +use rustc_data_structures::AtomicRef; pub use rustc_error_messages::{ fallback_fluent_bundle, fluent_bundle, DiagMessage, FluentBundle, LanguageIdentifier, LazyFallbackBundle, MultiSpan, SpanLabel, SubdiagMessage, }; +use rustc_lint_defs::LintExpectationId; pub use rustc_lint_defs::{pluralize, Applicability}; +use rustc_macros::{Decodable, Encodable}; pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker}; +use rustc_span::source_map::SourceMap; pub use rustc_span::ErrorGuaranteed; +use rustc_span::{Loc, Span, DUMMY_SP}; pub use snippet::Style; - // Used by external projects such as `rust-gpu`. // See https://github.com/rust-lang/rust/pull/115393. pub use termcolor::{Color, ColorSpec, WriteColor}; - -use emitter::{is_case_difference, DynEmitter, Emitter}; -use registry::Registry; -use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; -use rustc_data_structures::stable_hasher::{Hash128, StableHasher}; -use rustc_data_structures::sync::{Lock, Lrc}; -use rustc_data_structures::AtomicRef; -use rustc_lint_defs::LintExpectationId; -use rustc_macros::{Decodable, Encodable}; -use rustc_span::source_map::SourceMap; -use rustc_span::{Loc, Span, DUMMY_SP}; -use std::backtrace::{Backtrace, BacktraceStatus}; -use std::borrow::Cow; -use std::cell::Cell; -use std::error::Report; -use std::fmt; -use std::hash::Hash; -use std::io::Write; -use std::num::NonZero; -use std::ops::DerefMut; -use std::panic; -use std::path::{Path, PathBuf}; use tracing::debug; - use Level::*; pub mod annotate_snippet_emitter_writer; @@ -360,10 +357,16 @@ impl CodeSuggestion { _ => 1, }) .sum(); - line_highlight.push(SubstitutionHighlight { - start: (cur_lo.col.0 as isize + acc) as usize, - end: (cur_lo.col.0 as isize + acc + len) as usize, - }); + if !is_different(sm, &part.snippet, part.span) { + // Account for cases where we are suggesting the same code that's already + // there. This shouldn't happen often, but in some cases for multipart + // suggestions it's much easier to handle it here than in the origin. + } else { + line_highlight.push(SubstitutionHighlight { + start: (cur_lo.col.0 as isize + acc) as usize, + end: (cur_lo.col.0 as isize + acc + len) as usize, + }); + } buf.push_str(&part.snippet); let cur_hi = sm.lookup_char_pos(part.span.hi()); // Account for the difference between the width of the current code and the @@ -395,7 +398,11 @@ impl CodeSuggestion { while buf.ends_with('\n') { buf.pop(); } - Some((buf, substitution.parts, highlights, only_capitalization)) + if highlights.iter().all(|parts| parts.is_empty()) { + None + } else { + Some((buf, substitution.parts, highlights, only_capitalization)) + } }) .collect() } diff --git a/compiler/rustc_errors/src/lock.rs b/compiler/rustc_errors/src/lock.rs index 0aeb511214bbc..915542c909240 100644 --- a/compiler/rustc_errors/src/lock.rs +++ b/compiler/rustc_errors/src/lock.rs @@ -16,10 +16,10 @@ pub fn acquire_global_lock(name: &str) -> Box { use std::ffi::CString; use std::io; - use windows::{ - core::PCSTR, - Win32::Foundation::{CloseHandle, HANDLE, WAIT_ABANDONED, WAIT_OBJECT_0}, - Win32::System::Threading::{CreateMutexA, ReleaseMutex, WaitForSingleObject, INFINITE}, + use windows::core::PCSTR; + use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_ABANDONED, WAIT_OBJECT_0}; + use windows::Win32::System::Threading::{ + CreateMutexA, ReleaseMutex, WaitForSingleObject, INFINITE, }; struct Handle(HANDLE); diff --git a/compiler/rustc_errors/src/markdown/parse.rs b/compiler/rustc_errors/src/markdown/parse.rs index 69e7120e7149b..c44f136120a74 100644 --- a/compiler/rustc_errors/src/markdown/parse.rs +++ b/compiler/rustc_errors/src/markdown/parse.rs @@ -1,6 +1,7 @@ -use crate::markdown::{MdStream, MdTree}; use std::{iter, mem, str}; +use crate::markdown::{MdStream, MdTree}; + /// Short aliases that we can use in match patterns. If an end pattern is not /// included, this type may be variable const ANC_E: &[u8] = b">"; diff --git a/compiler/rustc_errors/src/markdown/tests/parse.rs b/compiler/rustc_errors/src/markdown/tests/parse.rs index e2e3f354ff6cb..bfcb3de16fa0e 100644 --- a/compiler/rustc_errors/src/markdown/tests/parse.rs +++ b/compiler/rustc_errors/src/markdown/tests/parse.rs @@ -1,6 +1,7 @@ -use super::*; use ParseOpt as PO; +use super::*; + #[test] fn test_parse_simple() { let buf = "**abcd** rest"; diff --git a/compiler/rustc_errors/src/markdown/tests/term.rs b/compiler/rustc_errors/src/markdown/tests/term.rs index bab47dcc175f1..e025870f055a0 100644 --- a/compiler/rustc_errors/src/markdown/tests/term.rs +++ b/compiler/rustc_errors/src/markdown/tests/term.rs @@ -1,5 +1,6 @@ use std::io::BufWriter; use std::path::PathBuf; + use termcolor::{BufferWriter, ColorChoice}; use super::*; diff --git a/compiler/rustc_errors/src/registry.rs b/compiler/rustc_errors/src/registry.rs index 8834d04d9718b..baca7700d90e2 100644 --- a/compiler/rustc_errors/src/registry.rs +++ b/compiler/rustc_errors/src/registry.rs @@ -1,6 +1,7 @@ -use crate::ErrCode; use rustc_data_structures::fx::FxHashMap; +use crate::ErrCode; + #[derive(Debug)] pub struct InvalidErrorCode; diff --git a/compiler/rustc_errors/src/snippet.rs b/compiler/rustc_errors/src/snippet.rs index d6119fb41d225..50abf8a49c268 100644 --- a/compiler/rustc_errors/src/snippet.rs +++ b/compiler/rustc_errors/src/snippet.rs @@ -1,8 +1,9 @@ // Code for annotating snippets. -use crate::{Level, Loc}; use rustc_macros::{Decodable, Encodable}; +use crate::{Level, Loc}; + #[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] pub struct Line { pub line_index: usize, diff --git a/compiler/rustc_errors/src/tests.rs b/compiler/rustc_errors/src/tests.rs index 50d58aec36a89..bfe4c9f2a3a2b 100644 --- a/compiler/rustc_errors/src/tests.rs +++ b/compiler/rustc_errors/src/tests.rs @@ -1,11 +1,11 @@ +use rustc_data_structures::sync::{IntoDynSyncSend, Lrc}; +use rustc_error_messages::fluent_bundle::resolver::errors::{ReferenceKind, ResolverError}; +use rustc_error_messages::{langid, DiagMessage}; + use crate::error::{TranslateError, TranslateErrorKind}; use crate::fluent_bundle::*; use crate::translation::Translate; use crate::FluentBundle; -use rustc_data_structures::sync::{IntoDynSyncSend, Lrc}; -use rustc_error_messages::fluent_bundle::resolver::errors::{ReferenceKind, ResolverError}; -use rustc_error_messages::langid; -use rustc_error_messages::DiagMessage; struct Dummy { bundle: FluentBundle, diff --git a/compiler/rustc_errors/src/translation.rs b/compiler/rustc_errors/src/translation.rs index 445e9b4fd6e04..a44e794ee12ce 100644 --- a/compiler/rustc_errors/src/translation.rs +++ b/compiler/rustc_errors/src/translation.rs @@ -1,13 +1,15 @@ -use crate::error::{TranslateError, TranslateErrorKind}; -use crate::snippet::Style; -use crate::{DiagArg, DiagMessage, FluentBundle}; -use rustc_data_structures::sync::Lrc; -pub use rustc_error_messages::FluentArgs; use std::borrow::Cow; use std::env; use std::error::Report; + +use rustc_data_structures::sync::Lrc; +pub use rustc_error_messages::FluentArgs; use tracing::{debug, trace}; +use crate::error::{TranslateError, TranslateErrorKind}; +use crate::snippet::Style; +use crate::{DiagArg, DiagMessage, FluentBundle}; + /// Convert diagnostic arguments (a rustc internal type that exists to implement /// `Encodable`/`Decodable`) into `FluentArgs` which is necessary to perform translation. /// diff --git a/compiler/rustc_expand/messages.ftl b/compiler/rustc_expand/messages.ftl index cc0b110d2bc6f..18d95a398fd4f 100644 --- a/compiler/rustc_expand/messages.ftl +++ b/compiler/rustc_expand/messages.ftl @@ -105,6 +105,11 @@ expand_meta_var_dif_seq_matchers = {$msg} expand_meta_var_expr_unrecognized_var = variable `{$key}` is not recognized in meta-variable expression +expand_missing_fragment_specifier = missing fragment specifier + .note = fragment specifiers must be specified in the 2024 edition + .suggestion_add_fragspec = try adding a specifier here + .valid = {$valid} + expand_module_circular = circular modules: {$modules} diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index b439ec74ffae7..c195d69258899 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1,7 +1,7 @@ -use crate::base::ast::NestedMetaItem; -use crate::errors; -use crate::expand::{self, AstFragment, Invocation}; -use crate::module::DirOwnership; +use std::default::Default; +use std::iter; +use std::path::{Path, PathBuf}; +use std::rc::Rc; use rustc_ast::attr::MarkedAttrs; use rustc_ast::ptr::P; @@ -15,9 +15,11 @@ use rustc_data_structures::sync::{self, Lrc}; use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, PResult}; use rustc_feature::Features; use rustc_lint_defs::{BufferedEarlyLint, RegisteredTools}; -use rustc_parse::{parser::Parser, MACRO_ARGUMENTS}; +use rustc_parse::parser::Parser; +use rustc_parse::MACRO_ARGUMENTS; use rustc_session::config::CollapseMacroDebuginfo; -use rustc_session::{parse::ParseSess, Limit, Session}; +use rustc_session::parse::ParseSess; +use rustc_session::{Limit, Session}; use rustc_span::def_id::{CrateNum, DefId, LocalDefId}; use rustc_span::edition::Edition; use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind}; @@ -25,12 +27,13 @@ use rustc_span::source_map::SourceMap; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{FileName, Span, DUMMY_SP}; use smallvec::{smallvec, SmallVec}; -use std::default::Default; -use std::iter; -use std::path::{Path, PathBuf}; -use std::rc::Rc; use thin_vec::ThinVec; +use crate::base::ast::NestedMetaItem; +use crate::errors; +use crate::expand::{self, AstFragment, Invocation}; +use crate::module::DirOwnership; + // When adding new variants, make sure to // adjust the `visit_*` / `flat_map_*` calls in `InvocationCollector` // to use `assign_id!` diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index 37dfd8305126a..8ecdb551342dd 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -1,12 +1,15 @@ -use crate::base::ExtCtxt; use rustc_ast::ptr::P; -use rustc_ast::{self as ast, AttrVec, BlockCheckMode, Expr, LocalKind, MatchKind, PatKind, UnOp}; -use rustc_ast::{attr, token, util::literal}; +use rustc_ast::util::literal; +use rustc_ast::{ + self as ast, attr, token, AttrVec, BlockCheckMode, Expr, LocalKind, MatchKind, PatKind, UnOp, +}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; use thin_vec::{thin_vec, ThinVec}; +use crate::base::ExtCtxt; + impl<'a> ExtCtxt<'a> { pub fn path(&self, span: Span, strs: Vec) -> ast::Path { self.path_all(span, false, strs, vec![]) diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 9da4aa84db525..f6bf9f5e89f2f 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -1,19 +1,16 @@ //! Conditional compilation stripping. -use crate::errors::{ - FeatureNotAllowed, FeatureRemoved, FeatureRemovedReason, InvalidCfg, MalformedFeatureAttribute, - MalformedFeatureAttributeHelp, RemoveExprNotSupported, -}; use rustc_ast::ptr::P; use rustc_ast::token::{Delimiter, Token, TokenKind}; -use rustc_ast::tokenstream::{AttrTokenStream, AttrTokenTree, DelimSpacing, DelimSpan, Spacing}; -use rustc_ast::tokenstream::{LazyAttrTokenStream, TokenTree}; -use rustc_ast::NodeId; -use rustc_ast::{self as ast, AttrStyle, Attribute, HasAttrs, HasTokens, MetaItem}; +use rustc_ast::tokenstream::{ + AttrTokenStream, AttrTokenTree, LazyAttrTokenStream, Spacing, TokenTree, +}; +use rustc_ast::{self as ast, AttrStyle, Attribute, HasAttrs, HasTokens, MetaItem, NodeId}; use rustc_attr as attr; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; -use rustc_feature::Features; -use rustc_feature::{ACCEPTED_FEATURES, REMOVED_FEATURES, UNSTABLE_FEATURES}; +use rustc_feature::{ + AttributeSafety, Features, ACCEPTED_FEATURES, REMOVED_FEATURES, UNSTABLE_FEATURES, +}; use rustc_lint_defs::BuiltinLintDiag; use rustc_parse::validate_attr; use rustc_session::parse::feature_err; @@ -23,6 +20,11 @@ use rustc_span::Span; use thin_vec::ThinVec; use tracing::instrument; +use crate::errors::{ + FeatureNotAllowed, FeatureRemoved, FeatureRemovedReason, InvalidCfg, MalformedFeatureAttribute, + MalformedFeatureAttributeHelp, RemoveExprNotSupported, +}; + /// A folder that strips out items that do not belong in the current configuration. pub struct StripUnconfigured<'a> { pub sess: &'a Session, @@ -117,6 +119,12 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - // Otherwise, the feature is unknown. Record it as a lib feature. // It will be checked later. features.set_declared_lib_feature(name, mi.span()); + + // Similar to above, detect internal lib features to suppress + // the ICE message that asks for a report. + if features.internal(name) && ![sym::core, sym::alloc, sym::std].contains(&crate_name) { + sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed); + } } } @@ -257,6 +265,13 @@ impl<'a> StripUnconfigured<'a> { /// is in the original source file. Gives a compiler error if the syntax of /// the attribute is incorrect. pub(crate) fn expand_cfg_attr(&self, cfg_attr: &Attribute, recursive: bool) -> Vec { + validate_attr::check_attribute_safety( + self.features.unwrap_or(&Features::default()), + &self.sess.psess, + AttributeSafety::Normal, + &cfg_attr, + ); + let Some((cfg_predicate, expanded_attrs)) = rustc_parse::parse_cfg_attr(cfg_attr, &self.sess.psess) else { @@ -298,47 +313,47 @@ impl<'a> StripUnconfigured<'a> { cfg_attr: &Attribute, (item, item_span): (ast::AttrItem, Span), ) -> Attribute { - // We are taking an attribute of the form `#[cfg_attr(pred, attr)]` - // and producing an attribute of the form `#[attr]`. We - // have captured tokens for `attr` itself, but we need to - // synthesize tokens for the wrapper `#` and `[]`, which - // we do below. - - // Use the `#` in `#[cfg_attr(pred, attr)]` as the `#` token - // for `attr` when we expand it to `#[attr]` + // Convert `#[cfg_attr(pred, attr)]` to `#[attr]`. + + // Use the `#` from `#[cfg_attr(pred, attr)]` in the result `#[attr]`. let mut orig_trees = cfg_attr.token_trees().into_iter(); - let TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _) = - orig_trees.next().unwrap().clone() + let Some(TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _)) = + orig_trees.next() else { panic!("Bad tokens for attribute {cfg_attr:?}"); }; - // We don't really have a good span to use for the synthesized `[]` - // in `#[attr]`, so just use the span of the `#` token. - let bracket_group = AttrTokenTree::Delimited( - DelimSpan::from_single(pound_token.span), - DelimSpacing::new(Spacing::JointHidden, Spacing::Alone), - Delimiter::Bracket, - item.tokens - .as_ref() - .unwrap_or_else(|| panic!("Missing tokens for {item:?}")) - .to_attr_token_stream(), - ); - let trees = if cfg_attr.style == AttrStyle::Inner { - // For inner attributes, we do the same thing for the `!` in `#![some_attr]` - let TokenTree::Token(bang_token @ Token { kind: TokenKind::Not, .. }, _) = - orig_trees.next().unwrap().clone() + // For inner attributes, we do the same thing for the `!` in `#![attr]`. + let mut trees = if cfg_attr.style == AttrStyle::Inner { + let Some(TokenTree::Token(bang_token @ Token { kind: TokenKind::Not, .. }, _)) = + orig_trees.next() else { panic!("Bad tokens for attribute {cfg_attr:?}"); }; vec![ AttrTokenTree::Token(pound_token, Spacing::Joint), AttrTokenTree::Token(bang_token, Spacing::JointHidden), - bracket_group, ] } else { - vec![AttrTokenTree::Token(pound_token, Spacing::JointHidden), bracket_group] + vec![AttrTokenTree::Token(pound_token, Spacing::JointHidden)] }; + + // And the same thing for the `[`/`]` delimiters in `#[attr]`. + let Some(TokenTree::Delimited(delim_span, delim_spacing, Delimiter::Bracket, _)) = + orig_trees.next() + else { + panic!("Bad tokens for attribute {cfg_attr:?}"); + }; + trees.push(AttrTokenTree::Delimited( + delim_span, + delim_spacing, + Delimiter::Bracket, + item.tokens + .as_ref() + .unwrap_or_else(|| panic!("Missing tokens for {item:?}")) + .to_attr_token_stream(), + )); + let tokens = Some(LazyAttrTokenStream::new(AttrTokenStream::new(trees))); let attr = attr::mk_attr_from_item( &self.sess.psess.attr_id_generator, @@ -379,6 +394,13 @@ impl<'a> StripUnconfigured<'a> { return (true, None); } }; + + validate_attr::deny_builtin_meta_unsafety( + self.features.unwrap_or(&Features::default()), + &self.sess.psess, + &meta_item, + ); + ( parse_cfg(&meta_item, self.sess).map_or(true, |meta_item| { attr::cfg_matches(meta_item, &self.sess, self.lint_node_id, self.features) diff --git a/compiler/rustc_expand/src/errors.rs b/compiler/rustc_expand/src/errors.rs index 0be7403f25b17..c30a9b0c3576d 100644 --- a/compiler/rustc_expand/src/errors.rs +++ b/compiler/rustc_expand/src/errors.rs @@ -1,10 +1,11 @@ +use std::borrow::Cow; + use rustc_ast::ast; use rustc_errors::codes::*; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_session::Limit; use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent}; use rustc_span::{Span, Symbol}; -use std::borrow::Cow; #[derive(Diagnostic)] #[diag(expand_expr_repeat_no_syntax_vars)] @@ -416,6 +417,23 @@ pub struct DuplicateMatcherBinding { pub prev: Span, } +#[derive(Diagnostic)] +#[diag(expand_missing_fragment_specifier)] +#[note] +#[help(expand_valid)] +pub struct MissingFragmentSpecifier { + #[primary_span] + pub span: Span, + #[suggestion( + expand_suggestion_add_fragspec, + style = "verbose", + code = ":spec", + applicability = "maybe-incorrect" + )] + pub add_span: Span, + pub valid: &'static str, +} + #[derive(Diagnostic)] #[diag(expand_invalid_fragment_specifier)] #[help] diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 3c43d47292fb2..d8cb367e3face 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -1,13 +1,7 @@ -use crate::base::*; -use crate::config::StripUnconfigured; -use crate::errors::{ - EmptyDelegationMac, GlobDelegationOutsideImpls, GlobDelegationTraitlessQpath, IncompleteParse, - RecursionLimitReached, RemoveExprNotSupported, RemoveNodeNotSupported, UnsupportedKeyValue, - WrongFragmentKind, -}; -use crate::mbe::diagnostics::annotate_err_with_kind; -use crate::module::{mod_dir_path, parse_external_mod, DirOwnership, ParsedExternalMod}; -use crate::placeholders::{placeholder, PlaceholderExpander}; +use std::ops::Deref; +use std::path::PathBuf; +use std::rc::Rc; +use std::{iter, mem}; use rustc_ast as ast; use rustc_ast::mut_visit::*; @@ -15,10 +9,11 @@ use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter}; use rustc_ast::tokenstream::TokenStream; use rustc_ast::visit::{self, try_visit, walk_list, AssocCtxt, Visitor, VisitorResult}; -use rustc_ast::{AssocItemKind, AstNodeWrapper, AttrArgs, AttrStyle, AttrVec, ExprKind}; -use rustc_ast::{ForeignItemKind, HasAttrs, HasNodeId}; -use rustc_ast::{Inline, ItemKind, MacStmtStyle, MetaItemKind, ModKind}; -use rustc_ast::{NestedMetaItem, NodeId, PatKind, StmtKind, TyKind}; +use rustc_ast::{ + AssocItemKind, AstNodeWrapper, AttrArgs, AttrStyle, AttrVec, ExprKind, ForeignItemKind, + HasAttrs, HasNodeId, Inline, ItemKind, MacStmtStyle, MetaItemKind, ModKind, NestedMetaItem, + NodeId, PatKind, StmtKind, TyKind, +}; use rustc_ast_pretty::pprust; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_data_structures::sync::Lrc; @@ -35,12 +30,18 @@ use rustc_session::{Limit, Session}; use rustc_span::hygiene::SyntaxContext; use rustc_span::symbol::{sym, Ident}; use rustc_span::{ErrorGuaranteed, FileName, LocalExpnId, Span}; - use smallvec::SmallVec; -use std::ops::Deref; -use std::path::PathBuf; -use std::rc::Rc; -use std::{iter, mem}; + +use crate::base::*; +use crate::config::StripUnconfigured; +use crate::errors::{ + EmptyDelegationMac, GlobDelegationOutsideImpls, GlobDelegationTraitlessQpath, IncompleteParse, + RecursionLimitReached, RemoveExprNotSupported, RemoveNodeNotSupported, UnsupportedKeyValue, + WrongFragmentKind, +}; +use crate::mbe::diagnostics::annotate_err_with_kind; +use crate::module::{mod_dir_path, parse_external_mod, DirOwnership, ParsedExternalMod}; +use crate::placeholders::{placeholder, PlaceholderExpander}; macro_rules! ast_fragments { ( diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index 2df8b8f00f862..6ce9ff18c279f 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -1,9 +1,5 @@ -use crate::base::{DummyResult, ExtCtxt, MacResult}; -use crate::expand::{parse_ast_fragment, AstFragmentKind}; -use crate::mbe::{ - macro_parser::{MatcherLoc, NamedParseResult, ParseResult::*, TtParser}, - macro_rules::{try_match_macro, Tracker}, -}; +use std::borrow::Cow; + use rustc_ast::token::{self, Token, TokenKind}; use rustc_ast::tokenstream::TokenStream; use rustc_ast_pretty::pprust; @@ -13,10 +9,14 @@ use rustc_parse::parser::{Parser, Recovery}; use rustc_span::source_map::SourceMap; use rustc_span::symbol::Ident; use rustc_span::{ErrorGuaranteed, Span}; -use std::borrow::Cow; use tracing::debug; use super::macro_rules::{parser_from_cx, NoopTracker}; +use crate::base::{DummyResult, ExtCtxt, MacResult}; +use crate::expand::{parse_ast_fragment, AstFragmentKind}; +use crate::mbe::macro_parser::ParseResult::*; +use crate::mbe::macro_parser::{MatcherLoc, NamedParseResult, TtParser}; +use crate::mbe::macro_rules::{try_match_macro, Tracker}; pub(super) fn failed_to_match_macro<'cx>( cx: &'cx mut ExtCtxt<'_>, diff --git a/compiler/rustc_expand/src/mbe/macro_check.rs b/compiler/rustc_expand/src/mbe/macro_check.rs index 4b730d307fd6c..68eeba6f415d5 100644 --- a/compiler/rustc_expand/src/mbe/macro_check.rs +++ b/compiler/rustc_expand/src/mbe/macro_check.rs @@ -105,8 +105,7 @@ //! stored when entering a macro definition starting from the state in which the meta-variable is //! bound. -use crate::errors; -use crate::mbe::{KleeneToken, TokenTree}; +use std::iter; use rustc_ast::token::{Delimiter, IdentIsRaw, Token, TokenKind}; use rustc_ast::{NodeId, DUMMY_NODE_ID}; @@ -115,12 +114,14 @@ use rustc_errors::MultiSpan; use rustc_lint_defs::BuiltinLintDiag; use rustc_session::lint::builtin::{META_VARIABLE_MISUSE, MISSING_FRAGMENT_SPECIFIER}; use rustc_session::parse::ParseSess; -use rustc_span::symbol::kw; -use rustc_span::{symbol::MacroRulesNormalizedIdent, ErrorGuaranteed, Span}; - +use rustc_span::edition::Edition; +use rustc_span::symbol::{kw, MacroRulesNormalizedIdent}; +use rustc_span::{ErrorGuaranteed, Span}; use smallvec::SmallVec; -use std::iter; +use super::quoted::VALID_FRAGMENT_NAMES_MSG_2021; +use crate::errors; +use crate::mbe::{KleeneToken, TokenTree}; /// Stack represented as linked list. /// @@ -269,12 +270,20 @@ fn check_binders( // FIXME: Report this as a hard error eventually and remove equivalent errors from // `parse_tt_inner` and `nameize`. Until then the error may be reported twice, once // as a hard error and then once as a buffered lint. - psess.buffer_lint( - MISSING_FRAGMENT_SPECIFIER, - span, - node_id, - BuiltinLintDiag::MissingFragmentSpecifier, - ); + if span.edition() >= Edition::Edition2024 { + psess.dcx().emit_err(errors::MissingFragmentSpecifier { + span, + add_span: span.shrink_to_hi(), + valid: VALID_FRAGMENT_NAMES_MSG_2021, + }); + } else { + psess.buffer_lint( + MISSING_FRAGMENT_SPECIFIER, + span, + node_id, + BuiltinLintDiag::MissingFragmentSpecifier, + ); + } } if !macros.is_empty() { psess.dcx().span_bug(span, "unexpected MetaVarDecl in nested lhs"); diff --git a/compiler/rustc_expand/src/mbe/macro_parser.rs b/compiler/rustc_expand/src/mbe/macro_parser.rs index 99a9d4f8912cd..e5b9c62742967 100644 --- a/compiler/rustc_expand/src/mbe/macro_parser.rs +++ b/compiler/rustc_expand/src/mbe/macro_parser.rs @@ -70,10 +70,10 @@ //! eof: [a $( a )* a b ·] //! ``` -pub(crate) use NamedMatch::*; -pub(crate) use ParseResult::*; - -use crate::mbe::{macro_rules::Tracker, KleeneOp, TokenTree}; +use std::borrow::Cow; +use std::collections::hash_map::Entry::{Occupied, Vacant}; +use std::fmt::Display; +use std::rc::Rc; use rustc_ast::token::{self, DocComment, NonterminalKind, Token}; use rustc_ast_pretty::pprust; @@ -81,13 +81,13 @@ use rustc_data_structures::fx::FxHashMap; use rustc_errors::ErrorGuaranteed; use rustc_lint_defs::pluralize; use rustc_parse::parser::{ParseNtResult, Parser}; -use rustc_span::symbol::Ident; -use rustc_span::symbol::MacroRulesNormalizedIdent; +use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent}; use rustc_span::Span; -use std::borrow::Cow; -use std::collections::hash_map::Entry::{Occupied, Vacant}; -use std::fmt::Display; -use std::rc::Rc; +pub(crate) use NamedMatch::*; +pub(crate) use ParseResult::*; + +use crate::mbe::macro_rules::Tracker; +use crate::mbe::{KleeneOp, TokenTree}; /// A unit within a matcher that a `MatcherPos` can refer to. Similar to (and derived from) /// `mbe::TokenTree`, but designed specifically for fast and easy traversal during matching. diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 88ec3d8366429..1502177563d9b 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -1,18 +1,12 @@ -use crate::base::{DummyResult, SyntaxExtension, SyntaxExtensionKind}; -use crate::base::{ExpandResult, ExtCtxt, MacResult, MacroExpanderResult, TTMacroExpander}; -use crate::expand::{ensure_complete_parse, parse_ast_fragment, AstFragment, AstFragmentKind}; -use crate::mbe; -use crate::mbe::diagnostics::{annotate_doc_comment, parse_failure_msg}; -use crate::mbe::macro_check; -use crate::mbe::macro_parser::{Error, ErrorReported, Failure, Success, TtParser}; -use crate::mbe::macro_parser::{MatcherLoc, NamedMatch::*}; -use crate::mbe::transcribe::transcribe; +use std::borrow::Cow; +use std::collections::hash_map::Entry; +use std::{mem, slice}; use ast::token::IdentIsRaw; use rustc_ast as ast; -use rustc_ast::token::{ - self, Delimiter, NonterminalKind, NtPatKind::*, Token, TokenKind, TokenKind::*, -}; +use rustc_ast::token::NtPatKind::*; +use rustc_ast::token::TokenKind::*; +use rustc_ast::token::{self, Delimiter, NonterminalKind, Token, TokenKind}; use rustc_ast::tokenstream::{DelimSpan, TokenStream}; use rustc_ast::{NodeId, DUMMY_NODE_ID}; use rustc_ast_pretty::pprust; @@ -33,12 +27,19 @@ use rustc_span::symbol::{kw, sym, Ident, MacroRulesNormalizedIdent}; use rustc_span::Span; use tracing::{debug, instrument, trace, trace_span}; -use std::borrow::Cow; -use std::collections::hash_map::Entry; -use std::{mem, slice}; - use super::diagnostics; use super::macro_parser::{NamedMatches, NamedParseResult}; +use crate::base::{ + DummyResult, ExpandResult, ExtCtxt, MacResult, MacroExpanderResult, SyntaxExtension, + SyntaxExtensionKind, TTMacroExpander, +}; +use crate::expand::{ensure_complete_parse, parse_ast_fragment, AstFragment, AstFragmentKind}; +use crate::mbe; +use crate::mbe::diagnostics::{annotate_doc_comment, parse_failure_msg}; +use crate::mbe::macro_check; +use crate::mbe::macro_parser::NamedMatch::*; +use crate::mbe::macro_parser::{Error, ErrorReported, Failure, MatcherLoc, Success, TtParser}; +use crate::mbe::transcribe::transcribe; pub(crate) struct ParserAnyMacro<'a> { parser: Parser<'a>, diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index 9c480f17b4215..e5a1c6c789928 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -1,22 +1,22 @@ -use crate::errors; -use crate::mbe::macro_parser::count_metavar_decls; -use crate::mbe::{Delimited, KleeneOp, KleeneToken, MetaVarExpr, SequenceRepetition, TokenTree}; - -use rustc_ast::token::{self, Delimiter, IdentIsRaw, NonterminalKind, NtExprKind::*, Token}; +use rustc_ast::token::NtExprKind::*; +use rustc_ast::token::{self, Delimiter, IdentIsRaw, NonterminalKind, Token}; use rustc_ast::{tokenstream, NodeId}; use rustc_ast_pretty::pprust; use rustc_feature::Features; use rustc_session::parse::feature_err; use rustc_session::Session; -use rustc_span::symbol::{kw, sym, Ident}; - use rustc_span::edition::Edition; +use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; +use crate::errors; +use crate::mbe::macro_parser::count_metavar_decls; +use crate::mbe::{Delimited, KleeneOp, KleeneToken, MetaVarExpr, SequenceRepetition, TokenTree}; + const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \ `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, \ `literal`, `path`, `meta`, `tt`, `item` and `vis`"; -const VALID_FRAGMENT_NAMES_MSG_2021: &str = "valid fragment specifiers are \ +pub const VALID_FRAGMENT_NAMES_MSG_2021: &str = "valid fragment specifiers are \ `ident`, `block`, `stmt`, `expr`, `expr_2021`, `pat`, \ `ty`, `lifetime`, `literal`, `path`, `meta`, `tt`, \ `item` and `vis`"; diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index 0da542d379d2d..b06910595bb25 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -1,26 +1,27 @@ -use crate::errors::{ - CountRepetitionMisplaced, MetaVarExprUnrecognizedVar, MetaVarsDifSeqMatchers, MustRepeatOnce, - NoSyntaxVarsExprRepeat, VarStillRepeating, -}; -use crate::mbe::macro_parser::{NamedMatch, NamedMatch::*}; -use crate::mbe::metavar_expr::{MetaVarExprConcatElem, RAW_IDENT_ERR}; -use crate::mbe::{self, KleeneOp, MetaVarExpr}; +use std::mem; + use rustc_ast::mut_visit::{self, MutVisitor}; -use rustc_ast::token::{self, Delimiter, Nonterminal, Token, TokenKind}; -use rustc_ast::token::{IdentIsRaw, Lit, LitKind}; +use rustc_ast::token::{self, Delimiter, IdentIsRaw, Lit, LitKind, Nonterminal, Token, TokenKind}; use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; use rustc_ast::ExprKind; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{pluralize, Diag, DiagCtxtHandle, PResult}; use rustc_parse::lexer::nfc_normalize; use rustc_parse::parser::ParseNtResult; -use rustc_session::parse::ParseSess; -use rustc_session::parse::SymbolGallery; +use rustc_session::parse::{ParseSess, SymbolGallery}; use rustc_span::hygiene::{LocalExpnId, Transparency}; use rustc_span::symbol::{sym, Ident, MacroRulesNormalizedIdent}; use rustc_span::{with_metavar_spans, Span, Symbol, SyntaxContext}; use smallvec::{smallvec, SmallVec}; -use std::mem; + +use crate::errors::{ + CountRepetitionMisplaced, MetaVarExprUnrecognizedVar, MetaVarsDifSeqMatchers, MustRepeatOnce, + NoSyntaxVarsExprRepeat, VarStillRepeating, +}; +use crate::mbe::macro_parser::NamedMatch; +use crate::mbe::macro_parser::NamedMatch::*; +use crate::mbe::metavar_expr::{MetaVarExprConcatElem, RAW_IDENT_ERR}; +use crate::mbe::{self, KleeneOp, MetaVarExpr}; // A Marker adds the given mark to the syntax context. struct Marker(LocalExpnId, Transparency, FxHashMap); diff --git a/compiler/rustc_expand/src/module.rs b/compiler/rustc_expand/src/module.rs index 506bd445be35f..133483768511b 100644 --- a/compiler/rustc_expand/src/module.rs +++ b/compiler/rustc_expand/src/module.rs @@ -1,20 +1,21 @@ -use crate::base::ModuleData; -use crate::errors::{ - ModuleCircular, ModuleFileNotFound, ModuleInBlock, ModuleInBlockName, ModuleMultipleCandidates, -}; +use std::iter::once; +use std::path::{self, Path, PathBuf}; + use rustc_ast::ptr::P; use rustc_ast::{token, AttrVec, Attribute, Inline, Item, ModSpans}; use rustc_errors::{Diag, ErrorGuaranteed}; -use rustc_parse::validate_attr; -use rustc_parse::{new_parser_from_file, unwrap_or_emit_fatal}; +use rustc_parse::{new_parser_from_file, unwrap_or_emit_fatal, validate_attr}; use rustc_session::parse::ParseSess; use rustc_session::Session; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; -use std::iter::once; -use std::path::{self, Path, PathBuf}; use thin_vec::ThinVec; +use crate::base::ModuleData; +use crate::errors::{ + ModuleCircular, ModuleFileNotFound, ModuleInBlock, ModuleInBlockName, ModuleMultipleCandidates, +}; + #[derive(Copy, Clone)] pub enum DirOwnership { Owned { diff --git a/compiler/rustc_expand/src/placeholders.rs b/compiler/rustc_expand/src/placeholders.rs index 3fa909877cc76..1e455d465e4d1 100644 --- a/compiler/rustc_expand/src/placeholders.rs +++ b/compiler/rustc_expand/src/placeholders.rs @@ -1,14 +1,16 @@ -use crate::expand::{AstFragment, AstFragmentKind}; use rustc_ast::mut_visit::*; use rustc_ast::ptr::P; use rustc_ast::token::Delimiter; -use rustc_ast::{self as ast, visit::AssocCtxt}; +use rustc_ast::visit::AssocCtxt; +use rustc_ast::{self as ast}; use rustc_data_structures::fx::FxHashMap; use rustc_span::symbol::Ident; use rustc_span::DUMMY_SP; use smallvec::{smallvec, SmallVec}; use thin_vec::ThinVec; +use crate::expand::{AstFragment, AstFragmentKind}; + pub(crate) fn placeholder( kind: AstFragmentKind, id: ast::NodeId, diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 96145affe0ae8..24f631ed5dc98 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -1,7 +1,3 @@ -use crate::base::{self, *}; -use crate::errors; -use crate::proc_macro_server; - use rustc_ast as ast; use rustc_ast::ptr::P; use rustc_ast::tokenstream::TokenStream; @@ -11,6 +7,9 @@ use rustc_session::config::ProcMacroExecutionStrategy; use rustc_span::profiling::SpannedEventArgRecorder; use rustc_span::Span; +use crate::base::{self, *}; +use crate::{errors, proc_macro_server}; + struct MessagePipe { tx: std::sync::mpsc::SyncSender, rx: std::sync::mpsc::Receiver, diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index 5508358f53bb2..1438d1ad11f57 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -1,4 +1,5 @@ -use crate::base::ExtCtxt; +use std::ops::{Bound, Range}; + use ast::token::IdentIsRaw; use pm::bridge::{ server, DelimSpan, Diagnostic, ExpnGlobals, Group, Ident, LitKind, Literal, Punct, TokenTree, @@ -20,7 +21,8 @@ use rustc_span::def_id::CrateNum; use rustc_span::symbol::{self, sym, Symbol}; use rustc_span::{BytePos, FileName, Pos, SourceFile, Span}; use smallvec::{smallvec, SmallVec}; -use std::ops::{Bound, Range}; + +use crate::base::ExtCtxt; trait FromInternal { fn from_internal(x: T) -> Self; diff --git a/compiler/rustc_feature/src/accepted.rs b/compiler/rustc_feature/src/accepted.rs index e671c7682391e..e42a655531b5d 100644 --- a/compiler/rustc_feature/src/accepted.rs +++ b/compiler/rustc_feature/src/accepted.rs @@ -1,8 +1,9 @@ //! List of the accepted feature gates. -use super::{to_nonzero, Feature}; use rustc_span::symbol::sym; +use super::{to_nonzero, Feature}; + macro_rules! declare_features { ($( $(#[doc = $doc:tt])* (accepted, $feature:ident, $ver:expr, $issue:expr), @@ -85,7 +86,7 @@ declare_features! ( /// Allows `c"foo"` literals. (accepted, c_str_literals, "1.77.0", Some(105723)), /// Allows `extern "C-unwind" fn` to enable unwinding across ABI boundaries and treat `extern "C" fn` as nounwind. - (accepted, c_unwind, "CURRENT_RUSTC_VERSION", Some(74990)), + (accepted, c_unwind, "1.81.0", Some(74990)), /// Allows `#[cfg_attr(predicate, multiple, attributes, here)]`. (accepted, cfg_attr_multi, "1.33.0", Some(54881)), /// Allows the use of `#[cfg(doctest)]`, set when rustdoc is collecting doctests. @@ -237,7 +238,7 @@ declare_features! ( /// Allows `let...else` statements. (accepted, let_else, "1.65.0", Some(87335)), /// Allows using `reason` in lint attributes and the `#[expect(lint)]` lint check. - (accepted, lint_reasons, "CURRENT_RUSTC_VERSION", Some(54503)), + (accepted, lint_reasons, "1.81.0", Some(54503)), /// Allows `break {expr}` with a value inside `loop`s. (accepted, loop_break_value, "1.19.0", Some(37339)), /// Allows use of `?` as the Kleene "at most one" operator in macros. @@ -291,6 +292,8 @@ declare_features! ( (accepted, non_exhaustive, "1.40.0", Some(44109)), /// Allows `foo.rs` as an alternative to `foo/mod.rs`. (accepted, non_modrs_mods, "1.30.0", Some(44660)), + /// Allows using multiple nested field accesses in offset_of! + (accepted, offset_of_nested, "CURRENT_RUSTC_VERSION", Some(120140)), /// Allows the use of or-patterns (e.g., `0 | 1`). (accepted, or_patterns, "1.53.0", Some(54883)), /// Allows using `+bundle,+whole-archive` link modifiers with native libs. @@ -387,6 +390,8 @@ declare_features! ( (accepted, unrestricted_attribute_tokens, "1.34.0", Some(55208)), /// The `unsafe_op_in_unsafe_fn` lint (allowed by default): no longer treat an unsafe function as an unsafe block. (accepted, unsafe_block_in_unsafe_fn, "1.52.0", Some(71668)), + /// Allows unsafe on extern declarations and safety qualifiers over internal items. + (accepted, unsafe_extern_blocks, "CURRENT_RUSTC_VERSION", Some(123743)), /// Allows importing and reexporting macros with `use`, /// enables macro modularization in general. (accepted, use_extern_macros, "1.30.0", Some(35896)), diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 7b27049a579a1..72ea55d5999a2 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -1,16 +1,15 @@ //! Built-in attributes and `cfg` flag gating. +use std::sync::LazyLock; + +use rustc_data_structures::fx::FxHashMap; +use rustc_span::symbol::{sym, Symbol}; use AttributeDuplicates::*; use AttributeGate::*; use AttributeType::*; use crate::{Features, Stability}; -use rustc_data_structures::fx::FxHashMap; -use rustc_span::symbol::{sym, Symbol}; - -use std::sync::LazyLock; - type GateFn = fn(&Features) -> bool; macro_rules! cfg_fn { @@ -704,21 +703,21 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ EncodeCrossCrate::No, allocator_internals, experimental!(needs_allocator), ), gated!( - panic_runtime, Normal, template!(Word), WarnFollowing, + panic_runtime, CrateLevel, template!(Word), WarnFollowing, EncodeCrossCrate::No, experimental!(panic_runtime) ), gated!( - needs_panic_runtime, Normal, template!(Word), WarnFollowing, + needs_panic_runtime, CrateLevel, template!(Word), WarnFollowing, EncodeCrossCrate::No, experimental!(needs_panic_runtime) ), gated!( - compiler_builtins, Normal, template!(Word), WarnFollowing, + compiler_builtins, CrateLevel, template!(Word), WarnFollowing, EncodeCrossCrate::No, "the `#[compiler_builtins]` attribute is used to identify the `compiler_builtins` crate \ which contains compiler-rt intrinsics and will never be stable", ), gated!( - profiler_runtime, Normal, template!(Word), WarnFollowing, + profiler_runtime, CrateLevel, template!(Word), WarnFollowing, EncodeCrossCrate::No, "the `#[profiler_runtime]` attribute is used to identify the `profiler_builtins` crate \ which contains the profiler runtime and will never be stable", diff --git a/compiler/rustc_feature/src/lib.rs b/compiler/rustc_feature/src/lib.rs index e9d3ce0a07494..dcc1c3202ea28 100644 --- a/compiler/rustc_feature/src/lib.rs +++ b/compiler/rustc_feature/src/lib.rs @@ -25,9 +25,10 @@ mod unstable; #[cfg(test)] mod tests; -use rustc_span::symbol::Symbol; use std::num::NonZero; +use rustc_span::symbol::Symbol; + #[derive(Debug, Clone)] pub struct Feature { pub name: Symbol, @@ -126,11 +127,10 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option, @@ -81,6 +82,9 @@ declare_features! ( /// Allows the use of `#[derive(Anything)]` as sugar for `#[derive_Anything]`. (removed, custom_derive, "1.32.0", Some(29644), Some("subsumed by `#[proc_macro_derive]`")), + /// Allows default type parameters to influence type inference. + (removed, default_type_parameter_fallback, "CURRENT_RUSTC_VERSION", Some(27336), + Some("never properly implemented; requires significant design work")), /// Allows using `#[doc(keyword = "...")]`. (removed, doc_keyword, "1.28.0", Some(51315), Some("merged into `#![feature(rustdoc_internals)]`")), @@ -222,7 +226,7 @@ declare_features! ( (removed, unwind_attributes, "1.56.0", Some(58760), Some("use the C-unwind ABI instead")), (removed, visible_private_types, "1.0.0", None, None), /// Allows `extern "wasm" fn` - (removed, wasm_abi, "CURRENT_RUSTC_VERSION", Some(83788), + (removed, wasm_abi, "1.81.0", Some(83788), Some("non-standard wasm ABI is no longer supported")), // !!!! !!!! !!!! !!!! !!!! !!!! !!!! !!!! !!!! !!!! !!!! // Features are listed in alphabetical order. Tidy will fail if you don't keep it this way. diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 9b5ed3b0876a5..88a4b5a838246 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -1,11 +1,11 @@ //! List of the unstable feature gates. -use super::{to_nonzero, Feature}; - use rustc_data_structures::fx::FxHashSet; use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use super::{to_nonzero, Feature}; + pub struct UnstableFeature { pub feature: Feature, pub set_enabled: fn(&mut Features), @@ -205,6 +205,8 @@ declare_features! ( (unstable, lifetime_capture_rules_2024, "1.76.0", None), /// Allows `#[link(..., cfg(..))]`; perma-unstable per #37406 (unstable, link_cfg, "1.14.0", None), + /// Allows using `?Trait` trait bounds in more contexts. + (internal, more_maybe_bounds, "CURRENT_RUSTC_VERSION", None), /// Allows the `multiple_supertrait_upcastable` lint. (unstable, multiple_supertrait_upcastable, "1.69.0", None), /// Allow negative trait bounds. This is an internal-only feature for testing the trait solver! @@ -429,8 +431,6 @@ declare_features! ( (unstable, custom_test_frameworks, "1.30.0", Some(50297)), /// Allows declarative macros 2.0 (`macro`). (unstable, decl_macro, "1.17.0", Some(39412)), - /// Allows default type parameters to influence type inference. - (unstable, default_type_parameter_fallback, "1.3.0", Some(27336)), /// Allows using `#[deprecated_safe]` to deprecate the safeness of a function or trait (unstable, deprecated_safe, "1.61.0", Some(94978)), /// Allows having using `suggestion` in the `#[deprecated]` attribute. @@ -516,7 +516,7 @@ declare_features! ( /// Give access to additional metadata about declarative macro meta-variables. (unstable, macro_metavar_expr, "1.61.0", Some(83527)), /// Provides a way to concatenate identifiers using metavariable expressions. - (unstable, macro_metavar_expr_concat, "CURRENT_RUSTC_VERSION", Some(124225)), + (unstable, macro_metavar_expr_concat, "1.81.0", Some(124225)), /// Allows `#[marker]` on certain traits allowing overlapping implementations. (unstable, marker_trait_attr, "1.30.0", Some(29864)), /// Allows exhaustive pattern matching on types that contain uninhabited types in cases that are @@ -558,14 +558,12 @@ declare_features! ( (unstable, object_safe_for_dispatch, "1.40.0", Some(43561)), /// Allows using enums in offset_of! (unstable, offset_of_enum, "1.75.0", Some(120141)), - /// Allows using multiple nested field accesses in offset_of! - (unstable, offset_of_nested, "1.77.0", Some(120140)), /// Allows using fields with slice type in offset_of! - (unstable, offset_of_slice, "CURRENT_RUSTC_VERSION", Some(126151)), + (unstable, offset_of_slice, "1.81.0", Some(126151)), /// Allows using `#[optimize(X)]`. (unstable, optimize_attribute, "1.34.0", Some(54882)), /// Allows specifying nop padding on functions for dynamic patching. - (unstable, patchable_function_entry, "CURRENT_RUSTC_VERSION", Some(123115)), + (unstable, patchable_function_entry, "1.81.0", Some(123115)), /// Allows postfix match `expr.match { ... }` (unstable, postfix_match, "1.79.0", Some(121618)), /// Allows `use<'a, 'b, A, B>` in `impl Trait + use<...>` for precise capture of generic args. @@ -577,7 +575,7 @@ declare_features! ( /// Makes `&` and `&mut` patterns eat only one layer of references in Rust 2024. (incomplete, ref_pat_eat_one_layer_2024, "1.79.0", Some(123076)), /// Makes `&` and `&mut` patterns eat only one layer of references in Rust 2024—structural variant - (incomplete, ref_pat_eat_one_layer_2024_structural, "CURRENT_RUSTC_VERSION", Some(123076)), + (incomplete, ref_pat_eat_one_layer_2024_structural, "1.81.0", Some(123076)), /// Allows using the `#[register_tool]` attribute. (unstable, register_tool, "1.41.0", Some(66079)), /// Allows the `#[repr(i128)]` attribute for enums. @@ -591,6 +589,8 @@ declare_features! ( (incomplete, return_type_notation, "1.70.0", Some(109417)), /// Allows `extern "rust-cold"`. (unstable, rust_cold_cc, "1.63.0", Some(97544)), + /// Allows use of x86 SHA512, SM3 and SM4 target-features and intrinsics + (unstable, sha512_sm_x86, "CURRENT_RUSTC_VERSION", Some(126624)), /// Shortern the tail expression lifetime (unstable, shorter_tail_lifetimes, "1.79.0", Some(123739)), /// Allows the use of SIMD types in functions declared in `extern` blocks. @@ -629,8 +629,6 @@ declare_features! ( (incomplete, unnamed_fields, "1.74.0", Some(49804)), /// Allows unsafe attributes. (unstable, unsafe_attributes, "1.80.0", Some(123757)), - /// Allows unsafe on extern declarations and safety qualifiers over internal items. - (unstable, unsafe_extern_blocks, "1.80.0", Some(123743)), /// Allows const generic parameters to be defined with types that /// are not `Sized`, e.g. `fn foo() {`. (incomplete, unsized_const_params, "CURRENT_RUSTC_VERSION", Some(95174)), @@ -643,9 +641,9 @@ declare_features! ( /// Allows using the `#[used(linker)]` (or `#[used(compiler)]`) attribute. (unstable, used_with_arg, "1.60.0", Some(93798)), /// Allows use of x86 `AMX` target-feature attributes and intrinsics - (unstable, x86_amx_intrinsics, "CURRENT_RUSTC_VERSION", Some(126622)), + (unstable, x86_amx_intrinsics, "1.81.0", Some(126622)), /// Allows use of the `xop` target-feature - (unstable, xop_target_feature, "CURRENT_RUSTC_VERSION", Some(127208)), + (unstable, xop_target_feature, "1.81.0", Some(127208)), /// Allows `do yeet` expressions (unstable, yeet_expr, "1.62.0", Some(96373)), // !!!! !!!! !!!! !!!! !!!! !!!! !!!! !!!! !!!! !!!! !!!! diff --git a/compiler/rustc_fluent_macro/src/fluent.rs b/compiler/rustc_fluent_macro/src/fluent.rs index 68fdabd3529a4..23795a96b923c 100644 --- a/compiler/rustc_fluent_macro/src/fluent.rs +++ b/compiler/rustc_fluent_macro/src/fluent.rs @@ -1,20 +1,16 @@ +use std::collections::{HashMap, HashSet}; +use std::fs::read_to_string; +use std::path::{Path, PathBuf}; + use annotate_snippets::{Annotation, AnnotationType, Renderer, Slice, Snippet, SourceAnnotation}; use fluent_bundle::{FluentBundle, FluentError, FluentResource}; -use fluent_syntax::{ - ast::{ - Attribute, Entry, Expression, Identifier, InlineExpression, Message, Pattern, - PatternElement, - }, - parser::ParserError, +use fluent_syntax::ast::{ + Attribute, Entry, Expression, Identifier, InlineExpression, Message, Pattern, PatternElement, }; +use fluent_syntax::parser::ParserError; use proc_macro::{Diagnostic, Level, Span}; use proc_macro2::TokenStream; use quote::quote; -use std::{ - collections::{HashMap, HashSet}, - fs::read_to_string, - path::{Path, PathBuf}, -}; use syn::{parse_macro_input, Ident, LitStr}; use unic_langid::langid; diff --git a/compiler/rustc_fs_util/src/lib.rs b/compiler/rustc_fs_util/src/lib.rs index d376c24cb589c..91eae98071a49 100644 --- a/compiler/rustc_fs_util/src/lib.rs +++ b/compiler/rustc_fs_util/src/lib.rs @@ -1,7 +1,6 @@ use std::ffi::CString; -use std::fs; -use std::io; use std::path::{absolute, Path, PathBuf}; +use std::{fs, io}; // Unfortunately, on windows, it looks like msvcrt.dll is silently translating // verbatim paths under the hood to non-verbatim paths! This manifests itself as diff --git a/compiler/rustc_graphviz/src/lib.rs b/compiler/rustc_graphviz/src/lib.rs index c0fe98254f087..c8f8fd5be0237 100644 --- a/compiler/rustc_graphviz/src/lib.rs +++ b/compiler/rustc_graphviz/src/lib.rs @@ -279,12 +279,12 @@ #![feature(rustdoc_internals)] // tidy-alphabetical-end -use LabelText::*; - use std::borrow::Cow; use std::io; use std::io::prelude::*; +use LabelText::*; + /// The text for a graphviz label on a node or edge. pub enum LabelText<'a> { /// This kind of label preserves the text directly as is. diff --git a/compiler/rustc_graphviz/src/tests.rs b/compiler/rustc_graphviz/src/tests.rs index 154bae4cb058b..01e6cb9a3daad 100644 --- a/compiler/rustc_graphviz/src/tests.rs +++ b/compiler/rustc_graphviz/src/tests.rs @@ -1,9 +1,11 @@ -use super::LabelText::{self, EscStr, HtmlStr, LabelStr}; -use super::{render, Edges, GraphWalk, Id, Labeller, Nodes, Style}; use std::io; use std::io::prelude::*; + use NodeLabels::*; +use super::LabelText::{self, EscStr, HtmlStr, LabelStr}; +use super::{render, Edges, GraphWalk, Id, Labeller, Nodes, Style}; + /// each node is an index in a vector in the graph. type Node = usize; struct Edge { diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index b1854923247f8..59204d799281f 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -1,5 +1,5 @@ -use crate::definitions::DefPathData; -use crate::hir; +use std::array::IntoIter; +use std::fmt::Debug; use rustc_ast as ast; use rustc_ast::NodeId; @@ -11,8 +11,8 @@ use rustc_span::hygiene::MacroKind; use rustc_span::symbol::kw; use rustc_span::Symbol; -use std::array::IntoIter; -use std::fmt::Debug; +use crate::definitions::DefPathData; +use crate::hir; /// Encodes if a `DefKind::Ctor` is the constructor of an enum variant or a struct. #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug, HashStable_Generic)] diff --git a/compiler/rustc_hir/src/definitions.rs b/compiler/rustc_hir/src/definitions.rs index 5c86135ec8dea..8c2be2152ea3a 100644 --- a/compiler/rustc_hir/src/definitions.rs +++ b/compiler/rustc_hir/src/definitions.rs @@ -4,18 +4,20 @@ //! There are also some rather random cases (like const initializer //! expressions) that are mostly just leftovers. -pub use crate::def_id::DefPathHash; -use crate::def_id::{CrateNum, DefIndex, LocalDefId, StableCrateId, CRATE_DEF_INDEX, LOCAL_CRATE}; -use crate::def_path_hash_map::DefPathHashMap; +use std::fmt::{self, Write}; +use std::hash::Hash; + use rustc_data_structures::stable_hasher::{Hash64, StableHasher}; use rustc_data_structures::unord::UnordMap; use rustc_index::IndexVec; use rustc_macros::{Decodable, Encodable}; use rustc_span::symbol::{kw, sym, Symbol}; -use std::fmt::{self, Write}; -use std::hash::Hash; use tracing::{debug, instrument}; +pub use crate::def_id::DefPathHash; +use crate::def_id::{CrateNum, DefIndex, LocalDefId, StableCrateId, CRATE_DEF_INDEX, LOCAL_CRATE}; +use crate::def_path_hash_map::DefPathHashMap; + /// The `DefPathTable` maps `DefIndex`es to `DefKey`s and vice versa. /// Internally the `DefPathTable` holds a tree of `DefKey`s, where each `DefKey` /// stores the `DefIndex` of its parent. diff --git a/compiler/rustc_hir/src/diagnostic_items.rs b/compiler/rustc_hir/src/diagnostic_items.rs index d4d09f9a4e06b..23a83a5011b5a 100644 --- a/compiler/rustc_hir/src/diagnostic_items.rs +++ b/compiler/rustc_hir/src/diagnostic_items.rs @@ -1,9 +1,10 @@ -use crate::def_id::DefId; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_span::def_id::DefIdMap; use rustc_span::Symbol; +use crate::def_id::DefId; + #[derive(Debug, Default)] pub struct DiagnosticItems { pub id_to_name: DefIdMap, diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index bf773f2d48793..9257be8647162 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1,29 +1,35 @@ -use crate::def::{CtorKind, DefKind, Res}; -use crate::def_id::{DefId, LocalDefIdMap}; -pub(crate) use crate::hir_id::{HirId, ItemLocalId, ItemLocalMap, OwnerId}; -use crate::intravisit::FnKind; -use crate::LangItem; +use std::fmt; + use rustc_ast as ast; use rustc_ast::util::parser::ExprPrecedence; -use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, TraitObjectSyntax, UintTy}; -pub use rustc_ast::{BinOp, BinOpKind, BindingMode, BorrowKind, ByRef, CaptureBy}; -pub use rustc_ast::{ImplPolarity, IsAuto, Movability, Mutability, UnOp}; -use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; +use rustc_ast::{ + Attribute, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece, IntTy, Label, LitKind, + TraitObjectSyntax, UintTy, +}; +pub use rustc_ast::{ + BinOp, BinOpKind, BindingMode, BorrowKind, ByRef, CaptureBy, ImplPolarity, IsAuto, Movability, + Mutability, UnOp, +}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::sorted_map::SortedMap; use rustc_index::IndexVec; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; +use rustc_span::def_id::LocalDefId; use rustc_span::hygiene::MacroKind; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::ErrorGuaranteed; -use rustc_span::{def_id::LocalDefId, BytePos, Span, DUMMY_SP}; +use rustc_span::{BytePos, ErrorGuaranteed, Span, DUMMY_SP}; use rustc_target::asm::InlineAsmRegOrRegClass; use rustc_target::spec::abi::Abi; use smallvec::SmallVec; -use std::fmt; use tracing::debug; +use crate::def::{CtorKind, DefKind, Res}; +use crate::def_id::{DefId, LocalDefIdMap}; +pub(crate) use crate::hir_id::{HirId, ItemLocalId, ItemLocalMap, OwnerId}; +use crate::intravisit::FnKind; +use crate::LangItem; + #[derive(Debug, Copy, Clone, HashStable_Generic)] pub struct Lifetime { pub hir_id: HirId, @@ -763,7 +769,7 @@ impl<'hir> Generics<'hir> { ) } - fn span_for_predicate_removal(&self, pos: usize) -> Span { + pub fn span_for_predicate_removal(&self, pos: usize) -> Span { let predicate = &self.predicates[pos]; let span = predicate.span(); @@ -806,15 +812,21 @@ impl<'hir> Generics<'hir> { return self.span_for_predicate_removal(predicate_pos); } - let span = bounds[bound_pos].span(); - if bound_pos == 0 { - // where T: ?Sized + Bar, Foo: Bar, - // ^^^^^^^^^ - span.to(bounds[1].span().shrink_to_lo()) + let bound_span = bounds[bound_pos].span(); + if bound_pos < bounds.len() - 1 { + // If there's another bound after the current bound + // include the following '+' e.g.: + // + // `T: Foo + CurrentBound + Bar` + // ^^^^^^^^^^^^^^^ + bound_span.to(bounds[bound_pos + 1].span().shrink_to_lo()) } else { - // where T: Bar + ?Sized, Foo: Bar, - // ^^^^^^^^^ - bounds[bound_pos - 1].span().shrink_to_hi().to(span) + // If the current bound is the last bound + // include the preceding '+' E.g.: + // + // `T: Foo + Bar + CurrentBound` + // ^^^^^^^^^^^^^^^ + bound_span.with_lo(bounds[bound_pos - 1].span().hi()) } } } @@ -2826,7 +2838,11 @@ pub enum TyKind<'hir> { OpaqueDef(ItemId, &'hir [GenericArg<'hir>], bool), /// A trait object type `Bound1 + Bound2 + Bound3` /// where `Bound` is a trait or a lifetime. - TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax), + TraitObject( + &'hir [(PolyTraitRef<'hir>, TraitBoundModifier)], + &'hir Lifetime, + TraitObjectSyntax, + ), /// Unused for now. Typeof(&'hir AnonConst), /// `TyKind::Infer` means the type should be inferred instead of it having been @@ -2936,6 +2952,17 @@ pub struct FnDecl<'hir> { pub lifetime_elision_allowed: bool, } +impl<'hir> FnDecl<'hir> { + pub fn opt_delegation_sig_id(&self) -> Option { + if let FnRetTy::Return(ty) = self.output + && let TyKind::InferDelegation(sig_id, _) = ty.kind + { + return Some(sig_id); + } + None + } +} + /// Represents what type of implicit self a function has, if any. #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)] pub enum ImplicitSelfKind { @@ -3998,8 +4025,9 @@ impl<'hir> Node<'hir> { // Some nodes are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(Block<'_>, 48); static_assert_size!(Body<'_>, 24); diff --git a/compiler/rustc_hir/src/hir_id.rs b/compiler/rustc_hir/src/hir_id.rs index c0ca1a8017eb2..f2142359935b9 100644 --- a/compiler/rustc_hir/src/hir_id.rs +++ b/compiler/rustc_hir/src/hir_id.rs @@ -1,8 +1,11 @@ -use crate::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_ID}; +use std::fmt::{self, Debug}; + use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableOrd, ToStableHashKey}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use rustc_span::{def_id::DefPathHash, HashStableContext}; -use std::fmt::{self, Debug}; +use rustc_span::def_id::DefPathHash; +use rustc_span::HashStableContext; + +use crate::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_ID}; #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable)] pub struct OwnerId { diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index c202ee41e3132..dd501f8417e64 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -64,13 +64,14 @@ //! This order consistency is required in a few places in rustc, for //! example coroutine inference, and possibly also HIR borrowck. -use crate::hir::*; use rustc_ast::visit::{try_visit, visit_opt, walk_list, VisitorResult}; use rustc_ast::{Attribute, Label}; use rustc_span::def_id::LocalDefId; use rustc_span::symbol::{Ident, Symbol}; use rustc_span::Span; +use crate::hir::*; + pub trait IntoVisitor<'hir> { type Visitor: Visitor<'hir>; fn into_visitor(&self) -> Self::Visitor; @@ -902,7 +903,9 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) -> V::Resul try_visit!(visitor.visit_array_length(length)); } TyKind::TraitObject(bounds, ref lifetime, _syntax) => { - walk_list!(visitor, visit_poly_trait_ref, bounds); + for (bound, _modifier) in bounds { + try_visit!(visitor.visit_poly_trait_ref(bound)); + } try_visit!(visitor.visit_lifetime(lifetime)); } TyKind::Typeof(ref expression) => try_visit!(visitor.visit_anon_const(expression)), diff --git a/compiler/rustc_hir/src/lang_items.rs b/compiler/rustc_hir/src/lang_items.rs index 58cc0f6211120..e7398fd222636 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -7,9 +7,6 @@ //! * Traits that represent operators; e.g., `Add`, `Sub`, `Index`. //! * Functions called by the compiler itself. -use crate::def_id::DefId; -use crate::{MethodKind, Target}; - use rustc_ast as ast; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; @@ -17,6 +14,9 @@ use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; +use crate::def_id::DefId; +use crate::{MethodKind, Target}; + /// All of the lang items, defined or not. /// Defined lang items can come from the current crate or its dependencies. #[derive(HashStable_Generic, Debug)] @@ -162,6 +162,7 @@ language_item_table! { StructuralPeq, sym::structural_peq, structural_peq_trait, Target::Trait, GenericRequirement::None; Copy, sym::copy, copy_trait, Target::Trait, GenericRequirement::Exact(0); Clone, sym::clone, clone_trait, Target::Trait, GenericRequirement::None; + CloneFn, sym::clone_fn, clone_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None; Sync, sym::sync, sync_trait, Target::Trait, GenericRequirement::Exact(0); DiscriminantKind, sym::discriminant_kind, discriminant_kind_trait, Target::Trait, GenericRequirement::None; /// The associated item of the `DiscriminantKind` trait. diff --git a/compiler/rustc_hir/src/pat_util.rs b/compiler/rustc_hir/src/pat_util.rs index 9991b02b1e120..73d1ea4070795 100644 --- a/compiler/rustc_hir/src/pat_util.rs +++ b/compiler/rustc_hir/src/pat_util.rs @@ -1,10 +1,11 @@ -use crate::def::{CtorOf, DefKind, Res}; -use crate::def_id::{DefId, DefIdSet}; -use crate::hir::{self, BindingMode, ByRef, HirId, PatKind}; +use std::iter::Enumerate; + use rustc_span::symbol::Ident; use rustc_span::Span; -use std::iter::Enumerate; +use crate::def::{CtorOf, DefKind, Res}; +use crate::def_id::{DefId, DefIdSet}; +use crate::hir::{self, BindingMode, ByRef, HirId, PatKind}; pub struct EnumerateAndAdjust { enumerate: Enumerate, diff --git a/compiler/rustc_hir/src/stable_hash_impls.rs b/compiler/rustc_hir/src/stable_hash_impls.rs index baa1635f7313f..fe169e989ec9f 100644 --- a/compiler/rustc_hir/src/stable_hash_impls.rs +++ b/compiler/rustc_hir/src/stable_hash_impls.rs @@ -1,10 +1,10 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey}; +use rustc_span::def_id::DefPathHash; use crate::hir::{ AttributeMap, BodyId, Crate, ForeignItemId, ImplItemId, ItemId, OwnerNodes, TraitItemId, }; use crate::hir_id::{HirId, ItemLocalId}; -use rustc_span::def_id::DefPathHash; /// Requirements for a `StableHashingContext` to be used in this crate. /// This is a hack to allow using the `HashStable_Generic` derive macro diff --git a/compiler/rustc_hir/src/target.rs b/compiler/rustc_hir/src/target.rs index e448d29e55fb7..f43008eda1181 100644 --- a/compiler/rustc_hir/src/target.rs +++ b/compiler/rustc_hir/src/target.rs @@ -4,11 +4,10 @@ //! conflicts between multiple such attributes attached to the same //! item. -use crate::hir; -use crate::{Item, ItemKind, TraitItem, TraitItemKind}; +use std::fmt::{self, Display}; use crate::def::DefKind; -use std::fmt::{self, Display}; +use crate::{hir, Item, ItemKind, TraitItem, TraitItemKind}; #[derive(Copy, Clone, PartialEq, Debug)] pub enum GenericParamKind { diff --git a/compiler/rustc_hir/src/tests.rs b/compiler/rustc_hir/src/tests.rs index 571923b546293..16b3c4a9ab691 100644 --- a/compiler/rustc_hir/src/tests.rs +++ b/compiler/rustc_hir/src/tests.rs @@ -1,9 +1,10 @@ -use crate::definitions::{DefKey, DefPathData, DisambiguatedDefPathData}; use rustc_data_structures::stable_hasher::Hash64; use rustc_span::def_id::{DefPathHash, StableCrateId}; use rustc_span::edition::Edition; use rustc_span::{create_session_globals_then, Symbol}; +use crate::definitions::{DefKey, DefPathData, DisambiguatedDefPathData}; + #[test] fn def_path_hash_depends_on_crate_id() { // This test makes sure that *both* halves of a DefPathHash depend on diff --git a/compiler/rustc_hir/src/weak_lang_items.rs b/compiler/rustc_hir/src/weak_lang_items.rs index 0cc50c6dd8505..ca133c5965dd0 100644 --- a/compiler/rustc_hir/src/weak_lang_items.rs +++ b/compiler/rustc_hir/src/weak_lang_items.rs @@ -1,9 +1,9 @@ //! Validity checking for weak lang items -use crate::LangItem; - use rustc_span::symbol::{sym, Symbol}; +use crate::LangItem; + macro_rules! weak_lang_items { ($($item:ident, $sym:ident;)*) => { pub static WEAK_LANG_ITEMS: &[LangItem] = &[$(LangItem::$item,)*]; diff --git a/compiler/rustc_hir_analysis/messages.ftl b/compiler/rustc_hir_analysis/messages.ftl index cc404daa51f59..bde94be6f514e 100644 --- a/compiler/rustc_hir_analysis/messages.ftl +++ b/compiler/rustc_hir_analysis/messages.ftl @@ -1,4 +1,4 @@ -hir_analysis_ambiguous_assoc_item = ambiguous associated {$assoc_kind} `{$assoc_name}` in bounds of `{$ty_param_name}` +hir_analysis_ambiguous_assoc_item = ambiguous associated {$assoc_kind} `{$assoc_name}` in bounds of `{$qself}` .label = ambiguous associated {$assoc_kind} `{$assoc_name}` hir_analysis_ambiguous_lifetime_bound = @@ -12,16 +12,21 @@ hir_analysis_assoc_item_is_private = {$kind} `{$name}` is private .label = private {$kind} .defined_here_label = the {$kind} is defined here -hir_analysis_assoc_item_not_found = associated {$assoc_kind} `{$assoc_name}` not found for `{$ty_param_name}` +hir_analysis_assoc_item_not_found = associated {$assoc_kind} `{$assoc_name}` not found for `{$qself}` hir_analysis_assoc_item_not_found_found_in_other_trait_label = there is {$identically_named -> [true] an *[false] a similarly named } associated {$assoc_kind} `{$suggested_name}` in the trait `{$trait_name}` hir_analysis_assoc_item_not_found_label = associated {$assoc_kind} `{$assoc_name}` not found -hir_analysis_assoc_item_not_found_other_sugg = `{$ty_param_name}` has the following associated {$assoc_kind} +hir_analysis_assoc_item_not_found_other_sugg = `{$qself}` has the following associated {$assoc_kind} +hir_analysis_assoc_item_not_found_similar_in_other_trait_qpath_sugg = + consider fully qualifying{$identically_named -> + [true] {""} + *[false] {" "}and renaming + } the associated {$assoc_kind} hir_analysis_assoc_item_not_found_similar_in_other_trait_sugg = change the associated {$assoc_kind} name to use `{$suggested_name}` from `{$trait_name}` -hir_analysis_assoc_item_not_found_similar_in_other_trait_with_bound_sugg = and also change the associated {$assoc_kind} name +hir_analysis_assoc_item_not_found_similar_in_other_trait_with_bound_sugg = ...and changing the associated {$assoc_kind} name hir_analysis_assoc_item_not_found_similar_sugg = there is an associated {$assoc_kind} with a similar name hir_analysis_assoc_kind_mismatch = expected {$expected}, found {$got} @@ -336,8 +341,7 @@ hir_analysis_must_implement_not_function_span_note = required by this annotation hir_analysis_must_implement_one_of_attribute = the `#[rustc_must_implement_one_of]` attribute must be used with at least 2 args -hir_analysis_not_supported_delegation = - {$descr} is not supported yet +hir_analysis_not_supported_delegation = {$descr} .label = callee defined here hir_analysis_only_current_traits_adt = `{$name}` is not defined in the current crate diff --git a/compiler/rustc_hir_analysis/src/autoderef.rs b/compiler/rustc_hir_analysis/src/autoderef.rs index 2bf14a2461f31..53c8586b52a79 100644 --- a/compiler/rustc_hir_analysis/src/autoderef.rs +++ b/compiler/rustc_hir_analysis/src/autoderef.rs @@ -1,15 +1,14 @@ -use crate::errors::AutoDerefReachedRecursionLimit; -use crate::traits; -use crate::traits::query::evaluate_obligation::InferCtxtExt; use rustc_infer::infer::InferCtxt; -use rustc_middle::ty::TypeVisitableExt; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; use rustc_session::Limit; -use rustc_span::def_id::LocalDefId; -use rustc_span::def_id::LOCAL_CRATE; +use rustc_span::def_id::{LocalDefId, LOCAL_CRATE}; use rustc_span::Span; use rustc_trait_selection::traits::ObligationCtxt; +use crate::errors::AutoDerefReachedRecursionLimit; +use crate::traits; +use crate::traits::query::evaluate_obligation::InferCtxtExt; + #[derive(Copy, Clone, Debug)] pub enum AutoderefKind { /// A true pointer type, such as `&T` and `*mut T`. diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 27db54181651a..2e778fd375961 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -1,12 +1,9 @@ -use crate::check::intrinsicck::InlineAsmCtxt; +use std::cell::LazyCell; +use std::ops::ControlFlow; -use super::compare_impl_item::check_type_bounds; -use super::compare_impl_item::{compare_impl_method, compare_impl_ty}; -use super::*; -use rustc_attr as attr; use rustc_data_structures::unord::{UnordMap, UnordSet}; -use rustc_errors::{codes::*, MultiSpan}; -use rustc_hir as hir; +use rustc_errors::codes::*; +use rustc_errors::MultiSpan; use rustc_hir::def::{CtorKind, DefKind}; use rustc_hir::Node; use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt}; @@ -19,9 +16,9 @@ use rustc_middle::ty::error::TypeErrorToStringExt; use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES}; use rustc_middle::ty::util::{Discr, InspectCoroutineFields, IntTypeExt}; -use rustc_middle::ty::GenericArgKind; use rustc_middle::ty::{ - AdtDef, ParamEnv, RegionKind, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, + AdtDef, GenericArgKind, ParamEnv, RegionKind, TypeSuperVisitable, TypeVisitable, + TypeVisitableExt, }; use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS}; use rustc_target::abi::FieldIdx; @@ -30,9 +27,11 @@ use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits; use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _; use rustc_type_ir::fold::TypeFoldable; +use {rustc_attr as attr, rustc_hir as hir}; -use std::cell::LazyCell; -use std::ops::ControlFlow; +use super::compare_impl_item::{check_type_bounds, compare_impl_method, compare_impl_ty}; +use super::*; +use crate::check::intrinsicck::InlineAsmCtxt; pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) { match tcx.sess.target.is_abi_supported(abi) { 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 c99f13468e200..53cde14f337be 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -1,24 +1,24 @@ -use super::potentially_plural_count; -use crate::errors::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture}; use core::ops::ControlFlow; +use std::borrow::Cow; +use std::iter; + use hir::def_id::{DefId, DefIdMap, LocalDefId}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; -use rustc_errors::{codes::*, pluralize, struct_span_code_err, Applicability, ErrorGuaranteed}; +use rustc_errors::codes::*; +use rustc_errors::{pluralize, struct_span_code_err, Applicability, ErrorGuaranteed}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::intravisit; -use rustc_hir::{GenericParamKind, ImplItemKind}; +use rustc_hir::{intravisit, GenericParamKind, ImplItemKind}; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::util; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::util::ExplicitSelf; -use rustc_middle::ty::Upcast; use rustc_middle::ty::{ - self, GenericArgs, Ty, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, + self, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, TypeFolder, + TypeSuperFoldable, TypeVisitableExt, Upcast, }; -use rustc_middle::ty::{GenericParamDefKind, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_span::Span; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; @@ -28,8 +28,9 @@ use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _; use rustc_trait_selection::traits::{ self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt, Reveal, }; -use std::borrow::Cow; -use std::iter; + +use super::potentially_plural_count; +use crate::errors::{LifetimesOrBoundsMismatchOnTrait, MethodShouldReturnFuture}; mod refine; diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs index ad3324f79e271..80daaa60324a3 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs @@ -1,7 +1,8 @@ use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; use rustc_hir::def_id::DefId; -use rustc_infer::infer::{outlives::env::OutlivesEnvironment, TyCtxtInferExt}; +use rustc_infer::infer::outlives::env::OutlivesEnvironment; +use rustc_infer::infer::TyCtxtInferExt; use rustc_lint_defs::builtin::{REFINING_IMPL_TRAIT_INTERNAL, REFINING_IMPL_TRAIT_REACHABLE}; use rustc_middle::span_bug; use rustc_middle::traits::{ObligationCause, Reveal}; @@ -10,9 +11,8 @@ use rustc_middle::ty::{ }; use rustc_span::Span; use rustc_trait_selection::regions::InferCtxtRegionExt; -use rustc_trait_selection::traits::{ - elaborate, normalize_param_env_or_error, outlives_bounds::InferCtxtExt, ObligationCtxt, -}; +use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt; +use rustc_trait_selection::traits::{elaborate, normalize_param_env_or_error, ObligationCtxt}; /// Check that an implementation does not refine an RPITIT from a trait method signature. pub(super) fn check_refining_return_position_impl_trait_in_trait<'tcx>( diff --git a/compiler/rustc_hir_analysis/src/check/dropck.rs b/compiler/rustc_hir_analysis/src/check/dropck.rs index 1937144802554..d173915e480b0 100644 --- a/compiler/rustc_hir_analysis/src/check/dropck.rs +++ b/compiler/rustc_hir_analysis/src/check/dropck.rs @@ -3,13 +3,13 @@ // We don't do any drop checking during hir typeck. use rustc_data_structures::fx::FxHashSet; -use rustc_errors::{codes::*, struct_span_code_err, ErrorGuaranteed}; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, ErrorGuaranteed}; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{RegionResolutionError, TyCtxtInferExt}; -use rustc_infer::traits::ObligationCauseCode; +use rustc_infer::traits::{ObligationCause, ObligationCauseCode}; use rustc_middle::ty::util::CheckRegions; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt}; use rustc_trait_selection::regions::InferCtxtRegionExt; use rustc_trait_selection::traits::{self, ObligationCtxt}; @@ -115,8 +115,9 @@ fn ensure_drop_params_and_item_params_correspond<'tcx>( Err(err.emit()) } -/// Confirms that every predicate imposed by dtor_predicates is -/// implied by assuming the predicates attached to self_type_did. +/// Confirms that all predicates defined on the `Drop` impl (`drop_impl_def_id`) are able to be +/// proven from within `adt_def_id`'s environment. I.e. all the predicates on the impl are +/// implied by the ADT being well formed. fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>( tcx: TyCtxt<'tcx>, drop_impl_def_id: LocalDefId, @@ -126,6 +127,8 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>( let infcx = tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new_with_diagnostics(&infcx); + let impl_span = tcx.def_span(drop_impl_def_id.to_def_id()); + // Take the param-env of the adt and instantiate the args that show up in // the implementation's self type. This gives us the assumptions that the // self ty of the implementation is allowed to know just from it being a @@ -135,14 +138,27 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>( // We don't need to normalize this param-env or anything, since we're only // instantiating it with free params, so no additional param-env normalization // can occur on top of what has been done in the param_env query itself. - let param_env = + // + // Note: Ideally instead of instantiating the `ParamEnv` with the arguments from the impl ty we + // could instead use identity args for the adt. Unfortunately this would cause any errors to + // reference the params from the ADT instead of from the impl which is bad UX. To resolve + // this we "rename" the ADT's params to be the impl's params which should not affect behaviour. + let impl_adt_ty = Ty::new_adt(tcx, tcx.adt_def(adt_def_id), adt_to_impl_args); + let adt_env = ty::EarlyBinder::bind(tcx.param_env(adt_def_id)).instantiate(tcx, adt_to_impl_args); - for (pred, span) in tcx.predicates_of(drop_impl_def_id).instantiate_identity(tcx) { + let fresh_impl_args = infcx.fresh_args_for_item(impl_span, drop_impl_def_id.to_def_id()); + let fresh_adt_ty = + tcx.impl_trait_ref(drop_impl_def_id).unwrap().instantiate(tcx, fresh_impl_args).self_ty(); + + ocx.eq(&ObligationCause::dummy_with_span(impl_span), adt_env, fresh_adt_ty, impl_adt_ty) + .unwrap(); + + for (clause, span) in tcx.predicates_of(drop_impl_def_id).instantiate(tcx, fresh_impl_args) { let normalize_cause = traits::ObligationCause::misc(span, adt_def_id); - let pred = ocx.normalize(&normalize_cause, param_env, pred); + let pred = ocx.normalize(&normalize_cause, adt_env, clause); let cause = traits::ObligationCause::new(span, adt_def_id, ObligationCauseCode::DropImpl); - ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, pred)); + ocx.register_obligation(traits::Obligation::new(tcx, cause, adt_env, pred)); } // All of the custom error reporting logic is to preserve parity with the old @@ -176,7 +192,7 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>( return Err(guar.unwrap()); } - let errors = ocx.infcx.resolve_regions(&OutlivesEnvironment::new(param_env)); + let errors = ocx.infcx.resolve_regions(&OutlivesEnvironment::new(adt_env)); if !errors.is_empty() { let mut guar = None; for error in errors { diff --git a/compiler/rustc_hir_analysis/src/check/entry.rs b/compiler/rustc_hir_analysis/src/check/entry.rs index e4d4b7df24ea6..1f724580564a4 100644 --- a/compiler/rustc_hir_analysis/src/check/entry.rs +++ b/compiler/rustc_hir_analysis/src/check/entry.rs @@ -1,3 +1,5 @@ +use std::ops::Not; + use rustc_hir as hir; use rustc_hir::Node; use rustc_infer::infer::TyCtxtInferExt; @@ -5,13 +7,12 @@ use rustc_middle::span_bug; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_session::config::EntryFnType; use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; -use rustc_span::{symbol::sym, Span}; +use rustc_span::symbol::sym; +use rustc_span::Span; use rustc_target::spec::abi::Abi; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode}; -use std::ops::Not; - use super::check_function_signature; use crate::errors; diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 6282499883ba4..4b45ced30c579 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -1,13 +1,8 @@ //! Type-checking for the rust-intrinsic and platform-intrinsic //! intrinsics that the compiler exposes. -use crate::check::check_function_signature; -use crate::errors::{ - UnrecognizedAtomicOperation, UnrecognizedIntrinsicFunction, - WrongNumberOfGenericArgumentsToIntrinsic, -}; - -use rustc_errors::{codes::*, struct_span_code_err, DiagMessage}; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, DiagMessage}; use rustc_hir as hir; use rustc_middle::bug; use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; @@ -17,6 +12,12 @@ use rustc_span::symbol::sym; use rustc_span::{Span, Symbol}; use rustc_target::spec::abi::Abi; +use crate::check::check_function_signature; +use crate::errors::{ + UnrecognizedAtomicOperation, UnrecognizedIntrinsicFunction, + WrongNumberOfGenericArgumentsToIntrinsic, +}; + fn equate_intrinsic_type<'tcx>( tcx: TyCtxt<'tcx>, span: Span, @@ -119,6 +120,7 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) - | sym::type_id | sym::likely | sym::unlikely + | sym::select_unpredictable | sym::ptr_guaranteed_cmp | sym::minnumf16 | sym::minnumf32 @@ -487,6 +489,7 @@ pub fn check_intrinsic_type( sym::assume => (0, 0, vec![tcx.types.bool], tcx.types.unit), sym::likely => (0, 0, vec![tcx.types.bool], tcx.types.bool), sym::unlikely => (0, 0, vec![tcx.types.bool], tcx.types.bool), + sym::select_unpredictable => (1, 0, vec![tcx.types.bool, param(0), param(0)], param(0)), sym::read_via_copy => (1, 0, vec![Ty::new_imm_ptr(tcx, param(0))], param(0)), sym::write_via_move => { diff --git a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs index 2e965c59ebb53..847a1e6470679 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs @@ -2,7 +2,7 @@ use rustc_ast::InlineAsmTemplatePiece; use rustc_data_structures::fx::FxIndexSet; use rustc_hir::{self as hir, LangItem}; use rustc_middle::bug; -use rustc_middle::ty::{self, Article, FloatTy, IntTy, Ty, TyCtxt, TypeVisitableExt, UintTy}; +use rustc_middle::ty::{self, FloatTy, IntTy, Ty, TyCtxt, TypeVisitableExt, UintTy}; use rustc_session::lint; use rustc_span::def_id::LocalDefId; use rustc_span::Symbol; @@ -455,32 +455,22 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { ); } } - // No special checking is needed for these: - // - Typeck has checked that Const operands are integers. - // - AST lowering guarantees that SymStatic points to a static. - hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::SymStatic { .. } => {} - // Check that sym actually points to a function. Later passes - // depend on this. + // Typeck has checked that Const operands are integers. + hir::InlineAsmOperand::Const { anon_const } => { + debug_assert!(matches!( + self.tcx.type_of(anon_const.def_id).instantiate_identity().kind(), + ty::Error(_) | ty::Int(_) | ty::Uint(_) + )); + } + // Typeck has checked that SymFn refers to a function. hir::InlineAsmOperand::SymFn { anon_const } => { - let ty = self.tcx.type_of(anon_const.def_id).instantiate_identity(); - match ty.kind() { - ty::Never | ty::Error(_) => {} - ty::FnDef(..) => {} - _ => { - self.tcx - .dcx() - .struct_span_err(*op_sp, "invalid `sym` operand") - .with_span_label( - self.tcx.def_span(anon_const.def_id), - format!("is {} `{}`", ty.kind().article(), ty), - ) - .with_help( - "`sym` operands must refer to either a function or a static", - ) - .emit(); - } - }; + debug_assert!(matches!( + self.tcx.type_of(anon_const.def_id).instantiate_identity().kind(), + ty::Error(_) | ty::FnDef(..) + )); } + // AST lowering guarantees that SymStatic points to a static. + hir::InlineAsmOperand::SymStatic { .. } => {} // No special checking is needed for labels. hir::InlineAsmOperand::Label { .. } => {} } diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index 4c230ad84def6..678b8c89a5054 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -72,13 +72,11 @@ pub mod intrinsicck; mod region; pub mod wfcheck; -pub use check::check_abi; - use std::num::NonZero; +pub use check::check_abi; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; -use rustc_errors::ErrorGuaranteed; -use rustc_errors::{pluralize, struct_span_code_err, Diag}; +use rustc_errors::{pluralize, struct_span_code_err, Diag, ErrorGuaranteed}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::Visitor; use rustc_index::bit_set::BitSet; @@ -87,12 +85,12 @@ use rustc_infer::infer::{self, TyCtxtInferExt as _}; use rustc_infer::traits::ObligationCause; use rustc_middle::query::Providers; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_middle::ty::{GenericArgs, GenericArgsRef}; +use rustc_middle::ty::{self, GenericArgs, GenericArgsRef, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_session::parse::feature_err; +use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::{def_id::CRATE_DEF_ID, BytePos, Span, Symbol, DUMMY_SP}; +use rustc_span::{BytePos, Span, Symbol, DUMMY_SP}; use rustc_target::abi::VariantIdx; use rustc_target::spec::abi::Abi; use rustc_trait_selection::error_reporting::infer::ObligationCauseExt as _; @@ -100,11 +98,9 @@ use rustc_trait_selection::error_reporting::traits::suggestions::ReturnsVisitor; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::ObligationCtxt; -use crate::errors; -use crate::require_c_abi_if_c_variadic; - use self::compare_impl_item::collect_return_position_impl_trait_in_trait_tys; use self::region::region_scope_tree; +use crate::{errors, require_c_abi_if_c_variadic}; pub fn provide(providers: &mut Providers) { wfcheck::provide(providers); diff --git a/compiler/rustc_hir_analysis/src/check/region.rs b/compiler/rustc_hir_analysis/src/check/region.rs index 2b5efd3b2f6f9..bc6641c688ccf 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -6,6 +6,8 @@ //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/borrow_check.html +use std::mem; + use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_hir::def_id::DefId; @@ -19,8 +21,6 @@ use rustc_span::source_map; use super::errs::{maybe_expr_static_mut, maybe_stmt_static_mut}; -use std::mem; - #[derive(Debug, Copy, Clone)] pub struct Context { /// The scope that contains any new variables declared, plus its depth in diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 0316ef69bf83e..c878095ba0d70 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -1,14 +1,10 @@ -use crate::autoderef::Autoderef; -use crate::collect::CollectItemTypesVisitor; -use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter}; -use crate::errors; -use crate::fluent_generated as fluent; +use std::cell::LazyCell; +use std::ops::{ControlFlow, Deref}; use hir::intravisit::{self, Visitor}; -use rustc_ast as ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; -use rustc_errors::{codes::*, pluralize, struct_span_code_err, Applicability, ErrorGuaranteed}; -use rustc_hir as hir; +use rustc_errors::codes::*; +use rustc_errors::{pluralize, struct_span_code_err, Applicability, ErrorGuaranteed}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId}; use rustc_hir::lang_items::LangItem; @@ -20,10 +16,9 @@ use rustc_middle::query::Providers; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::trait_def::TraitSpecializationKind; use rustc_middle::ty::{ - self, AdtKind, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, - TypeVisitable, TypeVisitableExt, TypeVisitor, Upcast, + self, AdtKind, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, + TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, Upcast, }; -use rustc_middle::ty::{GenericArgKind, GenericArgs}; use rustc_middle::{bug, span_bug}; use rustc_session::parse::feature_err; use rustc_span::symbol::{sym, Ident}; @@ -41,9 +36,12 @@ use rustc_trait_selection::traits::{ }; use rustc_type_ir::solve::NoSolution; use rustc_type_ir::TypeFlags; +use {rustc_ast as ast, rustc_hir as hir}; -use std::cell::LazyCell; -use std::ops::{ControlFlow, Deref}; +use crate::autoderef::Autoderef; +use crate::collect::CollectItemTypesVisitor; +use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter}; +use crate::{errors, fluent_generated as fluent}; pub(super) struct WfCheckingCtxt<'a, 'tcx> { pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>, @@ -831,7 +829,7 @@ impl<'tcx> TypeVisitor> for GATArgsCollector<'tcx> { fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool { match ty.kind { - hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments { + hir::TyKind::TraitObject([(trait_ref, _)], ..) => match trait_ref.trait_ref.path.segments { [s] => s.res.opt_def_id() == Some(trait_def_id.to_def_id()), _ => false, }, diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index b35ee270fef58..bdb5f5b720529 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -1,7 +1,7 @@ //! Check properties that are required by built-in traits and set //! up data structures required by type-checking/codegen. -use crate::errors; +use std::collections::BTreeMap; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{ErrorGuaranteed, MultiSpan}; @@ -10,8 +10,7 @@ use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::LangItem; use rustc_hir::ItemKind; use rustc_infer::infer::outlives::env::OutlivesEnvironment; -use rustc_infer::infer::TyCtxtInferExt; -use rustc_infer::infer::{self, RegionResolutionError}; +use rustc_infer::infer::{self, RegionResolutionError, TyCtxtInferExt}; use rustc_infer::traits::Obligation; use rustc_middle::ty::adjustment::CoerceUnsizedInfo; use rustc_middle::ty::print::PrintTraitRefExt as _; @@ -22,9 +21,9 @@ use rustc_trait_selection::traits::misc::{ type_allowed_to_implement_const_param_ty, type_allowed_to_implement_copy, ConstParamTyImplementationError, CopyImplementationError, InfringingFieldsReason, }; -use rustc_trait_selection::traits::ObligationCtxt; -use rustc_trait_selection::traits::{self, ObligationCause}; -use std::collections::BTreeMap; +use rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt}; + +use crate::errors; pub(super) fn check_trait<'tcx>( tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs index 3aef29f4ae4dd..cd5cc33d65abc 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs @@ -1,6 +1,6 @@ -use rustc_data_structures::fx::IndexEntry; -use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; -use rustc_errors::{codes::*, struct_span_code_err}; +use rustc_data_structures::fx::{FxHashSet, FxIndexMap, IndexEntry}; +use rustc_errors::codes::*; +use rustc_errors::struct_span_code_err; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; diff --git a/compiler/rustc_hir_analysis/src/coherence/mod.rs b/compiler/rustc_hir_analysis/src/coherence/mod.rs index e9961d3ad0862..8e4da90ca2646 100644 --- a/compiler/rustc_hir_analysis/src/coherence/mod.rs +++ b/compiler/rustc_hir_analysis/src/coherence/mod.rs @@ -5,8 +5,8 @@ // done by the orphan and overlap modules. Then we build up various // mappings. That mapping code resides here. -use crate::errors; -use rustc_errors::{codes::*, struct_span_code_err}; +use rustc_errors::codes::*; +use rustc_errors::struct_span_code_err; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::LangItem; use rustc_middle::query::Providers; @@ -14,6 +14,8 @@ use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; use rustc_session::parse::feature_err; use rustc_span::{sym, ErrorGuaranteed}; +use crate::errors; + mod builtin; mod inherent_impls; mod inherent_impls_overlap; diff --git a/compiler/rustc_hir_analysis/src/coherence/orphan.rs b/compiler/rustc_hir_analysis/src/coherence/orphan.rs index f2804ce31fa21..dcd0e3111a489 100644 --- a/compiler/rustc_hir_analysis/src/coherence/orphan.rs +++ b/compiler/rustc_hir_analysis/src/coherence/orphan.rs @@ -1,19 +1,21 @@ //! Orphan checker: every impl either implements a trait defined in this //! crate or pertains to a type defined in this crate. -use crate::errors; - use rustc_data_structures::fx::FxIndexSet; use rustc_errors::ErrorGuaranteed; use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_lint_defs::builtin::UNCOVERED_PARAM_IN_PROJECTION; -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_middle::ty::{TypeFoldable, TypeFolder, TypeSuperFoldable}; -use rustc_middle::ty::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; +use rustc_middle::ty::{ + self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeSuperVisitable, + TypeVisitable, TypeVisitableExt, TypeVisitor, +}; use rustc_middle::{bug, span_bug}; use rustc_span::def_id::{DefId, LocalDefId}; -use rustc_trait_selection::traits::{self, IsFirstInputType, UncoveredTyParams}; -use rustc_trait_selection::traits::{OrphanCheckErr, OrphanCheckMode}; +use rustc_trait_selection::traits::{ + self, IsFirstInputType, OrphanCheckErr, OrphanCheckMode, UncoveredTyParams, +}; + +use crate::errors; #[instrument(level = "debug", skip(tcx))] pub(crate) fn orphan_check_impl( diff --git a/compiler/rustc_hir_analysis/src/coherence/unsafety.rs b/compiler/rustc_hir_analysis/src/coherence/unsafety.rs index 5fe21e9b82242..7513f680271e3 100644 --- a/compiler/rustc_hir_analysis/src/coherence/unsafety.rs +++ b/compiler/rustc_hir_analysis/src/coherence/unsafety.rs @@ -1,10 +1,12 @@ //! Unsafety checker: every impl either implements a trait defined in this //! crate or pertains to a type defined in this crate. -use rustc_errors::{codes::*, struct_span_code_err}; +use rustc_errors::codes::*; +use rustc_errors::struct_span_code_err; use rustc_hir::Safety; use rustc_middle::ty::print::PrintTraitRefExt as _; -use rustc_middle::ty::{ImplPolarity::*, ImplTraitHeader, TraitDef, TyCtxt}; +use rustc_middle::ty::ImplPolarity::*; +use rustc_middle::ty::{ImplTraitHeader, TraitDef, TyCtxt}; use rustc_span::def_id::LocalDefId; use rustc_span::ErrorGuaranteed; diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 565351268c96b..47ff748547a90 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -14,6 +14,10 @@ //! At present, however, we do run collection across all items in the //! crate as a kind of pass. This should eventually be factored away. +use std::cell::Cell; +use std::iter; +use std::ops::Bound; + use rustc_ast::Recovered; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; @@ -24,8 +28,7 @@ use rustc_errors::{ use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{self, walk_generics, Visitor}; -use rustc_hir::{self as hir}; -use rustc_hir::{GenericParamKind, Node}; +use rustc_hir::{self as hir, GenericParamKind, Node}; use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::ObligationCause; use rustc_middle::hir::nested_filter; @@ -39,9 +42,6 @@ use rustc_target::spec::abi; use rustc_trait_selection::error_reporting::traits::suggestions::NextTypeParamName; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::ObligationCtxt; -use std::cell::Cell; -use std::iter; -use std::ops::Bound; use crate::check::intrinsic::intrinsic_operation_unsafety; use crate::errors; @@ -1207,25 +1207,29 @@ fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> { fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { let item = tcx.hir().expect_item(def_id); - let (is_auto, safety, items) = match item.kind { + let (is_alias, is_auto, safety, items) = match item.kind { hir::ItemKind::Trait(is_auto, safety, .., items) => { - (is_auto == hir::IsAuto::Yes, safety, items) + (false, is_auto == hir::IsAuto::Yes, safety, items) } - hir::ItemKind::TraitAlias(..) => (false, hir::Safety::Safe, &[][..]), + hir::ItemKind::TraitAlias(..) => (true, false, hir::Safety::Safe, &[][..]), _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"), }; - let constness = if tcx.has_attr(def_id, sym::const_trait) { + // Only regular traits can be const. + let constness = if !is_alias && tcx.has_attr(def_id, sym::const_trait) { hir::Constness::Const } else { hir::Constness::NotConst }; + let paren_sugar = tcx.has_attr(def_id, sym::rustc_paren_sugar); if paren_sugar && !tcx.features().unboxed_closures { tcx.dcx().emit_err(errors::ParenSugarAttribute { span: item.span }); } - let is_marker = tcx.has_attr(def_id, sym::marker); + // Only regular traits can be marker. + let is_marker = !is_alias && tcx.has_attr(def_id, sym::marker); + let rustc_coinductive = tcx.has_attr(def_id, sym::rustc_coinductive); let is_fundamental = tcx.has_attr(def_id, sym::fundamental); diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index 690423421b975..60e2c2eb30e56 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -1,10 +1,7 @@ use std::ops::ControlFlow; -use crate::middle::resolve_bound_vars as rbv; -use hir::{ - intravisit::{self, Visitor}, - GenericParamKind, HirId, Node, -}; +use hir::intravisit::{self, Visitor}; +use hir::{GenericParamKind, HirId, Node}; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; @@ -13,6 +10,9 @@ use rustc_session::lint; use rustc_span::symbol::{kw, Symbol}; use rustc_span::Span; +use crate::delegation::inherit_generics_for_delegation_item; +use crate::middle::resolve_bound_vars as rbv; + #[instrument(level = "debug", skip(tcx), ret)] pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { use rustc_hir::*; @@ -227,6 +227,16 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { // inherit the generics of the item. Some(parent.to_def_id()) } + ItemKind::Fn(sig, _, _) => { + // For a delegation item inherit generics from callee. + if let Some(sig_id) = sig.decl.opt_delegation_sig_id() + && let Some(generics) = + inherit_generics_for_delegation_item(tcx, def_id, sig_id) + { + return generics; + } + None + } _ => None, }, _ => None, @@ -328,8 +338,6 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { if default.is_some() { match allow_defaults { Defaults::Allowed => {} - Defaults::FutureCompatDisallowed - if tcx.features().default_type_parameter_fallback => {} Defaults::FutureCompatDisallowed => { tcx.node_span_lint( lint::builtin::INVALID_TYPE_PARAM_DEFAULT, diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index c03e074c80b7a..6bff99ea65f0b 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -1,15 +1,17 @@ -use super::ItemCtxt; -use crate::hir_ty_lowering::{HirTyLowerer, PredicateFilter}; use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; use rustc_infer::traits::util; -use rustc_middle::ty::GenericArgs; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable}; +use rustc_middle::ty::{ + self, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, +}; use rustc_middle::{bug, span_bug}; use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::Span; use rustc_type_ir::Upcast; +use super::ItemCtxt; +use crate::hir_ty_lowering::{HirTyLowerer, PredicateFilter}; + /// For associated types we include both bounds written on the type /// (`type X: Trait`) and predicates from the trait: `where Self::X: Trait`. /// diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 9e430c83e20d7..a5a56cb845d79 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -1,19 +1,20 @@ -use crate::bounds::Bounds; -use crate::collect::ItemCtxt; -use crate::constrained_generic_params as cgp; -use crate::hir_ty_lowering::{HirTyLowerer, OnlySelfBounds, PredicateFilter, RegionInferReason}; use hir::{HirId, Node}; use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_middle::ty::{GenericPredicates, ImplTraitInTraitData, Upcast}; +use rustc_middle::ty::{self, GenericPredicates, ImplTraitInTraitData, Ty, TyCtxt, Upcast}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::Ident; use rustc_span::{Span, DUMMY_SP}; +use crate::bounds::Bounds; +use crate::collect::ItemCtxt; +use crate::constrained_generic_params as cgp; +use crate::delegation::inherit_predicates_for_delegation_item; +use crate::hir_ty_lowering::{HirTyLowerer, OnlySelfBounds, PredicateFilter, RegionInferReason}; + /// Returns a list of all type predicates (explicit and implicit) for the definition with /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus /// `Self: Trait` predicates for traits. @@ -143,6 +144,16 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen ItemKind::Trait(_, _, _, self_bounds, ..) | ItemKind::TraitAlias(_, self_bounds) => { is_trait = Some(self_bounds); } + + ItemKind::Fn(sig, _, _) => { + // For a delegation item inherit predicates from callee. + if let Some(sig_id) = sig.decl.opt_delegation_sig_id() + && let Some(predicates) = + inherit_predicates_for_delegation_item(tcx, def_id, sig_id) + { + return predicates; + } + } _ => {} } }; 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 349dc9ad00ed3..e11d3c9c48b4e 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -7,6 +7,8 @@ //! is also responsible for assigning their semantics to implicit lifetimes in trait objects. use core::ops::ControlFlow; +use std::fmt; + use rustc_ast::visit::walk_list; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_hir as hir; @@ -23,7 +25,6 @@ use rustc_middle::{bug, span_bug}; use rustc_span::def_id::DefId; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; -use std::fmt; use crate::errors; @@ -652,7 +653,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { debug!(?bounds, ?lifetime, "TraitObject"); let scope = Scope::TraitRefBoundary { s: self.scope }; self.with(scope, |this| { - for bound in bounds { + for (bound, _) in bounds { this.visit_poly_trait_ref_inner( bound, NonLifetimeBinderAllowed::Deny("trait object types"), diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 9affd654366f1..8cb4ba6c6691d 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -1,4 +1,5 @@ use core::ops::ControlFlow; + use rustc_errors::{Applicability, StashKey}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -6,17 +7,15 @@ use rustc_hir::HirId; use rustc_middle::query::plumbing::CyclePlaceholder; use rustc_middle::ty::print::with_forced_trimmed_paths; use rustc_middle::ty::util::IntTypeExt; -use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, Article, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::Ident; use rustc_span::{Span, DUMMY_SP}; +use super::{bad_placeholder, ItemCtxt}; use crate::errors::TypeofReservedKeywordUsed; use crate::hir_ty_lowering::HirTyLowerer; -use super::bad_placeholder; -use super::ItemCtxt; - mod opaque; fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { @@ -35,6 +34,20 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { let parent_node_id = tcx.parent_hir_id(hir_id); let parent_node = tcx.hir_node(parent_node_id); + let find_sym_fn = |&(op, op_sp)| match op { + hir::InlineAsmOperand::SymFn { anon_const } if anon_const.hir_id == hir_id => { + Some((anon_const, op_sp)) + } + _ => None, + }; + + let find_const = |&(op, op_sp)| match op { + hir::InlineAsmOperand::Const { anon_const } if anon_const.hir_id == hir_id => { + Some((anon_const, op_sp)) + } + _ => None, + }; + match parent_node { // Anon consts "inside" the type system. Node::ConstArg(&ConstArg { @@ -46,13 +59,51 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { // Anon consts outside the type system. Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. }) | Node::Item(&Item { kind: ItemKind::GlobalAsm(asm), .. }) - if asm.operands.iter().any(|(op, _op_sp)| match op { - hir::InlineAsmOperand::Const { anon_const } - | hir::InlineAsmOperand::SymFn { anon_const } => anon_const.hir_id == hir_id, - _ => false, - }) => + if let Some((anon_const, op_sp)) = asm.operands.iter().find_map(find_sym_fn) => { - tcx.typeck(def_id).node_type(hir_id) + let ty = tcx.typeck(def_id).node_type(hir_id); + + match ty.kind() { + ty::Error(_) => ty, + ty::FnDef(..) => ty, + _ => { + let guar = tcx + .dcx() + .struct_span_err(op_sp, "invalid `sym` operand") + .with_span_label( + tcx.def_span(anon_const.def_id), + format!("is {} `{}`", ty.kind().article(), ty), + ) + .with_help("`sym` operands must refer to either a function or a static") + .emit(); + + Ty::new_error(tcx, guar) + } + } + } + Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. }) + | Node::Item(&Item { kind: ItemKind::GlobalAsm(asm), .. }) + if let Some((anon_const, op_sp)) = asm.operands.iter().find_map(find_const) => + { + let ty = tcx.typeck(def_id).node_type(hir_id); + + match ty.kind() { + ty::Error(_) => ty, + ty::Int(_) | ty::Uint(_) => ty, + _ => { + let guar = tcx + .dcx() + .struct_span_err(op_sp, "invalid type for `const` operand") + .with_span_label( + tcx.def_span(anon_const.def_id), + format!("is {} `{}`", ty.kind().article(), ty), + ) + .with_help("`const` operands must be of an integer type") + .emit(); + + Ty::new_error(tcx, guar) + } + } } Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => { tcx.adt_def(tcx.hir().get_parent_item(hir_id)).repr().discr_type().to_ty(tcx) diff --git a/compiler/rustc_hir_analysis/src/delegation.rs b/compiler/rustc_hir_analysis/src/delegation.rs new file mode 100644 index 0000000000000..ca62ef92b83de --- /dev/null +++ b/compiler/rustc_hir_analysis/src/delegation.rs @@ -0,0 +1,259 @@ +use rustc_data_structures::fx::FxHashMap; +use rustc_hir::def::DefKind; +use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; +use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_span::ErrorGuaranteed; +use rustc_type_ir::visit::TypeVisitableExt; + +type RemapTable = FxHashMap; + +struct ParamIndexRemapper<'tcx> { + tcx: TyCtxt<'tcx>, + remap_table: RemapTable, +} + +impl<'tcx> TypeFolder> for ParamIndexRemapper<'tcx> { + fn cx(&self) -> TyCtxt<'tcx> { + self.tcx + } + + fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { + if !ty.has_param() { + return ty; + } + + if let ty::Param(param) = ty.kind() + && let Some(index) = self.remap_table.get(¶m.index) + { + return Ty::new_param(self.tcx, *index, param.name); + } + ty.super_fold_with(self) + } + + fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { + if let ty::ReEarlyParam(param) = r.kind() + && let Some(index) = self.remap_table.get(¶m.index).copied() + { + return ty::Region::new_early_param( + self.tcx, + ty::EarlyParamRegion { index, name: param.name }, + ); + } + r + } + + fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> { + if let ty::ConstKind::Param(param) = ct.kind() + && let Some(idx) = self.remap_table.get(¶m.index) + { + let param = ty::ParamConst::new(*idx, param.name); + return ty::Const::new_param(self.tcx, param); + } + ct.super_fold_with(self) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum FnKind { + Free, + AssocInherentImpl, + AssocTrait, + AssocTraitImpl, +} + +fn fn_kind<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> FnKind { + debug_assert!(matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn)); + + let parent = tcx.parent(def_id); + match tcx.def_kind(parent) { + DefKind::Trait => FnKind::AssocTrait, + DefKind::Impl { of_trait: true } => FnKind::AssocTraitImpl, + DefKind::Impl { of_trait: false } => FnKind::AssocInherentImpl, + _ => FnKind::Free, + } +} + +fn create_generic_args<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: LocalDefId, + sig_id: DefId, +) -> ty::GenericArgsRef<'tcx> { + let caller_generics = tcx.generics_of(def_id); + let callee_generics = tcx.generics_of(sig_id); + + let caller_kind = fn_kind(tcx, def_id.into()); + let callee_kind = fn_kind(tcx, sig_id); + // FIXME(fn_delegation): Support generics on associated delegation items. + // Error will be reported in `check_constraints`. + match (caller_kind, callee_kind) { + (FnKind::Free, _) => { + // Lifetime parameters must be declared before type and const parameters. + // Therefore, When delegating from a free function to a associated function, + // generic parameters need to be reordered: + // + // trait Trait<'a, A> { + // fn foo<'b, B>(...) {...} + // } + // + // reuse Trait::foo; + // desugaring: + // fn foo<'a, 'b, This: Trait<'a, A>, A, B>(...) { + // Trait::foo(...) + // } + let mut remap_table = RemapTable::default(); + for caller_param in &caller_generics.own_params { + let callee_index = + callee_generics.param_def_id_to_index(tcx, caller_param.def_id).unwrap(); + remap_table.insert(callee_index, caller_param.index); + } + let mut folder = ParamIndexRemapper { tcx, remap_table }; + ty::GenericArgs::identity_for_item(tcx, sig_id).fold_with(&mut folder) + } + // FIXME(fn_delegation): Only `Self` param supported here. + (FnKind::AssocTraitImpl, FnKind::AssocTrait) + | (FnKind::AssocInherentImpl, FnKind::AssocTrait) => { + let parent = tcx.parent(def_id.into()); + let self_ty = tcx.type_of(parent).instantiate_identity(); + let generic_self_ty = ty::GenericArg::from(self_ty); + tcx.mk_args_from_iter(std::iter::once(generic_self_ty)) + } + _ => ty::GenericArgs::identity_for_item(tcx, sig_id), + } +} + +pub(crate) fn inherit_generics_for_delegation_item<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: LocalDefId, + sig_id: DefId, +) -> Option { + // FIXME(fn_delegation): Support generics on associated delegation items. + // Error will be reported in `check_constraints`. + if fn_kind(tcx, def_id.into()) != FnKind::Free { + return None; + } + + let mut own_params = vec![]; + + let callee_generics = tcx.generics_of(sig_id); + if let Some(parent_sig_id) = callee_generics.parent { + let parent_sig_generics = tcx.generics_of(parent_sig_id); + own_params.append(&mut parent_sig_generics.own_params.clone()); + } + own_params.append(&mut callee_generics.own_params.clone()); + + // Lifetimes go first. + own_params.sort_by_key(|key| key.kind.is_ty_or_const()); + + for (idx, param) in own_params.iter_mut().enumerate() { + param.index = idx as u32; + // Default parameters are not inherited: they are not allowed + // in fn's. + if let ty::GenericParamDefKind::Type { has_default, .. } + | ty::GenericParamDefKind::Const { has_default, .. } = &mut param.kind + { + *has_default = false; + } + } + + let param_def_id_to_index = + own_params.iter().map(|param| (param.def_id, param.index)).collect(); + + Some(ty::Generics { + parent: None, + parent_count: 0, + own_params, + param_def_id_to_index, + has_self: false, + has_late_bound_regions: callee_generics.has_late_bound_regions, + host_effect_index: callee_generics.host_effect_index, + }) +} + +pub(crate) fn inherit_predicates_for_delegation_item<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: LocalDefId, + sig_id: DefId, +) -> Option> { + // FIXME(fn_delegation): Support generics on associated delegation items. + // Error will be reported in `check_constraints`. + if fn_kind(tcx, def_id.into()) != FnKind::Free { + return None; + } + + let callee_predicates = tcx.predicates_of(sig_id); + let args = create_generic_args(tcx, def_id, sig_id); + + let mut preds = vec![]; + if let Some(parent_id) = callee_predicates.parent { + preds.extend(tcx.predicates_of(parent_id).instantiate_own(tcx, args)); + } + preds.extend(callee_predicates.instantiate_own(tcx, args)); + + Some(ty::GenericPredicates { + parent: None, + predicates: tcx.arena.alloc_from_iter(preds), + effects_min_tys: ty::List::empty(), + }) +} + +fn check_constraints<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: LocalDefId, + sig_id: DefId, +) -> Result<(), ErrorGuaranteed> { + let mut ret = Ok(()); + + let mut emit = |descr| { + ret = Err(tcx.dcx().emit_err(crate::errors::UnsupportedDelegation { + span: tcx.def_span(def_id), + descr, + callee_span: tcx.def_span(sig_id), + })); + }; + + if tcx.has_host_param(sig_id) { + emit("delegation to a function with effect parameter is not supported yet"); + } + + if let Some(local_sig_id) = sig_id.as_local() + && tcx.hir().opt_delegation_sig_id(local_sig_id).is_some() + { + emit("recursive delegation is not supported yet"); + } + + if fn_kind(tcx, def_id.into()) != FnKind::Free { + let sig_generics = tcx.generics_of(sig_id); + let parent = tcx.parent(def_id.into()); + let parent_generics = tcx.generics_of(parent); + + let parent_has_self = parent_generics.has_self as usize; + let sig_has_self = sig_generics.has_self as usize; + + if sig_generics.count() > sig_has_self || parent_generics.count() > parent_has_self { + emit("early bound generics are not supported for associated delegation items"); + } + } + + ret +} + +pub(crate) fn inherit_sig_for_delegation_item<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: LocalDefId, +) -> &'tcx [Ty<'tcx>] { + let sig_id = tcx.hir().opt_delegation_sig_id(def_id).unwrap(); + let caller_sig = tcx.fn_sig(sig_id); + if let Err(err) = check_constraints(tcx, def_id, sig_id) { + let sig_len = caller_sig.instantiate_identity().skip_binder().inputs().len() + 1; + let err_type = Ty::new_error(tcx, err); + return tcx.arena.alloc_from_iter((0..sig_len).map(|_| err_type)); + } + let args = create_generic_args(tcx, def_id, sig_id); + + // Bound vars are also inherited from `sig_id`. + // They will be rebound later in `lower_fn_ty`. + let sig = caller_sig.instantiate(tcx, args).skip_binder(); + let sig_iter = sig.inputs().iter().cloned().chain(std::iter::once(sig.output())); + tcx.arena.alloc_from_iter(sig_iter) +} diff --git a/compiler/rustc_hir_analysis/src/errors.rs b/compiler/rustc_hir_analysis/src/errors.rs index c83788928a978..7034735aec038 100644 --- a/compiler/rustc_hir_analysis/src/errors.rs +++ b/compiler/rustc_hir_analysis/src/errors.rs @@ -1,12 +1,15 @@ //! Errors emitted by `rustc_hir_analysis`. -use crate::fluent_generated as fluent; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, MultiSpan, + Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, MultiSpan, }; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::Ty; -use rustc_span::{symbol::Ident, Span, Symbol}; +use rustc_span::symbol::Ident; +use rustc_span::{Span, Symbol}; + +use crate::fluent_generated as fluent; mod pattern_types; pub use pattern_types::*; pub mod wrong_number_of_generic_args; @@ -22,7 +25,7 @@ pub struct AmbiguousAssocItem<'a> { pub span: Span, pub assoc_kind: &'static str, pub assoc_name: Ident, - pub ty_param_name: &'a str, + pub qself: &'a str, } #[derive(Diagnostic)] @@ -75,7 +78,7 @@ pub struct AssocItemNotFound<'a> { pub span: Span, pub assoc_name: Ident, pub assoc_kind: &'static str, - pub ty_param_name: &'a str, + pub qself: &'a str, #[subdiagnostic] pub label: Option>, #[subdiagnostic] @@ -126,13 +129,32 @@ pub enum AssocItemNotFoundSugg<'a> { assoc_kind: &'static str, suggested_name: Symbol, }, - #[suggestion(hir_analysis_assoc_item_not_found_other_sugg, code = "{suggested_name}")] + #[multipart_suggestion( + hir_analysis_assoc_item_not_found_similar_in_other_trait_qpath_sugg, + style = "verbose" + )] + SimilarInOtherTraitQPath { + #[suggestion_part(code = "<")] + lo: Span, + #[suggestion_part(code = " as {trait_ref}>")] + mi: Span, + #[suggestion_part(code = "{suggested_name}")] + hi: Option, + trait_ref: String, + suggested_name: Symbol, + identically_named: bool, + #[applicability] + applicability: Applicability, + }, + #[suggestion( + hir_analysis_assoc_item_not_found_other_sugg, + code = "{suggested_name}", + applicability = "maybe-incorrect" + )] Other { #[primary_span] span: Span, - #[applicability] - applicability: Applicability, - ty_param_name: &'a str, + qself: &'a str, assoc_kind: &'static str, suggested_name: Symbol, }, @@ -1553,7 +1575,7 @@ pub struct RefOfMutStatic<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_not_supported_delegation)] -pub struct NotSupportedDelegation<'a> { +pub struct UnsupportedDelegation<'a> { #[primary_span] pub span: Span, pub descr: &'a str, diff --git a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs index 10be69a9fbb85..8ecf53bfacb94 100644 --- a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs +++ b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs @@ -1,11 +1,10 @@ -use rustc_errors::{ - codes::*, pluralize, Applicability, Diag, Diagnostic, EmissionGuarantee, MultiSpan, -}; +use std::iter; + +use rustc_errors::codes::*; +use rustc_errors::{pluralize, Applicability, Diag, Diagnostic, EmissionGuarantee, MultiSpan}; use rustc_hir as hir; use rustc_middle::ty::{self as ty, AssocItems, AssocKind, TyCtxt}; use rustc_span::def_id::DefId; -use std::iter; - use GenericArgsInfo::*; /// Handles the `wrong number of type / lifetime / ... arguments` family of error messages. @@ -888,7 +887,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { let comma = if args.len() > 0 { ", " } else { "" }; let trait_path = self.tcx.def_path_str(trait_def_id); let method_name = self.tcx.item_name(self.def_id); - err.span_suggestion( + err.span_suggestion_verbose( expr.span, msg, format!("{trait_path}::{generics}::{method_name}({rcvr}{comma}{rest})"), @@ -939,18 +938,20 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { } } - let span_lo_redundant_lt_args = lt_arg_spans[self.num_expected_lifetime_args()]; + let span_lo_redundant_lt_args = if self.num_expected_lifetime_args() == 0 { + lt_arg_spans[0] + } else { + lt_arg_spans[self.num_expected_lifetime_args() - 1] + }; let span_hi_redundant_lt_args = lt_arg_spans[lt_arg_spans.len() - 1]; - let span_redundant_lt_args = span_lo_redundant_lt_args.to(span_hi_redundant_lt_args); + let span_redundant_lt_args = + span_lo_redundant_lt_args.shrink_to_hi().to(span_hi_redundant_lt_args); debug!("span_redundant_lt_args: {:?}", span_redundant_lt_args); let num_redundant_lt_args = lt_arg_spans.len() - self.num_expected_lifetime_args(); - let msg_lifetimes = format!( - "remove {these} lifetime argument{s}", - these = pluralize!("this", num_redundant_lt_args), - s = pluralize!(num_redundant_lt_args), - ); + let msg_lifetimes = + format!("remove the lifetime argument{s}", s = pluralize!(num_redundant_lt_args)); err.span_suggestion( span_redundant_lt_args, @@ -979,18 +980,22 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { } let span_lo_redundant_type_or_const_args = - gen_arg_spans[self.num_expected_type_or_const_args()]; + if self.num_expected_type_or_const_args() == 0 { + gen_arg_spans[0] + } else { + gen_arg_spans[self.num_expected_type_or_const_args() - 1] + }; let span_hi_redundant_type_or_const_args = gen_arg_spans[gen_arg_spans.len() - 1]; + let span_redundant_type_or_const_args = span_lo_redundant_type_or_const_args + .shrink_to_hi() + .to(span_hi_redundant_type_or_const_args); - let span_redundant_type_or_const_args = - span_lo_redundant_type_or_const_args.to(span_hi_redundant_type_or_const_args); debug!("span_redundant_type_or_const_args: {:?}", span_redundant_type_or_const_args); let num_redundant_gen_args = gen_arg_spans.len() - self.num_expected_type_or_const_args(); let msg_types_or_consts = format!( - "remove {these} generic argument{s}", - these = pluralize!("this", num_redundant_gen_args), + "remove the unnecessary generic argument{s}", s = pluralize!(num_redundant_gen_args), ); @@ -1036,7 +1041,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { .with_lo(self.path_segment.ident.span.hi()); let msg = format!( - "remove these {}generics", + "remove the unnecessary {}generics", if self.gen_args.parenthesized == hir::GenericArgsParentheses::ParenSugar { "parenthetical " } else { 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 6f9c481650b21..7f4c75d3a6a21 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -1,24 +1,24 @@ use std::ops::ControlFlow; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; -use rustc_errors::{codes::*, struct_span_code_err}; +use rustc_errors::codes::*; +use rustc_errors::struct_span_code_err; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::bug; -use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::{self as ty, IsSuggestable, Ty, TyCtxt}; use rustc_span::symbol::Ident; -use rustc_span::{ErrorGuaranteed, Span, Symbol}; +use rustc_span::{sym, ErrorGuaranteed, Span, Symbol}; use rustc_trait_selection::traits; use rustc_type_ir::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; use smallvec::SmallVec; use crate::bounds::Bounds; use crate::errors; -use crate::hir_ty_lowering::{HirTyLowerer, OnlySelfBounds, PredicateFilter}; - -use super::RegionInferReason; +use crate::hir_ty_lowering::{ + AssocItemQSelf, HirTyLowerer, OnlySelfBounds, PredicateFilter, RegionInferReason, +}; impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// Add a `Sized` bound to the `bounds` if appropriate. @@ -75,10 +75,22 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } + 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); + } + } if unbounds.len() > 1 { - self.dcx().emit_err(errors::MultipleRelaxedDefaultBounds { + let err = errors::MultipleRelaxedDefaultBounds { spans: unbounds.iter().map(|ptr| ptr.span).collect(), - }); + }; + if seen_repeat { + self.dcx().emit_err(err); + } else if !tcx.features().more_maybe_bounds { + self.tcx().sess.create_feature_err(err, sym::more_maybe_bounds).emit(); + }; } let mut seen_sized_unbound = false; @@ -288,8 +300,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // one that does define it. self.probe_single_bound_for_assoc_item( || traits::supertraits(tcx, trait_ref), - trait_ref.skip_binder().print_only_trait_name(), - None, + AssocItemQSelf::Trait(trait_ref.def_id()), assoc_kind, constraint.ident, path_span, 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 8ff6ced8b3983..d77cbe3053653 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -1,36 +1,35 @@ -use crate::errors::{ - self, AssocItemConstraintsNotAllowedHere, ManualImplementation, MissingTypeParams, - ParenthesizedFnTraitExpansion, TraitObjectDeclaredWithNoTraits, -}; -use crate::fluent_generated as fluent; -use crate::hir_ty_lowering::HirTyLowerer; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::unord::UnordMap; -use rustc_errors::MultiSpan; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, + pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan, }; +use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_hir::{self as hir, Node}; +use rustc_hir::def_id::DefId; use rustc_middle::bug; use rustc_middle::query::Key; use rustc_middle::ty::print::{PrintPolyTraitRefExt as _, PrintTraitRefExt as _}; -use rustc_middle::ty::GenericParamDefKind; -use rustc_middle::ty::{self, suggest_constraining_type_param}; -use rustc_middle::ty::{AdtDef, Ty, TyCtxt, TypeVisitableExt}; -use rustc_middle::ty::{Binder, TraitRef}; +use rustc_middle::ty::{ + self, suggest_constraining_type_param, AdtDef, Binder, GenericParamDefKind, TraitRef, Ty, + TyCtxt, TypeVisitableExt, +}; use rustc_session::parse::feature_err; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::BytePos; -use rustc_span::{Span, Symbol, DUMMY_SP}; +use rustc_span::{BytePos, Span, Symbol, DUMMY_SP}; use rustc_trait_selection::error_reporting::traits::report_object_safety_error; -use rustc_trait_selection::traits::FulfillmentError; use rustc_trait_selection::traits::{ - object_safety_violations_for_assoc_item, TraitAliasExpansionInfo, + object_safety_violations_for_assoc_item, FulfillmentError, TraitAliasExpansionInfo, +}; + +use crate::errors::{ + self, AssocItemConstraintsNotAllowedHere, ManualImplementation, MissingTypeParams, + ParenthesizedFnTraitExpansion, TraitObjectDeclaredWithNoTraits, }; +use crate::fluent_generated as fluent; +use crate::hir_ty_lowering::{AssocItemQSelf, HirTyLowerer}; impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// On missing type parameters, emit an E0393 error and provide a structured suggestion using @@ -116,8 +115,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { pub(super) fn complain_about_assoc_item_not_found( &self, all_candidates: impl Fn() -> I, - ty_param_name: &str, - ty_param_def_id: Option, + qself: AssocItemQSelf, assoc_kind: ty::AssocKind, assoc_name: Ident, span: Span, @@ -139,7 +137,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ); } - let assoc_kind_str = super::assoc_kind_str(assoc_kind); + let assoc_kind_str = assoc_kind_str(assoc_kind); + let qself_str = qself.to_string(tcx); // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a // valid span, so we point at the whole path segment instead. @@ -149,7 +148,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { span: if is_dummy { span } else { assoc_name.span }, assoc_name, assoc_kind: assoc_kind_str, - ty_param_name, + qself: &qself_str, label: None, sugg: None, }; @@ -219,19 +218,28 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { suggested_name, identically_named: suggested_name == assoc_name.name, }); - let hir = tcx.hir(); - if let Some(def_id) = ty_param_def_id - && let parent = hir.get_parent_item(tcx.local_def_id_to_hir_id(def_id)) - && let Some(generics) = hir.get_generics(parent.def_id) + if let AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span) = qself + // Not using `self.item_def_id()` here as that would yield the opaque type itself if we're + // inside an opaque type while we're interested in the overarching type alias (TAIT). + // FIXME: However, for trait aliases, this incorrectly returns the enclosing module... + && let item_def_id = + tcx.hir().get_parent_item(tcx.local_def_id_to_hir_id(ty_param_def_id)) + // FIXME: ...which obviously won't have any generics. + && let Some(generics) = tcx.hir().get_generics(item_def_id.def_id) { - if generics.bounds_for_param(def_id).flat_map(|pred| pred.bounds.iter()).any( - |b| match b { + // FIXME: Suggest adding supertrait bounds if we have a `Self` type param. + // FIXME(trait_alias): Suggest adding `Self: Trait` to + // `trait Alias = where Self::Proj:;` with `trait Trait { type Proj; }`. + if generics + .bounds_for_param(ty_param_def_id) + .flat_map(|pred| pred.bounds.iter()) + .any(|b| match b { hir::GenericBound::Trait(t, ..) => { t.trait_ref.trait_def_id() == Some(best_trait) } _ => false, - }, - ) { + }) + { // The type param already has a bound for `trait_name`, we just need to // change the associated item. err.sugg = Some(errors::AssocItemNotFoundSugg::SimilarInOtherTrait { @@ -242,48 +250,60 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { return self.dcx().emit_err(err); } - let mut err = self.dcx().create_err(err); - if suggest_constraining_type_param( - tcx, - generics, - &mut err, - &ty_param_name, - &trait_name, - None, - None, - ) && suggested_name != assoc_name.name + let trait_args = &ty::GenericArgs::identity_for_item(tcx, best_trait)[1..]; + let mut trait_ref = trait_name.clone(); + let applicability = if let [arg, args @ ..] = trait_args { + use std::fmt::Write; + write!(trait_ref, ""; + Applicability::HasPlaceholders + } else { + Applicability::MaybeIncorrect + }; + + let identically_named = suggested_name == assoc_name.name; + + if let DefKind::TyAlias = tcx.def_kind(item_def_id) + && !tcx.type_alias_is_lazy(item_def_id) { - // We suggested constraining a type parameter, but the associated item on it - // was also not an exact match, so we also suggest changing it. - err.span_suggestion_verbose( - assoc_name.span, - fluent::hir_analysis_assoc_item_not_found_similar_in_other_trait_with_bound_sugg, + err.sugg = Some(errors::AssocItemNotFoundSugg::SimilarInOtherTraitQPath { + lo: ty_param_span.shrink_to_lo(), + mi: ty_param_span.shrink_to_hi(), + hi: (!identically_named).then_some(assoc_name.span), + trait_ref, + identically_named, suggested_name, - Applicability::MaybeIncorrect, - ); + applicability, + }); + } else { + let mut err = self.dcx().create_err(err); + if suggest_constraining_type_param( + tcx, generics, &mut err, &qself_str, &trait_ref, None, None, + ) && !identically_named + { + // We suggested constraining a type parameter, but the associated item on it + // was also not an exact match, so we also suggest changing it. + err.span_suggestion_verbose( + assoc_name.span, + fluent::hir_analysis_assoc_item_not_found_similar_in_other_trait_with_bound_sugg, + suggested_name, + Applicability::MaybeIncorrect, + ); + } + return err.emit(); } - return err.emit(); } return self.dcx().emit_err(err); } } // If we still couldn't find any associated item, and only one associated item exists, - // suggests using it. + // suggest using it. if let [candidate_name] = all_candidate_names.as_slice() { - // This should still compile, except on `#![feature(associated_type_defaults)]` - // where it could suggests `type A = Self::A`, thus recursing infinitely. - let applicability = - if assoc_kind == ty::AssocKind::Type && tcx.features().associated_type_defaults { - Applicability::Unspecified - } else { - Applicability::MaybeIncorrect - }; - err.sugg = Some(errors::AssocItemNotFoundSugg::Other { span: assoc_name.span, - applicability, - ty_param_name, + qself: &qself_str, assoc_kind: assoc_kind_str, suggested_name: *candidate_name, }); @@ -349,10 +369,10 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { self.dcx().emit_err(errors::AssocKindMismatch { span, - expected: super::assoc_kind_str(expected), - got: super::assoc_kind_str(got), + expected: assoc_kind_str(expected), + got: assoc_kind_str(got), expected_because_label, - assoc_kind: super::assoc_kind_str(assoc_item.kind), + assoc_kind: assoc_kind_str(assoc_item.kind), def_span: tcx.def_span(assoc_item.def_id), bound_on_assoc_const_label, wrap_in_braces_sugg, @@ -698,7 +718,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { &self, associated_types: FxIndexMap>, potential_assoc_types: Vec, - trait_bounds: &[hir::PolyTraitRef<'_>], + trait_bounds: &[(hir::PolyTraitRef<'_>, hir::TraitBoundModifier)], ) { if associated_types.values().all(|v| v.is_empty()) { return; @@ -744,12 +764,12 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // related to issue #91997, turbofishes added only when in an expr or pat let mut in_expr_or_pat = false; if let ([], [bound]) = (&potential_assoc_types[..], &trait_bounds) { - let grandparent = tcx.parent_hir_node(tcx.parent_hir_id(bound.trait_ref.hir_ref_id)); + let grandparent = tcx.parent_hir_node(tcx.parent_hir_id(bound.0.trait_ref.hir_ref_id)); in_expr_or_pat = match grandparent { - Node::Expr(_) | Node::Pat(_) => true, + hir::Node::Expr(_) | hir::Node::Pat(_) => true, _ => false, }; - match bound.trait_ref.path.segments { + match bound.0.trait_ref.path.segments { // FIXME: `trait_ref.path.span` can point to a full path with multiple // segments, even though `trait_ref.path.segments` is of length `1`. Work // around that bug here, even though it should be fixed elsewhere. @@ -790,7 +810,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // and we can then use their span to indicate this to the user. let bound_names = trait_bounds .iter() - .filter_map(|poly_trait_ref| { + .filter_map(|(poly_trait_ref, _)| { let path = poly_trait_ref.trait_ref.path.segments.last()?; let args = path.args?; @@ -1612,3 +1632,11 @@ fn generics_args_err_extend<'a>( _ => {} } } + +pub(super) fn assoc_kind_str(kind: ty::AssocKind) -> &'static str { + match kind { + ty::AssocKind::Fn => "function", + ty::AssocKind::Const => "constant", + ty::AssocKind::Type => "type", + } +} 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 abe2cff321f76..f18224c39ae49 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs @@ -1,13 +1,6 @@ -use super::{HirTyLowerer, IsMethodCall}; -use crate::errors::wrong_number_of_generic_args::{GenericArgsInfo, WrongNumberOfGenericArgs}; -use crate::hir_ty_lowering::{ - errors::prohibit_assoc_item_constraint, ExplicitLateBound, GenericArgCountMismatch, - GenericArgCountResult, GenericArgPosition, GenericArgsLowerer, -}; use rustc_ast::ast::ParamKindOrd; -use rustc_errors::{ - codes::*, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan, -}; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; @@ -19,6 +12,14 @@ use rustc_session::lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS; use rustc_span::symbol::{kw, sym}; use smallvec::SmallVec; +use super::{HirTyLowerer, IsMethodCall}; +use crate::errors::wrong_number_of_generic_args::{GenericArgsInfo, WrongNumberOfGenericArgs}; +use crate::hir_ty_lowering::errors::prohibit_assoc_item_constraint; +use crate::hir_ty_lowering::{ + ExplicitLateBound, GenericArgCountMismatch, GenericArgCountResult, GenericArgPosition, + GenericArgsLowerer, +}; + /// Report an error that a generic argument did not match the generic parameter that was /// expected. fn generic_arg_mismatch_err( diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs index 29c71c3fa50b5..6aff518390ffc 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs @@ -1,8 +1,10 @@ use rustc_ast::TraitObjectSyntax; -use rustc_errors::{codes::*, Diag, EmissionGuarantee, StashKey}; +use rustc_errors::codes::*; +use rustc_errors::{Diag, EmissionGuarantee, StashKey}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_lint_defs::{builtin::BARE_TRAIT_OBJECTS, Applicability}; +use rustc_lint_defs::builtin::BARE_TRAIT_OBJECTS; +use rustc_lint_defs::Applicability; use rustc_span::Span; use rustc_trait_selection::error_reporting::traits::suggestions::NextTypeParamName; @@ -34,7 +36,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { .ok() .is_some_and(|s| s.trim_end().ends_with('<')); - let is_global = poly_trait_ref.trait_ref.path.is_global(); + let is_global = poly_trait_ref.0.trait_ref.path.is_global(); let mut sugg = vec![( self_ty.span.shrink_to_lo(), @@ -176,7 +178,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let mut is_downgradable = true; let is_object_safe = match self_ty.kind { hir::TyKind::TraitObject(objects, ..) => { - objects.iter().all(|o| match o.trait_ref.path.res { + objects.iter().all(|(o, _)| match o.trait_ref.path.res { Res::Def(DefKind::Trait, id) => { if Some(id) == owner { // For recursive traits, don't downgrade the error. (#119652) 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 d6eb1a66902fc..d865357b82900 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -20,17 +20,13 @@ pub mod generics; mod lint; mod object_safety; -use crate::bounds::Bounds; -use crate::errors::{AmbiguousLifetimeBound, WildPatTy}; -use crate::hir_ty_lowering::errors::{prohibit_assoc_item_constraint, GenericsArgsErrExtend}; -use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args}; -use crate::middle::resolve_bound_vars as rbv; -use crate::require_c_abi_if_c_variadic; +use std::slice; + use rustc_ast::TraitObjectSyntax; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, struct_span_code_err, Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, - FatalError, + struct_span_code_err, Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, }; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Namespace, Res}; @@ -55,8 +51,12 @@ use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::wf::object_region_bounds; use rustc_trait_selection::traits::{self, ObligationCtxt}; -use std::fmt::Display; -use std::slice; +use crate::bounds::Bounds; +use crate::errors::{AmbiguousLifetimeBound, WildPatTy}; +use crate::hir_ty_lowering::errors::{prohibit_assoc_item_constraint, GenericsArgsErrExtend}; +use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args}; +use crate::middle::resolve_bound_vars as rbv; +use crate::require_c_abi_if_c_variadic; /// A path segment that is semantically allowed to have generic arguments. #[derive(Debug)] @@ -193,6 +193,25 @@ pub trait HirTyLowerer<'tcx> { } } +/// The "qualified self" of an associated item path. +/// +/// For diagnostic purposes only. +enum AssocItemQSelf { + Trait(DefId), + TyParam(LocalDefId, Span), + SelfTyAlias, +} + +impl AssocItemQSelf { + fn to_string(&self, tcx: TyCtxt<'_>) -> String { + match *self { + Self::Trait(def_id) => tcx.def_path_str(def_id), + Self::TyParam(def_id, _) => tcx.hir().ty_param_name(def_id).to_string(), + Self::SelfTyAlias => kw::SelfUpper.to_string(), + } + } +} + /// New-typed boolean indicating whether explicit late-bound lifetimes /// are present in a set of generic arguments. /// @@ -802,6 +821,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { fn probe_single_ty_param_bound_for_assoc_ty( &self, ty_param_def_id: LocalDefId, + ty_param_span: Span, assoc_name: Ident, span: Span, ) -> Result, ErrorGuaranteed> { @@ -811,19 +831,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_name).predicates; debug!("predicates={:#?}", predicates); - let param_name = tcx.hir().ty_param_name(ty_param_def_id); self.probe_single_bound_for_assoc_item( || { - traits::transitive_bounds_that_define_assoc_item( - tcx, - predicates - .iter() - .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref))), - assoc_name, - ) + let trait_refs = predicates + .iter() + .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref))); + traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_name) }, - param_name, - Some(ty_param_def_id), + AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span), ty::AssocKind::Type, assoc_name, span, @@ -835,12 +850,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// /// This fails if there is no such bound in the list of candidates or if there are multiple /// candidates in which case it reports ambiguity. - #[instrument(level = "debug", skip(self, all_candidates, ty_param_name, constraint), ret)] + #[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)] fn probe_single_bound_for_assoc_item( &self, all_candidates: impl Fn() -> I, - ty_param_name: impl Display, - ty_param_def_id: Option, + qself: AssocItemQSelf, assoc_kind: ty::AssocKind, assoc_name: Ident, span: Span, @@ -858,8 +872,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let Some(bound) = matching_candidates.next() else { let reported = self.complain_about_assoc_item_not_found( all_candidates, - &ty_param_name.to_string(), - ty_param_def_id, + qself, assoc_kind, assoc_name, span, @@ -872,13 +885,13 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { if let Some(bound2) = matching_candidates.next() { debug!(?bound2); - let assoc_kind_str = assoc_kind_str(assoc_kind); - let ty_param_name = &ty_param_name.to_string(); + let assoc_kind_str = errors::assoc_kind_str(assoc_kind); + let qself_str = qself.to_string(tcx); let mut err = self.dcx().create_err(crate::errors::AmbiguousAssocItem { span, assoc_kind: assoc_kind_str, assoc_name, - ty_param_name, + qself: &qself_str, }); // Provide a more specific error code index entry for equality bindings. err.code( @@ -929,7 +942,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { err.span_suggestion_verbose( span.with_hi(assoc_name.span.lo()), "use fully-qualified syntax to disambiguate", - format!("<{ty_param_name} as {}>::", bound.print_only_trait_path()), + format!("<{qself_str} as {}>::", bound.print_only_trait_path()), Applicability::MaybeIncorrect, ); } @@ -943,7 +956,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { if !where_bounds.is_empty() { err.help(format!( "consider introducing a new type parameter `T` and adding `where` constraints:\ - \n where\n T: {ty_param_name},\n{}", + \n where\n T: {qself_str},\n{}", where_bounds.join(",\n"), )); } @@ -997,11 +1010,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let tcx = self.tcx(); let assoc_ident = assoc_segment.ident; - let qself_res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &qself.kind { - path.res - } else { - Res::Err - }; // Check if we have an enum variant or an inherent associated type. let mut variant_resolution = None; @@ -1038,6 +1046,12 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } } + let qself_res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &qself.kind { + path.res + } else { + Res::Err + }; + // Find the type of the associated item, and the trait where the associated // item is declared. let bound = match (&qself_ty.kind(), qself_res) { @@ -1056,8 +1070,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ty::Binder::dummy(trait_ref.instantiate_identity()), ) }, - kw::SelfUpper, - None, + AssocItemQSelf::SelfTyAlias, ty::AssocKind::Type, assoc_ident, span, @@ -1069,6 +1082,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did), ) => self.probe_single_ty_param_bound_for_assoc_ty( param_did.expect_local(), + qself.span, assoc_ident, span, )?, @@ -1993,93 +2007,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { self.lower_ty_common(hir_ty, false, true) } - fn check_delegation_constraints(&self, sig_id: DefId, span: Span, emit: bool) -> bool { - let mut error_occured = false; - let sig_span = self.tcx().def_span(sig_id); - let mut try_emit = |descr| { - if emit { - self.dcx().emit_err(crate::errors::NotSupportedDelegation { - span, - descr, - callee_span: sig_span, - }); - } - error_occured = true; - }; - - if let Some(node) = self.tcx().hir().get_if_local(sig_id) - && let Some(decl) = node.fn_decl() - && let hir::FnRetTy::Return(ty) = decl.output - && let hir::TyKind::InferDelegation(_, _) = ty.kind - { - try_emit("recursive delegation"); - } - - let sig_generics = self.tcx().generics_of(sig_id); - let parent = self.tcx().local_parent(self.item_def_id()); - let parent_generics = self.tcx().generics_of(parent); - - let parent_is_trait = (self.tcx().def_kind(parent) == DefKind::Trait) as usize; - let sig_has_self = sig_generics.has_self as usize; - - if sig_generics.count() > sig_has_self || parent_generics.count() > parent_is_trait { - try_emit("delegation with early bound generics"); - } - - // There is no way to instantiate `Self` param for caller if - // 1. callee is a trait method - // 2. delegation item isn't an associative item - if let DefKind::AssocFn = self.tcx().def_kind(sig_id) - && let DefKind::Fn = self.tcx().def_kind(self.item_def_id()) - && self.tcx().associated_item(sig_id).container - == ty::AssocItemContainer::TraitContainer - { - try_emit("delegation to a trait method from a free function"); - } - - error_occured - } - - fn lower_delegation_ty( - &self, - sig_id: DefId, - idx: hir::InferDelegationKind, - span: Span, - ) -> Ty<'tcx> { - if self.check_delegation_constraints(sig_id, span, idx == hir::InferDelegationKind::Output) - { - let e = self.dcx().span_delayed_bug(span, "not supported delegation case"); - return Ty::new_error(self.tcx(), e); - }; - let sig = self.tcx().fn_sig(sig_id); - let sig_generics = self.tcx().generics_of(sig_id); - - let parent = self.tcx().local_parent(self.item_def_id()); - let parent_def_kind = self.tcx().def_kind(parent); - - let sig = if let DefKind::Impl { .. } = parent_def_kind - && sig_generics.has_self - { - // Generic params can't be here except the trait self type. - // They are not supported yet. - assert_eq!(sig_generics.count(), 1); - assert_eq!(self.tcx().generics_of(parent).count(), 0); - - let self_ty = self.tcx().type_of(parent).instantiate_identity(); - let generic_self_ty = ty::GenericArg::from(self_ty); - let args = self.tcx().mk_args_from_iter(std::iter::once(generic_self_ty)); - sig.instantiate(self.tcx(), args) - } else { - sig.instantiate_identity() - }; - - // Bound vars are also inherited from `sig_id`. - // They will be rebound later in `lower_fn_ty`. - let sig = sig.skip_binder(); - + fn lower_delegation_ty(&self, idx: hir::InferDelegationKind) -> Ty<'tcx> { + let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id()); match idx { - hir::InferDelegationKind::Input(id) => sig.inputs()[id], - hir::InferDelegationKind::Output => sig.output(), + hir::InferDelegationKind::Input(idx) => delegation_sig[idx], + hir::InferDelegationKind::Output => *delegation_sig.last().unwrap(), } } @@ -2096,9 +2028,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let tcx = self.tcx(); let result_ty = match &hir_ty.kind { - hir::TyKind::InferDelegation(sig_id, idx) => { - self.lower_delegation_ty(*sig_id, *idx, hir_ty.span) - } + hir::TyKind::InferDelegation(_, idx) => self.lower_delegation_ty(*idx), hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)), hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl), hir::TyKind::Ref(region, mt) => { @@ -2522,11 +2452,3 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { Some(r) } } - -fn assoc_kind_str(kind: ty::AssocKind) -> &'static str { - match kind { - ty::AssocKind::Fn => "function", - ty::AssocKind::Const => "constant", - ty::AssocKind::Type => "type", - } -} diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/object_safety.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/object_safety.rs index aafadc7f9cbea..31d1750f33dfd 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/object_safety.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/object_safety.rs @@ -1,24 +1,25 @@ -use crate::bounds::Bounds; -use crate::hir_ty_lowering::{ - GenericArgCountMismatch, GenericArgCountResult, OnlySelfBounds, RegionInferReason, -}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; -use rustc_errors::{codes::*, struct_span_code_err}; +use rustc_errors::codes::*; +use rustc_errors::struct_span_code_err; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_lint_defs::builtin::UNUSED_ASSOCIATED_TYPE_BOUNDS; use rustc_middle::span_bug; use rustc_middle::ty::fold::BottomUpFolder; -use rustc_middle::ty::{self, ExistentialPredicateStableCmpExt as _, Ty, TyCtxt, TypeFoldable}; -use rustc_middle::ty::{DynKind, Upcast}; +use rustc_middle::ty::{ + self, DynKind, ExistentialPredicateStableCmpExt as _, Ty, TyCtxt, TypeFoldable, Upcast, +}; use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::error_reporting::traits::report_object_safety_error; use rustc_trait_selection::traits::{self, hir_ty_lowering_object_safety_violations}; - use smallvec::{smallvec, SmallVec}; use super::HirTyLowerer; +use crate::bounds::Bounds; +use crate::hir_ty_lowering::{ + GenericArgCountMismatch, GenericArgCountResult, OnlySelfBounds, RegionInferReason, +}; impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// Lower a trait object type from the HIR to our internal notion of a type. @@ -27,7 +28,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { &self, span: Span, hir_id: hir::HirId, - hir_trait_bounds: &[hir::PolyTraitRef<'tcx>], + hir_trait_bounds: &[(hir::PolyTraitRef<'tcx>, hir::TraitBoundModifier)], lifetime: &hir::Lifetime, borrowed: bool, representation: DynKind, @@ -37,7 +38,10 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let mut bounds = Bounds::default(); let mut potential_assoc_types = Vec::new(); let dummy_self = self.tcx().types.trait_object_dummy_self; - for trait_bound in hir_trait_bounds.iter().rev() { + for (trait_bound, modifier) in hir_trait_bounds.iter().rev() { + if *modifier == hir::TraitBoundModifier::Maybe { + continue; + } if let GenericArgCountResult { correct: Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }), @@ -249,7 +253,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let args = tcx.mk_args(&args); let span = i.bottom().1; - let empty_generic_args = hir_trait_bounds.iter().any(|hir_bound| { + let empty_generic_args = hir_trait_bounds.iter().any(|(hir_bound, _)| { hir_bound.trait_ref.path.res == Res::Def(DefKind::Trait, trait_ref.def_id) && hir_bound.span.contains(span) }); diff --git a/compiler/rustc_hir_analysis/src/hir_wf_check.rs b/compiler/rustc_hir_analysis/src/hir_wf_check.rs index 13993a1992b7c..7d2cabd3f2c7e 100644 --- a/compiler/rustc_hir_analysis/src/hir_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/hir_wf_check.rs @@ -1,4 +1,3 @@ -use crate::collect::ItemCtxt; use rustc_hir as hir; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{ForeignItem, ForeignItemKind}; @@ -10,6 +9,8 @@ use rustc_middle::ty::{self, TyCtxt}; use rustc_span::def_id::LocalDefId; use rustc_trait_selection::traits::{self, ObligationCtxt}; +use crate::collect::ItemCtxt; + pub fn provide(providers: &mut Providers) { *providers = Providers { diagnostic_hir_wf_check, ..*providers }; } diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check.rs b/compiler/rustc_hir_analysis/src/impl_wf_check.rs index f0fcbd5528f4e..a8ae620f7a49d 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check.rs @@ -8,9 +8,7 @@ //! specialization errors. These things can (and probably should) be //! fixed, but for the moment it's easier to do these checks early. -use crate::{constrained_generic_params as cgp, errors::UnconstrainedGenericParameter}; use min_specialization::check_min_specialization; - use rustc_data_structures::fx::FxHashSet; use rustc_errors::codes::*; use rustc_hir::def::DefKind; @@ -18,6 +16,9 @@ use rustc_hir::def_id::LocalDefId; use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; use rustc_span::ErrorGuaranteed; +use crate::constrained_generic_params as cgp; +use crate::errors::UnconstrainedGenericParameter; + mod min_specialization; /// Checks that all the type/lifetime parameters on an impl also diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs index 2e5f99bb78b22..f44a78bac4de2 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs @@ -65,9 +65,6 @@ //! cause use after frees with purely safe code in the same way as specializing //! on traits with methods can. -use crate::errors::GenericArgsOnOverriddenImpl; -use crate::{constrained_generic_params as cgp, errors}; - use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -75,13 +72,15 @@ use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::specialization_graph::Node; use rustc_middle::ty::trait_def::TraitSpecializationKind; -use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; -use rustc_middle::ty::{GenericArg, GenericArgs, GenericArgsRef}; +use rustc_middle::ty::{self, GenericArg, GenericArgs, GenericArgsRef, TyCtxt, TypeVisitableExt}; use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _; use rustc_trait_selection::traits::{self, translate_args_with_cause, wf, ObligationCtxt}; +use crate::errors::GenericArgsOnOverriddenImpl; +use crate::{constrained_generic_params as cgp, errors}; + pub(super) fn check_min_specialization( tcx: TyCtxt<'_>, impl_def_id: LocalDefId, diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index dd7fbba753bdd..061db14ad0a61 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -64,7 +64,6 @@ This API is completely unstable and subject to change. #![doc(rust_logo)] #![feature(control_flow_enum)] #![feature(if_let_guard)] -#![feature(is_sorted)] #![feature(iter_intersperse)] #![feature(let_chains)] #![feature(never_type)] @@ -84,6 +83,7 @@ pub mod autoderef; mod bounds; mod check_unused; mod coherence; +mod delegation; pub mod hir_ty_lowering; // FIXME: This module shouldn't be public. pub mod collect; @@ -101,7 +101,8 @@ use rustc_middle::mir::interpret::GlobalId; use rustc_middle::query::Providers; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_session::parse::feature_err; -use rustc_span::{symbol::sym, Span}; +use rustc_span::symbol::sym; +use rustc_span::Span; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits; @@ -146,6 +147,10 @@ pub fn provide(providers: &mut Providers) { variance::provide(providers); outlives::provide(providers); hir_wf_check::provide(providers); + *providers = Providers { + inherit_sig_for_delegation_item: delegation::inherit_sig_for_delegation_item, + ..*providers + }; } pub fn check_crate(tcx: TyCtxt<'_>) { diff --git a/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs b/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs index d953736c28c21..454c20d3e6485 100644 --- a/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs +++ b/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs @@ -1,8 +1,7 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_middle::ty::{GenericArg, GenericArgKind}; +use rustc_middle::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt}; use rustc_span::Span; use super::explicit::ExplicitPredicatesMap; diff --git a/compiler/rustc_hir_analysis/src/outlives/mod.rs b/compiler/rustc_hir_analysis/src/outlives/mod.rs index 1f74ebf99f166..cb61ef7c64da0 100644 --- a/compiler/rustc_hir_analysis/src/outlives/mod.rs +++ b/compiler/rustc_hir_analysis/src/outlives/mod.rs @@ -1,8 +1,7 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_middle::query::Providers; -use rustc_middle::ty::GenericArgKind; -use rustc_middle::ty::{self, CratePredicatesMap, TyCtxt, Upcast}; +use rustc_middle::ty::{self, CratePredicatesMap, GenericArgKind, TyCtxt, Upcast}; use rustc_span::Span; pub(crate) mod dump; diff --git a/compiler/rustc_hir_analysis/src/outlives/utils.rs b/compiler/rustc_hir_analysis/src/outlives/utils.rs index 08015c28a26ea..a1eccc91dea82 100644 --- a/compiler/rustc_hir_analysis/src/outlives/utils.rs +++ b/compiler/rustc_hir_analysis/src/outlives/utils.rs @@ -1,6 +1,5 @@ use rustc_data_structures::fx::FxIndexMap; -use rustc_middle::ty::{self, Region, Ty, TyCtxt}; -use rustc_middle::ty::{GenericArg, GenericArgKind}; +use rustc_middle::ty::{self, GenericArg, GenericArgKind, Region, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_span::Span; use rustc_type_ir::outlives::{push_outlives_components, Component}; diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index 0c436e21c16d9..92baa41e07f90 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -6,8 +6,7 @@ use hir::def_id::{DefId, LocalDefId}; use rustc_hir as hir; use rustc_hir::def::DefKind; -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_middle::ty::{GenericArgKind, GenericArgsRef}; +use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use super::terms::VarianceTerm::*; diff --git a/compiler/rustc_hir_analysis/src/variance/mod.rs b/compiler/rustc_hir_analysis/src/variance/mod.rs index 29f96e27b6492..8a4114c3e4bca 100644 --- a/compiler/rustc_hir_analysis/src/variance/mod.rs +++ b/compiler/rustc_hir_analysis/src/variance/mod.rs @@ -9,8 +9,9 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::query::Providers; use rustc_middle::span_bug; -use rustc_middle::ty::{self, CrateVariancesMap, GenericArgsRef, Ty, TyCtxt}; -use rustc_middle::ty::{TypeSuperVisitable, TypeVisitable}; +use rustc_middle::ty::{ + self, CrateVariancesMap, GenericArgsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, +}; /// Defines the `TermsContext` basically houses an arena where we can /// allocate terms. diff --git a/compiler/rustc_hir_analysis/src/variance/terms.rs b/compiler/rustc_hir_analysis/src/variance/terms.rs index 275df24956ccc..36bff60e01978 100644 --- a/compiler/rustc_hir_analysis/src/variance/terms.rs +++ b/compiler/rustc_hir_analysis/src/variance/terms.rs @@ -9,11 +9,12 @@ // `InferredIndex` is a newtype'd int representing the index of such // a variable. +use std::fmt; + use rustc_arena::DroplessArena; use rustc_hir::def::DefKind; use rustc_hir::def_id::{LocalDefId, LocalDefIdMap}; use rustc_middle::ty::{self, TyCtxt}; -use std::fmt; use self::VarianceTerm::*; diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index db5eba0d9ebaf..089cee2fa0dec 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -5,12 +5,13 @@ #![recursion_limit = "256"] // tidy-alphabetical-end -use rustc_ast as ast; +use std::cell::Cell; +use std::vec; + use rustc_ast::util::parser::{self, AssocOp, Fixity}; use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent}; use rustc_ast_pretty::pp::{self, Breaks}; use rustc_ast_pretty::pprust::{Comments, PrintState}; -use rustc_hir as hir; use rustc_hir::{ BindingMode, ByRef, ConstArgKind, GenericArg, GenericBound, GenericParam, GenericParamKind, HirId, LifetimeParamKind, Node, PatKind, PreciseCapturingArg, RangeEnd, Term, @@ -20,9 +21,7 @@ use rustc_span::source_map::SourceMap; use rustc_span::symbol::{kw, Ident, Symbol}; use rustc_span::FileName; use rustc_target::spec::abi::Abi; - -use std::cell::Cell; -use std::vec; +use {rustc_ast as ast, rustc_hir as hir}; pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: HirId) -> String { to_string(&map, |s| s.print_node(map.hir_node(hir_id))) @@ -300,13 +299,16 @@ impl<'a> State<'a> { self.word_space("dyn"); } let mut first = true; - for bound in bounds { + for (bound, modifier) in bounds { if first { first = false; } else { self.nbsp(); self.word_space("+"); } + if *modifier == TraitBoundModifier::Maybe { + self.word("?"); + } self.print_poly_trait_ref(bound); } if !lifetime.is_elided() { @@ -1298,35 +1300,7 @@ impl<'a> State<'a> { AsmArg::Options(opts) => { s.word("options"); s.popen(); - let mut options = vec![]; - if opts.contains(ast::InlineAsmOptions::PURE) { - options.push("pure"); - } - if opts.contains(ast::InlineAsmOptions::NOMEM) { - options.push("nomem"); - } - if opts.contains(ast::InlineAsmOptions::READONLY) { - options.push("readonly"); - } - if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) { - options.push("preserves_flags"); - } - if opts.contains(ast::InlineAsmOptions::NORETURN) { - options.push("noreturn"); - } - if opts.contains(ast::InlineAsmOptions::NOSTACK) { - options.push("nostack"); - } - if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) { - options.push("att_syntax"); - } - if opts.contains(ast::InlineAsmOptions::RAW) { - options.push("raw"); - } - if opts.contains(ast::InlineAsmOptions::MAY_UNWIND) { - options.push("may_unwind"); - } - s.commasep(Inconsistent, &options, |s, &opt| { + s.commasep(Inconsistent, &opts.human_readable_names(), |s, &opt| { s.word(opt); }); s.pclose(); diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index 4e2104ff56155..bc0ed4a7fa99d 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -1,5 +1,3 @@ -use crate::coercion::{AsCoercionSite, CoerceMany}; -use crate::{Diverges, Expectation, FnCtxt, Needs}; use rustc_errors::{Applicability, Diag}; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::LocalDefId; @@ -11,6 +9,9 @@ use rustc_trait_selection::traits::{ IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode, }; +use crate::coercion::{AsCoercionSite, CoerceMany}; +use crate::{Diverges, Expectation, FnCtxt, Needs}; + impl<'a, 'tcx> FnCtxt<'a, 'tcx> { #[instrument(skip(self), level = "debug", ret)] pub fn check_match( diff --git a/compiler/rustc_hir_typeck/src/autoderef.rs b/compiler/rustc_hir_typeck/src/autoderef.rs index 5db71591e66e4..69c4889d7a4b2 100644 --- a/compiler/rustc_hir_typeck/src/autoderef.rs +++ b/compiler/rustc_hir_typeck/src/autoderef.rs @@ -1,7 +1,6 @@ //! Some helper functions for `AutoDeref`. -use super::method::MethodCallee; -use super::{FnCtxt, PlaceOp}; +use std::iter; use itertools::Itertools; use rustc_hir_analysis::autoderef::{Autoderef, AutoderefKind}; @@ -10,7 +9,8 @@ use rustc_middle::ty::adjustment::{Adjust, Adjustment, OverloadedDeref}; use rustc_middle::ty::{self, Ty}; use rustc_span::Span; -use std::iter; +use super::method::MethodCallee; +use super::{FnCtxt, PlaceOp}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn autoderef(&'a self, span: Span, base_ty: Ty<'tcx>) -> Autoderef<'a, 'tcx> { diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 0d2a55a9507c2..07f64ead6f636 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -1,24 +1,17 @@ -use super::method::probe::ProbeScope; -use super::method::MethodCallee; -use super::{Expectation, FnCtxt, TupleArgumentsFlag}; +use std::{iter, slice}; -use crate::errors; use rustc_ast::util::parser::PREC_UNAMBIGUOUS; use rustc_errors::{Applicability, Diag, ErrorGuaranteed, StashKey}; use rustc_hir::def::{self, CtorKind, Namespace, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, LangItem}; use rustc_hir_analysis::autoderef::Autoderef; -use rustc_infer::traits::ObligationCauseCode; -use rustc_infer::{ - infer, - traits::{self, Obligation, ObligationCause}, -}; +use rustc_infer::infer; +use rustc_infer::traits::{self, Obligation, ObligationCause, ObligationCauseCode}; use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, }; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; use rustc_span::def_id::LocalDefId; use rustc_span::symbol::{sym, Ident}; @@ -28,7 +21,10 @@ use rustc_trait_selection::error_reporting::traits::DefIdOrName; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; -use std::{iter, slice}; +use super::method::probe::ProbeScope; +use super::method::MethodCallee; +use super::{Expectation, FnCtxt, TupleArgumentsFlag}; +use crate::errors; /// Checks that it is legal to call methods of the trait corresponding /// to `trait_id` (this only cares about the trait, not the specific diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index 6522972277183..de70273390466 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -28,12 +28,9 @@ //! expression, `e as U2` is not necessarily so (in fact it will only be valid if //! `U1` coerces to `U2`). -use super::FnCtxt; - -use crate::errors; -use crate::type_error_struct; use rustc_data_structures::fx::FxHashSet; -use rustc_errors::{codes::*, Applicability, Diag, ErrorGuaranteed}; +use rustc_errors::codes::*; +use rustc_errors::{Applicability, Diag, ErrorGuaranteed}; use rustc_hir::{self as hir, ExprKind}; use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_middle::bug; @@ -41,15 +38,16 @@ use rustc_middle::mir::Mutability; use rustc_middle::ty::adjustment::AllowTwoPhase; use rustc_middle::ty::cast::{CastKind, CastTy}; use rustc_middle::ty::error::TypeError; -use rustc_middle::ty::TyCtxt; -use rustc_middle::ty::{self, Ty, TypeAndMut, TypeVisitableExt, VariantDef}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, VariantDef}; use rustc_session::lint; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::symbol::sym; -use rustc_span::Span; -use rustc_span::DUMMY_SP; +use rustc_span::{Span, DUMMY_SP}; use rustc_trait_selection::infer::InferCtxtExt; +use super::FnCtxt; +use crate::{errors, type_error_struct}; + /// Reifies a cast check to be checked once we have full type information for /// a function context. #[derive(Debug)] diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index 843d9e3871489..89df464cca040 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -1,8 +1,5 @@ use std::cell::RefCell; -use crate::coercion::CoerceMany; -use crate::gather_locals::GatherLocalsVisitor; -use crate::{CoroutineTypes, Diverges, FnCtxt}; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::intravisit::Visitor; @@ -16,6 +13,10 @@ use rustc_span::symbol::sym; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode}; +use crate::coercion::CoerceMany; +use crate::gather_locals::GatherLocalsVisitor; +use crate::{CoroutineTypes, Diverges, FnCtxt}; + /// Helper used for fns and closures. Does the grungy work of checking a function /// body and returns the function context used for that purpose, since in the case of a fn item /// there is still a bit more to do. diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 79854976bdd57..a7953acc95c80 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -1,27 +1,26 @@ //! Code for type-checking closure expressions. -use super::{check_fn, CoroutineTypes, Expectation, FnCtxt}; +use std::iter; +use std::ops::ControlFlow; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; -use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes}; -use rustc_infer::infer::{InferOk, InferResult}; +use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk, InferResult}; use rustc_infer::traits::ObligationCauseCode; use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_middle::span_bug; use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; -use rustc_middle::ty::GenericArgs; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor}; +use rustc_middle::ty::{self, GenericArgs, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor}; use rustc_span::def_id::LocalDefId; use rustc_span::Span; use rustc_target::spec::abi::Abi; use rustc_trait_selection::error_reporting::traits::ArgKind; use rustc_trait_selection::traits; use rustc_type_ir::ClosureKind; -use std::iter; -use std::ops::ControlFlow; + +use super::{check_fn, CoroutineTypes, Expectation, FnCtxt}; /// What signature do we *expect* the closure to have from context? #[derive(Debug, Clone, TypeFoldable, TypeVisitable)] diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 1bfe9734217f2..fcd3798eb48e6 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -35,16 +35,18 @@ //! // and are then unable to coerce `&7i32` to `&mut i32`. //! ``` -use crate::errors::SuggestBoxingForReturnImplTrait; -use crate::FnCtxt; -use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diag}; +use std::ops::Deref; + +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, Applicability, Diag}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::infer::relate::RelateResult; use rustc_infer::infer::{Coercion, DefineOpaqueTypes, InferOk, InferResult}; -use rustc_infer::traits::{IfExpressionCause, MatchExpressionArmCause}; -use rustc_infer::traits::{Obligation, PredicateObligation}; +use rustc_infer::traits::{ + IfExpressionCause, MatchExpressionArmCause, Obligation, PredicateObligation, +}; use rustc_middle::lint::in_external_macro; use rustc_middle::span_bug; use rustc_middle::traits::BuiltinImplSource; @@ -63,9 +65,10 @@ use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::{ self, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt, }; - use smallvec::{smallvec, SmallVec}; -use std::ops::Deref; + +use crate::errors::SuggestBoxingForReturnImplTrait; +use crate::FnCtxt; struct Coerce<'a, 'tcx> { fcx: &'a FnCtxt<'a, 'tcx>, diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 4f1c2fdd92260..0a9fa5c64a54e 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -1,6 +1,4 @@ -use crate::FnCtxt; -use rustc_errors::MultiSpan; -use rustc_errors::{Applicability, Diag}; +use rustc_errors::{Applicability, Diag, MultiSpan}; use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::intravisit::Visitor; @@ -17,6 +15,7 @@ use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::ObligationCause; use super::method::probe; +use crate::FnCtxt; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn emit_type_mismatch_suggestions( diff --git a/compiler/rustc_hir_typeck/src/diverges.rs b/compiler/rustc_hir_typeck/src/diverges.rs index 0b559a0858e46..aa30fb0f0af39 100644 --- a/compiler/rustc_hir_typeck/src/diverges.rs +++ b/compiler/rustc_hir_typeck/src/diverges.rs @@ -1,6 +1,7 @@ -use rustc_span::{Span, DUMMY_SP}; use std::{cmp, ops}; +use rustc_span::{Span, DUMMY_SP}; + /// Tracks whether executing a node may exit normally (versus /// return/break/panic, which "diverge", leaving dead code in their /// wake). Tracked semi-automatically (through type variables marked diff --git a/compiler/rustc_hir_typeck/src/errors.rs b/compiler/rustc_hir_typeck/src/errors.rs index 9a38d6d4a7195..f802b8cf9cc9b 100644 --- a/compiler/rustc_hir_typeck/src/errors.rs +++ b/compiler/rustc_hir_typeck/src/errors.rs @@ -2,18 +2,18 @@ use std::borrow::Cow; -use crate::fluent_generated as fluent; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, Applicability, Diag, DiagArgValue, DiagSymbolList, EmissionGuarantee, IntoDiagArg, - MultiSpan, SubdiagMessageOp, Subdiagnostic, + Applicability, Diag, DiagArgValue, DiagSymbolList, EmissionGuarantee, IntoDiagArg, MultiSpan, + SubdiagMessageOp, Subdiagnostic, }; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::{self, Ty}; -use rustc_span::{ - edition::{Edition, LATEST_STABLE_EDITION}, - symbol::Ident, - Span, Symbol, -}; +use rustc_span::edition::{Edition, LATEST_STABLE_EDITION}; +use rustc_span::symbol::Ident; +use rustc_span::{Span, Symbol}; + +use crate::fluent_generated as fluent; #[derive(Diagnostic)] #[diag(hir_typeck_field_multiply_specified_in_initializer, code = E0062)] diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 0d002c52fbb86..e54f9486f6a89 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -2,33 +2,13 @@ //! //! See [`rustc_hir_analysis::check`] for more context on type checking in general. -use crate::cast; -use crate::coercion::CoerceMany; -use crate::coercion::DynamicCoerceMany; -use crate::errors::ReturnLikeStatementKind; -use crate::errors::TypeMismatchFruTypo; -use crate::errors::{AddressOfTemporaryTaken, ReturnStmtOutsideOfFnBody, StructExprNonExhaustive}; -use crate::errors::{ - FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct, HelpUseLatestEdition, - YieldExprOutsideOfCoroutine, -}; -use crate::fatally_break_rust; -use crate::type_error_struct; -use crate::CoroutineTypes; -use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation}; -use crate::{ - report_unexpected_variant_res, BreakableCtxt, Diverges, FnCtxt, Needs, - TupleArgumentsFlag::DontTupleArguments, -}; -use rustc_ast as ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::unord::UnordMap; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, StashKey, - Subdiagnostic, + pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, StashKey, Subdiagnostic, }; -use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::Visitor; @@ -36,14 +16,12 @@ use rustc_hir::lang_items::LangItem; use rustc_hir::{ExprKind, HirId, QPath}; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _; use rustc_infer::infer; -use rustc_infer::infer::DefineOpaqueTypes; -use rustc_infer::infer::InferOk; +use rustc_infer::infer::{DefineOpaqueTypes, InferOk}; use rustc_infer::traits::query::NoSolution; use rustc_infer::traits::ObligationCause; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase}; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, AdtKind, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self, AdtKind, GenericArgsRef, Ty, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; use rustc_session::errors::ExprParenthesesNeeded; use rustc_session::parse::feature_err; @@ -54,10 +32,23 @@ use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; use rustc_target::abi::{FieldIdx, FIRST_VARIANT}; use rustc_trait_selection::infer::InferCtxtExt; -use rustc_trait_selection::traits::ObligationCtxt; -use rustc_trait_selection::traits::{self, ObligationCauseCode}; - +use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt}; use smallvec::SmallVec; +use {rustc_ast as ast, rustc_hir as hir}; + +use crate::coercion::{CoerceMany, DynamicCoerceMany}; +use crate::errors::{ + AddressOfTemporaryTaken, FieldMultiplySpecifiedInInitializer, + FunctionalRecordUpdateOnNonStruct, HelpUseLatestEdition, ReturnLikeStatementKind, + ReturnStmtOutsideOfFnBody, StructExprNonExhaustive, TypeMismatchFruTypo, + YieldExprOutsideOfCoroutine, +}; +use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation}; +use crate::TupleArgumentsFlag::DontTupleArguments; +use crate::{ + cast, fatally_break_rust, report_unexpected_variant_res, type_error_struct, BreakableCtxt, + CoroutineTypes, Diverges, FnCtxt, Needs, +}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn check_expr_has_type_or_error( @@ -1315,6 +1306,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // No way to know whether it's diverging because // of a `break` or an outer `break` or `return`. self.diverges.set(Diverges::Maybe); + } else { + self.diverges.set(self.diverges.get() | Diverges::always(expr.span)); } // If we permit break with a value, then result type is @@ -3347,18 +3340,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Ty<'tcx> { let container = self.lower_ty(container).normalized; - if let Some(ident_2) = fields.get(1) - && !self.tcx.features().offset_of_nested - { - rustc_session::parse::feature_err( - &self.tcx.sess, - sym::offset_of_nested, - ident_2.span, - "only a single ident or integer is stable as the field in offset_of", - ) - .emit(); - } - let mut field_indices = Vec::with_capacity(fields.len()); let mut current_container = container; let mut fields = fields.into_iter(); diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index 193dbbbcdf44d..548d5a7cc4ccd 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -9,16 +9,15 @@ use std::slice::from_ref; use hir::def::DefKind; use hir::pat_util::EnumerateAndAdjustIterator as _; use hir::Expr; -use rustc_lint::LateContext; -// Export these here so that Clippy can use them. -pub use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection}; - use rustc_data_structures::fx::FxIndexMap; use rustc_hir as hir; use rustc_hir::def::{CtorOf, Res}; use rustc_hir::def_id::LocalDefId; use rustc_hir::{HirId, PatKind}; +use rustc_lint::LateContext; use rustc_middle::hir::place::ProjectionKind; +// Export these here so that Clippy can use them. +pub use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection}; use rustc_middle::mir::FakeReadCause; use rustc_middle::ty::{ self, adjustment, AdtKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt as _, diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index 9f3aeacd2c566..6e1b7504626d3 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -1,10 +1,9 @@ use std::cell::OnceCell; -use crate::{errors, FnCtxt, TypeckRootCtxt}; -use rustc_data_structures::{ - graph::{self, iterate::DepthFirstSearch, vec_graph::VecGraph}, - unord::{UnordBag, UnordMap, UnordSet}, -}; +use rustc_data_structures::graph::iterate::DepthFirstSearch; +use rustc_data_structures::graph::vec_graph::VecGraph; +use rustc_data_structures::graph::{self}; +use rustc_data_structures::unord::{UnordBag, UnordMap, UnordSet}; use rustc_hir as hir; use rustc_hir::intravisit::Visitor; use rustc_hir::HirId; @@ -12,10 +11,12 @@ use rustc_infer::infer::{DefineOpaqueTypes, InferOk}; use rustc_middle::bug; use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable}; use rustc_session::lint; -use rustc_span::DUMMY_SP; -use rustc_span::{def_id::LocalDefId, Span}; +use rustc_span::def_id::LocalDefId; +use rustc_span::{Span, DUMMY_SP}; use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt}; +use crate::{errors, FnCtxt, TypeckRootCtxt}; + #[derive(Copy, Clone)] pub enum DivergingFallbackBehavior { /// Always fallback to `()` (aka "always spontaneous decay") diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 87e8afe6dd17e..8c1aa66332fc9 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -1,8 +1,6 @@ -use crate::callee::{self, DeferredCallResolution}; -use crate::errors::{self, CtorIsPrivate}; -use crate::method::{self, MethodCallee}; -use crate::rvalue_scopes; -use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy}; +use std::collections::hash_map::Entry; +use std::slice; + use rustc_data_structures::fx::FxHashSet; use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey}; use rustc_hir as hir; @@ -26,9 +24,9 @@ use rustc_middle::ty::error::TypeError; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; use rustc_middle::ty::{ - self, AdtKind, CanonicalUserType, GenericParamDefKind, IsIdentity, Ty, TyCtxt, UserType, + self, AdtKind, CanonicalUserType, GenericArgKind, GenericArgsRef, GenericParamDefKind, + IsIdentity, Ty, TyCtxt, UserArgs, UserSelfTy, UserType, }; -use rustc_middle::ty::{GenericArgKind, GenericArgsRef, UserArgs, UserSelfTy}; use rustc_middle::{bug, span_bug}; use rustc_session::lint; use rustc_span::def_id::LocalDefId; @@ -41,37 +39,51 @@ use rustc_trait_selection::traits::{ self, NormalizeExt, ObligationCauseCode, ObligationCtxt, StructurallyNormalizeExt, }; -use std::collections::hash_map::Entry; -use std::slice; +use crate::callee::{self, DeferredCallResolution}; +use crate::errors::{self, CtorIsPrivate}; +use crate::method::{self, MethodCallee}; +use crate::{rvalue_scopes, BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Produces warning on the given node, if the current point in the /// function is unreachable, and there hasn't been another warning. pub(crate) fn warn_if_unreachable(&self, id: HirId, span: Span, kind: &str) { - // FIXME: Combine these two 'if' expressions into one once - // let chains are implemented - if let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() { - // If span arose from a desugaring of `if` or `while`, then it is the condition itself, - // which diverges, that we are about to lint on. This gives suboptimal diagnostics. - // Instead, stop here so that the `if`- or `while`-expression's block is linted instead. - if !span.is_desugaring(DesugaringKind::CondTemporary) - && !span.is_desugaring(DesugaringKind::Async) - && !orig_span.is_desugaring(DesugaringKind::Await) - { - self.diverges.set(Diverges::WarnedAlways); + let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() else { + return; + }; - debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind); + match span.desugaring_kind() { + // If span arose from a desugaring of `if` or `while`, then it is the condition + // itself, which diverges, that we are about to lint on. This gives suboptimal + // diagnostics. Instead, stop here so that the `if`- or `while`-expression's + // block is linted instead. + Some(DesugaringKind::CondTemporary) => return, - let msg = format!("unreachable {kind}"); - self.tcx().node_span_lint(lint::builtin::UNREACHABLE_CODE, id, span, |lint| { - lint.primary_message(msg.clone()); - lint.span_label(span, msg).span_label( - orig_span, - custom_note.unwrap_or("any code following this expression is unreachable"), - ); - }) - } + // Don't lint if the result of an async block or async function is `!`. + // This does not affect the unreachable lints *within* the body. + Some(DesugaringKind::Async) => return, + + // Don't lint *within* the `.await` operator, since that's all just desugaring + // junk. We only want to lint if there is a subsequent expression after the + // `.await` operator. + Some(DesugaringKind::Await) => return, + + _ => {} } + + // Don't warn twice. + self.diverges.set(Diverges::WarnedAlways); + + debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind); + + let msg = format!("unreachable {kind}"); + self.tcx().node_span_lint(lint::builtin::UNREACHABLE_CODE, id, span, |lint| { + lint.primary_message(msg.clone()); + lint.span_label(span, msg).span_label( + orig_span, + custom_note.unwrap_or("any code following this expression is unreachable"), + ); + }) } /// Resolves type and const variables in `ty` if possible. Unlike the infcx diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs index 8e35efa53ae54..130fd130ec837 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs @@ -1,13 +1,15 @@ -use crate::FnCtxt; +use std::ops::ControlFlow; + use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor}; -use rustc_span::{symbol::kw, Span}; +use rustc_span::symbol::kw; +use rustc_span::Span; use rustc_trait_selection::traits; -use std::ops::ControlFlow; +use crate::FnCtxt; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn adjust_fulfillment_error_for_expr_obligation( diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs index 566d407d23c12..788956894333b 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs @@ -1,7 +1,8 @@ use core::cmp::Ordering; +use std::cmp; + use rustc_index::IndexVec; use rustc_middle::ty::error::TypeError; -use std::cmp; rustc_index::newtype_index! { #[orderable] diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 7c96a991bed52..cef003e0a43de 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -1,26 +1,12 @@ -use crate::coercion::CoerceMany; -use crate::errors::SuggestPtrNullMut; -use crate::fn_ctxt::arg_matrix::{ArgMatrix, Compatibility, Error, ExpectedIdx, ProvidedIdx}; -use crate::fn_ctxt::infer::FnCall; -use crate::gather_locals::Declaration; -use crate::method::probe::IsSuggestion; -use crate::method::probe::Mode::MethodCall; -use crate::method::probe::ProbeScope::TraitsInScope; -use crate::method::MethodCallee; -use crate::TupleArgumentsFlag::*; -use crate::{errors, Expectation::*}; -use crate::{ - struct_span_code_err, BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy, Needs, - TupleArgumentsFlag, -}; +use std::{iter, mem}; + use itertools::Itertools; -use rustc_ast as ast; use rustc_data_structures::fx::FxIndexSet; +use rustc_errors::codes::*; use rustc_errors::{ - a_or_an, codes::*, display_list_with_comma_and, pluralize, Applicability, Diag, - ErrorGuaranteed, MultiSpan, StashKey, + a_or_an, display_list_with_comma_and, pluralize, Applicability, Diag, ErrorGuaranteed, + MultiSpan, StashKey, }; -use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::Visitor; @@ -29,8 +15,7 @@ use rustc_hir_analysis::check::intrinsicck::InlineAsmCtxt; use rustc_hir_analysis::check::potentially_plural_count; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_index::IndexVec; -use rustc_infer::infer::TypeTrace; -use rustc_infer::infer::{DefineOpaqueTypes, InferOk}; +use rustc_infer::infer::{DefineOpaqueTypes, InferOk, TypeTrace}; use rustc_middle::ty::adjustment::AllowTwoPhase; use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt}; @@ -41,9 +26,23 @@ use rustc_span::{sym, BytePos, Span, DUMMY_SP}; use rustc_trait_selection::error_reporting::infer::{FailureCode, ObligationCauseExt}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{self, ObligationCauseCode, SelectionContext}; +use {rustc_ast as ast, rustc_hir as hir}; -use std::iter; -use std::mem; +use crate::coercion::CoerceMany; +use crate::errors::SuggestPtrNullMut; +use crate::fn_ctxt::arg_matrix::{ArgMatrix, Compatibility, Error, ExpectedIdx, ProvidedIdx}; +use crate::fn_ctxt::infer::FnCall; +use crate::gather_locals::Declaration; +use crate::method::probe::IsSuggestion; +use crate::method::probe::Mode::MethodCall; +use crate::method::probe::ProbeScope::TraitsInScope; +use crate::method::MethodCallee; +use crate::Expectation::*; +use crate::TupleArgumentsFlag::*; +use crate::{ + errors, struct_span_code_err, BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy, Needs, + TupleArgumentsFlag, +}; #[derive(Clone, Copy, Default)] pub enum DivergingBlockBehavior { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs index 90dd5f73586b3..be4db2934b7b1 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs @@ -1,12 +1,14 @@ //! A utility module to inspect currently ambiguous obligations in the current context. -use crate::FnCtxt; use rustc_infer::traits::{self, ObligationCause}; use rustc_middle::traits::solve::Goal; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; use rustc_span::Span; -use rustc_trait_selection::solve::inspect::ProofTreeInferCtxtExt; -use rustc_trait_selection::solve::inspect::{InspectConfig, InspectGoal, ProofTreeVisitor}; +use rustc_trait_selection::solve::inspect::{ + InspectConfig, InspectGoal, ProofTreeInferCtxtExt, ProofTreeVisitor, +}; + +use crate::FnCtxt; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Returns a list of all obligations whose self type has been unified diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index 39d73dae0158f..33f80dd3773fa 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -5,13 +5,11 @@ mod checks; mod inspect_obligations; mod suggestions; -use rustc_errors::DiagCtxtHandle; +use std::cell::{Cell, RefCell}; +use std::ops::Deref; -use crate::coercion::DynamicCoerceMany; -use crate::fallback::DivergingFallbackBehavior; -use crate::fn_ctxt::checks::DivergingBlockBehavior; -use crate::{CoroutineTypes, Diverges, EnclosingBreakables, TypeckRootCtxt}; use hir::def_id::CRATE_DEF_ID; +use rustc_errors::DiagCtxtHandle; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir_analysis::hir_ty_lowering::{HirTyLowerer, RegionInferReason}; @@ -24,8 +22,10 @@ use rustc_trait_selection::error_reporting::infer::sub_relations::SubRelations; use rustc_trait_selection::error_reporting::TypeErrCtxt; use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt}; -use std::cell::{Cell, RefCell}; -use std::ops::Deref; +use crate::coercion::DynamicCoerceMany; +use crate::fallback::DivergingFallbackBehavior; +use crate::fn_ctxt::checks::DivergingBlockBehavior; +use crate::{CoroutineTypes, Diverges, EnclosingBreakables, TypeckRootCtxt}; /// The `FnCtxt` stores type-checking context needed to type-check bodies of /// functions, closures, and `const`s, including performing type inference diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index fe7495deb2bf3..6b4edcd95d993 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -1,20 +1,12 @@ -use super::FnCtxt; - -use crate::errors; -use crate::fluent_generated as fluent; -use crate::fn_ctxt::rustc_span::BytePos; -use crate::hir::is_range_literal; -use crate::method::probe; -use crate::method::probe::{IsSuggestion, Mode, ProbeScope}; use core::cmp::min; use core::iter; + use hir::def_id::LocalDefId; use rustc_ast::util::parser::{ExprPrecedence, PREC_UNAMBIGUOUS}; use rustc_data_structures::packed::Pu128; use rustc_errors::{Applicability, Diag, MultiSpan}; use rustc_hir as hir; -use rustc_hir::def::Res; -use rustc_hir::def::{CtorKind, CtorOf, DefKind}; +use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; use rustc_hir::lang_items::LangItem; use rustc_hir::{ Arm, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, ExprKind, GenericBound, HirId, @@ -26,8 +18,10 @@ use rustc_middle::lint::in_external_macro; use rustc_middle::middle::stability::EvalResult; use rustc_middle::span_bug; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::{self, suggest_constraining_type_params, Article, Binder}; -use rustc_middle::ty::{IsSuggestable, Ty, TyCtxt, TypeVisitableExt, Upcast}; +use rustc_middle::ty::{ + self, suggest_constraining_type_params, Article, Binder, IsSuggestable, Ty, TyCtxt, + TypeVisitableExt, Upcast, +}; use rustc_session::errors::ExprParenthesesNeeded; use rustc_span::source_map::Spanned; use rustc_span::symbol::{sym, Ident}; @@ -38,6 +32,13 @@ use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; +use super::FnCtxt; +use crate::fn_ctxt::rustc_span::BytePos; +use crate::hir::is_range_literal; +use crate::method::probe; +use crate::method::probe::{IsSuggestion, Mode, ProbeScope}; +use crate::{errors, fluent_generated as fluent}; + impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub(crate) fn body_fn_sig(&self) -> Option> { self.typeck_results diff --git a/compiler/rustc_hir_typeck/src/gather_locals.rs b/compiler/rustc_hir_typeck/src/gather_locals.rs index 13e4b625e2d0d..0fd450e869aa3 100644 --- a/compiler/rustc_hir_typeck/src/gather_locals.rs +++ b/compiler/rustc_hir_typeck/src/gather_locals.rs @@ -1,13 +1,13 @@ -use crate::FnCtxt; use rustc_hir as hir; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{HirId, PatKind}; use rustc_infer::traits::ObligationCauseCode; -use rustc_middle::ty::Ty; -use rustc_middle::ty::UserType; +use rustc_middle::ty::{Ty, UserType}; use rustc_span::def_id::LocalDefId; use rustc_span::Span; +use crate::FnCtxt; + /// Provides context for checking patterns in declarations. More specifically this /// allows us to infer array types if the pattern is irrefutable and allows us to infer /// the size of the array. See issue #76342. diff --git a/compiler/rustc_hir_typeck/src/intrinsicck.rs b/compiler/rustc_hir_typeck/src/intrinsicck.rs index 0389c06c3123f..a9c929e76d5bf 100644 --- a/compiler/rustc_hir_typeck/src/intrinsicck.rs +++ b/compiler/rustc_hir_typeck/src/intrinsicck.rs @@ -1,5 +1,6 @@ use hir::HirId; -use rustc_errors::{codes::*, struct_span_code_err}; +use rustc_errors::codes::*; +use rustc_errors::struct_span_code_err; use rustc_hir as hir; use rustc_index::Idx; use rustc_middle::bug; diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 2c79366450909..758a1cefe6341 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -44,16 +44,9 @@ mod writeback; pub use coercion::can_coerce; use fn_ctxt::FnCtxt; -use typeck_root_ctxt::TypeckRootCtxt; - -use crate::check::check_fn; -use crate::coercion::DynamicCoerceMany; -use crate::diverges::Diverges; -use crate::expectation::Expectation; -use crate::fn_ctxt::LoweredTy; -use crate::gather_locals::GatherLocalsVisitor; use rustc_data_structures::unord::UnordSet; -use rustc_errors::{codes::*, struct_span_code_err, Applicability, ErrorGuaranteed}; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, Applicability, ErrorGuaranteed}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::Visitor; @@ -67,6 +60,14 @@ use rustc_middle::{bug, span_bug}; use rustc_session::config; use rustc_span::def_id::LocalDefId; use rustc_span::Span; +use typeck_root_ctxt::TypeckRootCtxt; + +use crate::check::check_fn; +use crate::coercion::DynamicCoerceMany; +use crate::diverges::Diverges; +use crate::expectation::Expectation; +use crate::fn_ctxt::LoweredTy; +use crate::gather_locals::GatherLocalsVisitor; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } @@ -264,11 +265,10 @@ fn infer_type_if_missing<'tcx>(fcx: &FnCtxt<'_, 'tcx>, node: Node<'tcx>) -> Opti Node::Expr(&hir::Expr { kind: hir::ExprKind::InlineAsm(asm), span, .. }) | Node::Item(&hir::Item { kind: hir::ItemKind::GlobalAsm(asm), span, .. }) => { asm.operands.iter().find_map(|(op, _op_sp)| match op { - hir::InlineAsmOperand::Const { anon_const } if anon_const.hir_id == id => { - // Inline assembly constants must be integers. - Some(fcx.next_int_var()) - } - hir::InlineAsmOperand::SymFn { anon_const } if anon_const.hir_id == id => { + hir::InlineAsmOperand::Const { anon_const } + | hir::InlineAsmOperand::SymFn { anon_const } + if anon_const.hir_id == id => + { Some(fcx.next_ty_var(span)) } _ => None, diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index e70431a68ff16..f14159dc35a57 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -1,6 +1,5 @@ -use super::{probe, MethodCallee}; +use std::ops::Deref; -use crate::{callee, FnCtxt}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::GenericArg; @@ -12,17 +11,20 @@ use rustc_hir_analysis::hir_ty_lowering::{ }; use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk}; use rustc_middle::traits::{ObligationCauseCode, UnifyReceiverContext}; -use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCoercion}; -use rustc_middle::ty::adjustment::{AllowTwoPhase, AutoBorrow, AutoBorrowMutability}; +use rustc_middle::ty::adjustment::{ + Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCoercion, +}; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{ - self, GenericArgs, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt, UserArgs, UserType, + self, GenericArgs, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt, TypeVisitableExt, UserArgs, + UserType, }; use rustc_middle::{bug, span_bug}; use rustc_span::{Span, DUMMY_SP}; use rustc_trait_selection::traits; -use std::ops::Deref; +use super::{probe, MethodCallee}; +use crate::{callee, FnCtxt}; struct ConfirmContext<'a, 'tcx> { fcx: &'a FnCtxt<'a, 'tcx>, @@ -268,6 +270,17 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { probe::ObjectPick => { let trait_def_id = pick.item.container_id(self.tcx); + + // This shouldn't happen for non-region error kinds, but may occur + // when we have error regions. Specifically, since we canonicalize + // during method steps, we may successfully deref when we assemble + // the pick, but fail to deref when we try to extract the object + // type from the pick during confirmation. This is fine, we're basically + // already doomed by this point. + if self_ty.references_error() { + return ty::GenericArgs::extend_with_error(self.tcx, trait_def_id, &[]); + } + self.extract_existential_trait_ref(self_ty, |this, object_ty, principal| { // The object data has no entry for the Self // Type. For the purposes of this method call, we diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index daf4ef5cdb324..d6110ab94c15a 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -7,9 +7,6 @@ mod prelude_edition_lints; pub mod probe; mod suggest; -pub use self::MethodError::*; - -use crate::FnCtxt; use rustc_errors::{Applicability, Diag, SubdiagMessage}; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Namespace}; @@ -17,8 +14,9 @@ use rustc_hir::def_id::DefId; use rustc_infer::infer::{self, InferOk}; use rustc_middle::query::Providers; use rustc_middle::traits::ObligationCause; -use rustc_middle::ty::{self, GenericParamDefKind, Ty, TypeVisitableExt}; -use rustc_middle::ty::{GenericArgs, GenericArgsRef}; +use rustc_middle::ty::{ + self, GenericArgs, GenericArgsRef, GenericParamDefKind, Ty, TypeVisitableExt, +}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::Ident; use rustc_span::Span; @@ -26,6 +24,8 @@ use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::{self, NormalizeExt}; use self::probe::{IsSuggestion, ProbeScope}; +pub use self::MethodError::*; +use crate::FnCtxt; pub fn provide(providers: &mut Providers) { probe::provide(providers); diff --git a/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs b/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs index 3ee10f74d98a4..0a4c3dc8af96f 100644 --- a/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs +++ b/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs @@ -1,20 +1,20 @@ -use crate::method::probe::{self, Pick}; -use crate::FnCtxt; +use std::fmt::Write; use hir::def_id::DefId; -use hir::HirId; -use hir::ItemKind; +use hir::{HirId, ItemKind}; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::{ARRAY_INTO_ITER, BOXED_SLICE_INTO_ITER}; use rustc_middle::span_bug; use rustc_middle::ty::{self, Ty}; -use rustc_session::lint::builtin::RUST_2021_PRELUDE_COLLISIONS; +use rustc_session::lint::builtin::{RUST_2021_PRELUDE_COLLISIONS, RUST_2024_PRELUDE_COLLISIONS}; use rustc_span::symbol::kw::{Empty, Underscore}; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; use rustc_trait_selection::infer::InferCtxtExt; -use std::fmt::Write; + +use crate::method::probe::{self, Pick}; +use crate::FnCtxt; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub(super) fn lint_edition_dependent_dot_call( @@ -35,6 +35,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (prelude_or_array_lint, edition) = match segment.ident.name { // `try_into` was added to the prelude in Rust 2021. sym::try_into if !span.at_least_rust_2021() => (RUST_2021_PRELUDE_COLLISIONS, "2021"), + // `Future::poll` was added to the prelude in Rust 2024. + sym::poll + // We check that the self type is `Pin<&mut _>` to avoid false positives for this common name. + if !span.at_least_rust_2024() + && let ty::Adt(adt_def, args) = self_ty.kind() + && self.tcx.is_lang_item(adt_def.did(), hir::LangItem::Pin) + && let ty::Ref(_, _, ty::Mutability::Mut) = + args[0].as_type().unwrap().kind() => + { + (RUST_2024_PRELUDE_COLLISIONS, "2024") + } + // `IntoFuture::into_future` was added to the prelude in Rust 2024. + sym::into_future if !span.at_least_rust_2024() => { + (RUST_2024_PRELUDE_COLLISIONS, "2024") + } // `into_iter` wasn't added to the prelude, // but `[T; N].into_iter()` doesn't resolve to IntoIterator::into_iter // before Rust 2021, which results in the same problem. diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 9cb6124ab2176..28f537c87c4ee 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -1,58 +1,46 @@ -use super::suggest; -use super::CandidateSource; -use super::MethodError; -use super::NoMatchData; +use std::cell::{Cell, RefCell}; +use std::cmp::max; +use std::iter; +use std::ops::Deref; -use crate::FnCtxt; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::HirId; use rustc_hir_analysis::autoderef::{self, Autoderef}; -use rustc_infer::infer::canonical::OriginalQueryValues; -use rustc_infer::infer::canonical::{Canonical, QueryResponse}; -use rustc_infer::infer::DefineOpaqueTypes; -use rustc_infer::infer::{self, InferOk, TyCtxtInferExt}; +use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse}; +use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk, TyCtxtInferExt}; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::middle::stability; use rustc_middle::query::Providers; use rustc_middle::ty::fast_reject::{simplify_type, TreatParams}; -use rustc_middle::ty::AssocItem; -use rustc_middle::ty::AssocItemContainer; -use rustc_middle::ty::GenericParamDefKind; -use rustc_middle::ty::Upcast; -use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt}; -use rustc_middle::ty::{GenericArgs, GenericArgsRef}; +use rustc_middle::ty::{ + self, AssocItem, AssocItemContainer, GenericArgs, GenericArgsRef, GenericParamDefKind, + ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt, Upcast, +}; use rustc_middle::{bug, span_bug}; use rustc_session::lint; -use rustc_span::def_id::DefId; -use rustc_span::def_id::LocalDefId; +use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::edit_distance::{ edit_distance_with_substrings, find_best_match_for_name_with_substrings, }; -use rustc_span::symbol::sym; -use rustc_span::{symbol::Ident, Span, Symbol, DUMMY_SP}; +use rustc_span::symbol::{sym, Ident}; +use rustc_span::{Span, Symbol, DUMMY_SP}; use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; -use rustc_trait_selection::traits::query::method_autoderef::MethodAutoderefBadTy; use rustc_trait_selection::traits::query::method_autoderef::{ - CandidateStep, MethodAutoderefStepsResult, + CandidateStep, MethodAutoderefBadTy, MethodAutoderefStepsResult, }; use rustc_trait_selection::traits::query::CanonicalTyGoal; -use rustc_trait_selection::traits::ObligationCtxt; -use rustc_trait_selection::traits::{self, ObligationCause}; -use std::cell::Cell; -use std::cell::RefCell; -use std::cmp::max; -use std::iter; -use std::ops::Deref; - +use rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt}; use smallvec::{smallvec, SmallVec}; use self::CandidateKind::*; pub use self::PickKind::*; +use super::{suggest, CandidateSource, MethodError, NoMatchData}; +use crate::FnCtxt; /// Boolean flag used to indicate if this search is for a suggestion /// or not. If true, we can allow ambiguity and so forth. @@ -786,18 +774,23 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // instantiation that replaces `Self` with the object type itself. Hence, // a `&self` method will wind up with an argument type like `&dyn Trait`. let trait_ref = principal.with_self_ty(self.tcx, self_ty); - self.elaborate_bounds(iter::once(trait_ref), |this, new_trait_ref, item| { - this.push_candidate( - Candidate { item, kind: ObjectCandidate(new_trait_ref), import_ids: smallvec![] }, - true, - ); - }); + self.assemble_candidates_for_bounds( + traits::supertraits(self.tcx, trait_ref), + |this, new_trait_ref, item| { + this.push_candidate( + Candidate { + item, + kind: ObjectCandidate(new_trait_ref), + import_ids: smallvec![], + }, + true, + ); + }, + ); } #[instrument(level = "debug", skip(self))] fn assemble_inherent_candidates_from_param(&mut self, param_ty: ty::ParamTy) { - // FIXME: do we want to commit to this behavior for param bounds? - let bounds = self.param_env.caller_bounds().iter().filter_map(|predicate| { let bound_predicate = predicate.kind(); match bound_predicate.skip_binder() { @@ -818,7 +811,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { } }); - self.elaborate_bounds(bounds, |this, poly_trait_ref, item| { + self.assemble_candidates_for_bounds(bounds, |this, poly_trait_ref, item| { this.push_candidate( Candidate { item, @@ -832,15 +825,14 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // Do a search through a list of bounds, using a callback to actually // create the candidates. - fn elaborate_bounds( + fn assemble_candidates_for_bounds( &mut self, bounds: impl Iterator>, mut mk_cand: F, ) where F: for<'b> FnMut(&mut ProbeContext<'b, 'tcx>, ty::PolyTraitRef<'tcx>, ty::AssocItem), { - let tcx = self.tcx; - for bound_trait_ref in traits::transitive_bounds(tcx, bounds) { + for bound_trait_ref in bounds { debug!("elaborate_bounds(bound_trait_ref={:?})", bound_trait_ref); for item in self.impl_or_trait_item(bound_trait_ref.def_id()) { if !self.has_applicable_self(&item) { @@ -1846,7 +1838,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { /// Determine if the associated item with the given DefId matches /// the desired name via a doc alias. fn matches_by_doc_alias(&self, def_id: DefId) -> bool { - let Some(name) = self.method_name else { + let Some(method) = self.method_name else { return false; }; let Some(local_def_id) = def_id.as_local() else { @@ -1863,7 +1855,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // #[rustc_confusables("foo", "bar"))] for n in confusables { if let Some(lit) = n.lit() - && name.as_str() == lit.symbol.as_str() + && method.name == lit.symbol { return true; } @@ -1883,14 +1875,14 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // #[doc(alias("foo", "bar"))] for n in nested { if let Some(lit) = n.lit() - && name.as_str() == lit.symbol.as_str() + && method.name == lit.symbol { return true; } } } else if let Some(meta) = v.meta_item() && let Some(lit) = meta.name_value_literal() - && name.as_str() == lit.symbol.as_str() + && method.name == lit.symbol { // #[doc(alias = "foo")] return true; diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index da3ac2fea98e9..94133357a3eb5 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -3,49 +3,45 @@ // ignore-tidy-filelength -use crate::errors::{self, CandidateTraitNote, NoAssociatedItem}; -use crate::Expectation; -use crate::FnCtxt; use core::ops::ControlFlow; +use std::borrow::Cow; + use hir::Expr; use rustc_ast::ast::Mutability; use rustc_attr::parse_confusables; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::unord::UnordSet; -use rustc_errors::{ - codes::*, pluralize, struct_span_code_err, Applicability, Diag, MultiSpan, StashKey, -}; +use rustc_errors::codes::*; +use rustc_errors::{pluralize, struct_span_code_err, Applicability, Diag, MultiSpan, StashKey}; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; +use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::lang_items::LangItem; -use rustc_hir::PathSegment; -use rustc_hir::{self as hir, HirId}; -use rustc_hir::{ExprKind, Node, QPath}; +use rustc_hir::{self as hir, ExprKind, HirId, Node, PathSegment, QPath}; use rustc_infer::infer::{self, RegionVariableOrigin}; use rustc_middle::bug; -use rustc_middle::ty::fast_reject::DeepRejectCtxt; -use rustc_middle::ty::fast_reject::{simplify_type, TreatParams}; +use rustc_middle::ty::fast_reject::{simplify_type, DeepRejectCtxt, TreatParams}; use rustc_middle::ty::print::{ with_crate_prefix, with_forced_trimmed_paths, PrintTraitRefExt as _, }; -use rustc_middle::ty::IsSuggestable; -use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, GenericArgKind, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::def_id::DefIdSet; use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::{edit_distance, ErrorGuaranteed, ExpnKind, FileName, MacroKind, Span}; -use rustc_span::{Symbol, DUMMY_SP}; +use rustc_span::{ + edit_distance, ErrorGuaranteed, ExpnKind, FileName, MacroKind, Span, Symbol, DUMMY_SP, +}; use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedNote; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; use rustc_trait_selection::traits::{ supertraits, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, }; -use std::borrow::Cow; use super::probe::{AutorefOrPtrAdjustment, IsSuggestion, Mode, ProbeScope}; use super::{CandidateSource, MethodError, NoMatchData}; -use rustc_hir::intravisit::{self, Visitor}; +use crate::errors::{self, CandidateTraitNote, NoAssociatedItem}; +use crate::{Expectation, FnCtxt}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn is_fn_ty(&self, ty: Ty<'tcx>, span: Span) -> bool { diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index 7b5845388d4ee..c54f6cfd0999a 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -1,12 +1,8 @@ //! Code related to processing overloaded binary and unary operators. -use super::method::MethodCallee; -use super::FnCtxt; -use crate::Expectation; -use rustc_ast as ast; use rustc_data_structures::packed::Pu128; -use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diag}; -use rustc_hir as hir; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, Applicability, Diag}; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, @@ -21,6 +17,11 @@ use rustc_span::Span; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{FulfillmentError, ObligationCtxt}; use rustc_type_ir::TyKind::*; +use {rustc_ast as ast, rustc_hir as hir}; + +use super::method::MethodCallee; +use super::FnCtxt; +use crate::Expectation; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Checks a `a = b` diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 8afc6a48dfc5c..c4f74adb4207b 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -1,9 +1,11 @@ -use crate::gather_locals::DeclOrigin; -use crate::{errors, FnCtxt, LoweredTy}; +use std::cmp; +use std::collections::hash_map::Entry::{Occupied, Vacant}; + use rustc_ast as ast; use rustc_data_structures::fx::FxHashMap; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan, + pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan, }; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::pat_util::EnumerateAndAdjustIterator; @@ -12,7 +14,8 @@ use rustc_infer::infer; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; -use rustc_session::{lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS, parse::feature_err}; +use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS; +use rustc_session::parse::feature_err; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::hygiene::DesugaringKind; use rustc_span::source_map::Spanned; @@ -23,10 +26,9 @@ use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode}; use ty::VariantDef; -use std::cmp; -use std::collections::hash_map::Entry::{Occupied, Vacant}; - use super::report_unexpected_variant_res; +use crate::gather_locals::DeclOrigin; +use crate::{errors, FnCtxt, LoweredTy}; const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\ This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \ diff --git a/compiler/rustc_hir_typeck/src/place_op.rs b/compiler/rustc_hir_typeck/src/place_op.rs index 515e1b5ed0e0b..ad04b6b8b1df5 100644 --- a/compiler/rustc_hir_typeck/src/place_op.rs +++ b/compiler/rustc_hir_typeck/src/place_op.rs @@ -1,16 +1,18 @@ -use crate::method::MethodCallee; -use crate::{FnCtxt, PlaceOp}; -use rustc_ast as ast; use rustc_errors::Applicability; -use rustc_hir as hir; use rustc_hir_analysis::autoderef::Autoderef; use rustc_infer::infer::InferOk; use rustc_middle::span_bug; -use rustc_middle::ty::adjustment::{Adjust, Adjustment, OverloadedDeref, PointerCoercion}; -use rustc_middle::ty::adjustment::{AllowTwoPhase, AutoBorrow, AutoBorrowMutability}; +use rustc_middle::ty::adjustment::{ + Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, OverloadedDeref, + PointerCoercion, +}; use rustc_middle::ty::{self, Ty}; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; +use {rustc_ast as ast, rustc_hir as hir}; + +use crate::method::MethodCallee; +use crate::{FnCtxt, PlaceOp}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Type-check `*oprnd_expr` with `oprnd_expr` type-checked already. diff --git a/compiler/rustc_hir_typeck/src/rvalue_scopes.rs b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs index 805f36d9b97a1..f22a13d292e0f 100644 --- a/compiler/rustc_hir_typeck/src/rvalue_scopes.rs +++ b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs @@ -1,4 +1,3 @@ -use super::FnCtxt; use hir::def_id::DefId; use hir::Node; use rustc_hir as hir; @@ -6,6 +5,8 @@ use rustc_middle::bug; use rustc_middle::middle::region::{RvalueCandidateType, Scope, ScopeTree}; use rustc_middle::ty::RvalueScopes; +use super::FnCtxt; + /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let` diff --git a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs index c99e8a7fe8ecf..a43164589b5f3 100644 --- a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs +++ b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs @@ -1,4 +1,5 @@ -use super::callee::DeferredCallResolution; +use std::cell::RefCell; +use std::ops::Deref; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_hir as hir; @@ -15,8 +16,7 @@ use rustc_trait_selection::traits::{ self, FulfillmentError, PredicateObligation, TraitEngine, TraitEngineExt as _, }; -use std::cell::RefCell; -use std::ops::Deref; +use super::callee::DeferredCallResolution; /// Data shared between a "typeck root" and its nested bodies, /// e.g. closures defined within the function. For example: diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 466397817dae1..e64f4ebf45df1 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -30,9 +30,9 @@ //! then mean that all later passes would have to check for these figments //! and report an error, and it just seems like more mess in the end.) -use super::FnCtxt; +use std::iter; -use crate::expr_use_visitor as euv; +use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::unord::{ExtendUnord, UnordSet}; use rustc_errors::{Applicability, MultiSpan}; use rustc_hir as hir; @@ -49,14 +49,12 @@ use rustc_middle::ty::{ }; use rustc_middle::{bug, span_bug}; use rustc_session::lint; -use rustc_span::sym; -use rustc_span::{BytePos, Pos, Span, Symbol}; -use rustc_trait_selection::infer::InferCtxtExt; - -use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; +use rustc_span::{sym, BytePos, Pos, Span, Symbol}; use rustc_target::abi::FIRST_VARIANT; +use rustc_trait_selection::infer::InferCtxtExt; -use std::iter; +use super::FnCtxt; +use crate::expr_use_visitor as euv; /// Describe the relationship between the paths of two places /// eg: diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index 4ef7f37b3099f..0327a3097eca2 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -2,7 +2,8 @@ // unresolved type variables and replaces "ty_var" types with their // generic parameters. -use crate::FnCtxt; +use std::mem; + use rustc_data_structures::unord::ExtendUnord; use rustc_errors::{ErrorGuaranteed, StashKey}; use rustc_hir as hir; @@ -13,14 +14,13 @@ use rustc_middle::traits::ObligationCause; use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCoercion}; use rustc_middle::ty::fold::{TypeFoldable, TypeFolder}; use rustc_middle::ty::visit::TypeVisitableExt; -use rustc_middle::ty::TypeSuperFoldable; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperFoldable}; use rustc_span::symbol::sym; use rustc_span::Span; use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded; use rustc_trait_selection::solve; -use std::mem; +use crate::FnCtxt; /////////////////////////////////////////////////////////////////////////// // Entry point diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index 41caa5d4765bc..b29ba59c9f351 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -33,12 +33,12 @@ //! fn baz() { foo(); } //! ``` -use crate::errors; -use rustc_ast as ast; +use std::env; +use std::fs::{self, File}; +use std::io::{BufWriter, Write}; + use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::graph::implementation::{Direction, NodeIndex, INCOMING, OUTGOING}; -use rustc_graphviz as dot; -use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_hir::intravisit::{self, Visitor}; use rustc_middle::dep_graph::{ @@ -49,10 +49,10 @@ use rustc_middle::ty::TyCtxt; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; -use std::env; -use std::fs::{self, File}; -use std::io::{BufWriter, Write}; use tracing::debug; +use {rustc_ast as ast, rustc_graphviz as dot, rustc_hir as hir}; + +use crate::errors; #[allow(missing_docs)] pub fn assert_dep_graph(tcx: TyCtxt<'_>) { diff --git a/compiler/rustc_incremental/src/errors.rs b/compiler/rustc_incremental/src/errors.rs index e94a7fb876bbe..f891003063440 100644 --- a/compiler/rustc_incremental/src/errors.rs +++ b/compiler/rustc_incremental/src/errors.rs @@ -1,7 +1,9 @@ -use rustc_macros::Diagnostic; -use rustc_span::{symbol::Ident, Span, Symbol}; use std::path::{Path, PathBuf}; +use rustc_macros::Diagnostic; +use rustc_span::symbol::Ident; +use rustc_span::{Span, Symbol}; + #[derive(Diagnostic)] #[diag(incremental_unrecognized_depnode)] pub struct UnrecognizedDepNode { diff --git a/compiler/rustc_incremental/src/lib.rs b/compiler/rustc_incremental/src/lib.rs index 76e3c0682debb..fcdcb08eed655 100644 --- a/compiler/rustc_incremental/src/lib.rs +++ b/compiler/rustc_incremental/src/lib.rs @@ -12,14 +12,10 @@ mod assert_dep_graph; mod errors; mod persist; -pub use persist::copy_cgu_workproduct_to_incr_comp_cache_dir; -pub use persist::finalize_session_directory; -pub use persist::in_incr_comp_dir; -pub use persist::in_incr_comp_dir_sess; -pub use persist::load_query_result_cache; -pub use persist::save_dep_graph; -pub use persist::save_work_product_index; -pub use persist::setup_dep_graph; -pub use persist::LoadResult; +pub use persist::{ + copy_cgu_workproduct_to_incr_comp_cache_dir, finalize_session_directory, in_incr_comp_dir, + in_incr_comp_dir_sess, load_query_result_cache, save_dep_graph, save_work_product_index, + setup_dep_graph, LoadResult, +}; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 2a0d681fa37ed..1e02324f4048a 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -19,14 +19,11 @@ //! Errors are reported if we are in the suitable configuration but //! the required condition is not met. -use crate::errors; use rustc_ast::{self as ast, Attribute, NestedMetaItem}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::unord::UnordSet; use rustc_hir::def_id::LocalDefId; -use rustc_hir::intravisit; -use rustc_hir::Node as HirNode; -use rustc_hir::{ImplItemKind, ItemKind as HirItem, TraitItemKind}; +use rustc_hir::{intravisit, ImplItemKind, ItemKind as HirItem, Node as HirNode, TraitItemKind}; use rustc_middle::dep_graph::{label_strs, DepNode, DepNodeExt}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; @@ -35,6 +32,8 @@ use rustc_span::Span; use thin_vec::ThinVec; use tracing::debug; +use crate::errors; + const LOADED_FROM_DISK: Symbol = sym::loaded_from_disk; const EXCEPT: Symbol = sym::except; const CFG: Symbol = sym::cfg; diff --git a/compiler/rustc_incremental/src/persist/file_format.rs b/compiler/rustc_incremental/src/persist/file_format.rs index 303785bdb2206..174414d0c85ef 100644 --- a/compiler/rustc_incremental/src/persist/file_format.rs +++ b/compiler/rustc_incremental/src/persist/file_format.rs @@ -9,18 +9,19 @@ //! compiler versions don't change frequently for the typical user, being //! conservative here practically has no downside. -use crate::errors; +use std::borrow::Cow; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::{env, fs}; + use rustc_data_structures::memmap::Mmap; use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_serialize::Encoder; use rustc_session::Session; -use std::borrow::Cow; -use std::env; -use std::fs; -use std::io::{self, Read}; -use std::path::{Path, PathBuf}; use tracing::debug; +use crate::errors; + /// The first few bytes of files generated by incremental compilation. const FILE_MAGIC: &[u8] = b"RSIC"; diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index 9afea3d66b0de..5f85e622e892a 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -103,30 +103,27 @@ //! unsupported file system and emit a warning in that case. This is not yet //! implemented. -use crate::errors; -use rustc_data_structures::base_n; -use rustc_data_structures::base_n::BaseNString; -use rustc_data_structures::base_n::ToBaseN; -use rustc_data_structures::base_n::CASE_INSENSITIVE; -use rustc_data_structures::flock; +use std::fs as std_fs; +use std::io::{self, ErrorKind}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use rand::{thread_rng, RngCore}; +use rustc_data_structures::base_n::{BaseNString, ToBaseN, CASE_INSENSITIVE}; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_data_structures::svh::Svh; use rustc_data_structures::unord::{UnordMap, UnordSet}; +use rustc_data_structures::{base_n, flock}; use rustc_errors::ErrorGuaranteed; use rustc_fs_util::{link_or_copy, try_canonicalize, LinkOrCopy}; use rustc_middle::bug; use rustc_session::config::CrateType; use rustc_session::output::{collect_crate_types, find_crate_name}; use rustc_session::{Session, StableCrateId}; - -use std::fs as std_fs; -use std::io::{self, ErrorKind}; -use std::path::{Path, PathBuf}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use rand::{thread_rng, RngCore}; use tracing::debug; +use crate::errors; + #[cfg(test)] mod tests; diff --git a/compiler/rustc_incremental/src/persist/load.rs b/compiler/rustc_incremental/src/persist/load.rs index af667a57ce123..18088a10dd00f 100644 --- a/compiler/rustc_incremental/src/persist/load.rs +++ b/compiler/rustc_incremental/src/persist/load.rs @@ -1,6 +1,8 @@ //! Code to load the dep-graph from files. -use crate::errors; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + use rustc_data_structures::memmap::Mmap; use rustc_data_structures::unord::UnordMap; use rustc_middle::dep_graph::{DepGraph, DepsType, SerializedDepGraph, WorkProductMap}; @@ -10,15 +12,13 @@ use rustc_serialize::Decodable; use rustc_session::config::IncrementalStateAssertion; use rustc_session::Session; use rustc_span::ErrorGuaranteed; -use std::path::{Path, PathBuf}; -use std::sync::Arc; use tracing::{debug, warn}; use super::data::*; -use super::file_format; use super::fs::*; use super::save::build_dep_graph; -use super::work_product; +use super::{file_format, work_product}; +use crate::errors; #[derive(Debug)] /// Represents the result of an attempt to load incremental compilation data. diff --git a/compiler/rustc_incremental/src/persist/mod.rs b/compiler/rustc_incremental/src/persist/mod.rs index 94c05f4a2c81e..a529b1dcec082 100644 --- a/compiler/rustc_incremental/src/persist/mod.rs +++ b/compiler/rustc_incremental/src/persist/mod.rs @@ -10,12 +10,7 @@ mod load; mod save; mod work_product; -pub use fs::finalize_session_directory; -pub use fs::in_incr_comp_dir; -pub use fs::in_incr_comp_dir_sess; -pub use load::load_query_result_cache; -pub use load::setup_dep_graph; -pub use load::LoadResult; -pub use save::save_dep_graph; -pub use save::save_work_product_index; +pub use fs::{finalize_session_directory, in_incr_comp_dir, in_incr_comp_dir_sess}; +pub use load::{load_query_result_cache, setup_dep_graph, LoadResult}; +pub use save::{save_dep_graph, save_work_product_index}; pub use work_product::copy_cgu_workproduct_to_incr_comp_cache_dir; diff --git a/compiler/rustc_incremental/src/persist/save.rs b/compiler/rustc_incremental/src/persist/save.rs index 3bf582bd26c61..58a03cb8b30cd 100644 --- a/compiler/rustc_incremental/src/persist/save.rs +++ b/compiler/rustc_incremental/src/persist/save.rs @@ -1,5 +1,6 @@ -use crate::assert_dep_graph::assert_dep_graph; -use crate::errors; +use std::fs; +use std::sync::Arc; + use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::sync::join; use rustc_middle::dep_graph::{ @@ -9,15 +10,13 @@ use rustc_middle::ty::TyCtxt; use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_serialize::Encodable as RustcEncodable; use rustc_session::Session; -use std::fs; -use std::sync::Arc; use tracing::debug; use super::data::*; -use super::dirty_clean; -use super::file_format; use super::fs::*; -use super::work_product; +use super::{dirty_clean, file_format, work_product}; +use crate::assert_dep_graph::assert_dep_graph; +use crate::errors; /// Saves and writes the [`DepGraph`] to the file system. /// diff --git a/compiler/rustc_incremental/src/persist/work_product.rs b/compiler/rustc_incremental/src/persist/work_product.rs index e230da9dfb12f..048981f0d5ce3 100644 --- a/compiler/rustc_incremental/src/persist/work_product.rs +++ b/compiler/rustc_incremental/src/persist/work_product.rs @@ -2,16 +2,18 @@ //! //! [work products]: WorkProduct -use crate::errors; -use crate::persist::fs::*; +use std::fs as std_fs; +use std::path::Path; + use rustc_data_structures::unord::UnordMap; use rustc_fs_util::link_or_copy; use rustc_middle::dep_graph::{WorkProduct, WorkProductId}; use rustc_session::Session; -use std::fs as std_fs; -use std::path::Path; use tracing::debug; +use crate::errors; +use crate::persist::fs::*; + /// Copies a CGU work product to the incremental compilation directory, so next compilation can /// find and reuse it. pub fn copy_cgu_workproduct_to_incr_comp_cache_dir( diff --git a/compiler/rustc_index/src/bit_set.rs b/compiler/rustc_index/src/bit_set.rs index e37af6610dd9b..506afbae40c6e 100644 --- a/compiler/rustc_index/src/bit_set.rs +++ b/compiler/rustc_index/src/bit_set.rs @@ -1,21 +1,16 @@ -use std::fmt; -use std::iter; use std::marker::PhantomData; -use std::mem; use std::ops::{BitAnd, BitAndAssign, BitOrAssign, Bound, Not, Range, RangeBounds, Shl}; use std::rc::Rc; -use std::slice; +use std::{fmt, iter, mem, slice}; use arrayvec::ArrayVec; -use smallvec::{smallvec, SmallVec}; - #[cfg(feature = "nightly")] use rustc_macros::{Decodable_Generic, Encodable_Generic}; +use smallvec::{smallvec, SmallVec}; +use Chunk::*; use crate::{Idx, IndexVec}; -use Chunk::*; - #[cfg(test)] mod tests; diff --git a/compiler/rustc_index/src/bit_set/tests.rs b/compiler/rustc_index/src/bit_set/tests.rs index 351d62feed949..066aa46e35080 100644 --- a/compiler/rustc_index/src/bit_set/tests.rs +++ b/compiler/rustc_index/src/bit_set/tests.rs @@ -2,6 +2,7 @@ use super::*; extern crate test; use std::hint::black_box; + use test::Bencher; #[test] diff --git a/compiler/rustc_index/src/interval.rs b/compiler/rustc_index/src/interval.rs index 0c1180b3e9800..be028feca605f 100644 --- a/compiler/rustc_index/src/interval.rs +++ b/compiler/rustc_index/src/interval.rs @@ -1,7 +1,6 @@ use std::iter::Step; use std::marker::PhantomData; -use std::ops::RangeBounds; -use std::ops::{Bound, Range}; +use std::ops::{Bound, Range, RangeBounds}; use smallvec::SmallVec; diff --git a/compiler/rustc_index/src/lib.rs b/compiler/rustc_index/src/lib.rs index b775ae1f5e944..b5e4f02a8d15c 100644 --- a/compiler/rustc_index/src/lib.rs +++ b/compiler/rustc_index/src/lib.rs @@ -12,9 +12,10 @@ mod idx; mod slice; mod vec; -pub use {idx::Idx, slice::IndexSlice, vec::IndexVec}; - +pub use idx::Idx; pub use rustc_index_macros::newtype_index; +pub use slice::IndexSlice; +pub use vec::IndexVec; /// Type size assertion. The first argument is a type and the second argument is its expected size. /// diff --git a/compiler/rustc_index/src/slice.rs b/compiler/rustc_index/src/slice.rs index 0663c7247ded8..3205ca3f40be2 100644 --- a/compiler/rustc_index/src/slice.rs +++ b/compiler/rustc_index/src/slice.rs @@ -1,9 +1,6 @@ -use std::{ - fmt, - marker::PhantomData, - ops::{Index, IndexMut}, - slice, -}; +use std::marker::PhantomData; +use std::ops::{Index, IndexMut}; +use std::{fmt, slice}; use crate::{Idx, IndexVec}; diff --git a/compiler/rustc_index/src/vec.rs b/compiler/rustc_index/src/vec.rs index 346ce945bf94b..7438c97eb581c 100644 --- a/compiler/rustc_index/src/vec.rs +++ b/compiler/rustc_index/src/vec.rs @@ -1,13 +1,11 @@ -#[cfg(feature = "nightly")] -use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; - use std::borrow::{Borrow, BorrowMut}; -use std::fmt; use std::hash::Hash; use std::marker::PhantomData; use std::ops::{Deref, DerefMut, RangeBounds}; -use std::slice; -use std::vec; +use std::{fmt, slice, vec}; + +#[cfg(feature = "nightly")] +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use crate::{Idx, IndexSlice}; diff --git a/compiler/rustc_infer/src/infer/at.rs b/compiler/rustc_infer/src/infer/at.rs index fc7a22833ff05..9f6a17638664e 100644 --- a/compiler/rustc_infer/src/infer/at.rs +++ b/compiler/rustc_infer/src/infer/at.rs @@ -25,12 +25,11 @@ //! sometimes useful when the types of `c` and `d` are not traceable //! things. (That system should probably be refactored.) -use super::*; - -use crate::infer::relate::{Relate, StructurallyRelateAliases, TypeRelation}; use rustc_middle::bug; use rustc_middle::ty::{Const, ImplSubject}; +use super::*; +use crate::infer::relate::{Relate, StructurallyRelateAliases, TypeRelation}; use crate::traits::Obligation; /// Whether we should define opaque types or just treat them opaquely. diff --git a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index 1659f3d049370..3bcb92d8029a2 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -5,18 +5,19 @@ //! //! [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html +use rustc_data_structures::fx::FxHashMap; +use rustc_index::Idx; +use rustc_middle::bug; +use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; +use rustc_middle::ty::{ + self, BoundVar, GenericArg, InferConst, List, Ty, TyCtxt, TypeFlags, TypeVisitableExt, +}; +use smallvec::SmallVec; + use crate::infer::canonical::{ Canonical, CanonicalTyVarKind, CanonicalVarInfo, CanonicalVarKind, OriginalQueryValues, }; use crate::infer::InferCtxt; -use rustc_middle::bug; -use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; -use rustc_middle::ty::GenericArg; -use rustc_middle::ty::{self, BoundVar, InferConst, List, Ty, TyCtxt, TypeFlags, TypeVisitableExt}; - -use rustc_data_structures::fx::FxHashMap; -use rustc_index::Idx; -use smallvec::SmallVec; impl<'tcx> InferCtxt<'tcx> { /// Canonicalizes a query value `V`. When we canonicalize a query, diff --git a/compiler/rustc_infer/src/infer/canonical/instantiate.rs b/compiler/rustc_infer/src/infer/canonical/instantiate.rs index 153de3d4c09d8..c10df2ec02e1d 100644 --- a/compiler/rustc_infer/src/infer/canonical/instantiate.rs +++ b/compiler/rustc_infer/src/infer/canonical/instantiate.rs @@ -6,12 +6,12 @@ //! //! [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html -use crate::infer::canonical::{Canonical, CanonicalVarValues}; use rustc_macros::extension; use rustc_middle::bug; use rustc_middle::ty::fold::{FnMutDelegate, TypeFoldable}; -use rustc_middle::ty::GenericArgKind; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{self, GenericArgKind, TyCtxt}; + +use crate::infer::canonical::{Canonical, CanonicalVarValues}; /// FIXME(-Znext-solver): This or public because it is shared with the /// new trait solver implementation. We should deduplicate canonicalization. diff --git a/compiler/rustc_infer/src/infer/canonical/mod.rs b/compiler/rustc_infer/src/infer/canonical/mod.rs index 8ad4f7926cad3..8caedcd4053bb 100644 --- a/compiler/rustc_infer/src/infer/canonical/mod.rs +++ b/compiler/rustc_infer/src/infer/canonical/mod.rs @@ -21,16 +21,15 @@ //! //! [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html -use crate::infer::{InferCtxt, RegionVariableOrigin}; +pub use instantiate::CanonicalExt; use rustc_index::IndexVec; +pub use rustc_middle::infer::canonical::*; use rustc_middle::infer::unify_key::EffectVarValue; use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::GenericArg; -use rustc_middle::ty::{self, List, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArg, List, Ty, TyCtxt}; use rustc_span::Span; -pub use instantiate::CanonicalExt; -pub use rustc_middle::infer::canonical::*; +use crate::infer::{InferCtxt, RegionVariableOrigin}; mod canonicalizer; mod instantiate; diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index d7dd6a1e7cf53..85e3cfbcce1c1 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -7,6 +7,17 @@ //! //! [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html +use std::fmt::Debug; +use std::iter; + +use rustc_data_structures::captures::Captures; +use rustc_index::{Idx, IndexVec}; +use rustc_middle::arena::ArenaAllocatable; +use rustc_middle::mir::ConstraintCategory; +use rustc_middle::ty::fold::TypeFoldable; +use rustc_middle::ty::{self, BoundVar, GenericArg, GenericArgKind, Ty, TyCtxt}; +use rustc_middle::{bug, span_bug}; + use crate::infer::canonical::instantiate::{instantiate_value, CanonicalExt}; use crate::infer::canonical::{ Canonical, CanonicalQueryResponse, CanonicalVarValues, Certainty, OriginalQueryValues, @@ -15,19 +26,9 @@ use crate::infer::canonical::{ use crate::infer::region_constraints::{Constraint, RegionConstraintData}; use crate::infer::{DefineOpaqueTypes, InferCtxt, InferOk, InferResult}; use crate::traits::query::NoSolution; -use crate::traits::{Obligation, ObligationCause, PredicateObligation}; -use crate::traits::{ScrubbedTraitError, TraitEngine}; -use rustc_data_structures::captures::Captures; -use rustc_index::Idx; -use rustc_index::IndexVec; -use rustc_middle::arena::ArenaAllocatable; -use rustc_middle::mir::ConstraintCategory; -use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::{self, BoundVar, Ty, TyCtxt}; -use rustc_middle::ty::{GenericArg, GenericArgKind}; -use rustc_middle::{bug, span_bug}; -use std::fmt::Debug; -use std::iter; +use crate::traits::{ + Obligation, ObligationCause, PredicateObligation, ScrubbedTraitError, TraitEngine, +}; impl<'tcx> InferCtxt<'tcx> { /// This method is meant to be invoked as the final step of a canonical query diff --git a/compiler/rustc_infer/src/infer/freshen.rs b/compiler/rustc_infer/src/infer/freshen.rs index de4267f7ceadd..c4294111ebe85 100644 --- a/compiler/rustc_infer/src/infer/freshen.rs +++ b/compiler/rustc_infer/src/infer/freshen.rs @@ -31,12 +31,14 @@ //! variable only once, and it does so as soon as it can, so it is reasonable to ask what the type //! inferencer knows "so far". -use super::InferCtxt; +use std::collections::hash_map::Entry; + use rustc_data_structures::fx::FxHashMap; use rustc_middle::bug; use rustc_middle::ty::fold::TypeFolder; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, TypeVisitableExt}; -use std::collections::hash_map::Entry; + +use super::InferCtxt; pub struct TypeFreshener<'a, 'tcx> { infcx: &'a InferCtxt<'tcx>, diff --git a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs index 72944c9c7de68..c2c0c7a41feac 100644 --- a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs +++ b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs @@ -1,13 +1,7 @@ //! Lexical region resolution. -use crate::infer::region_constraints::Constraint; -use crate::infer::region_constraints::GenericKind; -use crate::infer::region_constraints::RegionConstraintData; -use crate::infer::region_constraints::VarInfos; -use crate::infer::region_constraints::VerifyBound; -use crate::infer::RegionRelations; -use crate::infer::RegionVariableOrigin; -use crate::infer::SubregionOrigin; +use std::fmt; + use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::graph::implementation::{ Direction, Graph, NodeIndex, INCOMING, OUTGOING, @@ -16,15 +10,18 @@ use rustc_data_structures::intern::Interned; use rustc_data_structures::unord::UnordSet; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_middle::ty::{ReBound, RePlaceholder, ReVar}; -use rustc_middle::ty::{ReEarlyParam, ReErased, ReError, ReLateParam, ReStatic}; -use rustc_middle::ty::{Region, RegionVid}; +use rustc_middle::ty::{ + self, ReBound, ReEarlyParam, ReErased, ReError, ReLateParam, RePlaceholder, ReStatic, ReVar, + Region, RegionVid, Ty, TyCtxt, +}; use rustc_middle::{bug, span_bug}; use rustc_span::Span; -use std::fmt; use super::outlives::test_type_match; +use crate::infer::region_constraints::{ + Constraint, GenericKind, RegionConstraintData, VarInfos, VerifyBound, +}; +use crate::infer::{RegionRelations, RegionVariableOrigin, SubregionOrigin}; /// This function performs lexical region resolution given a complete /// set of constraints and variable origins. It performs a fixed-point diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 3cee0a622f17b..f2fc25a2d2e10 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -1,55 +1,56 @@ -pub use at::DefineOpaqueTypes; -pub use freshen::TypeFreshener; -pub use lexical_region_resolve::RegionResolutionError; -pub use relate::combine::CombineFields; -pub use relate::combine::PredicateEmittingRelation; -pub use relate::StructurallyRelateAliases; -use rustc_errors::DiagCtxtHandle; -pub use rustc_macros::{TypeFoldable, TypeVisitable}; -pub use rustc_middle::ty::IntVarValue; -pub use BoundRegionConversionTime::*; -pub use RegionVariableOrigin::*; -pub use SubregionOrigin::*; +use std::cell::{Cell, RefCell}; +use std::fmt; -use crate::infer::relate::RelateResult; -use crate::traits::{self, ObligationCause, ObligationInspector, PredicateObligation, TraitEngine}; +pub use at::DefineOpaqueTypes; use free_regions::RegionRelations; +pub use freshen::TypeFreshener; use lexical_region_resolve::LexicalRegionResolutions; +pub use lexical_region_resolve::RegionResolutionError; use opaque_types::OpaqueTypeStorage; -use region_constraints::{GenericKind, VarInfos, VerifyBound}; -use region_constraints::{RegionConstraintCollector, RegionConstraintStorage}; +use region_constraints::{ + GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound, +}; +pub use relate::combine::{CombineFields, PredicateEmittingRelation}; +pub use relate::StructurallyRelateAliases; use rustc_data_structures::captures::Captures; -use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; +use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::sync::Lrc; use rustc_data_structures::undo_log::Rollback; use rustc_data_structures::unify as ut; -use rustc_errors::ErrorGuaranteed; +use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_macros::extension; +pub use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues}; -use rustc_middle::infer::unify_key::ConstVariableOrigin; -use rustc_middle::infer::unify_key::ConstVariableValue; -use rustc_middle::infer::unify_key::EffectVarValue; -use rustc_middle::infer::unify_key::{ConstVidKey, EffectVidKey}; +use rustc_middle::infer::unify_key::{ + ConstVariableOrigin, ConstVariableValue, ConstVidKey, EffectVarValue, EffectVidKey, +}; use rustc_middle::mir::interpret::{ErrorHandled, EvalToValTreeResult}; use rustc_middle::mir::ConstraintCategory; use rustc_middle::traits::select; use rustc_middle::traits::solve::{Goal, NoSolution}; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::fold::BoundVarReplacerDelegate; -use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; +use rustc_middle::ty::fold::{ + BoundVarReplacerDelegate, TypeFoldable, TypeFolder, TypeSuperFoldable, +}; use rustc_middle::ty::visit::TypeVisitableExt; -use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt}; -use rustc_middle::ty::{ConstVid, EffectVid, FloatVid, IntVid, TyVid}; -use rustc_middle::ty::{GenericArg, GenericArgKind, GenericArgs, GenericArgsRef}; +pub use rustc_middle::ty::IntVarValue; +use rustc_middle::ty::{ + self, ConstVid, EffectVid, FloatVid, GenericArg, GenericArgKind, GenericArgs, GenericArgsRef, + GenericParamDefKind, InferConst, IntVid, Ty, TyCtxt, TyVid, +}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::Symbol; use rustc_span::Span; use snapshot::undo_log::InferCtxtUndoLogs; -use std::cell::{Cell, RefCell}; -use std::fmt; use type_variable::TypeVariableOrigin; +pub use BoundRegionConversionTime::*; +pub use RegionVariableOrigin::*; +pub use SubregionOrigin::*; + +use crate::infer::relate::RelateResult; +use crate::traits::{self, ObligationCause, ObligationInspector, PredicateObligation, TraitEngine}; pub mod at; pub mod canonical; @@ -1317,38 +1318,36 @@ impl<'tcx> InferCtxt<'tcx> { return inner; } - struct ToFreshVars<'a, 'tcx> { - infcx: &'a InferCtxt<'tcx>, - span: Span, - lbrct: BoundRegionConversionTime, - map: FxHashMap>, + let bound_vars = value.bound_vars(); + let mut args = Vec::with_capacity(bound_vars.len()); + + for bound_var_kind in bound_vars { + let arg: ty::GenericArg<'_> = match bound_var_kind { + ty::BoundVariableKind::Ty(_) => self.next_ty_var(span).into(), + ty::BoundVariableKind::Region(br) => { + self.next_region_var(BoundRegion(span, br, lbrct)).into() + } + ty::BoundVariableKind::Const => self.next_const_var(span).into(), + }; + args.push(arg); + } + + struct ToFreshVars<'tcx> { + args: Vec>, } - impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'_, 'tcx> { + impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> { fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> { - self.map - .entry(br.var) - .or_insert_with(|| { - self.infcx - .next_region_var(BoundRegion(self.span, br.kind, self.lbrct)) - .into() - }) - .expect_region() + self.args[br.var.index()].expect_region() } fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> { - self.map - .entry(bt.var) - .or_insert_with(|| self.infcx.next_ty_var(self.span).into()) - .expect_ty() + self.args[bt.var.index()].expect_ty() } fn replace_const(&mut self, bv: ty::BoundVar) -> ty::Const<'tcx> { - self.map - .entry(bv) - .or_insert_with(|| self.infcx.next_const_var(self.span).into()) - .expect_const() + self.args[bv.index()].expect_const() } } - let delegate = ToFreshVars { infcx: self, span, lbrct, map: Default::default() }; + let delegate = ToFreshVars { args }; self.tcx.replace_bound_vars_uncached(value, delegate) } diff --git a/compiler/rustc_infer/src/infer/opaque_types/mod.rs b/compiler/rustc_infer/src/infer/opaque_types/mod.rs index 7c764cccc4772..e9726ee8ebf3b 100644 --- a/compiler/rustc_infer/src/infer/opaque_types/mod.rs +++ b/compiler/rustc_infer/src/infer/opaque_types/mod.rs @@ -1,6 +1,3 @@ -use crate::errors::OpaqueHiddenTypeDiag; -use crate::infer::{InferCtxt, InferOk}; -use crate::traits::{self, Obligation}; use hir::def_id::{DefId, LocalDefId}; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::sync::Lrc; @@ -9,13 +6,16 @@ use rustc_middle::traits::solve::Goal; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::fold::BottomUpFolder; -use rustc_middle::ty::GenericArgKind; use rustc_middle::ty::{ - self, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, - TypeVisitable, TypeVisitableExt, TypeVisitor, + self, GenericArgKind, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, + TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, }; use rustc_span::Span; +use crate::errors::OpaqueHiddenTypeDiag; +use crate::infer::{InferCtxt, InferOk}; +use crate::traits::{self, Obligation}; + mod table; pub type OpaqueTypeMap<'tcx> = FxIndexMap, OpaqueTypeDecl<'tcx>>; diff --git a/compiler/rustc_infer/src/infer/opaque_types/table.rs b/compiler/rustc_infer/src/infer/opaque_types/table.rs index e07d181e4e0a3..7b4e546d8318f 100644 --- a/compiler/rustc_infer/src/infer/opaque_types/table.rs +++ b/compiler/rustc_infer/src/infer/opaque_types/table.rs @@ -2,9 +2,8 @@ use rustc_data_structures::undo_log::UndoLogs; use rustc_middle::bug; use rustc_middle::ty::{self, OpaqueHiddenType, OpaqueTypeKey, Ty}; -use crate::infer::snapshot::undo_log::{InferCtxtUndoLogs, UndoLog}; - use super::{OpaqueTypeDecl, OpaqueTypeMap}; +use crate::infer::snapshot::undo_log::{InferCtxtUndoLogs, UndoLog}; #[derive(Default, Debug, Clone)] pub struct OpaqueTypeStorage<'tcx> { diff --git a/compiler/rustc_infer/src/infer/outlives/env.rs b/compiler/rustc_infer/src/infer/outlives/env.rs index 5bcb4f29364d7..cc763707c9cfb 100644 --- a/compiler/rustc_infer/src/infer/outlives/env.rs +++ b/compiler/rustc_infer/src/infer/outlives/env.rs @@ -1,12 +1,12 @@ -use crate::infer::free_regions::FreeRegionMap; -use crate::infer::GenericKind; -use crate::traits::query::OutlivesBound; use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::transitive_relation::TransitiveRelationBuilder; use rustc_middle::bug; use rustc_middle::ty::{self, Region}; use super::explicit_outlives_bounds; +use crate::infer::free_regions::FreeRegionMap; +use crate::infer::GenericKind; +use crate::traits::query::OutlivesBound; /// The `OutlivesEnvironment` collects information about what outlives /// what in a given type-checking setting. For example, if we have a diff --git a/compiler/rustc_infer/src/infer/outlives/mod.rs b/compiler/rustc_infer/src/infer/outlives/mod.rs index 89ff460456027..e4eefbc7a1a8b 100644 --- a/compiler/rustc_infer/src/infer/outlives/mod.rs +++ b/compiler/rustc_infer/src/infer/outlives/mod.rs @@ -1,12 +1,13 @@ //! Various code related to computing outlives relations. +use rustc_middle::traits::query::{NoSolution, OutlivesBound}; +use rustc_middle::ty; + use self::env::OutlivesEnvironment; use super::region_constraints::RegionConstraintData; use super::{InferCtxt, RegionResolutionError, SubregionOrigin}; use crate::infer::free_regions::RegionRelations; use crate::infer::lexical_region_resolve; -use rustc_middle::traits::query::{NoSolution, OutlivesBound}; -use rustc_middle::ty; pub mod env; pub mod for_liveness; diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index d82ae7b4fb888..88b004adc9418 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -59,25 +59,25 @@ //! might later infer `?U` to something like `&'b u32`, which would //! imply that `'b: 'a`. -use crate::infer::outlives::env::RegionBoundPairs; -use crate::infer::outlives::verify::VerifyBoundCx; -use crate::infer::resolve::OpportunisticRegionResolver; -use crate::infer::snapshot::undo_log::UndoLog; -use crate::infer::{self, GenericKind, InferCtxt, RegionObligation, SubregionOrigin, VerifyBound}; -use crate::traits::{ObligationCause, ObligationCauseCode}; use rustc_data_structures::undo_log::UndoLogs; use rustc_middle::bug; use rustc_middle::mir::ConstraintCategory; use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::{ - self, GenericArgsRef, Region, Ty, TyCtxt, TypeFoldable as _, TypeVisitableExt, + self, GenericArgKind, GenericArgsRef, PolyTypeOutlivesPredicate, Region, Ty, TyCtxt, + TypeFoldable as _, TypeVisitableExt, }; -use rustc_middle::ty::{GenericArgKind, PolyTypeOutlivesPredicate}; use rustc_span::DUMMY_SP; use rustc_type_ir::outlives::{push_outlives_components, Component}; use smallvec::smallvec; use super::env::OutlivesEnvironment; +use crate::infer::outlives::env::RegionBoundPairs; +use crate::infer::outlives::verify::VerifyBoundCx; +use crate::infer::resolve::OpportunisticRegionResolver; +use crate::infer::snapshot::undo_log::UndoLog; +use crate::infer::{self, GenericKind, InferCtxt, RegionObligation, SubregionOrigin, VerifyBound}; +use crate::traits::{ObligationCause, ObligationCauseCode}; impl<'tcx> InferCtxt<'tcx> { /// Registers that the given region obligation must be resolved diff --git a/compiler/rustc_infer/src/infer/outlives/test_type_match.rs b/compiler/rustc_infer/src/infer/outlives/test_type_match.rs index c63eeaf812c4e..835e34a3535bf 100644 --- a/compiler/rustc_infer/src/infer/outlives/test_type_match.rs +++ b/compiler/rustc_infer/src/infer/outlives/test_type_match.rs @@ -2,8 +2,7 @@ use std::collections::hash_map::Entry; use rustc_data_structures::fx::FxHashMap; use rustc_middle::ty::error::TypeError; -use rustc_middle::ty::TypeVisitableExt; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; use crate::infer::region_constraints::VerifyIfEq; use crate::infer::relate::{self as relate, Relate, RelateResult, TypeRelation}; diff --git a/compiler/rustc_infer/src/infer/outlives/verify.rs b/compiler/rustc_infer/src/infer/outlives/verify.rs index 2392a82025a46..c3d37d9986f6c 100644 --- a/compiler/rustc_infer/src/infer/outlives/verify.rs +++ b/compiler/rustc_infer/src/infer/outlives/verify.rs @@ -1,11 +1,11 @@ -use crate::infer::outlives::env::RegionBoundPairs; -use crate::infer::region_constraints::VerifyIfEq; -use crate::infer::{GenericKind, VerifyBound}; use rustc_middle::ty::{self, OutlivesPredicate, Ty, TyCtxt}; use rustc_type_ir::outlives::{compute_alias_components_recursive, Component}; - use smallvec::smallvec; +use crate::infer::outlives::env::RegionBoundPairs; +use crate::infer::region_constraints::VerifyIfEq; +use crate::infer::{GenericKind, VerifyBound}; + /// The `TypeOutlives` struct has the job of "lowering" a `T: 'a` /// obligation into a series of `'a: 'b` constraints and "verifys", as /// described on the module comment. The final constraints are emitted diff --git a/compiler/rustc_infer/src/infer/projection.rs b/compiler/rustc_infer/src/infer/projection.rs index a1ba43eb17159..b78f9d4926853 100644 --- a/compiler/rustc_infer/src/infer/projection.rs +++ b/compiler/rustc_infer/src/infer/projection.rs @@ -1,9 +1,8 @@ use rustc_middle::traits::ObligationCause; use rustc_middle::ty::{self, Ty}; -use crate::traits::{Obligation, PredicateObligation}; - use super::InferCtxt; +use crate::traits::{Obligation, PredicateObligation}; impl<'tcx> InferCtxt<'tcx> { /// Instead of normalizing an associated type projection, diff --git a/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs b/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs index 5b159d6273121..3d2a0a3356fd7 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/leak_check.rs @@ -1,12 +1,14 @@ -use super::*; -use crate::infer::relate::RelateResult; -use crate::infer::snapshot::CombinedSnapshot; use rustc_data_structures::fx::FxIndexMap; -use rustc_data_structures::graph::{scc::Sccs, vec_graph::VecGraph}; +use rustc_data_structures::graph::scc::Sccs; +use rustc_data_structures::graph::vec_graph::VecGraph; use rustc_index::Idx; use rustc_middle::span_bug; use rustc_middle::ty::error::TypeError; +use super::*; +use crate::infer::relate::RelateResult; +use crate::infer::snapshot::CombinedSnapshot; + impl<'tcx> RegionConstraintCollector<'_, 'tcx> { /// Searches new universes created during `snapshot`, looking for /// placeholders that may "leak" out from the universes they are contained diff --git a/compiler/rustc_infer/src/infer/region_constraints/mod.rs b/compiler/rustc_infer/src/infer/region_constraints/mod.rs index 6f755e07ff17d..6ee95c73cfbd9 100644 --- a/compiler/rustc_infer/src/infer/region_constraints/mod.rs +++ b/compiler/rustc_infer/src/infer/region_constraints/mod.rs @@ -1,10 +1,7 @@ //! See `README.md`. -use self::CombineMapType::*; -use self::UndoLog::*; - -use super::{MiscVariable, RegionVariableOrigin, Rollback, SubregionOrigin}; -use crate::infer::snapshot::undo_log::{InferCtxtUndoLogs, Snapshot}; +use std::ops::Range; +use std::{cmp, fmt, mem}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lrc; @@ -13,15 +10,14 @@ use rustc_data_structures::unify as ut; use rustc_index::IndexVec; use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_middle::infer::unify_key::{RegionVariableValue, RegionVidKey}; -use rustc_middle::ty::ReStatic; -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_middle::ty::{ReBound, ReVar}; -use rustc_middle::ty::{Region, RegionVid}; +use rustc_middle::ty::{self, ReBound, ReStatic, ReVar, Region, RegionVid, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_span::Span; -use std::ops::Range; -use std::{cmp, fmt, mem}; +use self::CombineMapType::*; +use self::UndoLog::*; +use super::{MiscVariable, RegionVariableOrigin, Rollback, SubregionOrigin}; +use crate::infer::snapshot::undo_log::{InferCtxtUndoLogs, Snapshot}; mod leak_check; diff --git a/compiler/rustc_infer/src/infer/relate/combine.rs b/compiler/rustc_infer/src/infer/relate/combine.rs index 1dc03de4c8ba0..5751ce466d982 100644 --- a/compiler/rustc_infer/src/infer/relate/combine.rs +++ b/compiler/rustc_infer/src/infer/relate/combine.rs @@ -18,22 +18,19 @@ //! On success, the LUB/GLB operations return the appropriate bound. The //! return value of `Equate` or `Sub` shouldn't really be used. +use rustc_middle::bug; +use rustc_middle::infer::unify_key::EffectVarValue; +use rustc_middle::traits::solve::Goal; +use rustc_middle::ty::error::{ExpectedFound, TypeError}; +use rustc_middle::ty::{self, InferConst, IntType, Ty, TyCtxt, TypeVisitableExt, UintType, Upcast}; pub use rustc_next_trait_solver::relate::combine::*; use super::glb::Glb; use super::lub::Lub; use super::type_relating::TypeRelating; -use super::RelateResult; -use super::StructurallyRelateAliases; -use crate::infer::relate; -use crate::infer::{DefineOpaqueTypes, InferCtxt, TypeTrace}; +use super::{RelateResult, StructurallyRelateAliases}; +use crate::infer::{relate, DefineOpaqueTypes, InferCtxt, TypeTrace}; use crate::traits::{Obligation, PredicateObligation}; -use rustc_middle::bug; -use rustc_middle::infer::unify_key::EffectVarValue; -use rustc_middle::traits::solve::Goal; -use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::{self, InferConst, Ty, TyCtxt, TypeVisitableExt, Upcast}; -use rustc_middle::ty::{IntType, UintType}; #[derive(Clone)] pub struct CombineFields<'infcx, 'tcx> { diff --git a/compiler/rustc_infer/src/infer/relate/generalize.rs b/compiler/rustc_infer/src/infer/relate/generalize.rs index 30cfbcae6b263..542104fa10ba0 100644 --- a/compiler/rustc_infer/src/infer/relate/generalize.rs +++ b/compiler/rustc_infer/src/infer/relate/generalize.rs @@ -1,10 +1,5 @@ use std::mem; -use super::StructurallyRelateAliases; -use super::{PredicateEmittingRelation, Relate, RelateResult, TypeRelation}; -use crate::infer::relate; -use crate::infer::type_variable::TypeVariableValue; -use crate::infer::{InferCtxt, RegionVariableOrigin}; use rustc_data_structures::sso::SsoHashMap; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir::def_id::DefId; @@ -12,10 +7,17 @@ use rustc_middle::bug; use rustc_middle::infer::unify_key::ConstVariableValue; use rustc_middle::ty::error::TypeError; use rustc_middle::ty::visit::MaxUniverse; -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_middle::ty::{AliasRelationDirection, InferConst, Term, TypeVisitable, TypeVisitableExt}; +use rustc_middle::ty::{ + self, AliasRelationDirection, InferConst, Term, Ty, TyCtxt, TypeVisitable, TypeVisitableExt, +}; use rustc_span::Span; +use super::{ + PredicateEmittingRelation, Relate, RelateResult, StructurallyRelateAliases, TypeRelation, +}; +use crate::infer::type_variable::TypeVariableValue; +use crate::infer::{relate, InferCtxt, RegionVariableOrigin}; + impl<'tcx> InferCtxt<'tcx> { /// The idea is that we should ensure that the type variable `target_vid` /// is equal to, a subtype of, or a supertype of `source_ty`. diff --git a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs index cfce28aca5d6a..c808ab5e6dd10 100644 --- a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs +++ b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs @@ -1,11 +1,12 @@ //! Helper routines for higher-ranked things. See the `doc` module at //! the end of the file for details. +use rustc_middle::ty::fold::FnMutDelegate; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; + use super::RelateResult; use crate::infer::snapshot::CombinedSnapshot; use crate::infer::InferCtxt; -use rustc_middle::ty::fold::FnMutDelegate; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; impl<'tcx> InferCtxt<'tcx> { /// Replaces all bound variables (lifetimes, types, and constants) bound by diff --git a/compiler/rustc_infer/src/infer/relate/lattice.rs b/compiler/rustc_infer/src/infer/relate/lattice.rs index d1d870715622f..f555fedbb5bcd 100644 --- a/compiler/rustc_infer/src/infer/relate/lattice.rs +++ b/compiler/rustc_infer/src/infer/relate/lattice.rs @@ -17,14 +17,13 @@ //! //! [lattices]: https://en.wikipedia.org/wiki/Lattice_(order) +use rustc_middle::ty::relate::RelateResult; +use rustc_middle::ty::{self, Ty, TyVar}; + use super::combine::PredicateEmittingRelation; use crate::infer::{DefineOpaqueTypes, InferCtxt}; use crate::traits::ObligationCause; -use rustc_middle::ty::relate::RelateResult; -use rustc_middle::ty::TyVar; -use rustc_middle::ty::{self, Ty}; - /// Trait for returning data about a lattice, and for abstracting /// over the "direction" of the lattice operation (LUB/GLB). /// diff --git a/compiler/rustc_infer/src/infer/relate/lub.rs b/compiler/rustc_infer/src/infer/relate/lub.rs index 2eb20f311cf4a..046e93b63e4cb 100644 --- a/compiler/rustc_infer/src/infer/relate/lub.rs +++ b/compiler/rustc_infer/src/infer/relate/lub.rs @@ -1,16 +1,16 @@ //! Least upper bound. See [`lattice`]. +use rustc_middle::traits::solve::Goal; +use rustc_middle::ty::relate::{Relate, RelateResult, TypeRelation}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; +use rustc_span::Span; + use super::combine::{CombineFields, PredicateEmittingRelation}; use super::lattice::{self, LatticeDir}; use super::StructurallyRelateAliases; use crate::infer::{DefineOpaqueTypes, InferCtxt, SubregionOrigin}; use crate::traits::ObligationCause; -use rustc_middle::traits::solve::Goal; -use rustc_middle::ty::relate::{Relate, RelateResult, TypeRelation}; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; -use rustc_span::Span; - /// "Least upper bound" (common supertype) pub struct Lub<'combine, 'infcx, 'tcx> { fields: &'combine mut CombineFields<'infcx, 'tcx>, diff --git a/compiler/rustc_infer/src/infer/relate/mod.rs b/compiler/rustc_infer/src/infer/relate/mod.rs index dd97dc061fe2c..183ea5b3309a9 100644 --- a/compiler/rustc_infer/src/infer/relate/mod.rs +++ b/compiler/rustc_infer/src/infer/relate/mod.rs @@ -5,8 +5,7 @@ pub use rustc_middle::ty::relate::RelateResult; pub use rustc_next_trait_solver::relate::*; -pub use self::combine::CombineFields; -pub use self::combine::PredicateEmittingRelation; +pub use self::combine::{CombineFields, PredicateEmittingRelation}; #[allow(hidden_glob_reexports)] pub(super) mod combine; diff --git a/compiler/rustc_infer/src/infer/relate/type_relating.rs b/compiler/rustc_infer/src/infer/relate/type_relating.rs index 3fe3535428626..ec600c60b240b 100644 --- a/compiler/rustc_infer/src/infer/relate/type_relating.rs +++ b/compiler/rustc_infer/src/infer/relate/type_relating.rs @@ -1,15 +1,15 @@ -use super::combine::CombineFields; -use crate::infer::relate::{PredicateEmittingRelation, StructurallyRelateAliases}; -use crate::infer::BoundRegionConversionTime::HigherRankedType; -use crate::infer::{DefineOpaqueTypes, InferCtxt, SubregionOrigin}; use rustc_middle::traits::solve::Goal; use rustc_middle::ty::relate::{ relate_args_invariantly, relate_args_with_variances, Relate, RelateResult, TypeRelation, }; -use rustc_middle::ty::TyVar; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt, TyVar}; use rustc_span::Span; +use super::combine::CombineFields; +use crate::infer::relate::{PredicateEmittingRelation, StructurallyRelateAliases}; +use crate::infer::BoundRegionConversionTime::HigherRankedType; +use crate::infer::{DefineOpaqueTypes, InferCtxt, SubregionOrigin}; + /// Enforce that `a` is equal to or a subtype of `b`. pub struct TypeRelating<'combine, 'a, 'tcx> { fields: &'combine mut CombineFields<'a, 'tcx>, diff --git a/compiler/rustc_infer/src/infer/resolve.rs b/compiler/rustc_infer/src/infer/resolve.rs index ed75fd183f29d..34625ffb77879 100644 --- a/compiler/rustc_infer/src/infer/resolve.rs +++ b/compiler/rustc_infer/src/infer/resolve.rs @@ -1,9 +1,10 @@ -use super::{FixupError, FixupResult, InferCtxt}; use rustc_middle::bug; use rustc_middle::ty::fold::{FallibleTypeFolder, TypeFolder, TypeSuperFoldable}; use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{self, Const, InferConst, Ty, TyCtxt, TypeFoldable}; +use super::{FixupError, FixupResult, InferCtxt}; + /////////////////////////////////////////////////////////////////////////// // OPPORTUNISTIC VAR RESOLVER diff --git a/compiler/rustc_infer/src/infer/snapshot/fudge.rs b/compiler/rustc_infer/src/infer/snapshot/fudge.rs index f15bd0babee5c..bc954054ea281 100644 --- a/compiler/rustc_infer/src/infer/snapshot/fudge.rs +++ b/compiler/rustc_infer/src/infer/snapshot/fudge.rs @@ -1,16 +1,13 @@ +use std::ops::Range; + +use rustc_data_structures::{snapshot_vec as sv, unify as ut}; use rustc_middle::infer::unify_key::{ConstVariableValue, ConstVidKey}; use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_middle::ty::{self, ConstVid, FloatVid, IntVid, RegionVid, Ty, TyCtxt, TyVid}; - -use crate::infer::type_variable::TypeVariableOrigin; -use crate::infer::InferCtxt; -use crate::infer::{ConstVariableOrigin, RegionVariableOrigin, UnificationTable}; - -use rustc_data_structures::snapshot_vec as sv; -use rustc_data_structures::unify as ut; use ut::UnifyKey; -use std::ops::Range; +use crate::infer::type_variable::TypeVariableOrigin; +use crate::infer::{ConstVariableOrigin, InferCtxt, RegionVariableOrigin, UnificationTable}; fn vars_since_snapshot<'tcx, T>( table: &UnificationTable<'_, 'tcx, T>, diff --git a/compiler/rustc_infer/src/infer/snapshot/mod.rs b/compiler/rustc_infer/src/infer/snapshot/mod.rs index 9eef1471b1af2..d76b9b00001a2 100644 --- a/compiler/rustc_infer/src/infer/snapshot/mod.rs +++ b/compiler/rustc_infer/src/infer/snapshot/mod.rs @@ -1,8 +1,9 @@ -use super::region_constraints::RegionSnapshot; -use super::InferCtxt; use rustc_data_structures::undo_log::UndoLogs; use rustc_middle::ty; +use super::region_constraints::RegionSnapshot; +use super::InferCtxt; + mod fudge; pub(crate) mod undo_log; diff --git a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs index 829b0a73a0df5..50a0d3bf21407 100644 --- a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs +++ b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs @@ -1,15 +1,12 @@ use std::marker::PhantomData; -use rustc_data_structures::snapshot_vec as sv; use rustc_data_structures::undo_log::{Rollback, UndoLogs}; -use rustc_data_structures::unify as ut; +use rustc_data_structures::{snapshot_vec as sv, unify as ut}; use rustc_middle::infer::unify_key::{ConstVidKey, EffectVidKey, RegionVidKey}; use rustc_middle::ty::{self, OpaqueHiddenType, OpaqueTypeKey}; -use crate::{ - infer::{region_constraints, type_variable, InferCtxtInner}, - traits, -}; +use crate::infer::{region_constraints, type_variable, InferCtxtInner}; +use crate::traits; pub struct Snapshot<'tcx> { pub(crate) undo_len: usize, diff --git a/compiler/rustc_infer/src/infer/type_variable.rs b/compiler/rustc_infer/src/infer/type_variable.rs index b56b39e61f0c8..f022b8ab637eb 100644 --- a/compiler/rustc_infer/src/infer/type_variable.rs +++ b/compiler/rustc_infer/src/infer/type_variable.rs @@ -1,4 +1,9 @@ +use std::cmp; +use std::marker::PhantomData; +use std::ops::Range; + use rustc_data_structures::undo_log::Rollback; +use rustc_data_structures::{snapshot_vec as sv, unify as ut}; use rustc_hir::def_id::DefId; use rustc_index::IndexVec; use rustc_middle::bug; @@ -7,12 +12,6 @@ use rustc_span::Span; use crate::infer::InferCtxtUndoLogs; -use rustc_data_structures::snapshot_vec as sv; -use rustc_data_structures::unify as ut; -use std::cmp; -use std::marker::PhantomData; -use std::ops::Range; - impl<'tcx> Rollback>>> for TypeVariableStorage<'tcx> { fn reverse(&mut self, undo: sv::UndoLog>>) { self.eq_relations.reverse(undo) diff --git a/compiler/rustc_infer/src/traits/engine.rs b/compiler/rustc_infer/src/traits/engine.rs index 026b2c1b905e3..fd38040406d47 100644 --- a/compiler/rustc_infer/src/traits/engine.rs +++ b/compiler/rustc_infer/src/traits/engine.rs @@ -1,11 +1,11 @@ use std::fmt::Debug; -use crate::infer::InferCtxt; -use crate::traits::Obligation; use rustc_hir::def_id::DefId; use rustc_middle::ty::{self, Ty, Upcast}; use super::{ObligationCause, PredicateObligation}; +use crate::infer::InferCtxt; +use crate::traits::Obligation; /// A trait error with most of its information removed. This is the error /// returned by an `ObligationCtxt` by default, and suitable if you just diff --git a/compiler/rustc_infer/src/traits/mod.rs b/compiler/rustc_infer/src/traits/mod.rs index 7bc3af374fc6a..4f34c1395451b 100644 --- a/compiler/rustc_infer/src/traits/mod.rs +++ b/compiler/rustc_infer/src/traits/mod.rs @@ -14,21 +14,19 @@ use hir::def_id::LocalDefId; use rustc_hir as hir; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::solve::Certainty; +pub use rustc_middle::traits::*; use rustc_middle::ty::{self, Ty, TyCtxt, Upcast}; use rustc_span::Span; -pub use self::ImplSource::*; -pub use self::SelectionError::*; -use crate::infer::InferCtxt; - pub use self::engine::{FromSolverError, ScrubbedTraitError, TraitEngine}; -pub use self::project::MismatchedProjectionTypes; pub(crate) use self::project::UndoLog; pub use self::project::{ - Normalized, NormalizedTerm, ProjectionCache, ProjectionCacheEntry, ProjectionCacheKey, - ProjectionCacheStorage, Reveal, + MismatchedProjectionTypes, Normalized, NormalizedTerm, ProjectionCache, ProjectionCacheEntry, + ProjectionCacheKey, ProjectionCacheStorage, Reveal, }; -pub use rustc_middle::traits::*; +pub use self::ImplSource::*; +pub use self::SelectionError::*; +use crate::infer::InferCtxt; /// An `Obligation` represents some trait reference (e.g., `i32: Eq`) for /// which the "impl_source" must be found. The process of finding an "impl_source" is diff --git a/compiler/rustc_infer/src/traits/project.rs b/compiler/rustc_infer/src/traits/project.rs index b696264aab03e..9ed557ec40bc3 100644 --- a/compiler/rustc_infer/src/traits/project.rs +++ b/compiler/rustc_infer/src/traits/project.rs @@ -1,16 +1,12 @@ //! Code for projecting associated types out of trait references. -use super::PredicateObligation; - -use crate::infer::snapshot::undo_log::InferCtxtUndoLogs; - -use rustc_data_structures::{ - snapshot_map::{self, SnapshotMapRef, SnapshotMapStorage}, - undo_log::Rollback, -}; +use rustc_data_structures::snapshot_map::{self, SnapshotMapRef, SnapshotMapStorage}; +use rustc_data_structures::undo_log::Rollback; +pub use rustc_middle::traits::{EvaluationResult, Reveal}; use rustc_middle::ty; -pub use rustc_middle::traits::{EvaluationResult, Reveal}; +use super::PredicateObligation; +use crate::infer::snapshot::undo_log::InferCtxtUndoLogs; pub(crate) type UndoLog<'tcx> = snapshot_map::UndoLog, ProjectionCacheEntry<'tcx>>; diff --git a/compiler/rustc_infer/src/traits/structural_impls.rs b/compiler/rustc_infer/src/traits/structural_impls.rs index b26734a296fd3..31f585c0c9edd 100644 --- a/compiler/rustc_infer/src/traits/structural_impls.rs +++ b/compiler/rustc_infer/src/traits/structural_impls.rs @@ -1,11 +1,12 @@ -use crate::traits; -use crate::traits::project::Normalized; +use std::fmt; + use rustc_ast_ir::try_visit; use rustc_middle::ty::fold::{FallibleTypeFolder, TypeFoldable}; use rustc_middle::ty::visit::{TypeVisitable, TypeVisitor}; use rustc_middle::ty::{self, TyCtxt}; -use std::fmt; +use crate::traits; +use crate::traits::project::Normalized; // Structural impls for the structs in `traits`. diff --git a/compiler/rustc_infer/src/traits/util.rs b/compiler/rustc_infer/src/traits/util.rs index f54d041859581..335c65da054c3 100644 --- a/compiler/rustc_infer/src/traits/util.rs +++ b/compiler/rustc_infer/src/traits/util.rs @@ -1,11 +1,11 @@ -use crate::traits::{self, Obligation, ObligationCauseCode, PredicateObligation}; use rustc_data_structures::fx::FxHashSet; -use rustc_middle::ty::ToPolyTraitRef; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{self, ToPolyTraitRef, TyCtxt}; use rustc_span::symbol::Ident; use rustc_span::Span; pub use rustc_type_ir::elaborate::*; +use crate::traits::{self, Obligation, ObligationCauseCode, PredicateObligation}; + pub fn anonymize_predicate<'tcx>( tcx: TyCtxt<'tcx>, pred: ty::Predicate<'tcx>, diff --git a/compiler/rustc_interface/src/callbacks.rs b/compiler/rustc_interface/src/callbacks.rs index a27f73789cdef..786e2bb511ffd 100644 --- a/compiler/rustc_interface/src/callbacks.rs +++ b/compiler/rustc_interface/src/callbacks.rs @@ -9,12 +9,13 @@ //! The functions in this file should fall back to the default set in their //! origin crate when the `TyCtxt` is not present in TLS. +use std::fmt; + use rustc_errors::{DiagInner, TRACK_DIAGNOSTIC}; use rustc_middle::dep_graph::{DepNodeExt, TaskDepsRef}; use rustc_middle::ty::tls; use rustc_query_system::dep_graph::dep_node::default_dep_kind_debug; use rustc_query_system::dep_graph::{DepContext, DepKind, DepNode}; -use std::fmt; fn track_span_parent(def_id: rustc_span::def_id::LocalDefId) { tls::with_opt(|tcx| { diff --git a/compiler/rustc_interface/src/errors.rs b/compiler/rustc_interface/src/errors.rs index 29294003b8f29..939980a932fdb 100644 --- a/compiler/rustc_interface/src/errors.rs +++ b/compiler/rustc_interface/src/errors.rs @@ -1,9 +1,9 @@ -use rustc_macros::Diagnostic; -use rustc_span::{Span, Symbol}; - use std::io; use std::path::Path; +use rustc_macros::Diagnostic; +use rustc_span::{Span, Symbol}; + #[derive(Diagnostic)] #[diag(interface_ferris_identifier)] pub struct FerrisIdentifier { diff --git a/compiler/rustc_interface/src/interface.rs b/compiler/rustc_interface/src/interface.rs index dba20e4a3355c..04e2b7d45dc93 100644 --- a/compiler/rustc_interface/src/interface.rs +++ b/compiler/rustc_interface/src/interface.rs @@ -1,13 +1,13 @@ -use crate::util; +use std::path::PathBuf; +use std::result; +use std::sync::Arc; -use rustc_ast::token; -use rustc_ast::{LitKind, MetaItemKind}; +use rustc_ast::{token, LitKind, MetaItemKind}; use rustc_codegen_ssa::traits::CodegenBackend; -use rustc_data_structures::defer; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_data_structures::jobserver; use rustc_data_structures::stable_hasher::StableHasher; use rustc_data_structures::sync::Lrc; +use rustc_data_structures::{defer, jobserver}; use rustc_errors::registry::Registry; use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed}; use rustc_lint::LintStore; @@ -15,6 +15,7 @@ use rustc_middle::ty; use rustc_middle::ty::CurrentGcx; use rustc_middle::util::Providers; use rustc_parse::new_parser_from_source_str; +use rustc_parse::parser::attr::AllowLeadingUnsafe; use rustc_query_impl::QueryCtxt; use rustc_query_system::query::print_query_stack; use rustc_session::config::{self, Cfg, CheckCfg, ExpectedValues, Input, OutFileName}; @@ -24,11 +25,10 @@ use rustc_session::{lint, CompilerIO, EarlyDiagCtxt, Session}; use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMapInputs}; use rustc_span::symbol::sym; use rustc_span::FileName; -use std::path::PathBuf; -use std::result; -use std::sync::Arc; use tracing::trace; +use crate::util; + pub type Result = result::Result; /// Represents a compiler session. Note that every `Compiler` contains a @@ -68,7 +68,7 @@ pub(crate) fn parse_cfg(dcx: DiagCtxtHandle<'_>, cfgs: Vec) -> Cfg { } match new_parser_from_source_str(&psess, filename, s.to_string()) { - Ok(mut parser) => match parser.parse_meta_item() { + Ok(mut parser) => match parser.parse_meta_item(AllowLeadingUnsafe::No) { Ok(meta_item) if parser.token == token::Eof => { if meta_item.path.segments.len() != 1 { error!("argument key must be an identifier"); @@ -174,7 +174,7 @@ pub(crate) fn parse_check_cfg(dcx: DiagCtxtHandle<'_>, specs: Vec) -> Ch } }; - let meta_item = match parser.parse_meta_item() { + let meta_item = match parser.parse_meta_item(AllowLeadingUnsafe::Yes) { Ok(meta_item) if parser.token == token::Eof => meta_item, Ok(..) => expected_error(), Err(err) => { diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 2951f50b1f598..8c99b1f444766 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -1,7 +1,9 @@ -use crate::errors; -use crate::interface::{Compiler, Result}; -use crate::proc_macro_decls; -use crate::util; +use std::any::Any; +use std::ffi::OsString; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, LazyLock}; +use std::{env, fs, iter}; use rustc_ast::{self as ast, visit}; use rustc_codegen_ssa::traits::CodegenBackend; @@ -27,23 +29,18 @@ use rustc_resolve::Resolver; use rustc_session::code_stats::VTableSizeInfo; use rustc_session::config::{CrateType, Input, OutFileName, OutputFilenames, OutputType}; use rustc_session::cstore::Untracked; -use rustc_session::output::filename_for_input; -use rustc_session::output::{collect_crate_types, find_crate_name}; +use rustc_session::output::{collect_crate_types, filename_for_input, find_crate_name}; use rustc_session::search_paths::PathKind; use rustc_session::{Limit, Session}; use rustc_span::symbol::{sym, Symbol}; use rustc_span::FileName; use rustc_target::spec::PanicStrategy; use rustc_trait_selection::traits; - -use std::any::Any; -use std::ffi::OsString; -use std::io::{self, BufWriter, Write}; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, LazyLock}; -use std::{env, fs, iter}; use tracing::{info, instrument}; +use crate::interface::{Compiler, Result}; +use crate::{errors, proc_macro_decls, util}; + pub(crate) fn parse<'a>(sess: &'a Session) -> Result { let krate = sess .time("parse_crate", || { @@ -547,7 +544,13 @@ fn resolver_for_lowering_raw<'tcx>( let arenas = Resolver::arenas(); let _ = tcx.registered_tools(()); // Uses `crate_for_resolver`. let (krate, pre_configured_attrs) = tcx.crate_for_resolver(()).steal(); - let mut resolver = Resolver::new(tcx, &pre_configured_attrs, krate.spans.inner_span, &arenas); + let mut resolver = Resolver::new( + tcx, + &pre_configured_attrs, + krate.spans.inner_span, + krate.spans.inject_use_span, + &arenas, + ); let krate = configure_and_expand(krate, &pre_configured_attrs, &mut resolver); // Make sure we don't mutate the cstore from here on. diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index 821e8ee7ba589..c5d56c15c6e2e 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -1,6 +1,6 @@ -use crate::errors::FailedWritingFile; -use crate::interface::{Compiler, Result}; -use crate::{errors, passes}; +use std::any::Any; +use std::cell::{RefCell, RefMut}; +use std::sync::Arc; use rustc_ast as ast; use rustc_codegen_ssa::traits::CodegenBackend; @@ -15,9 +15,10 @@ use rustc_middle::ty::{GlobalCtxt, TyCtxt}; use rustc_serialize::opaque::FileEncodeResult; use rustc_session::config::{self, OutputFilenames, OutputType}; use rustc_session::Session; -use std::any::Any; -use std::cell::{RefCell, RefMut}; -use std::sync::Arc; + +use crate::errors::FailedWritingFile; +use crate::interface::{Compiler, Result}; +use crate::{errors, passes}; /// Represent the result of a query. /// diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index 7d7a6a08bee42..ce3b2f77f210a 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -1,23 +1,20 @@ #![allow(rustc::bad_opt_access)] -use crate::interface::{initialize_checked_jobserver, parse_cfg}; +use std::collections::{BTreeMap, BTreeSet}; +use std::num::NonZero; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + use rustc_data_structures::profiling::TimePassesFormat; -use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig}; -use rustc_session::config::{build_configuration, build_session_options, rustc_optgroups}; -use rustc_session::config::{ - BranchProtection, CFGuard, Cfg, CollapseMacroDebuginfo, CoverageLevel, CoverageOptions, - DebugInfo, DumpMonoStatsFormat, ErrorOutputType, -}; -use rustc_session::config::{ - ExternEntry, ExternLocation, Externs, FunctionReturn, InliningThreshold, Input, - InstrumentCoverage, InstrumentXRay, LinkSelfContained, LinkerPluginLto, -}; -use rustc_session::config::{ - LocationDetail, LtoCli, NextSolverConfig, OomStrategy, Options, OutFileName, OutputType, - OutputTypes, PAuthKey, PacRet, Passes, PatchableFunctionEntry, -}; +use rustc_errors::emitter::HumanReadableErrorType; +use rustc_errors::{registry, ColorConfig}; use rustc_session::config::{ - Polonius, ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, SymbolManglingVersion, - WasiExecModel, + build_configuration, build_session_options, rustc_optgroups, BranchProtection, CFGuard, Cfg, + CollapseMacroDebuginfo, CoverageLevel, CoverageOptions, DebugInfo, DumpMonoStatsFormat, + ErrorOutputType, ExternEntry, ExternLocation, Externs, FunctionReturn, InliningThreshold, + Input, InstrumentCoverage, InstrumentXRay, LinkSelfContained, LinkerPluginLto, LocationDetail, + LtoCli, NextSolverConfig, OomStrategy, Options, OutFileName, OutputType, OutputTypes, PAuthKey, + PacRet, Passes, PatchableFunctionEntry, Polonius, ProcMacroExecutionStrategy, Strip, + SwitchWithOptPath, SymbolManglingVersion, WasiExecModel, }; use rustc_session::lint::Level; use rustc_session::search_paths::SearchPath; @@ -31,10 +28,8 @@ use rustc_target::spec::{ CodeModel, FramePointer, LinkerFlavorCli, MergeFunctions, OnBrokenPipe, PanicStrategy, RelocModel, RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, TlsModel, WasmCAbi, }; -use std::collections::{BTreeMap, BTreeSet}; -use std::num::NonZero; -use std::path::{Path, PathBuf}; -use std::sync::Arc; + +use crate::interface::{initialize_checked_jobserver, parse_cfg}; fn sess_and_cfg(args: &[&'static str], f: F) where diff --git a/compiler/rustc_interface/src/util.rs b/compiler/rustc_interface/src/util.rs index 8dac524bb5bfd..6f53b1c90313b 100644 --- a/compiler/rustc_interface/src/util.rs +++ b/compiler/rustc_interface/src/util.rs @@ -1,4 +1,9 @@ -use crate::errors; +use std::env::consts::{DLL_PREFIX, DLL_SUFFIX}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::OnceLock; +use std::{env, iter, thread}; + use rustc_ast as ast; use rustc_codegen_ssa::traits::CodegenBackend; #[cfg(parallel_compiler)] @@ -16,14 +21,10 @@ use rustc_span::edition::Edition; use rustc_span::source_map::SourceMapInputs; use rustc_span::symbol::sym; use rustc_target::spec::Target; -use std::env::consts::{DLL_PREFIX, DLL_SUFFIX}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::OnceLock; -use std::thread; -use std::{env, iter}; use tracing::info; +use crate::errors; + /// Function pointer type that constructs a new CodegenBackend. pub type MakeBackendFn = fn() -> Box; @@ -136,11 +137,13 @@ pub(crate) fn run_in_thread_pool_with_globals R + Send, sm_inputs: SourceMapInputs, f: F, ) -> R { - use rustc_data_structures::{defer, jobserver, sync::FromDyn}; + use std::process; + + use rustc_data_structures::sync::FromDyn; + use rustc_data_structures::{defer, jobserver}; use rustc_middle::ty::tls; use rustc_query_impl::QueryCtxt; use rustc_query_system::query::{break_query_cycles, QueryContext}; - use std::process; let thread_stack_size = init_stack_size(thread_builder_diag); diff --git a/compiler/rustc_lexer/src/lib.rs b/compiler/rustc_lexer/src/lib.rs index d4efb41eed08f..2116ba6c079ac 100644 --- a/compiler/rustc_lexer/src/lib.rs +++ b/compiler/rustc_lexer/src/lib.rs @@ -31,12 +31,12 @@ pub mod unescape; #[cfg(test)] mod tests; -pub use crate::cursor::Cursor; +use unicode_properties::UnicodeEmoji; use self::LiteralKind::*; use self::TokenKind::*; +pub use crate::cursor::Cursor; use crate::cursor::EOF_CHAR; -use unicode_properties::UnicodeEmoji; /// Parsed token. /// It doesn't contain information about data that has been parsed, diff --git a/compiler/rustc_lexer/src/tests.rs b/compiler/rustc_lexer/src/tests.rs index e4c1787f2ccef..493ec2b0f6045 100644 --- a/compiler/rustc_lexer/src/tests.rs +++ b/compiler/rustc_lexer/src/tests.rs @@ -1,7 +1,7 @@ -use super::*; - use expect_test::{expect, Expect}; +use super::*; + fn check_raw_str(s: &str, expected: Result) { let s = &format!("r{}", s); let mut cursor = Cursor::new(s); diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index 7d7b97e2eb1a3..7e4feb0a82716 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -5,6 +5,11 @@ lint_ambiguous_glob_reexport = ambiguous glob re-exports .label_first_reexport = the name `{$name}` in the {$namespace} namespace is first re-exported here .label_duplicate_reexport = but the name `{$name}` in the {$namespace} namespace is also re-exported here +lint_ambiguous_negative_literals = `-` has lower precedence than method calls, which might be unexpected + .example = e.g. `-4.abs()` equals `-4`; while `(-4).abs()` equals `4` + .negative_literal = add parentheses around the `-` and the literal to call the method on a negative literal + .current_behavior = add parentheses around the literal and the method call to keep the current behavior + lint_ambiguous_wide_pointer_comparisons = ambiguous wide pointer comparison, the comparison includes metadata which may not be expected .addr_metadata_suggestion = use explicit `std::ptr::eq` method to compare metadata and addresses .addr_suggestion = use `std::ptr::addr_eq` or untyped pointers to only compare their addresses @@ -139,13 +144,18 @@ lint_builtin_special_module_name_used_main = found module declaration for main.r lint_builtin_trivial_bounds = {$predicate_kind_name} bound {$predicate} does not depend on any type or lifetime parameters -lint_builtin_type_alias_bounds_help = use fully disambiguated paths (i.e., `::Assoc`) to refer to associated types in type aliases - -lint_builtin_type_alias_generic_bounds = bounds on generic parameters are not enforced in type aliases - .suggestion = the bound will not be checked when the type alias is used, and should be removed - -lint_builtin_type_alias_where_clause = where clauses are not enforced in type aliases - .suggestion = the clause will not be checked when the type alias is used, and should be removed +lint_builtin_type_alias_bounds_enable_feat_help = add `#![feature(lazy_type_alias)]` to the crate attributes to enable the desired semantics +lint_builtin_type_alias_bounds_label = will not be checked at usage sites of the type alias +lint_builtin_type_alias_bounds_limitation_note = this is a known limitation of the type checker that may be lifted in a future edition. + see issue #112792 for more information +lint_builtin_type_alias_bounds_param_bounds = bounds on generic parameters in type aliases are not enforced + .suggestion = remove {$count -> + [one] this bound + *[other] these bounds + } +lint_builtin_type_alias_bounds_qualify_assoc_tys_sugg = fully qualify this associated type +lint_builtin_type_alias_bounds_where_clause = where clauses on type aliases are not enforced + .suggestion = remove this where clause lint_builtin_unpermitted_type_init_label = this code causes undefined behavior when executed lint_builtin_unpermitted_type_init_label_suggestion = help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done @@ -690,10 +700,10 @@ lint_reason_must_be_string_literal = reason must be a string literal lint_reason_must_come_last = reason in lint attribute must come last lint_redundant_import = the item `{$ident}` is imported redundantly - .label_imported_here = the item `{ident}` is already imported here - .label_defined_here = the item `{ident}` is already defined here - .label_imported_prelude = the item `{ident}` is already imported by the extern prelude - .label_defined_prelude = the item `{ident}` is already defined by the extern prelude + .label_imported_here = the item `{$ident}` is already imported here + .label_defined_here = the item `{$ident}` is already defined here + .label_imported_prelude = the item `{$ident}` is already imported by the extern prelude + .label_defined_prelude = the item `{$ident}` is already defined by the extern prelude lint_redundant_import_visibility = glob import doesn't reexport anything with visibility `{$import_vis}` because no imported item is public enough .note = the most public imported item is `{$max_vis}` diff --git a/compiler/rustc_lint/src/async_fn_in_trait.rs b/compiler/rustc_lint/src/async_fn_in_trait.rs index 6daee95dda6a2..d904020730019 100644 --- a/compiler/rustc_lint/src/async_fn_in_trait.rs +++ b/compiler/rustc_lint/src/async_fn_in_trait.rs @@ -1,10 +1,10 @@ -use crate::lints::AsyncFnInTraitDiag; -use crate::LateContext; -use crate::LateLintPass; use rustc_hir as hir; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_trait_selection::error_reporting::traits::suggestions::suggest_desugaring_async_fn_to_impl_future_in_trait; +use crate::lints::AsyncFnInTraitDiag; +use crate::{LateContext, LateLintPass}; + declare_lint! { /// The `async_fn_in_trait` lint detects use of `async fn` in the /// definition of a publicly-reachable trait. diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 9ebada0fff377..d8674817cb5eb 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -20,26 +20,8 @@ //! If you define a new `LateLintPass`, you will also need to add it to the //! `late_lint_methods!` invocation in `lib.rs`. -use crate::fluent_generated as fluent; -use crate::{ - errors::BuiltinEllipsisInclusiveRangePatterns, - lints::{ - BuiltinAnonymousParams, BuiltinConstNoMangle, BuiltinDeprecatedAttrLink, - BuiltinDeprecatedAttrLinkSuggestion, BuiltinDeprecatedAttrUsed, BuiltinDerefNullptr, - BuiltinEllipsisInclusiveRangePatternsLint, BuiltinExplicitOutlives, - BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote, BuiltinIncompleteFeatures, - BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures, BuiltinKeywordIdents, - BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc, - BuiltinMutablesTransmutes, BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns, - BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasGenericBounds, - BuiltinTypeAliasGenericBoundsSuggestion, BuiltinTypeAliasWhereClause, - BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, - BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub, BuiltinUnsafe, - BuiltinUnstableFeatures, BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub, - BuiltinWhileTrue, InvalidAsmLabel, SuggestChangingAssocTypes, - }, - EarlyContext, EarlyLintPass, LateContext, LateLintPass, Level, LintContext, -}; +use std::fmt::Write; + use ast::token::TokenKind; use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_ast::visit::{FnCtxt, FnKind}; @@ -56,9 +38,9 @@ use rustc_middle::bug; use rustc_middle::lint::in_external_macro; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::TypeVisitableExt; -use rustc_middle::ty::Upcast; -use rustc_middle::ty::{self, Ty, TyCtxt, VariantDef}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Upcast, VariantDef}; +// hardwired lints from rustc_lint_defs +pub use rustc_session::lint::builtin::*; use rustc_session::lint::FutureIncompatibilityReason; use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass}; use rustc_span::edition::Edition; @@ -68,15 +50,29 @@ use rustc_span::{BytePos, InnerSpan, Span}; use rustc_target::abi::Abi; use rustc_target::asm::InlineAsmArch; use rustc_trait_selection::infer::{InferCtxtExt, TyCtxtInferExt}; +use rustc_trait_selection::traits::misc::type_allowed_to_implement_copy; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; -use rustc_trait_selection::traits::{self, misc::type_allowed_to_implement_copy}; - +use rustc_trait_selection::traits::{self}; + +use crate::errors::BuiltinEllipsisInclusiveRangePatterns; +use crate::lints::{ + BuiltinAnonymousParams, BuiltinConstNoMangle, BuiltinDeprecatedAttrLink, + BuiltinDeprecatedAttrLinkSuggestion, BuiltinDeprecatedAttrUsed, BuiltinDerefNullptr, + BuiltinEllipsisInclusiveRangePatternsLint, BuiltinExplicitOutlives, + BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote, BuiltinIncompleteFeatures, + BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures, BuiltinKeywordIdents, + BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc, BuiltinMutablesTransmutes, + BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns, BuiltinSpecialModuleNameUsed, + BuiltinTrivialBounds, BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller, + BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub, + BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub, + BuiltinWhileTrue, InvalidAsmLabel, +}; use crate::nonstandard_style::{method_context, MethodLateContext}; - -use std::fmt::Write; - -// hardwired lints from rustc_lint_defs -pub use rustc_session::lint::builtin::*; +use crate::{ + fluent_generated as fluent, EarlyContext, EarlyLintPass, LateContext, LateLintPass, Level, + LintContext, +}; declare_lint! { /// The `while_true` lint detects `while true { }`. @@ -1391,64 +1387,80 @@ declare_lint! { /// /// ### Explanation /// - /// The trait bounds in a type alias are currently ignored, and should not - /// be included to avoid confusion. This was previously allowed - /// unintentionally; this may become a hard error in the future. + /// Trait and lifetime bounds on generic parameters and in where clauses of + /// type aliases are not checked at usage sites of the type alias. Moreover, + /// they are not thoroughly checked for correctness at their definition site + /// either similar to the aliased type. + /// + /// This is a known limitation of the type checker that may be lifted in a + /// future edition. Permitting such bounds in light of this was unintentional. + /// + /// While these bounds may have secondary effects such as enabling the use of + /// "shorthand" associated type paths[^1] and affecting the default trait + /// object lifetime[^2] of trait object types passed to the type alias, this + /// should not have been allowed until the aforementioned restrictions of the + /// type checker have been lifted. + /// + /// Using such bounds is highly discouraged as they are actively misleading. + /// + /// [^1]: I.e., paths of the form `T::Assoc` where `T` is a type parameter + /// bounded by trait `Trait` which defines an associated type called `Assoc` + /// as opposed to a fully qualified path of the form `::Assoc`. + /// [^2]: TYPE_ALIAS_BOUNDS, Warn, "bounds in type aliases are not enforced" } -declare_lint_pass!( - /// Lint for trait and lifetime bounds in type aliases being mostly ignored. - /// They are relevant when using associated types, but otherwise neither checked - /// at definition site nor enforced at use site. - TypeAliasBounds => [TYPE_ALIAS_BOUNDS] -); +declare_lint_pass!(TypeAliasBounds => [TYPE_ALIAS_BOUNDS]); impl TypeAliasBounds { - pub(crate) fn is_type_variable_assoc(qpath: &hir::QPath<'_>) -> bool { - match *qpath { - hir::QPath::TypeRelative(ty, _) => { - // If this is a type variable, we found a `T::Assoc`. - match ty.kind { - hir::TyKind::Path(hir::QPath::Resolved(None, path)) => { - matches!(path.res, Res::Def(DefKind::TyParam, _)) - } - _ => false, - } - } - hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => false, + pub(crate) fn affects_object_lifetime_defaults(pred: &hir::WherePredicate<'_>) -> bool { + // Bounds of the form `T: 'a` with `T` type param affect object lifetime defaults. + if let hir::WherePredicate::BoundPredicate(pred) = pred + && pred.bounds.iter().any(|bound| matches!(bound, hir::GenericBound::Outlives(_))) + && pred.bound_generic_params.is_empty() // indeed, even if absent from the RHS + && pred.bounded_ty.as_generic_param().is_some() + { + return true; } + false } } impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { - let hir::ItemKind::TyAlias(hir_ty, type_alias_generics) = &item.kind else { return }; + let hir::ItemKind::TyAlias(hir_ty, generics) = item.kind else { return }; - // Bounds of lazy type aliases and TAITs are respected. - if cx.tcx.type_alias_is_lazy(item.owner_id) { + // There must not be a where clause. + if generics.predicates.is_empty() { return; } - let ty = cx.tcx.type_of(item.owner_id).skip_binder(); - if ty.has_inherent_projections() { - // Bounds of type aliases that contain opaque types or inherent projections are - // respected. E.g: `type X = impl Trait;`, `type X = (impl Trait, Y);`, `type X = - // Type::Inherent;`. + // Bounds of lazy type aliases and TAITs are respected. + if cx.tcx.type_alias_is_lazy(item.owner_id) { return; } - // There must not be a where clause - if type_alias_generics.predicates.is_empty() { + // FIXME(generic_const_exprs): Revisit this before stabilization. + // See also `tests/ui/const-generics/generic_const_exprs/type-alias-bounds.rs`. + let ty = cx.tcx.type_of(item.owner_id).instantiate_identity(); + if ty.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION) + && cx.tcx.features().generic_const_exprs + { return; } + // NOTE(inherent_associated_types): While we currently do take some bounds in type + // aliases into consideration during IAT *selection*, we don't perform full use+def + // site wfchecking for such type aliases. Therefore TAB should still trigger. + // See also `tests/ui/associated-inherent-types/type-alias-bounds.rs`. + let mut where_spans = Vec::new(); let mut inline_spans = Vec::new(); let mut inline_sugg = Vec::new(); - for p in type_alias_generics.predicates { + + for p in generics.predicates { let span = p.span(); if p.in_where_clause() { where_spans.push(span); @@ -1460,37 +1472,57 @@ impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { } } - let mut suggested_changing_assoc_types = false; - if !where_spans.is_empty() { - let sub = (!suggested_changing_assoc_types).then(|| { - suggested_changing_assoc_types = true; - SuggestChangingAssocTypes { ty: hir_ty } - }); + let mut ty = Some(hir_ty); + let enable_feat_help = cx.tcx.sess.is_nightly_build(); + + if let [.., label_sp] = *where_spans { cx.emit_span_lint( TYPE_ALIAS_BOUNDS, where_spans, - BuiltinTypeAliasWhereClause { - suggestion: type_alias_generics.where_clause_span, - sub, + BuiltinTypeAliasBounds { + in_where_clause: true, + label: label_sp, + enable_feat_help, + suggestions: vec![(generics.where_clause_span, String::new())], + preds: generics.predicates, + ty: ty.take(), }, ); } - - if !inline_spans.is_empty() { - let suggestion = BuiltinTypeAliasGenericBoundsSuggestion { suggestions: inline_sugg }; - let sub = (!suggested_changing_assoc_types).then(|| { - suggested_changing_assoc_types = true; - SuggestChangingAssocTypes { ty: hir_ty } - }); + if let [.., label_sp] = *inline_spans { cx.emit_span_lint( TYPE_ALIAS_BOUNDS, inline_spans, - BuiltinTypeAliasGenericBounds { suggestion, sub }, + BuiltinTypeAliasBounds { + in_where_clause: false, + label: label_sp, + enable_feat_help, + suggestions: inline_sugg, + preds: generics.predicates, + ty, + }, ); } } } +pub(crate) struct ShorthandAssocTyCollector { + pub(crate) qselves: Vec, +} + +impl hir::intravisit::Visitor<'_> for ShorthandAssocTyCollector { + fn visit_qpath(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, _: Span) { + // Look for "type-parameter shorthand-associated-types". I.e., paths of the + // form `T::Assoc` with `T` type param. These are reliant on trait bounds. + if let hir::QPath::TypeRelative(qself, _) = qpath + && qself.as_generic_param().is_some() + { + self.qselves.push(qself.span); + } + hir::intravisit::walk_qpath(self, qpath, id) + } +} + declare_lint! { /// The `trivial_bounds` lint detects trait bounds that don't depend on /// any type parameters. @@ -1637,7 +1669,8 @@ impl EarlyLintPass for EllipsisInclusiveRangePatterns { return; } - use self::ast::{PatKind, RangeSyntax::DotDotDot}; + use self::ast::PatKind; + use self::ast::RangeSyntax::DotDotDot; /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span /// corresponding to the ellipsis. diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 9f0f116cbd030..11ad1aa0e8d1a 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -14,10 +14,9 @@ //! upon. As the ast is traversed, this keeps track of the current lint level //! for all lint attributes. -use self::TargetLint::*; +use std::cell::Cell; +use std::{iter, slice}; -use crate::levels::LintLevelsBuilder; -use crate::passes::{EarlyLintPassObject, LateLintPassObject}; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::sync; use rustc_data_structures::unord::UnordMap; @@ -30,20 +29,22 @@ use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; use rustc_middle::bug; use rustc_middle::middle::privacy::EffectiveVisibilities; use rustc_middle::ty::layout::{LayoutError, LayoutOfHelpers, TyAndLayout}; -use rustc_middle::ty::print::{with_no_trimmed_paths, PrintError, PrintTraitRefExt as _}; -use rustc_middle::ty::{self, print::Printer, GenericArg, RegisteredTools, Ty, TyCtxt}; -use rustc_session::lint::{BuiltinLintDiag, LintExpectationId}; -use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId}; +use rustc_middle::ty::print::{with_no_trimmed_paths, PrintError, PrintTraitRefExt as _, Printer}; +use rustc_middle::ty::{self, GenericArg, RegisteredTools, Ty, TyCtxt}; +use rustc_session::lint::{ + BuiltinLintDiag, FutureIncompatibleInfo, Level, Lint, LintBuffer, LintExpectationId, LintId, +}; use rustc_session::{LintStoreMarker, Session}; use rustc_span::edit_distance::find_best_match_for_names; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; use rustc_target::abi; -use std::cell::Cell; -use std::iter; -use std::slice; use tracing::debug; +use self::TargetLint::*; +use crate::levels::LintLevelsBuilder; +use crate::passes::{EarlyLintPassObject, LateLintPassObject}; + mod diagnostics; type EarlyLintPassFactory = dyn Fn() -> EarlyLintPassObject + sync::DynSend + sync::DynSync; diff --git a/compiler/rustc_lint/src/context/diagnostics.rs b/compiler/rustc_lint/src/context/diagnostics.rs index 05e075205c4b7..a96af0764772b 100644 --- a/compiler/rustc_lint/src/context/diagnostics.rs +++ b/compiler/rustc_lint/src/context/diagnostics.rs @@ -4,8 +4,9 @@ use std::borrow::Cow; use rustc_ast::util::unicode::TEXT_FLOW_CONTROL_CHARS; -use rustc_errors::elided_lifetime_in_path_suggestion; -use rustc_errors::{Applicability, Diag, DiagArgValue, LintDiagnostic}; +use rustc_errors::{ + elided_lifetime_in_path_suggestion, Applicability, Diag, DiagArgValue, LintDiagnostic, +}; use rustc_middle::middle::stability; use rustc_session::lint::BuiltinLintDiag; use rustc_session::Session; diff --git a/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs b/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs index da36f68fca970..fb3f40aa27108 100644 --- a/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs +++ b/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs @@ -1,5 +1,6 @@ use rustc_middle::bug; -use rustc_session::{config::ExpectedValues, Session}; +use rustc_session::config::ExpectedValues; +use rustc_session::Session; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::{sym, Span, Symbol}; diff --git a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs index 911975f617912..f174470b7a731 100644 --- a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs +++ b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs @@ -1,8 +1,3 @@ -use crate::{ - lints::{SupertraitAsDerefTarget, SupertraitAsDerefTargetLabel}, - LateContext, LateLintPass, LintContext, -}; - use rustc_hir::{self as hir, LangItem}; use rustc_middle::ty; use rustc_session::lint::FutureIncompatibilityReason; @@ -10,6 +5,9 @@ use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::sym; use rustc_trait_selection::traits::supertraits; +use crate::lints::{SupertraitAsDerefTarget, SupertraitAsDerefTargetLabel}; +use crate::{LateContext, LateLintPass, LintContext}; + declare_lint! { /// The `deref_into_dyn_supertrait` lint is output whenever there is a use of the /// `Deref` implementation with a `dyn SuperTrait` type as `Output`. diff --git a/compiler/rustc_lint/src/drop_forget_useless.rs b/compiler/rustc_lint/src/drop_forget_useless.rs index eea0898d83fa6..2060858cc8af0 100644 --- a/compiler/rustc_lint/src/drop_forget_useless.rs +++ b/compiler/rustc_lint/src/drop_forget_useless.rs @@ -3,13 +3,11 @@ use rustc_middle::ty; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::sym; -use crate::{ - lints::{ - DropCopyDiag, DropRefDiag, ForgetCopyDiag, ForgetRefDiag, UndroppedManuallyDropsDiag, - UndroppedManuallyDropsSuggestion, UseLetUnderscoreIgnoreSuggestion, - }, - LateContext, LateLintPass, LintContext, +use crate::lints::{ + DropCopyDiag, DropRefDiag, ForgetCopyDiag, ForgetRefDiag, UndroppedManuallyDropsDiag, + UndroppedManuallyDropsSuggestion, UseLetUnderscoreIgnoreSuggestion, }; +use crate::{LateContext, LateLintPass, LintContext}; declare_lint! { /// The `dropping_references` lint checks for calls to `std::mem::drop` with a reference diff --git a/compiler/rustc_lint/src/early.rs b/compiler/rustc_lint/src/early.rs index 329221612b587..7b04e8c39e601 100644 --- a/compiler/rustc_lint/src/early.rs +++ b/compiler/rustc_lint/src/early.rs @@ -14,8 +14,6 @@ //! upon. As the ast is traversed, this keeps track of the current lint level //! for all lint attributes. -use crate::context::{EarlyContext, LintStore}; -use crate::passes::{EarlyLintPass, EarlyLintPassObject}; use rustc_ast::ptr::P; use rustc_ast::visit::{self as ast_visit, walk_list, Visitor}; use rustc_ast::{self as ast, HasAttrs}; @@ -28,6 +26,9 @@ use rustc_span::symbol::Ident; use rustc_span::Span; use tracing::debug; +use crate::context::{EarlyContext, LintStore}; +use crate::passes::{EarlyLintPass, EarlyLintPassObject}; + macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({ $cx.pass.$f(&$cx.context, $($args),*); }) } diff --git a/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs b/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs index 958da177eda5d..4e3eca496eadb 100644 --- a/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs +++ b/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs @@ -1,12 +1,13 @@ -use crate::{ - context::LintContext, - lints::{EnumIntrinsicsMemDiscriminate, EnumIntrinsicsMemVariant}, - LateContext, LateLintPass, -}; use rustc_hir as hir; -use rustc_middle::ty::{visit::TypeVisitableExt, Ty}; +use rustc_middle::ty::visit::TypeVisitableExt; +use rustc_middle::ty::Ty; use rustc_session::{declare_lint, declare_lint_pass}; -use rustc_span::{symbol::sym, Span}; +use rustc_span::symbol::sym; +use rustc_span::Span; + +use crate::context::LintContext; +use crate::lints::{EnumIntrinsicsMemDiscriminate, EnumIntrinsicsMemVariant}; +use crate::{LateContext, LateLintPass}; declare_lint! { /// The `enum_intrinsics_non_enums` lint detects calls to diff --git a/compiler/rustc_lint/src/errors.rs b/compiler/rustc_lint/src/errors.rs index 46dfaf0b83f95..23e6b73ee373b 100644 --- a/compiler/rustc_lint/src/errors.rs +++ b/compiler/rustc_lint/src/errors.rs @@ -1,9 +1,11 @@ -use crate::fluent_generated as fluent; -use rustc_errors::{codes::*, Diag, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic}; +use rustc_errors::codes::*; +use rustc_errors::{Diag, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic}; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_session::lint::Level; use rustc_span::{Span, Symbol}; +use crate::fluent_generated as fluent; + #[derive(Diagnostic)] #[diag(lint_overruled_attribute, code = E0453)] pub struct OverruledAttribute<'a> { diff --git a/compiler/rustc_lint/src/expect.rs b/compiler/rustc_lint/src/expect.rs index 04c2ebf189f94..35af694213d09 100644 --- a/compiler/rustc_lint/src/expect.rs +++ b/compiler/rustc_lint/src/expect.rs @@ -1,10 +1,11 @@ -use crate::lints::{Expectation, ExpectationNote}; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::lint::builtin::UNFULFILLED_LINT_EXPECTATIONS; use rustc_session::lint::LintExpectationId; use rustc_span::Symbol; +use crate::lints::{Expectation, ExpectationNote}; + pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { check_expectations, ..*providers }; } diff --git a/compiler/rustc_lint/src/for_loops_over_fallibles.rs b/compiler/rustc_lint/src/for_loops_over_fallibles.rs index aa00fb4573d80..6cb5263ac5432 100644 --- a/compiler/rustc_lint/src/for_loops_over_fallibles.rs +++ b/compiler/rustc_lint/src/for_loops_over_fallibles.rs @@ -1,19 +1,18 @@ -use crate::{ - lints::{ - ForLoopsOverFalliblesDiag, ForLoopsOverFalliblesLoopSub, ForLoopsOverFalliblesQuestionMark, - ForLoopsOverFalliblesSuggestion, - }, - LateContext, LateLintPass, LintContext, -}; - use hir::{Expr, Pat}; use rustc_hir as hir; -use rustc_infer::{infer::TyCtxtInferExt, traits::ObligationCause}; +use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::traits::ObligationCause; use rustc_middle::ty; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::{sym, Span}; use rustc_trait_selection::traits::ObligationCtxt; +use crate::lints::{ + ForLoopsOverFalliblesDiag, ForLoopsOverFalliblesLoopSub, ForLoopsOverFalliblesQuestionMark, + ForLoopsOverFalliblesSuggestion, +}; +use crate::{LateContext, LateLintPass, LintContext}; + declare_lint! { /// The `for_loops_over_fallibles` lint checks for `for` loops over `Option` or `Result` values. /// diff --git a/compiler/rustc_lint/src/hidden_unicode_codepoints.rs b/compiler/rustc_lint/src/hidden_unicode_codepoints.rs index aa8ca1776dc03..ebd8bd5605d78 100644 --- a/compiler/rustc_lint/src/hidden_unicode_codepoints.rs +++ b/compiler/rustc_lint/src/hidden_unicode_codepoints.rs @@ -1,15 +1,13 @@ -use crate::{ - lints::{ - HiddenUnicodeCodepointsDiag, HiddenUnicodeCodepointsDiagLabels, - HiddenUnicodeCodepointsDiagSub, - }, - EarlyContext, EarlyLintPass, LintContext, -}; use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS}; use rustc_ast as ast; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::{BytePos, Span, Symbol}; +use crate::lints::{ + HiddenUnicodeCodepointsDiag, HiddenUnicodeCodepointsDiagLabels, HiddenUnicodeCodepointsDiagSub, +}; +use crate::{EarlyContext, EarlyLintPass, LintContext}; + declare_lint! { /// The `text_direction_codepoint_in_literal` lint detects Unicode codepoints that change the /// visual representation of text on screen in a way that does not correspond to their on diff --git a/compiler/rustc_lint/src/impl_trait_overcaptures.rs b/compiler/rustc_lint/src/impl_trait_overcaptures.rs index 0860413190c3d..e914169f4c373 100644 --- a/compiler/rustc_lint/src/impl_trait_overcaptures.rs +++ b/compiler/rustc_lint/src/impl_trait_overcaptures.rs @@ -13,8 +13,7 @@ use rustc_middle::ty::{ use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::Span; -use crate::fluent_generated as fluent; -use crate::{LateContext, LateLintPass}; +use crate::{fluent_generated as fluent, LateContext, LateLintPass}; declare_lint! { /// The `impl_trait_overcaptures` lint warns against cases where lifetime diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index e15eb90f82708..044c9413f0b31 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -1,16 +1,13 @@ //! Some lints that are only useful in the compiler or crates that use compiler internals, such as //! Clippy. -use crate::lints::{ - BadOptAccessDiag, DefaultHashTypesDiag, DiagOutOfImpl, LintPassByHand, NonExistentDocKeyword, - NonGlobImportTypeIrInherent, QueryInstability, SpanUseEqCtxtDiag, TyQualified, TykindDiag, - TykindKind, UntranslatableDiag, -}; -use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; use rustc_ast as ast; use rustc_hir::def::Res; -use rustc_hir::{def_id::DefId, Expr, ExprKind, GenericArg, PatKind, Path, PathSegment, QPath}; -use rustc_hir::{BinOp, BinOpKind, HirId, Impl, Item, ItemKind, Node, Pat, Ty, TyKind}; +use rustc_hir::def_id::DefId; +use rustc_hir::{ + BinOp, BinOpKind, Expr, ExprKind, GenericArg, HirId, Impl, Item, ItemKind, Node, Pat, PatKind, + Path, PathSegment, QPath, Ty, TyKind, +}; use rustc_middle::ty::{self, Ty as MiddleTy}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::hygiene::{ExpnKind, MacroKind}; @@ -18,6 +15,13 @@ use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; use tracing::debug; +use crate::lints::{ + BadOptAccessDiag, DefaultHashTypesDiag, DiagOutOfImpl, LintPassByHand, NonExistentDocKeyword, + NonGlobImportTypeIrInherent, QueryInstability, SpanUseEqCtxtDiag, TyQualified, TykindDiag, + TykindKind, UntranslatableDiag, +}; +use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; + declare_tool_lint! { /// The `default_hash_type` lint detects use of [`std::collections::HashMap`] and /// [`std::collections::HashSet`], suggesting the use of `FxHashMap`/`FxHashSet`. diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index aa328fb87b273..638b623510e74 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -14,22 +14,24 @@ //! upon. As the ast is traversed, this keeps track of the current lint level //! for all lint attributes. -use crate::{passes::LateLintPassObject, LateContext, LateLintPass, LintStore}; +use std::any::Any; +use std::cell::Cell; + use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::sync::{join, Lrc}; use rustc_hir as hir; use rustc_hir::def_id::{LocalDefId, LocalModDefId}; -use rustc_hir::intravisit as hir_visit; -use rustc_hir::HirId; +use rustc_hir::{intravisit as hir_visit, HirId}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::{self, TyCtxt}; use rustc_session::lint::LintPass; use rustc_session::Session; use rustc_span::Span; -use std::any::Any; -use std::cell::Cell; use tracing::debug; +use crate::passes::LateLintPassObject; +use crate::{LateContext, LateLintPass, LintStore}; + /// Extract the [`LintStore`] from [`Session`]. /// /// This function exists because [`Session::lint_store`] is type-erased. diff --git a/compiler/rustc_lint/src/let_underscore.rs b/compiler/rustc_lint/src/let_underscore.rs index e6c274ec09a74..92db8a88e42d6 100644 --- a/compiler/rustc_lint/src/let_underscore.rs +++ b/compiler/rustc_lint/src/let_underscore.rs @@ -1,13 +1,12 @@ -use crate::{ - lints::{NonBindingLet, NonBindingLetSub}, - LateContext, LateLintPass, LintContext, -}; use rustc_errors::MultiSpan; use rustc_hir as hir; use rustc_middle::ty; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::{sym, Symbol}; +use crate::lints::{NonBindingLet, NonBindingLetSub}; +use crate::{LateContext, LateLintPass, LintContext}; + declare_lint! { /// The `let_underscore_drop` lint checks for statements which don't bind /// an expression which has a non-trivial Drop implementation to anything, diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 0df34c32e385b..72920fd045fd4 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -1,24 +1,7 @@ -use crate::errors::{CheckNameUnknownTool, RequestedLevel, UnsupportedGroup}; -use crate::lints::{ - DeprecatedLintNameFromCommandLine, RemovedLintFromCommandLine, RenamedLintFromCommandLine, - UnknownLintFromCommandLine, -}; -use crate::{ - builtin::MISSING_DOCS, - context::{CheckLintNameResult, LintStore}, - fluent_generated as fluent, - late::unerased_lint_store, - lints::{ - DeprecatedLintName, IgnoredUnlessCrateSpecified, OverruledAttributeLint, RemovedLint, - RenamedLint, RenamedLintSuggestion, UnknownLint, UnknownLintSuggestion, - }, -}; -use rustc_ast as ast; use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::{Diag, LintDiagnostic, MultiSpan}; use rustc_feature::{Features, GateIssue}; -use rustc_hir as hir; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::HirId; use rustc_index::IndexVec; @@ -30,21 +13,30 @@ use rustc_middle::lint::{ }; use rustc_middle::query::Providers; use rustc_middle::ty::{RegisteredTools, TyCtxt}; -use rustc_session::lint::{ - builtin::{ - self, FORBIDDEN_LINT_GROUPS, RENAMED_AND_REMOVED_LINTS, SINGLE_USE_LIFETIMES, - UNFULFILLED_LINT_EXPECTATIONS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES, - }, - Level, Lint, LintExpectationId, LintId, +use rustc_session::lint::builtin::{ + self, FORBIDDEN_LINT_GROUPS, RENAMED_AND_REMOVED_LINTS, SINGLE_USE_LIFETIMES, + UNFULFILLED_LINT_EXPECTATIONS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES, }; +use rustc_session::lint::{Level, Lint, LintExpectationId, LintId}; use rustc_session::Session; use rustc_span::symbol::{sym, Symbol}; use rustc_span::{Span, DUMMY_SP}; use tracing::{debug, instrument}; +use {rustc_ast as ast, rustc_hir as hir}; +use crate::builtin::MISSING_DOCS; +use crate::context::{CheckLintNameResult, LintStore}; use crate::errors::{ - MalformedAttribute, MalformedAttributeSub, OverruledAttribute, OverruledAttributeSub, - UnknownToolInScopedLint, + CheckNameUnknownTool, MalformedAttribute, MalformedAttributeSub, OverruledAttribute, + OverruledAttributeSub, RequestedLevel, UnknownToolInScopedLint, UnsupportedGroup, +}; +use crate::fluent_generated as fluent; +use crate::late::unerased_lint_store; +use crate::lints::{ + DeprecatedLintName, DeprecatedLintNameFromCommandLine, IgnoredUnlessCrateSpecified, + OverruledAttributeLint, RemovedLint, RemovedLintFromCommandLine, RenamedLint, + RenamedLintFromCommandLine, RenamedLintSuggestion, UnknownLint, UnknownLintFromCommandLine, + UnknownLintSuggestion, }; /// Collection of lint levels for the whole crate. diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index fc073233d9721..4f3933d461bbd 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -73,6 +73,7 @@ mod noop_method_call; mod opaque_hidden_inferred_bound; mod pass_by_value; mod passes; +mod precedence; mod ptr_nulls; mod redundant_semicolon; mod reference_casting; @@ -82,12 +83,6 @@ mod types; mod unit_bindings; mod unused; -pub use shadowed_into_iter::{ARRAY_INTO_ITER, BOXED_SLICE_INTO_ITER}; - -use rustc_hir::def_id::LocalModDefId; -use rustc_middle::query::Providers; -use rustc_middle::ty::TyCtxt; - use async_closures::AsyncClosureUsage; use async_fn_in_trait::AsyncFnInTrait; use builtin::*; @@ -111,24 +106,32 @@ use nonstandard_style::*; use noop_method_call::*; use opaque_hidden_inferred_bound::*; use pass_by_value::*; +use precedence::*; use ptr_nulls::*; use redundant_semicolon::*; use reference_casting::*; +use rustc_hir::def_id::LocalModDefId; +use rustc_middle::query::Providers; +use rustc_middle::ty::TyCtxt; use shadowed_into_iter::ShadowedIntoIter; +pub use shadowed_into_iter::{ARRAY_INTO_ITER, BOXED_SLICE_INTO_ITER}; use traits::*; use types::*; use unit_bindings::*; use unused::*; +#[rustfmt::skip] pub use builtin::{MissingDoc, SoftLints}; -pub use context::{CheckLintNameResult, FindLintError, LintStore}; -pub use context::{EarlyContext, LateContext, LintContext}; +pub use context::{ + CheckLintNameResult, EarlyContext, FindLintError, LateContext, LintContext, LintStore, +}; pub use early::{check_ast_node, EarlyCheckNode}; pub use late::{check_crate, late_lint_mod, unerased_lint_store}; pub use passes::{EarlyLintPass, LateLintPass}; pub use rustc_session::lint::Level::{self, *}; -pub use rustc_session::lint::{BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId}; -pub use rustc_session::lint::{LintPass, LintVec}; +pub use rustc_session::lint::{ + BufferedEarlyLint, FutureIncompatibleInfo, Lint, LintId, LintPass, LintVec, +}; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } @@ -174,6 +177,7 @@ early_lint_methods!( RedundantSemicolons: RedundantSemicolons, UnusedDocComment: UnusedDocComment, Expr2024: Expr2024, + Precedence: Precedence, ] ] ); @@ -539,7 +543,7 @@ fn register_builtins(store: &mut LintStore) { ); store.register_removed( "suspicious_auto_trait_impls", - "no longer needed, see #93367 \ + "no longer needed, see issue #93367 \ for more information", ); store.register_removed( @@ -561,6 +565,11 @@ fn register_builtins(store: &mut LintStore) { "box_pointers", "it does not detect other kinds of allocations, and existed only for historical reasons", ); + store.register_removed( + "byte_slice_in_packed_struct_with_derive", + "converted into hard error, see issue #107457 \ + for more information", + ) } fn register_internals(store: &mut LintStore) { diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 6c5f366727f95..46e7655a656b3 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -2,29 +2,26 @@ #![allow(rustc::untranslatable_diagnostic)] use std::num::NonZero; -use crate::errors::RequestedLevel; -use crate::fluent_generated as fluent; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, Applicability, Diag, DiagArgValue, DiagMessage, DiagStyledString, - ElidedLifetimeInPathSubdiag, EmissionGuarantee, LintDiagnostic, MultiSpan, SubdiagMessageOp, - Subdiagnostic, SuggestionStyle, + Applicability, Diag, DiagArgValue, DiagMessage, DiagStyledString, ElidedLifetimeInPathSubdiag, + EmissionGuarantee, LintDiagnostic, MultiSpan, SubdiagMessageOp, Subdiagnostic, SuggestionStyle, }; -use rustc_hir::{def::Namespace, def_id::DefId}; +use rustc_hir::def::Namespace; +use rustc_hir::def_id::DefId; +use rustc_hir::{self as hir}; use rustc_macros::{LintDiagnostic, Subdiagnostic}; -use rustc_middle::ty::{ - inhabitedness::InhabitedPredicate, Clause, PolyExistentialTraitRef, Ty, TyCtxt, -}; -use rustc_session::{lint::AmbiguityErrorDiag, Session}; -use rustc_span::{ - edition::Edition, - sym, - symbol::{Ident, MacroRulesNormalizedIdent}, - Span, Symbol, -}; - -use crate::{ - builtin::InitError, builtin::TypeAliasBounds, errors::OverruledAttributeSub, LateContext, -}; +use rustc_middle::ty::inhabitedness::InhabitedPredicate; +use rustc_middle::ty::{Clause, PolyExistentialTraitRef, Ty, TyCtxt}; +use rustc_session::lint::AmbiguityErrorDiag; +use rustc_session::Session; +use rustc_span::edition::Edition; +use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent}; +use rustc_span::{sym, Span, Symbol}; + +use crate::builtin::{InitError, ShorthandAssocTyCollector, TypeAliasBounds}; +use crate::errors::{OverruledAttributeSub, RequestedLevel}; +use crate::{fluent_generated as fluent, LateContext}; // array_into_iter.rs #[derive(LintDiagnostic)] @@ -263,62 +260,6 @@ pub struct BuiltinUnreachablePub<'a> { pub help: Option<()>, } -pub struct SuggestChangingAssocTypes<'a, 'b> { - pub ty: &'a rustc_hir::Ty<'b>, -} - -impl<'a, 'b> Subdiagnostic for SuggestChangingAssocTypes<'a, 'b> { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { - // Access to associates types should use `::Assoc`, which does not need a - // bound. Let's see if this type does that. - - // We use a HIR visitor to walk the type. - use rustc_hir::intravisit::{self, Visitor}; - struct WalkAssocTypes<'a, 'b, G: EmissionGuarantee> { - err: &'a mut Diag<'b, G>, - } - impl<'a, 'b, G: EmissionGuarantee> Visitor<'_> for WalkAssocTypes<'a, 'b, G> { - fn visit_qpath( - &mut self, - qpath: &rustc_hir::QPath<'_>, - id: rustc_hir::HirId, - span: Span, - ) { - if TypeAliasBounds::is_type_variable_assoc(qpath) { - self.err.span_help(span, fluent::lint_builtin_type_alias_bounds_help); - } - intravisit::walk_qpath(self, qpath, id) - } - } - - // Let's go for a walk! - let mut visitor = WalkAssocTypes { err: diag }; - visitor.visit_ty(self.ty); - } -} - -#[derive(LintDiagnostic)] -#[diag(lint_builtin_type_alias_where_clause)] -pub struct BuiltinTypeAliasWhereClause<'a, 'b> { - #[suggestion(code = "", applicability = "machine-applicable")] - pub suggestion: Span, - #[subdiagnostic] - pub sub: Option>, -} - -#[derive(LintDiagnostic)] -#[diag(lint_builtin_type_alias_generic_bounds)] -pub struct BuiltinTypeAliasGenericBounds<'a, 'b> { - #[subdiagnostic] - pub suggestion: BuiltinTypeAliasGenericBoundsSuggestion, - #[subdiagnostic] - pub sub: Option>, -} - #[derive(LintDiagnostic)] #[diag(lint_macro_expr_fragment_specifier_2024_migration)] pub struct MacroExprFragment2024 { @@ -326,21 +267,72 @@ pub struct MacroExprFragment2024 { pub suggestion: Span, } -pub struct BuiltinTypeAliasGenericBoundsSuggestion { +pub struct BuiltinTypeAliasBounds<'a, 'hir> { + pub in_where_clause: bool, + pub label: Span, + pub enable_feat_help: bool, pub suggestions: Vec<(Span, String)>, + pub preds: &'hir [hir::WherePredicate<'hir>], + pub ty: Option<&'a hir::Ty<'hir>>, } -impl Subdiagnostic for BuiltinTypeAliasGenericBoundsSuggestion { - fn add_to_diag_with>( - self, - diag: &mut Diag<'_, G>, - _f: &F, - ) { - diag.multipart_suggestion( - fluent::lint_suggestion, - self.suggestions, - Applicability::MachineApplicable, - ); +impl<'a> LintDiagnostic<'a, ()> for BuiltinTypeAliasBounds<'_, '_> { + fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) { + diag.primary_message(if self.in_where_clause { + fluent::lint_builtin_type_alias_bounds_where_clause + } else { + fluent::lint_builtin_type_alias_bounds_param_bounds + }); + diag.span_label(self.label, fluent::lint_builtin_type_alias_bounds_label); + diag.note(fluent::lint_builtin_type_alias_bounds_limitation_note); + if self.enable_feat_help { + diag.help(fluent::lint_builtin_type_alias_bounds_enable_feat_help); + } + + // We perform the walk in here instead of in `` to + // avoid doing throwaway work in case the lint ends up getting suppressed. + let mut collector = ShorthandAssocTyCollector { qselves: Vec::new() }; + if let Some(ty) = self.ty { + hir::intravisit::Visitor::visit_ty(&mut collector, ty); + } + + let affect_object_lifetime_defaults = self + .preds + .iter() + .filter(|pred| pred.in_where_clause() == self.in_where_clause) + .any(|pred| TypeAliasBounds::affects_object_lifetime_defaults(pred)); + + // If there are any shorthand assoc tys, then the bounds can't be removed automatically. + // The user first needs to fully qualify the assoc tys. + let applicability = if !collector.qselves.is_empty() || affect_object_lifetime_defaults { + Applicability::MaybeIncorrect + } else { + Applicability::MachineApplicable + }; + + diag.arg("count", self.suggestions.len()); + diag.multipart_suggestion(fluent::lint_suggestion, self.suggestions, applicability); + + // Suggest fully qualifying paths of the form `T::Assoc` with `T` type param via + // `::Assoc` to remove their reliance on any type param bounds. + // + // Instead of attempting to figure out the necessary trait ref, just use a + // placeholder. Since we don't record type-dependent resolutions for non-body + // items like type aliases, we can't simply deduce the corresp. trait from + // the HIR path alone without rerunning parts of HIR ty lowering here + // (namely `probe_single_ty_param_bound_for_assoc_ty`) which is infeasible. + // + // (We could employ some simple heuristics but that's likely not worth it). + for qself in collector.qselves { + diag.multipart_suggestion( + fluent::lint_builtin_type_alias_bounds_qualify_assoc_tys_sugg, + vec![ + (qself.shrink_to_lo(), "<".into()), + (qself.shrink_to_hi(), " as /* Trait */>".into()), + ], + Applicability::HasPlaceholders, + ); + } } } @@ -1499,6 +1491,35 @@ pub struct NonLocalDefinitionsCargoUpdateNote { pub crate_name: Symbol, } +// precedence.rs +#[derive(LintDiagnostic)] +#[diag(lint_ambiguous_negative_literals)] +#[note(lint_example)] +pub struct AmbiguousNegativeLiteralsDiag { + #[subdiagnostic] + pub negative_literal: AmbiguousNegativeLiteralsNegativeLiteralSuggestion, + #[subdiagnostic] + pub current_behavior: AmbiguousNegativeLiteralsCurrentBehaviorSuggestion, +} + +#[derive(Subdiagnostic)] +#[multipart_suggestion(lint_negative_literal, applicability = "maybe-incorrect")] +pub struct AmbiguousNegativeLiteralsNegativeLiteralSuggestion { + #[suggestion_part(code = "(")] + pub start_span: Span, + #[suggestion_part(code = ")")] + pub end_span: Span, +} + +#[derive(Subdiagnostic)] +#[multipart_suggestion(lint_current_behavior, applicability = "maybe-incorrect")] +pub struct AmbiguousNegativeLiteralsCurrentBehaviorSuggestion { + #[suggestion_part(code = "(")] + pub start_span: Span, + #[suggestion_part(code = ")")] + pub end_span: Span, +} + // pass_by_value.rs #[derive(LintDiagnostic)] #[diag(lint_pass_by_value)] diff --git a/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs b/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs index 867e132b1063e..e3b1967da09c7 100644 --- a/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs +++ b/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs @@ -1,16 +1,12 @@ -//! Migration code for the `expr_fragment_specifier_2024` -//! rule. -use tracing::debug; +//! Migration code for the `expr_fragment_specifier_2024` rule. -use rustc_ast::token::Token; -use rustc_ast::token::TokenKind; -use rustc_ast::tokenstream::TokenStream; -use rustc_ast::tokenstream::TokenTree; -use rustc_session::declare_lint; -use rustc_session::declare_lint_pass; +use rustc_ast::token::{Token, TokenKind}; +use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_session::lint::FutureIncompatibilityReason; +use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::edition::Edition; use rustc_span::sym; +use tracing::debug; use crate::lints::MacroExprFragment2024; use crate::EarlyLintPass; diff --git a/compiler/rustc_lint/src/map_unit_fn.rs b/compiler/rustc_lint/src/map_unit_fn.rs index e355604e2068c..3b27e45613690 100644 --- a/compiler/rustc_lint/src/map_unit_fn.rs +++ b/compiler/rustc_lint/src/map_unit_fn.rs @@ -1,13 +1,11 @@ -use crate::lints::MappingToUnit; -use crate::{LateContext, LateLintPass, LintContext}; - use rustc_hir::{Expr, ExprKind, HirId, Stmt, StmtKind}; -use rustc_middle::{ - query::Key, - ty::{self, Ty}, -}; +use rustc_middle::query::Key; +use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_lint, declare_lint_pass}; +use crate::lints::MappingToUnit; +use crate::{LateContext, LateLintPass, LintContext}; + declare_lint! { /// The `map_unit_fn` lint checks for `Iterator::map` receive /// a callable that returns `()`. diff --git a/compiler/rustc_lint/src/methods.rs b/compiler/rustc_lint/src/methods.rs index 7a71fec769fec..dff72bb622f23 100644 --- a/compiler/rustc_lint/src/methods.rs +++ b/compiler/rustc_lint/src/methods.rs @@ -1,11 +1,11 @@ -use crate::lints::CStringPtr; -use crate::LateContext; -use crate::LateLintPass; -use crate::LintContext; use rustc_hir::{Expr, ExprKind}; use rustc_middle::ty; use rustc_session::{declare_lint, declare_lint_pass}; -use rustc_span::{symbol::sym, Span}; +use rustc_span::symbol::sym; +use rustc_span::Span; + +use crate::lints::CStringPtr; +use crate::{LateContext, LateLintPass, LintContext}; declare_lint! { /// The `temporary_cstring_as_ptr` lint detects getting the inner pointer of diff --git a/compiler/rustc_lint/src/multiple_supertrait_upcastable.rs b/compiler/rustc_lint/src/multiple_supertrait_upcastable.rs index 93dd5e764c67d..978109aba5f92 100644 --- a/compiler/rustc_lint/src/multiple_supertrait_upcastable.rs +++ b/compiler/rustc_lint/src/multiple_supertrait_upcastable.rs @@ -1,8 +1,8 @@ -use crate::{LateContext, LateLintPass, LintContext}; - use rustc_hir as hir; use rustc_session::{declare_lint, declare_lint_pass}; +use crate::{LateContext, LateLintPass, LintContext}; + declare_lint! { /// The `multiple_supertrait_upcastable` lint detects when an object-safe trait has multiple /// supertraits. diff --git a/compiler/rustc_lint/src/non_ascii_idents.rs b/compiler/rustc_lint/src/non_ascii_idents.rs index 9f298a6071c69..08d054b6a8bd3 100644 --- a/compiler/rustc_lint/src/non_ascii_idents.rs +++ b/compiler/rustc_lint/src/non_ascii_idents.rs @@ -1,8 +1,3 @@ -use crate::lints::{ - ConfusableIdentifierPair, IdentifierNonAsciiChar, IdentifierUncommonCodepoints, - MixedScriptConfusables, -}; -use crate::{EarlyContext, EarlyLintPass, LintContext}; use rustc_ast as ast; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::unord::UnordMap; @@ -10,6 +5,12 @@ use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::symbol::Symbol; use unicode_security::general_security_profile::IdentifierType; +use crate::lints::{ + ConfusableIdentifierPair, IdentifierNonAsciiChar, IdentifierUncommonCodepoints, + MixedScriptConfusables, +}; +use crate::{EarlyContext, EarlyLintPass, LintContext}; + declare_lint! { /// The `non_ascii_idents` lint detects non-ASCII identifiers. /// @@ -152,9 +153,10 @@ declare_lint_pass!(NonAsciiIdents => [NON_ASCII_IDENTS, UNCOMMON_CODEPOINTS, CON impl EarlyLintPass for NonAsciiIdents { fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) { + use std::collections::BTreeMap; + use rustc_session::lint::Level; use rustc_span::Span; - use std::collections::BTreeMap; use unicode_security::GeneralSecurityProfile; let check_non_ascii_idents = cx.builder.lint_level(NON_ASCII_IDENTS).0 != Level::Allow; diff --git a/compiler/rustc_lint/src/non_fmt_panic.rs b/compiler/rustc_lint/src/non_fmt_panic.rs index 2dc2a0efdf040..10a517bfbcb76 100644 --- a/compiler/rustc_lint/src/non_fmt_panic.rs +++ b/compiler/rustc_lint/src/non_fmt_panic.rs @@ -1,19 +1,20 @@ -use crate::lints::{NonFmtPanicBraces, NonFmtPanicUnused}; -use crate::{fluent_generated as fluent, LateContext, LateLintPass, LintContext}; use rustc_ast as ast; use rustc_errors::Applicability; use rustc_hir::{self as hir, LangItem}; use rustc_infer::infer::TyCtxtInferExt; -use rustc_middle::bug; use rustc_middle::lint::in_external_macro; -use rustc_middle::ty; +use rustc_middle::{bug, ty}; use rustc_parse_format::{ParseMode, Parser, Piece}; use rustc_session::lint::FutureIncompatibilityReason; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::edition::Edition; -use rustc_span::{hygiene, sym, symbol::kw, InnerSpan, Span, Symbol}; +use rustc_span::symbol::kw; +use rustc_span::{hygiene, sym, InnerSpan, Span, Symbol}; use rustc_trait_selection::infer::InferCtxtExt; +use crate::lints::{NonFmtPanicBraces, NonFmtPanicUnused}; +use crate::{fluent_generated as fluent, LateContext, LateLintPass, LintContext}; + declare_lint! { /// The `non_fmt_panics` lint detects `panic!(..)` invocations where the first /// argument is not a formatting string. diff --git a/compiler/rustc_lint/src/non_local_def.rs b/compiler/rustc_lint/src/non_local_def.rs index 2f8eea6cd1816..5ad677995da1c 100644 --- a/compiler/rustc_lint/src/non_local_def.rs +++ b/compiler/rustc_lint/src/non_local_def.rs @@ -1,24 +1,23 @@ use rustc_errors::MultiSpan; +use rustc_hir::def::DefKind; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::HirId; -use rustc_hir::{def::DefKind, Body, Item, ItemKind, Node, TyKind}; -use rustc_hir::{Path, QPath}; +use rustc_hir::{Body, HirId, Item, ItemKind, Node, Path, QPath, TyKind}; use rustc_infer::infer::InferCtxt; use rustc_infer::traits::{Obligation, ObligationCause}; -use rustc_middle::ty::{self, Binder, Ty, TyCtxt, TypeFoldable, TypeFolder}; -use rustc_middle::ty::{EarlyBinder, TraitRef, TypeSuperFoldable}; +use rustc_middle::ty::{ + self, Binder, EarlyBinder, TraitRef, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, +}; use rustc_session::{declare_lint, impl_lint_pass}; use rustc_span::def_id::{DefId, LOCAL_CRATE}; -use rustc_span::Span; -use rustc_span::{sym, symbol::kw, ExpnKind, MacroKind, Symbol}; +use rustc_span::symbol::kw; +use rustc_span::{sym, ExpnKind, MacroKind, Span, Symbol}; use rustc_trait_selection::error_reporting::traits::ambiguity::{ compute_applicable_impls_for_diagnostics, CandidateSource, }; use rustc_trait_selection::infer::TyCtxtInferExt; -use crate::fluent_generated as fluent; use crate::lints::{NonLocalDefinitionsCargoUpdateNote, NonLocalDefinitionsDiag}; -use crate::{LateContext, LateLintPass, LintContext}; +use crate::{fluent_generated as fluent, LateContext, LateLintPass, LintContext}; declare_lint! { /// The `non_local_definitions` lint checks for `impl` blocks and `#[macro_export]` @@ -429,7 +428,7 @@ fn ty_has_local_parent( path_has_local_parent(ty_path, cx, impl_parent, impl_parent_parent) } TyKind::TraitObject([principle_poly_trait_ref, ..], _, _) => path_has_local_parent( - principle_poly_trait_ref.trait_ref.path, + principle_poly_trait_ref.0.trait_ref.path, cx, impl_parent, impl_parent_parent, @@ -527,7 +526,7 @@ fn self_ty_kind_for_diagnostic(ty: &rustc_hir::Ty<'_>, tcx: TyCtxt<'_>) -> (Span .to_string(), ), TyKind::TraitObject([principle_poly_trait_ref, ..], _, _) => { - let path = &principle_poly_trait_ref.trait_ref.path; + let path = &principle_poly_trait_ref.0.trait_ref.path; ( path_span_without_args(path), path.res diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index d64f444716207..ce7d203d8c05b 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -1,11 +1,3 @@ -use crate::lints::{ - NonCamelCaseType, NonCamelCaseTypeSub, NonSnakeCaseDiag, NonSnakeCaseDiagSub, - NonUpperCaseGlobal, NonUpperCaseGlobalSub, -}; -use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; -use rustc_ast as ast; -use rustc_attr as attr; -use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::FnKind; use rustc_hir::{GenericParamKind, PatKind}; @@ -16,6 +8,13 @@ use rustc_span::def_id::LocalDefId; use rustc_span::symbol::{sym, Ident}; use rustc_span::{BytePos, Span}; use rustc_target::spec::abi::Abi; +use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; + +use crate::lints::{ + NonCamelCaseType, NonCamelCaseTypeSub, NonSnakeCaseDiag, NonSnakeCaseDiagSub, + NonUpperCaseGlobal, NonUpperCaseGlobalSub, +}; +use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; #[derive(PartialEq)] pub enum MethodLateContext { diff --git a/compiler/rustc_lint/src/noop_method_call.rs b/compiler/rustc_lint/src/noop_method_call.rs index 307e4bebe9a1b..d08a959f6547b 100644 --- a/compiler/rustc_lint/src/noop_method_call.rs +++ b/compiler/rustc_lint/src/noop_method_call.rs @@ -1,9 +1,3 @@ -use crate::context::LintContext; -use crate::lints::{ - NoopMethodCallDiag, SuspiciousDoubleRefCloneDiag, SuspiciousDoubleRefDerefDiag, -}; -use crate::LateContext; -use crate::LateLintPass; use rustc_hir::def::DefKind; use rustc_hir::{Expr, ExprKind}; use rustc_middle::ty; @@ -11,6 +5,12 @@ use rustc_middle::ty::adjustment::Adjust; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::symbol::sym; +use crate::context::LintContext; +use crate::lints::{ + NoopMethodCallDiag, SuspiciousDoubleRefCloneDiag, SuspiciousDoubleRefDerefDiag, +}; +use crate::{LateContext, LateLintPass}; + declare_lint! { /// The `noop_method_call` lint detects specific calls to noop methods /// such as a calling `<&T as Clone>::clone` where `T: !Clone`. diff --git a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs index fdb71ad41a754..e0ba6a912f120 100644 --- a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs +++ b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs @@ -1,10 +1,12 @@ use rustc_hir as hir; use rustc_infer::infer::TyCtxtInferExt; use rustc_macros::{LintDiagnostic, Subdiagnostic}; +use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::print::{PrintTraitPredicateExt as _, TraitPredPrintModifiersAndPath}; -use rustc_middle::ty::{self, fold::BottomUpFolder, Ty, TypeFoldable}; +use rustc_middle::ty::{self, Ty, TypeFoldable}; use rustc_session::{declare_lint, declare_lint_pass}; -use rustc_span::{symbol::kw, Span}; +use rustc_span::symbol::kw; +use rustc_span::Span; use rustc_trait_selection::traits::{self, ObligationCtxt}; use crate::{LateContext, LateLintPass, LintContext}; diff --git a/compiler/rustc_lint/src/pass_by_value.rs b/compiler/rustc_lint/src/pass_by_value.rs index fa23f120468a4..23b200998a537 100644 --- a/compiler/rustc_lint/src/pass_by_value.rs +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -1,5 +1,3 @@ -use crate::lints::PassByValueDiag; -use crate::{LateContext, LateLintPass, LintContext}; use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::{GenericArg, PathSegment, QPath, TyKind}; @@ -7,6 +5,9 @@ use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::sym; +use crate::lints::PassByValueDiag; +use crate::{LateContext, LateLintPass, LintContext}; + declare_tool_lint! { /// The `rustc_pass_by_value` lint marks a type with `#[rustc_pass_by_value]` requiring it to /// always be passed by value. This is usually used for types that are thin wrappers around diff --git a/compiler/rustc_lint/src/passes.rs b/compiler/rustc_lint/src/passes.rs index 2a843977990c2..bf16e3b7d150f 100644 --- a/compiler/rustc_lint/src/passes.rs +++ b/compiler/rustc_lint/src/passes.rs @@ -1,8 +1,8 @@ -use crate::context::{EarlyContext, LateContext}; - use rustc_session::lint::builtin::HardwiredLints; use rustc_session::lint::LintPass; +use crate::context::{EarlyContext, LateContext}; + #[macro_export] macro_rules! late_lint_methods { ($macro:path, $args:tt) => ( diff --git a/compiler/rustc_lint/src/precedence.rs b/compiler/rustc_lint/src/precedence.rs new file mode 100644 index 0000000000000..52321e25c7d43 --- /dev/null +++ b/compiler/rustc_lint/src/precedence.rs @@ -0,0 +1,71 @@ +use rustc_ast::token::LitKind; +use rustc_ast::{Expr, ExprKind, MethodCall, UnOp}; +use rustc_session::{declare_lint, declare_lint_pass}; + +use crate::lints::{ + AmbiguousNegativeLiteralsCurrentBehaviorSuggestion, AmbiguousNegativeLiteralsDiag, + AmbiguousNegativeLiteralsNegativeLiteralSuggestion, +}; +use crate::{EarlyContext, EarlyLintPass, LintContext}; + +declare_lint! { + /// The `ambiguous_negative_literals` lint checks for cases that are + /// confusing between a negative literal and a negation that's not part + /// of the literal. + /// + /// ### Example + /// + /// ```rust,compile_fail + /// # #![deny(ambiguous_negative_literals)] + /// # #![allow(unused)] + /// -1i32.abs(); // equals -1, while `(-1i32).abs()` equals 1 + /// ``` + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// Method calls take precedence over unary precedence. Setting the + /// precedence explicitly makes the code clearer and avoid potential bugs. + pub AMBIGUOUS_NEGATIVE_LITERALS, + Allow, + "ambiguous negative literals operations", + report_in_external_macro +} + +declare_lint_pass!(Precedence => [AMBIGUOUS_NEGATIVE_LITERALS]); + +impl EarlyLintPass for Precedence { + fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) { + let ExprKind::Unary(UnOp::Neg, operand) = &expr.kind else { + return; + }; + + let mut arg = operand; + let mut at_least_one = false; + while let ExprKind::MethodCall(box MethodCall { receiver, .. }) = &arg.kind { + at_least_one = true; + arg = receiver; + } + + if at_least_one + && let ExprKind::Lit(lit) = &arg.kind + && let LitKind::Integer | LitKind::Float = &lit.kind + { + cx.emit_span_lint( + AMBIGUOUS_NEGATIVE_LITERALS, + expr.span, + AmbiguousNegativeLiteralsDiag { + negative_literal: AmbiguousNegativeLiteralsNegativeLiteralSuggestion { + start_span: expr.span.shrink_to_lo(), + end_span: arg.span.shrink_to_hi(), + }, + current_behavior: AmbiguousNegativeLiteralsCurrentBehaviorSuggestion { + start_span: operand.span.shrink_to_lo(), + end_span: operand.span.shrink_to_hi(), + }, + }, + ); + } + } +} diff --git a/compiler/rustc_lint/src/ptr_nulls.rs b/compiler/rustc_lint/src/ptr_nulls.rs index 8038115ef51c1..1489f9de81991 100644 --- a/compiler/rustc_lint/src/ptr_nulls.rs +++ b/compiler/rustc_lint/src/ptr_nulls.rs @@ -1,9 +1,11 @@ -use crate::{lints::PtrNullChecksDiag, LateContext, LateLintPass, LintContext}; use rustc_ast::LitKind; use rustc_hir::{BinOpKind, Expr, ExprKind, TyKind}; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::sym; +use crate::lints::PtrNullChecksDiag; +use crate::{LateContext, LateLintPass, LintContext}; + declare_lint! { /// The `useless_ptr_null_checks` lint checks for useless null checks against pointers /// obtained from non-null types. diff --git a/compiler/rustc_lint/src/redundant_semicolon.rs b/compiler/rustc_lint/src/redundant_semicolon.rs index ef08e79e24a0a..b43e4938b736c 100644 --- a/compiler/rustc_lint/src/redundant_semicolon.rs +++ b/compiler/rustc_lint/src/redundant_semicolon.rs @@ -1,8 +1,10 @@ -use crate::{lints::RedundantSemicolonsDiag, EarlyContext, EarlyLintPass, LintContext}; use rustc_ast::{Block, StmtKind}; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::Span; +use crate::lints::RedundantSemicolonsDiag; +use crate::{EarlyContext, EarlyLintPass, LintContext}; + declare_lint! { /// The `redundant_semicolons` lint detects unnecessary trailing /// semicolons. diff --git a/compiler/rustc_lint/src/reference_casting.rs b/compiler/rustc_lint/src/reference_casting.rs index 34153e3a220d3..5e8c39c0023eb 100644 --- a/compiler/rustc_lint/src/reference_casting.rs +++ b/compiler/rustc_lint/src/reference_casting.rs @@ -1,11 +1,12 @@ use rustc_ast::Mutability; use rustc_hir::{Expr, ExprKind, UnOp}; -use rustc_middle::ty::layout::LayoutOf as _; -use rustc_middle::ty::{self, layout::TyAndLayout}; +use rustc_middle::ty::layout::{LayoutOf as _, TyAndLayout}; +use rustc_middle::ty::{self}; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::sym; -use crate::{lints::InvalidReferenceCastingDiag, LateContext, LateLintPass, LintContext}; +use crate::lints::InvalidReferenceCastingDiag; +use crate::{LateContext, LateLintPass, LintContext}; declare_lint! { /// The `invalid_reference_casting` lint checks for casts of `&T` to `&mut T` diff --git a/compiler/rustc_lint/src/shadowed_into_iter.rs b/compiler/rustc_lint/src/shadowed_into_iter.rs index da2b5878b19cd..4fe35a6a0a3bc 100644 --- a/compiler/rustc_lint/src/shadowed_into_iter.rs +++ b/compiler/rustc_lint/src/shadowed_into_iter.rs @@ -1,11 +1,12 @@ -use crate::lints::{ShadowedIntoIterDiag, ShadowedIntoIterDiagSub}; -use crate::{LateContext, LateLintPass, LintContext}; use rustc_hir as hir; use rustc_middle::ty::{self, Ty}; use rustc_session::lint::FutureIncompatibilityReason; use rustc_session::{declare_lint, impl_lint_pass}; use rustc_span::edition::Edition; +use crate::lints::{ShadowedIntoIterDiag, ShadowedIntoIterDiagSub}; +use crate::{LateContext, LateLintPass, LintContext}; + declare_lint! { /// The `array_into_iter` lint detects calling `into_iter` on arrays. /// diff --git a/compiler/rustc_lint/src/tests.rs b/compiler/rustc_lint/src/tests.rs index 4fd054cb7179f..988d1645fba22 100644 --- a/compiler/rustc_lint/src/tests.rs +++ b/compiler/rustc_lint/src/tests.rs @@ -1,6 +1,7 @@ -use crate::levels::parse_lint_and_tool_name; use rustc_span::{create_default_session_globals_then, Symbol}; +use crate::levels::parse_lint_and_tool_name; + #[test] fn parse_lint_no_tool() { create_default_session_globals_then(|| { diff --git a/compiler/rustc_lint/src/traits.rs b/compiler/rustc_lint/src/traits.rs index 6983e7abbd64e..fea96b5366e6c 100644 --- a/compiler/rustc_lint/src/traits.rs +++ b/compiler/rustc_lint/src/traits.rs @@ -1,11 +1,10 @@ -use crate::lints::{DropGlue, DropTraitConstraintsDiag}; -use crate::LateContext; -use crate::LateLintPass; -use crate::LintContext; use rustc_hir::{self as hir, LangItem}; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::symbol::sym; +use crate::lints::{DropGlue, DropTraitConstraintsDiag}; +use crate::{LateContext, LateLintPass, LintContext}; + declare_lint! { /// The `drop_bounds` lint checks for generics with `std::ops::Drop` as /// bounds. @@ -113,9 +112,11 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx>) { let hir::TyKind::TraitObject(bounds, _lifetime, _syntax) = &ty.kind else { return }; - for bound in &bounds[..] { + for (bound, modifier) in &bounds[..] { let def_id = bound.trait_ref.trait_def_id(); - if cx.tcx.lang_items().drop_trait() == def_id { + if cx.tcx.lang_items().drop_trait() == def_id + && *modifier != hir::TraitBoundModifier::Maybe + { let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { return }; cx.emit_span_lint(DYN_DROP, bound.span, DropGlue { tcx: cx.tcx, def_id }); } diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index c0364b3571642..f3196cfed533e 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1,39 +1,33 @@ -use crate::{ - fluent_generated as fluent, - lints::{ - AmbiguousWidePointerComparisons, AmbiguousWidePointerComparisonsAddrMetadataSuggestion, - AmbiguousWidePointerComparisonsAddrSuggestion, AtomicOrderingFence, AtomicOrderingLoad, - AtomicOrderingStore, ImproperCTypes, InvalidAtomicOrderingDiag, InvalidNanComparisons, - InvalidNanComparisonsSuggestion, OnlyCastu8ToChar, OverflowingBinHex, - OverflowingBinHexSign, OverflowingBinHexSignBitSub, OverflowingBinHexSub, OverflowingInt, - OverflowingIntHelp, OverflowingLiteral, OverflowingUInt, RangeEndpointOutOfRange, - UnusedComparisons, UseInclusiveRange, VariantSizeDifferencesDiag, - }, -}; -use crate::{LateContext, LateLintPass, LintContext}; -use rustc_ast as ast; -use rustc_attr as attr; +use std::iter; +use std::ops::ControlFlow; + use rustc_data_structures::fx::FxHashSet; use rustc_errors::DiagMessage; -use rustc_hir as hir; use rustc_hir::{is_range_literal, Expr, ExprKind, Node}; use rustc_middle::bug; use rustc_middle::ty::layout::{IntegerExt, LayoutOf, SizeSkeleton}; -use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{ - self, AdtKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, + self, AdtKind, GenericArgsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, }; use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass}; use rustc_span::def_id::LocalDefId; -use rustc_span::source_map; use rustc_span::symbol::sym; -use rustc_span::{Span, Symbol}; -use rustc_target::abi::{Abi, Size, WrappingRange}; -use rustc_target::abi::{Integer, TagEncoding, Variants}; +use rustc_span::{source_map, Span, Symbol}; +use rustc_target::abi::{Abi, Integer, Size, TagEncoding, Variants, WrappingRange}; use rustc_target::spec::abi::Abi as SpecAbi; -use std::iter; -use std::ops::ControlFlow; use tracing::debug; +use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; + +use crate::lints::{ + AmbiguousWidePointerComparisons, AmbiguousWidePointerComparisonsAddrMetadataSuggestion, + AmbiguousWidePointerComparisonsAddrSuggestion, AtomicOrderingFence, AtomicOrderingLoad, + AtomicOrderingStore, ImproperCTypes, InvalidAtomicOrderingDiag, InvalidNanComparisons, + InvalidNanComparisonsSuggestion, OnlyCastu8ToChar, OverflowingBinHex, OverflowingBinHexSign, + OverflowingBinHexSignBitSub, OverflowingBinHexSub, OverflowingInt, OverflowingIntHelp, + OverflowingLiteral, OverflowingUInt, RangeEndpointOutOfRange, UnusedComparisons, + UseInclusiveRange, VariantSizeDifferencesDiag, +}; +use crate::{fluent_generated as fluent, LateContext, LateLintPass, LintContext}; declare_lint! { /// The `unused_comparisons` lint detects comparisons made useless by @@ -315,11 +309,7 @@ fn report_bin_hex_error( ) { let (t, actually) = match ty { attr::IntType::SignedInt(t) => { - let actually = if negative { - -(size.sign_extend(val) as i128) - } else { - size.sign_extend(val) as i128 - }; + let actually = if negative { -(size.sign_extend(val)) } else { size.sign_extend(val) }; (t.name_str(), actually.to_string()) } attr::IntType::UnsignedInt(t) => { diff --git a/compiler/rustc_lint/src/unit_bindings.rs b/compiler/rustc_lint/src/unit_bindings.rs index 8202bfa805a29..ed015908ae54a 100644 --- a/compiler/rustc_lint/src/unit_bindings.rs +++ b/compiler/rustc_lint/src/unit_bindings.rs @@ -1,8 +1,9 @@ -use crate::lints::UnitBindingsDiag; -use crate::{LateLintPass, LintContext}; use rustc_hir as hir; use rustc_session::{declare_lint, declare_lint_pass}; +use crate::lints::UnitBindingsDiag; +use crate::{LateLintPass, LintContext}; + declare_lint! { /// The `unit_bindings` lint detects cases where bindings are useless because they have /// the unit type `()` as their inferred type. The lint is suppressed if the user explicitly diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 65d42ed8054f9..795333224ba00 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -1,11 +1,6 @@ -use crate::lints::{ - PathStatementDrop, PathStatementDropSub, PathStatementNoEffect, UnusedAllocationDiag, - UnusedAllocationMutDiag, UnusedClosure, UnusedCoroutine, UnusedDef, UnusedDefSuggestion, - UnusedDelim, UnusedDelimSuggestion, UnusedImportBracesDiag, UnusedOp, UnusedOpSuggestion, - UnusedResult, -}; -use crate::Lint; -use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; +use std::iter; +use std::ops::ControlFlow; + use rustc_ast as ast; use rustc_ast::util::{classify, parser}; use rustc_ast::{ExprKind, StmtKind}; @@ -14,16 +9,20 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, LangItem}; use rustc_infer::traits::util::elaborate; -use rustc_middle::ty::adjustment; -use rustc_middle::ty::{self, Ty}; +use rustc_middle::ty::{self, adjustment, Ty}; use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass}; -use rustc_span::symbol::Symbol; -use rustc_span::symbol::{kw, sym}; +use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::{BytePos, Span}; -use std::iter; -use std::ops::ControlFlow; use tracing::instrument; +use crate::lints::{ + PathStatementDrop, PathStatementDropSub, PathStatementNoEffect, UnusedAllocationDiag, + UnusedAllocationMutDiag, UnusedClosure, UnusedCoroutine, UnusedDef, UnusedDefSuggestion, + UnusedDelim, UnusedDelimSuggestion, UnusedImportBracesDiag, UnusedOp, UnusedOpSuggestion, + UnusedResult, +}; +use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, Lint, LintContext}; + declare_lint! { /// The `unused_must_use` lint detects unused result of a type flagged as /// `#[must_use]`. @@ -1205,7 +1204,8 @@ impl EarlyLintPass for UnusedParens { } fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) { - use ast::{Mutability, PatKind::*}; + use ast::Mutability; + use ast::PatKind::*; let keep_space = (false, false); match &p.kind { // Do not lint on `(..)` as that will result in the other arms being useless. diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 2f4e6a3230831..ff0bdfcc9d261 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -7,9 +7,10 @@ //! When removing a lint, make sure to also add a call to `register_removed` in //! compiler/rustc_lint/src/lib.rs. -use crate::{declare_lint, declare_lint_pass, FutureIncompatibilityReason}; use rustc_span::edition::Edition; +use crate::{declare_lint, declare_lint_pass, FutureIncompatibilityReason}; + declare_lint_pass! { /// Does nothing as a lint pass, but registers some `Lint`s /// that are used by other parts of the compiler. @@ -25,7 +26,6 @@ declare_lint_pass! { BARE_TRAIT_OBJECTS, BINDINGS_WITH_VARIANT_NAME, BREAK_WITH_LABEL_AND_LOOP, - BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE, CENUM_IMPL_DROP_CAST, COHERENCE_LEAK_CHECK, CONFLICTING_REPR_HINTS, @@ -81,6 +81,7 @@ declare_lint_pass! { PROC_MACRO_DERIVE_RESOLUTION_FALLBACK, PTR_CAST_ADD_AUTO_TO_OBJECT, PUB_USE_OF_PRIVATE_EXTERN_CRATE, + REDUNDANT_IMPORTS, REDUNDANT_LIFETIMES, REFINING_IMPL_TRAIT_INTERNAL, REFINING_IMPL_TRAIT_REACHABLE, @@ -91,6 +92,7 @@ declare_lint_pass! { RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, RUST_2021_PRELUDE_COLLISIONS, RUST_2024_INCOMPATIBLE_PAT, + RUST_2024_PRELUDE_COLLISIONS, SELF_CONSTRUCTOR_FROM_OUTER_ITEM, SEMICOLON_IN_EXPRESSIONS_FROM_MACROS, SINGLE_USE_LIFETIMES, @@ -424,6 +426,31 @@ declare_lint! { "imports that are never used" } +declare_lint! { + /// The `redundant_imports` lint detects imports that are redundant due to being + /// imported already; either through a previous import, or being present in + /// the prelude. + /// + /// ### Example + /// + /// ```rust,compile_fail + /// #![deny(redundant_imports)] + /// use std::option::Option::None; + /// fn foo() -> Option { None } + /// ``` + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// Redundant imports are unnecessary and can be removed to simplify code. + /// If you intended to re-export the item to make it available outside of the + /// module, add a visibility modifier like `pub`. + pub REDUNDANT_IMPORTS, + Allow, + "imports that are redundant due to being imported already" +} + declare_lint! { /// The `must_not_suspend` lint guards against values that shouldn't be held across suspend points /// (`.await`) @@ -615,8 +642,6 @@ declare_lint! { /// ### Example /// /// ```rust - /// #![cfg_attr(bootstrap, feature(lint_reasons))] - /// /// #[expect(unused_variables)] /// let x = 10; /// println!("{}", x); @@ -1241,7 +1266,7 @@ declare_lint! { Deny, "type parameter default erroneously allowed in invalid location", @future_incompatible = FutureIncompatibleInfo { - reason: FutureIncompatibilityReason::FutureReleaseErrorDontReportInDeps, + reason: FutureIncompatibilityReason::FutureReleaseErrorReportInDeps, reference: "issue #36887 ", }; } @@ -1424,7 +1449,7 @@ declare_lint! { Deny, "detects missing fragment specifiers in unused `macro_rules!` patterns", @future_incompatible = FutureIncompatibleInfo { - reason: FutureIncompatibilityReason::FutureReleaseErrorDontReportInDeps, + reason: FutureIncompatibilityReason::FutureReleaseErrorReportInDeps, reference: "issue #40107 ", }; } @@ -1834,8 +1859,7 @@ declare_lint! { /// [placeholder lifetime]: https://doc.rust-lang.org/reference/lifetime-elision.html#lifetime-elision-in-functions pub ELIDED_LIFETIMES_IN_PATHS, Allow, - "hidden lifetime parameters in types are deprecated", - crate_level_only + "hidden lifetime parameters in types are deprecated" } declare_lint! { @@ -1984,14 +2008,18 @@ declare_lint! { /// /// ```rust /// trait MyIterator : Iterator { - /// // is_sorted is an unstable method that already exists on the Iterator trait - /// fn is_sorted(self) -> bool where Self: Sized {true} + /// // is_partitioned is an unstable method that already exists on the Iterator trait + /// fn is_partitioned

(self, predicate: P) -> bool + /// where + /// Self: Sized, + /// P: FnMut(Self::Item) -> bool, + /// {true} /// } /// /// impl MyIterator for T where T: Iterator { } /// /// let x = vec![1, 2, 3]; - /// let _ = x.iter().is_sorted(); + /// let _ = x.iter().is_partitioned(|_| true); /// ``` /// /// {{produces}} @@ -2007,7 +2035,7 @@ declare_lint! { /// is an early-warning to let you know that there may be a collision in /// the future. This can be avoided by adding type annotations to /// disambiguate which trait method you intend to call, such as - /// `MyIterator::is_sorted(my_iter)` or renaming or removing the method. + /// `MyIterator::is_partitioned(my_iter, my_predicate)` or renaming or removing the method. /// /// [nightly channel]: https://doc.rust-lang.org/book/appendix-07-nightly-rust.html /// [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/ @@ -3750,6 +3778,46 @@ declare_lint! { }; } +declare_lint! { + /// The `rust_2024_prelude_collisions` lint detects the usage of trait methods which are ambiguous + /// with traits added to the prelude in future editions. + /// + /// ### Example + /// + /// ```rust,edition2021,compile_fail + /// #![deny(rust_2024_prelude_collisions)] + /// trait Meow { + /// fn poll(&self) {} + /// } + /// impl Meow for T {} + /// + /// fn main() { + /// core::pin::pin!(async {}).poll(); + /// // ^^^^^^ + /// // This call to try_into matches both Future::poll and Meow::poll as + /// // `Future` has been added to the Rust prelude in 2024 edition. + /// } + /// ``` + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// Rust 2024, introduces two new additions to the standard library's prelude: + /// `Future` and `IntoFuture`. This results in an ambiguity as to which method/function + /// to call when an existing `poll`/`into_future` method is called via dot-call syntax or + /// a `poll`/`into_future` associated function is called directly on a type. + /// + pub RUST_2024_PRELUDE_COLLISIONS, + Allow, + "detects the usage of trait methods which are ambiguous with traits added to the \ + prelude in future editions", + @future_incompatible = FutureIncompatibleInfo { + reason: FutureIncompatibilityReason::EditionError(Edition::Edition2024), + reference: "", + }; +} + declare_lint! { /// The `rust_2021_prefixes_incompatible_syntax` lint detects identifiers that will be parsed as a /// prefix instead in Rust 2021. @@ -4246,39 +4314,6 @@ declare_lint! { report_in_external_macro } -declare_lint! { - /// The `byte_slice_in_packed_struct_with_derive` lint detects cases where a byte slice field - /// (`[u8]`) or string slice field (`str`) is used in a `packed` struct that derives one or - /// more built-in traits. - /// - /// ### Example - /// - /// ```rust - /// #[repr(packed)] - /// #[derive(Hash)] - /// struct FlexZeroSlice { - /// width: u8, - /// data: [u8], - /// } - /// ``` - /// - /// {{produces}} - /// - /// ### Explanation - /// - /// This was previously accepted but is being phased out, because fields in packed structs are - /// now required to implement `Copy` for `derive` to work. Byte slices and string slices are a - /// temporary exception because certain crates depended on them. - pub BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE, - Warn, - "`[u8]` or `str` used in a packed struct with `derive`", - @future_incompatible = FutureIncompatibleInfo { - reason: FutureIncompatibilityReason::FutureReleaseErrorReportInDeps, - reference: "issue #107457 ", - }; - report_in_external_macro -} - declare_lint! { /// The `invalid_macro_export_arguments` lint detects cases where `#[macro_export]` is being used with invalid arguments. /// @@ -4865,7 +4900,6 @@ declare_lint! { /// ### Example /// /// ```rust - /// #![feature(unsafe_extern_blocks)] /// #![warn(missing_unsafe_on_extern)] /// #![allow(dead_code)] /// diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index f87f19e170005..19efa36b40fbe 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -1,4 +1,3 @@ -pub use self::Level::*; use rustc_ast::node_id::NodeId; use rustc_ast::{AttrId, Attribute}; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; @@ -7,16 +6,16 @@ use rustc_data_structures::stable_hasher::{ }; use rustc_error_messages::{DiagMessage, MultiSpan}; use rustc_hir::def::Namespace; -use rustc_hir::HashStableContext; -use rustc_hir::HirId; +use rustc_hir::{HashStableContext, HirId}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_span::edition::Edition; -use rustc_span::symbol::MacroRulesNormalizedIdent; -use rustc_span::{sym, symbol::Ident, Span, Symbol}; +use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent}; +use rustc_span::{sym, Span, Symbol}; use rustc_target::spec::abi::Abi; - use serde::{Deserialize, Serialize}; +pub use self::Level::*; + pub mod builtin; #[macro_export] diff --git a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp index 14757b27a3758..2ff7335a0fc81 100644 --- a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp @@ -1419,8 +1419,6 @@ extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) { return LLVMPointerTypeKind; case Type::FixedVectorTyID: return LLVMVectorTypeKind; - case Type::X86_MMXTyID: - return LLVMX86_MMXTypeKind; case Type::TokenTyID: return LLVMTokenTypeKind; case Type::ScalableVectorTyID: @@ -1557,7 +1555,7 @@ LLVMRustGetInstrProfMCDCTVBitmapUpdateIntrinsic(LLVMModuleRef M) { extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCCondBitmapIntrinsic(LLVMModuleRef M) { -#if LLVM_VERSION_GE(18, 0) +#if LLVM_VERSION_GE(18, 0) && LLVM_VERSION_LT(19, 0) return wrap(llvm::Intrinsic::getDeclaration( unwrap(M), llvm::Intrinsic::instrprof_mcdc_condbitmap_update)); #else diff --git a/compiler/rustc_llvm/src/lib.rs b/compiler/rustc_llvm/src/lib.rs index 1365afbce1c37..939e5e4dbd4ff 100644 --- a/compiler/rustc_llvm/src/lib.rs +++ b/compiler/rustc_llvm/src/lib.rs @@ -7,10 +7,11 @@ // NOTE: This crate only exists to allow linking on mingw targets. -use libc::{c_char, size_t}; use std::cell::RefCell; use std::slice; +use libc::{c_char, size_t}; + #[repr(C)] pub struct RustString { pub bytes: RefCell>, diff --git a/compiler/rustc_log/src/lib.rs b/compiler/rustc_log/src/lib.rs index 01b6e342df047..b6d870768a862 100644 --- a/compiler/rustc_log/src/lib.rs +++ b/compiler/rustc_log/src/lib.rs @@ -41,12 +41,11 @@ use std::env::{self, VarError}; use std::fmt::{self, Display}; use std::io::{self, IsTerminal}; + use tracing_core::{Event, Subscriber}; use tracing_subscriber::filter::{Directive, EnvFilter, LevelFilter}; -use tracing_subscriber::fmt::{ - format::{self, FormatEvent, FormatFields}, - FmtContext, -}; +use tracing_subscriber::fmt::format::{self, FormatEvent, FormatFields}; +use tracing_subscriber::fmt::FmtContext; use tracing_subscriber::layer::SubscriberExt; /// The values of all the environment variables that matter for configuring a logger. diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic.rs b/compiler/rustc_macros/src/diagnostics/diagnostic.rs index 2743660ab8917..52d892a20f4d3 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic.rs @@ -2,14 +2,15 @@ use std::cell::RefCell; -use crate::diagnostics::diagnostic_builder::DiagnosticDeriveKind; -use crate::diagnostics::error::{span_err, DiagnosticDeriveError}; -use crate::diagnostics::utils::SetOnce; use proc_macro2::TokenStream; use quote::quote; use syn::spanned::Spanned; use synstructure::Structure; +use crate::diagnostics::diagnostic_builder::DiagnosticDeriveKind; +use crate::diagnostics::error::{span_err, DiagnosticDeriveError}; +use crate::diagnostics::utils::SetOnce; + /// The central struct for constructing the `into_diag` method from an annotated struct. pub(crate) struct DiagnosticDerive<'a> { structure: Structure<'a>, diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs index f93d89d6c0f04..5c2a429a1ebbe 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs @@ -1,5 +1,12 @@ #![deny(unused_must_use)] +use proc_macro2::{Ident, Span, TokenStream}; +use quote::{format_ident, quote, quote_spanned}; +use syn::spanned::Spanned; +use syn::{parse_quote, Attribute, Meta, Path, Token, Type}; +use synstructure::{BindingInfo, Structure, VariantInfo}; + +use super::utils::SubdiagnosticVariant; use crate::diagnostics::error::{ span_err, throw_invalid_attr, throw_span_err, DiagnosticDeriveError, }; @@ -8,13 +15,6 @@ use crate::diagnostics::utils::{ should_generate_arg, type_is_bool, type_is_unit, type_matches_path, FieldInfo, FieldInnerTy, FieldMap, HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind, }; -use proc_macro2::{Ident, Span, TokenStream}; -use quote::{format_ident, quote, quote_spanned}; -use syn::Token; -use syn::{parse_quote, spanned::Spanned, Attribute, Meta, Path, Type}; -use synstructure::{BindingInfo, Structure, VariantInfo}; - -use super::utils::SubdiagnosticVariant; /// What kind of diagnostic is being derived - a fatal/error/warning or a lint? #[derive(Clone, Copy, PartialEq, Eq)] diff --git a/compiler/rustc_macros/src/diagnostics/error.rs b/compiler/rustc_macros/src/diagnostics/error.rs index 13138ee4ab725..9cdb9fbab12a8 100644 --- a/compiler/rustc_macros/src/diagnostics/error.rs +++ b/compiler/rustc_macros/src/diagnostics/error.rs @@ -1,7 +1,8 @@ use proc_macro::{Diagnostic, Level, MultiSpan}; use proc_macro2::TokenStream; use quote::quote; -use syn::{spanned::Spanned, Attribute, Error as SynError, Meta}; +use syn::spanned::Spanned; +use syn::{Attribute, Error as SynError, Meta}; #[derive(Debug)] pub(crate) enum DiagnosticDeriveError { diff --git a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs index 7f090f5ebc163..5d5d279eaf0a5 100644 --- a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs @@ -1,5 +1,12 @@ #![deny(unused_must_use)] +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; +use syn::spanned::Spanned; +use syn::{Attribute, Meta, MetaList, Path}; +use synstructure::{BindingInfo, Structure, VariantInfo}; + +use super::utils::SubdiagnosticVariant; use crate::diagnostics::error::{ invalid_attr, span_err, throw_invalid_attr, throw_span_err, DiagnosticDeriveError, }; @@ -9,12 +16,6 @@ use crate::diagnostics::utils::{ should_generate_arg, AllowMultipleAlternatives, FieldInfo, FieldInnerTy, FieldMap, HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind, }; -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; -use syn::{spanned::Spanned, Attribute, Meta, MetaList, Path}; -use synstructure::{BindingInfo, Structure, VariantInfo}; - -use super::utils::SubdiagnosticVariant; /// The central struct for constructing the `add_to_diag` method from an annotated struct. pub(crate) struct SubdiagnosticDerive { diff --git a/compiler/rustc_macros/src/diagnostics/utils.rs b/compiler/rustc_macros/src/diagnostics/utils.rs index 05a5a32514bb7..0d3b2f52fa2af 100644 --- a/compiler/rustc_macros/src/diagnostics/utils.rs +++ b/compiler/rustc_macros/src/diagnostics/utils.rs @@ -1,20 +1,21 @@ -use crate::diagnostics::error::{ - span_err, throw_invalid_attr, throw_span_err, DiagnosticDeriveError, -}; -use proc_macro::Span; -use proc_macro2::{Ident, TokenStream}; -use quote::{format_ident, quote, ToTokens}; use std::cell::RefCell; use std::collections::{BTreeSet, HashMap}; use std::fmt; use std::str::FromStr; + +use proc_macro::Span; +use proc_macro2::{Ident, TokenStream}; +use quote::{format_ident, quote, ToTokens}; use syn::meta::ParseNestedMeta; use syn::punctuated::Punctuated; -use syn::{parenthesized, LitStr, Path, Token}; -use syn::{spanned::Spanned, Attribute, Field, Meta, Type, TypeTuple}; +use syn::spanned::Spanned; +use syn::{parenthesized, Attribute, Field, LitStr, Meta, Path, Token, Type, TypeTuple}; use synstructure::{BindingInfo, VariantInfo}; use super::error::invalid_attr; +use crate::diagnostics::error::{ + span_err, throw_invalid_attr, throw_span_err, DiagnosticDeriveError, +}; thread_local! { pub(crate) static CODE_IDENT_COUNT: RefCell = RefCell::new(0); diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs index 9d7418cd370af..c59f86b0a9bbe 100644 --- a/compiler/rustc_macros/src/lib.rs +++ b/compiler/rustc_macros/src/lib.rs @@ -10,9 +10,8 @@ #![feature(proc_macro_tracked_env)] // tidy-alphabetical-end -use synstructure::decl_derive; - use proc_macro::TokenStream; +use synstructure::decl_derive; mod current_version; mod diagnostics; diff --git a/compiler/rustc_macros/src/symbols.rs b/compiler/rustc_macros/src/symbols.rs index 488d4504a2d11..6074c93d59c5d 100644 --- a/compiler/rustc_macros/src/symbols.rs +++ b/compiler/rustc_macros/src/symbols.rs @@ -24,11 +24,13 @@ //! CFG_RELEASE="0.0.0" cargo +nightly expand > /tmp/rustc_span.rs //! ``` +use std::collections::HashMap; + use proc_macro2::{Span, TokenStream}; use quote::quote; -use std::collections::HashMap; use syn::parse::{Parse, ParseStream, Result}; -use syn::{braced, punctuated::Punctuated, Expr, Ident, Lit, LitStr, Macro, Token}; +use syn::punctuated::Punctuated; +use syn::{braced, Expr, Ident, Lit, LitStr, Macro, Token}; #[cfg(test)] mod tests; diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 749495bc2ef53..2fca443ffa035 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -1,9 +1,13 @@ //! Validates all used crates and extern libraries and loads their metadata -use crate::errors; -use crate::locator::{CrateError, CrateLocator, CratePaths}; -use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob}; +use std::error::Error; +use std::ops::Fn; +use std::path::Path; +use std::str::FromStr; +use std::time::Duration; +use std::{cmp, env, iter}; +use proc_macro::bridge::client::ProcMacro; use rustc_ast::expand::allocator::{alloc_error_handler_name, global_fn_name, AllocatorKind}; use rustc_ast::{self as ast, *}; use rustc_data_structures::fx::FxHashSet; @@ -29,13 +33,9 @@ use rustc_span::{Span, DUMMY_SP}; use rustc_target::spec::{PanicStrategy, Target, TargetTriple}; use tracing::{debug, info, trace}; -use proc_macro::bridge::client::ProcMacro; -use std::error::Error; -use std::ops::Fn; -use std::path::Path; -use std::str::FromStr; -use std::time::Duration; -use std::{cmp, env, iter}; +use crate::errors; +use crate::locator::{CrateError, CrateLocator, CratePaths}; +use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob}; /// The backend's way to give the crate store access to the metadata in a library. /// Note that it returns the raw metadata bytes stored in the library file, whether diff --git a/compiler/rustc_metadata/src/dependency_format.rs b/compiler/rustc_metadata/src/dependency_format.rs index 9c69ab2344e5e..17fd260fd794a 100644 --- a/compiler/rustc_metadata/src/dependency_format.rs +++ b/compiler/rustc_metadata/src/dependency_format.rs @@ -51,12 +51,6 @@ //! Additionally, the algorithm is geared towards finding *any* solution rather //! than finding a number of solutions (there are normally quite a few). -use crate::creader::CStore; -use crate::errors::{ - BadPanicStrategy, CrateDepMultiple, IncompatiblePanicInDropStrategy, LibRequired, - NonStaticCrateDep, RequiredPanicStrategy, RlibRequired, RustcLibRequired, TwoPanicRuntimes, -}; - use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::CrateNum; use rustc_middle::bug; @@ -67,6 +61,12 @@ use rustc_session::cstore::CrateDepKind; use rustc_session::cstore::LinkagePreference::{self, RequireDynamic, RequireStatic}; use tracing::info; +use crate::creader::CStore; +use crate::errors::{ + BadPanicStrategy, CrateDepMultiple, IncompatiblePanicInDropStrategy, LibRequired, + NonStaticCrateDep, RequiredPanicStrategy, RlibRequired, RustcLibRequired, TwoPanicRuntimes, +}; + pub(crate) fn calculate(tcx: TyCtxt<'_>) -> Dependencies { tcx.crate_types() .iter() diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index b0d82a0e3b7c9..89970dddf9fd4 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -1,9 +1,8 @@ -use std::{ - io::Error, - path::{Path, PathBuf}, -}; +use std::io::Error; +use std::path::{Path, PathBuf}; -use rustc_errors::{codes::*, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level}; +use rustc_errors::codes::*; +use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level}; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{sym, Span, Symbol}; use rustc_target::spec::{PanicStrategy, TargetTriple}; diff --git a/compiler/rustc_metadata/src/fs.rs b/compiler/rustc_metadata/src/fs.rs index a0abda53eb3e7..b2a979ed6d832 100644 --- a/compiler/rustc_metadata/src/fs.rs +++ b/compiler/rustc_metadata/src/fs.rs @@ -1,8 +1,5 @@ -use crate::errors::{ - BinaryOutputToTty, FailedCopyToStdout, FailedCreateEncodedMetadata, FailedCreateFile, - FailedCreateTempdir, FailedWriteError, -}; -use crate::{encode_metadata, EncodedMetadata}; +use std::path::{Path, PathBuf}; +use std::{fs, io}; use rustc_data_structures::temp_dir::MaybeTempDir; use rustc_middle::ty::TyCtxt; @@ -11,8 +8,11 @@ use rustc_session::output::filename_for_metadata; use rustc_session::{MetadataKind, Session}; use tempfile::Builder as TempFileBuilder; -use std::path::{Path, PathBuf}; -use std::{fs, io}; +use crate::errors::{ + BinaryOutputToTty, FailedCopyToStdout, FailedCreateEncodedMetadata, FailedCreateFile, + FailedCreateTempdir, FailedWriteError, +}; +use crate::{encode_metadata, EncodedMetadata}; // FIXME(eddyb) maybe include the crate name in this? pub const METADATA_FILENAME: &str = "lib.rmeta"; diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index 90fe52a34385a..25ae7b2bc3130 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -212,9 +212,11 @@ //! no means all of the necessary details. Take a look at the rest of //! metadata::locator or metadata::creader for all the juicy details! -use crate::creader::{Library, MetadataLoader}; -use crate::errors; -use crate::rmeta::{rustc_version, MetadataBlob, METADATA_HEADER}; +use std::borrow::Cow; +use std::io::{Read, Result as IoResult, Write}; +use std::ops::Deref; +use std::path::{Path, PathBuf}; +use std::{cmp, fmt}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::memmap::Mmap; @@ -230,14 +232,12 @@ use rustc_session::Session; use rustc_span::symbol::Symbol; use rustc_span::Span; use rustc_target::spec::{Target, TargetTriple}; +use snap::read::FrameDecoder; use tracing::{debug, info}; -use snap::read::FrameDecoder; -use std::borrow::Cow; -use std::io::{Read, Result as IoResult, Write}; -use std::ops::Deref; -use std::path::{Path, PathBuf}; -use std::{cmp, fmt}; +use crate::creader::{Library, MetadataLoader}; +use crate::errors; +use crate::rmeta::{rustc_version, MetadataBlob, METADATA_HEADER}; #[derive(Clone)] pub(crate) struct CrateLocator<'a> { diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index 1254ebead0727..b19493d12ff33 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -1,3 +1,5 @@ +use std::path::PathBuf; + use rustc_ast::{NestedMetaItem, CRATE_NODE_ID}; use rustc_attr as attr; use rustc_data_structures::fx::FxHashSet; @@ -17,8 +19,6 @@ use rustc_target::spec::abi::Abi; use crate::errors; -use std::path::PathBuf; - pub fn find_native_static_library(name: &str, verbatim: bool, sess: &Session) -> PathBuf { let formats = if verbatim { vec![("".into(), "".into())] diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index e5e430bc90dcd..8c0ea3eaea913 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -1,9 +1,11 @@ // Decoding metadata from a single crate's metadata -use crate::creader::CStore; -use crate::rmeta::table::IsDefault; -use crate::rmeta::*; +use std::iter::TrustedLen; +use std::path::Path; +use std::{io, iter, mem}; +pub(super) use cstore_impl::provide; +use proc_macro::bridge::client::ProcMacro; use rustc_ast as ast; use rustc_data_structures::captures::Captures; use rustc_data_structures::fingerprint::Fingerprint; @@ -27,17 +29,14 @@ use rustc_serialize::opaque::MemDecoder; use rustc_serialize::{Decodable, Decoder}; use rustc_session::cstore::{CrateSource, ExternCrate}; use rustc_session::Session; +use rustc_span::hygiene::HygieneDecodeContext; use rustc_span::symbol::kw; use rustc_span::{BytePos, Pos, SpanData, SpanDecoder, SyntaxContext, DUMMY_SP}; use tracing::debug; -use proc_macro::bridge::client::ProcMacro; -use std::iter::TrustedLen; -use std::path::Path; -use std::{io, iter, mem}; - -pub(super) use cstore_impl::provide; -use rustc_span::hygiene::HygieneDecodeContext; +use crate::creader::CStore; +use crate::rmeta::table::IsDefault; +use crate::rmeta::*; mod cstore_impl; @@ -1728,7 +1727,6 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { source_len, lines, multibyte_chars, - non_narrow_chars, normalized_pos, stable_id, .. @@ -1780,7 +1778,6 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { self.cnum, lines, multibyte_chars, - non_narrow_chars, normalized_pos, source_file_index, ); diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index bbd9ab5704fd8..46039f6e5f67c 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -1,8 +1,5 @@ -use crate::creader::{CStore, LoadedMacro}; -use crate::foreign_modules; -use crate::native_libs; -use crate::rmeta::table::IsDefault; -use crate::rmeta::AttrFlags; +use std::any::Any; +use std::mem; use rustc_ast as ast; use rustc_attr::Deprecation; @@ -15,8 +12,7 @@ use rustc_middle::bug; use rustc_middle::metadata::ModChild; use rustc_middle::middle::exported_symbols::ExportedSymbol; use rustc_middle::middle::stability::DeprecationEntry; -use rustc_middle::query::ExternProviders; -use rustc_middle::query::LocalCrate; +use rustc_middle::query::{ExternProviders, LocalCrate}; use rustc_middle::ty::fast_reject::SimplifiedType; use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::util::Providers; @@ -26,10 +22,11 @@ use rustc_span::hygiene::ExpnId; use rustc_span::symbol::{kw, Symbol}; use rustc_span::Span; -use std::any::Any; -use std::mem; - use super::{Decodable, DecodeContext, DecodeIterator}; +use crate::creader::{CStore, LoadedMacro}; +use crate::rmeta::table::IsDefault; +use crate::rmeta::AttrFlags; +use crate::{foreign_modules, native_libs}; trait ProcessQueryValue<'tcx, T> { fn process_decoded(self, _tcx: TyCtxt<'tcx>, _err: impl Fn() -> !) -> T; diff --git a/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs b/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs index 861bf6b2769e9..01fbf37788f9c 100644 --- a/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs +++ b/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs @@ -1,11 +1,11 @@ -use crate::rmeta::DecodeContext; -use crate::rmeta::EncodeContext; use rustc_data_structures::owned_slice::OwnedSlice; use rustc_hir::def_path_hash_map::{Config as HashMapConfig, DefPathHashMap}; use rustc_middle::parameterized_over_tcx; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_span::def_id::{DefIndex, DefPathHash}; +use crate::rmeta::{DecodeContext, EncodeContext}; + pub(crate) enum DefPathHashMapRef<'tcx> { OwnedFromMetadata(odht::HashTable), BorrowedFromTcx(&'tcx DefPathHashMap), diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 6f31c0fa52027..0d83f8c6c5c93 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1,5 +1,8 @@ -use crate::errors::{FailCreateFileEncoder, FailWriteFile}; -use crate::rmeta::*; +use std::borrow::Borrow; +use std::collections::hash_map::Entry; +use std::fs::File; +use std::io::{Read, Seek, Write}; +use std::path::{Path, PathBuf}; use rustc_ast::Attribute; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; @@ -27,13 +30,11 @@ use rustc_span::symbol::sym; use rustc_span::{ ExternalSource, FileName, SourceFile, SpanData, SpanEncoder, StableSourceFileId, SyntaxContext, }; -use std::borrow::Borrow; -use std::collections::hash_map::Entry; -use std::fs::File; -use std::io::{Read, Seek, Write}; -use std::path::{Path, PathBuf}; use tracing::{debug, instrument, trace}; +use crate::errors::{FailCreateFileEncoder, FailWriteFile}; +use crate::rmeta::*; + pub(super) struct EncodeContext<'a, 'tcx> { opaque: opaque::FileEncoder, tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index e565c8c1ea1c9..c1b77172983fb 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -1,35 +1,35 @@ -use crate::creader::CrateMetadataRef; +use std::marker::PhantomData; +use std::num::NonZero; + pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob}; use decoder::{DecodeContext, Metadata}; use def_path_hash_map::DefPathHashMapRef; use encoder::EncodeContext; pub use encoder::{encode_metadata, rendered_const, EncodedMetadata}; -use rustc_ast as ast; use rustc_ast::expand::StrippedCfgItem; -use rustc_attr as attr; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::svh::Svh; -use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, DocLinkResMap}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIndex, DefPathHash, StableCrateId}; use rustc_hir::definitions::DefKey; use rustc_hir::lang_items::LangItem; use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; -use rustc_macros::{Decodable, Encodable, TyDecodable, TyEncodable}; -use rustc_macros::{MetadataDecodable, MetadataEncodable}; +use rustc_macros::{ + Decodable, Encodable, MetadataDecodable, MetadataEncodable, TyDecodable, TyEncodable, +}; use rustc_middle::metadata::ModChild; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile; use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo}; use rustc_middle::middle::lib_features::FeatureStability; use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault; -use rustc_middle::mir; -use rustc_middle::trivially_parameterized_over_tcx; use rustc_middle::ty::fast_reject::SimplifiedType; -use rustc_middle::ty::{self, ReprOptions, Ty, UnusedGenericParams}; -use rustc_middle::ty::{DeducedParamAttrs, ParameterizedOverTcx, TyCtxt}; +use rustc_middle::ty::{ + self, DeducedParamAttrs, ParameterizedOverTcx, ReprOptions, Ty, TyCtxt, UnusedGenericParams, +}; use rustc_middle::util::Providers; +use rustc_middle::{mir, trivially_parameterized_over_tcx}; use rustc_serialize::opaque::FileEncoder; use rustc_session::config::SymbolManglingVersion; use rustc_session::cstore::{CrateDepKind, ForeignModule, LinkagePreference, NativeLib}; @@ -39,9 +39,10 @@ use rustc_span::symbol::{Ident, Symbol}; use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Span}; use rustc_target::abi::{FieldIdx, VariantIdx}; use rustc_target::spec::{PanicStrategy, TargetTriple}; -use std::marker::PhantomData; -use std::num::NonZero; use table::TableBuilder; +use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; + +use crate::creader::CrateMetadataRef; mod decoder; mod def_path_hash_map; diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs index dcbddad2dbcad..617372a97b5b2 100644 --- a/compiler/rustc_metadata/src/rmeta/table.rs +++ b/compiler/rustc_metadata/src/rmeta/table.rs @@ -1,9 +1,9 @@ -use crate::rmeta::*; - use rustc_hir::def::CtorOf; use rustc_index::Idx; use tracing::trace; +use crate::rmeta::*; + pub(super) trait IsDefault: Default { fn is_default(&self) -> bool; } diff --git a/compiler/rustc_middle/Cargo.toml b/compiler/rustc_middle/Cargo.toml index 290ebde871282..69e3b703ccee1 100644 --- a/compiler/rustc_middle/Cargo.toml +++ b/compiler/rustc_middle/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start bitflags = "2.4.1" -derivative = "2.2.0" +derive-where = "1.2.7" either = "1.5.0" field-offset = "0.3.5" gsgdt = "0.1.2" diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 84b47a6ed447b..9ebe4a57b0297 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -56,18 +56,17 @@ //! //! [dependency graph]: https://rustc-dev-guide.rust-lang.org/query.html -use crate::mir::mono::MonoItem; -use crate::ty::TyCtxt; - use rustc_data_structures::fingerprint::Fingerprint; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalModDefId, ModDefId, LOCAL_CRATE}; use rustc_hir::definitions::DefPathHash; use rustc_hir::{HirId, ItemLocalId, OwnerId}; +pub use rustc_query_system::dep_graph::dep_node::DepKind; use rustc_query_system::dep_graph::FingerprintStyle; +pub use rustc_query_system::dep_graph::{DepContext, DepNode, DepNodeParams}; use rustc_span::symbol::Symbol; -pub use rustc_query_system::dep_graph::dep_node::DepKind; -pub use rustc_query_system::dep_graph::{DepContext, DepNode, DepNodeParams}; +use crate::mir::mono::MonoItem; +use crate::ty::TyCtxt; macro_rules! define_dep_nodes { ( diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index dc0da165af67d..b24954584fe26 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -1,20 +1,19 @@ -use crate::ty::{self, TyCtxt}; use rustc_data_structures::profiling::SelfProfilerRef; use rustc_query_system::ich::StableHashingContext; use rustc_session::Session; +use crate::ty::{self, TyCtxt}; + #[macro_use] mod dep_node; -pub use rustc_query_system::dep_graph::debug::EdgeFilter; -pub use rustc_query_system::dep_graph::{ - debug::DepNodeFilter, hash_result, DepContext, DepGraphQuery, DepNodeIndex, Deps, - SerializedDepGraph, SerializedDepNodeIndex, TaskDepsRef, WorkProduct, WorkProductId, - WorkProductMap, -}; - pub use dep_node::{dep_kinds, label_strs, DepKind, DepNode, DepNodeExt}; pub(crate) use dep_node::{make_compile_codegen_unit, make_compile_mono_item}; +pub use rustc_query_system::dep_graph::debug::{DepNodeFilter, EdgeFilter}; +pub use rustc_query_system::dep_graph::{ + hash_result, DepContext, DepGraphQuery, DepNodeIndex, Deps, SerializedDepGraph, + SerializedDepNodeIndex, TaskDepsRef, WorkProduct, WorkProductId, WorkProductMap, +}; pub type DepGraph = rustc_query_system::dep_graph::DepGraph; diff --git a/compiler/rustc_middle/src/error.rs b/compiler/rustc_middle/src/error.rs index 711db4e0a6bdb..61348cdce2340 100644 --- a/compiler/rustc_middle/src/error.rs +++ b/compiler/rustc_middle/src/error.rs @@ -1,7 +1,8 @@ use std::fmt; use std::path::PathBuf; -use rustc_errors::{codes::*, DiagArgName, DiagArgValue, DiagMessage}; +use rustc_errors::codes::*; +use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage}; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Span, Symbol}; diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index ad59bfa904729..4c243e6330b91 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -1,8 +1,3 @@ -use crate::hir::ModuleItems; -use crate::middle::debugger_visualizer::DebuggerVisualizerFile; -use crate::query::LocalCrate; -use crate::ty::TyCtxt; -use rustc_ast as ast; use rustc_ast::visit::{walk_list, VisitorResult}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; @@ -13,12 +8,17 @@ use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId, LOCAL_CRATE}; use rustc_hir::definitions::{DefKey, DefPath, DefPathHash}; use rustc_hir::intravisit::Visitor; use rustc_hir::*; -use rustc_hir_pretty as pprust_hir; use rustc_middle::hir::nested_filter; use rustc_span::def_id::StableCrateId; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{ErrorGuaranteed, Span}; use rustc_target::spec::abi::Abi; +use {rustc_ast as ast, rustc_hir_pretty as pprust_hir}; + +use crate::hir::ModuleItems; +use crate::middle::debugger_visualizer::DebuggerVisualizerFile; +use crate::query::LocalCrate; +use crate::ty::TyCtxt; // FIXME: the structure was necessary in the past but now it // only serves as "namespace" for HIR-related methods, and can be @@ -746,6 +746,10 @@ impl<'hir> Map<'hir> { } } + pub fn opt_delegation_sig_id(self, def_id: LocalDefId) -> Option { + self.tcx.opt_hir_owner_node(def_id)?.fn_decl()?.opt_delegation_sig_id() + } + #[inline] fn opt_ident(self, id: HirId) -> Option { match self.tcx.hir_node(id) { diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 57c8ba96a20a7..fa521ab9f2fa9 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -6,8 +6,6 @@ pub mod map; pub mod nested_filter; pub mod place; -use crate::query::Providers; -use crate::ty::{EarlyBinder, ImplSubject, TyCtxt}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; @@ -18,6 +16,9 @@ use rustc_hir::*; use rustc_macros::{Decodable, Encodable, HashStable}; use rustc_span::{ErrorGuaranteed, ExpnId}; +use crate::query::Providers; +use crate::ty::{EarlyBinder, ImplSubject, TyCtxt}; + /// Gather the LocalDefId for each item-like within a module, including items contained within /// bodies. The Ids are in visitor order. This is used to partition a pass between modules. #[derive(Debug, HashStable, Encodable, Decodable)] diff --git a/compiler/rustc_middle/src/hir/place.rs b/compiler/rustc_middle/src/hir/place.rs index 1ac35314ead2f..4c7af0bc3726d 100644 --- a/compiler/rustc_middle/src/hir/place.rs +++ b/compiler/rustc_middle/src/hir/place.rs @@ -1,10 +1,10 @@ -use crate::ty; -use crate::ty::Ty; - use rustc_hir::HirId; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; use rustc_target::abi::{FieldIdx, VariantIdx}; +use crate::ty; +use crate::ty::Ty; + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable)] #[derive(TypeFoldable, TypeVisitable)] pub enum PlaceBase { diff --git a/compiler/rustc_middle/src/hooks/mod.rs b/compiler/rustc_middle/src/hooks/mod.rs index 75dc685a16aee..bde05210d9fc5 100644 --- a/compiler/rustc_middle/src/hooks/mod.rs +++ b/compiler/rustc_middle/src/hooks/mod.rs @@ -3,15 +3,16 @@ //! queries come with a lot of machinery for caching and incremental compilation, whereas hooks are //! just plain function pointers without any of the query magic. -use crate::mir; -use crate::query::TyCtxtAt; -use crate::ty::{Ty, TyCtxt}; use rustc_hir::def_id::{DefId, DefPathHash}; use rustc_session::StableCrateId; use rustc_span::def_id::{CrateNum, LocalDefId}; use rustc_span::{ExpnHash, ExpnId, DUMMY_SP}; use tracing::instrument; +use crate::mir; +use crate::query::TyCtxtAt; +use crate::ty::{Ty, TyCtxt}; + macro_rules! declare_hooks { ($($(#[$attr:meta])*hook $name:ident($($arg:ident: $K:ty),*) -> $V:ty;)*) => { diff --git a/compiler/rustc_middle/src/infer/canonical.rs b/compiler/rustc_middle/src/infer/canonical.rs index dba71d88f404b..d431497881919 100644 --- a/compiler/rustc_middle/src/infer/canonical.rs +++ b/compiler/rustc_middle/src/infer/canonical.rs @@ -21,18 +21,18 @@ //! //! [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html +use std::collections::hash_map::Entry; + use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lock; use rustc_macros::{HashStable, TypeFoldable, TypeVisitable}; pub use rustc_type_ir as ir; pub use rustc_type_ir::{CanonicalTyVarKind, CanonicalVarKind}; use smallvec::SmallVec; -use std::collections::hash_map::Entry; use crate::infer::MemberConstraint; use crate::mir::ConstraintCategory; -use crate::ty::GenericArg; -use crate::ty::{self, List, Ty, TyCtxt, TypeFlags, TypeVisitableExt}; +use crate::ty::{self, GenericArg, List, Ty, TyCtxt, TypeFlags, TypeVisitableExt}; pub type Canonical<'tcx, V> = ir::Canonical, V>; pub type CanonicalVarInfo<'tcx> = ir::CanonicalVarInfo>; diff --git a/compiler/rustc_middle/src/infer/mod.rs b/compiler/rustc_middle/src/infer/mod.rs index f74f71b6b378a..19fe9e5a54f53 100644 --- a/compiler/rustc_middle/src/infer/mod.rs +++ b/compiler/rustc_middle/src/infer/mod.rs @@ -1,12 +1,12 @@ pub mod canonical; pub mod unify_key; -use crate::ty::Region; -use crate::ty::{OpaqueTypeKey, Ty}; use rustc_data_structures::sync::Lrc; use rustc_macros::{HashStable, TypeFoldable, TypeVisitable}; use rustc_span::Span; +use crate::ty::{OpaqueTypeKey, Region, Ty}; + /// Requires that `region` must be equal to one of the regions in `choice_regions`. /// We often denote this using the syntax: /// diff --git a/compiler/rustc_middle/src/infer/unify_key.rs b/compiler/rustc_middle/src/infer/unify_key.rs index a5da7e7739e42..3fd4aba31696e 100644 --- a/compiler/rustc_middle/src/infer/unify_key.rs +++ b/compiler/rustc_middle/src/infer/unify_key.rs @@ -1,9 +1,11 @@ -use crate::ty::{self, Ty, TyCtxt}; +use std::cmp; +use std::marker::PhantomData; + use rustc_data_structures::unify::{NoError, UnifyKey, UnifyValue}; use rustc_span::def_id::DefId; use rustc_span::Span; -use std::cmp; -use std::marker::PhantomData; + +use crate::ty::{self, Ty, TyCtxt}; pub trait ToType { fn to_type<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>; diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index 4e655ca2027f2..6a9e67f74dac7 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -5,10 +5,8 @@ use rustc_data_structures::sorted_map::SortedMap; use rustc_errors::{Diag, MultiSpan}; use rustc_hir::{HirId, ItemLocalId}; use rustc_macros::HashStable; -use rustc_session::lint::{ - builtin::{self, FORBIDDEN_LINT_GROUPS}, - FutureIncompatibilityReason, Level, Lint, LintId, -}; +use rustc_session::lint::builtin::{self, FORBIDDEN_LINT_GROUPS}; +use rustc_session::lint::{FutureIncompatibilityReason, Level, Lint, LintId}; use rustc_session::Session; use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::{symbol, DesugaringKind, Span, Symbol, DUMMY_SP}; diff --git a/compiler/rustc_middle/src/metadata.rs b/compiler/rustc_middle/src/metadata.rs index 589f274eb1766..c3175c6bdf513 100644 --- a/compiler/rustc_middle/src/metadata.rs +++ b/compiler/rustc_middle/src/metadata.rs @@ -1,11 +1,11 @@ -use crate::ty; - use rustc_hir::def::Res; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_span::def_id::DefId; use rustc_span::symbol::Ident; use smallvec::SmallVec; +use crate::ty; + /// A simplified version of `ImportKind` from resolve. /// `DefId`s here correspond to `use` and `extern crate` items themselves, not their targets. #[derive(Clone, Copy, Debug, TyEncodable, TyDecodable, HashStable)] diff --git a/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs b/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs index 3ddf889b63afe..ff6a3a9c12d36 100644 --- a/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs +++ b/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs @@ -1,10 +1,11 @@ -use crate::mir::mono::Linkage; use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr}; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_span::symbol::Symbol; use rustc_target::abi::Align; use rustc_target::spec::SanitizerSet; +use crate::mir::mono::Linkage; + #[derive(Clone, TyEncodable, TyDecodable, HashStable, Debug)] pub struct CodegenFnAttrs { pub flags: CodegenFnAttrFlags, diff --git a/compiler/rustc_middle/src/middle/debugger_visualizer.rs b/compiler/rustc_middle/src/middle/debugger_visualizer.rs index 74a5dfb040099..615a7402139e1 100644 --- a/compiler/rustc_middle/src/middle/debugger_visualizer.rs +++ b/compiler/rustc_middle/src/middle/debugger_visualizer.rs @@ -1,6 +1,7 @@ +use std::path::PathBuf; + use rustc_data_structures::sync::Lrc; use rustc_macros::{Decodable, Encodable, HashStable}; -use std::path::PathBuf; #[derive(HashStable)] #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug, Encodable, Decodable)] diff --git a/compiler/rustc_middle/src/middle/exported_symbols.rs b/compiler/rustc_middle/src/middle/exported_symbols.rs index b35cc83cb8e80..0bfbd39879747 100644 --- a/compiler/rustc_middle/src/middle/exported_symbols.rs +++ b/compiler/rustc_middle/src/middle/exported_symbols.rs @@ -1,8 +1,8 @@ -use crate::ty::GenericArgsRef; -use crate::ty::{self, Ty, TyCtxt}; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_macros::{Decodable, Encodable, HashStable, TyDecodable, TyEncodable}; +use crate::ty::{self, GenericArgsRef, Ty, TyCtxt}; + /// The SymbolExportLevel of a symbols specifies from which kinds of crates /// the symbol will be exported. `C` symbols will be exported from any /// kind of crate, including cdylibs which export very few things. diff --git a/compiler/rustc_middle/src/middle/lang_items.rs b/compiler/rustc_middle/src/middle/lang_items.rs index a0c9af436e207..f141af4490057 100644 --- a/compiler/rustc_middle/src/middle/lang_items.rs +++ b/compiler/rustc_middle/src/middle/lang_items.rs @@ -7,13 +7,13 @@ //! * Traits that represent operators; e.g., `Add`, `Sub`, `Index`. //! * Functions called by the compiler itself. -use crate::ty::{self, TyCtxt}; - use rustc_hir::def_id::DefId; use rustc_hir::LangItem; use rustc_span::Span; use rustc_target::spec::PanicStrategy; +use crate::ty::{self, TyCtxt}; + impl<'tcx> TyCtxt<'tcx> { /// Returns the `DefId` for a given `LangItem`. /// If not found, fatally aborts compilation. diff --git a/compiler/rustc_middle/src/middle/limits.rs b/compiler/rustc_middle/src/middle/limits.rs index d0b4f36a426fd..70810f51a1f34 100644 --- a/compiler/rustc_middle/src/middle/limits.rs +++ b/compiler/rustc_middle/src/middle/limits.rs @@ -8,14 +8,14 @@ //! this via an attribute on the crate like `#![recursion_limit="22"]`. This pass //! just peeks and looks for that attribute. -use crate::error::LimitInvalid; -use crate::query::Providers; +use std::num::IntErrorKind; + use rustc_ast::Attribute; -use rustc_session::Session; -use rustc_session::{Limit, Limits}; +use rustc_session::{Limit, Limits, Session}; use rustc_span::symbol::{sym, Symbol}; -use std::num::IntErrorKind; +use crate::error::LimitInvalid; +use crate::query::Providers; pub fn provide(providers: &mut Providers) { providers.limits = |tcx, ()| Limits { diff --git a/compiler/rustc_middle/src/middle/mod.rs b/compiler/rustc_middle/src/middle/mod.rs index 5c395afadd7f0..0c4f37ab14f79 100644 --- a/compiler/rustc_middle/src/middle/mod.rs +++ b/compiler/rustc_middle/src/middle/mod.rs @@ -6,7 +6,8 @@ pub mod lang_items; pub mod lib_features { use rustc_data_structures::unord::UnordMap; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; - use rustc_span::{symbol::Symbol, Span}; + use rustc_span::symbol::Symbol; + use rustc_span::Span; #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(HashStable, TyEncodable, TyDecodable)] diff --git a/compiler/rustc_middle/src/middle/privacy.rs b/compiler/rustc_middle/src/middle/privacy.rs index 4b47b019fd4b0..db70f53b7b498 100644 --- a/compiler/rustc_middle/src/middle/privacy.rs +++ b/compiler/rustc_middle/src/middle/privacy.rs @@ -2,14 +2,16 @@ //! outside their scopes. This pass will also generate a set of exported items //! which are available for use externally when compiled as a library. -use crate::ty::{TyCtxt, Visibility}; +use std::hash::Hash; + use rustc_data_structures::fx::{FxIndexMap, IndexEntry}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_hir::def::DefKind; use rustc_macros::HashStable; use rustc_query_system::ich::StableHashingContext; use rustc_span::def_id::{LocalDefId, CRATE_DEF_ID}; -use std::hash::Hash; + +use crate::ty::{TyCtxt, Visibility}; /// Represents the levels of effective visibility an item can have. /// diff --git a/compiler/rustc_middle/src/middle/region.rs b/compiler/rustc_middle/src/middle/region.rs index 6e89dc494fa56..6ef1801717c81 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -6,7 +6,9 @@ //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/borrow_check.html -use crate::ty::TyCtxt; +use std::fmt; +use std::ops::Deref; + use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::unord::UnordMap; use rustc_hir as hir; @@ -15,8 +17,7 @@ use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_span::{Span, DUMMY_SP}; use tracing::debug; -use std::fmt; -use std::ops::Deref; +use crate::ty::TyCtxt; /// Represents a statically-describable scope that can be used to /// bound the lifetime/region for values. diff --git a/compiler/rustc_middle/src/middle/resolve_bound_vars.rs b/compiler/rustc_middle/src/middle/resolve_bound_vars.rs index d0103f622313b..a4f6d7afe4d11 100644 --- a/compiler/rustc_middle/src/middle/resolve_bound_vars.rs +++ b/compiler/rustc_middle/src/middle/resolve_bound_vars.rs @@ -1,13 +1,13 @@ //! Name resolution for lifetimes and late-bound type and const variables: type declarations. -use crate::ty; - use rustc_data_structures::fx::FxIndexMap; use rustc_errors::ErrorGuaranteed; use rustc_hir::def_id::DefId; use rustc_hir::{ItemLocalId, OwnerId}; use rustc_macros::{Decodable, Encodable, HashStable, TyDecodable, TyEncodable}; +use crate::ty; + #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, HashStable)] pub enum ResolvedArg { StaticLifetime, diff --git a/compiler/rustc_middle/src/middle/stability.rs b/compiler/rustc_middle/src/middle/stability.rs index b113e81bd2d79..3b8861378e08e 100644 --- a/compiler/rustc_middle/src/middle/stability.rs +++ b/compiler/rustc_middle/src/middle/stability.rs @@ -1,9 +1,8 @@ //! A pass that annotates every item and method with its stability level, //! propagating default levels lexically from parent to children ast nodes. -pub use self::StabilityLevel::*; +use std::num::NonZero; -use crate::ty::{self, TyCtxt}; use rustc_ast::NodeId; use rustc_attr::{ self as attr, ConstStability, DefaultBodyStability, DeprecatedSince, Deprecation, Stability, @@ -22,9 +21,11 @@ use rustc_session::parse::feature_err_issue; use rustc_session::Session; use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; -use std::num::NonZero; use tracing::debug; +pub use self::StabilityLevel::*; +use crate::ty::{self, TyCtxt}; + #[derive(PartialEq, Clone, Copy, Debug)] pub enum StabilityLevel { Unstable, diff --git a/compiler/rustc_middle/src/mir/basic_blocks.rs b/compiler/rustc_middle/src/mir/basic_blocks.rs index f9398b254c7b1..c08bfc1fa95f4 100644 --- a/compiler/rustc_middle/src/mir/basic_blocks.rs +++ b/compiler/rustc_middle/src/mir/basic_blocks.rs @@ -1,6 +1,3 @@ -use crate::mir::traversal::Postorder; -use crate::mir::{BasicBlock, BasicBlockData, Terminator, TerminatorKind, START_BLOCK}; - use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::graph; use rustc_data_structures::graph::dominators::{dominators, Dominators}; @@ -11,6 +8,9 @@ use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisit use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use smallvec::SmallVec; +use crate::mir::traversal::Postorder; +use crate::mir::{BasicBlock, BasicBlockData, Terminator, TerminatorKind, START_BLOCK}; + #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)] pub struct BasicBlocks<'tcx> { basic_blocks: IndexVec>, diff --git a/compiler/rustc_middle/src/mir/consts.rs b/compiler/rustc_middle/src/mir/consts.rs index 89f5acacf9d11..563647ad4e678 100644 --- a/compiler/rustc_middle/src/mir/consts.rs +++ b/compiler/rustc_middle/src/mir/consts.rs @@ -2,16 +2,15 @@ use std::fmt::{self, Debug, Display, Formatter}; use rustc_hir::def_id::DefId; use rustc_macros::{HashStable, Lift, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; -use rustc_session::{config::RemapPathScopeComponents, RemapFileNameExt}; +use rustc_session::config::RemapPathScopeComponents; +use rustc_session::RemapFileNameExt; use rustc_span::{Span, DUMMY_SP}; use rustc_target::abi::{HasDataLayout, Size}; use crate::mir::interpret::{alloc_range, AllocId, ConstAllocation, ErrorHandled, Scalar}; use crate::mir::{pretty_print_const_value, Promoted}; -use crate::ty::print::with_no_trimmed_paths; -use crate::ty::GenericArgsRef; -use crate::ty::ScalarInt; -use crate::ty::{self, print::pretty_print_const, Ty, TyCtxt}; +use crate::ty::print::{pretty_print_const, with_no_trimmed_paths}; +use crate::ty::{self, GenericArgsRef, ScalarInt, Ty, TyCtxt}; /////////////////////////////////////////////////////////////////////////// /// Evaluated Constants diff --git a/compiler/rustc_middle/src/mir/coverage.rs b/compiler/rustc_middle/src/mir/coverage.rs index 2a593340849ef..b11c523cfe964 100644 --- a/compiler/rustc_middle/src/mir/coverage.rs +++ b/compiler/rustc_middle/src/mir/coverage.rs @@ -1,11 +1,11 @@ //! Metadata from source code coverage analysis and instrumentation. +use std::fmt::{self, Debug, Formatter}; + use rustc_index::IndexVec; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; use rustc_span::{Span, Symbol}; -use std::fmt::{self, Debug, Formatter}; - rustc_index::newtype_index! { /// Used by [`CoverageKind::BlockMarker`] to mark blocks during THIR-to-MIR /// lowering, so that those blocks can be identified later. diff --git a/compiler/rustc_middle/src/mir/generic_graphviz.rs b/compiler/rustc_middle/src/mir/generic_graphviz.rs index 809d4cdce8dec..e1c3d8156d83e 100644 --- a/compiler/rustc_middle/src/mir/generic_graphviz.rs +++ b/compiler/rustc_middle/src/mir/generic_graphviz.rs @@ -1,7 +1,8 @@ +use std::io::{self, Write}; + use rustc_data_structures::graph::{self, iterate}; use rustc_graphviz as dot; use rustc_middle::ty::TyCtxt; -use std::io::{self, Write}; pub struct GraphvizWriter< 'a, diff --git a/compiler/rustc_middle/src/mir/graphviz.rs b/compiler/rustc_middle/src/mir/graphviz.rs index 2eadc4d553cc8..a3fe8f9cffa6c 100644 --- a/compiler/rustc_middle/src/mir/graphviz.rs +++ b/compiler/rustc_middle/src/mir/graphviz.rs @@ -1,7 +1,8 @@ +use std::io::{self, Write}; + use gsgdt::GraphvizSettings; use rustc_graphviz as dot; use rustc_middle::mir::*; -use std::io::{self, Write}; use super::generic_graph::mir_fn_to_generic_graph; use super::pretty::dump_mir_def_ids; diff --git a/compiler/rustc_middle/src/mir/interpret/allocation.rs b/compiler/rustc_middle/src/mir/interpret/allocation.rs index cac3bf948a0c1..665ab2797f21f 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation.rs @@ -4,14 +4,14 @@ mod init_mask; mod provenance_map; use std::borrow::Cow; -use std::fmt; -use std::hash; use std::hash::Hash; use std::ops::{Deref, DerefMut, Range}; -use std::ptr; +use std::{fmt, hash, ptr}; use either::{Left, Right}; - +use init_mask::*; +pub use init_mask::{InitChunk, InitChunkIter}; +use provenance_map::*; use rustc_ast::Mutability; use rustc_data_structures::intern::Interned; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; @@ -23,10 +23,6 @@ use super::{ ScalarSizeMismatch, UndefinedBehaviorInfo, UnsupportedOpInfo, }; use crate::ty; -use init_mask::*; -use provenance_map::*; - -pub use init_mask::{InitChunk, InitChunkIter}; /// Functionality required for the bytes of an `Allocation`. pub trait AllocBytes: Clone + fmt::Debug + Deref + DerefMut { diff --git a/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs b/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs index d60db775ff08a..1d2a82c575a34 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs @@ -1,9 +1,8 @@ #[cfg(test)] mod tests; -use std::hash; -use std::iter; use std::ops::Range; +use std::{hash, iter}; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_serialize::{Decodable, Encodable}; diff --git a/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs b/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs index 4e37295a571bd..4fe219441a064 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs @@ -3,13 +3,14 @@ use std::cmp; -use super::{alloc_range, AllocError, AllocRange, AllocResult, CtfeProvenance, Provenance}; use rustc_data_structures::sorted_map::SortedMap; use rustc_macros::HashStable; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_target::abi::{HasDataLayout, Size}; use tracing::trace; +use super::{alloc_range, AllocError, AllocRange, AllocResult, CtfeProvenance, Provenance}; + /// Stores the provenance information of pointers stored in memory. #[derive(Clone, PartialEq, Eq, Hash, Debug)] #[derive(HashStable)] diff --git a/compiler/rustc_middle/src/mir/interpret/error.rs b/compiler/rustc_middle/src/mir/interpret/error.rs index 9df19565ab383..69ce3e087350b 100644 --- a/compiler/rustc_middle/src/mir/interpret/error.rs +++ b/compiler/rustc_middle/src/mir/interpret/error.rs @@ -1,19 +1,19 @@ +use std::any::Any; +use std::backtrace::Backtrace; use std::borrow::Cow; -use std::{any::Any, backtrace::Backtrace, fmt}; +use std::fmt; use either::Either; - use rustc_ast_ir::Mutability; use rustc_data_structures::sync::Lock; use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage, ErrorGuaranteed, IntoDiagArg}; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_session::CtfeBacktrace; -use rustc_span::Symbol; -use rustc_span::{def_id::DefId, Span, DUMMY_SP}; +use rustc_span::def_id::DefId; +use rustc_span::{Span, Symbol, DUMMY_SP}; use rustc_target::abi::{call, Align, Size, VariantIdx, WrappingRange}; use super::{AllocId, AllocRange, ConstAllocation, Pointer, Scalar}; - use crate::error; use crate::mir::{ConstAlloc, ConstValue}; use crate::ty::{self, layout, tls, Ty, TyCtxt, ValTree}; @@ -329,16 +329,22 @@ pub enum UndefinedBehaviorInfo<'tcx> { /// Using a pointer after it got freed. PointerUseAfterFree(AllocId, CheckInAllocMsg), /// Used a pointer outside the bounds it is valid for. - /// (If `ptr_size > 0`, determines the size of the memory range that was expected to be in-bounds.) PointerOutOfBounds { alloc_id: AllocId, alloc_size: Size, ptr_offset: i64, - ptr_size: Size, + /// The size of the memory range that was expected to be in-bounds. + inbounds_size: i64, msg: CheckInAllocMsg, }, /// Using an integer as a pointer in the wrong way. - DanglingIntPointer(u64, CheckInAllocMsg), + DanglingIntPointer { + addr: u64, + /// The size of the memory range that was expected to be in-bounds (or 0 if we need an + /// allocation but not any actual memory there, e.g. for function pointers). + inbounds_size: i64, + msg: CheckInAllocMsg, + }, /// Used a pointer with bad alignment. AlignmentCheckFailed(Misalignment, CheckAlignMsg), /// Writing to read-only memory. diff --git a/compiler/rustc_middle/src/mir/interpret/mod.rs b/compiler/rustc_middle/src/mir/interpret/mod.rs index 15febfa7d9c0c..1851a61d7533c 100644 --- a/compiler/rustc_middle/src/mir/interpret/mod.rs +++ b/compiler/rustc_middle/src/mir/interpret/mod.rs @@ -8,12 +8,9 @@ mod pointer; mod queries; mod value; -use std::fmt; -use std::io; use std::io::{Read, Write}; use std::num::NonZero; - -use tracing::{debug, trace}; +use std::{fmt, io}; use rustc_ast::LitKind; use rustc_attr::InlineAttr; @@ -25,20 +22,7 @@ use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisit use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_serialize::{Decodable, Encodable}; use rustc_target::abi::{AddressSpace, Endian, HasDataLayout}; - -use crate::mir; -use crate::ty::codec::{TyDecoder, TyEncoder}; -use crate::ty::GenericArgKind; -use crate::ty::{self, Instance, Ty, TyCtxt}; - -pub use self::error::{ - BadBytesAccess, CheckAlignMsg, CheckInAllocMsg, ErrorHandled, EvalStaticInitializerRawResult, - EvalToAllocationRawResult, EvalToConstValueResult, EvalToValTreeResult, ExpectedKind, - InterpError, InterpErrorInfo, InterpResult, InvalidMetaKind, InvalidProgramInfo, - MachineStopType, Misalignment, PointerKind, ReportedErrorInfo, ResourceExhaustionInfo, - ScalarSizeMismatch, UndefinedBehaviorInfo, UnsupportedOpInfo, ValidationErrorInfo, - ValidationErrorKind, -}; +use tracing::{debug, trace}; // Also make the error macros available from this module. pub use { err_exhaust, err_inval, err_machine_stop, err_ub, err_ub_custom, err_ub_format, err_unsup, @@ -46,14 +30,23 @@ pub use { throw_ub_format, throw_unsup, throw_unsup_format, }; -pub use self::value::Scalar; - pub use self::allocation::{ alloc_range, AllocBytes, AllocError, AllocRange, AllocResult, Allocation, ConstAllocation, InitChunk, InitChunkIter, }; - +pub use self::error::{ + BadBytesAccess, CheckAlignMsg, CheckInAllocMsg, ErrorHandled, EvalStaticInitializerRawResult, + EvalToAllocationRawResult, EvalToConstValueResult, EvalToValTreeResult, ExpectedKind, + InterpError, InterpErrorInfo, InterpResult, InvalidMetaKind, InvalidProgramInfo, + MachineStopType, Misalignment, PointerKind, ReportedErrorInfo, ResourceExhaustionInfo, + ScalarSizeMismatch, UndefinedBehaviorInfo, UnsupportedOpInfo, ValidationErrorInfo, + ValidationErrorKind, +}; pub use self::pointer::{CtfeProvenance, Pointer, PointerArithmetic, Provenance}; +pub use self::value::Scalar; +use crate::mir; +use crate::ty::codec::{TyDecoder, TyEncoder}; +use crate::ty::{self, GenericArgKind, Instance, Ty, TyCtxt}; /// Uniquely identifies one of the following: /// - A constant diff --git a/compiler/rustc_middle/src/mir/interpret/pointer.rs b/compiler/rustc_middle/src/mir/interpret/pointer.rs index a0acacc844fd5..6cfd07d699c3e 100644 --- a/compiler/rustc_middle/src/mir/interpret/pointer.rs +++ b/compiler/rustc_middle/src/mir/interpret/pointer.rs @@ -1,10 +1,11 @@ -use super::{AllocId, InterpResult}; +use std::fmt; +use std::num::NonZero; use rustc_data_structures::static_assert_size; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_target::abi::{HasDataLayout, Size}; -use std::{fmt, num::NonZero}; +use super::AllocId; //////////////////////////////////////////////////////////////////////////////// // Pointer arithmetic @@ -39,62 +40,13 @@ pub trait PointerArithmetic: HasDataLayout { } #[inline] - fn target_usize_to_isize(&self, val: u64) -> i64 { - let val = val as i64; - // Now wrap-around into the machine_isize range. - if val > self.target_isize_max() { - // This can only happen if the ptr size is < 64, so we know max_usize_plus_1 fits into - // i64. - debug_assert!(self.pointer_size().bits() < 64); - let max_usize_plus_1 = 1u128 << self.pointer_size().bits(); - val - i64::try_from(max_usize_plus_1).unwrap() - } else { - val - } - } - - /// Helper function: truncate given value-"overflowed flag" pair to pointer size and - /// update "overflowed flag" if there was an overflow. - /// This should be called by all the other methods before returning! - #[inline] - fn truncate_to_ptr(&self, (val, over): (u64, bool)) -> (u64, bool) { - let val = u128::from(val); - let max_ptr_plus_1 = 1u128 << self.pointer_size().bits(); - (u64::try_from(val % max_ptr_plus_1).unwrap(), over || val >= max_ptr_plus_1) - } - - #[inline] - fn overflowing_offset(&self, val: u64, i: u64) -> (u64, bool) { - // We do not need to check if i fits in a machine usize. If it doesn't, - // either the wrapping_add will wrap or res will not fit in a pointer. - let res = val.overflowing_add(i); - self.truncate_to_ptr(res) - } - - #[inline] - fn overflowing_signed_offset(&self, val: u64, i: i64) -> (u64, bool) { - // We need to make sure that i fits in a machine isize. - let n = i.unsigned_abs(); - if i >= 0 { - let (val, over) = self.overflowing_offset(val, n); - (val, over || i > self.target_isize_max()) - } else { - let res = val.overflowing_sub(n); - let (val, over) = self.truncate_to_ptr(res); - (val, over || i < self.target_isize_min()) - } - } - - #[inline] - fn offset<'tcx>(&self, val: u64, i: u64) -> InterpResult<'tcx, u64> { - let (res, over) = self.overflowing_offset(val, i); - if over { throw_ub!(PointerArithOverflow) } else { Ok(res) } + fn truncate_to_target_usize(&self, val: u64) -> u64 { + self.pointer_size().truncate(val.into()).try_into().unwrap() } #[inline] - fn signed_offset<'tcx>(&self, val: u64, i: i64) -> InterpResult<'tcx, u64> { - let (res, over) = self.overflowing_signed_offset(val, i); - if over { throw_ub!(PointerArithOverflow) } else { Ok(res) } + fn sign_extend_to_target_isize(&self, val: u64) -> i64 { + self.pointer_size().sign_extend(val.into()).try_into().unwrap() } } @@ -330,7 +282,7 @@ impl Pointer> { } } -impl<'tcx, Prov> Pointer { +impl Pointer { #[inline(always)] pub fn new(provenance: Prov, offset: Size) -> Self { Pointer { provenance, offset } @@ -348,43 +300,16 @@ impl<'tcx, Prov> Pointer { Pointer { provenance: f(self.provenance), ..self } } - #[inline] - pub fn offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> { - Ok(Pointer { - offset: Size::from_bytes(cx.data_layout().offset(self.offset.bytes(), i.bytes())?), - ..self - }) - } - - #[inline] - pub fn overflowing_offset(self, i: Size, cx: &impl HasDataLayout) -> (Self, bool) { - let (res, over) = cx.data_layout().overflowing_offset(self.offset.bytes(), i.bytes()); - let ptr = Pointer { offset: Size::from_bytes(res), ..self }; - (ptr, over) - } - #[inline(always)] pub fn wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self { - self.overflowing_offset(i, cx).0 - } - - #[inline] - pub fn signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> { - Ok(Pointer { - offset: Size::from_bytes(cx.data_layout().signed_offset(self.offset.bytes(), i)?), - ..self - }) - } - - #[inline] - pub fn overflowing_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> (Self, bool) { - let (res, over) = cx.data_layout().overflowing_signed_offset(self.offset.bytes(), i); - let ptr = Pointer { offset: Size::from_bytes(res), ..self }; - (ptr, over) + let res = + cx.data_layout().truncate_to_target_usize(self.offset.bytes().wrapping_add(i.bytes())); + Pointer { offset: Size::from_bytes(res), ..self } } #[inline(always)] pub fn wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self { - self.overflowing_signed_offset(i, cx).0 + // It's wrapping anyway, so we can just cast to `u64`. + self.wrapping_offset(Size::from_bytes(i as u64), cx) } } diff --git a/compiler/rustc_middle/src/mir/interpret/queries.rs b/compiler/rustc_middle/src/mir/interpret/queries.rs index 96613592bbcce..675e78603aebd 100644 --- a/compiler/rustc_middle/src/mir/interpret/queries.rs +++ b/compiler/rustc_middle/src/mir/interpret/queries.rs @@ -1,17 +1,16 @@ +use rustc_hir::def::DefKind; +use rustc_hir::def_id::DefId; +use rustc_session::lint; +use rustc_span::{Span, DUMMY_SP}; +use tracing::{debug, instrument}; + use super::{ ErrorHandled, EvalToAllocationRawResult, EvalToConstValueResult, EvalToValTreeResult, GlobalId, }; - use crate::mir; use crate::query::TyCtxtEnsure; use crate::ty::visit::TypeVisitableExt; -use crate::ty::GenericArgs; -use crate::ty::{self, TyCtxt}; -use rustc_hir::def::DefKind; -use rustc_hir::def_id::DefId; -use rustc_session::lint; -use rustc_span::{Span, DUMMY_SP}; -use tracing::{debug, instrument}; +use crate::ty::{self, GenericArgs, TyCtxt}; impl<'tcx> TyCtxt<'tcx> { /// Evaluates a constant without providing any generic parameters. This is useful to evaluate consts diff --git a/compiler/rustc_middle/src/mir/interpret/value.rs b/compiler/rustc_middle/src/mir/interpret/value.rs index a84a4c583edd2..84c17b39a623e 100644 --- a/compiler/rustc_middle/src/mir/interpret/value.rs +++ b/compiler/rustc_middle/src/mir/interpret/value.rs @@ -1,20 +1,16 @@ use std::fmt; use either::{Either, Left, Right}; - -use rustc_apfloat::{ - ieee::{Double, Half, Quad, Single}, - Float, -}; +use rustc_apfloat::ieee::{Double, Half, Quad, Single}; +use rustc_apfloat::Float; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_target::abi::{HasDataLayout, Size}; -use crate::ty::ScalarInt; - use super::{ AllocId, CtfeProvenance, InterpResult, Pointer, PointerArithmetic, Provenance, ScalarSizeMismatch, }; +use crate::ty::ScalarInt; /// A `Scalar` represents an immediate, primitive value existing outside of a /// `memory::Allocation`. It is in many ways like a small chunk of an `Allocation`, up to 16 bytes in @@ -397,7 +393,7 @@ impl<'tcx, Prov: Provenance> Scalar { #[inline] pub fn to_int(self, size: Size) -> InterpResult<'tcx, i128> { let b = self.to_bits(size)?; - Ok(size.sign_extend(b) as i128) + Ok(size.sign_extend(b)) } /// Converts the scalar to produce an `i8`. Fails if the scalar is a pointer. diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 83e3898cebfa4..46c4d586f6ad9 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -2,53 +2,49 @@ //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/index.html -use crate::mir::interpret::{AllocRange, Scalar}; -use crate::mir::visit::MirVisitable; -use crate::ty::codec::{TyDecoder, TyEncoder}; -use crate::ty::fold::{FallibleTypeFolder, TypeFoldable}; -use crate::ty::print::{pretty_print_const, with_no_trimmed_paths}; -use crate::ty::print::{FmtPrinter, Printer}; -use crate::ty::visit::TypeVisitableExt; -use crate::ty::{self, List, Ty, TyCtxt}; -use crate::ty::{AdtDef, Instance, InstanceKind, UserTypeAnnotationIndex}; -use crate::ty::{GenericArg, GenericArgsRef}; +use std::borrow::Cow; +use std::cell::RefCell; +use std::collections::hash_map::Entry; +use std::fmt::{self, Debug, Formatter}; +use std::ops::{Index, IndexMut}; +use std::{iter, mem}; +pub use basic_blocks::BasicBlocks; +use either::Either; +use polonius_engine::Atom; +pub use rustc_ast::Mutability; use rustc_data_structures::captures::Captures; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_data_structures::graph::dominators::Dominators; use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage, ErrorGuaranteed, IntoDiagArg}; use rustc_hir::def::{CtorKind, Namespace}; use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; use rustc_hir::{ self as hir, BindingMode, ByRef, CoroutineDesugaring, CoroutineKind, HirId, ImplicitSelfKind, }; -use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; -use rustc_session::Session; -use rustc_span::source_map::Spanned; -use rustc_target::abi::{FieldIdx, VariantIdx}; - -use polonius_engine::Atom; -pub use rustc_ast::Mutability; -use rustc_data_structures::fx::FxHashMap; -use rustc_data_structures::fx::FxHashSet; -use rustc_data_structures::graph::dominators::Dominators; use rustc_index::bit_set::BitSet; use rustc_index::{Idx, IndexSlice, IndexVec}; +use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; use rustc_serialize::{Decodable, Encodable}; +use rustc_session::Session; +use rustc_span::source_map::Spanned; use rustc_span::symbol::Symbol; use rustc_span::{Span, DUMMY_SP}; - -use either::Either; +use rustc_target::abi::{FieldIdx, VariantIdx}; use tracing::trace; -use std::borrow::Cow; -use std::cell::RefCell; -use std::collections::hash_map::Entry; -use std::fmt::{self, Debug, Formatter}; -use std::ops::{Index, IndexMut}; -use std::{iter, mem}; - pub use self::query::*; use self::visit::TyContext; -pub use basic_blocks::BasicBlocks; +use crate::mir::interpret::{AllocRange, Scalar}; +use crate::mir::visit::MirVisitable; +use crate::ty::codec::{TyDecoder, TyEncoder}; +use crate::ty::fold::{FallibleTypeFolder, TypeFoldable}; +use crate::ty::print::{pretty_print_const, with_no_trimmed_paths, FmtPrinter, Printer}; +use crate::ty::visit::TypeVisitableExt; +use crate::ty::{ + self, AdtDef, GenericArg, GenericArgsRef, Instance, InstanceKind, List, Ty, TyCtxt, + UserTypeAnnotationIndex, +}; mod basic_blocks; mod consts; @@ -70,17 +66,18 @@ pub mod traversal; mod type_foldable; pub mod visit; -pub use self::generic_graph::graphviz_safe_def_name; -pub use self::graphviz::write_mir_graphviz; -pub use self::pretty::{ - create_dump_file, display_allocation, dump_enabled, dump_mir, write_mir_pretty, PassWhere, -}; pub use consts::*; use pretty::pretty_print_const_value; pub use statement::*; pub use syntax::*; pub use terminator::*; +pub use self::generic_graph::graphviz_safe_def_name; +pub use self::graphviz::write_mir_graphviz; +pub use self::pretty::{ + create_dump_file, display_allocation, dump_enabled, dump_mir, write_mir_pretty, PassWhere, +}; + /// Types for locals pub type LocalDecls<'tcx> = IndexSlice>; @@ -386,15 +383,17 @@ pub struct Body<'tcx> { /// Constants that are required to evaluate successfully for this MIR to be well-formed. /// We hold in this field all the constants we are not able to evaluate yet. + /// `None` indicates that the list has not been computed yet. /// /// This is soundness-critical, we make a guarantee that all consts syntactically mentioned in a /// function have successfully evaluated if the function ever gets executed at runtime. - pub required_consts: Vec>, + pub required_consts: Option>>, /// Further items that were mentioned in this function and hence *may* become monomorphized, /// depending on optimizations. We use this to avoid optimization-dependent compile errors: the /// collector recursively traverses all "mentioned" items and evaluates all their /// `required_consts`. + /// `None` indicates that the list has not been computed yet. /// /// This is *not* soundness-critical and the contents of this list are *not* a stable guarantee. /// All that's relevant is that this set is optimization-level-independent, and that it includes @@ -402,7 +401,7 @@ pub struct Body<'tcx> { /// set after drop elaboration, so some drop calls that can never be reached are not considered /// "mentioned".) See the documentation of `CollectionMode` in /// `compiler/rustc_monomorphize/src/collector.rs` for more context. - pub mentioned_items: Vec>>, + pub mentioned_items: Option>>>, /// Does this body use generic parameters. This is used for the `ConstEvaluatable` check. /// @@ -480,8 +479,8 @@ impl<'tcx> Body<'tcx> { spread_arg: None, var_debug_info, span, - required_consts: Vec::new(), - mentioned_items: Vec::new(), + required_consts: None, + mentioned_items: None, is_polymorphic: false, injection_phase: None, tainted_by_errors, @@ -510,8 +509,8 @@ impl<'tcx> Body<'tcx> { arg_count: 0, spread_arg: None, span: DUMMY_SP, - required_consts: Vec::new(), - mentioned_items: Vec::new(), + required_consts: None, + mentioned_items: None, var_debug_info: Vec::new(), is_polymorphic: false, injection_phase: None, @@ -788,6 +787,40 @@ impl<'tcx> Body<'tcx> { // No inlined `SourceScope`s, or all of them were `#[track_caller]`. caller_location.unwrap_or_else(|| from_span(source_info.span)) } + + #[track_caller] + pub fn set_required_consts(&mut self, required_consts: Vec>) { + assert!( + self.required_consts.is_none(), + "required_consts for {:?} have already been set", + self.source.def_id() + ); + self.required_consts = Some(required_consts); + } + #[track_caller] + pub fn required_consts(&self) -> &[ConstOperand<'tcx>] { + match &self.required_consts { + Some(l) => l, + None => panic!("required_consts for {:?} have not yet been set", self.source.def_id()), + } + } + + #[track_caller] + pub fn set_mentioned_items(&mut self, mentioned_items: Vec>>) { + assert!( + self.mentioned_items.is_none(), + "mentioned_items for {:?} have already been set", + self.source.def_id() + ); + self.mentioned_items = Some(mentioned_items); + } + #[track_caller] + pub fn mentioned_items(&self) -> &[Spanned>] { + match &self.mentioned_items { + Some(l) => l, + None => panic!("mentioned_items for {:?} have not yet been set", self.source.def_id()), + } + } } impl<'tcx> Index for Body<'tcx> { @@ -1815,8 +1848,9 @@ impl DefLocation { // Some nodes are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(BasicBlockData<'_>, 128); static_assert_size!(LocalDecl<'_>, 40); diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index 146cd6dfbeb7e..336a9388a561e 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -1,9 +1,8 @@ -use crate::dep_graph::{DepNode, WorkProduct, WorkProductId}; -use crate::ty::{GenericArgs, Instance, InstanceKind, SymbolName, TyCtxt}; +use std::fmt; +use std::hash::Hash; + use rustc_attr::InlineAttr; -use rustc_data_structures::base_n::BaseNString; -use rustc_data_structures::base_n::ToBaseN; -use rustc_data_structures::base_n::CASE_INSENSITIVE; +use rustc_data_structures::base_n::{BaseNString, ToBaseN, CASE_INSENSITIVE}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher, ToStableHashKey}; @@ -16,10 +15,11 @@ use rustc_query_system::ich::StableHashingContext; use rustc_session::config::OptLevel; use rustc_span::symbol::Symbol; use rustc_span::Span; -use std::fmt; -use std::hash::Hash; use tracing::debug; +use crate::dep_graph::{DepNode, WorkProduct, WorkProductId}; +use crate::ty::{GenericArgs, Instance, InstanceKind, SymbolName, TyCtxt}; + /// Describes how a monomorphization will be instantiated in object files. #[derive(PartialEq)] pub enum InstantiationMode { diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 223249952dc74..f2d8781413096 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -4,9 +4,6 @@ use std::fs; use std::io::{self, Write as _}; use std::path::{Path, PathBuf}; -use crate::mir::interpret::ConstAllocation; - -use super::graphviz::write_mir_fn_graphviz; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_middle::mir::interpret::{ alloc_range, read_target_uint, AllocBytes, AllocId, Allocation, GlobalAlloc, Pointer, @@ -17,6 +14,9 @@ use rustc_middle::mir::*; use rustc_target::abi::Size; use tracing::trace; +use super::graphviz::write_mir_fn_graphviz; +use crate::mir::interpret::ConstAllocation; + const INDENT: &str = " "; /// Alignment for lining up comments following MIR statements pub(crate) const ALIGN: usize = 40; diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index cd8e28522ecfb..a36e49f6ee0fb 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -1,7 +1,9 @@ //! Values computed by queries that use MIR. -use crate::mir; -use crate::ty::{self, CoroutineArgsExt, OpaqueHiddenType, Ty, TyCtxt}; +use std::cell::Cell; +use std::fmt::{self, Debug}; + +use derive_where::derive_where; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::ErrorGuaranteed; use rustc_hir::def_id::LocalDefId; @@ -12,10 +14,10 @@ use rustc_span::symbol::Symbol; use rustc_span::Span; use rustc_target::abi::{FieldIdx, VariantIdx}; use smallvec::SmallVec; -use std::cell::Cell; -use std::fmt::{self, Debug}; use super::{ConstValue, SourceInfo}; +use crate::mir; +use crate::ty::{self, CoroutineArgsExt, OpaqueHiddenType, Ty, TyCtxt}; rustc_index::newtype_index! { #[derive(HashStable)] @@ -224,13 +226,7 @@ rustc_data_structures::static_assert_size!(ConstraintCategory<'_>, 16); /// See also `rustc_const_eval::borrow_check::constraints`. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] #[derive(TyEncodable, TyDecodable, HashStable, TypeVisitable, TypeFoldable)] -#[derive(derivative::Derivative)] -#[derivative( - PartialOrd, - Ord, - PartialOrd = "feature_allow_slow_enum", - Ord = "feature_allow_slow_enum" -)] +#[derive_where(PartialOrd, Ord)] pub enum ConstraintCategory<'tcx> { Return(ReturnConstraint), Yield, @@ -240,7 +236,7 @@ pub enum ConstraintCategory<'tcx> { Cast { /// Whether this is an unsizing cast and if yes, this contains the target type. /// Region variables are erased to ReErased. - #[derivative(PartialOrd = "ignore", Ord = "ignore")] + #[derive_where(skip)] unsize_to: Option>, }, @@ -250,7 +246,7 @@ pub enum ConstraintCategory<'tcx> { ClosureBounds, /// Contains the function type if available. - CallArgument(#[derivative(PartialOrd = "ignore", Ord = "ignore")] Option>), + CallArgument(#[derive_where(skip)] Option>), CopyBound, SizedBound, Assignment, diff --git a/compiler/rustc_middle/src/mir/statement.rs b/compiler/rustc_middle/src/mir/statement.rs index ac3feb71a2b46..3009ca8d8097a 100644 --- a/compiler/rustc_middle/src/mir/statement.rs +++ b/compiler/rustc_middle/src/mir/statement.rs @@ -1,6 +1,7 @@ //! Functionality for statements, operands, places, and things that appear in them. -use super::{interpret::GlobalAlloc, *}; +use super::interpret::GlobalAlloc; +use super::*; /////////////////////////////////////////////////////////////////////////// // Statements diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 620fa962d791f..1119ff6ff3d60 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -3,31 +3,26 @@ //! This is in a dedicated file so that changes to this file can be reviewed more carefully. //! The intention is that this file only contains datatype declarations, no code. -use super::{BasicBlock, Const, Local, UserTypeProjection}; - -use crate::mir::coverage::CoverageKind; -use crate::traits::Reveal; -use crate::ty::adjustment::PointerCoercion; -use crate::ty::GenericArgsRef; -use crate::ty::{self, List, Ty}; -use crate::ty::{Region, UserTypeAnnotationIndex}; - -use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; +use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece, Mutability}; use rustc_data_structures::packed::Pu128; use rustc_hir::def_id::DefId; use rustc_hir::CoroutineKind; use rustc_index::IndexVec; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; -use rustc_span::source_map::Spanned; -use rustc_target::abi::{FieldIdx, VariantIdx}; - -use rustc_ast::Mutability; use rustc_span::def_id::LocalDefId; +use rustc_span::source_map::Spanned; use rustc_span::symbol::Symbol; use rustc_span::Span; +use rustc_target::abi::{FieldIdx, VariantIdx}; use rustc_target::asm::InlineAsmRegOrRegClass; use smallvec::SmallVec; +use super::{BasicBlock, Const, Local, UserTypeProjection}; +use crate::mir::coverage::CoverageKind; +use crate::traits::Reveal; +use crate::ty::adjustment::PointerCoercion; +use crate::ty::{self, GenericArgsRef, List, Region, Ty, UserTypeAnnotationIndex}; + /// Represents the "flavors" of MIR. /// /// All flavors of MIR use the same data structure, but there are some important differences. These @@ -1583,8 +1578,9 @@ pub enum BinOp { // Some nodes are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(AggregateKind<'_>, 32); static_assert_size!(Operand<'_>, 24); diff --git a/compiler/rustc_middle/src/mir/tcx.rs b/compiler/rustc_middle/src/mir/tcx.rs index 412cfc1fc7a66..1075344dc00f3 100644 --- a/compiler/rustc_middle/src/mir/tcx.rs +++ b/compiler/rustc_middle/src/mir/tcx.rs @@ -3,10 +3,11 @@ * building is complete. */ -use crate::mir::*; use rustc_hir as hir; use tracing::{debug, instrument}; +use crate::mir::*; + #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)] pub struct PlaceTy<'tcx> { pub ty: Ty<'tcx>, diff --git a/compiler/rustc_middle/src/mir/terminator.rs b/compiler/rustc_middle/src/mir/terminator.rs index 5b035d9579d76..962b93a25aac6 100644 --- a/compiler/rustc_middle/src/mir/terminator.rs +++ b/compiler/rustc_middle/src/mir/terminator.rs @@ -1,14 +1,13 @@ //! Functionality for terminators and helper types that appear in terminators. -use rustc_hir::LangItem; -use smallvec::{smallvec, SmallVec}; +use std::slice; -use super::TerminatorKind; use rustc_data_structures::packed::Pu128; +use rustc_hir::LangItem; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; -use std::slice; +use smallvec::{smallvec, SmallVec}; -use super::*; +use super::{TerminatorKind, *}; impl SwitchTargets { /// Creates switch targets from an iterator of values and target blocks. @@ -295,9 +294,10 @@ impl AssertKind { /// Note that we deliberately show more details here than we do at runtime, such as the actual /// numbers that overflowed -- it is much easier to do so here than at runtime. pub fn diagnostic_message(&self) -> DiagMessage { - use crate::fluent_generated::*; use AssertKind::*; + use crate::fluent_generated::*; + match self { BoundsCheck { .. } => middle_bounds_check, Overflow(BinOp::Shl, _, _) => middle_assert_shl_overflow, diff --git a/compiler/rustc_middle/src/mir/visit.rs b/compiler/rustc_middle/src/mir/visit.rs index 0031ded244062..3921176873c81 100644 --- a/compiler/rustc_middle/src/mir/visit.rs +++ b/compiler/rustc_middle/src/mir/visit.rs @@ -1066,9 +1066,11 @@ macro_rules! super_body { $self.visit_span($(& $mutability)? $body.span); - for const_ in &$($mutability)? $body.required_consts { - let location = Location::START; - $self.visit_const_operand(const_, location); + if let Some(required_consts) = &$($mutability)? $body.required_consts { + for const_ in required_consts { + let location = Location::START; + $self.visit_const_operand(const_, location); + } } } } diff --git a/compiler/rustc_middle/src/query/erase.rs b/compiler/rustc_middle/src/query/erase.rs index d9fa5b02f7f74..bd20e6aa00537 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -1,10 +1,10 @@ -use crate::mir; +use std::intrinsics::transmute_unchecked; +use std::mem::MaybeUninit; + use crate::query::CyclePlaceholder; -use crate::traits; use crate::ty::adjustment::CoerceUnsizedInfo; use crate::ty::{self, Ty}; -use std::intrinsics::transmute_unchecked; -use std::mem::MaybeUninit; +use crate::{mir, traits}; #[derive(Copy, Clone)] pub struct Erased { diff --git a/compiler/rustc_middle/src/query/keys.rs b/compiler/rustc_middle/src/query/keys.rs index add88491f8467..6562d46d7b866 100644 --- a/compiler/rustc_middle/src/query/keys.rs +++ b/compiler/rustc_middle/src/query/keys.rs @@ -1,12 +1,5 @@ //! Defines the set of legal keys that can be used in queries. -use crate::infer::canonical::Canonical; -use crate::mir; -use crate::traits; -use crate::ty::fast_reject::SimplifiedType; -use crate::ty::layout::{TyAndLayout, ValidityRequirement}; -use crate::ty::{self, Ty, TyCtxt}; -use crate::ty::{GenericArg, GenericArgsRef}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalModDefId, ModDefId, LOCAL_CRATE}; use rustc_hir::hir_id::{HirId, OwnerId}; use rustc_query_system::query::{DefIdCache, DefaultCache, SingleCache, VecCache}; @@ -14,6 +7,12 @@ use rustc_span::symbol::{Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; use rustc_target::abi; +use crate::infer::canonical::Canonical; +use crate::ty::fast_reject::SimplifiedType; +use crate::ty::layout::{TyAndLayout, ValidityRequirement}; +use crate::ty::{self, GenericArg, GenericArgsRef, Ty, TyCtxt}; +use crate::{mir, traits}; + /// Placeholder for `CrateNum`'s "local" counterpart #[derive(Copy, Clone, Debug)] pub struct LocalCrate; diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index c7ea1d4338366..c22c2e985abba 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -6,7 +6,44 @@ #![allow(unused_parens)] -use crate::dep_graph; +use std::mem; +use std::ops::Deref; +use std::path::PathBuf; +use std::sync::Arc; + +use rustc_arena::TypedArena; +use rustc_ast::expand::allocator::AllocatorKind; +use rustc_ast::expand::StrippedCfgItem; +use rustc_data_structures::fingerprint::Fingerprint; +use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; +use rustc_data_structures::steal::Steal; +use rustc_data_structures::svh::Svh; +use rustc_data_structures::sync::Lrc; +use rustc_data_structures::unord::{UnordMap, UnordSet}; +use rustc_errors::ErrorGuaranteed; +use rustc_hir::def::{DefKind, DocLinkResMap}; +use rustc_hir::def_id::{ + CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId, LocalDefIdMap, LocalDefIdSet, LocalModDefId, +}; +use rustc_hir::lang_items::{LangItem, LanguageItems}; +use rustc_hir::{Crate, ItemLocalId, ItemLocalMap, TraitCandidate}; +use rustc_index::IndexVec; +use rustc_macros::rustc_queries; +use rustc_query_system::ich::StableHashingContext; +use rustc_query_system::query::{try_get_cached, QueryCache, QueryMode, QueryState}; +use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion}; +use rustc_session::cstore::{ + CrateDepKind, CrateSource, ExternCrate, ForeignModule, LinkagePreference, NativeLib, +}; +use rustc_session::lint::LintExpectationId; +use rustc_session::Limits; +use rustc_span::def_id::LOCAL_CRATE; +use rustc_span::symbol::Symbol; +use rustc_span::{Span, DUMMY_SP}; +use rustc_target::abi; +use rustc_target::spec::PanicStrategy; +use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; + use crate::infer::canonical::{self, Canonical}; use crate::lint::LintExpectation; use crate::metadata::ModChild; @@ -17,79 +54,35 @@ 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::mir; -use crate::mir::interpret::GlobalId; use crate::mir::interpret::{ EvalStaticInitializerRawResult, EvalToAllocationRawResult, EvalToConstValueResult, - EvalToValTreeResult, + EvalToValTreeResult, GlobalId, LitToConstError, LitToConstInput, }; -use crate::mir::interpret::{LitToConstError, LitToConstInput}; use crate::mir::mono::CodegenUnit; use crate::query::erase::{erase, restore, Erase}; use crate::query::plumbing::{ query_ensure, query_ensure_error_guaranteed, query_get_at, CyclePlaceholder, DynamicQuery, }; -use crate::thir; use crate::traits::query::{ CanonicalAliasGoal, CanonicalPredicateGoal, CanonicalTyGoal, CanonicalTypeOpAscribeUserTypeGoal, CanonicalTypeOpEqGoal, CanonicalTypeOpNormalizeGoal, - CanonicalTypeOpProvePredicateGoal, CanonicalTypeOpSubtypeGoal, NoSolution, -}; -use crate::traits::query::{ - DropckConstraint, DropckOutlivesResult, MethodAutoderefStepsResult, NormalizationResult, + CanonicalTypeOpProvePredicateGoal, CanonicalTypeOpSubtypeGoal, DropckConstraint, + DropckOutlivesResult, MethodAutoderefStepsResult, NoSolution, NormalizationResult, OutlivesBound, }; -use crate::traits::specialization_graph; use crate::traits::{ - CodegenObligationError, EvaluationResult, ImplSource, ObjectSafetyViolation, ObligationCause, - OverflowError, WellFormedLoc, + specialization_graph, CodegenObligationError, EvaluationResult, ImplSource, + ObjectSafetyViolation, ObligationCause, OverflowError, WellFormedLoc, }; use crate::ty::fast_reject::SimplifiedType; use crate::ty::layout::ValidityRequirement; -use crate::ty::print::PrintTraitRefExt; +use crate::ty::print::{describe_as_module, PrintTraitRefExt}; use crate::ty::util::AlwaysRequiresDrop; -use crate::ty::TyCtxtFeed; use crate::ty::{ - self, print::describe_as_module, CrateInherentImpls, ParamEnvAnd, Ty, TyCtxt, + self, CrateInherentImpls, GenericArg, GenericArgsRef, ParamEnvAnd, Ty, TyCtxt, TyCtxtFeed, UnusedGenericParams, }; -use crate::ty::{GenericArg, GenericArgsRef}; -use rustc_arena::TypedArena; -use rustc_ast as ast; -use rustc_ast::expand::{allocator::AllocatorKind, StrippedCfgItem}; -use rustc_attr as attr; -use rustc_data_structures::fingerprint::Fingerprint; -use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; -use rustc_data_structures::steal::Steal; -use rustc_data_structures::svh::Svh; -use rustc_data_structures::sync::Lrc; -use rustc_data_structures::unord::{UnordMap, UnordSet}; -use rustc_errors::ErrorGuaranteed; -use rustc_hir as hir; -use rustc_hir::def::{DefKind, DocLinkResMap}; -use rustc_hir::def_id::{ - CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId, LocalDefIdMap, LocalDefIdSet, LocalModDefId, -}; -use rustc_hir::lang_items::{LangItem, LanguageItems}; -use rustc_hir::{Crate, ItemLocalId, ItemLocalMap, TraitCandidate}; -use rustc_index::IndexVec; -use rustc_macros::rustc_queries; -use rustc_query_system::ich::StableHashingContext; -use rustc_query_system::query::{try_get_cached, QueryCache, QueryMode, QueryState}; -use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion}; -use rustc_session::cstore::{CrateDepKind, CrateSource}; -use rustc_session::cstore::{ExternCrate, ForeignModule, LinkagePreference, NativeLib}; -use rustc_session::lint::LintExpectationId; -use rustc_session::Limits; -use rustc_span::def_id::LOCAL_CRATE; -use rustc_span::symbol::Symbol; -use rustc_span::{Span, DUMMY_SP}; -use rustc_target::abi; -use rustc_target::spec::PanicStrategy; -use std::mem; -use std::ops::Deref; -use std::path::PathBuf; -use std::sync::Arc; +use crate::{dep_graph, mir, thir}; pub mod erase; mod keys; @@ -1729,6 +1722,10 @@ rustc_queries! { desc { |tcx| "getting the native library for `{}`", tcx.def_path_str(def_id) } } + query inherit_sig_for_delegation_item(def_id: LocalDefId) -> &'tcx [Ty<'tcx>] { + desc { "inheriting delegation signature" } + } + /// Does lifetime resolution on items. Importantly, we can't resolve /// lifetimes directly on things like trait methods, because of trait params. /// See `rustc_resolve::late::lifetimes` for details. diff --git a/compiler/rustc_middle/src/query/on_disk_cache.rs b/compiler/rustc_middle/src/query/on_disk_cache.rs index 924249bf37d6c..ca52358218e92 100644 --- a/compiler/rustc_middle/src/query/on_disk_cache.rs +++ b/compiler/rustc_middle/src/query/on_disk_cache.rs @@ -1,3 +1,6 @@ +use std::collections::hash_map::Entry; +use std::mem; + use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; use rustc_data_structures::memmap::Mmap; use rustc_data_structures::sync::{HashMapExt, Lock, Lrc, RwLock}; @@ -13,22 +16,17 @@ use rustc_middle::mir::{self, interpret}; use rustc_middle::ty::codec::{RefDecodable, TyDecoder, TyEncoder}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_query_system::query::QuerySideEffects; -use rustc_serialize::{ - opaque::{FileEncodeResult, FileEncoder, IntEncodedWithFixedSize, MemDecoder}, - Decodable, Decoder, Encodable, Encoder, -}; +use rustc_serialize::opaque::{FileEncodeResult, FileEncoder, IntEncodedWithFixedSize, MemDecoder}; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_session::Session; use rustc_span::hygiene::{ ExpnId, HygieneDecodeContext, HygieneEncodeContext, SyntaxContext, SyntaxContextData, }; use rustc_span::source_map::SourceMap; use rustc_span::{ - BytePos, ExpnData, ExpnHash, Pos, RelativeBytePos, SourceFile, Span, SpanDecoder, SpanEncoder, - StableSourceFileId, + BytePos, CachingSourceMapView, ExpnData, ExpnHash, Pos, RelativeBytePos, SourceFile, Span, + SpanDecoder, SpanEncoder, StableSourceFileId, Symbol, }; -use rustc_span::{CachingSourceMapView, Symbol}; -use std::collections::hash_map::Entry; -use std::mem; const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE; diff --git a/compiler/rustc_middle/src/query/plumbing.rs b/compiler/rustc_middle/src/query/plumbing.rs index 8a4e3ab0e619a..c9bd702cce340 100644 --- a/compiler/rustc_middle/src/query/plumbing.rs +++ b/compiler/rustc_middle/src/query/plumbing.rs @@ -1,25 +1,23 @@ -use crate::dep_graph; -use crate::dep_graph::DepKind; -use crate::query::on_disk_cache::CacheEncoder; -use crate::query::on_disk_cache::EncodedDepNodeIndex; -use crate::query::on_disk_cache::OnDiskCache; -use crate::query::{ - DynamicQueries, ExternProviders, Providers, QueryArenas, QueryCaches, QueryEngine, QueryStates, -}; -use crate::ty::TyCtxt; +use std::ops::Deref; + use field_offset::FieldOffset; -use rustc_data_structures::sync::AtomicU64; -use rustc_data_structures::sync::WorkerLocal; +use rustc_data_structures::sync::{AtomicU64, WorkerLocal}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::hir_id::OwnerId; use rustc_macros::HashStable; -use rustc_query_system::dep_graph::DepNodeIndex; -use rustc_query_system::dep_graph::SerializedDepNodeIndex; +use rustc_query_system::dep_graph::{DepNodeIndex, SerializedDepNodeIndex}; pub(crate) use rustc_query_system::query::QueryJobId; use rustc_query_system::query::*; use rustc_query_system::HandleCycleError; use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; -use std::ops::Deref; + +use crate::dep_graph; +use crate::dep_graph::DepKind; +use crate::query::on_disk_cache::{CacheEncoder, EncodedDepNodeIndex, OnDiskCache}; +use crate::query::{ + DynamicQueries, ExternProviders, Providers, QueryArenas, QueryCaches, QueryEngine, QueryStates, +}; +use crate::ty::TyCtxt; pub struct DynamicQuery<'tcx, C: QueryCache> { pub name: &'static str, @@ -574,9 +572,10 @@ macro_rules! define_feedable { // as they will raise an fatal error on query cycles instead. mod sealed { - use super::{DefId, LocalDefId, OwnerId}; use rustc_hir::def_id::{LocalModDefId, ModDefId}; + use super::{DefId, LocalDefId, OwnerId}; + /// An analogue of the `Into` trait that's intended only for query parameters. /// /// This exists to allow queries to accept either `DefId` or `LocalDefId` while requiring that the diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index b80d00719ee5e..f2ea32275f9b1 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -8,13 +8,15 @@ //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/thir.html +use std::cmp::Ordering; +use std::fmt; +use std::ops::Index; + use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; -use rustc_errors::{DiagArgValue, IntoDiagArg}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::{BindingMode, ByRef, HirId, MatchSource, RangeEnd}; -use rustc_index::newtype_index; -use rustc_index::IndexVec; +use rustc_index::{newtype_index, IndexVec}; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeVisitable}; use rustc_middle::middle::region; use rustc_middle::mir::interpret::AllocId; @@ -26,12 +28,9 @@ use rustc_middle::ty::{ TyCtxt, UpvarArgs, }; use rustc_span::def_id::LocalDefId; -use rustc_span::{sym, ErrorGuaranteed, Span, Symbol, DUMMY_SP}; +use rustc_span::{ErrorGuaranteed, Span, Symbol}; use rustc_target::abi::{FieldIdx, Integer, Size, VariantIdx}; use rustc_target::asm::InlineAsmRegOrRegClass; -use std::cmp::Ordering; -use std::fmt; -use std::ops::Index; use tracing::instrument; pub mod visit; @@ -598,10 +597,6 @@ pub struct Pat<'tcx> { } impl<'tcx> Pat<'tcx> { - pub fn wildcard_from_ty(ty: Ty<'tcx>) -> Self { - Pat { ty, span: DUMMY_SP, kind: PatKind::Wild } - } - pub fn simple_ident(&self) -> Option { match self.kind { PatKind::Binding { @@ -702,12 +697,6 @@ impl<'tcx> Pat<'tcx> { } } -impl<'tcx> IntoDiagArg for Pat<'tcx> { - fn into_diag_arg(self) -> DiagArgValue { - format!("{self}").into_diag_arg() - } -} - #[derive(Clone, Debug, HashStable, TypeVisitable)] pub struct Ascription<'tcx> { pub annotation: CanonicalUserTypeAnnotation<'tcx>, @@ -1080,164 +1069,12 @@ impl<'tcx> PatRangeBoundary<'tcx> { } } -impl<'tcx> fmt::Display for Pat<'tcx> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - // Printing lists is a chore. - let mut first = true; - let mut start_or_continue = |s| { - if first { - first = false; - "" - } else { - s - } - }; - let mut start_or_comma = || start_or_continue(", "); - - match self.kind { - PatKind::Wild => write!(f, "_"), - PatKind::Never => write!(f, "!"), - PatKind::AscribeUserType { ref subpattern, .. } => write!(f, "{subpattern}: _"), - PatKind::Binding { name, mode, ref subpattern, .. } => { - f.write_str(mode.prefix_str())?; - write!(f, "{name}")?; - if let Some(ref subpattern) = *subpattern { - write!(f, " @ {subpattern}")?; - } - Ok(()) - } - PatKind::Variant { ref subpatterns, .. } | PatKind::Leaf { ref subpatterns } => { - let variant_and_name = match self.kind { - PatKind::Variant { adt_def, variant_index, .. } => ty::tls::with(|tcx| { - let variant = adt_def.variant(variant_index); - let adt_did = adt_def.did(); - let name = if tcx.get_diagnostic_item(sym::Option) == Some(adt_did) - || tcx.get_diagnostic_item(sym::Result) == Some(adt_did) - { - variant.name.to_string() - } else { - format!("{}::{}", tcx.def_path_str(adt_def.did()), variant.name) - }; - Some((variant, name)) - }), - _ => self.ty.ty_adt_def().and_then(|adt_def| { - if !adt_def.is_enum() { - ty::tls::with(|tcx| { - Some((adt_def.non_enum_variant(), tcx.def_path_str(adt_def.did()))) - }) - } else { - None - } - }), - }; - - if let Some((variant, name)) = &variant_and_name { - write!(f, "{name}")?; - - // Only for Adt we can have `S {...}`, - // which we handle separately here. - if variant.ctor.is_none() { - write!(f, " {{ ")?; - - let mut printed = 0; - for p in subpatterns { - if let PatKind::Wild = p.pattern.kind { - continue; - } - let name = variant.fields[p.field].name; - write!(f, "{}{}: {}", start_or_comma(), name, p.pattern)?; - printed += 1; - } - - let is_union = self.ty.ty_adt_def().is_some_and(|adt| adt.is_union()); - if printed < variant.fields.len() && (!is_union || printed == 0) { - write!(f, "{}..", start_or_comma())?; - } - - return write!(f, " }}"); - } - } - - let num_fields = - variant_and_name.as_ref().map_or(subpatterns.len(), |(v, _)| v.fields.len()); - if num_fields != 0 || variant_and_name.is_none() { - write!(f, "(")?; - for i in 0..num_fields { - write!(f, "{}", start_or_comma())?; - - // Common case: the field is where we expect it. - if let Some(p) = subpatterns.get(i) { - if p.field.index() == i { - write!(f, "{}", p.pattern)?; - continue; - } - } - - // Otherwise, we have to go looking for it. - if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) { - write!(f, "{}", p.pattern)?; - } else { - write!(f, "_")?; - } - } - write!(f, ")")?; - } - - Ok(()) - } - PatKind::Deref { ref subpattern } => { - match self.ty.kind() { - ty::Adt(def, _) if def.is_box() => write!(f, "box ")?, - ty::Ref(_, _, mutbl) => { - write!(f, "&{}", mutbl.prefix_str())?; - } - _ => bug!("{} is a bad Deref pattern type", self.ty), - } - write!(f, "{subpattern}") - } - PatKind::DerefPattern { ref subpattern, .. } => { - write!(f, "deref!({subpattern})") - } - PatKind::Constant { value } => write!(f, "{value}"), - PatKind::InlineConstant { def: _, ref subpattern } => { - write!(f, "{} (from inline const)", subpattern) - } - PatKind::Range(ref range) => write!(f, "{range}"), - PatKind::Slice { ref prefix, ref slice, ref suffix } - | PatKind::Array { ref prefix, ref slice, ref suffix } => { - write!(f, "[")?; - for p in prefix.iter() { - write!(f, "{}{}", start_or_comma(), p)?; - } - if let Some(ref slice) = *slice { - write!(f, "{}", start_or_comma())?; - match slice.kind { - PatKind::Wild => {} - _ => write!(f, "{slice}")?, - } - write!(f, "..")?; - } - for p in suffix.iter() { - write!(f, "{}{}", start_or_comma(), p)?; - } - write!(f, "]") - } - PatKind::Or { ref pats } => { - for pat in pats.iter() { - write!(f, "{}{}", start_or_continue(" | "), pat)?; - } - Ok(()) - } - PatKind::Error(_) => write!(f, ""), - } - } -} - // Some nodes are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(Block, 48); static_assert_size!(Expr<'_>, 64); diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index b74775142e487..d54e2ca0a74f7 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -8,10 +8,8 @@ pub mod solve; pub mod specialization_graph; mod structural_impls; -use crate::mir::ConstraintCategory; -use crate::ty::abstract_const::NotConstEvaluatable; -use crate::ty::GenericArgsRef; -use crate::ty::{self, AdtKind, Ty}; +use std::borrow::Cow; +use std::hash::{Hash, Hasher}; use rustc_data_structures::sync::Lrc; use rustc_errors::{Applicability, Diag, EmissionGuarantee}; @@ -24,14 +22,14 @@ use rustc_macros::{ use rustc_span::def_id::{LocalDefId, CRATE_DEF_ID}; use rustc_span::symbol::Symbol; use rustc_span::{Span, DUMMY_SP}; +// FIXME: Remove this import and import via `solve::` +pub use rustc_type_ir::solve::{BuiltinImplSource, Reveal}; use smallvec::{smallvec, SmallVec}; -use std::borrow::Cow; -use std::hash::{Hash, Hasher}; - pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache}; -// FIXME: Remove this import and import via `solve::` -pub use rustc_type_ir::solve::{BuiltinImplSource, Reveal}; +use crate::mir::ConstraintCategory; +use crate::ty::abstract_const::NotConstEvaluatable; +use crate::ty::{self, AdtKind, GenericArgsRef, Ty}; /// The reason why we incurred this obligation; used for error reporting. /// diff --git a/compiler/rustc_middle/src/traits/query.rs b/compiler/rustc_middle/src/traits/query.rs index 4fad721ce9847..81a543e647a7e 100644 --- a/compiler/rustc_middle/src/traits/query.rs +++ b/compiler/rustc_middle/src/traits/query.rs @@ -5,20 +5,22 @@ //! The providers for the queries defined here can be found in //! `rustc_traits`. -use crate::error::DropCheckOverflow; -use crate::infer::canonical::{Canonical, QueryResponse}; -use crate::ty::GenericArg; -use crate::ty::{self, Ty, TyCtxt}; use rustc_macros::{HashStable, TypeFoldable, TypeVisitable}; use rustc_span::Span; // FIXME: Remove this import and import via `traits::solve`. pub use rustc_type_ir::solve::NoSolution; +use crate::error::DropCheckOverflow; +use crate::infer::canonical::{Canonical, QueryResponse}; +use crate::ty::{self, GenericArg, Ty, TyCtxt}; + pub mod type_op { + use std::fmt; + + use rustc_macros::{HashStable, TypeFoldable, TypeVisitable}; + use crate::ty::fold::TypeFoldable; use crate::ty::{Predicate, Ty, TyCtxt, UserType}; - use rustc_macros::{HashStable, TypeFoldable, TypeVisitable}; - use std::fmt; #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, HashStable, TypeFoldable, TypeVisitable)] pub struct AscribeUserType<'tcx> { diff --git a/compiler/rustc_middle/src/traits/select.rs b/compiler/rustc_middle/src/traits/select.rs index c8caf228ffb5b..66035464fa55a 100644 --- a/compiler/rustc_middle/src/traits/select.rs +++ b/compiler/rustc_middle/src/traits/select.rs @@ -2,17 +2,15 @@ //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection -use self::EvaluationResult::*; - -use super::{SelectionError, SelectionResult}; use rustc_errors::ErrorGuaranteed; - -use crate::ty; - use rustc_hir::def_id::DefId; use rustc_macros::{HashStable, TypeVisitable}; use rustc_query_system::cache::Cache; +use self::EvaluationResult::*; +use super::{SelectionError, SelectionResult}; +use crate::ty; + pub type SelectionCache<'tcx> = Cache< // This cache does not use `ParamEnvAnd` in its keys because `ParamEnv::and` can replace // caller bounds with an empty list if the `TraitPredicate` looks global, which may happen diff --git a/compiler/rustc_middle/src/traits/specialization_graph.rs b/compiler/rustc_middle/src/traits/specialization_graph.rs index ff5d51bcb66f5..26dcae001e0eb 100644 --- a/compiler/rustc_middle/src/traits/specialization_graph.rs +++ b/compiler/rustc_middle/src/traits/specialization_graph.rs @@ -1,13 +1,14 @@ -use crate::error::StrictCoherenceNeedsNegativeCoherence; -use crate::ty::fast_reject::SimplifiedType; -use crate::ty::visit::TypeVisitableExt; -use crate::ty::{self, TyCtxt}; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::ErrorGuaranteed; use rustc_hir::def_id::{DefId, DefIdMap}; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_span::symbol::sym; +use crate::error::StrictCoherenceNeedsNegativeCoherence; +use crate::ty::fast_reject::SimplifiedType; +use crate::ty::visit::TypeVisitableExt; +use crate::ty::{self, TyCtxt}; + /// A per-trait graph of impls in specialization order. At the moment, this /// graph forms a tree rooted with the trait itself, with all other nodes /// representing impls, and parent-child relationships representing diff --git a/compiler/rustc_middle/src/traits/structural_impls.rs b/compiler/rustc_middle/src/traits/structural_impls.rs index ec450cf559006..d79a9368f3431 100644 --- a/compiler/rustc_middle/src/traits/structural_impls.rs +++ b/compiler/rustc_middle/src/traits/structural_impls.rs @@ -1,7 +1,7 @@ -use crate::traits; - use std::fmt; +use crate::traits; + // Structural impls for the structs in `traits`. impl<'tcx, N: fmt::Debug> fmt::Debug for traits::ImplSource<'tcx, N> { diff --git a/compiler/rustc_middle/src/ty/abstract_const.rs b/compiler/rustc_middle/src/ty/abstract_const.rs index 3aa01fbef2fbf..002d381962124 100644 --- a/compiler/rustc_middle/src/ty/abstract_const.rs +++ b/compiler/rustc_middle/src/ty/abstract_const.rs @@ -1,11 +1,12 @@ //! A subset of a mir body used for const evaluability checking. +use rustc_errors::ErrorGuaranteed; +use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeVisitable}; + use crate::ty::{ self, Const, EarlyBinder, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, }; -use rustc_errors::ErrorGuaranteed; -use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeVisitable}; #[derive(Hash, Debug, Clone, Copy, Ord, PartialOrd, PartialEq, Eq)] #[derive(TyDecodable, TyEncodable, HashStable, TypeVisitable, TypeFoldable)] diff --git a/compiler/rustc_middle/src/ty/adjustment.rs b/compiler/rustc_middle/src/ty/adjustment.rs index 6d7b62597475a..1236c9efb41cf 100644 --- a/compiler/rustc_middle/src/ty/adjustment.rs +++ b/compiler/rustc_middle/src/ty/adjustment.rs @@ -1,10 +1,11 @@ -use crate::ty::{self, Ty, TyCtxt}; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; use rustc_span::Span; use rustc_target::abi::FieldIdx; +use crate::ty::{self, Ty, TyCtxt}; + #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)] pub enum PointerCoercion { /// Go from a fn-item type to a fn-pointer type. diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index 88ee32eae9529..204f61b4804e4 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -1,12 +1,13 @@ -use crate::mir::interpret::ErrorHandled; -use crate::ty; -use crate::ty::util::{Discr, IntTypeExt}; +use std::cell::RefCell; +use std::hash::{Hash, Hasher}; +use std::ops::Range; +use std::str; + use rustc_data_structures::captures::Captures; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::intern::Interned; -use rustc_data_structures::stable_hasher::HashingControls; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::stable_hasher::{HashStable, HashingControls, StableHasher}; use rustc_errors::ErrorGuaranteed; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; @@ -19,14 +20,12 @@ use rustc_span::symbol::sym; use rustc_target::abi::{ReprOptions, VariantIdx, FIRST_VARIANT}; use tracing::{debug, info, trace}; -use std::cell::RefCell; -use std::hash::{Hash, Hasher}; -use std::ops::Range; -use std::str; - use super::{ AsyncDestructor, Destructor, FieldDef, GenericPredicates, Ty, TyCtxt, VariantDef, VariantDiscr, }; +use crate::mir::interpret::ErrorHandled; +use crate::ty; +use crate::ty::util::{Discr, IntTypeExt}; #[derive(Clone, Copy, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)] pub struct AdtFlags(u16); diff --git a/compiler/rustc_middle/src/ty/assoc.rs b/compiler/rustc_middle/src/ty/assoc.rs index 820f5e950a9d9..0ce5c613c4ce3 100644 --- a/compiler/rustc_middle/src/ty/assoc.rs +++ b/compiler/rustc_middle/src/ty/assoc.rs @@ -1,4 +1,3 @@ -use crate::ty; use rustc_data_structures::sorted_map::SortedIndexMultiMap; use rustc_hir as hir; use rustc_hir::def::{DefKind, Namespace}; @@ -7,6 +6,7 @@ use rustc_macros::{Decodable, Encodable, HashStable}; use rustc_span::symbol::{Ident, Symbol}; use super::{TyCtxt, Visibility}; +use crate::ty; #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable, Hash, Encodable, Decodable)] pub enum AssocItemContainer { diff --git a/compiler/rustc_middle/src/ty/cast.rs b/compiler/rustc_middle/src/ty/cast.rs index 26c5a865fdc22..46f3765953678 100644 --- a/compiler/rustc_middle/src/ty/cast.rs +++ b/compiler/rustc_middle/src/ty/cast.rs @@ -1,10 +1,10 @@ // Helpers for handling cast expressions, used in both // typeck and codegen. -use crate::ty::{self, Ty}; +use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_middle::mir; -use rustc_macros::{HashStable, TyDecodable, TyEncodable}; +use crate::ty::{self, Ty}; /// Types that are represented as ints. #[derive(Copy, Clone, Debug, PartialEq, Eq)] diff --git a/compiler/rustc_middle/src/ty/closure.rs b/compiler/rustc_middle/src/ty/closure.rs index bdd9a6bab2bee..8eb3c0156796a 100644 --- a/compiler/rustc_middle/src/ty/closure.rs +++ b/compiler/rustc_middle/src/ty/closure.rs @@ -1,11 +1,5 @@ -use crate::hir::place::{ - Place as HirPlace, PlaceBase as HirPlaceBase, ProjectionKind as HirProjectionKind, -}; -use crate::{mir, ty}; - use std::fmt::Write; -use crate::query::Providers; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexMap; use rustc_hir as hir; @@ -16,9 +10,13 @@ use rustc_span::def_id::LocalDefIdMap; use rustc_span::symbol::Ident; use rustc_span::{Span, Symbol}; -use super::TyCtxt; - use self::BorrowKind::*; +use super::TyCtxt; +use crate::hir::place::{ + Place as HirPlace, PlaceBase as HirPlaceBase, ProjectionKind as HirProjectionKind, +}; +use crate::query::Providers; +use crate::{mir, ty}; /// Captures are represented using fields inside a structure. /// This represents accessing self in the closure structure diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 33f564e9b59c3..401f6da6526aa 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -6,16 +6,10 @@ //! The functionality in here is shared between persisting to crate metadata and //! persisting to incr. comp. caches. -use crate::arena::ArenaAllocatable; -use crate::infer::canonical::{CanonicalVarInfo, CanonicalVarInfos}; -use crate::mir::interpret::CtfeProvenance; -use crate::mir::{ - self, - interpret::{AllocId, ConstAllocation}, -}; -use crate::traits; -use crate::ty::GenericArgsRef; -use crate::ty::{self, AdtDef, Ty}; +use std::hash::Hash; +use std::intrinsics; +use std::marker::DiscriminantKind; + use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::LocalDefId; use rustc_middle::ty::TyCtxt; @@ -23,9 +17,13 @@ use rustc_serialize::{Decodable, Encodable}; use rustc_span::Span; use rustc_target::abi::{FieldIdx, VariantIdx}; pub use rustc_type_ir::{TyDecoder, TyEncoder}; -use std::hash::Hash; -use std::intrinsics; -use std::marker::DiscriminantKind; + +use crate::arena::ArenaAllocatable; +use crate::infer::canonical::{CanonicalVarInfo, CanonicalVarInfos}; +use crate::mir::interpret::{AllocId, ConstAllocation, CtfeProvenance}; +use crate::mir::{self}; +use crate::traits; +use crate::ty::{self, AdtDef, GenericArgsRef, Ty}; /// The shorthand encoding uses an enum's variant index `usize` /// and is offset by this value so it never matches a real variant. diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 5cf1247f0c820..c380019e63f47 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -1,6 +1,3 @@ -use crate::middle::resolve_bound_vars as rbv; -use crate::mir::interpret::{ErrorHandled, LitToConstInput, Scalar}; -use crate::ty::{self, GenericArgs, ParamEnv, ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt}; use either::Either; use rustc_data_structures::intern::Interned; use rustc_error_messages::MultiSpan; @@ -11,14 +8,17 @@ use rustc_macros::HashStable; use rustc_type_ir::{self as ir, TypeFlags, WithCachedTypeInfo}; use tracing::{debug, instrument}; +use crate::middle::resolve_bound_vars as rbv; +use crate::mir::interpret::{ErrorHandled, LitToConstInput, Scalar}; +use crate::ty::{self, GenericArgs, ParamEnv, ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt}; + mod int; mod kind; mod valtree; pub use int::*; pub use kind::*; -use rustc_span::DUMMY_SP; -use rustc_span::{ErrorGuaranteed, Span}; +use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; pub use valtree::*; pub type ConstKind<'tcx> = ir::ConstKind>; diff --git a/compiler/rustc_middle/src/ty/consts/int.rs b/compiler/rustc_middle/src/ty/consts/int.rs index 13691b61941bd..0024a2ae756ea 100644 --- a/compiler/rustc_middle/src/ty/consts/int.rs +++ b/compiler/rustc_middle/src/ty/consts/int.rs @@ -1,10 +1,11 @@ +use std::fmt; +use std::num::NonZero; + use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_apfloat::Float; use rustc_errors::{DiagArgValue, IntoDiagArg}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_target::abi::Size; -use std::fmt; -use std::num::NonZero; use crate::ty::TyCtxt; @@ -233,7 +234,7 @@ impl ScalarInt { let data = i.into(); // `into` performed sign extension, we have to truncate let r = Self::raw(size.truncate(data as u128), size); - (r, size.sign_extend(r.data) as i128 != data) + (r, size.sign_extend(r.data) != data) } #[inline] @@ -334,7 +335,7 @@ impl ScalarInt { #[inline] pub fn to_int(self, size: Size) -> i128 { let b = self.to_bits(size); - size.sign_extend(b) as i128 + size.sign_extend(b) } /// Converts the `ScalarInt` to i8. diff --git a/compiler/rustc_middle/src/ty/consts/kind.rs b/compiler/rustc_middle/src/ty/consts/kind.rs index 98f35b6b8ab99..7f096dd36f8f2 100644 --- a/compiler/rustc_middle/src/ty/consts/kind.rs +++ b/compiler/rustc_middle/src/ty/consts/kind.rs @@ -1,8 +1,10 @@ +use rustc_macros::{extension, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; + use super::Const; use crate::mir; use crate::ty::abstract_const::CastKind; -use crate::ty::{self, visit::TypeVisitableExt as _, Ty, TyCtxt}; -use rustc_macros::{extension, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; +use crate::ty::visit::TypeVisitableExt as _; +use crate::ty::{self, Ty, TyCtxt}; #[extension(pub(crate) trait UnevaluatedConstEvalExt<'tcx>)] impl<'tcx> ty::UnevaluatedConst<'tcx> { diff --git a/compiler/rustc_middle/src/ty/consts/valtree.rs b/compiler/rustc_middle/src/ty/consts/valtree.rs index efc91357af8c8..9f9bf41c3355a 100644 --- a/compiler/rustc_middle/src/ty/consts/valtree.rs +++ b/compiler/rustc_middle/src/ty/consts/valtree.rs @@ -1,7 +1,8 @@ +use rustc_macros::{HashStable, TyDecodable, TyEncodable}; + use super::ScalarInt; use crate::mir::interpret::Scalar; use crate::ty::{self, Ty, TyCtxt}; -use rustc_macros::{HashStable, TyDecodable, TyEncodable}; #[derive(Copy, Clone, Debug, Hash, TyEncodable, TyDecodable, Eq, PartialEq)] #[derive(HashStable)] diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index fd41668ae44c8..8f8fd09c9e4d9 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -4,36 +4,14 @@ pub mod tls; -pub use rustc_type_ir::lift::Lift; +use std::assert_matches::assert_matches; +use std::borrow::Borrow; +use std::cmp::Ordering; +use std::hash::{Hash, Hasher}; +use std::marker::PhantomData; +use std::ops::{Bound, Deref}; +use std::{fmt, iter, mem}; -use crate::arena::Arena; -use crate::dep_graph::{DepGraph, DepKindStruct}; -use crate::infer::canonical::{CanonicalParamEnvCache, CanonicalVarInfo, CanonicalVarInfos}; -use crate::lint::lint_level; -use crate::metadata::ModChild; -use crate::middle::codegen_fn_attrs::CodegenFnAttrs; -use crate::middle::resolve_bound_vars; -use crate::middle::stability; -use crate::mir::interpret::{self, Allocation, ConstAllocation}; -use crate::mir::{Body, Local, Place, PlaceElem, ProjectionKind, Promoted}; -use crate::query::plumbing::QuerySystem; -use crate::query::LocalCrate; -use crate::query::Providers; -use crate::query::{IntoQueryParam, TyCtxtAt}; -use crate::thir::Thir; -use crate::traits; -use crate::traits::solve; -use crate::traits::solve::{ - ExternalConstraints, ExternalConstraintsData, PredefinedOpaques, PredefinedOpaquesData, -}; -use crate::ty::predicate::ExistentialPredicateStableCmpExt as _; -use crate::ty::{ - self, AdtDef, AdtDefData, AdtKind, Binder, Clause, Clauses, Const, GenericParamDefKind, - ImplPolarity, List, ListWithCachedTypeInfo, ParamConst, ParamTy, Pattern, PatternKind, - PolyExistentialPredicate, PolyFnSig, Predicate, PredicateKind, PredicatePolarity, Region, - RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyVid, Visibility, -}; -use crate::ty::{GenericArg, GenericArgs, GenericArgsRef}; use rustc_ast::{self as ast, attr}; use rustc_data_structures::defer; use rustc_data_structures::fingerprint::Fingerprint; @@ -74,20 +52,37 @@ use rustc_target::abi::{FieldIdx, Layout, LayoutS, TargetDataLayout, VariantIdx} use rustc_target::spec::abi; use rustc_type_ir::fold::TypeFoldable; use rustc_type_ir::lang_items::TraitSolverLangItem; +pub use rustc_type_ir::lift::Lift; use rustc_type_ir::solve::SolverMode; use rustc_type_ir::TyKind::*; use rustc_type_ir::{search_graph, CollectAndApply, Interner, TypeFlags, WithCachedTypeInfo}; use tracing::{debug, instrument}; -use std::assert_matches::assert_matches; -use std::borrow::Borrow; -use std::cmp::Ordering; -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::iter; -use std::marker::PhantomData; -use std::mem; -use std::ops::{Bound, Deref}; +use crate::arena::Arena; +use crate::dep_graph::{DepGraph, DepKindStruct}; +use crate::infer::canonical::{CanonicalParamEnvCache, CanonicalVarInfo, CanonicalVarInfos}; +use crate::lint::lint_level; +use crate::metadata::ModChild; +use crate::middle::codegen_fn_attrs::CodegenFnAttrs; +use crate::middle::{resolve_bound_vars, stability}; +use crate::mir::interpret::{self, Allocation, ConstAllocation}; +use crate::mir::{Body, Local, Place, PlaceElem, ProjectionKind, Promoted}; +use crate::query::plumbing::QuerySystem; +use crate::query::{IntoQueryParam, LocalCrate, Providers, TyCtxtAt}; +use crate::thir::Thir; +use crate::traits; +use crate::traits::solve; +use crate::traits::solve::{ + ExternalConstraints, ExternalConstraintsData, PredefinedOpaques, PredefinedOpaquesData, +}; +use crate::ty::predicate::ExistentialPredicateStableCmpExt as _; +use crate::ty::{ + self, AdtDef, AdtDefData, AdtKind, Binder, Clause, Clauses, Const, GenericArg, GenericArgs, + GenericArgsRef, GenericParamDefKind, ImplPolarity, List, ListWithCachedTypeInfo, ParamConst, + ParamTy, Pattern, PatternKind, PolyExistentialPredicate, PolyFnSig, Predicate, PredicateKind, + PredicatePolarity, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyVid, + Visibility, +}; #[allow(rustc::usage_of_ty_tykind)] impl<'tcx> Interner for TyCtxt<'tcx> { diff --git a/compiler/rustc_middle/src/ty/context/tls.rs b/compiler/rustc_middle/src/ty/context/tls.rs index 7b5ccae35682e..6a5d30306466e 100644 --- a/compiler/rustc_middle/src/ty/context/tls.rs +++ b/compiler/rustc_middle/src/ty/context/tls.rs @@ -1,15 +1,15 @@ -use super::{GlobalCtxt, TyCtxt}; +#[cfg(not(parallel_compiler))] +use std::cell::Cell; +use std::{mem, ptr}; -use crate::dep_graph::TaskDepsRef; -use crate::query::plumbing::QueryJobId; use rustc_data_structures::sync::{self, Lock}; use rustc_errors::DiagInner; -#[cfg(not(parallel_compiler))] -use std::cell::Cell; -use std::mem; -use std::ptr; use thin_vec::ThinVec; +use super::{GlobalCtxt, TyCtxt}; +use crate::dep_graph::TaskDepsRef; +use crate::query::plumbing::QueryJobId; + /// This is the implicit state of rustc. It contains the current /// `TyCtxt` and query. It is updated when creating a local interner or /// executing a new query. Whenever there's a `TyCtxt` value available diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index f479b18c7c43d..5acc0b7ac7ff1 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -4,12 +4,6 @@ use std::borrow::Cow; use std::fmt::Write; use std::ops::ControlFlow; -use crate::ty::{ - self, AliasTy, Const, ConstKind, FallibleTypeFolder, InferConst, InferTy, Opaque, - PolyTraitPredicate, Projection, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, - TypeSuperVisitable, TypeVisitable, TypeVisitor, -}; - use rustc_data_structures::fx::FxHashMap; use rustc_errors::{into_diag_arg_using_display, Applicability, Diag, DiagArgValue, IntoDiagArg}; use rustc_hir as hir; @@ -19,6 +13,12 @@ use rustc_hir::{PredicateOrigin, WherePredicate}; use rustc_span::{BytePos, Span}; use rustc_type_ir::TyKind::*; +use crate::ty::{ + self, AliasTy, Const, ConstKind, FallibleTypeFolder, InferConst, InferTy, Opaque, + PolyTraitPredicate, Projection, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, + TypeSuperVisitable, TypeVisitable, TypeVisitor, +}; + into_diag_arg_using_display! { Ty<'_>, ty::Region<'_>, @@ -188,31 +188,60 @@ fn suggest_changing_unsized_bound( continue; }; - for (pos, bound) in predicate.bounds.iter().enumerate() { - let hir::GenericBound::Trait(poly, hir::TraitBoundModifier::Maybe) = bound else { - continue; - }; - if poly.trait_ref.trait_def_id() != def_id { - continue; - } - if predicate.origin == PredicateOrigin::ImplTrait && predicate.bounds.len() == 1 { - // For `impl ?Sized` with no other bounds, suggest `impl Sized` instead. - let bound_span = bound.span(); - if bound_span.can_be_used_for_suggestions() { - let question_span = bound_span.with_hi(bound_span.lo() + BytePos(1)); - suggestions.push(( + let unsized_bounds = predicate + .bounds + .iter() + .enumerate() + .filter(|(_, bound)| { + if let hir::GenericBound::Trait(poly, hir::TraitBoundModifier::Maybe) = bound + && poly.trait_ref.trait_def_id() == def_id + { + true + } else { + false + } + }) + .collect::>(); + + if unsized_bounds.is_empty() { + continue; + } + + let mut push_suggestion = |sp, msg| suggestions.push((sp, String::new(), msg)); + + if predicate.bounds.len() == unsized_bounds.len() { + // All the bounds are unsized bounds, e.g. + // `T: ?Sized + ?Sized` or `_: impl ?Sized + ?Sized`, + // so in this case: + // - if it's an impl trait predicate suggest changing the + // the first bound to sized and removing the rest + // - Otherwise simply suggest removing the entire predicate + if predicate.origin == PredicateOrigin::ImplTrait { + let first_bound = unsized_bounds[0].1; + let first_bound_span = first_bound.span(); + if first_bound_span.can_be_used_for_suggestions() { + let question_span = + first_bound_span.with_hi(first_bound_span.lo() + BytePos(1)); + push_suggestion( question_span, - String::new(), SuggestChangingConstraintsMessage::ReplaceMaybeUnsizedWithSized, - )); + ); + + for (pos, _) in unsized_bounds.iter().skip(1) { + let sp = generics.span_for_bound_removal(where_pos, *pos); + push_suggestion(sp, SuggestChangingConstraintsMessage::RemoveMaybeUnsized); + } } } else { + let sp = generics.span_for_predicate_removal(where_pos); + push_suggestion(sp, SuggestChangingConstraintsMessage::RemoveMaybeUnsized); + } + } else { + // Some of the bounds are other than unsized. + // So push separate removal suggestion for each unsized bound + for (pos, _) in unsized_bounds { let sp = generics.span_for_bound_removal(where_pos, pos); - suggestions.push(( - sp, - String::new(), - SuggestChangingConstraintsMessage::RemoveMaybeUnsized, - )); + push_suggestion(sp, SuggestChangingConstraintsMessage::RemoveMaybeUnsized); } } } diff --git a/compiler/rustc_middle/src/ty/erase_regions.rs b/compiler/rustc_middle/src/ty/erase_regions.rs index 9d5481f3df376..ecca1d4490769 100644 --- a/compiler/rustc_middle/src/ty/erase_regions.rs +++ b/compiler/rustc_middle/src/ty/erase_regions.rs @@ -1,7 +1,8 @@ +use tracing::debug; + use crate::query::Providers; use crate::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use crate::ty::{self, Ty, TyCtxt, TypeFlags, TypeVisitableExt}; -use tracing::debug; pub(super) fn provide(providers: &mut Providers) { *providers = Providers { erase_regions_ty, ..*providers }; diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index 32dc9fa5fc621..2f9bdb16bb0ab 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -1,5 +1,6 @@ -use crate::ty::print::{with_forced_trimmed_paths, FmtPrinter, PrettyPrinter}; -use crate::ty::{self, Ty, TyCtxt}; +use std::borrow::Cow; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::path::PathBuf; use rustc_errors::pluralize; use rustc_hir as hir; @@ -7,9 +8,8 @@ use rustc_hir::def::{CtorOf, DefKind}; use rustc_macros::extension; pub use rustc_type_ir::error::ExpectedFound; -use std::borrow::Cow; -use std::hash::{DefaultHasher, Hash, Hasher}; -use std::path::PathBuf; +use crate::ty::print::{with_forced_trimmed_paths, FmtPrinter, PrettyPrinter}; +use crate::ty::{self, Ty, TyCtxt}; pub type TypeError<'tcx> = rustc_type_ir::error::TypeError>; diff --git a/compiler/rustc_middle/src/ty/fast_reject.rs b/compiler/rustc_middle/src/ty/fast_reject.rs index 0413cfa5a63c5..91344c4e39c8b 100644 --- a/compiler/rustc_middle/src/ty/fast_reject.rs +++ b/compiler/rustc_middle/src/ty/fast_reject.rs @@ -1,9 +1,8 @@ use rustc_hir::def_id::DefId; +pub use rustc_type_ir::fast_reject::*; use super::TyCtxt; -pub use rustc_type_ir::fast_reject::*; - pub type DeepRejectCtxt<'tcx> = rustc_type_ir::fast_reject::DeepRejectCtxt>; pub type SimplifiedType = rustc_type_ir::fast_reject::SimplifiedType; diff --git a/compiler/rustc_middle/src/ty/flags.rs b/compiler/rustc_middle/src/ty/flags.rs index 21c115c2c9667..c3430b5840692 100644 --- a/compiler/rustc_middle/src/ty/flags.rs +++ b/compiler/rustc_middle/src/ty/flags.rs @@ -1,7 +1,7 @@ -use crate::ty::{self, InferConst, Ty, TypeFlags}; -use crate::ty::{GenericArg, GenericArgKind}; use std::slice; +use crate::ty::{self, GenericArg, GenericArgKind, InferConst, Ty, TypeFlags}; + #[derive(Debug)] pub struct FlagComputation { pub flags: TypeFlags, diff --git a/compiler/rustc_middle/src/ty/fold.rs b/compiler/rustc_middle/src/ty/fold.rs index 81ea8738e7269..7892ef818194a 100644 --- a/compiler/rustc_middle/src/ty/fold.rs +++ b/compiler/rustc_middle/src/ty/fold.rs @@ -1,11 +1,11 @@ -use crate::ty::{self, Binder, BoundTy, Ty, TyCtxt, TypeVisitableExt}; use rustc_data_structures::fx::FxIndexMap; use rustc_hir::def_id::DefId; -use tracing::{debug, instrument}; - pub use rustc_type_ir::fold::{ shift_region, shift_vars, FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable, }; +use tracing::{debug, instrument}; + +use crate::ty::{self, Binder, BoundTy, Ty, TyCtxt, TypeVisitableExt}; /////////////////////////////////////////////////////////////////////////// // Some sample folders diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index 10919623de728..80c31e236e2c2 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -1,28 +1,27 @@ // Generic arguments. -use crate::ty::codec::{TyDecoder, TyEncoder}; -use crate::ty::fold::{FallibleTypeFolder, TypeFoldable}; -use crate::ty::visit::{TypeVisitable, TypeVisitor}; -use crate::ty::{ - self, ClosureArgs, CoroutineArgs, CoroutineClosureArgs, InlineConstArgs, Lift, List, Ty, TyCtxt, -}; +use core::intrinsics; +use std::marker::PhantomData; +use std::mem; +use std::num::NonZero; +use std::ptr::NonNull; use rustc_ast_ir::visit::VisitorResult; use rustc_ast_ir::walk_visitable_list; use rustc_data_structures::intern::Interned; use rustc_errors::{DiagArgValue, IntoDiagArg}; use rustc_hir::def_id::DefId; -use rustc_macros::extension; -use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; +use rustc_macros::{extension, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; use rustc_serialize::{Decodable, Encodable}; use rustc_type_ir::WithCachedTypeInfo; use smallvec::SmallVec; -use core::intrinsics; -use std::marker::PhantomData; -use std::mem; -use std::num::NonZero; -use std::ptr::NonNull; +use crate::ty::codec::{TyDecoder, TyEncoder}; +use crate::ty::fold::{FallibleTypeFolder, TypeFoldable}; +use crate::ty::visit::{TypeVisitable, TypeVisitor}; +use crate::ty::{ + self, ClosureArgs, CoroutineArgs, CoroutineClosureArgs, InlineConstArgs, Lift, List, Ty, TyCtxt, +}; pub type GenericArgKind<'tcx> = rustc_type_ir::GenericArgKind>; pub type TermKind<'tcx> = rustc_type_ir::TermKind>; diff --git a/compiler/rustc_middle/src/ty/generics.rs b/compiler/rustc_middle/src/ty/generics.rs index 11ed0bdaa7028..39c306a720f95 100644 --- a/compiler/rustc_middle/src/ty/generics.rs +++ b/compiler/rustc_middle/src/ty/generics.rs @@ -1,5 +1,3 @@ -use crate::ty; -use crate::ty::{EarlyBinder, GenericArgsRef}; use rustc_ast as ast; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::DefId; @@ -9,6 +7,8 @@ use rustc_span::Span; use tracing::instrument; use super::{Clause, InstantiatedPredicates, ParamConst, ParamTy, Ty, TyCtxt}; +use crate::ty; +use crate::ty::{EarlyBinder, GenericArgsRef}; #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)] pub enum GenericParamDefKind { diff --git a/compiler/rustc_middle/src/ty/impls_ty.rs b/compiler/rustc_middle/src/ty/impls_ty.rs index 9be7370a1c21c..b5b7b8bcfef00 100644 --- a/compiler/rustc_middle/src/ty/impls_ty.rs +++ b/compiler/rustc_middle/src/ty/impls_ty.rs @@ -1,18 +1,20 @@ //! This module contains `HashStable` implementations for various data types //! from `rustc_middle::ty` in no particular order. -use crate::middle::region; -use crate::mir; -use crate::ty; +use std::cell::RefCell; +use std::ptr; + use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; -use rustc_data_structures::stable_hasher::HashingControls; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey}; +use rustc_data_structures::stable_hasher::{ + HashStable, HashingControls, StableHasher, ToStableHashKey, +}; use rustc_query_system::ich::StableHashingContext; -use std::cell::RefCell; -use std::ptr; use tracing::trace; +use crate::middle::region; +use crate::{mir, ty}; + impl<'a, 'tcx, H, T> HashStable> for &'tcx ty::list::RawList where T: HashStable>, diff --git a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs index afdf2cbc72667..698104b0462e3 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs @@ -43,13 +43,13 @@ //! This code should only compile in modules where the uninhabitedness of `Foo` //! is visible. +use rustc_type_ir::TyKind::*; +use tracing::instrument; + use crate::query::Providers; use crate::ty::context::TyCtxt; use crate::ty::{self, DefId, Ty, TypeVisitableExt, VariantDef, Visibility}; -use rustc_type_ir::TyKind::*; -use tracing::instrument; - pub mod inhabited_predicate; pub use inhabited_predicate::InhabitedPredicate; diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 6e64e9bc4f87a..0496c571f5e0a 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -1,10 +1,7 @@ -use crate::error; -use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use crate::ty::print::{shrunk_instance_name, FmtPrinter, Printer}; -use crate::ty::{ - self, EarlyBinder, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, - TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, -}; +use std::assert_matches::assert_matches; +use std::fmt; +use std::path::PathBuf; + use rustc_data_structures::fx::FxHashMap; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; @@ -18,9 +15,13 @@ use rustc_span::def_id::LOCAL_CRATE; use rustc_span::{Span, Symbol, DUMMY_SP}; use tracing::{debug, instrument}; -use std::assert_matches::assert_matches; -use std::fmt; -use std::path::PathBuf; +use crate::error; +use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; +use crate::ty::print::{shrunk_instance_name, FmtPrinter, Printer}; +use crate::ty::{ + self, EarlyBinder, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, + TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, +}; /// An `InstanceKind` along with the args that are needed to substitute the instance. /// diff --git a/compiler/rustc_middle/src/ty/intrinsic.rs b/compiler/rustc_middle/src/ty/intrinsic.rs index 68c1d8c17ec11..41a966da8aa49 100644 --- a/compiler/rustc_middle/src/ty/intrinsic.rs +++ b/compiler/rustc_middle/src/ty/intrinsic.rs @@ -1,5 +1,6 @@ use rustc_macros::{Decodable, Encodable, HashStable}; -use rustc_span::{def_id::DefId, Symbol}; +use rustc_span::def_id::DefId; +use rustc_span::Symbol; use super::TyCtxt; diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 22a6786665ca1..d7d27975f60a9 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -1,8 +1,8 @@ -use crate::error::UnsupportedFnAbi; -use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use crate::query::TyCtxtAt; -use crate::ty::normalize_erasing_regions::NormalizationError; -use crate::ty::{self, CoroutineArgsExt, Ty, TyCtxt, TypeVisitableExt}; +use std::borrow::Cow; +use std::num::NonZero; +use std::ops::Bound; +use std::{cmp, fmt}; + use rustc_error_messages::DiagMessage; use rustc_errors::{ Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level, @@ -17,16 +17,15 @@ use rustc_span::symbol::{sym, Symbol}; use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; use rustc_target::abi::call::FnAbi; use rustc_target::abi::*; -use rustc_target::spec::{ - abi::Abi as SpecAbi, HasTargetSpec, HasWasmCAbiOpt, PanicStrategy, Target, WasmCAbi, -}; +use rustc_target::spec::abi::Abi as SpecAbi; +use rustc_target::spec::{HasTargetSpec, HasWasmCAbiOpt, PanicStrategy, Target, WasmCAbi}; use tracing::debug; -use std::borrow::Cow; -use std::cmp; -use std::fmt; -use std::num::NonZero; -use std::ops::Bound; +use crate::error::UnsupportedFnAbi; +use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; +use crate::query::TyCtxtAt; +use crate::ty::normalize_erasing_regions::NormalizationError; +use crate::ty::{self, CoroutineArgsExt, Ty, TyCtxt, TypeVisitableExt}; #[extension(pub trait IntegerExt)] impl Integer { @@ -231,8 +230,9 @@ pub enum LayoutError<'tcx> { impl<'tcx> LayoutError<'tcx> { pub fn diagnostic_message(&self) -> DiagMessage { - use crate::fluent_generated::*; use LayoutError::*; + + use crate::fluent_generated::*; match self { Unknown(_) => middle_unknown_layout, SizeOverflow(_) => middle_values_too_big, @@ -243,8 +243,9 @@ impl<'tcx> LayoutError<'tcx> { } pub fn into_diagnostic(self) -> crate::error::LayoutError<'tcx> { - use crate::error::LayoutError as E; use LayoutError::*; + + use crate::error::LayoutError as E; match self { Unknown(ty) => E::Unknown { ty }, SizeOverflow(ty) => E::Overflow { ty }, diff --git a/compiler/rustc_middle/src/ty/list.rs b/compiler/rustc_middle/src/ty/list.rs index 73eba93194e1e..1a1acf36d77a4 100644 --- a/compiler/rustc_middle/src/ty/list.rs +++ b/compiler/rustc_middle/src/ty/list.rs @@ -1,20 +1,17 @@ -use super::flags::FlagComputation; -use super::{DebruijnIndex, TypeFlags}; -use crate::arena::Arena; -use rustc_data_structures::aligned::{align_of, Aligned}; -use rustc_serialize::{Encodable, Encoder}; use std::alloc::Layout; use std::cmp::Ordering; -use std::fmt; use std::hash::{Hash, Hasher}; -use std::iter; -use std::mem; use std::ops::Deref; -use std::ptr; -use std::slice; +use std::{fmt, iter, mem, ptr, slice}; +use rustc_data_structures::aligned::{align_of, Aligned}; #[cfg(parallel_compiler)] use rustc_data_structures::sync::DynSync; +use rustc_serialize::{Encodable, Encoder}; + +use super::flags::FlagComputation; +use super::{DebruijnIndex, TypeFlags}; +use crate::arena::Arena; /// `List` is a bit like `&[T]`, but with some critical differences. /// - IMPORTANT: Every `List` is *required* to have unique contents. The diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 558590af7ec19..9736428e6f7c7 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -11,37 +11,28 @@ #![allow(rustc::usage_of_ty_tykind)] -pub use self::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable}; -pub use self::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; -pub use self::AssocItemContainer::*; -pub use self::BorrowKind::*; -pub use self::IntVarValue::*; -use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason}; -use crate::metadata::ModChild; -use crate::middle::privacy::EffectiveVisibilities; -use crate::mir::{Body, CoroutineLayout}; -use crate::query::Providers; -use crate::traits::{self, Reveal}; -use crate::ty; -use crate::ty::fast_reject::SimplifiedType; -use crate::ty::util::Discr; +use std::assert_matches::assert_matches; +use std::fmt::Debug; +use std::hash::{Hash, Hasher}; +use std::marker::PhantomData; +use std::num::NonZero; +use std::ptr::NonNull; +use std::{fmt, mem, str}; + pub use adt::*; pub use assoc::*; pub use generic_args::{GenericArgKind, TermKind, *}; pub use generics::*; pub use intrinsic::IntrinsicDef; -use rustc_ast as ast; use rustc_ast::expand::StrippedCfgItem; use rustc_ast::node_id::NodeMap; pub use rustc_ast_ir::{try_visit, Movability, Mutability}; -use rustc_attr as attr; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::steal::Steal; use rustc_data_structures::tagged_ptr::CopyTaggedPtr; use rustc_errors::{Diag, ErrorGuaranteed, StashKey}; -use rustc_hir as hir; use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap}; use rustc_index::IndexVec; @@ -59,24 +50,14 @@ use rustc_span::{ExpnId, ExpnKind, Span}; use rustc_target::abi::{Align, FieldIdx, Integer, IntegerType, VariantIdx}; pub use rustc_target::abi::{ReprFlags, ReprOptions}; pub use rustc_type_ir::relate::VarianceDiagInfo; -use tracing::{debug, instrument}; -pub use vtable::*; - -use std::assert_matches::assert_matches; -use std::fmt::Debug; -use std::hash::{Hash, Hasher}; -use std::marker::PhantomData; -use std::mem; -use std::num::NonZero; -use std::ptr::NonNull; -use std::{fmt, str}; - -pub use crate::ty::diagnostics::*; pub use rustc_type_ir::ConstKind::{ Bound as BoundCt, Error as ErrorCt, Expr as ExprCt, Infer as InferCt, Param as ParamCt, Placeholder as PlaceholderCt, Unevaluated, Value, }; pub use rustc_type_ir::*; +use tracing::{debug, instrument}; +pub use vtable::*; +use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; pub use self::closure::{ analyze_coroutine_closure_captures, is_ancestor_or_same_capture, place_to_string_for_capture, @@ -91,6 +72,7 @@ pub use self::context::{ tls, CtxtInterners, CurrentGcx, DeducedParamAttrs, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed, }; +pub use self::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable}; pub use self::instance::{Instance, InstanceKind, ReifyReason, ShortInstance, UnusedGenericParams}; pub use self::list::{List, ListWithCachedTypeInfo}; pub use self::opaque_types::OpaqueTypeKey; @@ -105,9 +87,9 @@ pub use self::predicate::{ PredicateKind, ProjectionPredicate, RegionOutlivesPredicate, SubtypePredicate, ToPolyTraitRef, TraitPredicate, TraitRef, TypeOutlivesPredicate, }; +pub use self::region::BoundRegionKind::*; pub use self::region::{ - BoundRegion, BoundRegionKind, BoundRegionKind::*, EarlyParamRegion, LateParamRegion, Region, - RegionKind, RegionVid, + BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, Region, RegionKind, RegionVid, }; pub use self::rvalue_scopes::RvalueScopes; pub use self::sty::{ @@ -120,6 +102,20 @@ pub use self::typeck_results::{ CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity, TypeckResults, UserType, UserTypeAnnotationIndex, }; +pub use self::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; +pub use self::AssocItemContainer::*; +pub use self::BorrowKind::*; +pub use self::IntVarValue::*; +use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason}; +use crate::metadata::ModChild; +use crate::middle::privacy::EffectiveVisibilities; +use crate::mir::{Body, CoroutineLayout}; +use crate::query::Providers; +use crate::traits::{self, Reveal}; +use crate::ty; +pub use crate::ty::diagnostics::*; +use crate::ty::fast_reject::SimplifiedType; +use crate::ty::util::Discr; pub mod abstract_const; pub mod adjustment; @@ -2148,8 +2144,9 @@ pub struct DestructuredConst<'tcx> { // Some types are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(PredicateKind<'_>, 32); static_assert_size!(WithCachedTypeInfo>, 56); diff --git a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs index 96f00e1d3063a..e51d220192273 100644 --- a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs +++ b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs @@ -7,11 +7,12 @@ //! `normalize_generic_arg_after_erasing_regions` query for each type //! or constant found within. (This underlying query is what is cached.) +use rustc_macros::{HashStable, TyDecodable, TyEncodable}; +use tracing::{debug, instrument}; + use crate::traits::query::NoSolution; use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder}; use crate::ty::{self, EarlyBinder, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt}; -use rustc_macros::{HashStable, TyDecodable, TyEncodable}; -use tracing::{debug, instrument}; #[derive(Debug, Copy, Clone, HashStable, TyEncodable, TyDecodable)] pub enum NormalizationError<'tcx> { diff --git a/compiler/rustc_middle/src/ty/opaque_types.rs b/compiler/rustc_middle/src/ty/opaque_types.rs index 70a54e96d3678..d3f44326c272d 100644 --- a/compiler/rustc_middle/src/ty/opaque_types.rs +++ b/compiler/rustc_middle/src/ty/opaque_types.rs @@ -1,12 +1,12 @@ -use crate::error::ConstNotUsedTraitAlias; -use crate::ty::fold::{TypeFolder, TypeSuperFoldable}; -use crate::ty::{self, Ty, TyCtxt, TypeFoldable}; -use crate::ty::{GenericArg, GenericArgKind}; use rustc_data_structures::fx::FxHashMap; use rustc_span::def_id::DefId; use rustc_span::Span; use tracing::{debug, instrument, trace}; +use crate::error::ConstNotUsedTraitAlias; +use crate::ty::fold::{TypeFolder, TypeSuperFoldable}; +use crate::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt, TypeFoldable}; + pub type OpaqueTypeKey<'tcx> = rustc_type_ir::OpaqueTypeKey>; /// Converts generic params of a TypeFoldable from one diff --git a/compiler/rustc_middle/src/ty/parameterized.rs b/compiler/rustc_middle/src/ty/parameterized.rs index f394b3c990ce5..7e1255f606c35 100644 --- a/compiler/rustc_middle/src/ty/parameterized.rs +++ b/compiler/rustc_middle/src/ty/parameterized.rs @@ -1,7 +1,8 @@ +use std::hash::Hash; + use rustc_data_structures::unord::UnordMap; use rustc_hir::def_id::DefIndex; use rustc_index::{Idx, IndexVec}; -use std::hash::Hash; use crate::ty; diff --git a/compiler/rustc_middle/src/ty/pattern.rs b/compiler/rustc_middle/src/ty/pattern.rs index d1875fbaea376..e604aedd05e32 100644 --- a/compiler/rustc_middle/src/ty/pattern.rs +++ b/compiler/rustc_middle/src/ty/pattern.rs @@ -1,9 +1,10 @@ use std::fmt; -use crate::ty; use rustc_data_structures::intern::Interned; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; +use crate::ty; + #[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable)] #[rustc_pass_by_value] pub struct Pattern<'tcx>(pub Interned<'tcx, PatternKind<'tcx>>); diff --git a/compiler/rustc_middle/src/ty/predicate.rs b/compiler/rustc_middle/src/ty/predicate.rs index 5d6352c57ce6a..8e72505b86200 100644 --- a/compiler/rustc_middle/src/ty/predicate.rs +++ b/compiler/rustc_middle/src/ty/predicate.rs @@ -1,9 +1,10 @@ +use std::cmp::Ordering; + use rustc_data_structures::captures::Captures; use rustc_data_structures::intern::Interned; use rustc_hir::def_id::DefId; use rustc_macros::{extension, HashStable}; use rustc_type_ir as ir; -use std::cmp::Ordering; use tracing::instrument; use crate::ty::{ diff --git a/compiler/rustc_middle/src/ty/print/mod.rs b/compiler/rustc_middle/src/ty/print/mod.rs index c165790548d75..6cce79dfdc1cf 100644 --- a/compiler/rustc_middle/src/ty/print/mod.rs +++ b/compiler/rustc_middle/src/ty/print/mod.rs @@ -1,8 +1,5 @@ use std::path::PathBuf; -use crate::ty::GenericArg; -use crate::ty::{self, ShortInstance, Ty, TyCtxt}; - use hir::def::Namespace; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::sso::SsoHashSet; @@ -11,10 +8,11 @@ use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; use tracing::{debug, instrument, trace}; +use crate::ty::{self, GenericArg, ShortInstance, Ty, TyCtxt}; + // `pretty` is a separate module only for organization. mod pretty; pub use self::pretty::*; - use super::Lift; pub type PrintError = std::fmt::Error; diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 0e241663e184b..29d72183dd3ff 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -1,11 +1,8 @@ -use crate::mir::interpret::{AllocRange, GlobalAlloc, Pointer, Provenance, Scalar}; -use crate::query::IntoQueryParam; -use crate::query::Providers; -use crate::ty::GenericArgKind; -use crate::ty::{ - ConstInt, Expr, ParamConst, ScalarInt, Term, TermKind, TypeFoldable, TypeSuperFoldable, - TypeSuperVisitable, TypeVisitable, TypeVisitableExt, -}; +use std::cell::Cell; +use std::fmt::{self, Write as _}; +use std::iter; +use std::ops::{Deref, DerefMut}; + use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_apfloat::Float; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; @@ -25,13 +22,14 @@ use rustc_target::spec::abi::Abi; use rustc_type_ir::{elaborate, Upcast as _}; use smallvec::SmallVec; -use std::cell::Cell; -use std::fmt::{self, Write as _}; -use std::iter; -use std::ops::{Deref, DerefMut}; - // `pretty` is a separate module only for organization. use super::*; +use crate::mir::interpret::{AllocRange, GlobalAlloc, Pointer, Provenance, Scalar}; +use crate::query::{IntoQueryParam, Providers}; +use crate::ty::{ + ConstInt, Expr, GenericArgKind, ParamConst, ScalarInt, Term, TermKind, TypeFoldable, + TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, +}; macro_rules! p { (@$lit:literal) => { diff --git a/compiler/rustc_middle/src/ty/region.rs b/compiler/rustc_middle/src/ty/region.rs index 4e85af9017078..a2a961057771a 100644 --- a/compiler/rustc_middle/src/ty/region.rs +++ b/compiler/rustc_middle/src/ty/region.rs @@ -1,13 +1,13 @@ +use std::ops::Deref; + use rustc_data_structures::intern::Interned; use rustc_errors::MultiSpan; use rustc_hir::def_id::DefId; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; -use rustc_span::symbol::sym; -use rustc_span::symbol::{kw, Symbol}; +use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::{ErrorGuaranteed, DUMMY_SP}; use rustc_type_ir::RegionKind as IrRegionKind; pub use rustc_type_ir::RegionVid; -use std::ops::Deref; use tracing::debug; use crate::ty::{self, BoundVar, TyCtxt, TypeFlags}; diff --git a/compiler/rustc_middle/src/ty/rvalue_scopes.rs b/compiler/rustc_middle/src/ty/rvalue_scopes.rs index 8ec7946e71801..bcab54cf8bad0 100644 --- a/compiler/rustc_middle/src/ty/rvalue_scopes.rs +++ b/compiler/rustc_middle/src/ty/rvalue_scopes.rs @@ -1,9 +1,10 @@ -use crate::middle::region::{Scope, ScopeData, ScopeTree}; use rustc_hir as hir; use rustc_hir::ItemLocalMap; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use tracing::debug; +use crate::middle::region::{Scope, ScopeData, ScopeTree}; + /// `RvalueScopes` is a mapping from sub-expressions to _extended_ lifetime as determined by /// rules laid out in `rustc_hir_analysis::check::rvalue_scopes`. #[derive(TyEncodable, TyDecodable, Clone, Debug, Default, Eq, PartialEq, HashStable)] diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 7cdc0e32953de..8fb44a5f0b1b1 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -3,11 +3,8 @@ //! written by hand, though we've recently added some macros and proc-macros //! to help with the tedium. -use crate::mir::interpret; -use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeSuperFoldable}; -use crate::ty::print::{with_no_trimmed_paths, FmtPrinter, Printer}; -use crate::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor}; -use crate::ty::{self, InferConst, Lift, Term, TermKind, Ty, TyCtxt}; +use std::fmt::{self, Debug}; + use rustc_ast_ir::try_visit; use rustc_ast_ir::visit::VisitorResult; use rustc_hir::def::Namespace; @@ -15,12 +12,13 @@ use rustc_span::source_map::Spanned; use rustc_target::abi::TyAndLayout; use rustc_type_ir::ConstKind; -use std::fmt::{self, Debug}; - use super::print::PrettyPrinter; -use super::{GenericArg, GenericArgKind, Region}; - -use super::Pattern; +use super::{GenericArg, GenericArgKind, Pattern, Region}; +use crate::mir::interpret; +use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeSuperFoldable}; +use crate::ty::print::{with_no_trimmed_paths, FmtPrinter, Printer}; +use crate::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor}; +use crate::ty::{self, InferConst, Lift, Term, TermKind, Ty, TyCtxt}; impl fmt::Debug for ty::TraitDef { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index d2b444a066bcc..8c97de1c59b26 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -2,14 +2,11 @@ #![allow(rustc::usage_of_ty_tykind)] -use crate::infer::canonical::Canonical; -use crate::ty::InferTy::*; -use crate::ty::{ - self, AdtDef, BoundRegionKind, Discr, Region, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, - TypeVisitable, TypeVisitor, -}; -use crate::ty::{GenericArg, GenericArgs, GenericArgsRef}; -use crate::ty::{List, ParamEnv}; +use std::assert_matches::debug_assert_matches; +use std::borrow::Cow; +use std::iter; +use std::ops::{ControlFlow, Range}; + use hir::def::{CtorKind, DefKind}; use rustc_data_structures::captures::Captures; use rustc_errors::{ErrorGuaranteed, MultiSpan}; @@ -22,16 +19,17 @@ use rustc_span::{Span, DUMMY_SP}; use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; use rustc_target::spec::abi; use rustc_type_ir::visit::TypeVisitableExt; -use std::assert_matches::debug_assert_matches; -use std::borrow::Cow; -use std::iter; -use std::ops::{ControlFlow, Range}; -use ty::util::{AsyncDropGlueMorphology, IntTypeExt}; - use rustc_type_ir::TyKind::*; use rustc_type_ir::{self as ir, BoundVar, CollectAndApply, DynKind}; +use ty::util::{AsyncDropGlueMorphology, IntTypeExt}; use super::GenericParamDefKind; +use crate::infer::canonical::Canonical; +use crate::ty::InferTy::*; +use crate::ty::{ + self, AdtDef, BoundRegionKind, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv, + Region, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor, +}; // Re-export and re-parameterize some `I = TyCtxt<'tcx>` types here #[rustc_diagnostic_item = "TyKind"] @@ -1864,9 +1862,9 @@ impl<'tcx> Ty<'tcx> { // Definitely absolutely not copy. ty::Ref(_, _, hir::Mutability::Mut) => false, - // Thin pointers & thin shared references are pure-clone-copy, but for - // anything with custom metadata it might be more complicated. - ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => false, + // The standard library has a blanket Copy impl for shared references and raw pointers, + // for all unsized types. + ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => true, ty::Coroutine(..) | ty::CoroutineWitness(..) => false, @@ -1966,8 +1964,9 @@ impl<'tcx> rustc_type_ir::inherent::Tys> for &'tcx ty::List, 24); static_assert_size!(ty::TyKind<'_>, 32); diff --git a/compiler/rustc_middle/src/ty/trait_def.rs b/compiler/rustc_middle/src/ty/trait_def.rs index 3bd9f6ad11b23..dfb137f738f1e 100644 --- a/compiler/rustc_middle/src/ty/trait_def.rs +++ b/compiler/rustc_middle/src/ty/trait_def.rs @@ -1,13 +1,12 @@ use std::iter; -use tracing::debug; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; use rustc_hir::def::DefKind; -use rustc_hir::def_id::DefId; -use rustc_hir::def_id::LOCAL_CRATE; +use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_macros::{Decodable, Encodable, HashStable}; +use tracing::debug; use crate::query::LocalCrate; use crate::traits::specialization_graph; diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index a6dec66449e9f..a92bdb2eae0de 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -1,21 +1,15 @@ -use crate::{ - hir::place::Place as HirPlace, - infer::canonical::Canonical, - traits::ObligationCause, - ty::{ - self, tls, BoundVar, CanonicalPolyFnSig, ClosureSizeProfileData, GenericArgKind, - GenericArgs, GenericArgsRef, Ty, UserArgs, - }, -}; +use std::collections::hash_map::Entry; +use std::hash::Hash; +use std::iter; + use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::unord::{ExtendUnord, UnordItems, UnordSet}; use rustc_errors::ErrorGuaranteed; +use rustc_hir::def::{DefKind, Res}; +use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdMap}; +use rustc_hir::hir_id::OwnerId; use rustc_hir::{ - self as hir, - def::{DefKind, Res}, - def_id::{DefId, LocalDefId, LocalDefIdMap}, - hir_id::OwnerId, - BindingMode, ByRef, HirId, ItemLocalId, ItemLocalMap, ItemLocalSet, Mutability, + self as hir, BindingMode, ByRef, HirId, ItemLocalId, ItemLocalMap, ItemLocalSet, Mutability, }; use rustc_index::IndexVec; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; @@ -23,9 +17,15 @@ use rustc_middle::mir::FakeReadCause; use rustc_session::Session; use rustc_span::Span; use rustc_target::abi::{FieldIdx, VariantIdx}; -use std::{collections::hash_map::Entry, hash::Hash, iter}; use super::RvalueScopes; +use crate::hir::place::Place as HirPlace; +use crate::infer::canonical::Canonical; +use crate::traits::ObligationCause; +use crate::ty::{ + self, tls, BoundVar, CanonicalPolyFnSig, ClosureSizeProfileData, GenericArgKind, GenericArgs, + GenericArgsRef, Ty, UserArgs, +}; #[derive(TyEncodable, TyDecodable, Debug, HashStable)] pub struct TypeckResults<'tcx> { diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 9307e38068128..3cf8531bb62d5 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -1,13 +1,7 @@ //! Miscellaneous type-system utilities that are too small to deserve their own modules. -use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use crate::query::{IntoQueryParam, Providers}; -use crate::ty::layout::{FloatExt, IntegerExt}; -use crate::ty::{ - self, Asyncness, FallibleTypeFolder, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, - TypeVisitableExt, Upcast, -}; -use crate::ty::{GenericArgKind, GenericArgsRef}; +use std::{fmt, iter}; + use rustc_apfloat::Float as _; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher}; @@ -23,9 +17,16 @@ use rustc_span::sym; use rustc_target::abi::{Float, Integer, IntegerType, Size}; use rustc_target::spec::abi::Abi; use smallvec::{smallvec, SmallVec}; -use std::{fmt, iter}; use tracing::{debug, instrument, trace}; +use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; +use crate::query::{IntoQueryParam, Providers}; +use crate::ty::layout::{FloatExt, IntegerExt}; +use crate::ty::{ + self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable, + TypeFolder, TypeSuperFoldable, TypeVisitableExt, Upcast, +}; + #[derive(Copy, Clone, Debug)] pub struct Discr<'tcx> { /// Bit representation of the discriminant (e.g., `-128i8` is `0xFF_u128`). @@ -78,7 +79,7 @@ impl<'tcx> Discr<'tcx> { let (val, oflo) = if signed { let min = size.signed_int_min(); let max = size.signed_int_max(); - let val = size.sign_extend(self.val) as i128; + let val = size.sign_extend(self.val); assert!(n < (i128::MAX as u128)); let n = n as i128; let oflo = val > max - n; @@ -1268,7 +1269,7 @@ impl<'tcx> Ty<'tcx> { /// /// Returning true means the type is known to be `Freeze`. Returning /// `false` means nothing -- could be `Freeze`, might not be. - fn is_trivially_freeze(self) -> bool { + pub fn is_trivially_freeze(self) -> bool { match self.kind() { ty::Int(_) | ty::Uint(_) diff --git a/compiler/rustc_middle/src/ty/visit.rs b/compiler/rustc_middle/src/ty/visit.rs index b1bbfd420e1b1..78d83004c14e1 100644 --- a/compiler/rustc_middle/src/ty/visit.rs +++ b/compiler/rustc_middle/src/ty/visit.rs @@ -1,11 +1,11 @@ -use crate::ty::{self, Binder, Ty, TyCtxt, TypeFlags}; +use std::ops::ControlFlow; use rustc_data_structures::fx::FxHashSet; use rustc_type_ir::fold::TypeFoldable; -use std::ops::ControlFlow; - pub use rustc_type_ir::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; +use crate::ty::{self, Binder, Ty, TyCtxt, TypeFlags}; + /////////////////////////////////////////////////////////////////////////// // Region folder diff --git a/compiler/rustc_middle/src/ty/vtable.rs b/compiler/rustc_middle/src/ty/vtable.rs index 466c3b93f8e5d..f38f27b84f0b9 100644 --- a/compiler/rustc_middle/src/ty/vtable.rs +++ b/compiler/rustc_middle/src/ty/vtable.rs @@ -1,10 +1,11 @@ use std::fmt; -use crate::mir::interpret::{alloc_range, AllocId, Allocation, Pointer, Scalar}; -use crate::ty::{self, Instance, PolyTraitRef, Ty, TyCtxt}; use rustc_ast::Mutability; use rustc_macros::HashStable; +use crate::mir::interpret::{alloc_range, AllocId, Allocation, Pointer, Scalar}; +use crate::ty::{self, Instance, PolyTraitRef, Ty, TyCtxt}; + #[derive(Clone, Copy, PartialEq, HashStable)] pub enum VtblEntry<'tcx> { /// destructor of this type (used in vtable header) diff --git a/compiler/rustc_middle/src/ty/walk.rs b/compiler/rustc_middle/src/ty/walk.rs index efcaf89081f77..2dd7a96f19268 100644 --- a/compiler/rustc_middle/src/ty/walk.rs +++ b/compiler/rustc_middle/src/ty/walk.rs @@ -1,12 +1,12 @@ //! An iterator over the type substructure. //! WARNING: this does not keep track of the region depth. -use crate::ty::{self, Ty}; -use crate::ty::{GenericArg, GenericArgKind}; use rustc_data_structures::sso::SsoHashSet; use smallvec::{smallvec, SmallVec}; use tracing::debug; +use crate::ty::{self, GenericArg, GenericArgKind, Ty}; + // The TypeWalker's stack is hot enough that it's worth going to some effort to // avoid heap allocations. type TypeWalkerStack<'tcx> = SmallVec<[GenericArg<'tcx>; 8]>; diff --git a/compiler/rustc_middle/src/util/bug.rs b/compiler/rustc_middle/src/util/bug.rs index 43853a108960f..32f5251568f1b 100644 --- a/compiler/rustc_middle/src/util/bug.rs +++ b/compiler/rustc_middle/src/util/bug.rs @@ -1,11 +1,13 @@ // These functions are used by macro expansion for bug! and span_bug! -use crate::ty::{tls, TyCtxt}; -use rustc_errors::MultiSpan; -use rustc_span::Span; use std::fmt; use std::panic::{panic_any, Location}; +use rustc_errors::MultiSpan; +use rustc_span::Span; + +use crate::ty::{tls, TyCtxt}; + #[cold] #[inline(never)] #[track_caller] diff --git a/compiler/rustc_middle/src/util/call_kind.rs b/compiler/rustc_middle/src/util/call_kind.rs index 0815c291173de..75ae4e11fa9ea 100644 --- a/compiler/rustc_middle/src/util/call_kind.rs +++ b/compiler/rustc_middle/src/util/call_kind.rs @@ -2,14 +2,14 @@ //! as well as errors when attempting to call a non-const function in a const //! context. -use crate::ty::GenericArgsRef; -use crate::ty::{AssocItemContainer, Instance, ParamEnv, Ty, TyCtxt}; use rustc_hir::def_id::DefId; use rustc_hir::{lang_items, LangItem}; use rustc_span::symbol::Ident; use rustc_span::{sym, DesugaringKind, Span}; use tracing::debug; +use crate::ty::{AssocItemContainer, GenericArgsRef, Instance, ParamEnv, Ty, TyCtxt}; + #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum CallDesugaringKind { /// for _ in x {} calls x.into_iter() diff --git a/compiler/rustc_middle/src/util/find_self_call.rs b/compiler/rustc_middle/src/util/find_self_call.rs index 831853b0b48c3..ec6051d0a771a 100644 --- a/compiler/rustc_middle/src/util/find_self_call.rs +++ b/compiler/rustc_middle/src/util/find_self_call.rs @@ -1,10 +1,10 @@ -use crate::mir::*; -use crate::ty::GenericArgsRef; -use crate::ty::{self, TyCtxt}; use rustc_span::def_id::DefId; use rustc_span::source_map::Spanned; use tracing::debug; +use crate::mir::*; +use crate::ty::{self, GenericArgsRef, TyCtxt}; + /// Checks if the specified `local` is used as the `self` parameter of a method call /// in the provided `BasicBlock`. If it is, then the `DefId` of the called method is /// returned. diff --git a/compiler/rustc_middle/src/values.rs b/compiler/rustc_middle/src/values.rs index 8c323188826b2..9e429f5a4c737 100644 --- a/compiler/rustc_middle/src/values.rs +++ b/compiler/rustc_middle/src/values.rs @@ -1,19 +1,20 @@ -use crate::dep_graph::dep_kinds; -use crate::query::plumbing::CyclePlaceholder; +use std::collections::VecDeque; +use std::fmt::Write; +use std::ops::ControlFlow; + use rustc_data_structures::fx::FxHashSet; -use rustc_errors::{codes::*, pluralize, struct_span_code_err, Applicability, MultiSpan}; +use rustc_errors::codes::*; +use rustc_errors::{pluralize, struct_span_code_err, Applicability, MultiSpan}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_middle::ty::Representability; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Representability, Ty, TyCtxt}; use rustc_query_system::query::{report_cycle, CycleError}; use rustc_query_system::Value; use rustc_span::def_id::LocalDefId; use rustc_span::{ErrorGuaranteed, Span}; -use std::collections::VecDeque; -use std::fmt::Write; -use std::ops::ControlFlow; +use crate::dep_graph::dep_kinds; +use crate::query::plumbing::CyclePlaceholder; impl<'tcx> Value> for Ty<'_> { fn from_cycle_error(tcx: TyCtxt<'tcx>, _: &CycleError, guar: ErrorGuaranteed) -> Self { diff --git a/compiler/rustc_mir_build/messages.ftl b/compiler/rustc_mir_build/messages.ftl index 281f3ef6ef35a..dda4debecec67 100644 --- a/compiler/rustc_mir_build/messages.ftl +++ b/compiler/rustc_mir_build/messages.ftl @@ -325,9 +325,16 @@ mir_build_union_field_requires_unsafe_unsafe_op_in_unsafe_fn_allowed = mir_build_union_pattern = cannot use unions in constant patterns +mir_build_unreachable_making_this_unreachable = collectively making this unreachable + +mir_build_unreachable_matches_same_values = matches some of the same values + mir_build_unreachable_pattern = unreachable pattern .label = unreachable pattern - .catchall_label = matches any value + .unreachable_matches_no_values = this pattern matches no values because `{$ty}` is uninhabited + .unreachable_covered_by_catchall = matches any value + .unreachable_covered_by_one = matches all the values already + .unreachable_covered_by_many = these patterns collectively make the last one unreachable mir_build_unsafe_fn_safe_body = an unsafe function restricts its caller, but its body is safe by default mir_build_unsafe_not_inherited = items do not inherit unsafety from separate enclosing items diff --git a/compiler/rustc_mir_build/src/build/block.rs b/compiler/rustc_mir_build/src/build/block.rs index c608e5c63d842..7afa628843f22 100644 --- a/compiler/rustc_mir_build/src/build/block.rs +++ b/compiler/rustc_mir_build/src/build/block.rs @@ -1,13 +1,14 @@ -use crate::build::matches::{DeclareLetBindings, EmitStorageLive, ScheduleDrops}; -use crate::build::ForGuard::OutsideGuard; -use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; use rustc_middle::middle::region::Scope; -use rustc_middle::span_bug; +use rustc_middle::mir::*; use rustc_middle::thir::*; -use rustc_middle::{mir::*, ty}; +use rustc_middle::{span_bug, ty}; use rustc_span::Span; use tracing::debug; +use crate::build::matches::{DeclareLetBindings, EmitStorageLive, ScheduleDrops}; +use crate::build::ForGuard::OutsideGuard; +use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; + impl<'a, 'tcx> Builder<'a, 'tcx> { pub(crate) fn ast_block( &mut self, diff --git a/compiler/rustc_mir_build/src/build/cfg.rs b/compiler/rustc_mir_build/src/build/cfg.rs index 6034c8fadc57f..e80b654309ea5 100644 --- a/compiler/rustc_mir_build/src/build/cfg.rs +++ b/compiler/rustc_mir_build/src/build/cfg.rs @@ -1,10 +1,11 @@ //! Routines for manipulating the control-flow graph. -use crate::build::CFG; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; use tracing::debug; +use crate::build::CFG; + impl<'tcx> CFG<'tcx> { pub(crate) fn block_data(&self, blk: BasicBlock) -> &BasicBlockData<'tcx> { &self.basic_blocks[blk] diff --git a/compiler/rustc_mir_build/src/build/custom/mod.rs b/compiler/rustc_mir_build/src/build/custom/mod.rs index f6ebcbcbdc949..28477e527c721 100644 --- a/compiler/rustc_mir_build/src/build/custom/mod.rs +++ b/compiler/rustc_mir_build/src/build/custom/mod.rs @@ -22,12 +22,10 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::DefId; use rustc_hir::HirId; use rustc_index::{IndexSlice, IndexVec}; -use rustc_middle::{ - mir::*, - span_bug, - thir::*, - ty::{ParamEnv, Ty, TyCtxt}, -}; +use rustc_middle::mir::*; +use rustc_middle::span_bug; +use rustc_middle::thir::*; +use rustc_middle::ty::{ParamEnv, Ty, TyCtxt}; use rustc_span::Span; mod parse; @@ -56,8 +54,8 @@ pub(super) fn build_custom_mir<'tcx>( spread_arg: None, var_debug_info: Vec::new(), span, - required_consts: Vec::new(), - mentioned_items: Vec::new(), + required_consts: None, + mentioned_items: None, is_polymorphic: false, tainted_by_errors: None, injection_phase: None, diff --git a/compiler/rustc_mir_build/src/build/custom/parse.rs b/compiler/rustc_mir_build/src/build/custom/parse.rs index 9607022c6df04..646aefa08829e 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse.rs +++ b/compiler/rustc_mir_build/src/build/custom/parse.rs @@ -1,6 +1,7 @@ use rustc_index::IndexSlice; +use rustc_middle::mir::*; +use rustc_middle::thir::*; use rustc_middle::ty::{self, Ty}; -use rustc_middle::{mir::*, thir::*}; use rustc_span::Span; use super::{PResult, ParseCtxt, ParseError}; diff --git a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs index 94ab2fb45818d..56896d945e5f3 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs +++ b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs @@ -1,16 +1,17 @@ use rustc_middle::mir::interpret::Scalar; use rustc_middle::mir::tcx::PlaceTy; +use rustc_middle::mir::*; +use rustc_middle::thir::*; +use rustc_middle::ty; use rustc_middle::ty::cast::mir_cast_kind; -use rustc_middle::{mir::*, thir::*, ty}; use rustc_span::source_map::Spanned; use rustc_span::Span; use rustc_target::abi::{FieldIdx, VariantIdx}; +use super::{parse_by_kind, PResult, ParseCtxt}; use crate::build::custom::ParseError; use crate::build::expr::as_constant::as_constant_inner; -use super::{parse_by_kind, PResult, ParseCtxt}; - impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { pub(crate) fn parse_statement(&self, expr_id: ExprId) -> PResult> { parse_by_kind!(self, expr_id, _, "statement", @@ -74,6 +75,9 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { @call(mir_call, args) => { self.parse_call(args) }, + @call(mir_tail_call, args) => { + self.parse_tail_call(args) + }, ExprKind::Match { scrutinee, arms, .. } => { let discr = self.parse_operand(*scrutinee)?; self.parse_match(arms, expr.span).map(|t| TerminatorKind::SwitchInt { discr, targets: t }) @@ -186,6 +190,25 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { ) } + fn parse_tail_call(&self, args: &[ExprId]) -> PResult> { + parse_by_kind!(self, args[0], _, "tail call", + ExprKind::Call { fun, args, fn_span, .. } => { + let fun = self.parse_operand(*fun)?; + let args = args + .iter() + .map(|arg| + Ok(Spanned { node: self.parse_operand(*arg)?, span: self.thir.exprs[*arg].span } ) + ) + .collect::>>()?; + Ok(TerminatorKind::TailCall { + func: fun, + args, + fn_span: *fn_span, + }) + }, + ) + } + fn parse_rvalue(&self, expr_id: ExprId) -> PResult> { parse_by_kind!(self, expr_id, expr, "rvalue", @call(mir_discriminant, args) => self.parse_place(args[0]).map(Rvalue::Discriminant), diff --git a/compiler/rustc_mir_build/src/build/expr/as_constant.rs b/compiler/rustc_mir_build/src/build/expr/as_constant.rs index be62a3d373656..10cf545f1b79d 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_constant.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_constant.rs @@ -1,19 +1,19 @@ //! See docs in build/expr/mod.rs -use crate::build::{parse_float_into_constval, Builder}; use rustc_ast as ast; use rustc_hir::LangItem; -use rustc_middle::mir; use rustc_middle::mir::interpret::{Allocation, LitToConstError, LitToConstInput, Scalar}; use rustc_middle::mir::*; use rustc_middle::thir::*; use rustc_middle::ty::{ self, CanonicalUserType, CanonicalUserTypeAnnotation, Ty, TyCtxt, UserTypeAnnotationIndex, }; -use rustc_middle::{bug, span_bug}; +use rustc_middle::{bug, mir, span_bug}; use rustc_target::abi::Size; use tracing::{instrument, trace}; +use crate::build::{parse_float_into_constval, Builder}; + impl<'a, 'tcx> Builder<'a, 'tcx> { /// Compile `expr`, yielding a compile-time constant. Assumes that /// `expr` is a valid compile-time constant! diff --git a/compiler/rustc_mir_build/src/build/expr/as_operand.rs b/compiler/rustc_mir_build/src/build/expr/as_operand.rs index 09ce134a2bf6c..1e67e759aa20a 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_operand.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_operand.rs @@ -1,12 +1,13 @@ //! See docs in build/expr/mod.rs -use crate::build::expr::category::Category; -use crate::build::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary}; use rustc_middle::middle::region; use rustc_middle::mir::*; use rustc_middle::thir::*; use tracing::{debug, instrument}; +use crate::build::expr::category::Category; +use crate::build::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary}; + impl<'a, 'tcx> Builder<'a, 'tcx> { /// Returns an operand suitable for use until the end of the current /// scope expression. diff --git a/compiler/rustc_mir_build/src/build/expr/as_place.rs b/compiler/rustc_mir_build/src/build/expr/as_place.rs index 91a3b53cc79c7..b80d9de70c8da 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_place.rs @@ -1,24 +1,23 @@ //! See docs in build/expr/mod.rs -use crate::build::expr::category::Category; -use crate::build::ForGuard::{OutsideGuard, RefWithinGuard}; -use crate::build::{BlockAnd, BlockAndExtension, Builder, Capture, CaptureMap}; +use std::assert_matches::assert_matches; +use std::iter; + use rustc_hir::def_id::LocalDefId; -use rustc_middle::hir::place::Projection as HirProjection; -use rustc_middle::hir::place::ProjectionKind as HirProjectionKind; +use rustc_middle::hir::place::{Projection as HirProjection, ProjectionKind as HirProjectionKind}; use rustc_middle::middle::region; use rustc_middle::mir::AssertKind::BoundsCheck; use rustc_middle::mir::*; use rustc_middle::thir::*; -use rustc_middle::ty::AdtDef; -use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, Variance}; +use rustc_middle::ty::{self, AdtDef, CanonicalUserTypeAnnotation, Ty, Variance}; use rustc_middle::{bug, span_bug}; use rustc_span::Span; use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; use tracing::{debug, instrument, trace}; -use std::assert_matches::assert_matches; -use std::iter; +use crate::build::expr::category::Category; +use crate::build::ForGuard::{OutsideGuard, RefWithinGuard}; +use crate::build::{BlockAnd, BlockAndExtension, Builder, Capture, CaptureMap}; /// The "outermost" place that holds this value. #[derive(Copy, Clone, Debug, PartialEq)] diff --git a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs index 40cfe563accea..379d2140c09c5 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs @@ -1,14 +1,7 @@ //! See docs in `build/expr/mod.rs`. -use rustc_index::{Idx, IndexVec}; -use rustc_middle::ty::util::IntTypeExt; -use rustc_span::source_map::Spanned; -use rustc_target::abi::{Abi, FieldIdx, Primitive}; - -use crate::build::expr::as_place::PlaceBase; -use crate::build::expr::category::{Category, RvalueFunc}; -use crate::build::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary}; use rustc_hir::lang_items::LangItem; +use rustc_index::{Idx, IndexVec}; use rustc_middle::bug; use rustc_middle::middle::region; use rustc_middle::mir::interpret::Scalar; @@ -16,10 +9,17 @@ use rustc_middle::mir::*; use rustc_middle::thir::*; use rustc_middle::ty::cast::{mir_cast_kind, CastTy}; use rustc_middle::ty::layout::IntegerExt; +use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, Ty, UpvarArgs}; +use rustc_span::source_map::Spanned; use rustc_span::{Span, DUMMY_SP}; +use rustc_target::abi::{Abi, FieldIdx, Primitive}; use tracing::debug; +use crate::build::expr::as_place::PlaceBase; +use crate::build::expr::category::{Category, RvalueFunc}; +use crate::build::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary}; + impl<'a, 'tcx> Builder<'a, 'tcx> { /// Returns an rvalue suitable for use until the end of the current /// scope expression. diff --git a/compiler/rustc_mir_build/src/build/expr/as_temp.rs b/compiler/rustc_mir_build/src/build/expr/as_temp.rs index 82673582e796d..af5940ff50e61 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_temp.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_temp.rs @@ -1,13 +1,14 @@ //! See docs in build/expr/mod.rs -use crate::build::scope::DropKind; -use crate::build::{BlockAnd, BlockAndExtension, Builder}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_middle::middle::region; use rustc_middle::mir::*; use rustc_middle::thir::*; use tracing::{debug, instrument}; +use crate::build::scope::DropKind; +use crate::build::{BlockAnd, BlockAndExtension, Builder}; + impl<'a, 'tcx> Builder<'a, 'tcx> { /// Compile `expr` into a fresh temporary. This is used when building /// up rvalues so as to freeze the value that will be consumed. diff --git a/compiler/rustc_mir_build/src/build/expr/into.rs b/compiler/rustc_mir_build/src/build/expr/into.rs index 9cd958a21da4d..01b32b8e05e49 100644 --- a/compiler/rustc_mir_build/src/build/expr/into.rs +++ b/compiler/rustc_mir_build/src/build/expr/into.rs @@ -1,8 +1,7 @@ //! See docs in build/expr/mod.rs -use crate::build::expr::category::{Category, RvalueFunc}; -use crate::build::matches::DeclareLetBindings; -use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder, NeedsTemporary}; +use std::iter; + use rustc_ast::InlineAsmOptions; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::stack::ensure_sufficient_stack; @@ -12,9 +11,12 @@ use rustc_middle::span_bug; use rustc_middle::thir::*; use rustc_middle::ty::CanonicalUserTypeAnnotation; use rustc_span::source_map::Spanned; -use std::iter; use tracing::{debug, instrument}; +use crate::build::expr::category::{Category, RvalueFunc}; +use crate::build::matches::DeclareLetBindings; +use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder, NeedsTemporary}; + impl<'a, 'tcx> Builder<'a, 'tcx> { /// Compile `expr`, storing the result into `destination`, which /// is assumed to be uninitialized. diff --git a/compiler/rustc_mir_build/src/build/expr/stmt.rs b/compiler/rustc_mir_build/src/build/expr/stmt.rs index 8e13edb4c89b7..b38f0a41e5d21 100644 --- a/compiler/rustc_mir_build/src/build/expr/stmt.rs +++ b/compiler/rustc_mir_build/src/build/expr/stmt.rs @@ -1,5 +1,3 @@ -use crate::build::scope::BreakableTarget; -use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; use rustc_middle::middle::region; use rustc_middle::mir::*; use rustc_middle::span_bug; @@ -7,6 +5,9 @@ use rustc_middle::thir::*; use rustc_span::source_map::Spanned; use tracing::debug; +use crate::build::scope::BreakableTarget; +use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; + impl<'a, 'tcx> Builder<'a, 'tcx> { /// Builds a block of MIR statements to evaluate the THIR `expr`. /// diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/build/matches/mod.rs index 95bc8b3d0cbc4..cae4aa7bad3d2 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/build/matches/mod.rs @@ -5,12 +5,8 @@ //! This also includes code for pattern bindings in `let` statements and //! function parameters. -use crate::build::expr::as_place::PlaceBuilder; -use crate::build::scope::DropKind; -use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard}; -use crate::build::{BlockAnd, BlockAndExtension, Builder}; -use crate::build::{GuardFrame, GuardFrameLocal, LocalsForNode}; -use rustc_data_structures::{fx::FxIndexMap, stack::ensure_sufficient_stack}; +use rustc_data_structures::fx::FxIndexMap; +use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir::{BindingMode, ByRef}; use rustc_middle::bug; use rustc_middle::middle::region; @@ -21,7 +17,13 @@ use rustc_span::symbol::Symbol; use rustc_span::{BytePos, Pos, Span}; use rustc_target::abi::VariantIdx; use tracing::{debug, instrument}; -use util::visit_bindings; + +use crate::build::expr::as_place::PlaceBuilder; +use crate::build::scope::DropKind; +use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard}; +use crate::build::{ + BlockAnd, BlockAndExtension, Builder, GuardFrame, GuardFrameLocal, LocalsForNode, +}; // helper functions, broken out by category: mod match_pair; @@ -363,28 +365,22 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let scrutinee_place = unpack!(block = self.lower_scrutinee(block, scrutinee_id, scrutinee_span)); - let mut arm_candidates = self.create_match_candidates(&scrutinee_place, arms); - - let match_has_guard = arm_candidates.iter().any(|(_, candidate)| candidate.has_guard); - let mut candidates = - arm_candidates.iter_mut().map(|(_, candidate)| candidate).collect::>(); - + let arms = arms.iter().map(|arm| &self.thir[*arm]); let match_start_span = span.shrink_to_lo().to(scrutinee_span); - - // The set of places that we are creating fake borrows of. If there are no match guards then - // we don't need any fake borrows, so don't track them. - let fake_borrow_temps: Vec<(Place<'tcx>, Local, FakeBorrowKind)> = if match_has_guard { - util::collect_fake_borrows(self, &candidates, scrutinee_span, scrutinee_place.base()) - } else { - Vec::new() - }; - - self.lower_match_tree( + let patterns = arms + .clone() + .map(|arm| { + let has_match_guard = + if arm.guard.is_some() { HasMatchGuard::Yes } else { HasMatchGuard::No }; + (&*arm.pattern, has_match_guard) + }) + .collect(); + let built_tree = self.lower_match_tree( block, scrutinee_span, &scrutinee_place, match_start_span, - &mut candidates, + patterns, false, ); @@ -392,9 +388,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { destination, scrutinee_place, scrutinee_span, - arm_candidates, + arms, + built_tree, self.source_info(span), - fake_borrow_temps, ) } @@ -414,51 +410,29 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { block.and(scrutinee_place_builder) } - /// Create the initial `Candidate`s for a `match` expression. - fn create_match_candidates<'pat>( - &mut self, - scrutinee: &PlaceBuilder<'tcx>, - arms: &'pat [ArmId], - ) -> Vec<(&'pat Arm<'tcx>, Candidate<'pat, 'tcx>)> - where - 'a: 'pat, - { - // Assemble the initial list of candidates. These top-level candidates - // are 1:1 with the original match arms, but other parts of match - // lowering also introduce subcandidates (for subpatterns), and will - // also flatten candidates in some cases. So in general a list of - // candidates does _not_ necessarily correspond to a list of arms. - arms.iter() - .copied() - .map(|arm| { - let arm = &self.thir[arm]; - let arm_has_guard = arm.guard.is_some(); - let arm_candidate = - Candidate::new(scrutinee.clone(), &arm.pattern, arm_has_guard, self); - (arm, arm_candidate) - }) - .collect() - } - /// Lower the bindings, guards and arm bodies of a `match` expression. /// /// The decision tree should have already been created /// (by [Builder::lower_match_tree]). /// /// `outer_source_info` is the SourceInfo for the whole match. - fn lower_match_arms( + fn lower_match_arms<'pat>( &mut self, destination: Place<'tcx>, scrutinee_place_builder: PlaceBuilder<'tcx>, scrutinee_span: Span, - arm_candidates: Vec<(&'_ Arm<'tcx>, Candidate<'_, 'tcx>)>, + arms: impl IntoIterator>, + built_match_tree: BuiltMatchTree<'tcx>, outer_source_info: SourceInfo, - fake_borrow_temps: Vec<(Place<'tcx>, Local, FakeBorrowKind)>, - ) -> BlockAnd<()> { - let arm_end_blocks: Vec = arm_candidates + ) -> BlockAnd<()> + where + 'tcx: 'pat, + { + let arm_end_blocks: Vec = arms .into_iter() - .map(|(arm, candidate)| { - debug!("lowering arm {:?}\ncandidate = {:?}", arm, candidate); + .zip(built_match_tree.branches) + .map(|(arm, branch)| { + debug!("lowering arm {:?}\ncorresponding branch = {:?}", arm, branch); let arm_source_info = self.source_info(arm.span); let arm_scope = (arm.scope, arm_source_info); @@ -491,8 +465,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let arm_block = this.bind_pattern( outer_source_info, - candidate, - &fake_borrow_temps, + branch, + &built_match_tree.fake_borrow_temps, scrutinee_span, Some((arm, match_scope)), EmitStorageLive::Yes, @@ -528,27 +502,34 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { end_block.unit() } - /// Binds the variables and ascribes types for a given `match` arm or - /// `let` binding. + /// For a top-level `match` arm or a `let` binding, binds the variables and + /// ascribes types, and also checks the match arm guard (if present). /// - /// Also check if the guard matches, if it's provided. /// `arm_scope` should be `Some` if and only if this is called for a /// `match` arm. + /// + /// In the presence of or-patterns, a match arm might have multiple + /// sub-branches representing different ways to match, with each sub-branch + /// requiring its own bindings and its own copy of the guard. This method + /// handles those sub-branches individually, and then has them jump together + /// to a common block. + /// + /// Returns a single block that the match arm can be lowered into. + /// (For `let` bindings, this is the code that can use the bindings.) fn bind_pattern( &mut self, outer_source_info: SourceInfo, - candidate: Candidate<'_, 'tcx>, + branch: MatchTreeBranch<'tcx>, fake_borrow_temps: &[(Place<'tcx>, Local, FakeBorrowKind)], scrutinee_span: Span, arm_match_scope: Option<(&Arm<'tcx>, region::Scope)>, emit_storage_live: EmitStorageLive, ) -> BasicBlock { - if candidate.subcandidates.is_empty() { - // Avoid generating another `BasicBlock` when we only have one - // candidate. + if branch.sub_branches.len() == 1 { + let [sub_branch] = branch.sub_branches.try_into().unwrap(); + // Avoid generating another `BasicBlock` when we only have one sub branch. self.bind_and_guard_matched_candidate( - candidate, - &[], + sub_branch, fake_borrow_temps, scrutinee_span, arm_match_scope, @@ -576,35 +557,23 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // We keep a stack of all of the bindings and type ascriptions // from the parent candidates that we visit, that also need to // be bound for each candidate. - traverse_candidate( - candidate, - &mut Vec::new(), - &mut |leaf_candidate, parent_data| { - if let Some(arm) = arm { - self.clear_top_scope(arm.scope); - } - let binding_end = self.bind_and_guard_matched_candidate( - leaf_candidate, - parent_data, - fake_borrow_temps, - scrutinee_span, - arm_match_scope, - schedule_drops, - emit_storage_live, - ); - if arm.is_none() { - schedule_drops = ScheduleDrops::No; - } - self.cfg.goto(binding_end, outer_source_info, target_block); - }, - |inner_candidate, parent_data| { - parent_data.push(inner_candidate.extra_data); - inner_candidate.subcandidates.into_iter() - }, - |parent_data| { - parent_data.pop(); - }, - ); + for sub_branch in branch.sub_branches { + if let Some(arm) = arm { + self.clear_top_scope(arm.scope); + } + let binding_end = self.bind_and_guard_matched_candidate( + sub_branch, + fake_borrow_temps, + scrutinee_span, + arm_match_scope, + schedule_drops, + emit_storage_live, + ); + if arm.is_none() { + schedule_drops = ScheduleDrops::No; + } + self.cfg.goto(binding_end, outer_source_info, target_block); + } target_block } @@ -638,12 +607,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Optimize the case of `let x: T = ...` to write directly // into `x` and then require that `T == typeof(x)`. - // - // Weirdly, this is needed to prevent the - // `intrinsic-move-val.rs` test case from crashing. That - // test works with uninitialized values in a rather - // dubious way, so it may be that the test is kind of - // broken. PatKind::AscribeUserType { subpattern: box Pat { @@ -720,7 +683,15 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { initializer: PlaceBuilder<'tcx>, set_match_place: bool, ) -> BlockAnd<()> { - let mut candidate = Candidate::new(initializer.clone(), irrefutable_pat, false, self); + let built_tree = self.lower_match_tree( + block, + irrefutable_pat.span, + &initializer, + irrefutable_pat.span, + vec![(irrefutable_pat, HasMatchGuard::No)], + false, + ); + let [branch] = built_tree.branches.try_into().unwrap(); // For matches and function arguments, the place that is being matched // can be set when creating the variables. But the place for @@ -741,7 +712,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // }; // ``` if let Some(place) = initializer.try_to_place(self) { - visit_bindings(&[&mut candidate], |binding: &Binding<'_>| { + // Because or-alternatives bind the same variables, we only explore the first one. + let first_sub_branch = branch.sub_branches.first().unwrap(); + for binding in &first_sub_branch.bindings { let local = self.var_local_id(binding.var_id, OutsideGuard); if let LocalInfo::User(BindingForm::Var(VarBindingForm { opt_match_place: Some((ref mut match_place, _)), @@ -752,21 +725,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } else { bug!("Let binding to non-user variable.") }; - }); + } } } - self.lower_match_tree( - block, - irrefutable_pat.span, - &initializer, - irrefutable_pat.span, - &mut [&mut candidate], - false, - ); self.bind_pattern( self.source_info(irrefutable_pat.span), - candidate, + branch, &[], irrefutable_pat.span, None, @@ -1022,7 +987,8 @@ impl<'tcx> PatternExtraData<'tcx> { } } -/// A pattern in a form suitable for generating code. +/// A pattern in a form suitable for lowering the match tree, with all irrefutable +/// patterns simplified away, and or-patterns sorted to the end. /// /// Here, "flat" indicates that the pattern's match pairs have been recursively /// simplified by [`Builder::simplify_match_pairs`]. They are not necessarily @@ -1055,36 +1021,89 @@ impl<'tcx, 'pat> FlatPat<'pat, 'tcx> { ascriptions: Vec::new(), is_never: pattern.is_never_pattern(), }; - // Partly-flatten and sort the match pairs, while recording extra data. + // Recursively remove irrefutable match pairs, while recording their + // bindings/ascriptions, and sort or-patterns after other match pairs. cx.simplify_match_pairs(&mut match_pairs, &mut extra_data); Self { match_pairs, extra_data } } } +/// Candidates are a generalization of (a) top-level match arms, and +/// (b) sub-branches of or-patterns, allowing the match-lowering process to handle +/// them both in a mostly-uniform way. For example, the list of candidates passed +/// to [`Builder::match_candidates`] will often contain a mixture of top-level +/// candidates and or-pattern subcandidates. +/// +/// At the start of match lowering, there is one candidate for each match arm. +/// During match lowering, arms with or-patterns will be expanded into a tree +/// of candidates, where each "leaf" candidate represents one of the ways for +/// the arm pattern to successfully match. #[derive(Debug)] struct Candidate<'pat, 'tcx> { /// For the candidate to match, all of these must be satisfied... - // Invariant: all the match pairs are recursively simplified. - // Invariant: or-patterns must be sorted at the end. + /// + /// --- + /// Initially contains a list of match pairs created by [`FlatPat`], but is + /// subsequently mutated (in a queue-like way) while lowering the match tree. + /// When this list becomes empty, the candidate is fully matched and becomes + /// a leaf (see [`Builder::select_matched_candidate`]). + /// + /// Key mutations include: + /// + /// - When a match pair is fully satisfied by a test, it is removed from the + /// list, and its subpairs are added instead (see [`Builder::sort_candidate`]). + /// - During or-pattern expansion, any leading or-pattern is removed, and is + /// converted into subcandidates (see [`Builder::expand_and_match_or_candidates`]). + /// - After a candidate's subcandidates have been lowered, a copy of any remaining + /// or-patterns is added to each leaf subcandidate + /// (see [`Builder::test_remaining_match_pairs_after_or`]). + /// + /// Invariants: + /// - All [`TestCase::Irrefutable`] patterns have been removed by simplification. + /// - All or-patterns ([`TestCase::Or`]) have been sorted to the end. match_pairs: Vec>, /// ...and if this is non-empty, one of these subcandidates also has to match... - // Invariant: at the end of the algorithm, this must never contain a `is_never` candidate - // because that would break binding consistency. + /// + /// --- + /// Initially a candidate has no subcandidates; they are added (and then immediately + /// lowered) during or-pattern expansion. Their main function is to serve as _output_ + /// of match tree lowering, allowing later steps to see the leaf candidates that + /// represent a match of the entire match arm. + /// + /// A candidate no subcandidates is either incomplete (if it has match pairs left), + /// or is a leaf in the match tree. A candidate with one or more subcandidates is + /// an internal node in the match tree. + /// + /// Invariant: at the end of match tree lowering, this must not contain an + /// `is_never` candidate, because that would break binding consistency. + /// - See [`Builder::remove_never_subcandidates`]. subcandidates: Vec>, /// ...and if there is a guard it must be evaluated; if it's `false` then branch to `otherwise_block`. + /// + /// --- + /// For subcandidates, this is copied from the parent candidate, so it indicates + /// whether the enclosing match arm has a guard. has_guard: bool, - /// If the candidate matches, bindings and ascriptions must be established. + /// Holds extra pattern data that was prepared by [`FlatPat`], including bindings and + /// ascriptions that must be established if this candidate succeeds. extra_data: PatternExtraData<'tcx>, - /// If we filled `self.subcandidate`, we store here the span of the or-pattern they came from. - // Invariant: it is `None` iff `subcandidates.is_empty()`. + /// When setting `self.subcandidates`, we store here the span of the or-pattern they came from. + /// + /// --- + /// Invariant: it is `None` iff `subcandidates.is_empty()`. + /// - FIXME: We sometimes don't unset this when clearing `subcandidates`. or_span: Option, /// The block before the `bindings` have been established. + /// + /// After the match tree has been lowered, [`Builder::lower_match_arms`] + /// will use this as the start point for lowering bindings and guards, and + /// then jump to a shared block containing the arm body. pre_binding_block: Option, /// The block to branch to if the guard or a nested candidate fails to match. @@ -1093,20 +1112,21 @@ struct Candidate<'pat, 'tcx> { /// The earliest block that has only candidates >= this one as descendents. Used for false /// edges, see the doc for [`Builder::match_expr`]. false_edge_start_block: Option, - /// The `false_edge_start_block` of the next candidate. - next_candidate_start_block: Option, } impl<'tcx, 'pat> Candidate<'pat, 'tcx> { fn new( place: PlaceBuilder<'tcx>, pattern: &'pat Pat<'tcx>, - has_guard: bool, + has_guard: HasMatchGuard, cx: &mut Builder<'_, 'tcx>, ) -> Self { // Use `FlatPat` to build simplified match pairs, then immediately // incorporate them into a new candidate. - Self::from_flat_pat(FlatPat::new(place, pattern, cx), has_guard) + Self::from_flat_pat( + FlatPat::new(place, pattern, cx), + matches!(has_guard, HasMatchGuard::Yes), + ) } /// Incorporates an already-simplified [`FlatPat`] into a new candidate. @@ -1120,7 +1140,6 @@ impl<'tcx, 'pat> Candidate<'pat, 'tcx> { otherwise_block: None, pre_binding_block: None, false_edge_start_block: None, - next_candidate_start_block: None, } } @@ -1140,18 +1159,39 @@ impl<'tcx, 'pat> Candidate<'pat, 'tcx> { |_| {}, ); } + + /// Visit the leaf candidates in reverse order. + fn visit_leaves_rev<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) { + traverse_candidate( + self, + &mut (), + &mut move |c, _| visit_leaf(c), + move |c, _| c.subcandidates.iter_mut().rev(), + |_| {}, + ); + } } /// A depth-first traversal of the `Candidate` and all of its recursive /// subcandidates. +/// +/// This signature is very generic, to support traversing candidate trees by +/// reference or by value, and to allow a mutable "context" to be shared by the +/// traversal callbacks. Most traversals can use the simpler +/// [`Candidate::visit_leaves`] wrapper instead. fn traverse_candidate<'pat, 'tcx: 'pat, C, T, I>( candidate: C, context: &mut T, + // Called when visiting a "leaf" candidate (with no subcandidates). visit_leaf: &mut impl FnMut(C, &mut T), + // Called when visiting a "node" candidate (with one or more subcandidates). + // Returns an iterator over the candidate's children (by value or reference). + // Can perform setup before visiting the node's children. get_children: impl Copy + Fn(C, &mut T) -> I, + // Called after visiting a "node" candidate's children. complete_children: impl Copy + Fn(&mut T), ) where - C: Borrow>, + C: Borrow>, // Typically `Candidate` or `&mut Candidate` I: Iterator, { if candidate.borrow().subcandidates.is_empty() { @@ -1182,6 +1222,24 @@ struct Ascription<'tcx> { variance: ty::Variance, } +/// Partial summary of a [`thir::Pat`], indicating what sort of test should be +/// performed to match/reject the pattern, and what the desired test outcome is. +/// This avoids having to perform a full match on [`thir::PatKind`] in some places, +/// and helps [`TestKind::Switch`] and [`TestKind::SwitchInt`] know what target +/// values to use. +/// +/// Created by [`MatchPairTree::for_pattern`], and then inspected primarily by: +/// - [`Builder::pick_test_for_match_pair`] (to choose a test) +/// - [`Builder::sort_candidate`] (to see how the test interacts with a match pair) +/// +/// Two variants are unlike the others and deserve special mention: +/// +/// - [`Self::Irrefutable`] is only used temporarily when building a [`MatchPairTree`]. +/// They are then flattened away by [`Builder::simplify_match_pairs`], with any +/// bindings/ascriptions incorporated into the enclosing [`FlatPat`]. +/// - [`Self::Or`] are not tested directly like the other variants. Instead they +/// participate in or-pattern expansion, where they are transformed into subcandidates. +/// - See [`Builder::expand_and_match_or_candidates`]. #[derive(Debug, Clone)] enum TestCase<'pat, 'tcx> { Irrefutable { binding: Option>, ascription: Option> }, @@ -1224,6 +1282,12 @@ pub(crate) struct MatchPairTree<'pat, 'tcx> { test_case: TestCase<'pat, 'tcx>, /// ... and these subpairs must match. + /// + /// --- + /// Subpairs typically represent tests that can only be performed after their + /// parent has succeeded. For example, the pattern `Some(3)` might have an + /// outer match pair that tests for the variant `Some`, and then a subpair + /// that tests its field for the value `3`. subpairs: Vec, /// The pattern this was created from. @@ -1234,15 +1298,22 @@ pub(crate) struct MatchPairTree<'pat, 'tcx> { #[derive(Clone, Debug, PartialEq)] enum TestKind<'tcx> { /// Test what enum variant a value is. + /// + /// The subset of expected variants is not stored here; instead they are + /// extracted from the [`TestCase`]s of the candidates participating in the + /// test. Switch { /// The enum type being tested. adt_def: ty::AdtDef<'tcx>, }, /// Test what value an integer or `char` has. + /// + /// The test's target values are not stored here; instead they are extracted + /// from the [`TestCase`]s of the candidates participating in the test. SwitchInt, - /// Test what value a `bool` has. + /// Test whether a `bool` is `true` or `false`. If, /// Test for equality with value, possibly after an unsizing coercion to @@ -1258,7 +1329,7 @@ enum TestKind<'tcx> { /// Test whether the value falls within an inclusive or exclusive range. Range(Box>), - /// Test that the length of the slice is equal to `len`. + /// Test that the length of the slice is `== len` or `>= len`. Len { len: u64, op: BinOp }, /// Call `Deref::deref[_mut]` on the value. @@ -1309,12 +1380,114 @@ pub(crate) struct ArmHasGuard(pub(crate) bool); /////////////////////////////////////////////////////////////////////////// // Main matching algorithm +/// A sub-branch in the output of match lowering. Match lowering has generated MIR code that will +/// branch to `success_block` when the matched value matches the corresponding pattern. If there is +/// a guard, its failure must continue to `otherwise_block`, which will resume testing patterns. +#[derive(Debug)] +struct MatchTreeSubBranch<'tcx> { + span: Span, + /// The block that is branched to if the corresponding subpattern matches. + success_block: BasicBlock, + /// The block to branch to if this arm had a guard and the guard fails. + otherwise_block: BasicBlock, + /// The bindings to set up in this sub-branch. + bindings: Vec>, + /// The ascriptions to set up in this sub-branch. + ascriptions: Vec>, + /// Whether the sub-branch corresponds to a never pattern. + is_never: bool, +} + +/// A branch in the output of match lowering. +#[derive(Debug)] +struct MatchTreeBranch<'tcx> { + sub_branches: Vec>, +} + +/// The result of generating MIR for a pattern-matching expression. Each input branch/arm/pattern +/// gives rise to an output `MatchTreeBranch`. If one of the patterns matches, we branch to the +/// corresponding `success_block`. If none of the patterns matches, we branch to `otherwise_block`. +/// +/// Each branch is made of one of more sub-branches, corresponding to or-patterns. E.g. +/// ```ignore(illustrative) +/// match foo { +/// (x, false) | (false, x) => {} +/// (true, true) => {} +/// } +/// ``` +/// Here the first arm gives the first `MatchTreeBranch`, which has two sub-branches, one for each +/// alternative of the or-pattern. They are kept separate because each needs to bind `x` to a +/// different place. +#[derive(Debug)] +struct BuiltMatchTree<'tcx> { + branches: Vec>, + otherwise_block: BasicBlock, + /// If any of the branches had a guard, we collect here the places and locals to fakely borrow + /// to ensure match guards can't modify the values as we match them. For more details, see + /// [`util::collect_fake_borrows`]. + fake_borrow_temps: Vec<(Place<'tcx>, Local, FakeBorrowKind)>, +} + +impl<'tcx> MatchTreeSubBranch<'tcx> { + fn from_sub_candidate( + candidate: Candidate<'_, 'tcx>, + parent_data: &Vec>, + ) -> Self { + debug_assert!(candidate.match_pairs.is_empty()); + MatchTreeSubBranch { + span: candidate.extra_data.span, + success_block: candidate.pre_binding_block.unwrap(), + otherwise_block: candidate.otherwise_block.unwrap(), + bindings: parent_data + .iter() + .flat_map(|d| &d.bindings) + .chain(&candidate.extra_data.bindings) + .cloned() + .collect(), + ascriptions: parent_data + .iter() + .flat_map(|d| &d.ascriptions) + .cloned() + .chain(candidate.extra_data.ascriptions) + .collect(), + is_never: candidate.extra_data.is_never, + } + } +} + +impl<'tcx> MatchTreeBranch<'tcx> { + fn from_candidate(candidate: Candidate<'_, 'tcx>) -> Self { + let mut sub_branches = Vec::new(); + traverse_candidate( + candidate, + &mut Vec::new(), + &mut |candidate: Candidate<'_, '_>, parent_data: &mut Vec>| { + sub_branches.push(MatchTreeSubBranch::from_sub_candidate(candidate, parent_data)); + }, + |inner_candidate, parent_data| { + parent_data.push(inner_candidate.extra_data); + inner_candidate.subcandidates.into_iter() + }, + |parent_data| { + parent_data.pop(); + }, + ); + MatchTreeBranch { sub_branches } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum HasMatchGuard { + Yes, + No, +} + impl<'a, 'tcx> Builder<'a, 'tcx> { /// The entrypoint of the matching algorithm. Create the decision tree for the match expression, /// starting from `block`. /// - /// Modifies `candidates` to store the bindings and type ascriptions for - /// that candidate. + /// `patterns` is a list of patterns, one for each arm. The associated boolean indicates whether + /// the arm has a guard. /// /// `refutable` indicates whether the candidate list is refutable (for `if let` and `let else`) /// or not (for `let` and `match`). In the refutable case we return the block to which we branch @@ -1325,31 +1498,76 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { scrutinee_span: Span, scrutinee_place_builder: &PlaceBuilder<'tcx>, match_start_span: Span, - candidates: &mut [&mut Candidate<'pat, 'tcx>], + patterns: Vec<(&'pat Pat<'tcx>, HasMatchGuard)>, refutable: bool, - ) -> BasicBlock { + ) -> BuiltMatchTree<'tcx> + where + 'tcx: 'pat, + { + // Assemble the initial list of candidates. These top-level candidates are 1:1 with the + // input patterns, but other parts of match lowering also introduce subcandidates (for + // sub-or-patterns). So inside the algorithm, the candidates list may not correspond to + // match arms directly. + let mut candidates: Vec> = patterns + .into_iter() + .map(|(pat, has_guard)| { + Candidate::new(scrutinee_place_builder.clone(), pat, has_guard, self) + }) + .collect(); + + let fake_borrow_temps = util::collect_fake_borrows( + self, + &candidates, + scrutinee_span, + scrutinee_place_builder.base(), + ); + // This will generate code to test scrutinee_place and branch to the appropriate arm block. - // See the doc comment on `match_candidates` for why we have an otherwise block. + // If none of the arms match, we branch to `otherwise_block`. When lowering a `match` + // expression, exhaustiveness checking ensures that this block is unreachable. + let mut candidate_refs = candidates.iter_mut().collect::>(); let otherwise_block = - self.match_candidates(match_start_span, scrutinee_span, block, candidates); - - // Link each leaf candidate to the `false_edge_start_block` of the next one. - let mut previous_candidate: Option<&mut Candidate<'_, '_>> = None; - for candidate in candidates { - candidate.visit_leaves(|leaf_candidate| { - if let Some(ref mut prev) = previous_candidate { - assert!(leaf_candidate.false_edge_start_block.is_some()); - prev.next_candidate_start_block = leaf_candidate.false_edge_start_block; + self.match_candidates(match_start_span, scrutinee_span, block, &mut candidate_refs); + + // Set up false edges so that the borrow-checker cannot make use of the specific CFG we + // generated. We falsely branch from each candidate to the one below it to make it as if we + // were testing match branches one by one in order. In the refutable case we also want a + // false edge to the final failure block. + let mut next_candidate_start_block = if refutable { Some(otherwise_block) } else { None }; + for candidate in candidates.iter_mut().rev() { + let has_guard = candidate.has_guard; + candidate.visit_leaves_rev(|leaf_candidate| { + if let Some(next_candidate_start_block) = next_candidate_start_block { + let source_info = self.source_info(leaf_candidate.extra_data.span); + // Falsely branch to `next_candidate_start_block` before reaching pre_binding. + let old_pre_binding = leaf_candidate.pre_binding_block.unwrap(); + let new_pre_binding = self.cfg.start_new_block(); + self.false_edges( + old_pre_binding, + new_pre_binding, + next_candidate_start_block, + source_info, + ); + leaf_candidate.pre_binding_block = Some(new_pre_binding); + if has_guard { + // Falsely branch to `next_candidate_start_block` also if the guard fails. + let new_otherwise = self.cfg.start_new_block(); + let old_otherwise = leaf_candidate.otherwise_block.unwrap(); + self.false_edges( + new_otherwise, + old_otherwise, + next_candidate_start_block, + source_info, + ); + leaf_candidate.otherwise_block = Some(new_otherwise); + } } - previous_candidate = Some(leaf_candidate); + assert!(leaf_candidate.false_edge_start_block.is_some()); + next_candidate_start_block = leaf_candidate.false_edge_start_block; }); } - if refutable { - // In refutable cases there's always at least one candidate, and we want a false edge to - // the failure block. - previous_candidate.as_mut().unwrap().next_candidate_start_block = Some(otherwise_block) - } else { + if !refutable { // Match checking ensures `otherwise_block` is actually unreachable in irrefutable // cases. let source_info = self.source_info(scrutinee_span); @@ -1379,26 +1597,30 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { self.cfg.terminate(otherwise_block, source_info, TerminatorKind::Unreachable); } - otherwise_block + BuiltMatchTree { + branches: candidates.into_iter().map(MatchTreeBranch::from_candidate).collect(), + otherwise_block, + fake_borrow_temps, + } } /// The main match algorithm. It begins with a set of candidates `candidates` and has the job of /// generating code that branches to an appropriate block if the scrutinee matches one of these /// candidates. The - /// candidates are sorted such that the first item in the list + /// candidates are ordered such that the first item in the list /// has the highest priority. When a candidate is found to match /// the value, we will set and generate a branch to the appropriate /// pre-binding block. /// /// If none of the candidates apply, we continue to the returned `otherwise_block`. /// - /// It might be surprising that the input can be non-exhaustive. - /// Indeed, for matches, initially, it is not, because all matches are - /// exhaustive in Rust. But during processing we sometimes divide - /// up the list of candidates and recurse with a non-exhaustive - /// list. This is how our lowering approach (called "backtracking - /// automaton" in the literature) works. - /// See [`Builder::test_candidates`] for more details. + /// Note that while `match` expressions in the Rust language are exhaustive, + /// candidate lists passed to this method are often _non-exhaustive_. + /// For example, the match lowering process will frequently divide up the + /// list of candidates, and recursively call this method with a non-exhaustive + /// subset of candidates. + /// See [`Builder::test_candidates`] for more details on this + /// "backtracking automata" approach. /// /// For an example of how we use `otherwise_block`, consider: /// ``` @@ -1478,14 +1700,20 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { return start_block; } [first, remaining @ ..] if first.match_pairs.is_empty() => { - // The first candidate has satisfied all its match pairs; we link it up and continue - // with the remaining candidates. + // The first candidate has satisfied all its match pairs. + // We record the blocks that will be needed by match arm lowering, + // and then continue with the remaining candidates. let remainder_start = self.select_matched_candidate(first, start_block); remainder_start.and(remaining) } candidates if candidates.iter().any(|candidate| candidate.starts_with_or_pattern()) => { - // If any candidate starts with an or-pattern, we have to expand the or-pattern before we - // can proceed further. + // If any candidate starts with an or-pattern, we want to expand or-patterns + // before we do any more tests. + // + // The only candidate we strictly _need_ to expand here is the first one. + // But by expanding other candidates as early as possible, we unlock more + // opportunities to include them in test outcomes, making the match tree + // smaller and simpler. self.expand_and_match_or_candidates(span, scrutinee_span, start_block, candidates) } candidates => { @@ -1588,6 +1816,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let (candidates_to_expand, remaining_candidates) = candidates.split_at_mut(expand_until); // Expand one level of or-patterns for each candidate in `candidates_to_expand`. + // We take care to preserve the relative ordering of candidates, so that + // or-patterns are expanded in their parent's relative position. let mut expanded_candidates = Vec::new(); for candidate in candidates_to_expand.iter_mut() { if candidate.starts_with_or_pattern() { @@ -1608,7 +1838,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - // Process the expanded candidates. + // Recursively lower the part of the match tree represented by the + // expanded candidates. This is where subcandidates actually get lowered! let remainder_start = self.match_candidates( span, scrutinee_span, @@ -1628,6 +1859,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { self.remove_never_subcandidates(candidate); } } + // It's important to perform the above simplifications _before_ dealing + // with remaining match pairs, to avoid exponential blowup if possible + // (for trivial or-patterns), and avoid useless work (for never patterns). if let Some(last_candidate) = candidates_to_expand.last_mut() { self.test_remaining_match_pairs_after_or(span, scrutinee_span, last_candidate); } @@ -1808,6 +2042,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { .all(|match_pair| matches!(match_pair.test_case, TestCase::Or { .. })) ); + // Visit each leaf candidate within this subtree, add a copy of the remaining + // match pairs to it, and then recursively lower the rest of the match tree + // from that point. candidate.visit_leaves(|leaf_candidate| { // At this point the leaf's own match pairs have all been lowered // and removed, so `extend` and assignment are equivalent, @@ -1860,17 +2097,20 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { (match_place, test) } - /// Given a test, we sort the input candidates into several buckets. If a candidate only matches - /// in one of the branches of `test`, we move it there. If it could match in more than one of - /// the branches of `test`, we stop sorting candidates. + /// Given a test, we partition the input candidates into several buckets. + /// If a candidate matches in exactly one of the branches of `test` + /// (and no other branches), we put it into the corresponding bucket. + /// If it could match in more than one of the branches of `test`, the test + /// doesn't usefully apply to it, and we stop partitioning candidates. + /// + /// Importantly, we also **mutate** the branched candidates to remove match pairs + /// that are entailed by the outcome of the test, and add any sub-pairs of the + /// removed pairs. /// /// This returns a pair of /// - the candidates that weren't sorted; /// - for each possible outcome of the test, the candidates that match in that outcome. /// - /// Moreover, we transform the branched candidates to reflect the fact that we know which - /// outcome of `test` occurred. - /// /// For example: /// ``` /// # let (x, y, z) = (true, true, true); @@ -1883,14 +2123,18 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// # ; /// ``` /// - /// Assume we are testing on `x`. There are 2 overlapping candidate sets: - /// - If the outcome is that `x` is true, candidates 0, 2, and 3 - /// - If the outcome is that `x` is false, candidates 1 and 2 + /// Assume we are testing on `x`. Conceptually, there are 2 overlapping candidate sets: + /// - If the outcome is that `x` is true, candidates {0, 2, 3} are possible + /// - If the outcome is that `x` is false, candidates {1, 2} are possible /// - /// Following our algorithm, candidate 0 is sorted into outcome `x == true`, candidate 1 goes - /// into outcome `x == false`, and candidate 2 and 3 remain unsorted. + /// Following our algorithm: + /// - Candidate 0 is sorted into outcome `x == true` + /// - Candidate 1 is sorted into outcome `x == false` + /// - Candidate 2 remains unsorted, because testing `x` has no effect on it + /// - Candidate 3 remains unsorted, because a previous candidate (2) was unsorted + /// - This helps preserve the illusion that candidates are tested "in order" /// - /// The sorted candidates are transformed: + /// The sorted candidates are mutated to remove entailed match pairs: /// - candidate 0 becomes `[z @ true]` since we know that `x` was `true`; /// - candidate 1 becomes `[y @ false]` since we know that `x` was `false`. fn sort_candidates<'b, 'c, 'pat>( @@ -1933,15 +2177,16 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { (candidates, target_candidates) } - /// This is the most subtle part of the match lowering algorithm. At this point, the input - /// candidates have been fully simplified, so all remaining match-pairs require some sort of - /// test. + /// This is the most subtle part of the match lowering algorithm. At this point, there are + /// no fully-satisfied candidates, and no or-patterns to expand, so we actually need to + /// perform some sort of test to make progress. /// /// Once we pick what sort of test we are going to perform, this test will help us winnow down /// our candidates. So we walk over the candidates (from high to low priority) and check. We - /// compute, for each outcome of the test, a transformed list of candidates. If a candidate - /// matches in a single branch of our test, we add it to the corresponding outcome. We also - /// transform it to record the fact that we know which outcome occurred. + /// compute, for each outcome of the test, a list of (modified) candidates. If a candidate + /// matches in exactly one branch of our test, we add it to the corresponding outcome. We also + /// **mutate its list of match pairs** if appropriate, to reflect the fact that we know which + /// outcome occurred. /// /// For example, if we are testing `x.0`'s variant, and we have a candidate `(x.0 @ Some(v), x.1 /// @ 22)`, then we would have a resulting candidate of `((x.0 as Some).0 @ v, x.1 @ 22)` in the @@ -2036,32 +2281,38 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>], start_block: BasicBlock, ) -> BlockAnd<&'b mut [&'c mut Candidate<'pat, 'tcx>]> { - // Extract the match-pair from the highest priority candidate and build a test from it. + // Choose a match pair from the first candidate, and use it to determine a + // test to perform that will confirm or refute that match pair. let (match_place, test) = self.pick_test(candidates); // For each of the N possible test outcomes, build the vector of candidates that applies if - // the test has that particular outcome. + // the test has that particular outcome. This also mutates the candidates to remove match + // pairs that are fully satisfied by the relevant outcome. let (remaining_candidates, target_candidates) = self.sort_candidates(match_place, &test, candidates); - // The block that we should branch to if none of the - // `target_candidates` match. + // The block that we should branch to if none of the `target_candidates` match. let remainder_start = self.cfg.start_new_block(); - // For each outcome of test, process the candidates that still apply. + // For each outcome of the test, recursively lower the rest of the match tree + // from that point. (Note that we haven't lowered the actual test yet!) let target_blocks: FxIndexMap<_, _> = target_candidates .into_iter() .map(|(branch, mut candidates)| { let branch_start = self.cfg.start_new_block(); + // Recursively lower the rest of the match tree after the relevant outcome. let branch_otherwise = self.match_candidates(span, scrutinee_span, branch_start, &mut *candidates); + + // Link up the `otherwise` block of the subtree to `remainder_start`. let source_info = self.source_info(span); self.cfg.goto(branch_otherwise, source_info, remainder_start); (branch, branch_start) }) .collect(); - // Perform the test, branching to one of N blocks. + // Perform the chosen test, branching to one of the N subtrees prepared above + // (or to `remainder_start` if no outcome was satisfied). self.perform_test( span, scrutinee_span, @@ -2100,17 +2351,17 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ) -> BlockAnd<()> { let expr_span = self.thir[expr_id].span; let scrutinee = unpack!(block = self.lower_scrutinee(block, expr_id, expr_span)); - let mut candidate = Candidate::new(scrutinee.clone(), pat, false, self); - let otherwise_block = self.lower_match_tree( + let built_tree = self.lower_match_tree( block, expr_span, &scrutinee, pat.span, - &mut [&mut candidate], + vec![(pat, HasMatchGuard::No)], true, ); + let [branch] = built_tree.branches.try_into().unwrap(); - self.break_for_else(otherwise_block, self.source_info(expr_span)); + self.break_for_else(built_tree.otherwise_block, self.source_info(expr_span)); match declare_let_bindings { DeclareLetBindings::Yes => { @@ -2132,7 +2383,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let success = self.bind_pattern( self.source_info(pat.span), - candidate, + branch, &[], expr_span, None, @@ -2140,7 +2391,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); // If branch coverage is enabled, record this branch. - self.visit_coverage_conditional_let(pat, success, otherwise_block); + self.visit_coverage_conditional_let(pat, success, built_tree.otherwise_block); success.unit() } @@ -2153,52 +2404,28 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// Note: we do not check earlier that if there is a guard, /// there cannot be move bindings. We avoid a use-after-move by only /// moving the binding once the guard has evaluated to true (see below). - fn bind_and_guard_matched_candidate<'pat>( + fn bind_and_guard_matched_candidate( &mut self, - candidate: Candidate<'pat, 'tcx>, - parent_data: &[PatternExtraData<'tcx>], + sub_branch: MatchTreeSubBranch<'tcx>, fake_borrows: &[(Place<'tcx>, Local, FakeBorrowKind)], scrutinee_span: Span, arm_match_scope: Option<(&Arm<'tcx>, region::Scope)>, schedule_drops: ScheduleDrops, emit_storage_live: EmitStorageLive, ) -> BasicBlock { - debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate); - - debug_assert!(candidate.match_pairs.is_empty()); - - let candidate_source_info = self.source_info(candidate.extra_data.span); - - let mut block = candidate.pre_binding_block.unwrap(); + debug!("bind_and_guard_matched_candidate(subbranch={:?})", sub_branch); - if candidate.next_candidate_start_block.is_some() { - let fresh_block = self.cfg.start_new_block(); - self.false_edges( - block, - fresh_block, - candidate.next_candidate_start_block, - candidate_source_info, - ); - block = fresh_block; - } + let block = sub_branch.success_block; - if candidate.extra_data.is_never { + if sub_branch.is_never { // This arm has a dummy body, we don't need to generate code for it. `block` is already // unreachable (except via false edge). - let source_info = self.source_info(candidate.extra_data.span); + let source_info = self.source_info(sub_branch.span); self.cfg.terminate(block, source_info, TerminatorKind::Unreachable); return self.cfg.start_new_block(); } - let ascriptions = parent_data - .iter() - .flat_map(|d| &d.ascriptions) - .cloned() - .chain(candidate.extra_data.ascriptions); - let bindings = - parent_data.iter().flat_map(|d| &d.bindings).chain(&candidate.extra_data.bindings); - - self.ascribe_types(block, ascriptions); + self.ascribe_types(block, sub_branch.ascriptions); // Lower an instance of the arm guard (if present) for this candidate, // and then perform bindings for the arm body. @@ -2209,9 +2436,17 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // Bindings for guards require some extra handling to automatically // insert implicit references/dereferences. - self.bind_matched_candidate_for_guard(block, schedule_drops, bindings.clone()); + self.bind_matched_candidate_for_guard( + block, + schedule_drops, + sub_branch.bindings.iter(), + ); let guard_frame = GuardFrame { - locals: bindings.clone().map(|b| GuardFrameLocal::new(b.var_id)).collect(), + locals: sub_branch + .bindings + .iter() + .map(|b| GuardFrameLocal::new(b.var_id)) + .collect(), }; debug!("entering guard building context: {:?}", guard_frame); self.guard_context.push(guard_frame); @@ -2247,17 +2482,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(temp)); } - let otherwise_block = candidate.otherwise_block.unwrap_or_else(|| { - let unreachable = self.cfg.start_new_block(); - self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable); - unreachable - }); - self.false_edges( - otherwise_post_guard_block, - otherwise_block, - candidate.next_candidate_start_block, - source_info, - ); + self.cfg.goto(otherwise_post_guard_block, source_info, sub_branch.otherwise_block); // We want to ensure that the matched candidates are bound // after we have confirmed this candidate *and* any @@ -2285,8 +2510,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // ``` // // and that is clearly not correct. - let by_value_bindings = - bindings.filter(|binding| matches!(binding.binding_mode.0, ByRef::No)); + let by_value_bindings = sub_branch + .bindings + .iter() + .filter(|binding| matches!(binding.binding_mode.0, ByRef::No)); // Read all of the by reference bindings to ensure that the // place they refer to can't be modified by the guard. for binding in by_value_bindings.clone() { @@ -2314,7 +2541,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { self.bind_matched_candidate_for_arm_body( block, schedule_drops, - bindings, + sub_branch.bindings.iter(), emit_storage_live, ); block diff --git a/compiler/rustc_mir_build/src/build/matches/simplify.rs b/compiler/rustc_mir_build/src/build/matches/simplify.rs index 20310f6082108..04cf81d54e9df 100644 --- a/compiler/rustc_mir_build/src/build/matches/simplify.rs +++ b/compiler/rustc_mir_build/src/build/matches/simplify.rs @@ -12,11 +12,12 @@ //! sort of test: for example, testing which variant an enum is, or //! testing a value against a constant. -use crate::build::matches::{MatchPairTree, PatternExtraData, TestCase}; -use crate::build::Builder; +use std::mem; + use tracing::{debug, instrument}; -use std::mem; +use crate::build::matches::{MatchPairTree, PatternExtraData, TestCase}; +use crate::build::Builder; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Simplify a list of match pairs so they all require a test. Stores relevant bindings and diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index 8a02ea1a06de4..7af1ede24a4f4 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -5,14 +5,14 @@ // identify what tests are needed, perform the tests, and then filter // the candidates based on the result. -use crate::build::matches::{Candidate, MatchPairTree, Test, TestBranch, TestCase, TestKind}; -use crate::build::Builder; +use std::cmp::Ordering; + use rustc_data_structures::fx::FxIndexMap; use rustc_hir::{LangItem, RangeEnd}; use rustc_middle::mir::*; +use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::util::IntTypeExt; -use rustc_middle::ty::GenericArg; -use rustc_middle::ty::{self, adjustment::PointerCoercion, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArg, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_span::def_id::DefId; use rustc_span::source_map::Spanned; @@ -20,7 +20,8 @@ use rustc_span::symbol::{sym, Symbol}; use rustc_span::{Span, DUMMY_SP}; use tracing::{debug, instrument}; -use std::cmp::Ordering; +use crate::build::matches::{Candidate, MatchPairTree, Test, TestBranch, TestCase, TestKind}; +use crate::build::Builder; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Identifies what test is needed to decide if `match_pair` is applicable. @@ -51,6 +52,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { TestCase::Never => TestKind::Never, + // Or-patterns are not tested directly; instead they are expanded into subcandidates, + // which are then distinguished by testing whatever non-or patterns they contain. TestCase::Or { .. } => bug!("or-patterns should have already been handled"), TestCase::Irrefutable { .. } => span_bug!( @@ -544,6 +547,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { .enumerate() .find(|&(_, mp)| mp.place == Some(test_place))?; + // If true, the match pair is completely entailed by its corresponding test + // branch, so it can be removed. If false, the match pair is _compatible_ + // with its test branch, but still needs a more specific test. let fully_matched; let ret = match (&test.kind, &match_pair.test_case) { // If we are performing a variant switch, then this @@ -565,8 +571,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { (TestKind::SwitchInt, &TestCase::Constant { value }) if is_switch_ty(match_pair.pattern.ty) => { - // Beware: there might be some ranges sorted into the failure case; we must not add - // a success case that could be matched by one of these ranges. + // An important invariant of candidate sorting is that a candidate + // must not match in multiple branches. For `SwitchInt` tests, adding + // a new value might invalidate that property for range patterns that + // have already been sorted into the failure arm, so we must take care + // not to add such values here. let is_covering_range = |test_case: &TestCase<'_, 'tcx>| { test_case.as_range().is_some_and(|range| { matches!(range.contains(value, self.tcx, self.param_env), None | Some(true)) @@ -591,6 +600,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } (TestKind::SwitchInt, TestCase::Range(range)) => { + // When performing a `SwitchInt` test, a range pattern can be + // sorted into the failure arm if it doesn't contain _any_ of + // the values being tested. (This restricts what values can be + // added to the test by subsequent candidates.) fully_matched = false; let not_contained = sorted_candidates.keys().filter_map(|br| br.as_constant()).copied().all( diff --git a/compiler/rustc_mir_build/src/build/matches/util.rs b/compiler/rustc_mir_build/src/build/matches/util.rs index 8fe8069b3455d..8491b5fe380c7 100644 --- a/compiler/rustc_mir_build/src/build/matches/util.rs +++ b/compiler/rustc_mir_build/src/build/matches/util.rs @@ -1,14 +1,13 @@ -use std::marker::PhantomData; - -use crate::build::expr::as_place::PlaceBase; -use crate::build::matches::{Binding, Candidate, FlatPat, MatchPairTree, TestCase}; -use crate::build::Builder; use rustc_data_structures::fx::FxIndexMap; use rustc_middle::mir::*; use rustc_middle::ty::Ty; use rustc_span::Span; use tracing::debug; +use crate::build::expr::as_place::PlaceBase; +use crate::build::matches::{Binding, Candidate, FlatPat, MatchPairTree, TestCase}; +use crate::build::Builder; + impl<'a, 'tcx> Builder<'a, 'tcx> { /// Creates a false edge to `imaginary_target` and a real edge to /// real_target. If `imaginary_target` is none, or is the same as the real @@ -17,18 +16,17 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { &mut self, from_block: BasicBlock, real_target: BasicBlock, - imaginary_target: Option, + imaginary_target: BasicBlock, source_info: SourceInfo, ) { - match imaginary_target { - Some(target) if target != real_target => { - self.cfg.terminate( - from_block, - source_info, - TerminatorKind::FalseEdge { real_target, imaginary_target: target }, - ); - } - _ => self.cfg.goto(from_block, source_info, real_target), + if imaginary_target != real_target { + self.cfg.terminate( + from_block, + source_info, + TerminatorKind::FalseEdge { real_target, imaginary_target }, + ); + } else { + self.cfg.goto(from_block, source_info, real_target) } } } @@ -70,10 +68,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// a MIR pass run after borrow checking. pub(super) fn collect_fake_borrows<'tcx>( cx: &mut Builder<'_, 'tcx>, - candidates: &[&mut Candidate<'_, 'tcx>], + candidates: &[Candidate<'_, 'tcx>], temp_span: Span, scrutinee_base: PlaceBase, ) -> Vec<(Place<'tcx>, Local, FakeBorrowKind)> { + if candidates.iter().all(|candidate| !candidate.has_guard) { + // Fake borrows are only used when there is a guard. + return Vec::new(); + } let mut collector = FakeBorrowCollector { cx, scrutinee_base, fake_borrows: FxIndexMap::default() }; for candidate in candidates.iter() { @@ -221,57 +223,6 @@ impl<'a, 'b, 'tcx> FakeBorrowCollector<'a, 'b, 'tcx> { } } -/// Visit all the bindings of these candidates. Because or-alternatives bind the same variables, we -/// only explore the first one of each or-pattern. -pub(super) fn visit_bindings<'tcx>( - candidates: &[&mut Candidate<'_, 'tcx>], - f: impl FnMut(&Binding<'tcx>), -) { - let mut visitor = BindingsVisitor { f, phantom: PhantomData }; - for candidate in candidates.iter() { - visitor.visit_candidate(candidate); - } -} - -pub(super) struct BindingsVisitor<'tcx, F> { - f: F, - phantom: PhantomData<&'tcx ()>, -} - -impl<'tcx, F> BindingsVisitor<'tcx, F> -where - F: FnMut(&Binding<'tcx>), -{ - fn visit_candidate(&mut self, candidate: &Candidate<'_, 'tcx>) { - for binding in &candidate.extra_data.bindings { - (self.f)(binding) - } - for match_pair in &candidate.match_pairs { - self.visit_match_pair(match_pair); - } - } - - fn visit_flat_pat(&mut self, flat_pat: &FlatPat<'_, 'tcx>) { - for binding in &flat_pat.extra_data.bindings { - (self.f)(binding) - } - for match_pair in &flat_pat.match_pairs { - self.visit_match_pair(match_pair); - } - } - - fn visit_match_pair(&mut self, match_pair: &MatchPairTree<'_, 'tcx>) { - if let TestCase::Or { pats, .. } = &match_pair.test_case { - // All the or-alternatives should bind the same locals, so we only visit the first one. - self.visit_flat_pat(&pats[0]) - } else { - for subpair in &match_pair.subpairs { - self.visit_match_pair(subpair); - } - } - } -} - #[must_use] pub(crate) fn ref_pat_borrow_kind(ref_mutability: Mutability) -> BorrowKind { match ref_mutability { diff --git a/compiler/rustc_mir_build/src/build/misc.rs b/compiler/rustc_mir_build/src/build/misc.rs index 04e6d24e5a172..26906973ca86c 100644 --- a/compiler/rustc_mir_build/src/build/misc.rs +++ b/compiler/rustc_mir_build/src/build/misc.rs @@ -1,14 +1,14 @@ //! Miscellaneous builder routines that are not specific to building any particular //! kind of thing. -use crate::build::Builder; - use rustc_middle::mir::*; use rustc_middle::ty::{self, Ty}; use rustc_span::Span; use rustc_trait_selection::infer::InferCtxtExt; use tracing::debug; +use crate::build::Builder; + impl<'a, 'tcx> Builder<'a, 'tcx> { /// Adds a new temporary value of type `ty` storing the result of /// evaluating `expr`. diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index 2793a7d873621..b98deda8fd022 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -1,5 +1,3 @@ -use crate::build::expr::as_place::PlaceBuilder; -use crate::build::scope::DropKind; use itertools::Itertools; use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_apfloat::Float; @@ -21,12 +19,13 @@ use rustc_middle::thir::{self, ExprId, LintLevel, LocalVarId, Param, ParamId, Pa use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::sym; -use rustc_span::Span; -use rustc_span::Symbol; +use rustc_span::{Span, Symbol}; use rustc_target::abi::FieldIdx; use rustc_target::spec::abi::Abi; use super::lints; +use crate::build::expr::as_place::PlaceBuilder; +use crate::build::scope::DropKind; pub(crate) fn closure_saved_names_of_captured_variables<'tcx>( tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_mir_build/src/build/scope.rs b/compiler/rustc_mir_build/src/build/scope.rs index b630c74a20283..8546a2539d725 100644 --- a/compiler/rustc_mir_build/src/build/scope.rs +++ b/compiler/rustc_mir_build/src/build/scope.rs @@ -83,7 +83,6 @@ that contains only loops and breakable blocks. It tracks where a `break`, use std::mem; -use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder, CFG}; use rustc_data_structures::fx::FxHashMap; use rustc_hir::HirId; use rustc_index::{IndexSlice, IndexVec}; @@ -96,6 +95,8 @@ use rustc_span::source_map::Spanned; use rustc_span::{Span, DUMMY_SP}; use tracing::{debug, instrument}; +use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder, CFG}; + #[derive(Debug)] pub(crate) struct Scopes<'tcx> { scopes: Vec, diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 6309f2ac98e24..48018fcaa36df 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -1,5 +1,6 @@ -use crate::build::ExprCategory; -use crate::errors::*; +use std::borrow::Cow; +use std::mem; +use std::ops::Bound; use rustc_errors::DiagArgValue; use rustc_hir::def::DefKind; @@ -16,9 +17,8 @@ use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::symbol::Symbol; use rustc_span::{sym, Span}; -use std::borrow::Cow; -use std::mem; -use std::ops::Bound; +use crate::build::ExprCategory; +use crate::errors::*; struct UnsafetyVisitor<'a, 'tcx> { tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_mir_build/src/errors.rs b/compiler/rustc_mir_build/src/errors.rs index f6f443b64a63a..42eca71ca3f30 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -1,15 +1,17 @@ -use crate::fluent_generated as fluent; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, Applicability, Diag, Diagnostic, EmissionGuarantee, Level, MultiSpan, - SubdiagMessageOp, Subdiagnostic, + Applicability, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, + MultiSpan, SubdiagMessageOp, Subdiagnostic, }; -use rustc_errors::{DiagArgValue, DiagCtxtHandle}; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::{self, Ty}; -use rustc_pattern_analysis::{errors::Uncovered, rustc::RustcPatCtxt}; +use rustc_pattern_analysis::errors::Uncovered; +use rustc_pattern_analysis::rustc::RustcPatCtxt; use rustc_span::symbol::Symbol; use rustc_span::Span; +use crate::fluent_generated as fluent; + #[derive(LintDiagnostic)] #[diag(mir_build_unconditional_recursion)] #[help] @@ -582,11 +584,23 @@ pub(crate) struct NonConstPath { #[derive(LintDiagnostic)] #[diag(mir_build_unreachable_pattern)] -pub(crate) struct UnreachablePattern { +pub(crate) struct UnreachablePattern<'tcx> { #[label] pub(crate) span: Option, - #[label(mir_build_catchall_label)] - pub(crate) catchall: Option, + #[subdiagnostic] + pub(crate) matches_no_values: Option>, + #[label(mir_build_unreachable_covered_by_catchall)] + pub(crate) covered_by_catchall: Option, + #[label(mir_build_unreachable_covered_by_one)] + pub(crate) covered_by_one: Option, + #[note(mir_build_unreachable_covered_by_many)] + pub(crate) covered_by_many: Option, +} + +#[derive(Subdiagnostic)] +#[note(mir_build_unreachable_matches_no_values)] +pub(crate) struct UnreachableMatchesNoValues<'tcx> { + pub(crate) ty: Ty<'tcx>, } #[derive(Diagnostic)] @@ -844,7 +858,7 @@ pub(crate) struct PatternNotCovered<'s, 'tcx> { pub(crate) span: Span, pub(crate) origin: &'s str, #[subdiagnostic] - pub(crate) uncovered: Uncovered<'tcx>, + pub(crate) uncovered: Uncovered, #[subdiagnostic] pub(crate) inform: Option, #[subdiagnostic] diff --git a/compiler/rustc_mir_build/src/lints.rs b/compiler/rustc_mir_build/src/lints.rs index 263e777d03ae1..80e91811b1c5f 100644 --- a/compiler/rustc_mir_build/src/lints.rs +++ b/compiler/rustc_mir_build/src/lints.rs @@ -1,14 +1,15 @@ -use crate::errors::UnconditionalRecursion; +use std::ops::ControlFlow; + use rustc_data_structures::graph::iterate::{ NodeStatus, TriColorDepthFirstSearch, TriColorVisitor, }; use rustc_hir::def::DefKind; use rustc_middle::mir::{self, BasicBlock, BasicBlocks, Body, Terminator, TerminatorKind}; -use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; -use rustc_middle::ty::{GenericArg, GenericArgs}; +use rustc_middle::ty::{self, GenericArg, GenericArgs, Instance, Ty, TyCtxt}; use rustc_session::lint::builtin::UNCONDITIONAL_RECURSION; use rustc_span::Span; -use std::ops::ControlFlow; + +use crate::errors::UnconditionalRecursion; pub(crate) fn check<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) { check_call_recursion(tcx, body); diff --git a/compiler/rustc_mir_build/src/thir/cx/block.rs b/compiler/rustc_mir_build/src/thir/cx/block.rs index 95cd703dbb3c0..069c2e7881ea6 100644 --- a/compiler/rustc_mir_build/src/thir/cx/block.rs +++ b/compiler/rustc_mir_build/src/thir/cx/block.rs @@ -1,5 +1,3 @@ -use crate::thir::cx::Cx; - use rustc_hir as hir; use rustc_index::Idx; use rustc_middle::middle::region; @@ -8,6 +6,8 @@ use rustc_middle::ty; use rustc_middle::ty::CanonicalUserTypeAnnotation; use tracing::debug; +use crate::thir::cx::Cx; + impl<'tcx> Cx<'tcx> { pub(crate) fn mirror_block(&mut self, block: &'tcx hir::Block<'tcx>) -> BlockId { // We have to eagerly lower the "spine" of the statements diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 99afb500e0b6f..d4de5fac96eb0 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -1,32 +1,31 @@ -use crate::errors; -use crate::thir::cx::region::Scope; -use crate::thir::cx::Cx; -use crate::thir::util::UserAnnotatedTyHelpers; use itertools::Itertools; -use rustc_ast::LitKind; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir as hir; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; use rustc_index::Idx; -use rustc_middle::hir::place::Place as HirPlace; -use rustc_middle::hir::place::PlaceBase as HirPlaceBase; -use rustc_middle::hir::place::ProjectionKind as HirProjectionKind; +use rustc_middle::hir::place::{ + Place as HirPlace, PlaceBase as HirPlaceBase, ProjectionKind as HirProjectionKind, +}; use rustc_middle::middle::region; use rustc_middle::mir::{self, BinOp, BorrowKind, UnOp}; use rustc_middle::thir::*; use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, PointerCoercion, }; -use rustc_middle::ty::GenericArgs; use rustc_middle::ty::{ - self, AdtKind, InlineConstArgs, InlineConstArgsParts, ScalarInt, Ty, UpvarArgs, UserType, + self, AdtKind, GenericArgs, InlineConstArgs, InlineConstArgsParts, ScalarInt, Ty, UpvarArgs, + UserType, }; use rustc_middle::{bug, span_bug}; -use rustc_span::source_map::Spanned; -use rustc_span::{sym, Span, DUMMY_SP}; +use rustc_span::{sym, Span}; use rustc_target::abi::{FieldIdx, FIRST_VARIANT}; use tracing::{debug, info, instrument, trace}; +use crate::errors; +use crate::thir::cx::region::Scope; +use crate::thir::cx::Cx; +use crate::thir::util::UserAnnotatedTyHelpers; + impl<'tcx> Cx<'tcx> { pub(crate) fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId { // `mirror_expr` is recursing very deep. Make sure the stack doesn't overflow. @@ -899,14 +898,10 @@ impl<'tcx> Cx<'tcx> { let hir_id = self.tcx.local_def_id_to_hir_id(def_id.expect_local()); let generics = self.tcx.generics_of(hir_id.owner); let Some(&index) = generics.param_def_id_to_index.get(&def_id) else { - let guar = self.tcx.dcx().has_errors().unwrap(); - // We already errored about a late bound const - - let lit = self - .tcx - .hir_arena - .alloc(Spanned { span: DUMMY_SP, node: LitKind::Err(guar) }); - return ExprKind::Literal { lit, neg: false }; + span_bug!( + expr.span, + "Should have already errored about late bound consts: {def_id:?}" + ); }; let name = self.tcx.hir().name(hir_id); let param = ty::ParamConst::new(index, name); diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index 244ac409fd381..6120b1453cfab 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -2,23 +2,22 @@ //! structures into the THIR. The `builder` is generally ignorant of the tcx, //! etc., and instead goes through the `Cx` for most of its work. -use crate::thir::pattern::pat_from_hir; -use crate::thir::util::UserAnnotatedTyHelpers; - use rustc_data_structures::steal::Steal; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::LangItem; -use rustc_hir::HirId; -use rustc_hir::Node; +use rustc_hir::{HirId, Node}; use rustc_middle::bug; use rustc_middle::middle::region; use rustc_middle::thir::*; use rustc_middle::ty::{self, RvalueScopes, TyCtxt}; use tracing::instrument; +use crate::thir::pattern::pat_from_hir; +use crate::thir::util::UserAnnotatedTyHelpers; + pub(crate) fn thir_body( tcx: TyCtxt<'_>, owner_def: LocalDefId, diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 95799cec94b04..64c6ff952c686 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -1,10 +1,9 @@ -use crate::errors::*; - use rustc_arena::{DroplessArena, TypedArena}; use rustc_ast::Mutability; use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::stack::ensure_sufficient_stack; -use rustc_errors::{codes::*, struct_span_code_err, Applicability, ErrorGuaranteed, MultiSpan}; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, Applicability, ErrorGuaranteed, MultiSpan}; use rustc_hir::def::*; use rustc_hir::def_id::LocalDefId; use rustc_hir::{self as hir, BindingMode, ByRef, HirId}; @@ -16,8 +15,8 @@ use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt}; use rustc_pattern_analysis::errors::Uncovered; use rustc_pattern_analysis::rustc::{ - Constructor, DeconstructedPat, MatchArm, RevealedTy, RustcPatCtxt as PatCtxt, Usefulness, - UsefulnessReport, WitnessPat, + Constructor, DeconstructedPat, MatchArm, RedundancyExplanation, RevealedTy, + RustcPatCtxt as PatCtxt, Usefulness, UsefulnessReport, WitnessPat, }; use rustc_session::lint::builtin::{ BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS, @@ -26,6 +25,9 @@ use rustc_span::hygiene::DesugaringKind; use rustc_span::{sym, Span}; use tracing::instrument; +use crate::errors::*; +use crate::fluent_generated as fluent; + pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> { let typeck_results = tcx.typeck(def_id); let (thir, expr) = tcx.thir_body(def_id)?; @@ -391,12 +393,16 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { ) -> Result, ErrorGuaranteed> { let pattern_complexity_limit = get_limit_size(cx.tcx.hir().krate_attrs(), cx.tcx.sess, sym::pattern_complexity); - let report = - rustc_pattern_analysis::analyze_match(&cx, &arms, scrut_ty, pattern_complexity_limit) - .map_err(|err| { - self.error = Err(err); - err - })?; + let report = rustc_pattern_analysis::rustc::analyze_match( + &cx, + &arms, + scrut_ty, + pattern_complexity_limit, + ) + .map_err(|err| { + self.error = Err(err); + err + })?; // Warn unreachable subpatterns. for (arm, is_useful) in report.arm_usefulness.iter() { @@ -405,9 +411,9 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { { let mut redundant_subpats = redundant_subpats.clone(); // Emit lints in the order in which they occur in the file. - redundant_subpats.sort_unstable_by_key(|pat| pat.data().span); - for pat in redundant_subpats { - report_unreachable_pattern(cx, arm.arm_data, pat.data().span, None) + redundant_subpats.sort_unstable_by_key(|(pat, _)| pat.data().span); + for (pat, explanation) in redundant_subpats { + report_unreachable_pattern(cx, arm.arm_data, pat, &explanation) } } } @@ -906,26 +912,60 @@ fn report_irrefutable_let_patterns( fn report_unreachable_pattern<'p, 'tcx>( cx: &PatCtxt<'p, 'tcx>, hir_id: HirId, - span: Span, - catchall: Option, + pat: &DeconstructedPat<'p, 'tcx>, + explanation: &RedundancyExplanation<'p, 'tcx>, ) { - cx.tcx.emit_node_span_lint( - UNREACHABLE_PATTERNS, - hir_id, - span, - UnreachablePattern { span: if catchall.is_some() { Some(span) } else { None }, catchall }, - ); + let pat_span = pat.data().span; + let mut lint = UnreachablePattern { + span: Some(pat_span), + matches_no_values: None, + covered_by_catchall: None, + covered_by_one: None, + covered_by_many: None, + }; + match explanation.covered_by.as_slice() { + [] => { + // Empty pattern; we report the uninhabited type that caused the emptiness. + lint.span = None; // Don't label the pattern itself + pat.walk(&mut |subpat| { + let ty = **subpat.ty(); + if cx.is_uninhabited(ty) { + lint.matches_no_values = Some(UnreachableMatchesNoValues { ty }); + false // No need to dig further. + } else if matches!(subpat.ctor(), Constructor::Ref | Constructor::UnionField) { + false // Don't explore further since they are not by-value. + } else { + true + } + }); + } + [covering_pat] if pat_is_catchall(covering_pat) => { + lint.covered_by_catchall = Some(covering_pat.data().span); + } + [covering_pat] => { + lint.covered_by_one = Some(covering_pat.data().span); + } + covering_pats => { + let mut multispan = MultiSpan::from_span(pat_span); + for p in covering_pats { + multispan.push_span_label( + p.data().span, + fluent::mir_build_unreachable_matches_same_values, + ); + } + multispan + .push_span_label(pat_span, fluent::mir_build_unreachable_making_this_unreachable); + lint.covered_by_many = Some(multispan); + } + } + cx.tcx.emit_node_span_lint(UNREACHABLE_PATTERNS, hir_id, pat_span, lint); } /// Report unreachable arms, if any. fn report_arm_reachability<'p, 'tcx>(cx: &PatCtxt<'p, 'tcx>, report: &UsefulnessReport<'p, 'tcx>) { - let mut catchall = None; for (arm, is_useful) in report.arm_usefulness.iter() { - if matches!(is_useful, Usefulness::Redundant) { - report_unreachable_pattern(cx, arm.arm_data, arm.pat.data().span, catchall) - } - if !arm.has_guard && catchall.is_none() && pat_is_catchall(arm.pat) { - catchall = Some(arm.pat.data().span); + if let Usefulness::Redundant(explanation) = is_useful { + report_unreachable_pattern(cx, arm.arm_data, arm.pat, explanation) } } } @@ -1038,7 +1078,7 @@ fn report_non_exhaustive_match<'p, 'tcx>( let suggested_arm = if suggest_the_witnesses { let pattern = witnesses .iter() - .map(|witness| cx.hoist_witness_pat(witness).to_string()) + .map(|witness| cx.print_witness_pat(witness)) .collect::>() .join(" | "); if witnesses.iter().all(|p| p.is_never_pattern()) && cx.tcx.features().never_patterns { @@ -1156,13 +1196,13 @@ fn joined_uncovered_patterns<'p, 'tcx>( witnesses: &[WitnessPat<'p, 'tcx>], ) -> String { const LIMIT: usize = 3; - let pat_to_str = |pat: &WitnessPat<'p, 'tcx>| cx.hoist_witness_pat(pat).to_string(); + let pat_to_str = |pat: &WitnessPat<'p, 'tcx>| cx.print_witness_pat(pat); match witnesses { [] => bug!(), - [witness] => format!("`{}`", cx.hoist_witness_pat(witness)), + [witness] => format!("`{}`", cx.print_witness_pat(witness)), [head @ .., tail] if head.len() < LIMIT => { let head: Vec<_> = head.iter().map(pat_to_str).collect(); - format!("`{}` and `{}`", head.join("`, `"), cx.hoist_witness_pat(tail)) + format!("`{}` and `{}`", head.join("`, `"), cx.print_witness_pat(tail)) } _ => { let (head, tail) = witnesses.split_at(LIMIT); diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index 0d54f332585aa..6f8d17b772aaa 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -7,8 +7,7 @@ use rustc_infer::traits::Obligation; use rustc_middle::mir; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::thir::{FieldPat, Pat, PatKind}; -use rustc_middle::ty::TypeVisitableExt; -use rustc_middle::ty::{self, Ty, TyCtxt, ValTree}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, ValTree}; use rustc_span::Span; use rustc_target::abi::{FieldIdx, VariantIdx}; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 622651800f44c..615070034b96b 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -3,10 +3,7 @@ mod check_match; mod const_to_pat; -pub(crate) use self::check_match::check_match; - -use crate::errors::*; -use crate::thir::util::UserAnnotatedTyHelpers; +use std::cmp::Ordering; use rustc_errors::codes::*; use rustc_hir::def::{CtorOf, DefKind, Res}; @@ -26,7 +23,9 @@ use rustc_span::{ErrorGuaranteed, Span}; use rustc_target::abi::{FieldIdx, Integer}; use tracing::{debug, instrument}; -use std::cmp::Ordering; +pub(crate) use self::check_match::check_match; +use crate::errors::*; +use crate::thir::util::UserAnnotatedTyHelpers; struct PatCtxt<'a, 'tcx> { tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_mir_build/src/thir/print.rs b/compiler/rustc_mir_build/src/thir/print.rs index 619bfbcf43d3a..2d4b39e7b08f3 100644 --- a/compiler/rustc_mir_build/src/thir/print.rs +++ b/compiler/rustc_mir_build/src/thir/print.rs @@ -1,8 +1,9 @@ +use std::fmt::{self, Write}; + use rustc_middle::query::TyCtxtAt; use rustc_middle::thir::*; use rustc_middle::ty; use rustc_span::def_id::LocalDefId; -use std::fmt::{self, Write}; pub(crate) fn thir_tree(tcx: TyCtxtAt<'_>, owner_def: LocalDefId) -> String { match super::cx::thir_body(*tcx, owner_def) { diff --git a/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs b/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs index 82c59d7d9595c..bb53eaf6cbd1c 100644 --- a/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs +++ b/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs @@ -1,10 +1,9 @@ -use crate::elaborate_drops::DropFlagState; use rustc_middle::mir::{self, Body, Location, Terminator, TerminatorKind}; use rustc_target::abi::VariantIdx; use tracing::debug; use super::move_paths::{InitKind, LookupResult, MoveData, MovePathIndex}; -use super::MoveDataParamEnv; +use crate::elaborate_drops::DropFlagState; pub fn move_path_children_matching<'tcx, F>( move_data: &MoveData<'tcx>, @@ -70,12 +69,11 @@ pub fn on_all_children_bits<'tcx, F>( pub fn drop_flag_effects_for_function_entry<'tcx, F>( body: &Body<'tcx>, - ctxt: &MoveDataParamEnv<'tcx>, + move_data: &MoveData<'tcx>, mut callback: F, ) where F: FnMut(MovePathIndex, DropFlagState), { - let move_data = &ctxt.move_data; for arg in body.args_iter() { let place = mir::Place::from(arg); let lookup_result = move_data.rev_lookup.find(place.as_ref()); @@ -87,13 +85,12 @@ pub fn drop_flag_effects_for_function_entry<'tcx, F>( pub fn drop_flag_effects_for_location<'tcx, F>( body: &Body<'tcx>, - ctxt: &MoveDataParamEnv<'tcx>, + move_data: &MoveData<'tcx>, loc: Location, mut callback: F, ) where F: FnMut(MovePathIndex, DropFlagState), { - let move_data = &ctxt.move_data; debug!("drop_flag_effects_for_location({:?})", loc); // first, move out of the RHS diff --git a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs index e0da9600ae37f..2ec3b53bc9814 100644 --- a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs +++ b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs @@ -1,3 +1,5 @@ +use std::{fmt, iter}; + use rustc_hir::lang_items::LangItem; use rustc_index::Idx; use rustc_middle::mir::patch::MirPatch; @@ -5,12 +7,10 @@ use rustc_middle::mir::*; use rustc_middle::span_bug; use rustc_middle::traits::Reveal; use rustc_middle::ty::util::IntTypeExt; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt}; use rustc_span::source_map::Spanned; use rustc_span::DUMMY_SP; use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; -use std::{fmt, iter}; use tracing::{debug, instrument}; /// The value of an inserted drop flag. diff --git a/compiler/rustc_mir_dataflow/src/framework/cursor.rs b/compiler/rustc_mir_dataflow/src/framework/cursor.rs index 1bd9167be12ed..7cfaef22689fa 100644 --- a/compiler/rustc_mir_dataflow/src/framework/cursor.rs +++ b/compiler/rustc_mir_dataflow/src/framework/cursor.rs @@ -1,7 +1,5 @@ //! Random access inspection of the results of a dataflow analysis. -use crate::framework::BitSetExt; - use std::cmp::Ordering; #[cfg(debug_assertions)] @@ -9,6 +7,7 @@ use rustc_index::bit_set::BitSet; use rustc_middle::mir::{self, BasicBlock, Location}; use super::{Analysis, Direction, Effect, EffectIndex, Results}; +use crate::framework::BitSetExt; /// Allows random access inspection of the results of a dataflow analysis. /// diff --git a/compiler/rustc_mir_dataflow/src/framework/direction.rs b/compiler/rustc_mir_dataflow/src/framework/direction.rs index f57e8b8bd6f97..ba4a7d7651141 100644 --- a/compiler/rustc_mir_dataflow/src/framework/direction.rs +++ b/compiler/rustc_mir_dataflow/src/framework/direction.rs @@ -1,7 +1,8 @@ +use std::ops::RangeInclusive; + use rustc_middle::mir::{ self, BasicBlock, CallReturnPlaces, Location, SwitchTargets, TerminatorEdges, }; -use std::ops::RangeInclusive; use super::visitor::{ResultsVisitable, ResultsVisitor}; use super::{Analysis, Effect, EffectIndex, GenKillAnalysis, GenKillSet, SwitchIntTarget}; diff --git a/compiler/rustc_mir_dataflow/src/framework/engine.rs b/compiler/rustc_mir_dataflow/src/framework/engine.rs index 564a99e5df81b..364a416480fed 100644 --- a/compiler/rustc_mir_dataflow/src/framework/engine.rs +++ b/compiler/rustc_mir_dataflow/src/framework/engine.rs @@ -1,32 +1,28 @@ //! A solver for dataflow problems. -use crate::errors::{ - DuplicateValuesFor, PathMustEndInFilename, RequiresAnArgument, UnknownFormatter, -}; -use crate::framework::BitSetExt; - use std::ffi::OsString; use std::path::PathBuf; -use rustc_ast as ast; use rustc_data_structures::work_queue::WorkQueue; -use rustc_graphviz as dot; use rustc_hir::def_id::DefId; use rustc_index::{Idx, IndexVec}; use rustc_middle::bug; -use rustc_middle::mir::{self, traversal, BasicBlock}; -use rustc_middle::mir::{create_dump_file, dump_enabled}; +use rustc_middle::mir::{self, create_dump_file, dump_enabled, traversal, BasicBlock}; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::{sym, Symbol}; use tracing::{debug, error}; +use {rustc_ast as ast, rustc_graphviz as dot}; use super::fmt::DebugWithContext; -use super::graphviz; use super::{ - visit_results, Analysis, AnalysisDomain, Direction, GenKill, GenKillAnalysis, GenKillSet, - JoinSemiLattice, ResultsCursor, ResultsVisitor, + graphviz, visit_results, Analysis, AnalysisDomain, Direction, GenKill, GenKillAnalysis, + GenKillSet, JoinSemiLattice, ResultsCursor, ResultsVisitor, }; +use crate::errors::{ + DuplicateValuesFor, PathMustEndInFilename, RequiresAnArgument, UnknownFormatter, +}; +use crate::framework::BitSetExt; pub type EntrySets<'tcx, A> = IndexVec>::Domain>; diff --git a/compiler/rustc_mir_dataflow/src/framework/fmt.rs b/compiler/rustc_mir_dataflow/src/framework/fmt.rs index e3a66bd952c56..5e4f36e4ae3ae 100644 --- a/compiler/rustc_mir_dataflow/src/framework/fmt.rs +++ b/compiler/rustc_mir_dataflow/src/framework/fmt.rs @@ -1,10 +1,12 @@ //! Custom formatting traits used when outputting Graphviz diagrams with the results of a dataflow //! analysis. -use super::lattice::MaybeReachable; +use std::fmt; + use rustc_index::bit_set::{BitSet, ChunkedBitSet, HybridBitSet}; use rustc_index::Idx; -use std::fmt; + +use super::lattice::MaybeReachable; /// An extension to `fmt::Debug` for data that can be better printed with some auxiliary data `C`. pub trait DebugWithContext: Eq + fmt::Debug { diff --git a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs index a827f6a8dbd9d..2e860e2d84121 100644 --- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs +++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs @@ -8,8 +8,7 @@ use std::{io, ops, str}; use regex::Regex; use rustc_graphviz as dot; use rustc_index::bit_set::BitSet; -use rustc_middle::mir::graphviz_safe_def_name; -use rustc_middle::mir::{self, BasicBlock, Body, Location}; +use rustc_middle::mir::{self, graphviz_safe_def_name, BasicBlock, Body, Location}; use super::fmt::{DebugDiffWithAdapter, DebugWithAdapter, DebugWithContext}; use super::{Analysis, CallReturnPlaces, Direction, Results, ResultsCursor, ResultsVisitor}; diff --git a/compiler/rustc_mir_dataflow/src/framework/lattice.rs b/compiler/rustc_mir_dataflow/src/framework/lattice.rs index 23738f7a4a538..4d03ee53b7c00 100644 --- a/compiler/rustc_mir_dataflow/src/framework/lattice.rs +++ b/compiler/rustc_mir_dataflow/src/framework/lattice.rs @@ -38,10 +38,12 @@ //! [Hasse diagram]: https://en.wikipedia.org/wiki/Hasse_diagram //! [poset]: https://en.wikipedia.org/wiki/Partially_ordered_set -use crate::framework::BitSetExt; +use std::iter; + use rustc_index::bit_set::{BitSet, ChunkedBitSet, HybridBitSet}; use rustc_index::{Idx, IndexVec}; -use std::iter; + +use crate::framework::BitSetExt; /// A [partially ordered set][poset] that has a [least upper bound][lub] for any pair of elements /// in the set. diff --git a/compiler/rustc_mir_dataflow/src/impls/initialized.rs b/compiler/rustc_mir_dataflow/src/impls/initialized.rs index d44da42416dbb..e9e8ddefa020b 100644 --- a/compiler/rustc_mir_dataflow/src/impls/initialized.rs +++ b/compiler/rustc_mir_dataflow/src/impls/initialized.rs @@ -5,15 +5,14 @@ use rustc_middle::mir::{self, Body, CallReturnPlaces, Location, TerminatorEdges} use rustc_middle::ty::{self, TyCtxt}; use tracing::{debug, instrument}; -use crate::drop_flag_effects_for_function_entry; -use crate::drop_flag_effects_for_location; use crate::elaborate_drops::DropFlagState; use crate::framework::SwitchIntEdgeEffects; use crate::move_paths::{HasMoveData, InitIndex, InitKind, LookupResult, MoveData, MovePathIndex}; -use crate::on_lookup_result_bits; -use crate::MoveDataParamEnv; -use crate::{drop_flag_effects, on_all_children_bits}; -use crate::{lattice, AnalysisDomain, GenKill, GenKillAnalysis, MaybeReachable}; +use crate::{ + drop_flag_effects, drop_flag_effects_for_function_entry, drop_flag_effects_for_location, + lattice, on_all_children_bits, on_lookup_result_bits, AnalysisDomain, GenKill, GenKillAnalysis, + MaybeReachable, +}; /// `MaybeInitializedPlaces` tracks all places that might be /// initialized upon reaching a particular point in the control flow @@ -53,17 +52,13 @@ use crate::{lattice, AnalysisDomain, GenKill, GenKillAnalysis, MaybeReachable}; pub struct MaybeInitializedPlaces<'a, 'mir, 'tcx> { tcx: TyCtxt<'tcx>, body: &'mir Body<'tcx>, - mdpe: &'a MoveDataParamEnv<'tcx>, + move_data: &'a MoveData<'tcx>, skip_unreachable_unwind: bool, } impl<'a, 'mir, 'tcx> MaybeInitializedPlaces<'a, 'mir, 'tcx> { - pub fn new( - tcx: TyCtxt<'tcx>, - body: &'mir Body<'tcx>, - mdpe: &'a MoveDataParamEnv<'tcx>, - ) -> Self { - MaybeInitializedPlaces { tcx, body, mdpe, skip_unreachable_unwind: false } + pub fn new(tcx: TyCtxt<'tcx>, body: &'mir Body<'tcx>, move_data: &'a MoveData<'tcx>) -> Self { + MaybeInitializedPlaces { tcx, body, move_data, skip_unreachable_unwind: false } } pub fn skipping_unreachable_unwind(mut self) -> Self { @@ -90,7 +85,7 @@ impl<'a, 'mir, 'tcx> MaybeInitializedPlaces<'a, 'mir, 'tcx> { impl<'a, 'mir, 'tcx> HasMoveData<'tcx> for MaybeInitializedPlaces<'a, 'mir, 'tcx> { fn move_data(&self) -> &MoveData<'tcx> { - &self.mdpe.move_data + self.move_data } } @@ -132,22 +127,18 @@ impl<'a, 'mir, 'tcx> HasMoveData<'tcx> for MaybeInitializedPlaces<'a, 'mir, 'tcx pub struct MaybeUninitializedPlaces<'a, 'mir, 'tcx> { tcx: TyCtxt<'tcx>, body: &'mir Body<'tcx>, - mdpe: &'a MoveDataParamEnv<'tcx>, + move_data: &'a MoveData<'tcx>, mark_inactive_variants_as_uninit: bool, skip_unreachable_unwind: BitSet, } impl<'a, 'mir, 'tcx> MaybeUninitializedPlaces<'a, 'mir, 'tcx> { - pub fn new( - tcx: TyCtxt<'tcx>, - body: &'mir Body<'tcx>, - mdpe: &'a MoveDataParamEnv<'tcx>, - ) -> Self { + pub fn new(tcx: TyCtxt<'tcx>, body: &'mir Body<'tcx>, move_data: &'a MoveData<'tcx>) -> Self { MaybeUninitializedPlaces { tcx, body, - mdpe, + move_data, mark_inactive_variants_as_uninit: false, skip_unreachable_unwind: BitSet::new_empty(body.basic_blocks.len()), } @@ -174,7 +165,7 @@ impl<'a, 'mir, 'tcx> MaybeUninitializedPlaces<'a, 'mir, 'tcx> { impl<'a, 'tcx> HasMoveData<'tcx> for MaybeUninitializedPlaces<'a, '_, 'tcx> { fn move_data(&self) -> &MoveData<'tcx> { - &self.mdpe.move_data + self.move_data } } @@ -214,18 +205,18 @@ impl<'a, 'tcx> HasMoveData<'tcx> for MaybeUninitializedPlaces<'a, '_, 'tcx> { /// that would require a dynamic drop-flag at that statement. pub struct DefinitelyInitializedPlaces<'a, 'tcx> { body: &'a Body<'tcx>, - mdpe: &'a MoveDataParamEnv<'tcx>, + move_data: &'a MoveData<'tcx>, } impl<'a, 'tcx> DefinitelyInitializedPlaces<'a, 'tcx> { - pub fn new(body: &'a Body<'tcx>, mdpe: &'a MoveDataParamEnv<'tcx>) -> Self { - DefinitelyInitializedPlaces { body, mdpe } + pub fn new(body: &'a Body<'tcx>, move_data: &'a MoveData<'tcx>) -> Self { + DefinitelyInitializedPlaces { body, move_data } } } impl<'a, 'tcx> HasMoveData<'tcx> for DefinitelyInitializedPlaces<'a, 'tcx> { fn move_data(&self) -> &MoveData<'tcx> { - &self.mdpe.move_data + self.move_data } } @@ -260,18 +251,18 @@ impl<'a, 'tcx> HasMoveData<'tcx> for DefinitelyInitializedPlaces<'a, 'tcx> { /// ``` pub struct EverInitializedPlaces<'a, 'mir, 'tcx> { body: &'mir Body<'tcx>, - mdpe: &'a MoveDataParamEnv<'tcx>, + move_data: &'a MoveData<'tcx>, } impl<'a, 'mir, 'tcx> EverInitializedPlaces<'a, 'mir, 'tcx> { - pub fn new(body: &'mir Body<'tcx>, mdpe: &'a MoveDataParamEnv<'tcx>) -> Self { - EverInitializedPlaces { body, mdpe } + pub fn new(body: &'mir Body<'tcx>, move_data: &'a MoveData<'tcx>) -> Self { + EverInitializedPlaces { body, move_data } } } impl<'a, 'tcx> HasMoveData<'tcx> for EverInitializedPlaces<'a, '_, 'tcx> { fn move_data(&self) -> &MoveData<'tcx> { - &self.mdpe.move_data + self.move_data } } @@ -329,7 +320,7 @@ impl<'tcx> AnalysisDomain<'tcx> for MaybeInitializedPlaces<'_, '_, 'tcx> { fn initialize_start_block(&self, _: &mir::Body<'tcx>, state: &mut Self::Domain) { *state = MaybeReachable::Reachable(ChunkedBitSet::new_empty(self.move_data().move_paths.len())); - drop_flag_effects_for_function_entry(self.body, self.mdpe, |path, s| { + drop_flag_effects_for_function_entry(self.body, self.move_data, |path, s| { assert!(s == DropFlagState::Present); state.gen_(path); }); @@ -349,7 +340,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for MaybeInitializedPlaces<'_, '_, 'tcx> { statement: &mir::Statement<'tcx>, location: Location, ) { - drop_flag_effects_for_location(self.body, self.mdpe, location, |path, s| { + drop_flag_effects_for_location(self.body, self.move_data, location, |path, s| { Self::update_bits(trans, path, s) }); @@ -381,7 +372,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for MaybeInitializedPlaces<'_, '_, 'tcx> { { edges = TerminatorEdges::Single(target); } - drop_flag_effects_for_location(self.body, self.mdpe, location, |path, s| { + drop_flag_effects_for_location(self.body, self.move_data, location, |path, s| { Self::update_bits(state, path, s) }); edges @@ -466,7 +457,7 @@ impl<'tcx> AnalysisDomain<'tcx> for MaybeUninitializedPlaces<'_, '_, 'tcx> { // set all bits to 1 (uninit) before gathering counter-evidence state.insert_all(); - drop_flag_effects_for_function_entry(self.body, self.mdpe, |path, s| { + drop_flag_effects_for_function_entry(self.body, self.move_data, |path, s| { assert!(s == DropFlagState::Present); state.remove(path); }); @@ -486,7 +477,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for MaybeUninitializedPlaces<'_, '_, 'tcx> { _statement: &mir::Statement<'tcx>, location: Location, ) { - drop_flag_effects_for_location(self.body, self.mdpe, location, |path, s| { + drop_flag_effects_for_location(self.body, self.move_data, location, |path, s| { Self::update_bits(trans, path, s) }); @@ -500,7 +491,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for MaybeUninitializedPlaces<'_, '_, 'tcx> { terminator: &'mir mir::Terminator<'tcx>, location: Location, ) -> TerminatorEdges<'mir, 'tcx> { - drop_flag_effects_for_location(self.body, self.mdpe, location, |path, s| { + drop_flag_effects_for_location(self.body, self.move_data, location, |path, s| { Self::update_bits(trans, path, s) }); if self.skip_unreachable_unwind.contains(location.block) { @@ -593,7 +584,7 @@ impl<'a, 'tcx> AnalysisDomain<'tcx> for DefinitelyInitializedPlaces<'a, 'tcx> { fn initialize_start_block(&self, _: &mir::Body<'tcx>, state: &mut Self::Domain) { state.0.clear(); - drop_flag_effects_for_function_entry(self.body, self.mdpe, |path, s| { + drop_flag_effects_for_function_entry(self.body, self.move_data, |path, s| { assert!(s == DropFlagState::Present); state.0.insert(path); }); @@ -613,7 +604,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for DefinitelyInitializedPlaces<'_, 'tcx> { _statement: &mir::Statement<'tcx>, location: Location, ) { - drop_flag_effects_for_location(self.body, self.mdpe, location, |path, s| { + drop_flag_effects_for_location(self.body, self.move_data, location, |path, s| { Self::update_bits(trans, path, s) }) } @@ -624,7 +615,7 @@ impl<'tcx> GenKillAnalysis<'tcx> for DefinitelyInitializedPlaces<'_, 'tcx> { terminator: &'mir mir::Terminator<'tcx>, location: Location, ) -> TerminatorEdges<'mir, 'tcx> { - drop_flag_effects_for_location(self.body, self.mdpe, location, |path, s| { + drop_flag_effects_for_location(self.body, self.move_data, location, |path, s| { Self::update_bits(trans, path, s) }); terminator.edges() diff --git a/compiler/rustc_mir_dataflow/src/impls/mod.rs b/compiler/rustc_mir_dataflow/src/impls/mod.rs index f8db18fc1f8d1..f283660e1e793 100644 --- a/compiler/rustc_mir_dataflow/src/impls/mod.rs +++ b/compiler/rustc_mir_dataflow/src/impls/mod.rs @@ -7,13 +7,12 @@ mod initialized; mod liveness; mod storage_liveness; -pub use self::borrowed_locals::borrowed_locals; -pub use self::borrowed_locals::MaybeBorrowedLocals; +pub use self::borrowed_locals::{borrowed_locals, MaybeBorrowedLocals}; pub use self::initialized::{ DefinitelyInitializedPlaces, EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces, }; -pub use self::liveness::MaybeLiveLocals; -pub use self::liveness::MaybeTransitiveLiveLocals; -pub use self::liveness::TransferFunction as LivenessTransferFunction; +pub use self::liveness::{ + MaybeLiveLocals, MaybeTransitiveLiveLocals, TransferFunction as LivenessTransferFunction, +}; pub use self::storage_liveness::{MaybeRequiresStorage, MaybeStorageDead, MaybeStorageLive}; diff --git a/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs b/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs index 682cec12f1fbd..9f2f0187698a8 100644 --- a/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs +++ b/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs @@ -1,9 +1,9 @@ +use std::borrow::Cow; + use rustc_index::bit_set::BitSet; use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; -use std::borrow::Cow; - use super::MaybeBorrowedLocals; use crate::{GenKill, ResultsCursor}; diff --git a/compiler/rustc_mir_dataflow/src/move_paths/builder.rs b/compiler/rustc_mir_dataflow/src/move_paths/builder.rs index 7b39db821d839..c26a72e454382 100644 --- a/compiler/rustc_mir_dataflow/src/move_paths/builder.rs +++ b/compiler/rustc_mir_dataflow/src/move_paths/builder.rs @@ -1,3 +1,5 @@ +use std::mem; + use rustc_index::IndexVec; use rustc_middle::mir::tcx::{PlaceTy, RvalueInitializationState}; use rustc_middle::mir::*; @@ -6,12 +8,10 @@ use rustc_middle::{bug, span_bug}; use smallvec::{smallvec, SmallVec}; use tracing::debug; -use std::mem; - use super::abs_domain::Lift; -use super::{Init, InitIndex, InitKind, InitLocation, LookupResult}; use super::{ - LocationMap, MoveData, MoveOut, MoveOutIndex, MovePath, MovePathIndex, MovePathLookup, + Init, InitIndex, InitKind, InitLocation, LocationMap, LookupResult, MoveData, MoveOut, + MoveOutIndex, MovePath, MovePathIndex, MovePathLookup, }; struct MoveDataBuilder<'a, 'tcx, F> { diff --git a/compiler/rustc_mir_dataflow/src/move_paths/mod.rs b/compiler/rustc_mir_dataflow/src/move_paths/mod.rs index 830f44df5fb39..bc1177976b5de 100644 --- a/compiler/rustc_mir_dataflow/src/move_paths/mod.rs +++ b/compiler/rustc_mir_dataflow/src/move_paths/mod.rs @@ -1,4 +1,6 @@ -use crate::un_derefer::UnDerefer; +use std::fmt; +use std::ops::{Index, IndexMut}; + use rustc_data_structures::fx::FxHashMap; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::mir::*; @@ -6,10 +8,8 @@ use rustc_middle::ty::{ParamEnv, Ty, TyCtxt}; use rustc_span::Span; use smallvec::SmallVec; -use std::fmt; -use std::ops::{Index, IndexMut}; - use self::abs_domain::{AbstractElem, Lift}; +use crate::un_derefer::UnDerefer; mod abs_domain; diff --git a/compiler/rustc_mir_dataflow/src/points.rs b/compiler/rustc_mir_dataflow/src/points.rs index bbfb37d2a8265..4be7492366ad3 100644 --- a/compiler/rustc_mir_dataflow/src/points.rs +++ b/compiler/rustc_mir_dataflow/src/points.rs @@ -1,10 +1,10 @@ -use crate::framework::{visit_results, ResultsVisitable, ResultsVisitor}; use rustc_index::bit_set::BitSet; use rustc_index::interval::SparseIntervalMatrix; -use rustc_index::Idx; -use rustc_index::IndexVec; +use rustc_index::{Idx, IndexVec}; use rustc_middle::mir::{self, BasicBlock, Body, Location}; +use crate::framework::{visit_results, ResultsVisitable, ResultsVisitor}; + /// Maps between a `Location` and a `PointIndex` (and vice versa). pub struct DenseLocationMap { /// For each basic block, how many points are contained within? diff --git a/compiler/rustc_mir_dataflow/src/rustc_peek.rs b/compiler/rustc_mir_dataflow/src/rustc_peek.rs index 1de9055273b73..0171cc8591809 100644 --- a/compiler/rustc_mir_dataflow/src/rustc_peek.rs +++ b/compiler/rustc_mir_dataflow/src/rustc_peek.rs @@ -1,3 +1,12 @@ +use rustc_ast::MetaItem; +use rustc_hir::def_id::DefId; +use rustc_index::bit_set::BitSet; +use rustc_middle::mir::{self, Body, Local, Location, MirPass}; +use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_span::symbol::{sym, Symbol}; +use rustc_span::Span; +use tracing::{debug, info}; + use crate::errors::{ PeekArgumentNotALocal, PeekArgumentUntracked, PeekBitNotSet, PeekMustBeNotTemporary, PeekMustBePlaceOrRefPlace, StopAfterDataFlowEndedCompilation, @@ -6,19 +15,8 @@ use crate::framework::BitSetExt; use crate::impls::{ DefinitelyInitializedPlaces, MaybeInitializedPlaces, MaybeLiveLocals, MaybeUninitializedPlaces, }; -use crate::move_paths::{HasMoveData, MoveData}; -use crate::move_paths::{LookupResult, MovePathIndex}; -use crate::MoveDataParamEnv; +use crate::move_paths::{HasMoveData, LookupResult, MoveData, MovePathIndex}; use crate::{Analysis, JoinSemiLattice, ResultsCursor}; -use rustc_ast::MetaItem; -use rustc_hir::def_id::DefId; -use rustc_index::bit_set::BitSet; -use rustc_middle::mir::MirPass; -use rustc_middle::mir::{self, Body, Local, Location}; -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_span::symbol::{sym, Symbol}; -use rustc_span::Span; -use tracing::{debug, info}; pub struct SanityCheck; @@ -48,10 +46,9 @@ impl<'tcx> MirPass<'tcx> for SanityCheck { let param_env = tcx.param_env(def_id); let move_data = MoveData::gather_moves(body, tcx, param_env, |_| true); - let mdpe = MoveDataParamEnv { move_data, param_env }; if has_rustc_mir_with(tcx, def_id, sym::rustc_peek_maybe_init).is_some() { - let flow_inits = MaybeInitializedPlaces::new(tcx, body, &mdpe) + let flow_inits = MaybeInitializedPlaces::new(tcx, body, &move_data) .into_engine(tcx, body) .iterate_to_fixpoint(); @@ -59,7 +56,7 @@ impl<'tcx> MirPass<'tcx> for SanityCheck { } if has_rustc_mir_with(tcx, def_id, sym::rustc_peek_maybe_uninit).is_some() { - let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe) + let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &move_data) .into_engine(tcx, body) .iterate_to_fixpoint(); @@ -67,7 +64,7 @@ impl<'tcx> MirPass<'tcx> for SanityCheck { } if has_rustc_mir_with(tcx, def_id, sym::rustc_peek_definite_init).is_some() { - let flow_def_inits = DefinitelyInitializedPlaces::new(body, &mdpe) + let flow_def_inits = DefinitelyInitializedPlaces::new(body, &move_data) .into_engine(tcx, body) .iterate_to_fixpoint(); diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index c9f5d38fe2c1c..ca8a2777045f4 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -48,10 +48,9 @@ use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_target::abi::{FieldIdx, VariantIdx}; use tracing::debug; +use crate::fmt::DebugWithContext; use crate::lattice::{HasBottom, HasTop}; -use crate::{ - fmt::DebugWithContext, Analysis, AnalysisDomain, JoinSemiLattice, SwitchIntEdgeEffects, -}; +use crate::{Analysis, AnalysisDomain, JoinSemiLattice, SwitchIntEdgeEffects}; pub trait ValueAnalysis<'tcx> { /// For each place of interest, the analysis tracks a value of the given type. diff --git a/compiler/rustc_mir_transform/Cargo.toml b/compiler/rustc_mir_transform/Cargo.toml index f864a13a31bbc..07ca51a67aefb 100644 --- a/compiler/rustc_mir_transform/Cargo.toml +++ b/compiler/rustc_mir_transform/Cargo.toml @@ -25,6 +25,7 @@ rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } +rustc_type_ir = { path = "../rustc_type_ir" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } tracing = "0.1" # tidy-alphabetical-end diff --git a/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs b/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs index d43fca3dc7efe..f52a4524d784b 100644 --- a/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs +++ b/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs @@ -1,8 +1,7 @@ use rustc_ast::InlineAsmOptions; use rustc_middle::mir::*; use rustc_middle::span_bug; -use rustc_middle::ty::layout; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{self, layout, TyCtxt}; use rustc_target::spec::abi::Abi; use rustc_target::spec::PanicStrategy; diff --git a/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs b/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs index de6d20ae3e807..cd850e2d73189 100644 --- a/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs +++ b/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs @@ -1,8 +1,8 @@ +use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; use crate::util; -use rustc_middle::mir::patch::MirPatch; /// This pass moves values being dropped that are within a packed /// struct to a separate local before dropping them, to ensure that diff --git a/compiler/rustc_mir_transform/src/check_alignment.rs b/compiler/rustc_mir_transform/src/check_alignment.rs index 5199c41c58cd4..a1dbd7dc50ec7 100644 --- a/compiler/rustc_mir_transform/src/check_alignment.rs +++ b/compiler/rustc_mir_transform/src/check_alignment.rs @@ -1,10 +1,8 @@ use rustc_hir::lang_items::LangItem; use rustc_index::IndexVec; +use rustc_middle::mir::interpret::Scalar; +use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; -use rustc_middle::mir::{ - interpret::Scalar, - visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor}, -}; use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt}; use rustc_session::Session; diff --git a/compiler/rustc_mir_transform/src/check_packed_ref.rs b/compiler/rustc_mir_transform/src/check_packed_ref.rs index 5f67bd75c48a2..9902002580aed 100644 --- a/compiler/rustc_mir_transform/src/check_packed_ref.rs +++ b/compiler/rustc_mir_transform/src/check_packed_ref.rs @@ -3,8 +3,7 @@ use rustc_middle::mir::*; use rustc_middle::span_bug; use rustc_middle::ty::{self, TyCtxt}; -use crate::MirLint; -use crate::{errors, util}; +use crate::{errors, util, MirLint}; pub struct CheckPackedRef; diff --git a/compiler/rustc_mir_transform/src/cleanup_post_borrowck.rs b/compiler/rustc_mir_transform/src/cleanup_post_borrowck.rs index 264d8a1399604..08c9f9f08e6b2 100644 --- a/compiler/rustc_mir_transform/src/cleanup_post_borrowck.rs +++ b/compiler/rustc_mir_transform/src/cleanup_post_borrowck.rs @@ -16,12 +16,13 @@ //! [`BlockMarker`]: rustc_middle::mir::coverage::CoverageKind::BlockMarker //! [`SpanMarker`]: rustc_middle::mir::coverage::CoverageKind::SpanMarker -use crate::MirPass; use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::mir::{Body, BorrowKind, CastKind, Rvalue, StatementKind, TerminatorKind}; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::TyCtxt; +use crate::MirPass; + pub struct CleanupPostBorrowck; impl<'tcx> MirPass<'tcx> for CleanupPostBorrowck { diff --git a/compiler/rustc_mir_transform/src/coroutine.rs b/compiler/rustc_mir_transform/src/coroutine.rs index 658cc4c51a948..82528109be9ab 100644 --- a/compiler/rustc_mir_transform/src/coroutine.rs +++ b/compiler/rustc_mir_transform/src/coroutine.rs @@ -51,13 +51,9 @@ //! Otherwise it drops all the values in scope at the last suspension point. mod by_move_body; -pub use by_move_body::ByMoveBody; +use std::{iter, ops}; -use crate::abort_unwinding_calls; -use crate::deref_separator::deref_finder; -use crate::errors; -use crate::pass_manager as pm; -use crate::simplify; +pub use by_move_body::ByMoveBody; use rustc_data_structures::fx::FxHashSet; use rustc_errors::pluralize; use rustc_hir as hir; @@ -67,9 +63,7 @@ use rustc_index::bit_set::{BitMatrix, BitSet, GrowableBitSet}; use rustc_index::{Idx, IndexVec}; use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor}; use rustc_middle::mir::*; -use rustc_middle::ty::CoroutineArgs; -use rustc_middle::ty::InstanceKind; -use rustc_middle::ty::{self, CoroutineArgsExt, Ty, TyCtxt}; +use rustc_middle::ty::{self, CoroutineArgs, CoroutineArgsExt, InstanceKind, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_mir_dataflow::impls::{ MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive, @@ -83,9 +77,10 @@ use rustc_target::abi::{FieldIdx, VariantIdx}; use rustc_target::spec::PanicStrategy; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::TyCtxtInferExt as _; -use rustc_trait_selection::traits::ObligationCtxt; -use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode}; -use std::{iter, ops}; +use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt}; + +use crate::deref_separator::deref_finder; +use crate::{abort_unwinding_calls, errors, pass_manager as pm, simplify}; pub struct StateTransform; @@ -1167,10 +1162,11 @@ fn insert_switch<'tcx>( } fn elaborate_coroutine_drops<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { - use crate::shim::DropShimElaborator; use rustc_middle::mir::patch::MirPatch; use rustc_mir_dataflow::elaborate_drops::{elaborate_drop, Unwind}; + use crate::shim::DropShimElaborator; + // Note that `elaborate_drops` only drops the upvars of a coroutine, and // this is ok because `open_drop` can only be reached within that own // coroutine's resume function. diff --git a/compiler/rustc_mir_transform/src/coverage/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs index 83fb9ff974369..c3f4bbf1a6521 100644 --- a/compiler/rustc_mir_transform/src/coverage/graph.rs +++ b/compiler/rustc_mir_transform/src/coverage/graph.rs @@ -1,3 +1,7 @@ +use std::cmp::Ordering; +use std::collections::VecDeque; +use std::ops::{Index, IndexMut}; + use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::graph::dominators::{self, Dominators}; @@ -7,10 +11,6 @@ use rustc_index::IndexVec; use rustc_middle::bug; use rustc_middle::mir::{self, BasicBlock, Terminator, TerminatorKind}; -use std::cmp::Ordering; -use std::collections::VecDeque; -use std::ops::{Index, IndexMut}; - /// A coverage-specific simplification of the MIR control flow graph (CFG). The `CoverageGraph`s /// nodes are `BasicCoverageBlock`s, which encompass one or more MIR `BasicBlock`s. #[derive(Debug)] diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index 3772a8f511814..96ca3b43d5c2a 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -147,7 +147,8 @@ fn create_mappings<'tcx>( let source_file = source_map.lookup_source_file(body_span.lo()); - use rustc_session::{config::RemapPathScopeComponents, RemapFileNameExt}; + use rustc_session::config::RemapPathScopeComponents; + use rustc_session::RemapFileNameExt; let file_name = Symbol::intern( &source_file.name.for_scope(tcx.sess, RemapPathScopeComponents::MACRO).to_string_lossy(), ); diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index dbc26a2808edd..092ec1e06d240 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -6,11 +6,10 @@ use rustc_middle::mir; use rustc_span::Span; use crate::coverage::graph::{BasicCoverageBlock, CoverageGraph}; -use crate::coverage::mappings; use crate::coverage::spans::from_mir::{ extract_covspans_from_mir, ExtractedCovspans, Hole, SpanFromMir, }; -use crate::coverage::ExtractedHirInfo; +use crate::coverage::{mappings, ExtractedHirInfo}; mod from_mir; diff --git a/compiler/rustc_mir_transform/src/coverage/tests.rs b/compiler/rustc_mir_transform/src/coverage/tests.rs index 63a9f303b8521..a4db11bb2c160 100644 --- a/compiler/rustc_mir_transform/src/coverage/tests.rs +++ b/compiler/rustc_mir_transform/src/coverage/tests.rs @@ -24,16 +24,15 @@ //! globals is comparatively simpler. The easiest way is to wrap the test in a closure argument //! to: `rustc_span::create_default_session_globals_then(|| { test_here(); })`. -use super::graph::{self, BasicCoverageBlock}; - use itertools::Itertools; use rustc_data_structures::graph::{DirectedGraph, Successors}; use rustc_index::{Idx, IndexVec}; -use rustc_middle::bug; use rustc_middle::mir::*; -use rustc_middle::ty; +use rustc_middle::{bug, ty}; use rustc_span::{BytePos, Pos, Span, DUMMY_SP}; +use super::graph::{self, BasicCoverageBlock}; + fn bcb(index: u32) -> BasicCoverageBlock { BasicCoverageBlock::from_u32(index) } diff --git a/compiler/rustc_mir_transform/src/cross_crate_inline.rs b/compiler/rustc_mir_transform/src/cross_crate_inline.rs index 483fd753e7077..50aaed090f6b8 100644 --- a/compiler/rustc_mir_transform/src/cross_crate_inline.rs +++ b/compiler/rustc_mir_transform/src/cross_crate_inline.rs @@ -1,5 +1,3 @@ -use crate::inline; -use crate::pass_manager as pm; use rustc_attr::InlineAttr; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; @@ -7,10 +5,11 @@ use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; -use rustc_session::config::InliningThreshold; -use rustc_session::config::OptLevel; +use rustc_session::config::{InliningThreshold, OptLevel}; use rustc_span::sym; +use crate::{inline, pass_manager as pm}; + pub fn provide(providers: &mut Providers) { providers.cross_crate_inlinable = cross_crate_inlinable; } diff --git a/compiler/rustc_mir_transform/src/ctfe_limit.rs b/compiler/rustc_mir_transform/src/ctfe_limit.rs index a0dddec185cc8..ff9fc776e541f 100644 --- a/compiler/rustc_mir_transform/src/ctfe_limit.rs +++ b/compiler/rustc_mir_transform/src/ctfe_limit.rs @@ -1,14 +1,14 @@ //! A pass that inserts the `ConstEvalCounter` instruction into any blocks that have a back edge //! (thus indicating there is a loop in the CFG), or whose terminator is a function call. -use crate::MirPass; - use rustc_data_structures::graph::dominators::Dominators; use rustc_middle::mir::{ BasicBlock, BasicBlockData, Body, Statement, StatementKind, TerminatorKind, }; use rustc_middle::ty::TyCtxt; +use crate::MirPass; + pub struct CtfeLimit; impl<'tcx> MirPass<'tcx> for CtfeLimit { diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index 8303ef039d183..0fc4d6b9f4e1e 100644 --- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs +++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs @@ -12,10 +12,11 @@ use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor}; use rustc_middle::mir::*; use rustc_middle::ty::layout::{HasParamEnv, LayoutOf}; use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_mir_dataflow::lattice::FlatSet; use rustc_mir_dataflow::value_analysis::{ Map, PlaceIndex, State, TrackElem, ValueAnalysis, ValueAnalysisWrapper, ValueOrPlace, }; -use rustc_mir_dataflow::{lattice::FlatSet, Analysis, Results, ResultsVisitor}; +use rustc_mir_dataflow::{Analysis, Results, ResultsVisitor}; use rustc_span::DUMMY_SP; use rustc_target::abi::{Abi, FieldIdx, Size, VariantIdx, FIRST_VARIANT}; diff --git a/compiler/rustc_mir_transform/src/dead_store_elimination.rs b/compiler/rustc_mir_transform/src/dead_store_elimination.rs index 60230bea02e29..f473073083af4 100644 --- a/compiler/rustc_mir_transform/src/dead_store_elimination.rs +++ b/compiler/rustc_mir_transform/src/dead_store_elimination.rs @@ -12,7 +12,6 @@ //! will still not cause any further changes. //! -use crate::util::is_within_packed; use rustc_middle::bug; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; @@ -23,6 +22,8 @@ use rustc_mir_dataflow::impls::{ }; use rustc_mir_dataflow::Analysis; +use crate::util::is_within_packed; + /// Performs the optimization on the body /// /// The `borrowed` set must be a `BitSet` of all the locals that are ever borrowed in this body. It diff --git a/compiler/rustc_mir_transform/src/deduplicate_blocks.rs b/compiler/rustc_mir_transform/src/deduplicate_blocks.rs index 824974970bb3f..4a94c3eca8658 100644 --- a/compiler/rustc_mir_transform/src/deduplicate_blocks.rs +++ b/compiler/rustc_mir_transform/src/deduplicate_blocks.rs @@ -1,7 +1,9 @@ //! This pass finds basic blocks that are completely equal, //! and replaces all uses with just one of them. -use std::{collections::hash_map::Entry, hash::Hash, hash::Hasher, iter}; +use std::collections::hash_map::Entry; +use std::hash::{Hash, Hasher}; +use std::iter; use rustc_data_structures::fx::FxHashMap; use rustc_middle::mir::visit::MutVisitor; diff --git a/compiler/rustc_mir_transform/src/dest_prop.rs b/compiler/rustc_mir_transform/src/dest_prop.rs index ab73a8af317a7..054cdbc6bad9f 100644 --- a/compiler/rustc_mir_transform/src/dest_prop.rs +++ b/compiler/rustc_mir_transform/src/dest_prop.rs @@ -131,23 +131,22 @@ //! [attempt 2]: https://github.com/rust-lang/rust/pull/71003 //! [attempt 3]: https://github.com/rust-lang/rust/pull/72632 -use crate::MirPass; use rustc_data_structures::fx::{FxIndexMap, IndexEntry, IndexOccupiedEntry}; use rustc_index::bit_set::BitSet; use rustc_index::interval::SparseIntervalMatrix; use rustc_middle::bug; use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor}; -use rustc_middle::mir::HasLocalDecls; -use rustc_middle::mir::{dump_mir, PassWhere}; use rustc_middle::mir::{ - traversal, Body, InlineAsmOperand, Local, LocalKind, Location, Operand, Place, Rvalue, - Statement, StatementKind, TerminatorKind, + dump_mir, traversal, Body, HasLocalDecls, InlineAsmOperand, Local, LocalKind, Location, + Operand, PassWhere, Place, Rvalue, Statement, StatementKind, TerminatorKind, }; use rustc_middle::ty::TyCtxt; use rustc_mir_dataflow::impls::MaybeLiveLocals; use rustc_mir_dataflow::points::{save_as_intervals, DenseLocationMap, PointIndex}; use rustc_mir_dataflow::Analysis; +use crate::MirPass; + pub struct DestinationPropagation; impl<'tcx> MirPass<'tcx> for DestinationPropagation { diff --git a/compiler/rustc_mir_transform/src/dump_mir.rs b/compiler/rustc_mir_transform/src/dump_mir.rs index 3b71cf02c1a0a..29db45f94506f 100644 --- a/compiler/rustc_mir_transform/src/dump_mir.rs +++ b/compiler/rustc_mir_transform/src/dump_mir.rs @@ -3,12 +3,12 @@ use std::fs::File; use std::io; -use crate::MirPass; -use rustc_middle::mir::write_mir_pretty; -use rustc_middle::mir::Body; +use rustc_middle::mir::{write_mir_pretty, Body}; use rustc_middle::ty::TyCtxt; use rustc_session::config::{OutFileName, OutputType}; +use crate::MirPass; + pub struct Marker(pub &'static str); impl<'tcx> MirPass<'tcx> for Marker { diff --git a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs index 40c0c723d255a..e4fec786814d6 100644 --- a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs +++ b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs @@ -1,7 +1,8 @@ +use std::fmt::Debug; + use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::*; use rustc_middle::ty::{Ty, TyCtxt}; -use std::fmt::Debug; use super::simplify::simplify_cfg; diff --git a/compiler/rustc_mir_transform/src/elaborate_drops.rs b/compiler/rustc_mir_transform/src/elaborate_drops.rs index 25bebb0539a4f..5a22ef7790349 100644 --- a/compiler/rustc_mir_transform/src/elaborate_drops.rs +++ b/compiler/rustc_mir_transform/src/elaborate_drops.rs @@ -1,20 +1,22 @@ -use crate::deref_separator::deref_finder; +use std::fmt; + use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::*; use rustc_middle::ty::{self, TyCtxt}; -use rustc_mir_dataflow::elaborate_drops::{elaborate_drop, DropFlagState, Unwind}; -use rustc_mir_dataflow::elaborate_drops::{DropElaborator, DropFlagMode, DropStyle}; +use rustc_mir_dataflow::elaborate_drops::{ + elaborate_drop, DropElaborator, DropFlagMode, DropFlagState, DropStyle, Unwind, +}; use rustc_mir_dataflow::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces}; use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex}; -use rustc_mir_dataflow::on_all_children_bits; -use rustc_mir_dataflow::on_lookup_result_bits; -use rustc_mir_dataflow::MoveDataParamEnv; -use rustc_mir_dataflow::{Analysis, ResultsCursor}; +use rustc_mir_dataflow::{ + on_all_children_bits, on_lookup_result_bits, Analysis, MoveDataParamEnv, ResultsCursor, +}; use rustc_span::Span; use rustc_target::abi::{FieldIdx, VariantIdx}; -use std::fmt; + +use crate::deref_separator::deref_finder; /// During MIR building, Drop terminators are inserted in every place where a drop may occur. /// However, in this phase, the presence of these terminators does not guarantee that a destructor will run, @@ -60,7 +62,7 @@ impl<'tcx> MirPass<'tcx> for ElaborateDrops { let elaborate_patch = { let env = MoveDataParamEnv { move_data, param_env }; - let mut inits = MaybeInitializedPlaces::new(tcx, body, &env) + let mut inits = MaybeInitializedPlaces::new(tcx, body, &env.move_data) .skipping_unreachable_unwind() .into_engine(tcx, body) .pass_name("elaborate_drops") @@ -68,7 +70,7 @@ impl<'tcx> MirPass<'tcx> for ElaborateDrops { .into_results_cursor(body); let dead_unwinds = compute_dead_unwinds(body, &mut inits); - let uninits = MaybeUninitializedPlaces::new(tcx, body, &env) + let uninits = MaybeUninitializedPlaces::new(tcx, body, &env.move_data) .mark_inactive_variants_as_uninit() .skipping_unreachable_unwind(dead_unwinds) .into_engine(tcx, body) @@ -441,9 +443,13 @@ impl<'b, 'mir, 'tcx> ElaborateDropsCtxt<'b, 'mir, 'tcx> { fn drop_flags_for_args(&mut self) { let loc = Location::START; - rustc_mir_dataflow::drop_flag_effects_for_function_entry(self.body, self.env, |path, ds| { - self.set_drop_flag(loc, path, ds); - }) + rustc_mir_dataflow::drop_flag_effects_for_function_entry( + self.body, + &self.env.move_data, + |path, ds| { + self.set_drop_flag(loc, path, ds); + }, + ) } fn drop_flags_for_locs(&mut self) { @@ -476,7 +482,7 @@ impl<'b, 'mir, 'tcx> ElaborateDropsCtxt<'b, 'mir, 'tcx> { let loc = Location { block: bb, statement_index: i }; rustc_mir_dataflow::drop_flag_effects_for_location( self.body, - self.env, + &self.env.move_data, loc, |path, ds| self.set_drop_flag(loc, path, ds), ) diff --git a/compiler/rustc_mir_transform/src/errors.rs b/compiler/rustc_mir_transform/src/errors.rs index dc7648d27b560..2703dc57cdad9 100644 --- a/compiler/rustc_mir_transform/src/errors.rs +++ b/compiler/rustc_mir_transform/src/errors.rs @@ -1,4 +1,5 @@ -use rustc_errors::{codes::*, Diag, LintDiagnostic}; +use rustc_errors::codes::*; +use rustc_errors::{Diag, LintDiagnostic}; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::mir::AssertKind; use rustc_middle::ty::TyCtxt; diff --git a/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs b/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs index 0cb304da80a10..4132e604f20e0 100644 --- a/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs +++ b/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs @@ -1,9 +1,7 @@ use rustc_hir::def_id::{LocalDefId, LOCAL_CRATE}; use rustc_middle::mir::*; -use rustc_middle::query::LocalCrate; -use rustc_middle::query::Providers; -use rustc_middle::ty::layout; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::query::{LocalCrate, Providers}; +use rustc_middle::ty::{self, layout, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_session::lint::builtin::FFI_UNWIND_CALLS; use rustc_target::spec::abi::Abi; diff --git a/compiler/rustc_mir_transform/src/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs index 434529ccff4bc..b7873e73c18c7 100644 --- a/compiler/rustc_mir_transform/src/function_item_references.rs +++ b/compiler/rustc_mir_transform/src/function_item_references.rs @@ -5,7 +5,8 @@ use rustc_middle::mir::*; use rustc_middle::ty::{self, EarlyBinder, GenericArgsRef, Ty, TyCtxt}; use rustc_session::lint::builtin::FUNCTION_ITEM_REFERENCES; use rustc_span::source_map::Spanned; -use rustc_span::{symbol::sym, Span}; +use rustc_span::symbol::sym; +use rustc_span::Span; use rustc_target::spec::abi::Abi; use crate::{errors, MirLint}; diff --git a/compiler/rustc_mir_transform/src/gvn.rs b/compiler/rustc_mir_transform/src/gvn.rs index 1002746e553d7..e16911d79c378 100644 --- a/compiler/rustc_mir_transform/src/gvn.rs +++ b/compiler/rustc_mir_transform/src/gvn.rs @@ -82,15 +82,19 @@ //! Second, when writing constants in MIR, we do not write `Const::Slice` or `Const` //! that contain `AllocId`s. +use std::borrow::Cow; + +use either::Either; use rustc_const_eval::const_eval::DummyMachine; -use rustc_const_eval::interpret::{intern_const_alloc_for_constprop, MemPlaceMeta, MemoryKind}; -use rustc_const_eval::interpret::{ImmTy, Immediate, InterpCx, OpTy, Projectable, Scalar}; +use rustc_const_eval::interpret::{ + intern_const_alloc_for_constprop, ImmTy, Immediate, InterpCx, MemPlaceMeta, MemoryKind, OpTy, + Projectable, Scalar, +}; use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::graph::dominators::Dominators; use rustc_hir::def::DefKind; use rustc_index::bit_set::BitSet; -use rustc_index::newtype_index; -use rustc_index::IndexVec; +use rustc_index::{newtype_index, IndexVec}; use rustc_middle::bug; use rustc_middle::mir::interpret::GlobalAlloc; use rustc_middle::mir::visit::*; @@ -101,10 +105,8 @@ use rustc_span::def_id::DefId; use rustc_span::DUMMY_SP; use rustc_target::abi::{self, Abi, FieldIdx, Size, VariantIdx, FIRST_VARIANT}; use smallvec::SmallVec; -use std::borrow::Cow; use crate::ssa::{AssignedValue, SsaLocals}; -use either::Either; pub struct GVN; @@ -126,7 +128,7 @@ fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // Clone dominators as we need them while mutating the body. let dominators = body.basic_blocks.dominators().clone(); - let mut state = VnState::new(tcx, param_env, &ssa, &dominators, &body.local_decls); + let mut state = VnState::new(tcx, body, param_env, &ssa, &dominators, &body.local_decls); ssa.for_each_assignment_mut( body.basic_blocks.as_mut_preserves_cfg(), |local, value, location| { @@ -202,6 +204,7 @@ enum Value<'tcx> { value: Const<'tcx>, /// Some constants do not have a deterministic value. To avoid merging two instances of the /// same `Const`, we assign them an additional integer index. + // `disambiguator` is 0 iff the constant is deterministic. disambiguator: usize, }, /// An aggregate value, either tuple/closure/struct/enum. @@ -264,21 +267,29 @@ struct VnState<'body, 'tcx> { impl<'body, 'tcx> VnState<'body, 'tcx> { fn new( tcx: TyCtxt<'tcx>, + body: &Body<'tcx>, param_env: ty::ParamEnv<'tcx>, ssa: &'body SsaLocals, dominators: &'body Dominators, local_decls: &'body LocalDecls<'tcx>, ) -> Self { + // Compute a rough estimate of the number of values in the body from the number of + // statements. This is meant to reduce the number of allocations, but it's all right if + // we miss the exact amount. We estimate based on 2 values per statement (one in LHS and + // one in RHS) and 4 values per terminator (for call operands). + let num_values = + 2 * body.basic_blocks.iter().map(|bbdata| bbdata.statements.len()).sum::() + + 4 * body.basic_blocks.len(); VnState { tcx, ecx: InterpCx::new(tcx, DUMMY_SP, param_env, DummyMachine), param_env, local_decls, locals: IndexVec::from_elem(None, local_decls), - rev_locals: IndexVec::default(), - values: FxIndexSet::default(), - evaluated: IndexVec::new(), - next_opaque: Some(0), + rev_locals: IndexVec::with_capacity(num_values), + values: FxIndexSet::with_capacity_and_hasher(num_values, Default::default()), + evaluated: IndexVec::with_capacity(num_values), + next_opaque: Some(1), feature_unsized_locals: tcx.features().unsized_locals, ssa, dominators, @@ -291,9 +302,15 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { let (index, new) = self.values.insert_full(value); let index = VnIndex::from_usize(index); if new { + // Grow `evaluated` and `rev_locals` here to amortize the allocations. let evaluated = self.eval_to_const(index); let _index = self.evaluated.push(evaluated); debug_assert_eq!(index, _index); + // No need to push to `rev_locals` if we finished listing assignments. + if self.next_opaque.is_some() { + let _index = self.rev_locals.push(SmallVec::new()); + debug_assert_eq!(index, _index); + } } index } @@ -330,7 +347,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { let is_sized = !self.feature_unsized_locals || self.local_decls[local].ty.is_sized(self.tcx, self.param_env); if is_sized { - self.rev_locals.ensure_contains_elem(value, SmallVec::new).push(local); + self.rev_locals[value].push(local); } } @@ -344,6 +361,8 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { let next_opaque = self.next_opaque.as_mut()?; let disambiguator = *next_opaque; *next_opaque += 1; + // `disambiguator: 0` means deterministic. + debug_assert_ne!(disambiguator, 0); disambiguator }; Some(self.insert(Value::Constant { value, disambiguator })) @@ -351,12 +370,16 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { fn insert_bool(&mut self, flag: bool) -> VnIndex { // Booleans are deterministic. - self.insert(Value::Constant { value: Const::from_bool(self.tcx, flag), disambiguator: 0 }) + let value = Const::from_bool(self.tcx, flag); + debug_assert!(value.is_deterministic()); + self.insert(Value::Constant { value, disambiguator: 0 }) } fn insert_scalar(&mut self, scalar: Scalar, ty: Ty<'tcx>) -> VnIndex { - self.insert_constant(Const::from_scalar(self.tcx, scalar, ty)) - .expect("scalars are deterministic") + // Scalars are deterministic. + let value = Const::from_scalar(self.tcx, scalar, ty); + debug_assert!(value.is_deterministic()); + self.insert(Value::Constant { value, disambiguator: 0 }) } fn insert_tuple(&mut self, values: Vec) -> VnIndex { @@ -669,7 +692,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { fn simplify_place_projection(&mut self, place: &mut Place<'tcx>, location: Location) { // If the projection is indirect, we treat the local as a value, so can replace it with // another local. - if place.is_indirect() + if place.is_indirect_first_projection() && let Some(base) = self.locals[place.local] && let Some(new_local) = self.try_as_local(base, location) && place.local != new_local @@ -771,10 +794,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { location: Location, ) -> Option { match *operand { - Operand::Constant(ref mut constant) => { - let const_ = constant.const_.normalize(self.tcx, self.param_env); - self.insert_constant(const_) - } + Operand::Constant(ref constant) => self.insert_constant(constant.const_), Operand::Copy(ref mut place) | Operand::Move(ref mut place) => { let value = self.simplify_place_value(place, location)?; if let Some(const_) = self.try_as_constant(value) { @@ -1369,8 +1389,13 @@ fn op_to_prop_const<'tcx>( // If this constant has scalar ABI, return it as a `ConstValue::Scalar`. if let Abi::Scalar(abi::Scalar::Initialized { .. }) = op.layout.abi && let Ok(scalar) = ecx.read_scalar(op) - && scalar.try_to_scalar_int().is_ok() { + if !scalar.try_to_scalar_int().is_ok() { + // Check that we do not leak a pointer. + // Those pointers may lose part of their identity in codegen. + // FIXME: remove this hack once https://github.com/rust-lang/rust/issues/79738 is fixed. + return None; + } return Some(ConstValue::Scalar(scalar)); } @@ -1434,12 +1459,11 @@ impl<'tcx> VnState<'_, 'tcx> { /// If `index` is a `Value::Constant`, return the `Constant` to be put in the MIR. fn try_as_constant(&mut self, index: VnIndex) -> Option> { - // This was already constant in MIR, do not change it. - if let Value::Constant { value, disambiguator: _ } = *self.get(index) - // If the constant is not deterministic, adding an additional mention of it in MIR will - // not give the same value as the former mention. - && value.is_deterministic() - { + // This was already constant in MIR, do not change it. If the constant is not + // deterministic, adding an additional mention of it in MIR will not give the same value as + // the former mention. + if let Value::Constant { value, disambiguator: 0 } = *self.get(index) { + debug_assert!(value.is_deterministic()); return Some(ConstOperand { span: DUMMY_SP, user_ty: None, const_: value }); } diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index fd9f0fec88ddd..f30732e6aaf3b 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -1,6 +1,8 @@ //! Inlining pass for MIR functions. -use crate::deref_separator::deref_finder; +use std::iter; +use std::ops::{Range, RangeFrom}; + use rustc_attr::InlineAttr; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; @@ -10,8 +12,9 @@ use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs}; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; -use rustc_middle::ty::TypeVisitableExt; -use rustc_middle::ty::{self, Instance, InstanceKind, ParamEnv, Ty, TyCtxt, TypeFlags}; +use rustc_middle::ty::{ + self, Instance, InstanceKind, ParamEnv, Ty, TyCtxt, TypeFlags, TypeVisitableExt, +}; use rustc_session::config::{DebugInfo, OptLevel}; use rustc_span::source_map::Spanned; use rustc_span::sym; @@ -19,11 +22,10 @@ use rustc_target::abi::FieldIdx; use rustc_target::spec::abi::Abi; use crate::cost_checker::CostChecker; +use crate::deref_separator::deref_finder; use crate::simplify::simplify_cfg; use crate::util; use crate::validate::validate_types; -use std::iter; -use std::ops::{Range, RangeFrom}; pub(crate) mod cycle; @@ -742,8 +744,8 @@ impl<'tcx> Inliner<'tcx> { // Copy required constants from the callee_body into the caller_body. Although we are only // pushing unevaluated consts to `required_consts`, here they may have been evaluated // because we are calling `instantiate_and_normalize_erasing_regions` -- so we filter again. - caller_body.required_consts.extend( - callee_body.required_consts.into_iter().filter(|ct| ct.const_.is_required_const()), + caller_body.required_consts.as_mut().unwrap().extend( + callee_body.required_consts().into_iter().filter(|ct| ct.const_.is_required_const()), ); // Now that we incorporated the callee's `required_consts`, we can remove the callee from // `mentioned_items` -- but we have to take their `mentioned_items` in return. This does @@ -753,12 +755,11 @@ impl<'tcx> Inliner<'tcx> { // We need to reconstruct the `required_item` for the callee so that we can find and // remove it. let callee_item = MentionedItem::Fn(func.ty(caller_body, self.tcx)); - if let Some(idx) = - caller_body.mentioned_items.iter().position(|item| item.node == callee_item) - { + let caller_mentioned_items = caller_body.mentioned_items.as_mut().unwrap(); + if let Some(idx) = caller_mentioned_items.iter().position(|item| item.node == callee_item) { // We found the callee, so remove it and add its items instead. - caller_body.mentioned_items.remove(idx); - caller_body.mentioned_items.extend(callee_body.mentioned_items); + caller_mentioned_items.remove(idx); + caller_mentioned_items.extend(callee_body.mentioned_items()); } else { // If we can't find the callee, there's no point in adding its items. Probably it // already got removed by being inlined elsewhere in the same function, so we already diff --git a/compiler/rustc_mir_transform/src/inline/cycle.rs b/compiler/rustc_mir_transform/src/inline/cycle.rs index d4477563e3adb..f5274c664cfa7 100644 --- a/compiler/rustc_mir_transform/src/inline/cycle.rs +++ b/compiler/rustc_mir_transform/src/inline/cycle.rs @@ -2,8 +2,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::mir::TerminatorKind; -use rustc_middle::ty::TypeVisitableExt; -use rustc_middle::ty::{self, GenericArgsRef, InstanceKind, TyCtxt}; +use rustc_middle::ty::{self, GenericArgsRef, InstanceKind, TyCtxt, TypeVisitableExt}; use rustc_session::Limit; use rustc_span::sym; diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index 8209e5e27111c..2fc5f7e536ba8 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -1,20 +1,37 @@ //! Performs various peephole optimizations. -use crate::simplify::simplify_duplicate_switch_targets; -use crate::take_array; use rustc_ast::attr; +use rustc_hir::LangItem; use rustc_middle::bug; use rustc_middle::mir::*; -use rustc_middle::ty::layout; use rustc_middle::ty::layout::ValidityRequirement; -use rustc_middle::ty::{self, GenericArgsRef, ParamEnv, Ty, TyCtxt}; +use rustc_middle::ty::{self, layout, GenericArgsRef, ParamEnv, Ty, TyCtxt}; use rustc_span::sym; use rustc_span::symbol::Symbol; use rustc_target::spec::abi::Abi; -pub struct InstSimplify; +use crate::simplify::simplify_duplicate_switch_targets; +use crate::take_array; + +pub enum InstSimplify { + BeforeInline, + AfterSimplifyCfg, +} + +impl InstSimplify { + pub fn name(&self) -> &'static str { + match self { + InstSimplify::BeforeInline => "InstSimplify-before-inline", + InstSimplify::AfterSimplifyCfg => "InstSimplify-after-simplifycfg", + } + } +} impl<'tcx> MirPass<'tcx> for InstSimplify { + fn name(&self) -> &'static str { + self.name() + } + fn is_enabled(&self, sess: &rustc_session::Session) -> bool { sess.mir_opt_level() > 0 } @@ -271,8 +288,7 @@ impl<'tcx> InstSimplifyContext<'tcx, '_> { return; } - let trait_def_id = self.tcx.trait_of_item(fn_def_id); - if trait_def_id.is_none() || trait_def_id != self.tcx.lang_items().clone_trait() { + if !self.tcx.is_lang_item(fn_def_id, LangItem::CloneFn) { return; } diff --git a/compiler/rustc_mir_transform/src/jump_threading.rs b/compiler/rustc_mir_transform/src/jump_threading.rs index 2100f4b4a1af5..96c52845a4a39 100644 --- a/compiler/rustc_mir_transform/src/jump_threading.rs +++ b/compiler/rustc_mir_transform/src/jump_threading.rs @@ -509,6 +509,13 @@ impl<'tcx, 'a> TOFinder<'tcx, 'a> { BinOp::Ne => ScalarInt::FALSE, _ => return None, }; + if value.const_.ty().is_floating_point() { + // Floating point equality does not follow bit-patterns. + // -0.0 and NaN both have special rules for equality, + // and therefore we cannot use integer comparisons for them. + // Avoid handling them, though this could be extended in the future. + return None; + } let value = value.const_.normalize(self.tcx, self.param_env).try_to_scalar_int()?; let conds = conditions.map(self.arena, |c| Condition { value, diff --git a/compiler/rustc_mir_transform/src/known_panics_lint.rs b/compiler/rustc_mir_transform/src/known_panics_lint.rs index 82ad8879d17b3..7202cc2d0427e 100644 --- a/compiler/rustc_mir_transform/src/known_panics_lint.rs +++ b/compiler/rustc_mir_transform/src/known_panics_lint.rs @@ -13,7 +13,8 @@ use rustc_const_eval::interpret::{ use rustc_data_structures::fx::FxHashSet; use rustc_hir::def::DefKind; use rustc_hir::HirId; -use rustc_index::{bit_set::BitSet, IndexVec}; +use rustc_index::bit_set::BitSet; +use rustc_index::IndexVec; use rustc_middle::bug; use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 5d253d7384df4..1f214bc42cbe6 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -6,7 +6,6 @@ #![feature(decl_macro)] #![feature(if_let_guard)] #![feature(impl_trait_in_assoc_type)] -#![feature(is_sorted)] #![feature(let_chains)] #![feature(map_try_insert)] #![feature(never_type)] @@ -29,17 +28,16 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, Visitor}; use rustc_index::IndexVec; -use rustc_middle::mir::visit::Visitor as _; use rustc_middle::mir::{ - traversal, AnalysisPhase, Body, CallSource, ClearCrossCrate, ConstOperand, ConstQualifs, - LocalDecl, MirPass, MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, - SourceInfo, Statement, StatementKind, TerminatorKind, START_BLOCK, + AnalysisPhase, Body, CallSource, ClearCrossCrate, ConstOperand, ConstQualifs, LocalDecl, + MirPass, MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, SourceInfo, + Statement, StatementKind, TerminatorKind, START_BLOCK, }; -use rustc_middle::query; use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; use rustc_middle::util::Providers; -use rustc_middle::{bug, span_bug}; -use rustc_span::{source_map::Spanned, sym, DUMMY_SP}; +use rustc_middle::{bug, query, span_bug}; +use rustc_span::source_map::Spanned; +use rustc_span::{sym, DUMMY_SP}; use rustc_trait_selection::traits; #[macro_use] @@ -340,12 +338,15 @@ fn mir_promoted( // Collect `required_consts` *before* promotion, so if there are any consts being promoted // we still add them to the list in the outer MIR body. - let mut required_consts = Vec::new(); - let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts); - for (bb, bb_data) in traversal::reverse_postorder(&body) { - required_consts_visitor.visit_basic_block_data(bb, bb_data); + RequiredConstsVisitor::compute_required_consts(&mut body); + // If this has an associated by-move async closure body, that doesn't get run through these + // passes itself, it gets "tagged along" by the pass manager. `RequiredConstsVisitor` is not + // a regular pass so we have to also apply it manually to the other body. + if let Some(coroutine) = body.coroutine.as_mut() { + if let Some(by_move_body) = coroutine.by_move_body.as_mut() { + RequiredConstsVisitor::compute_required_consts(by_move_body); + } } - body.required_consts = required_consts; // What we need to run borrowck etc. let promote_pass = promote_consts::PromoteTemps::default(); @@ -562,9 +563,6 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { tcx, body, &[ - // Before doing anything, remember which items are being mentioned so that the set of items - // visited does not depend on the optimization level. - &mentioned_items::MentionedItems, // Add some UB checks before any UB gets optimized away. &check_alignment::CheckAlignment, // Before inlining: trim down MIR with passes to reduce inlining work. @@ -572,6 +570,8 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // Has to be done before inlining, otherwise actual call will be almost always inlined. // Also simple, so can just do first &lower_slice_len::LowerSliceLenCalls, + // Perform instsimplify before inline to eliminate some trivial calls (like clone shims). + &instsimplify::InstSimplify::BeforeInline, // Perform inlining, which may add a lot of code. &inline::Inline, // Code from other crates may have storage markers, so this needs to happen after inlining. @@ -591,7 +591,8 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { &match_branches::MatchBranchSimplification, // inst combine is after MatchBranchSimplification to clean up Ne(_1, false) &multiple_return_terminators::MultipleReturnTerminators, - &instsimplify::InstSimplify, + // After simplifycfg, it allows us to discover new opportunities for peephole optimizations. + &instsimplify::InstSimplify::AfterSimplifyCfg, &simplify::SimplifyLocals::BeforeConstProp, &dead_store_elimination::DeadStoreElimination::Initial, &gvn::GVN, @@ -655,6 +656,19 @@ fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> { return body; } + // Before doing anything, remember which items are being mentioned so that the set of items + // visited does not depend on the optimization level. + // We do not use `run_passes` for this as that might skip the pass if `injection_phase` is set. + mentioned_items::MentionedItems.run_pass(tcx, &mut body); + // If this has an associated by-move async closure body, that doesn't get run through these + // passes itself, it gets "tagged along" by the pass manager. Since we're not using the pass + // manager we have to do this by hand. + if let Some(coroutine) = body.coroutine.as_mut() { + if let Some(by_move_body) = coroutine.by_move_body.as_mut() { + mentioned_items::MentionedItems.run_pass(tcx, by_move_body); + } + } + // If `mir_drops_elaborated_and_const_checked` found that the current body has unsatisfiable // predicates, it will shrink the MIR to a single `unreachable` terminator. // More generally, if MIR is a lone `unreachable`, there is nothing to optimize. diff --git a/compiler/rustc_mir_transform/src/lint.rs b/compiler/rustc_mir_transform/src/lint.rs index 3d1e1e481750a..746068064b8fb 100644 --- a/compiler/rustc_mir_transform/src/lint.rs +++ b/compiler/rustc_mir_transform/src/lint.rs @@ -2,6 +2,8 @@ //! It can be used to locate problems in MIR building or optimizations. It assumes that all code //! can be executed, so it has false positives. +use std::borrow::Cow; + use rustc_data_structures::fx::FxHashSet; use rustc_index::bit_set::BitSet; use rustc_middle::mir::visit::{PlaceContext, Visitor}; @@ -10,7 +12,6 @@ use rustc_middle::ty::TyCtxt; use rustc_mir_dataflow::impls::{MaybeStorageDead, MaybeStorageLive}; use rustc_mir_dataflow::storage::always_storage_live_locals; use rustc_mir_dataflow::{Analysis, ResultsCursor}; -use std::borrow::Cow; pub fn lint_body<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, when: String) { let always_live_locals = &always_storage_live_locals(body); diff --git a/compiler/rustc_mir_transform/src/lower_intrinsics.rs b/compiler/rustc_mir_transform/src/lower_intrinsics.rs index 6aa9039435547..a9bdff95fe5ac 100644 --- a/compiler/rustc_mir_transform/src/lower_intrinsics.rs +++ b/compiler/rustc_mir_transform/src/lower_intrinsics.rs @@ -1,11 +1,12 @@ //! Lowers intrinsic calls -use crate::take_array; use rustc_middle::mir::*; use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::sym; +use crate::take_array; + pub struct LowerIntrinsics; impl<'tcx> MirPass<'tcx> for LowerIntrinsics { diff --git a/compiler/rustc_mir_transform/src/match_branches.rs b/compiler/rustc_mir_transform/src/match_branches.rs index 6ab4ec6fe7e69..47758b56f8c90 100644 --- a/compiler/rustc_mir_transform/src/match_branches.rs +++ b/compiler/rustc_mir_transform/src/match_branches.rs @@ -1,9 +1,12 @@ +use std::iter; + use rustc_index::IndexSlice; use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::*; +use rustc_middle::ty::layout::{IntegerExt, TyAndLayout}; use rustc_middle::ty::{ParamEnv, ScalarInt, Ty, TyCtxt}; -use rustc_target::abi::Size; -use std::iter; +use rustc_target::abi::Integer; +use rustc_type_ir::TyKind::*; use super::simplify::simplify_cfg; @@ -41,10 +44,7 @@ impl<'tcx> MirPass<'tcx> for MatchBranchSimplification { should_cleanup = true; continue; } - // unsound: https://github.com/rust-lang/rust/issues/124150 - if tcx.sess.opts.unstable_opts.unsound_mir_opts - && SimplifyToExp::default().simplify(tcx, body, bb_idx, param_env).is_some() - { + if SimplifyToExp::default().simplify(tcx, body, bb_idx, param_env).is_some() { should_cleanup = true; continue; } @@ -263,33 +263,56 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToIf { } } +/// Check if the cast constant using `IntToInt` is equal to the target constant. +fn can_cast( + tcx: TyCtxt<'_>, + src_val: impl Into, + src_layout: TyAndLayout<'_>, + cast_ty: Ty<'_>, + target_scalar: ScalarInt, +) -> bool { + let from_scalar = ScalarInt::try_from_uint(src_val.into(), src_layout.size).unwrap(); + let v = match src_layout.ty.kind() { + Uint(_) => from_scalar.to_uint(src_layout.size), + Int(_) => from_scalar.to_int(src_layout.size) as u128, + _ => unreachable!("invalid int"), + }; + let size = match *cast_ty.kind() { + Int(t) => Integer::from_int_ty(&tcx, t).size(), + Uint(t) => Integer::from_uint_ty(&tcx, t).size(), + _ => unreachable!("invalid int"), + }; + let v = size.truncate(v); + let cast_scalar = ScalarInt::try_from_uint(v, size).unwrap(); + cast_scalar == target_scalar +} + #[derive(Default)] struct SimplifyToExp { - transfrom_types: Vec, + transfrom_kinds: Vec, } #[derive(Clone, Copy)] -enum CompareType<'tcx, 'a> { +enum ExpectedTransformKind<'tcx, 'a> { /// Identical statements. Same(&'a StatementKind<'tcx>), /// Assignment statements have the same value. - Eq(&'a Place<'tcx>, Ty<'tcx>, ScalarInt), + SameByEq { place: &'a Place<'tcx>, ty: Ty<'tcx>, scalar: ScalarInt }, /// Enum variant comparison type. - Discr { place: &'a Place<'tcx>, ty: Ty<'tcx>, is_signed: bool }, + Cast { place: &'a Place<'tcx>, ty: Ty<'tcx> }, } -enum TransfromType { +enum TransfromKind { Same, - Eq, - Discr, + Cast, } -impl From> for TransfromType { - fn from(compare_type: CompareType<'_, '_>) -> Self { +impl From> for TransfromKind { + fn from(compare_type: ExpectedTransformKind<'_, '_>) -> Self { match compare_type { - CompareType::Same(_) => TransfromType::Same, - CompareType::Eq(_, _, _) => TransfromType::Eq, - CompareType::Discr { .. } => TransfromType::Discr, + ExpectedTransformKind::Same(_) => TransfromKind::Same, + ExpectedTransformKind::SameByEq { .. } => TransfromKind::Same, + ExpectedTransformKind::Cast { .. } => TransfromKind::Cast, } } } @@ -353,7 +376,7 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp { return None; } let mut target_iter = targets.iter(); - let (first_val, first_target) = target_iter.next().unwrap(); + let (first_case_val, first_target) = target_iter.next().unwrap(); let first_terminator_kind = &bbs[first_target].terminator().kind; // Check that destinations are identical, and if not, then don't optimize this block if !targets @@ -363,24 +386,20 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp { return None; } - let discr_size = tcx.layout_of(param_env.and(discr_ty)).unwrap().size; + let discr_layout = tcx.layout_of(param_env.and(discr_ty)).unwrap(); let first_stmts = &bbs[first_target].statements; - let (second_val, second_target) = target_iter.next().unwrap(); + let (second_case_val, second_target) = target_iter.next().unwrap(); let second_stmts = &bbs[second_target].statements; if first_stmts.len() != second_stmts.len() { return None; } - fn int_equal(l: ScalarInt, r: impl Into, size: Size) -> bool { - l.to_bits_unchecked() == ScalarInt::try_from_uint(r, size).unwrap().to_bits_unchecked() - } - // We first compare the two branches, and then the other branches need to fulfill the same conditions. - let mut compare_types = Vec::new(); + let mut expected_transform_kinds = Vec::new(); for (f, s) in iter::zip(first_stmts, second_stmts) { let compare_type = match (&f.kind, &s.kind) { // If two statements are exactly the same, we can optimize. - (f_s, s_s) if f_s == s_s => CompareType::Same(f_s), + (f_s, s_s) if f_s == s_s => ExpectedTransformKind::Same(f_s), // If two statements are assignments with the match values to the same place, we can optimize. ( @@ -394,22 +413,29 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp { f_c.const_.try_eval_scalar_int(tcx, param_env), s_c.const_.try_eval_scalar_int(tcx, param_env), ) { - (Some(f), Some(s)) if f == s => CompareType::Eq(lhs_f, f_c.const_.ty(), f), - // Enum variants can also be simplified to an assignment statement if their values are equal. - // We need to consider both unsigned and signed scenarios here. + (Some(f), Some(s)) if f == s => ExpectedTransformKind::SameByEq { + place: lhs_f, + ty: f_c.const_.ty(), + scalar: f, + }, + // Enum variants can also be simplified to an assignment statement, + // if we can use `IntToInt` cast to get an equal value. (Some(f), Some(s)) - if ((f_c.const_.ty().is_signed() || discr_ty.is_signed()) - && int_equal(f, first_val, discr_size) - && int_equal(s, second_val, discr_size)) - || (Some(f) == ScalarInt::try_from_uint(first_val, f.size()) - && Some(s) - == ScalarInt::try_from_uint(second_val, s.size())) => + if (can_cast( + tcx, + first_case_val, + discr_layout, + f_c.const_.ty(), + f, + ) && can_cast( + tcx, + second_case_val, + discr_layout, + f_c.const_.ty(), + s, + )) => { - CompareType::Discr { - place: lhs_f, - ty: f_c.const_.ty(), - is_signed: f_c.const_.ty().is_signed() || discr_ty.is_signed(), - } + ExpectedTransformKind::Cast { place: lhs_f, ty: f_c.const_.ty() } } _ => { return None; @@ -420,47 +446,36 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp { // Otherwise we cannot optimize. Try another block. _ => return None, }; - compare_types.push(compare_type); + expected_transform_kinds.push(compare_type); } // All remaining BBs need to fulfill the same pattern as the two BBs from the previous step. for (other_val, other_target) in target_iter { let other_stmts = &bbs[other_target].statements; - if compare_types.len() != other_stmts.len() { + if expected_transform_kinds.len() != other_stmts.len() { return None; } - for (f, s) in iter::zip(&compare_types, other_stmts) { + for (f, s) in iter::zip(&expected_transform_kinds, other_stmts) { match (*f, &s.kind) { - (CompareType::Same(f_s), s_s) if f_s == s_s => {} + (ExpectedTransformKind::Same(f_s), s_s) if f_s == s_s => {} ( - CompareType::Eq(lhs_f, f_ty, val), + ExpectedTransformKind::SameByEq { place: lhs_f, ty: f_ty, scalar }, StatementKind::Assign(box (lhs_s, Rvalue::Use(Operand::Constant(s_c)))), ) if lhs_f == lhs_s && s_c.const_.ty() == f_ty - && s_c.const_.try_eval_scalar_int(tcx, param_env) == Some(val) => {} + && s_c.const_.try_eval_scalar_int(tcx, param_env) == Some(scalar) => {} ( - CompareType::Discr { place: lhs_f, ty: f_ty, is_signed }, + ExpectedTransformKind::Cast { place: lhs_f, ty: f_ty }, StatementKind::Assign(box (lhs_s, Rvalue::Use(Operand::Constant(s_c)))), - ) if lhs_f == lhs_s && s_c.const_.ty() == f_ty => { - let Some(f) = s_c.const_.try_eval_scalar_int(tcx, param_env) else { - return None; - }; - if is_signed - && s_c.const_.ty().is_signed() - && int_equal(f, other_val, discr_size) - { - continue; - } - if Some(f) == ScalarInt::try_from_uint(other_val, f.size()) { - continue; - } - return None; - } + ) if let Some(f) = s_c.const_.try_eval_scalar_int(tcx, param_env) + && lhs_f == lhs_s + && s_c.const_.ty() == f_ty + && can_cast(tcx, other_val, discr_layout, f_ty, f) => {} _ => return None, } } } - self.transfrom_types = compare_types.into_iter().map(|c| c.into()).collect(); + self.transfrom_kinds = expected_transform_kinds.into_iter().map(|c| c.into()).collect(); Some(()) } @@ -478,13 +493,13 @@ impl<'tcx> SimplifyMatch<'tcx> for SimplifyToExp { let (_, first) = targets.iter().next().unwrap(); let first = &bbs[first]; - for (t, s) in iter::zip(&self.transfrom_types, &first.statements) { + for (t, s) in iter::zip(&self.transfrom_kinds, &first.statements) { match (t, &s.kind) { - (TransfromType::Same, _) | (TransfromType::Eq, _) => { + (TransfromKind::Same, _) => { patch.add_statement(parent_end, s.kind.clone()); } ( - TransfromType::Discr, + TransfromKind::Cast, StatementKind::Assign(box (lhs, Rvalue::Use(Operand::Constant(f_c)))), ) => { let operand = Operand::Copy(Place::from(discr_local)); diff --git a/compiler/rustc_mir_transform/src/mentioned_items.rs b/compiler/rustc_mir_transform/src/mentioned_items.rs index d928d7cf76445..32c8064ebca50 100644 --- a/compiler/rustc_mir_transform/src/mentioned_items.rs +++ b/compiler/rustc_mir_transform/src/mentioned_items.rs @@ -1,6 +1,7 @@ use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::{self, Location, MentionedItem, MirPass}; -use rustc_middle::ty::{self, adjustment::PointerCoercion, TyCtxt}; +use rustc_middle::ty::adjustment::PointerCoercion; +use rustc_middle::ty::{self, TyCtxt}; use rustc_session::Session; use rustc_span::source_map::Spanned; @@ -22,10 +23,9 @@ impl<'tcx> MirPass<'tcx> for MentionedItems { } fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut mir::Body<'tcx>) { - debug_assert!(body.mentioned_items.is_empty()); let mut mentioned_items = Vec::new(); MentionedItemsVisitor { tcx, body, mentioned_items: &mut mentioned_items }.visit_body(body); - body.mentioned_items = mentioned_items; + body.set_mentioned_items(mentioned_items); } } diff --git a/compiler/rustc_mir_transform/src/multiple_return_terminators.rs b/compiler/rustc_mir_transform/src/multiple_return_terminators.rs index 64749a4b5b688..1e87a0e01d9be 100644 --- a/compiler/rustc_mir_transform/src/multiple_return_terminators.rs +++ b/compiler/rustc_mir_transform/src/multiple_return_terminators.rs @@ -1,11 +1,12 @@ //! This pass removes jumps to basic blocks containing only a return, and replaces them with a //! return instead. -use crate::simplify; use rustc_index::bit_set::BitSet; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; +use crate::simplify; + pub struct MultipleReturnTerminators; impl<'tcx> MirPass<'tcx> for MultipleReturnTerminators { diff --git a/compiler/rustc_mir_transform/src/pass_manager.rs b/compiler/rustc_mir_transform/src/pass_manager.rs index 17a1c3c715797..824a4b2f2df5b 100644 --- a/compiler/rustc_mir_transform/src/pass_manager.rs +++ b/compiler/rustc_mir_transform/src/pass_manager.rs @@ -2,7 +2,8 @@ use rustc_middle::mir::{self, Body, MirPhase, RuntimePhase}; use rustc_middle::ty::TyCtxt; use rustc_session::Session; -use crate::{lint::lint_body, validate, MirPass}; +use crate::lint::lint_body; +use crate::{validate, MirPass}; /// Just like `MirPass`, except it cannot mutate `Body`. pub trait MirLint<'tcx> { diff --git a/compiler/rustc_mir_transform/src/prettify.rs b/compiler/rustc_mir_transform/src/prettify.rs index 7b77d0323533e..14dd0c6f61e76 100644 --- a/compiler/rustc_mir_transform/src/prettify.rs +++ b/compiler/rustc_mir_transform/src/prettify.rs @@ -4,7 +4,8 @@ //! (`-Zmir-enable-passes=+ReorderBasicBlocks,+ReorderLocals`) //! to make the MIR easier to read for humans. -use rustc_index::{bit_set::BitSet, IndexSlice, IndexVec}; +use rustc_index::bit_set::BitSet; +use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor}; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; diff --git a/compiler/rustc_mir_transform/src/promote_consts.rs b/compiler/rustc_mir_transform/src/promote_consts.rs index 736647fb64b12..dc8e50ac8cd28 100644 --- a/compiler/rustc_mir_transform/src/promote_consts.rs +++ b/compiler/rustc_mir_transform/src/promote_consts.rs @@ -12,25 +12,21 @@ //! initialization and can otherwise silence errors, if //! move analysis runs after promotion on broken MIR. +use std::assert_matches::assert_matches; +use std::cell::Cell; +use std::{cmp, iter, mem}; + use either::{Left, Right}; +use rustc_const_eval::check_consts::{qualifs, ConstCx}; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; -use rustc_middle::mir; +use rustc_index::{Idx, IndexSlice, IndexVec}; use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; -use rustc_middle::ty::GenericArgs; -use rustc_middle::ty::{self, List, Ty, TyCtxt, TypeVisitableExt}; -use rustc_middle::{bug, span_bug}; -use rustc_span::Span; - -use rustc_index::{Idx, IndexSlice, IndexVec}; +use rustc_middle::ty::{self, GenericArgs, List, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::{bug, mir, span_bug}; use rustc_span::source_map::Spanned; - -use std::assert_matches::assert_matches; -use std::cell::Cell; -use std::{cmp, iter, mem}; - -use rustc_const_eval::check_consts::{qualifs, ConstCx}; +use rustc_span::Span; /// A `MirPass` for promotion. /// @@ -706,6 +702,9 @@ struct Promoter<'a, 'tcx> { temps: &'a mut IndexVec, extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>, + /// Used to assemble the required_consts list while building the promoted. + required_consts: Vec>, + /// If true, all nested temps are also kept in the /// source MIR, not moved to the promoted MIR. keep_original: bool, @@ -928,11 +927,14 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> { let span = self.promoted.span; self.assign(RETURN_PLACE, rvalue, span); - // Now that we did promotion, we know whether we'll want to add this to `required_consts`. + // Now that we did promotion, we know whether we'll want to add this to `required_consts` of + // the surrounding MIR body. if self.add_to_required { - self.source.required_consts.push(promoted_op); + self.source.required_consts.as_mut().unwrap().push(promoted_op); } + self.promoted.set_required_consts(self.required_consts); + self.promoted } } @@ -951,7 +953,7 @@ impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> { fn visit_const_operand(&mut self, constant: &mut ConstOperand<'tcx>, _location: Location) { if constant.const_.is_required_const() { - self.promoted.required_consts.push(*constant); + self.required_consts.push(*constant); } // Skipping `super_constant` as the visitor is otherwise only looking for locals. @@ -1015,9 +1017,9 @@ fn promote_candidates<'tcx>( extra_statements: &mut extra_statements, keep_original: false, add_to_required: false, + required_consts: Vec::new(), }; - // `required_consts` of the promoted itself gets filled while building the MIR body. let mut promoted = promoter.promote_candidate(candidate, promotions.len()); promoted.source.promoted = Some(promotions.next_index()); promotions.push(promoted); diff --git a/compiler/rustc_mir_transform/src/ref_prop.rs b/compiler/rustc_mir_transform/src/ref_prop.rs index 801ef14c9cd90..76e65099e9028 100644 --- a/compiler/rustc_mir_transform/src/ref_prop.rs +++ b/compiler/rustc_mir_transform/src/ref_prop.rs @@ -1,3 +1,5 @@ +use std::borrow::Cow; + use rustc_data_structures::fx::FxHashSet; use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; @@ -8,7 +10,6 @@ use rustc_middle::ty::TyCtxt; use rustc_mir_dataflow::impls::MaybeStorageDead; use rustc_mir_dataflow::storage::always_storage_live_locals; use rustc_mir_dataflow::Analysis; -use std::borrow::Cow; use crate::ssa::{SsaLocals, StorageLiveLocals}; diff --git a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs index 7d12bcf2fa153..fae1cb5f7d8a5 100644 --- a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs +++ b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs @@ -1,10 +1,9 @@ use rustc_index::bit_set::ChunkedBitSet; use rustc_middle::mir::{Body, TerminatorKind}; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt, VariantDef}; +use rustc_middle::ty::{self, GenericArgsRef, ParamEnv, Ty, TyCtxt, VariantDef}; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex}; -use rustc_mir_dataflow::{move_path_children_matching, Analysis, MaybeReachable, MoveDataParamEnv}; +use rustc_mir_dataflow::{move_path_children_matching, Analysis, MaybeReachable}; use rustc_target::abi::FieldIdx; use crate::MirPass; @@ -25,8 +24,7 @@ impl<'tcx> MirPass<'tcx> for RemoveUninitDrops { let move_data = MoveData::gather_moves(body, tcx, param_env, |ty| ty.needs_drop(tcx, param_env)); - let mdpe = MoveDataParamEnv { move_data, param_env }; - let mut maybe_inits = MaybeInitializedPlaces::new(tcx, body, &mdpe) + let mut maybe_inits = MaybeInitializedPlaces::new(tcx, body, &move_data) .into_engine(tcx, body) .pass_name("remove_uninit_drops") .iterate_to_fixpoint() @@ -41,7 +39,7 @@ impl<'tcx> MirPass<'tcx> for RemoveUninitDrops { let MaybeReachable::Reachable(maybe_inits) = maybe_inits.get() else { continue }; // If there's no move path for the dropped place, it's probably a `Deref`. Let it alone. - let LookupResult::Exact(mpi) = mdpe.move_data.rev_lookup.find(place.as_ref()) else { + let LookupResult::Exact(mpi) = move_data.rev_lookup.find(place.as_ref()) else { continue; }; @@ -49,7 +47,7 @@ impl<'tcx> MirPass<'tcx> for RemoveUninitDrops { tcx, param_env, maybe_inits, - &mdpe.move_data, + &move_data, place.ty(body, tcx).ty, mpi, ); diff --git a/compiler/rustc_mir_transform/src/required_consts.rs b/compiler/rustc_mir_transform/src/required_consts.rs index 00bfb5e66008b..50637e2ac03bb 100644 --- a/compiler/rustc_mir_transform/src/required_consts.rs +++ b/compiler/rustc_mir_transform/src/required_consts.rs @@ -1,14 +1,23 @@ use rustc_middle::mir::visit::Visitor; -use rustc_middle::mir::{ConstOperand, Location}; +use rustc_middle::mir::{traversal, Body, ConstOperand, Location}; pub struct RequiredConstsVisitor<'a, 'tcx> { required_consts: &'a mut Vec>, } impl<'a, 'tcx> RequiredConstsVisitor<'a, 'tcx> { - pub fn new(required_consts: &'a mut Vec>) -> Self { + fn new(required_consts: &'a mut Vec>) -> Self { RequiredConstsVisitor { required_consts } } + + pub fn compute_required_consts(body: &mut Body<'tcx>) { + let mut required_consts = Vec::new(); + let mut required_consts_visitor = RequiredConstsVisitor::new(&mut required_consts); + for (bb, bb_data) in traversal::reverse_postorder(&body) { + required_consts_visitor.visit_basic_block_data(bb, bb_data); + } + body.set_required_consts(required_consts); + } } impl<'tcx> Visitor<'tcx> for RequiredConstsVisitor<'_, 'tcx> { diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 6835a39cf3624..f41f3ef656c51 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -1,26 +1,27 @@ +use std::assert_matches::assert_matches; +use std::{fmt, iter}; + use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; use rustc_index::{Idx, IndexVec}; +use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::*; use rustc_middle::query::Providers; -use rustc_middle::ty::GenericArgs; -use rustc_middle::ty::{self, CoroutineArgs, CoroutineArgsExt, EarlyBinder, Ty, TyCtxt}; +use rustc_middle::ty::{ + self, CoroutineArgs, CoroutineArgsExt, EarlyBinder, GenericArgs, Ty, TyCtxt, +}; use rustc_middle::{bug, span_bug}; -use rustc_span::{source_map::Spanned, Span, DUMMY_SP}; +use rustc_mir_dataflow::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle}; +use rustc_span::source_map::Spanned; +use rustc_span::{Span, DUMMY_SP}; use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; use rustc_target::spec::abi::Abi; -use std::assert_matches::assert_matches; -use std::fmt; -use std::iter; - use crate::{ abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, deref_separator, - mentioned_items, pass_manager as pm, remove_noop_landing_pads, simplify, + instsimplify, mentioned_items, pass_manager as pm, remove_noop_landing_pads, simplify, }; -use rustc_middle::mir::patch::MirPatch; -use rustc_mir_dataflow::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle}; mod async_destructor_ctor; @@ -154,6 +155,7 @@ fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceKind<'tcx>) -> Body< &deref_separator::Derefer, &remove_noop_landing_pads::RemoveNoopLandingPads, &simplify::SimplifyCfg::MakeShim, + &instsimplify::InstSimplify::BeforeInline, &abort_unwinding_calls::AbortUnwindingCalls, &add_call_guards::CriticalCallEdges, ], @@ -303,7 +305,7 @@ fn new_body<'tcx>( arg_count: usize, span: Span, ) -> Body<'tcx> { - Body::new( + let mut body = Body::new( source, basic_blocks, IndexVec::from_elem_n( @@ -324,7 +326,10 @@ fn new_body<'tcx>( None, // FIXME(compiler-errors): is this correct? None, - ) + ); + // Shims do not directly mention any consts. + body.set_required_consts(Vec::new()); + body } pub struct DropShimElaborator<'a, 'tcx> { @@ -434,6 +439,9 @@ fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) - match self_ty.kind() { ty::FnDef(..) | ty::FnPtr(_) => builder.copy_shim(), ty::Closure(_, args) => builder.tuple_like_shim(dest, src, args.as_closure().upvar_tys()), + ty::CoroutineClosure(_, args) => { + builder.tuple_like_shim(dest, src, args.as_coroutine_closure().upvar_tys()) + } ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()), ty::Coroutine(coroutine_def_id, args) => { assert_eq!(tcx.coroutine_movability(*coroutine_def_id), hir::Movability::Movable); @@ -964,13 +972,16 @@ pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { }; let source = MirSource::item(ctor_id); - let body = new_body( + let mut body = new_body( source, IndexVec::from_elem_n(start_block, 1), local_decls, sig.inputs().len(), span, ); + // A constructor doesn't mention any other items (and we don't run the usual optimization passes + // so this would otherwise not get filled). + body.set_mentioned_items(Vec::new()); crate::pass_manager::dump_mir_for_phase_change(tcx, &body); diff --git a/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs b/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs index e174cccdad6b7..59f67d8e73f45 100644 --- a/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs +++ b/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs @@ -1,14 +1,14 @@ use std::iter; -use super::MirPass; -use rustc_middle::{ - bug, - mir::{ - interpret::Scalar, BasicBlock, BinOp, Body, Operand, Place, Rvalue, Statement, - StatementKind, SwitchTargets, TerminatorKind, - }, - ty::{Ty, TyCtxt}, +use rustc_middle::bug; +use rustc_middle::mir::interpret::Scalar; +use rustc_middle::mir::{ + BasicBlock, BinOp, Body, Operand, Place, Rvalue, Statement, StatementKind, SwitchTargets, + TerminatorKind, }; +use rustc_middle::ty::{Ty, TyCtxt}; + +use super::MirPass; /// Pass to convert `if` conditions on integrals into switches on the integral. /// For an example, it turns something like diff --git a/compiler/rustc_mir_transform/src/single_use_consts.rs b/compiler/rustc_mir_transform/src/single_use_consts.rs index 93736e55996ec..35cb6872fe9a2 100644 --- a/compiler/rustc_mir_transform/src/single_use_consts.rs +++ b/compiler/rustc_mir_transform/src/single_use_consts.rs @@ -1,4 +1,5 @@ -use rustc_index::{bit_set::BitSet, IndexVec}; +use rustc_index::bit_set::BitSet; +use rustc_index::IndexVec; use rustc_middle::bug; use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor}; use rustc_middle::mir::*; diff --git a/compiler/rustc_mir_transform/src/unreachable_enum_branching.rs b/compiler/rustc_mir_transform/src/unreachable_enum_branching.rs index 1404a45f4d2db..81baf58a5e0a0 100644 --- a/compiler/rustc_mir_transform/src/unreachable_enum_branching.rs +++ b/compiler/rustc_mir_transform/src/unreachable_enum_branching.rs @@ -1,6 +1,5 @@ //! A pass that eliminates branches on uninhabited or unreachable enum variants. -use crate::MirPass; use rustc_data_structures::fx::FxHashSet; use rustc_middle::bug; use rustc_middle::mir::patch::MirPatch; @@ -12,6 +11,8 @@ use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{Ty, TyCtxt}; use rustc_target::abi::{Abi, Variants}; +use crate::MirPass; + pub struct UnreachableEnumBranching; fn get_discriminant_local(terminator: &TerminatorKind<'_>) -> Option { diff --git a/compiler/rustc_mir_transform/src/validate.rs b/compiler/rustc_mir_transform/src/validate.rs index ab5c25c493773..746d423b7a98c 100644 --- a/compiler/rustc_mir_transform/src/validate.rs +++ b/compiler/rustc_mir_transform/src/validate.rs @@ -17,9 +17,7 @@ use rustc_middle::{bug, span_bug}; use rustc_target::abi::{Size, FIRST_VARIANT}; use rustc_target::spec::abi::Abi; -use crate::util::is_within_packed; - -use crate::util::relate_types; +use crate::util::{is_within_packed, relate_types}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum EdgeKind { diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 3655a677ba0ad..df2abf6dc9cc4 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -207,6 +207,9 @@ mod move_check; +use std::path::PathBuf; + +use move_check::MoveCheckState; use rustc_data_structures::sync::{par_for_each_in, LRef, MTLock}; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_hir as hir; @@ -216,17 +219,15 @@ use rustc_hir::lang_items::LangItem; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::mir::interpret::{AllocId, ErrorHandled, GlobalAlloc, Scalar}; use rustc_middle::mir::mono::{InstantiationMode, MonoItem}; -use rustc_middle::mir::traversal; use rustc_middle::mir::visit::Visitor as MirVisitor; -use rustc_middle::mir::{self, Location, MentionedItem}; +use rustc_middle::mir::{self, traversal, Location, MentionedItem}; use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::adjustment::{CustomCoerceUnsized, PointerCoercion}; use rustc_middle::ty::layout::ValidityRequirement; use rustc_middle::ty::print::{shrunk_instance_name, with_no_trimmed_paths}; -use rustc_middle::ty::GenericArgs; use rustc_middle::ty::{ - self, AssocKind, GenericParamDefKind, Instance, InstanceKind, Ty, TyCtxt, TypeFoldable, - TypeVisitableExt, VtblEntry, + self, AssocKind, GenericArgs, GenericParamDefKind, Instance, InstanceKind, Ty, TyCtxt, + TypeFoldable, TypeVisitableExt, VtblEntry, }; use rustc_middle::util::Providers; use rustc_middle::{bug, span_bug}; @@ -236,11 +237,9 @@ use rustc_span::source_map::{dummy_spanned, respan, Spanned}; use rustc_span::symbol::{sym, Ident}; use rustc_span::{Span, DUMMY_SP}; use rustc_target::abi::Size; -use std::path::PathBuf; use tracing::{debug, instrument, trace}; use crate::errors::{self, EncounteredErrorWhileInstantiating, NoOptimizedMir, RecursionLimit}; -use move_check::MoveCheckState; #[derive(PartialEq)] pub enum MonoItemCollectionStrategy { @@ -1230,7 +1229,7 @@ fn collect_items_of_instance<'tcx>( // Always visit all `required_consts`, so that we evaluate them and abort compilation if any of // them errors. - for const_op in &body.required_consts { + for const_op in body.required_consts() { if let Some(val) = collector.eval_constant(const_op) { collect_const_value(tcx, val, mentioned_items); } @@ -1238,7 +1237,7 @@ fn collect_items_of_instance<'tcx>( // Always gather mentioned items. We try to avoid processing items that we have already added to // `used_items` above. - for item in &body.mentioned_items { + for item in body.mentioned_items() { if !collector.used_mentioned_items.contains(&item.node) { let item_mono = collector.monomorphize(item.node); visit_mentioned_item(tcx, &item_mono, item.span, mentioned_items); diff --git a/compiler/rustc_monomorphize/src/errors.rs b/compiler/rustc_monomorphize/src/errors.rs index 9548c46e6fa04..88286cb73a6c3 100644 --- a/compiler/rustc_monomorphize/src/errors.rs +++ b/compiler/rustc_monomorphize/src/errors.rs @@ -1,10 +1,11 @@ use std::path::PathBuf; -use crate::fluent_generated as fluent; use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level}; use rustc_macros::{Diagnostic, LintDiagnostic}; use rustc_span::{Span, Symbol}; +use crate::fluent_generated as fluent; + #[derive(Diagnostic)] #[diag(monomorphize_recursion_limit)] pub struct RecursionLimit { diff --git a/compiler/rustc_monomorphize/src/lib.rs b/compiler/rustc_monomorphize/src/lib.rs index fc6e8e0d14fd2..d6b0f9c4d288f 100644 --- a/compiler/rustc_monomorphize/src/lib.rs +++ b/compiler/rustc_monomorphize/src/lib.rs @@ -1,15 +1,13 @@ // tidy-alphabetical-start #![feature(array_windows)] -#![feature(is_sorted)] // tidy-alphabetical-end use rustc_hir::lang_items::LangItem; -use rustc_middle::bug; use rustc_middle::query::TyCtxtAt; -use rustc_middle::traits; use rustc_middle::ty::adjustment::CustomCoerceUnsized; use rustc_middle::ty::{self, Ty}; use rustc_middle::util::Providers; +use rustc_middle::{bug, traits}; use rustc_span::ErrorGuaranteed; mod collector; diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index 8c7c5e0074abf..65a3d8d1742d9 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -113,15 +113,15 @@ use rustc_middle::mir::mono::{ Visibility, }; use rustc_middle::ty::print::{characteristic_def_id_of_type, with_no_trimmed_paths}; -use rustc_middle::ty::{self, visit::TypeVisitableExt, InstanceKind, TyCtxt}; +use rustc_middle::ty::visit::TypeVisitableExt; +use rustc_middle::ty::{self, InstanceKind, TyCtxt}; use rustc_middle::util::Providers; use rustc_session::config::{DumpMonoStatsFormat, SwitchWithOptPath}; use rustc_session::CodegenUnits; use rustc_span::symbol::Symbol; use tracing::debug; -use crate::collector::UsageMap; -use crate::collector::{self, MonoItemCollectionStrategy}; +use crate::collector::{self, MonoItemCollectionStrategy, UsageMap}; use crate::errors::{CouldntDumpMonoStats, SymbolAlreadyDefined, UnknownCguCollectionMode}; struct PartitioningCx<'a, 'tcx> { diff --git a/compiler/rustc_monomorphize/src/polymorphize.rs b/compiler/rustc_monomorphize/src/polymorphize.rs index 2d69bfa4da8e6..5a24202db65ec 100644 --- a/compiler/rustc_monomorphize/src/polymorphize.rs +++ b/compiler/rustc_monomorphize/src/polymorphize.rs @@ -5,18 +5,14 @@ //! generic parameters are unused (and eventually, in what ways generic parameters are used - only //! for their size, offset of a field, etc.). -use rustc_hir::{def::DefKind, def_id::DefId, ConstContext}; -use rustc_middle::mir::{ - self, - visit::{TyContext, Visitor}, - Local, LocalDecl, Location, -}; +use rustc_hir::def::DefKind; +use rustc_hir::def_id::DefId; +use rustc_hir::ConstContext; +use rustc_middle::mir::visit::{TyContext, Visitor}; +use rustc_middle::mir::{self, Local, LocalDecl, Location}; use rustc_middle::query::Providers; -use rustc_middle::ty::{ - self, - visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}, - GenericArgsRef, Ty, TyCtxt, UnusedGenericParams, -}; +use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; +use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, UnusedGenericParams}; use rustc_span::symbol::sym; use tracing::{debug, instrument}; diff --git a/compiler/rustc_monomorphize/src/util.rs b/compiler/rustc_monomorphize/src/util.rs index e25c5c9f27c75..093a697beebaf 100644 --- a/compiler/rustc_monomorphize/src/util.rs +++ b/compiler/rustc_monomorphize/src/util.rs @@ -1,7 +1,8 @@ -use rustc_middle::ty::{self, ClosureSizeProfileData, Instance, TyCtxt}; use std::fs::OpenOptions; use std::io::prelude::*; +use rustc_middle::ty::{self, ClosureSizeProfileData, Instance, TyCtxt}; + /// For a given closure, writes out the data for the profiling the impact of RFC 2229 on /// closure size into a CSV. /// diff --git a/compiler/rustc_next_trait_solver/Cargo.toml b/compiler/rustc_next_trait_solver/Cargo.toml index 79d2107b2a0a2..fdf44e1237815 100644 --- a/compiler/rustc_next_trait_solver/Cargo.toml +++ b/compiler/rustc_next_trait_solver/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start bitflags = "2.4.1" -derivative = "2.2.0" +derive-where = "1.2.7" rustc_ast_ir = { path = "../rustc_ast_ir", default-features = false } rustc_data_structures = { path = "../rustc_data_structures", optional = true } rustc_index = { path = "../rustc_index", default-features = false } diff --git a/compiler/rustc_next_trait_solver/src/coherence.rs b/compiler/rustc_next_trait_solver/src/coherence.rs index 55f602d907bbd..f22ea41c51222 100644 --- a/compiler/rustc_next_trait_solver/src/coherence.rs +++ b/compiler/rustc_next_trait_solver/src/coherence.rs @@ -1,6 +1,7 @@ use std::fmt::Debug; use std::ops::ControlFlow; +use derive_where::derive_where; use rustc_type_ir::inherent::*; use rustc_type_ir::visit::{TypeVisitable, TypeVisitableExt, TypeVisitor}; use rustc_type_ir::{self as ty, InferCtxtLike, Interner}; @@ -108,15 +109,13 @@ impl From for IsFirstInputType { } } -#[derive(derivative::Derivative)] -#[derivative(Debug(bound = "T: Debug"))] +#[derive_where(Debug; I: Interner, T: Debug)] pub enum OrphanCheckErr { NonLocalInputType(Vec<(I::Ty, IsFirstInputType)>), UncoveredTyParams(UncoveredTyParams), } -#[derive(derivative::Derivative)] -#[derivative(Debug(bound = "T: Debug"))] +#[derive_where(Debug; I: Interner, T: Debug)] pub struct UncoveredTyParams { pub uncovered: T, pub local_ty: Option, diff --git a/compiler/rustc_next_trait_solver/src/resolve.rs b/compiler/rustc_next_trait_solver/src/resolve.rs index 254ee514f8bde..132b7400300c5 100644 --- a/compiler/rustc_next_trait_solver/src/resolve.rs +++ b/compiler/rustc_next_trait_solver/src/resolve.rs @@ -1,9 +1,10 @@ -use crate::delegate::SolverDelegate; use rustc_type_ir::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_type_ir::inherent::*; use rustc_type_ir::visit::TypeVisitableExt; use rustc_type_ir::{self as ty, InferCtxtLike, Interner}; +use crate::delegate::SolverDelegate; + /////////////////////////////////////////////////////////////////////////// // EAGER RESOLUTION diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs index 01dde9ca587ca..84921e87fb3f4 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs @@ -2,12 +2,12 @@ pub(super) mod structural_traits; -use rustc_type_ir::elaborate; +use derive_where::derive_where; use rustc_type_ir::fold::TypeFoldable; use rustc_type_ir::inherent::*; use rustc_type_ir::lang_items::TraitSolverLangItem; use rustc_type_ir::visit::TypeVisitableExt as _; -use rustc_type_ir::{self as ty, Interner, Upcast as _}; +use rustc_type_ir::{self as ty, elaborate, Interner, Upcast as _}; use tracing::{debug, instrument}; use crate::delegate::SolverDelegate; @@ -21,8 +21,7 @@ use crate::solve::{ /// /// It consists of both the `source`, which describes how that goal would be proven, /// and the `result` when using the given `source`. -#[derive(derivative::Derivative)] -#[derivative(Debug(bound = ""), Clone(bound = ""))] +#[derive_where(Clone, Debug; I: Interner)] pub(super) struct Candidate { pub(super) source: CandidateSource, pub(super) result: CanonicalResponse, @@ -699,6 +698,18 @@ where if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? { Err(NoSolution) } else { + // While the trait bound itself may be unknowable, we may be able to + // prove that a super trait is not implemented. For this, we recursively + // prove the super trait bounds of the current goal. + // + // We skip the goal itself as that one would cycle. + let predicate: I::Predicate = trait_ref.upcast(cx); + ecx.add_goals( + GoalSource::Misc, + elaborate::elaborate(cx, [predicate]) + .skip(1) + .map(|predicate| goal.with(cx, predicate)), + ); ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS) } }, diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs index 7df14e81ab5d4..e69d8d84d7d89 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs @@ -1,12 +1,13 @@ //! Code which is used by built-in goals that match "structurally", such a auto //! traits, `Copy`/`Clone`. +use derive_where::derive_where; use rustc_ast_ir::{Movability, Mutability}; use rustc_type_ir::data_structures::HashMap; use rustc_type_ir::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_type_ir::inherent::*; use rustc_type_ir::lang_items::TraitSolverLangItem; -use rustc_type_ir::{self as ty, Interner, Upcast as _}; +use rustc_type_ir::{self as ty, elaborate, Interner, Upcast as _}; use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; use tracing::instrument; @@ -216,7 +217,10 @@ where // impl Copy/Clone for Closure where Self::TupledUpvars: Copy/Clone ty::Closure(_, args) => Ok(vec![ty::Binder::dummy(args.as_closure().tupled_upvars_ty())]), - ty::CoroutineClosure(..) => Err(NoSolution), + // impl Copy/Clone for CoroutineClosure where Self::TupledUpvars: Copy/Clone + ty::CoroutineClosure(_, args) => { + Ok(vec![ty::Binder::dummy(args.as_coroutine_closure().tupled_upvars_ty())]) + } // only when `coroutine_clone` is enabled and the coroutine is movable // impl Copy/Clone for Coroutine where T: Copy/Clone forall T in (upvars, witnesses) @@ -384,8 +388,7 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_callable { pub tupled_inputs_ty: I::Ty, @@ -668,11 +671,19 @@ where { let cx = ecx.cx(); let mut requirements = vec![]; - requirements.extend( + // Elaborating all supertrait outlives obligations here is not soundness critical, + // since if we just used the unelaborated set, then the transitive supertraits would + // be reachable when proving the former. However, since we elaborate all supertrait + // outlives obligations when confirming impls, we would end up with a different set + // of outlives obligations here if we didn't do the same, leading to ambiguity. + // FIXME(-Znext-solver=coinductive): Adding supertraits here can be removed once we + // make impls coinductive always, since they'll always need to prove their supertraits. + requirements.extend(elaborate::elaborate( + cx, cx.explicit_super_predicates_of(trait_ref.def_id) .iter_instantiated(cx, trait_ref.args) .map(|(pred, _)| pred), - ); + )); // FIXME(associated_const_equality): Also add associated consts to // the requirements here. diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs index 9474d501d6ff0..2e521ddcec322 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs @@ -21,9 +21,8 @@ use crate::canonicalizer::{CanonicalizeMode, Canonicalizer}; use crate::delegate::SolverDelegate; use crate::resolve::EagerResolver; use crate::solve::eval_ctxt::NestedGoals; -use crate::solve::inspect; use crate::solve::{ - response_no_constraints_raw, CanonicalInput, CanonicalResponse, Certainty, EvalCtxt, + inspect, response_no_constraints_raw, CanonicalInput, CanonicalResponse, Certainty, EvalCtxt, ExternalConstraintsData, Goal, MaybeCause, NestedNormalizationGoals, NoSolution, PredefinedOpaquesData, QueryInput, QueryResult, Response, }; diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs index c23bc8f09ad16..e328284c0010f 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs @@ -1,5 +1,6 @@ use std::ops::ControlFlow; +use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; use rustc_type_ir::data_structures::ensure_sufficient_stack; @@ -87,8 +88,7 @@ where pub(super) inspect: ProofTreeBuilder, } -#[derive(derivative::Derivative)] -#[derivative(Clone(bound = ""), Debug(bound = ""), Default(bound = ""))] +#[derive_where(Clone, Debug, Default; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] // FIXME: This can be made crate-private once `EvalCtxt` also lives in this crate. diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/probe.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/probe.rs index 4258dd9263a4e..e459d5cbe5889 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/probe.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/probe.rs @@ -5,8 +5,9 @@ use tracing::instrument; use crate::delegate::SolverDelegate; use crate::solve::assembly::Candidate; -use crate::solve::inspect; -use crate::solve::{BuiltinImplSource, CandidateSource, EvalCtxt, NoSolution, QueryResult}; +use crate::solve::{ + inspect, BuiltinImplSource, CandidateSource, EvalCtxt, NoSolution, QueryResult, +}; pub(in crate::solve) struct ProbeCtxt<'me, 'a, D, I, F, T> where diff --git a/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs b/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs index 3e266ddac71fd..a3c21666bd67c 100644 --- a/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs +++ b/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs @@ -7,15 +7,15 @@ use std::marker::PhantomData; use std::mem; +use derive_where::derive_where; use rustc_type_ir::inherent::*; use rustc_type_ir::{self as ty, search_graph, Interner}; use crate::delegate::SolverDelegate; use crate::solve::eval_ctxt::canonical; -use crate::solve::inspect; use crate::solve::{ - CanonicalInput, Certainty, GenerateProofTree, Goal, GoalEvaluationKind, GoalSource, QueryInput, - QueryResult, + inspect, CanonicalInput, Certainty, GenerateProofTree, Goal, GoalEvaluationKind, GoalSource, + QueryInput, QueryResult, }; /// The core data structure when building proof trees. @@ -51,8 +51,7 @@ where /// in the code, only one or two variants are actually possible. /// /// We simply ICE in case that assumption is broken. -#[derive(derivative::Derivative)] -#[derivative(Debug(bound = ""))] +#[derive_where(Debug; I: Interner)] enum DebugSolver { Root, GoalEvaluation(WipGoalEvaluation), @@ -78,8 +77,7 @@ impl From> for DebugSolver { } } -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""), Debug(bound = ""))] +#[derive_where(PartialEq, Eq, Debug; I: Interner)] struct WipGoalEvaluation { pub uncanonicalized_goal: Goal, pub orig_values: Vec, @@ -96,8 +94,7 @@ impl WipGoalEvaluation { } } -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""))] +#[derive_where(PartialEq, Eq; I: Interner)] pub(in crate::solve) enum WipCanonicalGoalEvaluationKind { Overflow, CycleInStack, @@ -118,8 +115,7 @@ impl std::fmt::Debug for WipCanonicalGoalEvaluationKind { } } -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""), Debug(bound = ""))] +#[derive_where(PartialEq, Eq, Debug; I: Interner)] struct WipCanonicalGoalEvaluation { goal: CanonicalInput, kind: Option>, @@ -153,8 +149,7 @@ impl WipCanonicalGoalEvaluation { } } -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""), Debug(bound = ""))] +#[derive_where(PartialEq, Eq, Debug; I: Interner)] struct WipCanonicalGoalEvaluationStep { /// Unlike `EvalCtxt::var_values`, we append a new /// generic arg here whenever we create a new inference @@ -193,8 +188,7 @@ impl WipCanonicalGoalEvaluationStep { } } -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""), Debug(bound = ""))] +#[derive_where(PartialEq, Eq, Debug; I: Interner)] struct WipProbe { initial_num_var_values: usize, steps: Vec>, @@ -212,8 +206,7 @@ impl WipProbe { } } -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""), Debug(bound = ""))] +#[derive_where(PartialEq, Eq, Debug; I: Interner)] enum WipProbeStep { AddGoal(GoalSource, inspect::CanonicalState>), NestedProbe(WipProbe), diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs index a83bd689a80a4..5738173c7a804 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs @@ -6,8 +6,7 @@ mod weak_types; use rustc_type_ir::fast_reject::{DeepRejectCtxt, TreatParams}; use rustc_type_ir::inherent::*; use rustc_type_ir::lang_items::TraitSolverLangItem; -use rustc_type_ir::Upcast as _; -use rustc_type_ir::{self as ty, Interner, NormalizesTo}; +use rustc_type_ir::{self as ty, Interner, NormalizesTo, Upcast as _}; use tracing::instrument; use crate::delegate::SolverDelegate; 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 4474bbc235198..b1dba712f797a 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -87,6 +87,19 @@ where .map(|pred| goal.with(cx, pred)); ecx.add_goals(GoalSource::ImplWhereBound, where_clause_bounds); + // We currently elaborate all supertrait outlives obligations from impls. + // This can be removed when we actually do coinduction correctly, and prove + // all supertrait obligations unconditionally. + let goal_clause: I::Clause = goal.predicate.upcast(cx); + for clause in elaborate::elaborate(cx, [goal_clause]) { + if matches!( + clause.kind().skip_binder(), + ty::ClauseKind::TypeOutlives(..) | ty::ClauseKind::RegionOutlives(..) + ) { + ecx.add_goal(GoalSource::Misc, goal.with(cx, clause)); + } + } + ecx.evaluate_added_goals_and_make_canonical_response(maximal_certainty) }) } diff --git a/compiler/rustc_parse/messages.ftl b/compiler/rustc_parse/messages.ftl index c79dad3953ba0..8e8d91ce4d038 100644 --- a/compiler/rustc_parse/messages.ftl +++ b/compiler/rustc_parse/messages.ftl @@ -53,6 +53,12 @@ parse_bare_cr = {$double_quotes -> parse_bare_cr_in_raw_string = bare CR not allowed in raw string +parse_binder_and_polarity = `for<...>` binder not allowed with `{$polarity}` trait polarity modifier + .label = there is not a well-defined meaning for a higher-ranked `{$polarity}` trait + +parse_binder_before_modifiers = `for<...>` binder should be placed before trait bound modifiers + .label = place the `for<...>` binder before any modifiers + parse_bounds_not_allowed_on_trait_aliases = bounds are not allowed on trait aliases parse_box_not_pat = expected pattern, found {$descr} @@ -60,7 +66,7 @@ parse_box_not_pat = expected pattern, found {$descr} .suggestion = escape `box` to use it as an identifier parse_box_syntax_removed = `box_syntax` has been removed - .suggestion = use `Box::new()` instead +parse_box_syntax_removed_suggestion = use `Box::new()` instead parse_cannot_be_raw_ident = `{$ident}` cannot be a raw identifier @@ -359,6 +365,7 @@ parse_inner_doc_comment_not_permitted = expected outer doc comment .sugg_change_inner_to_outer = to annotate the {$item}, change the doc comment from inner to outer style parse_invalid_attr_unsafe = `{$name}` is not an unsafe attribute + .label = this is not an unsafe attribute .suggestion = remove the `unsafe(...)` .note = extraneous unsafe is not allowed in attributes @@ -577,6 +584,9 @@ parse_missing_trait_in_trait_impl = missing trait in a trait impl parse_modifier_lifetime = `{$modifier}` may only modify trait bounds, not lifetime bounds .suggestion = remove the `{$modifier}` +parse_modifiers_and_polarity = `{$modifiers_concatenated}` trait not allowed with `{$polarity}` trait polarity modifier + .label = there is not a well-defined meaning for a `{$modifiers_concatenated} {$polarity}` trait + parse_more_than_one_char = character literal may only contain one codepoint .followed_by = this `{$chr}` is followed by the combining {$len -> [one] mark diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index 109d36fe68998..0d4512be480c3 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -2,9 +2,10 @@ use std::borrow::Cow; use rustc_ast::token::Token; use rustc_ast::{Path, Visibility}; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, - SubdiagMessageOp, Subdiagnostic, + Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, SubdiagMessageOp, + Subdiagnostic, }; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_session::errors::ExprParenthesesNeeded; @@ -554,12 +555,7 @@ pub(crate) enum MissingInInForLoopSub { code = "in" )] InNotOf(#[primary_span] Span), - #[suggestion( - parse_add_in, - style = "verbose", - applicability = "maybe-incorrect", - code = " in " - )] + #[suggestion(parse_add_in, style = "verbose", applicability = "maybe-incorrect", code = " in ")] AddIn(#[primary_span] Span), } @@ -2729,15 +2725,24 @@ impl HelpUseLatestEdition { #[derive(Diagnostic)] #[diag(parse_box_syntax_removed)] -pub struct BoxSyntaxRemoved<'a> { +pub struct BoxSyntaxRemoved { #[primary_span] - #[suggestion( - code = "Box::new({code})", - applicability = "machine-applicable", - style = "verbose" - )] pub span: Span, - pub code: &'a str, + #[subdiagnostic] + pub sugg: AddBoxNew, +} + +#[derive(Subdiagnostic)] +#[multipart_suggestion( + parse_box_syntax_removed_suggestion, + applicability = "machine-applicable", + style = "verbose" +)] +pub struct AddBoxNew { + #[suggestion_part(code = "Box::new(")] + pub box_kw_and_lo: Span, + #[suggestion_part(code = ")")] + pub hi: Span, } #[derive(Diagnostic)] @@ -3187,6 +3192,7 @@ pub(crate) struct DotDotRangeAttribute { #[note] pub struct InvalidAttrUnsafe { #[primary_span] + #[label] pub span: Span, pub name: Path, } @@ -3212,3 +3218,33 @@ pub struct UnsafeAttrOutsideUnsafeSuggestion { #[suggestion_part(code = ")")] pub right: Span, } + +#[derive(Diagnostic)] +#[diag(parse_binder_before_modifiers)] +pub struct BinderBeforeModifiers { + #[primary_span] + pub binder_span: Span, + #[label] + pub modifiers_span: Span, +} + +#[derive(Diagnostic)] +#[diag(parse_binder_and_polarity)] +pub struct BinderAndPolarity { + #[primary_span] + pub polarity_span: Span, + #[label] + pub binder_span: Span, + pub polarity: &'static str, +} + +#[derive(Diagnostic)] +#[diag(parse_modifiers_and_polarity)] +pub struct PolarityAndModifiers { + #[primary_span] + pub polarity_span: Span, + #[label] + pub modifiers_span: Span, + pub polarity: &'static str, + pub modifiers_concatenated: String, +} diff --git a/compiler/rustc_parse/src/lexer/diagnostics.rs b/compiler/rustc_parse/src/lexer/diagnostics.rs index 1247e2e44fb13..4d5d1ce099ec4 100644 --- a/compiler/rustc_parse/src/lexer/diagnostics.rs +++ b/compiler/rustc_parse/src/lexer/diagnostics.rs @@ -1,9 +1,10 @@ -use super::UnmatchedDelim; use rustc_ast::token::Delimiter; use rustc_errors::Diag; use rustc_span::source_map::SourceMap; use rustc_span::Span; +use super::UnmatchedDelim; + #[derive(Default)] pub(super) struct TokenTreeDiagInfo { /// Stack of open delimiters and their spans. Used for error message. diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs index 511805cf8d6e9..f30939093c2ec 100644 --- a/compiler/rustc_parse/src/lexer/mod.rs +++ b/compiler/rustc_parse/src/lexer/mod.rs @@ -1,25 +1,26 @@ use std::ops::Range; -use crate::errors; -use crate::lexer::unicode_chars::UNICODE_ARRAY; -use crate::make_unclosed_delims_error; use rustc_ast::ast::{self, AttrStyle}; use rustc_ast::token::{self, CommentKind, Delimiter, IdentIsRaw, Token, TokenKind}; use rustc_ast::tokenstream::TokenStream; use rustc_ast::util::unicode::contains_text_flow_control_chars; -use rustc_errors::{codes::*, Applicability, Diag, DiagCtxtHandle, StashKey}; +use rustc_errors::codes::*; +use rustc_errors::{Applicability, Diag, DiagCtxtHandle, StashKey}; use rustc_lexer::unescape::{self, EscapeError, Mode}; -use rustc_lexer::{Base, DocStyle, RawStrError}; -use rustc_lexer::{Cursor, LiteralKind}; +use rustc_lexer::{Base, Cursor, DocStyle, LiteralKind, RawStrError}; use rustc_session::lint::builtin::{ RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, TEXT_DIRECTION_CODEPOINT_IN_COMMENT, }; use rustc_session::lint::BuiltinLintDiag; use rustc_session::parse::ParseSess; +use rustc_span::edition::Edition; use rustc_span::symbol::Symbol; -use rustc_span::{edition::Edition, BytePos, Pos, Span}; +use rustc_span::{BytePos, Pos, Span}; use tracing::debug; +use crate::lexer::unicode_chars::UNICODE_ARRAY; +use crate::{errors, make_unclosed_delims_error}; + mod diagnostics; mod tokentrees; mod unescape_error_reporting; diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs index 8e54345469133..fb4ed5b93b27f 100644 --- a/compiler/rustc_parse/src/lexer/tokentrees.rs +++ b/compiler/rustc_parse/src/lexer/tokentrees.rs @@ -1,14 +1,15 @@ -use super::diagnostics::report_suspicious_mismatch_block; -use super::diagnostics::same_indentation_level; -use super::diagnostics::TokenTreeDiagInfo; -use super::{StringReader, UnmatchedDelim}; -use crate::Parser; use rustc_ast::token::{self, Delimiter, Token}; use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; use rustc_ast_pretty::pprust::token_to_string; use rustc_errors::{Applicability, PErr}; use rustc_span::symbol::kw; +use super::diagnostics::{ + report_suspicious_mismatch_block, same_indentation_level, TokenTreeDiagInfo, +}; +use super::{StringReader, UnmatchedDelim}; +use crate::Parser; + pub(super) struct TokenTreesReader<'psess, 'src> { string_reader: StringReader<'psess, 'src>, /// The "next" token, which has been obtained from the `StringReader` but @@ -72,16 +73,31 @@ impl<'psess, 'src> TokenTreesReader<'psess, 'src> { fn eof_err(&mut self) -> PErr<'psess> { let msg = "this file contains an unclosed delimiter"; let mut err = self.string_reader.dcx().struct_span_err(self.token.span, msg); - for &(_, sp) in &self.diag_info.open_braces { - err.span_label(sp, "unclosed delimiter"); + + let unclosed_delimiter_show_limit = 5; + let len = usize::min(unclosed_delimiter_show_limit, self.diag_info.open_braces.len()); + for &(_, span) in &self.diag_info.open_braces[..len] { + err.span_label(span, "unclosed delimiter"); self.diag_info.unmatched_delims.push(UnmatchedDelim { found_delim: None, found_span: self.token.span, - unclosed_span: Some(sp), + unclosed_span: Some(span), candidate_span: None, }); } + if let Some((_, span)) = self.diag_info.open_braces.get(unclosed_delimiter_show_limit) + && self.diag_info.open_braces.len() >= unclosed_delimiter_show_limit + 2 + { + err.span_label( + *span, + format!( + "another {} unclosed delimiters begin from here", + self.diag_info.open_braces.len() - unclosed_delimiter_show_limit + ), + ); + } + if let Some((delim, _)) = self.diag_info.open_braces.last() { report_suspicious_mismatch_block( &mut err, diff --git a/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs b/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs index b7a790fcf83a7..efa53f0962b78 100644 --- a/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs +++ b/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs @@ -40,7 +40,8 @@ pub(crate) fn emit_unescape_error( dcx.emit_err(UnescapeError::InvalidUnicodeEscape { span: err_span, surrogate: false }) } EscapeError::MoreThanOneChar => { - use unicode_normalization::{char::is_combining_mark, UnicodeNormalization}; + use unicode_normalization::char::is_combining_mark; + use unicode_normalization::UnicodeNormalization; let mut sugg = None; let mut note = None; diff --git a/compiler/rustc_parse/src/lexer/unicode_chars.rs b/compiler/rustc_parse/src/lexer/unicode_chars.rs index 0a82ede3b75d4..d78b3664b1ee8 100644 --- a/compiler/rustc_parse/src/lexer/unicode_chars.rs +++ b/compiler/rustc_parse/src/lexer/unicode_chars.rs @@ -1,12 +1,12 @@ //! Characters and their corresponding confusables were collected from //! +use rustc_span::symbol::kw; +use rustc_span::{BytePos, Pos, Span}; + use super::StringReader; -use crate::{ - errors::TokenSubstitution, - token::{self, Delimiter}, -}; -use rustc_span::{symbol::kw, BytePos, Pos, Span}; +use crate::errors::TokenSubstitution; +use crate::token::{self, Delimiter}; #[rustfmt::skip] // for line breaks pub(super) const UNICODE_ARRAY: &[(char, &str, &str)] = &[ diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index 4454747ea0212..e6b04080c8d85 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -12,18 +12,17 @@ #![feature(let_chains)] // tidy-alphabetical-end +use std::path::Path; + use rustc_ast as ast; -use rustc_ast::token; use rustc_ast::tokenstream::TokenStream; -use rustc_ast::{AttrItem, Attribute, MetaItem}; +use rustc_ast::{token, AttrItem, Attribute, MetaItem}; use rustc_ast_pretty::pprust; use rustc_data_structures::sync::Lrc; use rustc_errors::{Diag, FatalError, PResult}; use rustc_session::parse::ParseSess; use rustc_span::{FileName, SourceFile, Span}; -use std::path::Path; - pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments"); #[macro_use] diff --git a/compiler/rustc_parse/src/parser/attr.rs b/compiler/rustc_parse/src/parser/attr.rs index 0b2c304403941..8fdfbcee38546 100644 --- a/compiler/rustc_parse/src/parser/attr.rs +++ b/compiler/rustc_parse/src/parser/attr.rs @@ -1,16 +1,16 @@ -use crate::errors; -use crate::fluent_generated as fluent; -use crate::maybe_whole; - -use super::{AttrWrapper, Capturing, FnParseMode, ForceCollect, Parser, PathStyle}; use rustc_ast as ast; use rustc_ast::attr; use rustc_ast::token::{self, Delimiter}; -use rustc_errors::{codes::*, Diag, PResult}; -use rustc_span::{sym, symbol::kw, BytePos, Span}; +use rustc_errors::codes::*; +use rustc_errors::{Diag, PResult}; +use rustc_span::symbol::kw; +use rustc_span::{sym, BytePos, Span}; use thin_vec::ThinVec; use tracing::debug; +use super::{AttrWrapper, Capturing, FnParseMode, ForceCollect, Parser, ParserRange, PathStyle}; +use crate::{errors, fluent_generated as fluent, maybe_whole}; + // Public for rustfmt usage #[derive(Debug)] pub enum InnerAttrPolicy { @@ -31,6 +31,12 @@ enum OuterAttributeType { Attribute, } +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum AllowLeadingUnsafe { + Yes, + No, +} + impl<'a> Parser<'a> { /// Parses attributes that appear before an item. pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, AttrWrapper> { @@ -307,8 +313,8 @@ impl<'a> Parser<'a> { // inner attribute, for possible later processing in a `LazyAttrTokenStream`. if let Capturing::Yes = self.capture_state.capturing { let end_pos = self.num_bump_calls; - let range = start_pos..end_pos; - self.capture_state.inner_attr_ranges.insert(attr.id, range); + let parser_range = ParserRange(start_pos..end_pos); + self.capture_state.inner_attr_parser_ranges.insert(attr.id, parser_range); } attrs.push(attr); } else { @@ -332,7 +338,7 @@ impl<'a> Parser<'a> { /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited. pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> { - let cfg_predicate = self.parse_meta_item()?; + let cfg_predicate = self.parse_meta_item(AllowLeadingUnsafe::No)?; self.expect(&token::Comma)?; // Presumably, the majority of the time there will only be one attr. @@ -368,7 +374,10 @@ impl<'a> Parser<'a> { /// MetaItem = SimplePath ( '=' UNSUFFIXED_LIT | '(' MetaSeq? ')' )? ; /// MetaSeq = MetaItemInner (',' MetaItemInner)* ','? ; /// ``` - pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> { + pub fn parse_meta_item( + &mut self, + unsafe_allowed: AllowLeadingUnsafe, + ) -> PResult<'a, ast::MetaItem> { // We can't use `maybe_whole` here because it would bump in the `None` // case, which we don't want. if let token::Interpolated(nt) = &self.token.kind @@ -384,7 +393,11 @@ impl<'a> Parser<'a> { } let lo = self.token.span; - let is_unsafe = self.eat_keyword(kw::Unsafe); + let is_unsafe = if unsafe_allowed == AllowLeadingUnsafe::Yes { + self.eat_keyword(kw::Unsafe) + } else { + false + }; let unsafety = if is_unsafe { let unsafe_span = self.prev_token.span; self.psess.gated_spans.gate(sym::unsafe_attributes, unsafe_span); @@ -427,7 +440,7 @@ impl<'a> Parser<'a> { Err(err) => err.cancel(), // we provide a better error below } - match self.parse_meta_item() { + match self.parse_meta_item(AllowLeadingUnsafe::No) { Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)), Err(err) => err.cancel(), // we provide a better error below } @@ -457,14 +470,3 @@ impl<'a> Parser<'a> { Err(self.dcx().create_err(err)) } } - -/// The attributes are complete if all attributes are either a doc comment or a -/// builtin attribute other than `cfg_attr`. -pub fn is_complete(attrs: &[ast::Attribute]) -> bool { - attrs.iter().all(|attr| { - attr.is_doc_comment() - || attr.ident().is_some_and(|ident| { - ident.name != sym::cfg_attr && rustc_feature::is_builtin_attr_name(ident.name) - }) - }) -} diff --git a/compiler/rustc_parse/src/parser/attr_wrapper.rs b/compiler/rustc_parse/src/parser/attr_wrapper.rs index dc5f98f7be8b6..abf61036c2deb 100644 --- a/compiler/rustc_parse/src/parser/attr_wrapper.rs +++ b/compiler/rustc_parse/src/parser/attr_wrapper.rs @@ -1,14 +1,19 @@ -use super::{Capturing, FlatToken, ForceCollect, Parser, ReplaceRange, TokenCursor}; +use std::{iter, mem}; + use rustc_ast::token::{Delimiter, Token, TokenKind}; -use rustc_ast::tokenstream::{AttrTokenStream, AttrTokenTree, AttrsTarget, DelimSpacing}; -use rustc_ast::tokenstream::{DelimSpan, LazyAttrTokenStream, Spacing, ToAttrTokenStream}; -use rustc_ast::{self as ast}; -use rustc_ast::{AttrVec, Attribute, HasAttrs, HasTokens}; +use rustc_ast::tokenstream::{ + AttrTokenStream, AttrTokenTree, AttrsTarget, DelimSpacing, DelimSpan, LazyAttrTokenStream, + Spacing, ToAttrTokenStream, +}; +use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, HasTokens}; use rustc_errors::PResult; use rustc_session::parse::ParseSess; use rustc_span::{sym, Span, DUMMY_SP}; -use std::{iter, mem}; +use super::{ + Capturing, FlatToken, ForceCollect, NodeRange, NodeReplacement, Parser, ParserRange, + TokenCursor, +}; /// A wrapper type to ensure that the parser handles outer attributes correctly. /// When we parse outer attributes, we need to ensure that we capture tokens @@ -26,8 +31,8 @@ use std::{iter, mem}; #[derive(Debug, Clone)] pub struct AttrWrapper { attrs: AttrVec, - // The start of the outer attributes in the token cursor. - // This allows us to create a `ReplaceRange` for the entire attribute + // The start of the outer attributes in the parser's token stream. + // This lets us create a `NodeReplacement` for the entire attribute // target, including outer attributes. start_pos: u32, } @@ -51,19 +56,14 @@ impl AttrWrapper { /// Prepend `self.attrs` to `attrs`. // FIXME: require passing an NT to prevent misuse of this method - pub(crate) fn prepend_to_nt_inner(self, attrs: &mut AttrVec) { - let mut self_attrs = self.attrs; - mem::swap(attrs, &mut self_attrs); - attrs.extend(self_attrs); + pub(crate) fn prepend_to_nt_inner(mut self, attrs: &mut AttrVec) { + mem::swap(attrs, &mut self.attrs); + attrs.extend(self.attrs); } pub fn is_empty(&self) -> bool { self.attrs.is_empty() } - - pub fn is_complete(&self) -> bool { - crate::parser::attr::is_complete(&self.attrs) - } } /// Returns `true` if `attrs` contains a `cfg` or `cfg_attr` attribute @@ -91,7 +91,7 @@ struct LazyAttrTokenStreamImpl { cursor_snapshot: TokenCursor, num_calls: u32, break_last_token: bool, - replace_ranges: Box<[ReplaceRange]>, + node_replacements: Box<[NodeReplacement]>, } impl ToAttrTokenStream for LazyAttrTokenStreamImpl { @@ -106,25 +106,26 @@ impl ToAttrTokenStream for LazyAttrTokenStreamImpl { .chain(iter::repeat_with(|| FlatToken::Token(cursor_snapshot.next()))) .take(self.num_calls as usize); - if self.replace_ranges.is_empty() { + if self.node_replacements.is_empty() { make_attr_token_stream(tokens, self.break_last_token) } else { let mut tokens: Vec<_> = tokens.collect(); - let mut replace_ranges = self.replace_ranges.to_vec(); - replace_ranges.sort_by_key(|(range, _)| range.start); + let mut node_replacements = self.node_replacements.to_vec(); + node_replacements.sort_by_key(|(range, _)| range.0.start); #[cfg(debug_assertions)] + for [(node_range, tokens), (next_node_range, next_tokens)] in + node_replacements.array_windows() { - for [(range, tokens), (next_range, next_tokens)] in replace_ranges.array_windows() { - assert!( - range.end <= next_range.start || range.end >= next_range.end, - "Replace ranges should either be disjoint or nested: ({:?}, {:?}) ({:?}, {:?})", - range, - tokens, - next_range, - next_tokens, - ); - } + assert!( + node_range.0.end <= next_node_range.0.start + || node_range.0.end >= next_node_range.0.end, + "Node ranges should be disjoint or nested: ({:?}, {:?}) ({:?}, {:?})", + node_range, + tokens, + next_node_range, + next_tokens, + ); } // Process the replace ranges, starting from the highest start @@ -137,23 +138,26 @@ impl ToAttrTokenStream for LazyAttrTokenStreamImpl { // `#[cfg(FALSE)] struct Foo { #[cfg(FALSE)] field: bool }` // // By starting processing from the replace range with the greatest - // start position, we ensure that any replace range which encloses - // another replace range will capture the *replaced* tokens for the inner - // range, not the original tokens. - for (range, target) in replace_ranges.into_iter().rev() { - assert!(!range.is_empty(), "Cannot replace an empty range: {range:?}"); + // start position, we ensure that any (outer) replace range which + // encloses another (inner) replace range will fully overwrite the + // inner range's replacement. + for (node_range, target) in node_replacements.into_iter().rev() { + assert!( + !node_range.0.is_empty(), + "Cannot replace an empty node range: {:?}", + node_range.0 + ); // Replace the tokens in range with zero or one `FlatToken::AttrsTarget`s, plus // enough `FlatToken::Empty`s to fill up the rest of the range. This keeps the // total length of `tokens` constant throughout the replacement process, allowing - // us to use all of the `ReplaceRanges` entries without adjusting indices. + // us to do all replacements without adjusting indices. let target_len = target.is_some() as usize; tokens.splice( - (range.start as usize)..(range.end as usize), - target - .into_iter() - .map(|target| FlatToken::AttrsTarget(target)) - .chain(iter::repeat(FlatToken::Empty).take(range.len() - target_len)), + (node_range.0.start as usize)..(node_range.0.end as usize), + target.into_iter().map(|target| FlatToken::AttrsTarget(target)).chain( + iter::repeat(FlatToken::Empty).take(node_range.0.len() - target_len), + ), ); } make_attr_token_stream(tokens.into_iter(), self.break_last_token) @@ -199,20 +203,20 @@ impl<'a> Parser<'a> { force_collect: ForceCollect, f: impl FnOnce(&mut Self, ast::AttrVec) -> PResult<'a, (R, bool)>, ) -> PResult<'a, R> { - // Skip collection when nothing could observe the collected tokens, i.e. - // all of the following conditions hold. - // - We are not force collecting tokens (because force collection - // requires tokens by definition). - if matches!(force_collect, ForceCollect::No) - // - None of our outer attributes require tokens. - && attrs.is_complete() - // - Our target doesn't support custom inner attributes (custom + // We must collect if anything could observe the collected tokens, i.e. + // if any of the following conditions hold. + // - We are force collecting tokens (because force collection requires + // tokens by definition). + let needs_collection = matches!(force_collect, ForceCollect::Yes) + // - Any of our outer attributes require tokens. + || needs_tokens(&attrs.attrs) + // - Our target supports custom inner attributes (custom // inner attribute invocation might require token capturing). - && !R::SUPPORTS_CUSTOM_INNER_ATTRS - // - We are not in `capture_cfg` mode (which requires tokens if + || R::SUPPORTS_CUSTOM_INNER_ATTRS + // - We are in `capture_cfg` mode (which requires tokens if // the parsed node has `#[cfg]` or `#[cfg_attr]` attributes). - && !self.capture_cfg - { + || self.capture_cfg; + if !needs_collection { return Ok(f(self, attrs.attrs)?.0); } @@ -220,7 +224,7 @@ impl<'a> Parser<'a> { let cursor_snapshot = self.token_cursor.clone(); let start_pos = self.num_bump_calls; let has_outer_attrs = !attrs.attrs.is_empty(); - let replace_ranges_start = self.capture_state.replace_ranges.len(); + let parser_replacements_start = self.capture_state.parser_replacements.len(); // We set and restore `Capturing::Yes` on either side of the call to // `f`, so we can distinguish the outermost call to @@ -250,32 +254,32 @@ impl<'a> Parser<'a> { return Ok(ret); } - // This is similar to the "skip collection" check at the start of this - // function, but now that we've parsed an AST node we have more + // This is similar to the `needs_collection` check at the start of this + // function, but now that we've parsed an AST node we have complete // information available. (If we return early here that means the // setup, such as cloning the token cursor, was unnecessary. That's // hard to avoid.) // - // Skip collection when nothing could observe the collected tokens, i.e. - // all of the following conditions hold. - // - We are not force collecting tokens. - if matches!(force_collect, ForceCollect::No) - // - None of our outer *or* inner attributes require tokens. - // (`attrs` was just outer attributes, but `ret.attrs()` is outer - // and inner attributes. That makes this check more precise than - // `attrs.is_complete()` at the start of the function, and we can - // skip the subsequent check on `R::SUPPORTS_CUSTOM_INNER_ATTRS`. - && crate::parser::attr::is_complete(ret.attrs()) - // - We are not in `capture_cfg` mode, or we are but there are no - // `#[cfg]` or `#[cfg_attr]` attributes. (During normal - // non-`capture_cfg` parsing, we don't need any special capturing - // for those attributes, because they're builtin.) - && (!self.capture_cfg || !has_cfg_or_cfg_attr(ret.attrs())) - { + // We must collect if anything could observe the collected tokens, i.e. + // if any of the following conditions hold. + // - We are force collecting tokens. + let needs_collection = matches!(force_collect, ForceCollect::Yes) + // - Any of our outer *or* inner attributes require tokens. + // (`attr.attrs` was just outer attributes, but `ret.attrs()` is + // outer and inner attributes. So this check is more precise than + // the earlier `needs_tokens` check, and we don't need to + // check `R::SUPPORTS_CUSTOM_INNER_ATTRS`.) + || needs_tokens(ret.attrs()) + // - We are in `capture_cfg` mode and there are `#[cfg]` or + // `#[cfg_attr]` attributes. (During normal non-`capture_cfg` + // parsing, we don't need any special capturing for those + // attributes, because they're builtin.) + || (self.capture_cfg && has_cfg_or_cfg_attr(ret.attrs())); + if !needs_collection { return Ok(ret); } - let replace_ranges_end = self.capture_state.replace_ranges.len(); + let parser_replacements_end = self.capture_state.parser_replacements.len(); assert!( !(self.break_last_token && capture_trailing), @@ -292,53 +296,59 @@ impl<'a> Parser<'a> { let num_calls = end_pos - start_pos; - // Take the captured ranges for any inner attributes that we parsed in - // `Parser::parse_inner_attributes`, and pair them in a `ReplaceRange` - // with `None`, which means the relevant tokens will be removed. (More - // details below.) - let mut inner_attr_replace_ranges = Vec::new(); - for inner_attr in ret.attrs().iter().filter(|a| a.style == ast::AttrStyle::Inner) { - if let Some(attr_range) = self.capture_state.inner_attr_ranges.remove(&inner_attr.id) { - inner_attr_replace_ranges.push((attr_range, None)); - } else { - self.dcx().span_delayed_bug(inner_attr.span, "Missing token range for attribute"); + // Take the captured `ParserRange`s for any inner attributes that we parsed in + // `Parser::parse_inner_attributes`, and pair them in a `ParserReplacement` with `None`, + // which means the relevant tokens will be removed. (More details below.) + let mut inner_attr_parser_replacements = Vec::new(); + for attr in ret.attrs() { + if attr.style == ast::AttrStyle::Inner { + if let Some(inner_attr_parser_range) = + self.capture_state.inner_attr_parser_ranges.remove(&attr.id) + { + inner_attr_parser_replacements.push((inner_attr_parser_range, None)); + } else { + self.dcx().span_delayed_bug(attr.span, "Missing token range for attribute"); + } } } // This is hot enough for `deep-vector` that checking the conditions for an empty iterator // is measurably faster than actually executing the iterator. - let replace_ranges: Box<[ReplaceRange]> = - if replace_ranges_start == replace_ranges_end && inner_attr_replace_ranges.is_empty() { - Box::new([]) - } else { - // Grab any replace ranges that occur *inside* the current AST node. We will - // perform the actual replacement only when we convert the `LazyAttrTokenStream` to - // an `AttrTokenStream`. - self.capture_state.replace_ranges[replace_ranges_start..replace_ranges_end] - .iter() - .cloned() - .chain(inner_attr_replace_ranges.iter().cloned()) - .map(|(range, data)| ((range.start - start_pos)..(range.end - start_pos), data)) - .collect() - }; + let node_replacements: Box<[_]> = if parser_replacements_start == parser_replacements_end + && inner_attr_parser_replacements.is_empty() + { + Box::new([]) + } else { + // Grab any replace ranges that occur *inside* the current AST node. Convert them + // from `ParserRange` form to `NodeRange` form. We will perform the actual + // replacement only when we convert the `LazyAttrTokenStream` to an + // `AttrTokenStream`. + self.capture_state.parser_replacements + [parser_replacements_start..parser_replacements_end] + .iter() + .cloned() + .chain(inner_attr_parser_replacements.iter().cloned()) + .map(|(parser_range, data)| (NodeRange::new(parser_range, start_pos), data)) + .collect() + }; // What is the status here when parsing the example code at the top of this method? // // When parsing `g`: // - `start_pos..end_pos` is `12..33` (`fn g { ... }`, excluding the outer attr). - // - `inner_attr_replace_ranges` has one entry (`5..15`, when counting from `fn`), to + // - `inner_attr_parser_replacements` has one entry (`ParserRange(17..27)`), to // delete the inner attr's tokens. - // - This entry is put into the lazy tokens for `g`, i.e. deleting the inner attr from - // those tokens (if they get evaluated). + // - This entry is converted to `NodeRange(5..15)` (relative to the `fn`) and put into + // the lazy tokens for `g`, i.e. deleting the inner attr from those tokens (if they get + // evaluated). // - Those lazy tokens are also put into an `AttrsTarget` that is appended to `self`'s // replace ranges at the bottom of this function, for processing when parsing `m`. - // - `replace_ranges_start..replace_ranges_end` is empty. + // - `parser_replacements_start..parser_replacements_end` is empty. // // When parsing `m`: // - `start_pos..end_pos` is `0..34` (`mod m`, excluding the `#[cfg_eval]` attribute). - // - `inner_attr_replace_ranges` is empty. - // - `replace_range_start..replace_ranges_end` has two entries. - // - One to delete the inner attribute (`17..27`), obtained when parsing `g` (see above). + // - `inner_attr_parser_replacements` is empty. + // - `parser_replacements_start..parser_replacements_end` has one entry. // - One `AttrsTarget` (added below when parsing `g`) to replace all of `g` (`3..33`, // including its outer attribute), with: // - `attrs`: includes the outer and the inner attr. @@ -349,7 +359,7 @@ impl<'a> Parser<'a> { num_calls, cursor_snapshot, break_last_token: self.break_last_token, - replace_ranges, + node_replacements, }); // If we support tokens and don't already have them, store the newly captured tokens. @@ -369,12 +379,10 @@ impl<'a> Parser<'a> { // What is the status here when parsing the example code at the top of this method? // - // When parsing `g`, we add two entries: - // - The `start_pos..end_pos` (`3..33`) entry has a new `AttrsTarget` with: + // When parsing `g`, we add one entry: + // - The pushed entry (`ParserRange(3..33)`) has a new `AttrsTarget` with: // - `attrs`: includes the outer and the inner attr. // - `tokens`: lazy tokens for `g` (with its inner attr deleted). - // - `inner_attr_replace_ranges` contains the one entry to delete the inner attr's - // tokens (`17..27`). // // When parsing `m`, we do nothing here. @@ -383,13 +391,14 @@ impl<'a> Parser<'a> { // cfg-expand this AST node. let start_pos = if has_outer_attrs { attrs.start_pos } else { start_pos }; let target = AttrsTarget { attrs: ret.attrs().iter().cloned().collect(), tokens }; - self.capture_state.replace_ranges.push((start_pos..end_pos, Some(target))); - self.capture_state.replace_ranges.extend(inner_attr_replace_ranges); + self.capture_state + .parser_replacements + .push((ParserRange(start_pos..end_pos), Some(target))); } else if matches!(self.capture_state.capturing, Capturing::No) { // Only clear the ranges once we've finished capturing entirely, i.e. we've finished // the outermost call to this method. - self.capture_state.replace_ranges.clear(); - self.capture_state.inner_attr_ranges.clear(); + self.capture_state.parser_replacements.clear(); + self.capture_state.inner_attr_parser_ranges.clear(); } Ok(ret) } @@ -461,11 +470,25 @@ fn make_attr_token_stream( AttrTokenStream::new(stack_top.inner) } +/// Tokens are needed if: +/// - any non-single-segment attributes (other than doc comments) are present; or +/// - any `cfg_attr` attributes are present; +/// - any single-segment, non-builtin attributes are present. +fn needs_tokens(attrs: &[ast::Attribute]) -> bool { + attrs.iter().any(|attr| match attr.ident() { + None => !attr.is_doc_comment(), + Some(ident) => { + ident.name == sym::cfg_attr || !rustc_feature::is_builtin_attr_name(ident.name) + } + }) +} + // Some types are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(AttrWrapper, 16); static_assert_size!(LazyAttrTokenStreamImpl, 96); diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 1a0d9aa6378e7..47ca85ba060b9 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -1,25 +1,6 @@ -use super::pat::Expected; -use super::{ - BlockMode, CommaRecoveryMode, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep, TokenType, -}; -use crate::errors::{ - AddParen, AmbiguousPlus, AsyncMoveBlockIn2015, AttributeOnParamType, AwaitSuggestion, - BadQPathStage2, BadTypePlus, BadTypePlusSub, ColonAsSemi, ComparisonOperatorsCannotBeChained, - ComparisonOperatorsCannotBeChainedSugg, ConstGenericWithoutBraces, - ConstGenericWithoutBracesSugg, DocCommentDoesNotDocumentAnything, DocCommentOnParamType, - DoubleColonInBound, ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg, - GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg, - HelpIdentifierStartsWithNumber, HelpUseLatestEdition, InInTypo, IncorrectAwait, - IncorrectSemicolon, IncorrectUseOfAwait, PatternMethodParamWithoutBody, QuestionMarkInType, - QuestionMarkInTypeSugg, SelfParamNotFirst, StructLiteralBodyWithoutPath, - StructLiteralBodyWithoutPathSugg, StructLiteralNeedingParens, StructLiteralNeedingParensSugg, - SuggAddMissingLetStmt, SuggEscapeIdentifier, SuggRemoveComma, TernaryOperator, - UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration, - UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead, WrapType, -}; -use crate::fluent_generated as fluent; -use crate::parser; -use crate::parser::attr::InnerAttrPolicy; +use std::mem::take; +use std::ops::{Deref, DerefMut}; + use ast::token::IdentIsRaw; use rustc_ast as ast; use rustc_ast::ptr::P; @@ -41,11 +22,31 @@ use rustc_session::errors::ExprParenthesesNeeded; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{BytePos, Span, SpanSnippetError, Symbol, DUMMY_SP}; -use std::mem::take; -use std::ops::{Deref, DerefMut}; use thin_vec::{thin_vec, ThinVec}; use tracing::{debug, trace}; +use super::pat::Expected; +use super::{ + BlockMode, CommaRecoveryMode, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep, TokenType, +}; +use crate::errors::{ + AddParen, AmbiguousPlus, AsyncMoveBlockIn2015, AttributeOnParamType, AwaitSuggestion, + BadQPathStage2, BadTypePlus, BadTypePlusSub, ColonAsSemi, ComparisonOperatorsCannotBeChained, + ComparisonOperatorsCannotBeChainedSugg, ConstGenericWithoutBraces, + ConstGenericWithoutBracesSugg, DocCommentDoesNotDocumentAnything, DocCommentOnParamType, + DoubleColonInBound, ExpectedIdentifier, ExpectedSemi, ExpectedSemiSugg, + GenericParamsWithoutAngleBrackets, GenericParamsWithoutAngleBracketsSugg, + HelpIdentifierStartsWithNumber, HelpUseLatestEdition, InInTypo, IncorrectAwait, + IncorrectSemicolon, IncorrectUseOfAwait, PatternMethodParamWithoutBody, QuestionMarkInType, + QuestionMarkInTypeSugg, SelfParamNotFirst, StructLiteralBodyWithoutPath, + StructLiteralBodyWithoutPathSugg, StructLiteralNeedingParens, StructLiteralNeedingParensSugg, + SuggAddMissingLetStmt, SuggEscapeIdentifier, SuggRemoveComma, TernaryOperator, + UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration, + UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead, WrapType, +}; +use crate::parser::attr::InnerAttrPolicy; +use crate::{fluent_generated as fluent, parser}; + /// Creates a placeholder argument. pub(super) fn dummy_arg(ident: Ident, guar: ErrorGuaranteed) -> Param { let pat = P(Pat { diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 389a6d11e19e2..ccf8dcdf0b6f2 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -1,30 +1,22 @@ // ignore-tidy-filelength -use super::diagnostics::SnapshotParser; -use super::pat::{CommaRecoveryMode, Expected, RecoverColon, RecoverComma}; -use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign}; -use super::{ - AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions, - SemiColonMode, SeqSep, TokenType, Trailing, -}; +use core::mem; +use core::ops::ControlFlow; -use crate::errors; -use crate::maybe_recover_from_interpolated_ty_qpath; use ast::mut_visit::{self, MutVisitor}; use ast::token::IdentIsRaw; use ast::{CoroutineKind, ForLoopKind, GenBlockKind, MatchKind, Pat, Path, PathSegment, Recovered}; -use core::mem; -use core::ops::ControlFlow; use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter, Token, TokenKind}; use rustc_ast::util::case::Case; use rustc_ast::util::classify; use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity}; use rustc_ast::visit::{walk_expr, Visitor}; -use rustc_ast::{self as ast, AttrStyle, AttrVec, CaptureBy, ExprField, UnOp, DUMMY_NODE_ID}; -use rustc_ast::{AnonConst, BinOp, BinOpKind, FnDecl, FnRetTy, MacCall, Param, Ty, TyKind}; -use rustc_ast::{Arm, BlockCheckMode, Expr, ExprKind, Label, Movability, RangeLimits}; -use rustc_ast::{ClosureBinder, MetaItemLit, StmtKind}; +use rustc_ast::{ + self as ast, AnonConst, Arm, AttrStyle, AttrVec, BinOp, BinOpKind, BlockCheckMode, CaptureBy, + ClosureBinder, Expr, ExprField, ExprKind, FnDecl, FnRetTy, Label, MacCall, MetaItemLit, + Movability, Param, RangeLimits, StmtKind, Ty, TyKind, UnOp, DUMMY_NODE_ID, +}; use rustc_ast_pretty::pprust; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::{Applicability, Diag, PResult, StashKey, Subdiagnostic}; @@ -39,13 +31,14 @@ use rustc_span::{BytePos, ErrorGuaranteed, Pos, Span}; use thin_vec::{thin_vec, ThinVec}; use tracing::instrument; -#[derive(Debug)] -pub(super) enum LhsExpr { - // Already parsed just the outer attributes. - Unparsed { attrs: AttrWrapper }, - // Already parsed the expression. - Parsed { expr: P, starts_statement: bool }, -} +use super::diagnostics::SnapshotParser; +use super::pat::{CommaRecoveryMode, Expected, RecoverColon, RecoverComma}; +use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign}; +use super::{ + AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions, + SemiColonMode, SeqSep, TokenType, Trailing, +}; +use crate::{errors, maybe_recover_from_interpolated_ty_qpath}; #[derive(Debug)] enum DestructuredFloat { @@ -112,30 +105,31 @@ impl<'a> Parser<'a> { r: Restrictions, attrs: AttrWrapper, ) -> PResult<'a, P> { - self.with_res(r, |this| this.parse_expr_assoc_with(0, LhsExpr::Unparsed { attrs })) + self.with_res(r, |this| this.parse_expr_assoc_with(0, attrs)) } /// Parses an associative expression with operators of at least `min_prec` precedence. pub(super) fn parse_expr_assoc_with( &mut self, min_prec: usize, - lhs: LhsExpr, + attrs: AttrWrapper, ) -> PResult<'a, P> { - let mut starts_stmt = false; - let mut lhs = match lhs { - LhsExpr::Parsed { expr, starts_statement } => { - starts_stmt = starts_statement; - expr - } - LhsExpr::Unparsed { attrs } => { - if self.token.is_range_separator() { - return self.parse_expr_prefix_range(attrs); - } else { - self.parse_expr_prefix(attrs)? - } - } + let lhs = if self.token.is_range_separator() { + return self.parse_expr_prefix_range(attrs); + } else { + self.parse_expr_prefix(attrs)? }; + self.parse_expr_assoc_rest_with(min_prec, false, lhs) + } + /// Parses the rest of an associative expression (i.e. the part after the lhs) with operators + /// of at least `min_prec` precedence. + pub(super) fn parse_expr_assoc_rest_with( + &mut self, + min_prec: usize, + starts_stmt: bool, + mut lhs: P, + ) -> PResult<'a, P> { if !self.should_continue_as_assoc_expr(&lhs) { return Ok(lhs); } @@ -271,7 +265,7 @@ impl<'a> Parser<'a> { }; let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| { let attrs = this.parse_outer_attributes()?; - this.parse_expr_assoc_with(prec + prec_adjustment, LhsExpr::Unparsed { attrs }) + this.parse_expr_assoc_with(prec + prec_adjustment, attrs) })?; let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span); @@ -446,7 +440,7 @@ impl<'a> Parser<'a> { let maybe_lt = self.token.clone(); let attrs = self.parse_outer_attributes()?; Some( - self.parse_expr_assoc_with(prec + 1, LhsExpr::Unparsed { attrs }) + self.parse_expr_assoc_with(prec + 1, attrs) .map_err(|err| self.maybe_err_dotdotlt_syntax(maybe_lt, err))?, ) } else { @@ -503,12 +497,9 @@ impl<'a> Parser<'a> { let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() { // RHS must be parsed with more associativity than the dots. let attrs = this.parse_outer_attributes()?; - this.parse_expr_assoc_with( - op.unwrap().precedence() + 1, - LhsExpr::Unparsed { attrs }, - ) - .map(|x| (lo.to(x.span), Some(x))) - .map_err(|err| this.maybe_err_dotdotlt_syntax(maybe_lt, err))? + this.parse_expr_assoc_with(op.unwrap().precedence() + 1, attrs) + .map(|x| (lo.to(x.span), Some(x))) + .map_err(|err| this.maybe_err_dotdotlt_syntax(maybe_lt, err))? } else { (lo, None) }; @@ -617,10 +608,12 @@ impl<'a> Parser<'a> { /// Parse `box expr` - this syntax has been removed, but we still parse this /// for now to provide a more useful error fn parse_expr_box(&mut self, box_kw: Span) -> PResult<'a, (Span, ExprKind)> { - let (span, _) = self.parse_expr_prefix_common(box_kw)?; - let inner_span = span.with_lo(box_kw.hi()); - let code = self.psess.source_map().span_to_snippet(inner_span).unwrap(); - let guar = self.dcx().emit_err(errors::BoxSyntaxRemoved { span: span, code: code.trim() }); + let (span, expr) = self.parse_expr_prefix_common(box_kw)?; + // Make a multipart suggestion instead of `span_to_snippet` in case source isn't available + let box_kw_and_lo = box_kw.until(self.interpolated_or_expr_span(&expr)); + let hi = span.shrink_to_hi(); + let sugg = errors::AddBoxNew { box_kw_and_lo, hi }; + let guar = self.dcx().emit_err(errors::BoxSyntaxRemoved { span, sugg }); Ok((span, ExprKind::Err(guar))) } @@ -886,7 +879,7 @@ impl<'a> Parser<'a> { mut e: P, lo: Span, ) -> PResult<'a, P> { - let res = ensure_sufficient_stack(|| { + let mut res = ensure_sufficient_stack(|| { loop { let has_question = if self.prev_token.kind == TokenKind::Ident(kw::Return, IdentIsRaw::No) { @@ -933,17 +926,13 @@ impl<'a> Parser<'a> { // Stitch the list of outer attributes onto the return value. A little // bit ugly, but the best way given the current code structure. - if attrs.is_empty() { - res - } else { - res.map(|expr| { - expr.map(|mut expr| { - attrs.extend(expr.attrs); - expr.attrs = attrs; - expr - }) - }) + if !attrs.is_empty() + && let Ok(expr) = &mut res + { + mem::swap(&mut expr.attrs, &mut attrs); + expr.attrs.extend(attrs) } + res } pub(super) fn parse_dot_suffix_expr( @@ -2644,10 +2633,7 @@ impl<'a> Parser<'a> { self.expect(&token::Eq)?; } let attrs = self.parse_outer_attributes()?; - let expr = self.parse_expr_assoc_with( - 1 + prec_let_scrutinee_needs_par(), - LhsExpr::Unparsed { attrs }, - )?; + let expr = self.parse_expr_assoc_with(1 + prec_let_scrutinee_needs_par(), attrs)?; let span = lo.to(expr.span); Ok(self.mk_expr(span, ExprKind::Let(pat, expr, span, recovered))) } @@ -3152,7 +3138,8 @@ impl<'a> Parser<'a> { if !require_comma { arm_body = Some(expr); - this.eat(&token::Comma); + // Eat a comma if it exists, though. + let _ = this.eat(&token::Comma); Ok(Recovered::No) } else if let Some((span, guar)) = this.parse_arm_body_missing_braces(&expr, arrow_span) @@ -3653,7 +3640,7 @@ impl<'a> Parser<'a> { fields.push(f); } self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore); - self.eat(&token::Comma); + let _ = self.eat(&token::Comma); } } } diff --git a/compiler/rustc_parse/src/parser/generics.rs b/compiler/rustc_parse/src/parser/generics.rs index 523538e9643ac..9124c15707de5 100644 --- a/compiler/rustc_parse/src/parser/generics.rs +++ b/compiler/rustc_parse/src/parser/generics.rs @@ -1,21 +1,19 @@ -use crate::errors::{ - self, MultipleWhereClauses, UnexpectedDefaultValueForLifetimeInGenericParameters, - UnexpectedSelfInGenericParameters, WhereClauseBeforeTupleStructBody, - WhereClauseBeforeTupleStructBodySugg, -}; - -use super::{ForceCollect, Parser}; - use ast::token::Delimiter; -use rustc_ast::token; use rustc_ast::{ - self as ast, AttrVec, GenericBounds, GenericParam, GenericParamKind, TyKind, WhereClause, + self as ast, token, AttrVec, GenericBounds, GenericParam, GenericParamKind, TyKind, WhereClause, }; use rustc_errors::{Applicability, PResult}; use rustc_span::symbol::{kw, Ident}; use rustc_span::Span; use thin_vec::ThinVec; +use super::{ForceCollect, Parser}; +use crate::errors::{ + self, MultipleWhereClauses, UnexpectedDefaultValueForLifetimeInGenericParameters, + UnexpectedSelfInGenericParameters, WhereClauseBeforeTupleStructBody, + WhereClauseBeforeTupleStructBodySugg, +}; + enum PredicateOrStructBody { Predicate(ast::WherePredicate), StructBody(ThinVec), @@ -180,7 +178,8 @@ impl<'a> Parser<'a> { span: this.prev_token.span, }); - this.eat(&token::Comma); + // Eat a trailing comma, if it exists. + let _ = this.eat(&token::Comma); } let param = if this.check_lifetime() { diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index fbc5b91460034..baa5eb2df635d 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -1,9 +1,6 @@ -use super::diagnostics::{dummy_arg, ConsumeClosingDelim}; -use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign}; -use super::{AttrWrapper, FollowedByType, ForceCollect, Parser, PathStyle, Trailing}; -use crate::errors::{self, MacroExpandsToAdtField}; -use crate::fluent_generated as fluent; -use crate::maybe_whole; +use std::fmt::Write; +use std::mem; + use ast::token::IdentIsRaw; use rustc_ast::ast::*; use rustc_ast::ptr::P; @@ -12,18 +9,21 @@ use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree}; use rustc_ast::util::case::Case; use rustc_ast::{self as ast}; use rustc_ast_pretty::pprust; -use rustc_errors::{codes::*, struct_span_code_err, Applicability, PResult, StashKey}; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, Applicability, PResult, StashKey}; use rustc_span::edit_distance::edit_distance; use rustc_span::edition::Edition; -use rustc_span::source_map; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::ErrorGuaranteed; -use rustc_span::{Span, DUMMY_SP}; -use std::fmt::Write; -use std::mem; +use rustc_span::{source_map, ErrorGuaranteed, Span, DUMMY_SP}; use thin_vec::{thin_vec, ThinVec}; use tracing::debug; +use super::diagnostics::{dummy_arg, ConsumeClosingDelim}; +use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign}; +use super::{AttrWrapper, FollowedByType, ForceCollect, Parser, PathStyle, Trailing}; +use crate::errors::{self, MacroExpandsToAdtField}; +use crate::{fluent_generated as fluent, maybe_whole}; + impl<'a> Parser<'a> { /// Parses a source module as a crate. This is the main entry point for the parser. pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> { @@ -1192,13 +1192,14 @@ impl<'a> Parser<'a> { mut safety: Safety, ) -> PResult<'a, ItemInfo> { let abi = self.parse_abi(); // ABI? + // FIXME: This recovery should be tested better. if safety == Safety::Default && self.token.is_keyword(kw::Unsafe) && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace)) { self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err().emit(); safety = Safety::Unsafe(self.token.span); - self.eat_keyword(kw::Unsafe); + let _ = self.eat_keyword(kw::Unsafe); } let module = ast::ForeignMod { safety, @@ -1759,7 +1760,7 @@ impl<'a> Parser<'a> { } } } - self.eat(&token::CloseDelim(Delimiter::Brace)); + self.expect(&token::CloseDelim(Delimiter::Brace))?; } else { let token_str = super::token_descr(&self.token); let where_str = if parsed_where { "" } else { "`where`, or " }; @@ -1902,7 +1903,7 @@ impl<'a> Parser<'a> { if let Some(_guar) = guar { // Handle a case like `Vec>,` where we can continue parsing fields // after the comma - self.eat(&token::Comma); + let _ = self.eat(&token::Comma); // `check_trailing_angle_brackets` already emitted a nicer error, as // proven by the presence of `_guar`. We can continue parsing. @@ -2483,12 +2484,15 @@ impl<'a> Parser<'a> { /// `check_pub` adds additional `pub` to the checks in case users place it /// wrongly, can be used to ensure `pub` never comes after `default`. pub(super) fn check_fn_front_matter(&mut self, check_pub: bool, case: Case) -> bool { + const ALL_QUALS: &[Symbol] = + &[kw::Pub, kw::Gen, kw::Const, kw::Async, kw::Unsafe, kw::Safe, kw::Extern]; + // We use an over-approximation here. // `const const`, `fn const` won't parse, but we're not stepping over other syntax either. // `pub` is added in case users got confused with the ordering like `async pub fn`, // only if it wasn't preceded by `default` as `default pub` is invalid. let quals: &[Symbol] = if check_pub { - &[kw::Pub, kw::Gen, kw::Const, kw::Async, kw::Unsafe, kw::Safe, kw::Extern] + ALL_QUALS } else { &[kw::Gen, kw::Const, kw::Async, kw::Unsafe, kw::Safe, kw::Extern] }; @@ -2518,9 +2522,9 @@ impl<'a> Parser<'a> { || self.check_keyword_case(kw::Extern, case) && self.look_ahead(1, |t| t.can_begin_string_literal()) && (self.look_ahead(2, |t| t.is_keyword_case(kw::Fn, case)) || - // this branch is only for better diagnostic in later, `pub` is not allowed here + // this branch is only for better diagnostics; `pub`, `unsafe`, etc. are not allowed here (self.may_recover() - && self.look_ahead(2, |t| t.is_keyword(kw::Pub)) + && self.look_ahead(2, |t| ALL_QUALS.iter().any(|&kw| t.is_keyword(kw))) && self.look_ahead(3, |t| t.is_keyword_case(kw::Fn, case)))) } @@ -2773,7 +2777,14 @@ impl<'a> Parser<'a> { let snapshot = p.create_snapshot_for_diagnostic(); let param = p.parse_param_general(req_name, first_param).or_else(|e| { let guar = e.emit(); - let lo = p.prev_token.span; + // When parsing a param failed, we should check to make the span of the param + // not contain '(' before it. + // For example when parsing `*mut Self` in function `fn oof(*mut Self)`. + let lo = if let TokenKind::OpenDelim(Delimiter::Parenthesis) = p.prev_token.kind { + p.prev_token.span.shrink_to_hi() + } else { + p.prev_token.span + }; p.restore_snapshot(snapshot); // Skip every token until next possible arg or end. p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]); diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 7326b9ec51f2b..4b8e4c25e16c2 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -10,18 +10,20 @@ mod path; mod stmt; mod ty; -use crate::lexer::UnmatchedDelim; +use std::ops::Range; +use std::{fmt, mem, slice}; + use attr_wrapper::AttrWrapper; pub use diagnostics::AttemptLocalParseRecovery; pub(crate) use expr::ForbiddenLetReason; pub(crate) use item::FnParseMode; pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma}; use path::PathStyle; - use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter, IdentIsRaw, Nonterminal, Token, TokenKind}; -use rustc_ast::tokenstream::{AttrsTarget, DelimSpacing, DelimSpan, Spacing}; -use rustc_ast::tokenstream::{TokenStream, TokenTree, TokenTreeCursor}; +use rustc_ast::tokenstream::{ + AttrsTarget, DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree, TokenTreeCursor, +}; use rustc_ast::util::case::Case; use rustc_ast::{ self as ast, AnonConst, AttrArgs, AttrArgsEq, AttrId, ByRef, Const, CoroutineKind, DelimArgs, @@ -35,14 +37,13 @@ use rustc_errors::{Applicability, Diag, FatalError, MultiSpan, PResult}; use rustc_session::parse::ParseSess; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; -use std::ops::Range; -use std::{fmt, mem, slice}; use thin_vec::ThinVec; use tracing::debug; use crate::errors::{ self, IncorrectVisibilityRestriction, MismatchedClosingDelimiter, NonStringAbiLiteral, }; +use crate::lexer::UnmatchedDelim; #[cfg(test)] mod tests; @@ -191,24 +192,54 @@ struct ClosureSpans { body: Span, } -/// Indicates a range of tokens that should be replaced by -/// the tokens in the provided `AttrsTarget`. This is used in two -/// places during token collection: +/// A token range within a `Parser`'s full token stream. +#[derive(Clone, Debug)] +struct ParserRange(Range); + +/// A token range within an individual AST node's (lazy) token stream, i.e. +/// relative to that node's first token. Distinct from `ParserRange` so the two +/// kinds of range can't be mixed up. +#[derive(Clone, Debug)] +struct NodeRange(Range); + +/// Indicates a range of tokens that should be replaced by an `AttrsTarget` +/// (replacement) or be replaced by nothing (deletion). This is used in two +/// places during token collection. +/// +/// 1. Replacement. During the parsing of an AST node that may have a +/// `#[derive]` attribute, when we parse a nested AST node that has `#[cfg]` +/// or `#[cfg_attr]`, we replace the entire inner AST node with +/// `FlatToken::AttrsTarget`. This lets us perform eager cfg-expansion on an +/// `AttrTokenStream`. /// -/// 1. During the parsing of an AST node that may have a `#[derive]` -/// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]` -/// In this case, we use a `ReplaceRange` to replace the entire inner AST node -/// with `FlatToken::AttrsTarget`, allowing us to perform eager cfg-expansion -/// on an `AttrTokenStream`. +/// 2. Deletion. We delete inner attributes from all collected token streams, +/// and instead track them through the `attrs` field on the AST node. This +/// lets us manipulate them similarly to outer attributes. When we create a +/// `TokenStream`, the inner attributes are inserted into the proper place +/// in the token stream. /// -/// 2. When we parse an inner attribute while collecting tokens. We -/// remove inner attributes from the token stream entirely, and -/// instead track them through the `attrs` field on the AST node. -/// This allows us to easily manipulate them (for example, removing -/// the first macro inner attribute to invoke a proc-macro). -/// When create a `TokenStream`, the inner attributes get inserted -/// into the proper place in the token stream. -type ReplaceRange = (Range, Option); +/// Each replacement starts off in `ParserReplacement` form but is converted to +/// `NodeReplacement` form when it is attached to a single AST node, via +/// `LazyAttrTokenStreamImpl`. +type ParserReplacement = (ParserRange, Option); + +/// See the comment on `ParserReplacement`. +type NodeReplacement = (NodeRange, Option); + +impl NodeRange { + // Converts a range within a parser's tokens to a range within a + // node's tokens beginning at `start_pos`. + // + // For example, imagine a parser with 50 tokens in its token stream, a + // function that spans `ParserRange(20..40)` and an inner attribute within + // that function that spans `ParserRange(30..35)`. We would find the inner + // attribute's range within the function's tokens by subtracting 20, which + // is the position of the function's start token. This gives + // `NodeRange(10..15)`. + fn new(ParserRange(parser_range): ParserRange, start_pos: u32) -> NodeRange { + NodeRange((parser_range.start - start_pos)..(parser_range.end - start_pos)) + } +} /// Controls how we capture tokens. Capturing can be expensive, /// so we try to avoid performing capturing in cases where @@ -225,8 +256,8 @@ enum Capturing { #[derive(Clone, Debug)] struct CaptureState { capturing: Capturing, - replace_ranges: Vec, - inner_attr_ranges: FxHashMap>, + parser_replacements: Vec, + inner_attr_parser_ranges: FxHashMap, } /// Iterator over a `TokenStream` that produces `Token`s. It's a bit odd that @@ -416,8 +447,8 @@ impl<'a> Parser<'a> { subparser_name, capture_state: CaptureState { capturing: Capturing::No, - replace_ranges: Vec::new(), - inner_attr_ranges: Default::default(), + parser_replacements: Vec::new(), + inner_attr_parser_ranges: Default::default(), }, current_closure: None, recovery: Recovery::Allowed, @@ -546,6 +577,7 @@ impl<'a> Parser<'a> { } #[inline] + #[must_use] fn check_noexpect(&self, tok: &TokenKind) -> bool { self.token == *tok } @@ -555,6 +587,7 @@ impl<'a> Parser<'a> { /// the main purpose of this function is to reduce the cluttering of the suggestions list /// which using the normal eat method could introduce in some cases. #[inline] + #[must_use] fn eat_noexpect(&mut self, tok: &TokenKind) -> bool { let is_present = self.check_noexpect(tok); if is_present { @@ -565,6 +598,7 @@ impl<'a> Parser<'a> { /// Consumes a token 'tok' if it exists. Returns whether the given token was present. #[inline] + #[must_use] pub fn eat(&mut self, tok: &TokenKind) -> bool { let is_present = self.check(tok); if is_present { @@ -576,12 +610,14 @@ impl<'a> Parser<'a> { /// If the next token is the given keyword, returns `true` without eating it. /// An expectation is also added for diagnostics purposes. #[inline] + #[must_use] fn check_keyword(&mut self, kw: Symbol) -> bool { self.expected_tokens.push(TokenType::Keyword(kw)); self.token.is_keyword(kw) } #[inline] + #[must_use] fn check_keyword_case(&mut self, kw: Symbol, case: Case) -> bool { if self.check_keyword(kw) { return true; @@ -599,8 +635,9 @@ impl<'a> Parser<'a> { /// If the next token is the given keyword, eats it and returns `true`. /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. - // Public for rustfmt usage. + // Public for rustc_builtin_macros and rustfmt usage. #[inline] + #[must_use] pub fn eat_keyword(&mut self, kw: Symbol) -> bool { if self.check_keyword(kw) { self.bump(); @@ -614,6 +651,7 @@ impl<'a> Parser<'a> { /// If the case differs (and is ignored) an error is issued. /// This is useful for recovery. #[inline] + #[must_use] fn eat_keyword_case(&mut self, kw: Symbol, case: Case) -> bool { if self.eat_keyword(kw) { return true; @@ -631,8 +669,12 @@ impl<'a> Parser<'a> { false } + /// If the next token is the given keyword, eats it and returns `true`. + /// Otherwise, returns `false`. No expectation is added. + // Public for rustc_builtin_macros usage. #[inline] - fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { + #[must_use] + pub fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { if self.token.is_keyword(kw) { self.bump(); true @@ -644,7 +686,7 @@ impl<'a> Parser<'a> { /// If the given word is not a keyword, signals an error. /// If the next token is not the given word, signals an error. /// Otherwise, eats it. - fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { + pub fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } } @@ -1021,8 +1063,11 @@ impl<'a> Parser<'a> { f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, ) -> PResult<'a, (ThinVec, Trailing)> { let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; - if matches!(recovered, Recovered::No) { - self.eat(ket); + if matches!(recovered, Recovered::No) && !self.eat(ket) { + self.dcx().span_delayed_bug( + self.token.span, + "recovered but `parse_seq_to_before_end` did not give us the ket token", + ); } Ok((val, trailing)) } @@ -1205,9 +1250,6 @@ impl<'a> Parser<'a> { if self.eat_keyword_case(kw::Unsafe, case) { Safety::Unsafe(self.prev_token.uninterpolated_span()) } else if self.eat_keyword_case(kw::Safe, case) { - self.psess - .gated_spans - .gate(sym::unsafe_extern_blocks, self.prev_token.uninterpolated_span()); Safety::Safe(self.prev_token.uninterpolated_span()) } else { Safety::Default @@ -1246,7 +1288,7 @@ impl<'a> Parser<'a> { if pat { self.psess.gated_spans.gate(sym::inline_const_pat, span); } - self.eat_keyword(kw::Const); + self.expect_keyword(kw::Const)?; let (attrs, blk) = self.parse_inner_attrs_and_block()?; let anon_const = AnonConst { id: DUMMY_NODE_ID, diff --git a/compiler/rustc_parse/src/parser/mut_visit/tests.rs b/compiler/rustc_parse/src/parser/mut_visit/tests.rs index 677bcdf7fcdf4..b82c295732de9 100644 --- a/compiler/rustc_parse/src/parser/mut_visit/tests.rs +++ b/compiler/rustc_parse/src/parser/mut_visit/tests.rs @@ -1,10 +1,11 @@ -use crate::parser::tests::{matches_codepattern, string_to_crate}; use rustc_ast as ast; use rustc_ast::mut_visit::MutVisitor; use rustc_ast_pretty::pprust; use rustc_span::create_default_session_globals_then; use rustc_span::symbol::Ident; +use crate::parser::tests::{matches_codepattern, string_to_crate}; + // This version doesn't care about getting comments or doc-strings in. fn print_crate_items(krate: &ast::Crate) -> String { krate.items.iter().map(|i| pprust::item_to_string(i)).collect::>().join(" ") diff --git a/compiler/rustc_parse/src/parser/nonterminal.rs b/compiler/rustc_parse/src/parser/nonterminal.rs index 886d6af173535..999f6f0eeb0ce 100644 --- a/compiler/rustc_parse/src/parser/nonterminal.rs +++ b/compiler/rustc_parse/src/parser/nonterminal.rs @@ -1,7 +1,8 @@ use rustc_ast::ptr::P; -use rustc_ast::token::{ - self, Delimiter, Nonterminal::*, NonterminalKind, NtExprKind::*, NtPatKind::*, Token, -}; +use rustc_ast::token::Nonterminal::*; +use rustc_ast::token::NtExprKind::*; +use rustc_ast::token::NtPatKind::*; +use rustc_ast::token::{self, Delimiter, NonterminalKind, Token}; use rustc_ast::HasTokens; use rustc_ast_pretty::pprust; use rustc_data_structures::sync::Lrc; @@ -38,6 +39,7 @@ impl<'a> Parser<'a> { } match kind { + // `expr_2021` and earlier NonterminalKind::Expr(Expr2021 { .. }) => { token.can_begin_expr() // This exception is here for backwards compatibility. @@ -45,8 +47,16 @@ impl<'a> Parser<'a> { // This exception is here for backwards compatibility. && !token.is_keyword(kw::Const) } + // Current edition expressions NonterminalKind::Expr(Expr) => { - token.can_begin_expr() + // In Edition 2024, `_` is considered an expression, so we + // need to allow it here because `token.can_begin_expr()` does + // not consider `_` to be an expression. + // + // Because `can_begin_expr` is used elsewhere, we need to reduce + // the scope of where the `_` is considered an expression to + // just macro parsing code. + (token.can_begin_expr() || token.is_keyword(kw::Underscore)) // This exception is here for backwards compatibility. && !token.is_keyword(kw::Let) } diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index aa818878cd812..5bfb8bdf776a0 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -1,17 +1,3 @@ -use super::{ForceCollect, Parser, PathStyle, Restrictions, Trailing}; -use crate::errors::{ - self, AmbiguousRangePattern, DotDotDotForRemainingFields, DotDotDotRangeToPatternNotAllowed, - DotDotDotRestPattern, EnumPatternInsteadOfIdentifier, ExpectedBindingLeftOfAt, - ExpectedCommaAfterPatternField, GenericArgsInPatRequireTurbofishSyntax, - InclusiveRangeExtraEquals, InclusiveRangeMatchArrow, InclusiveRangeNoEnd, InvalidMutInPattern, - ParenRangeSuggestion, PatternOnWrongSideOfAt, RemoveLet, RepeatedMutInPattern, - SwitchRefBoxOrder, TopLevelOrPatternNotAllowed, TopLevelOrPatternNotAllowedSugg, - TrailingVertNotAllowed, UnexpectedExpressionInPattern, UnexpectedLifetimeInPattern, - UnexpectedParenInRangePat, UnexpectedParenInRangePatSugg, - UnexpectedVertVertBeforeFunctionParam, UnexpectedVertVertInPattern, WrapInParens, -}; -use crate::parser::expr::{could_be_unclosed_char_literal, LhsExpr}; -use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole}; use rustc_ast::mut_visit::{walk_pat, MutVisitor}; use rustc_ast::ptr::P; use rustc_ast::token::{self, BinOpToken, Delimiter, Token}; @@ -27,6 +13,21 @@ use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{BytePos, ErrorGuaranteed, Span}; use thin_vec::{thin_vec, ThinVec}; +use super::{ForceCollect, Parser, PathStyle, Restrictions, Trailing}; +use crate::errors::{ + self, AmbiguousRangePattern, DotDotDotForRemainingFields, DotDotDotRangeToPatternNotAllowed, + DotDotDotRestPattern, EnumPatternInsteadOfIdentifier, ExpectedBindingLeftOfAt, + ExpectedCommaAfterPatternField, GenericArgsInPatRequireTurbofishSyntax, + InclusiveRangeExtraEquals, InclusiveRangeMatchArrow, InclusiveRangeNoEnd, InvalidMutInPattern, + ParenRangeSuggestion, PatternOnWrongSideOfAt, RemoveLet, RepeatedMutInPattern, + SwitchRefBoxOrder, TopLevelOrPatternNotAllowed, TopLevelOrPatternNotAllowedSugg, + TrailingVertNotAllowed, UnexpectedExpressionInPattern, UnexpectedLifetimeInPattern, + UnexpectedParenInRangePat, UnexpectedParenInRangePatSugg, + UnexpectedVertVertBeforeFunctionParam, UnexpectedVertVertInPattern, WrapInParens, +}; +use crate::parser::expr::could_be_unclosed_char_literal; +use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole}; + #[derive(PartialEq, Copy, Clone)] pub enum Expected { ParameterName, @@ -402,8 +403,9 @@ impl<'a> Parser<'a> { // Parse an associative expression such as `+ expr`, `% expr`, ... // Assignements, ranges and `|` are disabled by [`Restrictions::IS_PAT`]. - let lhs = LhsExpr::Parsed { expr, starts_statement: false }; - if let Ok(expr) = snapshot.parse_expr_assoc_with(0, lhs).map_err(|err| err.cancel()) { + if let Ok(expr) = + snapshot.parse_expr_assoc_rest_with(0, false, expr).map_err(|err| err.cancel()) + { // We got a valid expression. self.restore_snapshot(snapshot); self.restrictions.remove(Restrictions::IS_PAT); diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index b9014dea72666..70d2c98d4f1bd 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -1,8 +1,5 @@ -use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign}; -use super::{Parser, Restrictions, TokenType}; -use crate::errors::PathSingleColon; -use crate::parser::{CommaRecoveryMode, RecoverColon, RecoverComma}; -use crate::{errors, maybe_whole}; +use std::mem; + use ast::token::IdentIsRaw; use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter, Token, TokenKind}; @@ -14,10 +11,15 @@ use rustc_ast::{ use rustc_errors::{Applicability, Diag, PResult}; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{BytePos, Span}; -use std::mem; use thin_vec::ThinVec; use tracing::debug; +use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign}; +use super::{Parser, Restrictions, TokenType}; +use crate::errors::PathSingleColon; +use crate::parser::{CommaRecoveryMode, RecoverColon, RecoverComma}; +use crate::{errors, maybe_whole}; + /// Specifies how to parse a path. #[derive(Copy, Clone, PartialEq)] pub(super) enum PathStyle { @@ -311,7 +313,8 @@ impl<'a> Parser<'a> { } // Generic arguments are found - `<`, `(`, `::<` or `::(`. - self.eat(&token::PathSep); + // First, eat `::` if it exists. + let _ = self.eat(&token::PathSep); let lo = self.token.span; let args = if self.eat_lt() { // `<'a, T, A = U>` diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index d8de7c1bfa1c5..b3efb87a4a26a 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -1,31 +1,30 @@ -use super::attr::InnerAttrForbiddenReason; -use super::diagnostics::AttemptLocalParseRecovery; -use super::expr::LhsExpr; -use super::pat::{PatternLocation, RecoverComma}; -use super::path::PathStyle; -use super::{ - AttrWrapper, BlockMode, FnParseMode, ForceCollect, Parser, Restrictions, SemiColonMode, -}; -use crate::errors; -use crate::maybe_whole; +use std::borrow::Cow; +use std::mem; -use crate::errors::MalformedLoopLabel; use ast::Label; use rustc_ast as ast; use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter, TokenKind}; use rustc_ast::util::classify::{self, TrailingBrace}; -use rustc_ast::{AttrStyle, AttrVec, LocalKind, MacCall, MacCallStmt, MacStmtStyle}; -use rustc_ast::{Block, BlockCheckMode, Expr, ExprKind, HasAttrs, Local, Recovered, Stmt}; -use rustc_ast::{StmtKind, DUMMY_NODE_ID}; +use rustc_ast::{ + AttrStyle, AttrVec, Block, BlockCheckMode, Expr, ExprKind, HasAttrs, Local, LocalKind, MacCall, + MacCallStmt, MacStmtStyle, Recovered, Stmt, StmtKind, DUMMY_NODE_ID, +}; use rustc_errors::{Applicability, Diag, PResult}; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{BytePos, ErrorGuaranteed, Span}; - -use std::borrow::Cow; -use std::mem; use thin_vec::{thin_vec, ThinVec}; +use super::attr::InnerAttrForbiddenReason; +use super::diagnostics::AttemptLocalParseRecovery; +use super::pat::{PatternLocation, RecoverComma}; +use super::path::PathStyle; +use super::{ + AttrWrapper, BlockMode, FnParseMode, ForceCollect, Parser, Restrictions, SemiColonMode, +}; +use crate::errors::MalformedLoopLabel; +use crate::{errors, maybe_whole}; + impl<'a> Parser<'a> { /// Parses a statement. This stops just before trailing semicolons on everything but items. /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed. @@ -66,7 +65,12 @@ impl<'a> Parser<'a> { } Ok(Some(if self.token.is_keyword(kw::Let) { - self.parse_local_mk(lo, attrs, capture_semi, force_collect)? + self.collect_tokens_trailing_token(attrs, force_collect, |this, attrs| { + this.expect_keyword(kw::Let)?; + let local = this.parse_local(attrs)?; + let trailing = capture_semi && this.token.kind == token::Semi; + Ok((this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Let(local)), trailing)) + })? } else if self.is_kw_followed_by_ident(kw::Mut) && self.may_recover() { self.recover_stmt_local_after_let( lo, @@ -112,13 +116,12 @@ impl<'a> Parser<'a> { } } } else if let Some(item) = self.parse_item_common( - attrs.clone(), + attrs.clone(), // FIXME: unwanted clone of attrs false, true, FnParseMode { req_name: |_| true, req_body: true }, force_collect, )? { - // FIXME: Bad copy of attrs self.mk_stmt(lo.to(item.span), StmtKind::Item(P(item))) } else if self.eat(&token::Semi) { // Do not attempt to parse an expression if we're done here. @@ -173,7 +176,7 @@ impl<'a> Parser<'a> { // Perform this outside of the `collect_tokens_trailing_token` closure, // since our outer attributes do not apply to this part of the expression let expr = self.with_res(Restrictions::STMT_EXPR, |this| { - this.parse_expr_assoc_with(0, LhsExpr::Parsed { expr, starts_statement: true }) + this.parse_expr_assoc_rest_with(0, true, expr) })?; Ok(self.mk_stmt(lo.to(self.prev_token.span), StmtKind::Expr(expr))) } else { @@ -206,8 +209,7 @@ impl<'a> Parser<'a> { let e = self.mk_expr(lo.to(hi), ExprKind::MacCall(mac)); let e = self.maybe_recover_from_bad_qpath(e)?; let e = self.parse_expr_dot_or_call_with(attrs, e, lo)?; - let e = self - .parse_expr_assoc_with(0, LhsExpr::Parsed { expr: e, starts_statement: false })?; + let e = self.parse_expr_assoc_rest_with(0, false, e)?; StmtKind::Expr(e) }; Ok(self.mk_stmt(lo.to(hi), kind)) @@ -247,21 +249,6 @@ impl<'a> Parser<'a> { Ok(stmt) } - fn parse_local_mk( - &mut self, - lo: Span, - attrs: AttrWrapper, - capture_semi: bool, - force_collect: ForceCollect, - ) -> PResult<'a, Stmt> { - self.collect_tokens_trailing_token(attrs, force_collect, |this, attrs| { - this.expect_keyword(kw::Let)?; - let local = this.parse_local(attrs)?; - let trailing = capture_semi && this.token.kind == token::Semi; - Ok((this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Let(local)), trailing)) - }) - } - /// Parses a local variable declaration. fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P> { let lo = self.prev_token.span; diff --git a/compiler/rustc_parse/src/parser/tests.rs b/compiler/rustc_parse/src/parser/tests.rs index 491aa71155af2..2d82742f66c02 100644 --- a/compiler/rustc_parse/src/parser/tests.rs +++ b/compiler/rustc_parse/src/parser/tests.rs @@ -1,30 +1,27 @@ -use crate::parser::ForceCollect; -use crate::{ - new_parser_from_source_str, parser::Parser, source_str_to_stream, unwrap_or_emit_fatal, -}; +use std::io::prelude::*; +use std::iter::Peekable; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::{io, str}; + use ast::token::IdentIsRaw; use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter, Token}; use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; -use rustc_ast::visit; -use rustc_ast::{self as ast, PatKind}; +use rustc_ast::{self as ast, visit, PatKind}; use rustc_ast_pretty::pprust::item_to_string; use rustc_data_structures::sync::Lrc; use rustc_errors::emitter::HumanEmitter; use rustc_errors::{DiagCtxt, MultiSpan, PResult}; use rustc_session::parse::ParseSess; -use rustc_span::create_default_session_globals_then; use rustc_span::source_map::{FilePathMapping, SourceMap}; use rustc_span::symbol::{kw, sym, Symbol}; -use rustc_span::{BytePos, FileName, Pos, Span}; -use std::io; -use std::io::prelude::*; -use std::iter::Peekable; -use std::path::{Path, PathBuf}; -use std::str; -use std::sync::{Arc, Mutex}; +use rustc_span::{create_default_session_globals_then, BytePos, FileName, Pos, Span}; use termcolor::WriteColor; +use crate::parser::{ForceCollect, Parser}; +use crate::{new_parser_from_source_str, source_str_to_stream, unwrap_or_emit_fatal}; + fn psess() -> ParseSess { ParseSess::new(vec![crate::DEFAULT_LOCALE_RESOURCE, crate::DEFAULT_LOCALE_RESOURCE]) } diff --git a/compiler/rustc_parse/src/parser/tokenstream/tests.rs b/compiler/rustc_parse/src/parser/tokenstream/tests.rs index 9be00a1479153..d518dfee2b26e 100644 --- a/compiler/rustc_parse/src/parser/tokenstream/tests.rs +++ b/compiler/rustc_parse/src/parser/tokenstream/tests.rs @@ -1,8 +1,8 @@ -use crate::parser::tests::string_to_stream; use rustc_ast::token::{self, IdentIsRaw}; use rustc_ast::tokenstream::{TokenStream, TokenTree}; -use rustc_span::create_default_session_globals_then; -use rustc_span::{BytePos, Span, Symbol}; +use rustc_span::{create_default_session_globals_then, BytePos, Span, Symbol}; + +use crate::parser::tests::string_to_stream; fn string_to_ts(string: &str) -> TokenStream { string_to_stream(string.to_owned()) diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index a8134110010d3..352ddd9eac4a5 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -1,13 +1,3 @@ -use super::{Parser, PathStyle, SeqSep, TokenType, Trailing}; - -use crate::errors::{ - self, DynAfterMut, ExpectedFnPathFoundFnKeyword, ExpectedMutOrConstInRawPointerType, - FnPointerCannotBeAsync, FnPointerCannotBeConst, FnPtrWithGenerics, FnPtrWithGenericsSugg, - HelpUseLatestEdition, InvalidDynKeyword, LifetimeAfterMut, NeedPlusAfterTraitObjectLifetime, - NestedCVariadicType, ReturnTypesUseThinArrow, -}; -use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole}; - use rustc_ast::ptr::P; use rustc_ast::token::{self, BinOpToken, Delimiter, Token, TokenKind}; use rustc_ast::util::case::Case; @@ -21,6 +11,15 @@ use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{ErrorGuaranteed, Span, Symbol}; use thin_vec::{thin_vec, ThinVec}; +use super::{Parser, PathStyle, SeqSep, TokenType, Trailing}; +use crate::errors::{ + self, DynAfterMut, ExpectedFnPathFoundFnKeyword, ExpectedMutOrConstInRawPointerType, + FnPointerCannotBeAsync, FnPointerCannotBeConst, FnPtrWithGenerics, FnPtrWithGenericsSugg, + HelpUseLatestEdition, InvalidDynKeyword, LifetimeAfterMut, NeedPlusAfterTraitObjectLifetime, + NestedCVariadicType, ReturnTypesUseThinArrow, +}; +use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole}; + /// Signals whether parsing a type should allow `+`. /// /// For example, let T be the type `impl Default + 'static` @@ -935,9 +934,14 @@ impl<'a> Parser<'a> { /// If no modifiers are present, this does not consume any tokens. /// /// ```ebnf - /// TRAIT_BOUND_MODIFIERS = [["~"] "const"] ["async"] ["?" | "!"] + /// CONSTNESS = [["~"] "const"] + /// ASYNCNESS = ["async"] + /// POLARITY = ["?" | "!"] /// ``` + /// + /// See `parse_generic_ty_bound` for the complete grammar of trait bound modifiers. fn parse_trait_bound_modifiers(&mut self) -> PResult<'a, TraitBoundModifiers> { + let modifier_lo = self.token.span; let constness = if self.eat(&token::Tilde) { let tilde = self.prev_token.span; self.expect_keyword(kw::Const)?; @@ -970,6 +974,7 @@ impl<'a> Parser<'a> { } else { BoundAsyncness::Normal }; + let modifier_hi = self.prev_token.span; let polarity = if self.eat(&token::Question) { BoundPolarity::Maybe(self.prev_token.span) @@ -980,13 +985,40 @@ impl<'a> Parser<'a> { BoundPolarity::Positive }; + // Enforce the mutual-exclusivity of `const`/`async` and `?`/`!`. + match polarity { + BoundPolarity::Positive => { + // All trait bound modifiers allowed to combine with positive polarity + } + BoundPolarity::Maybe(polarity_span) | BoundPolarity::Negative(polarity_span) => { + match (asyncness, constness) { + (BoundAsyncness::Normal, BoundConstness::Never) => { + // Ok, no modifiers. + } + (_, _) => { + let constness = constness.as_str(); + let asyncness = asyncness.as_str(); + let glue = + if !constness.is_empty() && !asyncness.is_empty() { " " } else { "" }; + let modifiers_concatenated = format!("{constness}{glue}{asyncness}"); + self.dcx().emit_err(errors::PolarityAndModifiers { + polarity_span, + polarity: polarity.as_str(), + modifiers_span: modifier_lo.to(modifier_hi), + modifiers_concatenated, + }); + } + } + } + } + Ok(TraitBoundModifiers { constness, asyncness, polarity }) } /// Parses a type bound according to: /// ```ebnf /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN) - /// TY_BOUND_NOPAREN = [TRAIT_BOUND_MODIFIERS] [for] SIMPLE_PATH + /// TY_BOUND_NOPAREN = [for CONSTNESS ASYNCNESS | POLARITY] SIMPLE_PATH /// ``` /// /// For example, this grammar accepts `for<'a: 'b> ~const ?m::Trait<'a>`. @@ -996,9 +1028,25 @@ impl<'a> Parser<'a> { has_parens: bool, leading_token: &Token, ) -> PResult<'a, GenericBound> { - let modifiers = self.parse_trait_bound_modifiers()?; let (mut lifetime_defs, binder_span) = self.parse_late_bound_lifetime_defs()?; + let modifiers_lo = self.token.span; + let modifiers = self.parse_trait_bound_modifiers()?; + let modifiers_span = modifiers_lo.to(self.prev_token.span); + + if let Some(binder_span) = binder_span { + match modifiers.polarity { + BoundPolarity::Negative(polarity_span) | BoundPolarity::Maybe(polarity_span) => { + self.dcx().emit_err(errors::BinderAndPolarity { + binder_span, + polarity_span, + polarity: modifiers.polarity.as_str(), + }); + } + BoundPolarity::Positive => {} + } + } + // Recover erroneous lifetime bound with modifiers or binder. // e.g. `T: for<'a> 'a` or `T: ~const 'a`. if self.token.is_lifetime() { @@ -1006,6 +1054,11 @@ impl<'a> Parser<'a> { return self.parse_generic_lt_bound(lo, has_parens); } + if let (more_lifetime_defs, Some(binder_span)) = self.parse_late_bound_lifetime_defs()? { + lifetime_defs.extend(more_lifetime_defs); + self.dcx().emit_err(errors::BinderBeforeModifiers { binder_span, modifiers_span }); + } + let mut path = if self.token.is_keyword(kw::Fn) && self.look_ahead(1, |tok| tok.kind == TokenKind::OpenDelim(Delimiter::Parenthesis)) && let Some(path) = self.recover_path_from_fn() diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs index 3d5e6371f4ce6..a64c00f3b6cbc 100644 --- a/compiler/rustc_parse/src/validate_attr.rs +++ b/compiler/rustc_parse/src/validate_attr.rs @@ -1,7 +1,5 @@ //! Meta-syntax validation logic of attributes for post-expansion. -use crate::{errors, parse_in}; - use rustc_ast::token::Delimiter; use rustc_ast::tokenstream::DelimSpan; use rustc_ast::{ @@ -18,6 +16,8 @@ use rustc_session::lint::BuiltinLintDiag; use rustc_session::parse::ParseSess; use rustc_span::{sym, BytePos, Span, Symbol}; +use crate::{errors, parse_in}; + pub fn check_attr(features: &Features, psess: &ParseSess, attr: &Attribute) { if attr.is_doc_comment() { return; @@ -26,76 +26,35 @@ pub fn check_attr(features: &Features, psess: &ParseSess, attr: &Attribute) { let attr_info = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)); let attr_item = attr.get_normal_item(); - let is_unsafe_attr = attr_info.is_some_and(|attr| attr.safety == AttributeSafety::Unsafe); - - if features.unsafe_attributes { - if is_unsafe_attr { - if let ast::Safety::Default = attr_item.unsafety { - let path_span = attr_item.path.span; - - // If the `attr_item`'s span is not from a macro, then just suggest - // wrapping it in `unsafe(...)`. Otherwise, we suggest putting the - // `unsafe(`, `)` right after and right before the opening and closing - // square bracket respectively. - let diag_span = if attr_item.span().can_be_used_for_suggestions() { - attr_item.span() - } else { - attr.span - .with_lo(attr.span.lo() + BytePos(2)) - .with_hi(attr.span.hi() - BytePos(1)) - }; - - if attr.span.at_least_rust_2024() { - psess.dcx().emit_err(errors::UnsafeAttrOutsideUnsafe { - span: path_span, - suggestion: errors::UnsafeAttrOutsideUnsafeSuggestion { - left: diag_span.shrink_to_lo(), - right: diag_span.shrink_to_hi(), - }, - }); - } else { - psess.buffer_lint( - UNSAFE_ATTR_OUTSIDE_UNSAFE, - path_span, - ast::CRATE_NODE_ID, - BuiltinLintDiag::UnsafeAttrOutsideUnsafe { - attribute_name_span: path_span, - sugg_spans: (diag_span.shrink_to_lo(), diag_span.shrink_to_hi()), - }, - ); - } - } - } else { - if let Safety::Unsafe(unsafe_span) = attr_item.unsafety { - psess.dcx().emit_err(errors::InvalidAttrUnsafe { - span: unsafe_span, - name: attr_item.path.clone(), - }); - } - } - } + // All non-builtin attributes are considered safe + let safety = attr_info.map(|x| x.safety).unwrap_or(AttributeSafety::Normal); + check_attribute_safety(features, psess, safety, attr); // Check input tokens for built-in and key-value attributes. match attr_info { // `rustc_dummy` doesn't have any restrictions specific to built-in attributes. Some(BuiltinAttribute { name, template, .. }) if *name != sym::rustc_dummy => { match parse_meta(psess, attr) { - Ok(meta) => check_builtin_meta_item(psess, &meta, attr.style, *name, *template), + // Don't check safety again, we just did that + Ok(meta) => check_builtin_meta_item( + features, psess, &meta, attr.style, *name, *template, false, + ), Err(err) => { err.emit(); } } } - _ if let AttrArgs::Eq(..) = attr_item.args => { - // All key-value attributes are restricted to meta-item syntax. - match parse_meta(psess, attr) { - Ok(_) => {} - Err(err) => { - err.emit(); + _ => { + if let AttrArgs::Eq(..) = attr_item.args { + // All key-value attributes are restricted to meta-item syntax. + match parse_meta(psess, attr) { + Ok(_) => {} + Err(err) => { + err.emit(); + } } } } - _ => {} } } @@ -198,12 +157,85 @@ fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaIte } } +pub fn check_attribute_safety( + features: &Features, + psess: &ParseSess, + safety: AttributeSafety, + attr: &Attribute, +) { + if !features.unsafe_attributes { + return; + } + + let attr_item = attr.get_normal_item(); + + if safety == AttributeSafety::Unsafe { + if let ast::Safety::Default = attr_item.unsafety { + let path_span = attr_item.path.span; + + // If the `attr_item`'s span is not from a macro, then just suggest + // wrapping it in `unsafe(...)`. Otherwise, we suggest putting the + // `unsafe(`, `)` right after and right before the opening and closing + // square bracket respectively. + let diag_span = if attr_item.span().can_be_used_for_suggestions() { + attr_item.span() + } else { + attr.span.with_lo(attr.span.lo() + BytePos(2)).with_hi(attr.span.hi() - BytePos(1)) + }; + + if attr.span.at_least_rust_2024() { + psess.dcx().emit_err(errors::UnsafeAttrOutsideUnsafe { + span: path_span, + suggestion: errors::UnsafeAttrOutsideUnsafeSuggestion { + left: diag_span.shrink_to_lo(), + right: diag_span.shrink_to_hi(), + }, + }); + } else { + psess.buffer_lint( + UNSAFE_ATTR_OUTSIDE_UNSAFE, + path_span, + ast::CRATE_NODE_ID, + BuiltinLintDiag::UnsafeAttrOutsideUnsafe { + attribute_name_span: path_span, + sugg_spans: (diag_span.shrink_to_lo(), diag_span.shrink_to_hi()), + }, + ); + } + } + } else { + if let Safety::Unsafe(unsafe_span) = attr_item.unsafety { + psess.dcx().emit_err(errors::InvalidAttrUnsafe { + span: unsafe_span, + name: attr_item.path.clone(), + }); + } + } +} + +// Called by `check_builtin_meta_item` and code that manually denies +// `unsafe(...)` in `cfg` +pub fn deny_builtin_meta_unsafety(features: &Features, psess: &ParseSess, meta: &MetaItem) { + // This only supports denying unsafety right now - making builtin attributes + // support unsafety will requite us to thread the actual `Attribute` through + // for the nice diagnostics. + if features.unsafe_attributes { + if let Safety::Unsafe(unsafe_span) = meta.unsafety { + psess + .dcx() + .emit_err(errors::InvalidAttrUnsafe { span: unsafe_span, name: meta.path.clone() }); + } + } +} + pub fn check_builtin_meta_item( + features: &Features, psess: &ParseSess, meta: &MetaItem, style: ast::AttrStyle, name: Symbol, template: AttributeTemplate, + deny_unsafety: bool, ) { // Some special attributes like `cfg` must be checked // before the generic check, so we skip them here. @@ -212,6 +244,10 @@ pub fn check_builtin_meta_item( if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) { emit_malformed_attribute(psess, style, meta.span, name, template); } + + if deny_unsafety { + deny_builtin_meta_unsafety(features, psess, meta); + } } fn emit_malformed_attribute( diff --git a/compiler/rustc_parse_format/src/lib.rs b/compiler/rustc_parse_format/src/lib.rs index 7e22644977d1a..cb758150789b0 100644 --- a/compiler/rustc_parse_format/src/lib.rs +++ b/compiler/rustc_parse_format/src/lib.rs @@ -15,16 +15,14 @@ )] // tidy-alphabetical-end +use std::{iter, str, string}; + use rustc_lexer::unescape; pub use Alignment::*; pub use Count::*; pub use Piece::*; pub use Position::*; -use std::iter; -use std::str; -use std::string; - // Note: copied from rustc_span /// Range inside of a `Span` used for diagnostics when we only have access to relative positions. #[derive(Copy, Clone, PartialEq, Eq, Debug)] diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index 1d93cbaddd6fe..59c9d1e49f5b3 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -69,9 +69,6 @@ passes_break_non_loop = .suggestion = use `break` on its own without a value inside this `{$kind}` loop .break_expr_suggestion = alternatively, you might have meant to use the available loop label -passes_cannot_inline_naked_function = - naked functions cannot be inlined - passes_cannot_stabilize_deprecated = an API can't be stabilized after it is deprecated .label = invalid version @@ -103,6 +100,10 @@ passes_continue_labeled_block = .label = labeled blocks cannot be `continue`'d .block_label = labeled block the `continue` points to +passes_coroutine_on_non_closure = + attribute should be applied to closures + .label = not a closure + passes_coverage_not_fn_or_closure = attribute should be applied to a function definition or closure .label = not a function or closure @@ -485,6 +486,11 @@ passes_naked_functions_asm_block = passes_naked_functions_asm_options = asm options unsupported in naked functions: {$unsupported_options} +passes_naked_functions_incompatible_attribute = + attribute incompatible with `#[naked]` + .label = the `{$attr}` attribute is incompatible with `#[naked]` + .naked_attribute = function marked with `#[naked]` here + passes_naked_functions_must_use_noreturn = asm in naked functions must use `noreturn` option .suggestion = consider specifying that the asm block is responsible for returning from the function @@ -492,9 +498,6 @@ passes_naked_functions_must_use_noreturn = passes_naked_functions_operands = only `const` and `sym` operands are supported in naked functions -passes_naked_tracked_caller = - cannot use `#[track_caller]` with `#[naked]` - passes_no_link = attribute should be applied to an `extern crate` item .label = not an `extern crate` item @@ -543,6 +546,10 @@ passes_only_has_effect_on = *[unspecified] (unspecified--this is a compiler bug) } +passes_optimize_not_fn_or_closure = + attribute should be applied to function or closure + .label = not a function or closure + passes_outer_crate_level_attr = crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 9cbd989cc0e9f..a0d0d80b9572e 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -4,28 +4,29 @@ //! conflicts between multiple such attributes attached to the same //! item. -use crate::{errors, fluent_generated as fluent}; -use rustc_ast::{ast, AttrKind, AttrStyle, Attribute, LitKind}; -use rustc_ast::{MetaItemKind, MetaItemLit, NestedMetaItem}; +use std::cell::Cell; +use std::collections::hash_map::Entry; + +use rustc_ast::{ + ast, AttrKind, AttrStyle, Attribute, LitKind, MetaItemKind, MetaItemLit, NestedMetaItem, +}; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::{Applicability, IntoDiagArg, MultiSpan}; -use rustc_errors::{DiagCtxtHandle, StashKey}; +use rustc_errors::{Applicability, DiagCtxtHandle, IntoDiagArg, MultiSpan, StashKey}; use rustc_feature::{AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP}; use rustc_hir::def_id::LocalModDefId; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{self as hir}; use rustc_hir::{ - self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID, + self as hir, self, FnSig, ForeignItem, HirId, Item, ItemKind, MethodKind, Safety, Target, + TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID, }; -use rustc_hir::{MethodKind, Safety, Target}; use rustc_macros::LintDiagnostic; -use rustc_middle::bug; use rustc_middle::hir::nested_filter; use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault; use rustc_middle::query::Providers; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::{bug, span_bug}; use rustc_session::lint::builtin::{ CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, INVALID_MACRO_EXPORT_ARGUMENTS, UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES, @@ -37,10 +38,10 @@ use rustc_target::spec::abi::Abi; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::{TyCtxtInferExt, ValuePairs}; use rustc_trait_selection::traits::ObligationCtxt; -use std::cell::Cell; -use std::collections::hash_map::Entry; use tracing::debug; +use crate::{errors, fluent_generated as fluent}; + #[derive(LintDiagnostic)] #[diag(passes_diagnostic_diagnostic_on_unimplemented_only_for_traits)] struct DiagnosticOnUnimplementedOnlyForTraits; @@ -115,132 +116,184 @@ impl<'tcx> CheckAttrVisitor<'tcx> { let attrs = self.tcx.hir().attrs(hir_id); for attr in attrs { match attr.path().as_slice() { - [sym::diagnostic, sym::do_not_recommend] => { + [sym::diagnostic, sym::do_not_recommend, ..] => { self.check_do_not_recommend(attr.span, hir_id, target) } - [sym::diagnostic, sym::on_unimplemented] => { + [sym::diagnostic, sym::on_unimplemented, ..] => { self.check_diagnostic_on_unimplemented(attr.span, hir_id, target) } - [sym::inline] => self.check_inline(hir_id, attr, span, target), - [sym::coverage] => self.check_coverage(attr, span, target), - [sym::non_exhaustive] => self.check_non_exhaustive(hir_id, attr, span, target), - [sym::marker] => self.check_marker(hir_id, attr, span, target), - [sym::target_feature] => { + [sym::inline, ..] => self.check_inline(hir_id, attr, span, target), + [sym::coverage, ..] => self.check_coverage(attr, span, target), + [sym::optimize, ..] => self.check_optimize(hir_id, attr, target), + [sym::non_exhaustive, ..] => self.check_non_exhaustive(hir_id, attr, span, target), + [sym::marker, ..] => self.check_marker(hir_id, attr, span, target), + [sym::target_feature, ..] => { self.check_target_feature(hir_id, attr, span, target, attrs) } - [sym::thread_local] => self.check_thread_local(attr, span, target), - [sym::track_caller] => { + [sym::thread_local, ..] => self.check_thread_local(attr, span, target), + [sym::track_caller, ..] => { self.check_track_caller(hir_id, attr.span, attrs, span, target) } - [sym::doc] => self.check_doc_attrs( + [sym::doc, ..] => self.check_doc_attrs( attr, hir_id, target, &mut specified_inline, &mut doc_aliases, ), - [sym::no_link] => self.check_no_link(hir_id, attr, span, target), - [sym::export_name] => self.check_export_name(hir_id, attr, span, target), - [sym::rustc_layout_scalar_valid_range_start] - | [sym::rustc_layout_scalar_valid_range_end] => { + [sym::no_link, ..] => self.check_no_link(hir_id, attr, span, target), + [sym::export_name, ..] => self.check_export_name(hir_id, attr, span, target), + [sym::rustc_layout_scalar_valid_range_start, ..] + | [sym::rustc_layout_scalar_valid_range_end, ..] => { self.check_rustc_layout_scalar_valid_range(attr, span, target) } - [sym::allow_internal_unstable] => { + [sym::allow_internal_unstable, ..] => { self.check_allow_internal_unstable(hir_id, attr, span, target, attrs) } - [sym::debugger_visualizer] => self.check_debugger_visualizer(attr, target), - [sym::rustc_allow_const_fn_unstable] => { + [sym::debugger_visualizer, ..] => self.check_debugger_visualizer(attr, target), + [sym::rustc_allow_const_fn_unstable, ..] => { self.check_rustc_allow_const_fn_unstable(hir_id, attr, span, target) } - [sym::rustc_std_internal_symbol] => { + [sym::rustc_std_internal_symbol, ..] => { self.check_rustc_std_internal_symbol(attr, span, target) } - [sym::naked] => self.check_naked(hir_id, attr, span, target), - [sym::rustc_never_returns_null_ptr] => { + [sym::naked, ..] => self.check_naked(hir_id, attr, span, target, attrs), + [sym::rustc_never_returns_null_ptr, ..] => { self.check_applied_to_fn_or_method(hir_id, attr, span, target) } - [sym::rustc_legacy_const_generics] => { + [sym::rustc_legacy_const_generics, ..] => { self.check_rustc_legacy_const_generics(hir_id, attr, span, target, item) } - [sym::rustc_lint_query_instability] => { + [sym::rustc_lint_query_instability, ..] => { self.check_rustc_lint_query_instability(hir_id, attr, span, target) } - [sym::rustc_lint_diagnostics] => { + [sym::rustc_lint_diagnostics, ..] => { self.check_rustc_lint_diagnostics(hir_id, attr, span, target) } - [sym::rustc_lint_opt_ty] => self.check_rustc_lint_opt_ty(attr, span, target), - [sym::rustc_lint_opt_deny_field_access] => { + [sym::rustc_lint_opt_ty, ..] => self.check_rustc_lint_opt_ty(attr, span, target), + [sym::rustc_lint_opt_deny_field_access, ..] => { self.check_rustc_lint_opt_deny_field_access(attr, span, target) } - [sym::rustc_clean] - | [sym::rustc_dirty] - | [sym::rustc_if_this_changed] - | [sym::rustc_then_this_would_need] => self.check_rustc_dirty_clean(attr), - [sym::rustc_coinductive] - | [sym::rustc_must_implement_one_of] - | [sym::rustc_deny_explicit_impl] - | [sym::const_trait] => self.check_must_be_applied_to_trait(attr, span, target), - [sym::cmse_nonsecure_entry] => { + [sym::rustc_clean, ..] + | [sym::rustc_dirty, ..] + | [sym::rustc_if_this_changed, ..] + | [sym::rustc_then_this_would_need, ..] => self.check_rustc_dirty_clean(attr), + [sym::rustc_coinductive, ..] + | [sym::rustc_must_implement_one_of, ..] + | [sym::rustc_deny_explicit_impl, ..] + | [sym::const_trait, ..] => self.check_must_be_applied_to_trait(attr, span, target), + [sym::cmse_nonsecure_entry, ..] => { self.check_cmse_nonsecure_entry(hir_id, attr, span, target) } - [sym::collapse_debuginfo] => self.check_collapse_debuginfo(attr, span, target), - [sym::must_not_suspend] => self.check_must_not_suspend(attr, span, target), - [sym::must_use] => self.check_must_use(hir_id, attr, target), - [sym::rustc_pass_by_value] => self.check_pass_by_value(attr, span, target), - [sym::rustc_allow_incoherent_impl] => { + [sym::collapse_debuginfo, ..] => self.check_collapse_debuginfo(attr, span, target), + [sym::must_not_suspend, ..] => self.check_must_not_suspend(attr, span, target), + [sym::must_use, ..] => self.check_must_use(hir_id, attr, target), + [sym::rustc_pass_by_value, ..] => self.check_pass_by_value(attr, span, target), + [sym::rustc_allow_incoherent_impl, ..] => { self.check_allow_incoherent_impl(attr, span, target) } - [sym::rustc_has_incoherent_inherent_impls] => { + [sym::rustc_has_incoherent_inherent_impls, ..] => { self.check_has_incoherent_inherent_impls(attr, span, target) } - [sym::ffi_pure] => self.check_ffi_pure(attr.span, attrs, target), - [sym::ffi_const] => self.check_ffi_const(attr.span, target), - [sym::rustc_const_unstable] - | [sym::rustc_const_stable] - | [sym::unstable] - | [sym::stable] - | [sym::rustc_allowed_through_unstable_modules] - | [sym::rustc_promotable] => self.check_stability_promotable(attr, target), - [sym::link_ordinal] => self.check_link_ordinal(attr, span, target), - [sym::rustc_confusables] => self.check_confusables(attr, target), - [sym::rustc_safe_intrinsic] => { + [sym::ffi_pure, ..] => self.check_ffi_pure(attr.span, attrs, target), + [sym::ffi_const, ..] => self.check_ffi_const(attr.span, target), + [sym::rustc_const_unstable, ..] + | [sym::rustc_const_stable, ..] + | [sym::unstable, ..] + | [sym::stable, ..] + | [sym::rustc_allowed_through_unstable_modules, ..] + | [sym::rustc_promotable, ..] => self.check_stability_promotable(attr, target), + [sym::link_ordinal, ..] => self.check_link_ordinal(attr, span, target), + [sym::rustc_confusables, ..] => self.check_confusables(attr, target), + [sym::rustc_safe_intrinsic, ..] => { self.check_rustc_safe_intrinsic(hir_id, attr, span, target) } - _ => true, - }; - - // lint-only checks - match attr.name_or_empty() { - sym::cold => self.check_cold(hir_id, attr, span, target), - sym::link => self.check_link(hir_id, attr, span, target), - sym::link_name => self.check_link_name(hir_id, attr, span, target), - sym::link_section => self.check_link_section(hir_id, attr, span, target), - sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target), - sym::deprecated => self.check_deprecated(hir_id, attr, span, target), - sym::macro_use | sym::macro_escape => self.check_macro_use(hir_id, attr, target), - sym::path => self.check_generic_attr(hir_id, attr, target, Target::Mod), - sym::macro_export => self.check_macro_export(hir_id, attr, target), - sym::ignore | sym::should_panic => { + [sym::cold, ..] => self.check_cold(hir_id, attr, span, target), + [sym::link, ..] => self.check_link(hir_id, attr, span, target), + [sym::link_name, ..] => self.check_link_name(hir_id, attr, span, target), + [sym::link_section, ..] => self.check_link_section(hir_id, attr, span, target), + [sym::no_mangle, ..] => self.check_no_mangle(hir_id, attr, span, target), + [sym::deprecated, ..] => self.check_deprecated(hir_id, attr, span, target), + [sym::macro_use, ..] | [sym::macro_escape, ..] => { + self.check_macro_use(hir_id, attr, target) + } + [sym::path, ..] => self.check_generic_attr(hir_id, attr, target, Target::Mod), + [sym::macro_export, ..] => self.check_macro_export(hir_id, attr, target), + [sym::ignore, ..] | [sym::should_panic, ..] => { self.check_generic_attr(hir_id, attr, target, Target::Fn) } - sym::automatically_derived => { + [sym::automatically_derived, ..] => { self.check_generic_attr(hir_id, attr, target, Target::Impl) } - sym::no_implicit_prelude => { + [sym::no_implicit_prelude, ..] => { self.check_generic_attr(hir_id, attr, target, Target::Mod) } - sym::rustc_object_lifetime_default => self.check_object_lifetime_default(hir_id), - sym::proc_macro => { + [sym::rustc_object_lifetime_default, ..] => self.check_object_lifetime_default(hir_id), + [sym::proc_macro, ..] => { self.check_proc_macro(hir_id, target, ProcMacroKind::FunctionLike) } - sym::proc_macro_attribute => { + [sym::proc_macro_attribute, ..] => { self.check_proc_macro(hir_id, target, ProcMacroKind::Attribute); } - sym::proc_macro_derive => { + [sym::proc_macro_derive, ..] => { self.check_generic_attr(hir_id, attr, target, Target::Fn); self.check_proc_macro(hir_id, target, ProcMacroKind::Derive) } - _ => {} + [sym::coroutine, ..] => { + self.check_coroutine(attr, target); + } + [ + // ok + sym::allow + | sym::expect + | sym::warn + | sym::deny + | sym::forbid + | sym::cfg + // need to be fixed + | sym::cfi_encoding // FIXME(cfi_encoding) + | sym::may_dangle // FIXME(dropck_eyepatch) + | sym::pointee // FIXME(derive_smart_pointer) + | sym::linkage // FIXME(linkage) + | sym::no_sanitize // FIXME(no_sanitize) + | sym::omit_gdb_pretty_printer_section // FIXME(omit_gdb_pretty_printer_section) + | sym::used // handled elsewhere to restrict to static items + | sym::repr // handled elsewhere to restrict to type decls items + | sym::instruction_set // broken on stable!!! + | sym::windows_subsystem // broken on stable!!! + | sym::patchable_function_entry // FIXME(patchable_function_entry) + | sym::deprecated_safe // FIXME(deprecated_safe) + // internal + | sym::prelude_import + | sym::panic_handler + | sym::allow_internal_unsafe + | sym::fundamental + | sym::lang + | sym::needs_allocator + | sym::default_lib_allocator + | sym::start + | sym::custom_mir, + .. + ] => {} + [name, ..] => { + match BUILTIN_ATTRIBUTE_MAP.get(name) { + // checked below + Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) => {} + Some(_) => { + // FIXME: differentiate between unstable and internal attributes just + // like we do with features instead of just accepting `rustc_` + // attributes by name. That should allow trimming the above list, too. + if !name.as_str().starts_with("rustc_") { + span_bug!( + attr.span, + "builtin attribute {name:?} not handled by `CheckAttrVisitor`" + ) + } + } + None => (), + } + } + [] => unreachable!(), } let builtin = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)); @@ -296,7 +349,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } /// Checks if `#[diagnostic::do_not_recommend]` is applied on a trait impl. - fn check_do_not_recommend(&self, attr_span: Span, hir_id: HirId, target: Target) -> bool { + fn check_do_not_recommend(&self, attr_span: Span, hir_id: HirId, target: Target) { if !matches!(target, Target::Impl) { self.tcx.emit_node_span_lint( UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, @@ -305,16 +358,10 @@ impl<'tcx> CheckAttrVisitor<'tcx> { errors::IncorrectDoNotRecommendLocation, ); } - true } /// Checks if `#[diagnostic::on_unimplemented]` is applied to a trait definition - fn check_diagnostic_on_unimplemented( - &self, - attr_span: Span, - hir_id: HirId, - target: Target, - ) -> bool { + fn check_diagnostic_on_unimplemented(&self, attr_span: Span, hir_id: HirId, target: Target) { if !matches!(target, Target::Trait) { self.tcx.emit_node_span_lint( UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, @@ -323,68 +370,82 @@ impl<'tcx> CheckAttrVisitor<'tcx> { DiagnosticOnUnimplementedOnlyForTraits, ); } - true } - /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid. - fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool { + /// Checks if an `#[inline]` is applied to a function or a closure. + fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) { match target { Target::Fn | Target::Closure - | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, + | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {} Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => { self.tcx.emit_node_span_lint( UNUSED_ATTRIBUTES, hir_id, attr.span, errors::IgnoredInlineAttrFnProto, - ); - true + ) } // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with // just a lint, because we previously erroneously allowed it and some crates used it // accidentally, to be compatible with crates depending on them, we can't throw an // error here. - Target::AssocConst => { - self.tcx.emit_node_span_lint( - UNUSED_ATTRIBUTES, - hir_id, - attr.span, - errors::IgnoredInlineAttrConstants, - ); - true - } + Target::AssocConst => self.tcx.emit_node_span_lint( + UNUSED_ATTRIBUTES, + hir_id, + attr.span, + errors::IgnoredInlineAttrConstants, + ), // FIXME(#80564): Same for fields, arms, and macro defs Target::Field | Target::Arm | Target::MacroDef => { - self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline"); - true + self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline") } _ => { self.dcx().emit_err(errors::InlineNotFnOrClosure { attr_span: attr.span, defn_span: span, }); - false } } } /// Checks that `#[coverage(..)]` is applied to a function/closure/method, /// or to an impl block or module. - fn check_coverage(&self, attr: &Attribute, span: Span, target: Target) -> bool { + fn check_coverage(&self, attr: &Attribute, span: Span, target: Target) { match target { Target::Fn | Target::Closure | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) | Target::Impl - | Target::Mod => true, + | Target::Mod => {} _ => { self.dcx().emit_err(errors::CoverageNotFnOrClosure { attr_span: attr.span, defn_span: span, }); - false + } + } + } + + /// Checks that `#[optimize(..)]` is applied to a function/closure/method, + /// or to an impl block or module. + // FIXME(#128488): this should probably be elevated to an error? + fn check_optimize(&self, hir_id: HirId, attr: &Attribute, target: Target) { + match target { + Target::Fn + | Target::Closure + | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) + | Target::Impl + | Target::Mod => {} + + _ => { + self.tcx.emit_node_span_lint( + UNUSED_ATTRIBUTES, + hir_id, + attr.span, + errors::OptimizeNotFnOrClosure, + ); } } } @@ -410,17 +471,79 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } /// Checks if `#[naked]` is applied to a function definition. - fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool { + fn check_naked( + &self, + hir_id: HirId, + attr: &Attribute, + span: Span, + target: Target, + attrs: &[Attribute], + ) { + // many attributes don't make sense in combination with #[naked]. + // Notable attributes that are incompatible with `#[naked]` are: + // + // * `#[inline]` + // * `#[track_caller]` + // * `#[test]`, `#[ignore]`, `#[should_panic]` + // + // NOTE: when making changes to this list, check that `error_codes/E0736.md` remains accurate + const ALLOW_LIST: &[rustc_span::Symbol] = &[ + // conditional compilation + sym::cfg, + sym::cfg_attr, + // testing (allowed here so better errors can be generated in `rustc_builtin_macros::test`) + sym::test, + sym::ignore, + sym::should_panic, + sym::bench, + // diagnostics + sym::allow, + sym::warn, + sym::deny, + sym::forbid, + sym::deprecated, + sym::must_use, + // abi, linking and FFI + sym::export_name, + sym::link_section, + sym::linkage, + sym::no_mangle, + sym::naked, + sym::instruction_set, + // code generation + sym::cold, + sym::target_feature, + // documentation + sym::doc, + ]; + match target { Target::Fn - | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, + | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => { + for other_attr in attrs { + // this covers "sugared doc comments" of the form `/// ...` + // it does not cover `#[doc = "..."]`, which is handled below + if other_attr.is_doc_comment() { + continue; + } + + if !ALLOW_LIST.iter().any(|name| other_attr.has_name(*name)) { + self.dcx().emit_err(errors::NakedFunctionIncompatibleAttribute { + span: other_attr.span, + naked_span: attr.span, + attr: other_attr.name_or_empty(), + }); + + return; + } + } + } // FIXME(#80564): We permit struct fields, match arms and macro defs to have an - // `#[allow_internal_unstable]` attribute with just a lint, because we previously + // `#[naked]` attribute with just a lint, because we previously // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { - self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked"); - true + self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked") } _ => { self.dcx().emit_err(errors::AttrShouldBeAppliedToFn { @@ -428,7 +551,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { defn_span: span, on_crate: hir_id == CRATE_HIR_ID, }); - false } } } @@ -440,17 +562,16 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr: &Attribute, span: Span, target: Target, - ) -> bool { + ) { match target { Target::Fn - | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, + | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {} _ => { self.dcx().emit_err(errors::AttrShouldBeAppliedToFn { attr_span: attr.span, defn_span: span, on_crate: hir_id == CRATE_HIR_ID, }); - false } } } @@ -476,19 +597,18 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } /// Checks if `#[collapse_debuginfo]` is applied to a macro. - fn check_collapse_debuginfo(&self, attr: &Attribute, span: Span, target: Target) -> bool { + fn check_collapse_debuginfo(&self, attr: &Attribute, span: Span, target: Target) { match target { - Target::MacroDef => true, + Target::MacroDef => {} _ => { self.tcx .dcx() .emit_err(errors::CollapseDebuginfo { attr_span: attr.span, defn_span: span }); - false } } } - /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid. + /// Checks if a `#[track_caller]` is applied to a function. fn check_track_caller( &self, hir_id: HirId, @@ -496,12 +616,8 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attrs: &[Attribute], span: Span, target: Target, - ) -> bool { + ) { match target { - _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => { - self.dcx().emit_err(errors::NakedTrackedCaller { attr_span }); - false - } Target::Fn => { // `#[track_caller]` is not valid on weak lang items because they are called via // `extern` declarations and `#[track_caller]` would alter their ABI. @@ -516,12 +632,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { name: lang_item, sig_span: sig.span, }); - false - } else { - true } } - Target::Method(..) | Target::ForeignFn | Target::Closure => true, + Target::Method(..) | Target::ForeignFn | Target::Closure => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[track_caller]` attribute with just a lint, because we previously // erroneously allowed it and some crates used it accidentally, to be compatible @@ -530,7 +643,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { for attr in attrs { self.inline_attr_str_error_with_macro_def(hir_id, attr, "track_caller"); } - true } _ => { self.dcx().emit_err(errors::TrackedCallerWrongLocation { @@ -538,62 +650,51 @@ impl<'tcx> CheckAttrVisitor<'tcx> { defn_span: span, on_crate: hir_id == CRATE_HIR_ID, }); - false } } } - /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid. - fn check_non_exhaustive( - &self, - hir_id: HirId, - attr: &Attribute, - span: Span, - target: Target, - ) -> bool { + /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. + fn check_non_exhaustive(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) { match target { - Target::Struct | Target::Enum | Target::Variant => true, + Target::Struct | Target::Enum | Target::Variant => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[non_exhaustive]` attribute with just a lint, because we previously // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive"); - true } _ => { self.dcx().emit_err(errors::NonExhaustiveWrongLocation { attr_span: attr.span, defn_span: span, }); - false } } } - /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid. - fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool { + /// Checks if the `#[marker]` attribute on an `item` is valid. + fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) { match target { - Target::Trait => true, + Target::Trait => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[marker]` attribute with just a lint, because we previously // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker"); - true } _ => { self.dcx().emit_err(errors::AttrShouldBeAppliedToTrait { attr_span: attr.span, defn_span: span, }); - false } } } - /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid. + /// Checks if the `#[target_feature]` attribute on `item` is valid. fn check_target_feature( &self, hir_id: HirId, @@ -601,7 +702,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { span: Span, target: Target, attrs: &[Attribute], - ) -> bool { + ) { match target { Target::Fn => { // `#[target_feature]` is not allowed in lang items. @@ -618,12 +719,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { name: lang_item, sig_span: sig.span, }); - false - } else { - true } } - Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, + Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {} // FIXME: #[target_feature] was previously erroneously allowed on statements and some // crates used this, so only emit a warning. Target::Statement => { @@ -633,7 +731,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr.span, errors::TargetFeatureOnStatement, ); - true } // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[target_feature]` attribute with just a lint, because we previously @@ -641,7 +738,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature"); - true } _ => { self.dcx().emit_err(errors::AttrShouldBeAppliedToFn { @@ -649,21 +745,19 @@ impl<'tcx> CheckAttrVisitor<'tcx> { defn_span: span, on_crate: hir_id == CRATE_HIR_ID, }); - false } } } - /// Checks if the `#[thread_local]` attribute on `item` is valid. Returns `true` if valid. - fn check_thread_local(&self, attr: &Attribute, span: Span, target: Target) -> bool { + /// Checks if the `#[thread_local]` attribute on `item` is valid. + fn check_thread_local(&self, attr: &Attribute, span: Span, target: Target) { match target { - Target::ForeignStatic | Target::Static => true, + Target::ForeignStatic | Target::Static => {} _ => { self.dcx().emit_err(errors::AttrShouldBeAppliedToStatic { attr_span: attr.span, defn_span: span, }); - false } } } @@ -680,14 +774,14 @@ impl<'tcx> CheckAttrVisitor<'tcx> { target: Target, is_list: bool, aliases: &mut FxHashMap, - ) -> bool { + ) { let tcx = self.tcx; let span = meta.name_value_literal_span().unwrap_or_else(|| meta.span()); let attr_str = &format!("`#[doc(alias{})]`", if is_list { "(\"...\")" } else { " = \"...\"" }); if doc_alias == kw::Empty { tcx.dcx().emit_err(errors::DocAliasEmpty { span, attr_str }); - return false; + return; } let doc_alias_str = doc_alias.as_str(); @@ -696,11 +790,11 @@ impl<'tcx> CheckAttrVisitor<'tcx> { .find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' ')) { tcx.dcx().emit_err(errors::DocAliasBadChar { span, attr_str, char_: c }); - return false; + return; } if doc_alias_str.starts_with(' ') || doc_alias_str.ends_with(' ') { tcx.dcx().emit_err(errors::DocAliasStartEnd { span, attr_str }); - return false; + return; } let span = meta.span(); @@ -725,7 +819,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } // we check the validity of params elsewhere - Target::Param => return false, + Target::Param => return, Target::Expression | Target::Statement | Target::Arm @@ -758,12 +852,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | Target::ExprField => None, } { tcx.dcx().emit_err(errors::DocAliasBadLocation { span, attr_str, location }); - return false; + return; } let item_name = self.tcx.hir().name(hir_id); if item_name == doc_alias { tcx.dcx().emit_err(errors::DocAliasNotAnAlias { span, attr_str }); - return false; + return; } if let Err(entry) = aliases.try_insert(doc_alias_str.to_owned(), span) { self.tcx.emit_node_span_lint( @@ -773,7 +867,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { errors::DocAliasDuplicated { first_defn: *entry.entry.get() }, ); } - true } fn check_doc_alias( @@ -782,46 +875,39 @@ impl<'tcx> CheckAttrVisitor<'tcx> { hir_id: HirId, target: Target, aliases: &mut FxHashMap, - ) -> bool { + ) { if let Some(values) = meta.meta_item_list() { - let mut errors = 0; for v in values { match v.lit() { Some(l) => match l.kind { LitKind::Str(s, _) => { - if !self.check_doc_alias_value(v, s, hir_id, target, true, aliases) { - errors += 1; - } + self.check_doc_alias_value(v, s, hir_id, target, true, aliases); } _ => { self.tcx .dcx() .emit_err(errors::DocAliasNotStringLiteral { span: v.span() }); - errors += 1; } }, None => { self.tcx .dcx() .emit_err(errors::DocAliasNotStringLiteral { span: v.span() }); - errors += 1; } } } - errors == 0 } else if let Some(doc_alias) = meta.value_str() { self.check_doc_alias_value(meta, doc_alias, hir_id, target, false, aliases) } else { self.dcx().emit_err(errors::DocAliasMalformed { span: meta.span() }); - false } } - fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool { + fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) { let doc_keyword = meta.value_str().unwrap_or(kw::Empty); if doc_keyword == kw::Empty { self.doc_attr_str_error(meta, "keyword"); - return false; + return; } let item_kind = match self.tcx.hir_node(hir_id) { hir::Node::Item(item) => Some(&item.kind), @@ -831,12 +917,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> { Some(ItemKind::Mod(module)) => { if !module.item_ids.is_empty() { self.dcx().emit_err(errors::DocKeywordEmptyMod { span: meta.span() }); - return false; + return; } } _ => { self.dcx().emit_err(errors::DocKeywordNotMod { span: meta.span() }); - return false; + return; } } if !rustc_lexer::is_ident(doc_keyword.as_str()) { @@ -844,12 +930,10 @@ impl<'tcx> CheckAttrVisitor<'tcx> { span: meta.name_value_literal_span().unwrap_or_else(|| meta.span()), doc_keyword, }); - return false; } - true } - fn check_doc_fake_variadic(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool { + fn check_doc_fake_variadic(&self, meta: &NestedMetaItem, hir_id: HirId) { let item_kind = match self.tcx.hir_node(hir_id) { hir::Node::Item(item) => Some(&item.kind), _ => None, @@ -864,18 +948,15 @@ impl<'tcx> CheckAttrVisitor<'tcx> { }; if !is_valid { self.dcx().emit_err(errors::DocFakeVariadicNotValid { span: meta.span() }); - return false; } } _ => { self.dcx().emit_err(errors::DocKeywordOnlyImpl { span: meta.span() }); - return false; } } - true } - /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. Returns `true` if valid. + /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. /// /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or /// if there are conflicting attributes for one item. @@ -891,7 +972,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { hir_id: HirId, target: Target, specified_inline: &mut Option<(bool, Span)>, - ) -> bool { + ) { match target { Target::Use | Target::ExternCrate => { let do_inline = meta.name_or_empty() == sym::inline; @@ -904,12 +985,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { fluent::passes_doc_inline_conflict_second, ); self.dcx().emit_err(errors::DocKeywordConflict { spans }); - return false; } - true } else { *specified_inline = Some((do_inline, meta.span())); - true } } _ => { @@ -923,7 +1001,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { .then(|| self.tcx.hir().span(hir_id)), }, ); - false } } } @@ -934,7 +1011,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { meta: &NestedMetaItem, hir_id: HirId, target: Target, - ) -> bool { + ) { if target != Target::ExternCrate { self.tcx.emit_node_span_lint( INVALID_DOC_ATTRIBUTES, @@ -946,7 +1023,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { .then(|| self.tcx.hir().span(hir_id)), }, ); - return false; + return; } if self.tcx.extern_mod_stmt_cnum(hir_id.owner).is_none() { @@ -960,10 +1037,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { .then(|| self.tcx.hir().span(hir_id)), }, ); - return false; } - - true } /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid. @@ -1008,8 +1082,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { /// Checks that `doc(test(...))` attribute contains only valid attributes. Returns `true` if /// valid. - fn check_test_attr(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool { - let mut is_valid = true; + fn check_test_attr(&self, meta: &NestedMetaItem, hir_id: HirId) { if let Some(metas) = meta.meta_item_list() { for i_meta in metas { match (i_meta.name_or_empty(), i_meta.meta_item()) { @@ -1023,7 +1096,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { path: rustc_ast_pretty::pprust::path_to_string(&m.path), }, ); - is_valid = false; } (_, None) => { self.tcx.emit_node_span_lint( @@ -1032,7 +1104,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { i_meta.span(), errors::DocTestLiteral, ); - is_valid = false; } } } @@ -1043,28 +1114,23 @@ impl<'tcx> CheckAttrVisitor<'tcx> { meta.span(), errors::DocTestTakesList, ); - is_valid = false; } - is_valid } /// Check that the `#![doc(cfg_hide(...))]` attribute only contains a list of attributes. - /// Returns `true` if valid. - fn check_doc_cfg_hide(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool { - if meta.meta_item_list().is_some() { - true - } else { + /// + fn check_doc_cfg_hide(&self, meta: &NestedMetaItem, hir_id: HirId) { + if meta.meta_item_list().is_none() { self.tcx.emit_node_span_lint( INVALID_DOC_ATTRIBUTES, hir_id, meta.span(), errors::DocCfgHideTakesList, ); - false } } - /// Runs various checks on `#[doc]` attributes. Returns `true` if valid. + /// Runs various checks on `#[doc]` attributes. /// /// `specified_inline` should be initialized to `None` and kept for the scope /// of one item. Read the documentation of [`check_doc_inline`] for more information. @@ -1078,34 +1144,35 @@ impl<'tcx> CheckAttrVisitor<'tcx> { target: Target, specified_inline: &mut Option<(bool, Span)>, aliases: &mut FxHashMap, - ) -> bool { - let mut is_valid = true; - + ) { if let Some(mi) = attr.meta() && let Some(list) = mi.meta_item_list() { for meta in list { if let Some(i_meta) = meta.meta_item() { match i_meta.name_or_empty() { - sym::alias - if !self.check_attr_not_crate_level(meta, hir_id, "alias") - || !self.check_doc_alias(meta, hir_id, target, aliases) => - { - is_valid = false + sym::alias => { + if self.check_attr_not_crate_level(meta, hir_id, "alias") { + self.check_doc_alias(meta, hir_id, target, aliases); + } } - sym::keyword - if !self.check_attr_not_crate_level(meta, hir_id, "keyword") - || !self.check_doc_keyword(meta, hir_id) => - { - is_valid = false + sym::keyword => { + if self.check_attr_not_crate_level(meta, hir_id, "keyword") { + self.check_doc_keyword(meta, hir_id); + } } - sym::fake_variadic - if !self.check_attr_not_crate_level(meta, hir_id, "fake_variadic") - || !self.check_doc_fake_variadic(meta, hir_id) => - { - is_valid = false + sym::fake_variadic => { + if self.check_attr_not_crate_level(meta, hir_id, "fake_variadic") { + self.check_doc_fake_variadic(meta, hir_id); + } + } + + sym::test => { + if self.check_attr_crate_level(attr, meta, hir_id) { + self.check_test_attr(meta, hir_id); + } } sym::html_favicon_url @@ -1113,62 +1180,36 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::html_playground_url | sym::issue_tracker_base_url | sym::html_root_url - | sym::html_no_source - | sym::test - | sym::rust_logo - if !self.check_attr_crate_level(attr, meta, hir_id) => - { - is_valid = false; + | sym::html_no_source => { + self.check_attr_crate_level(attr, meta, hir_id); } - sym::cfg_hide - if !self.check_attr_crate_level(attr, meta, hir_id) - || !self.check_doc_cfg_hide(meta, hir_id) => - { - is_valid = false; + sym::cfg_hide => { + if self.check_attr_crate_level(attr, meta, hir_id) { + self.check_doc_cfg_hide(meta, hir_id); + } } - sym::inline | sym::no_inline - if !self.check_doc_inline( - attr, - meta, - hir_id, - target, - specified_inline, - ) => - { - is_valid = false; + sym::inline | sym::no_inline => { + self.check_doc_inline(attr, meta, hir_id, target, specified_inline) } - sym::masked if !self.check_doc_masked(attr, meta, hir_id, target) => { - is_valid = false; - } + sym::masked => self.check_doc_masked(attr, meta, hir_id, target), // no_default_passes: deprecated // passes: deprecated // plugins: removed, but rustdoc warns about it itself - sym::alias - | sym::cfg - | sym::cfg_hide + sym::cfg | sym::hidden - | sym::html_favicon_url - | sym::html_logo_url - | sym::html_no_source - | sym::html_playground_url - | sym::html_root_url - | sym::inline - | sym::issue_tracker_base_url - | sym::keyword - | sym::masked | sym::no_default_passes - | sym::no_inline | sym::notable_trait | sym::passes - | sym::plugins - | sym::fake_variadic => {} + | sym::plugins => {} sym::rust_logo => { - if !self.tcx.features().rustdoc_internals { + if self.check_attr_crate_level(attr, meta, hir_id) + && !self.tcx.features().rustdoc_internals + { feature_err( &self.tcx.sess, sym::rustdoc_internals, @@ -1179,12 +1220,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - sym::test => { - if !self.check_test_attr(meta, hir_id) { - is_valid = false; - } - } - _ => { let path = rustc_ast_pretty::pprust::path_to_string(&i_meta.path); if i_meta.has_name(sym::spotlight) { @@ -1226,7 +1261,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { errors::DocTestUnknownAny { path }, ); } - is_valid = false; } } } else { @@ -1236,79 +1270,60 @@ impl<'tcx> CheckAttrVisitor<'tcx> { meta.span(), errors::DocInvalid, ); - is_valid = false; } } } - - is_valid } /// Warns against some misuses of `#[pass_by_value]` - fn check_pass_by_value(&self, attr: &Attribute, span: Span, target: Target) -> bool { + fn check_pass_by_value(&self, attr: &Attribute, span: Span, target: Target) { match target { - Target::Struct | Target::Enum | Target::TyAlias => true, + Target::Struct | Target::Enum | Target::TyAlias => {} _ => { self.dcx().emit_err(errors::PassByValue { attr_span: attr.span, span }); - false } } } - fn check_allow_incoherent_impl(&self, attr: &Attribute, span: Span, target: Target) -> bool { + fn check_allow_incoherent_impl(&self, attr: &Attribute, span: Span, target: Target) { match target { - Target::Method(MethodKind::Inherent) => true, + Target::Method(MethodKind::Inherent) => {} _ => { self.dcx().emit_err(errors::AllowIncoherentImpl { attr_span: attr.span, span }); - false } } } - fn check_has_incoherent_inherent_impls( - &self, - attr: &Attribute, - span: Span, - target: Target, - ) -> bool { + fn check_has_incoherent_inherent_impls(&self, attr: &Attribute, span: Span, target: Target) { match target { - Target::Trait | Target::Struct | Target::Enum | Target::Union | Target::ForeignTy => { - true - } + Target::Trait | Target::Struct | Target::Enum | Target::Union | Target::ForeignTy => {} _ => { self.tcx .dcx() .emit_err(errors::HasIncoherentInherentImpl { attr_span: attr.span, span }); - false } } } - fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute], target: Target) -> bool { + fn check_ffi_pure(&self, attr_span: Span, attrs: &[Attribute], target: Target) { if target != Target::ForeignFn { self.dcx().emit_err(errors::FfiPureInvalidTarget { attr_span }); - return false; + return; } if attrs.iter().any(|a| a.has_name(sym::ffi_const)) { // `#[ffi_const]` functions cannot be `#[ffi_pure]` self.dcx().emit_err(errors::BothFfiConstAndPure { attr_span }); - false - } else { - true } } - fn check_ffi_const(&self, attr_span: Span, target: Target) -> bool { - if target == Target::ForeignFn { - true - } else { + fn check_ffi_const(&self, attr_span: Span, target: Target) { + if target != Target::ForeignFn { self.dcx().emit_err(errors::FfiConstInvalidTarget { attr_span }); - false } } /// Warns against some misuses of `#[must_use]` - fn check_must_use(&self, hir_id: HirId, attr: &Attribute, target: Target) -> bool { + fn check_must_use(&self, hir_id: HirId, attr: &Attribute, target: Target) { if !matches!( target, Target::Fn @@ -1341,23 +1356,19 @@ impl<'tcx> CheckAttrVisitor<'tcx> { errors::MustUseNoEffect { article, target }, ); } - - // For now, its always valid - true } - /// Checks if `#[must_not_suspend]` is applied to a function. Returns `true` if valid. - fn check_must_not_suspend(&self, attr: &Attribute, span: Span, target: Target) -> bool { + /// Checks if `#[must_not_suspend]` is applied to a function. + fn check_must_not_suspend(&self, attr: &Attribute, span: Span, target: Target) { match target { - Target::Struct | Target::Enum | Target::Union | Target::Trait => true, + Target::Struct | Target::Enum | Target::Union | Target::Trait => {} _ => { self.dcx().emit_err(errors::MustNotSuspend { attr_span: attr.span, span }); - false } } } - /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid. + /// Checks if `#[cold]` is applied to a non-function. fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) { match target { Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {} @@ -1433,21 +1444,19 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid. - fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool { + /// Checks if `#[no_link]` is applied to an `extern crate`. + fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) { match target { - Target::ExternCrate => true, + Target::ExternCrate => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[no_link]` attribute with just a lint, because we previously // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link"); - true } _ => { self.dcx().emit_err(errors::NoLink { attr_span: attr.span, span }); - false } } } @@ -1456,57 +1465,42 @@ impl<'tcx> CheckAttrVisitor<'tcx> { matches!(self.tcx.hir_node(hir_id), hir::Node::ImplItem(..)) } - /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid. - fn check_export_name( - &self, - hir_id: HirId, - attr: &Attribute, - span: Span, - target: Target, - ) -> bool { + /// Checks if `#[export_name]` is applied to a function or static. + fn check_export_name(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) { match target { - Target::Static | Target::Fn => true, - Target::Method(..) if self.is_impl_item(hir_id) => true, + Target::Static | Target::Fn => {} + Target::Method(..) if self.is_impl_item(hir_id) => {} // FIXME(#80564): We permit struct fields, match arms and macro defs to have an // `#[export_name]` attribute with just a lint, because we previously // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name"); - true } _ => { self.dcx().emit_err(errors::ExportName { attr_span: attr.span, span }); - false } } } - fn check_rustc_layout_scalar_valid_range( - &self, - attr: &Attribute, - span: Span, - target: Target, - ) -> bool { + fn check_rustc_layout_scalar_valid_range(&self, attr: &Attribute, span: Span, target: Target) { if target != Target::Struct { self.dcx().emit_err(errors::RustcLayoutScalarValidRangeNotStruct { attr_span: attr.span, span, }); - return false; + return; } let Some(list) = attr.meta_item_list() else { - return false; + return; }; - if matches!(&list[..], &[NestedMetaItem::Lit(MetaItemLit { kind: LitKind::Int(..), .. })]) { - true - } else { + if !matches!(&list[..], &[NestedMetaItem::Lit(MetaItemLit { kind: LitKind::Int(..), .. })]) + { self.tcx .dcx() .emit_err(errors::RustcLayoutScalarValidRangeArg { attr_span: attr.span }); - false } } @@ -1518,7 +1512,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { span: Span, target: Target, item: Option>, - ) -> bool { + ) { let is_function = matches!(target, Target::Fn); if !is_function { self.dcx().emit_err(errors::AttrShouldBeAppliedToFn { @@ -1526,12 +1520,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> { defn_span: span, on_crate: hir_id == CRATE_HIR_ID, }); - return false; + return; } let Some(list) = attr.meta_item_list() else { // The attribute form is validated on AST. - return false; + return; }; let Some(ItemLike::Item(Item { @@ -1549,7 +1543,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr_span: attr.span, param_span: param.span, }); - return false; + return; } } } @@ -1559,7 +1553,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr_span: attr.span, generics_span: generics.span, }); - return false; + return; } let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128; @@ -1572,7 +1566,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { span, arg_count: arg_count as usize, }); - return false; + return; } } else { invalid_args.push(meta.span()); @@ -1581,9 +1575,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { if !invalid_args.is_empty() { self.dcx().emit_err(errors::RustcLegacyConstGenericsIndexNegative { invalid_args }); - false - } else { - true } } @@ -1595,7 +1586,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr: &Attribute, span: Span, target: Target, - ) -> bool { + ) { let is_function = matches!(target, Target::Fn | Target::Method(..)); if !is_function { self.dcx().emit_err(errors::AttrShouldBeAppliedToFn { @@ -1603,9 +1594,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { defn_span: span, on_crate: hir_id == CRATE_HIR_ID, }); - false - } else { - true } } @@ -1617,7 +1605,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr: &Attribute, span: Span, target: Target, - ) -> bool { + ) { self.check_applied_to_fn_or_method(hir_id, attr, span, target) } @@ -1629,60 +1617,49 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr: &Attribute, span: Span, target: Target, - ) -> bool { + ) { self.check_applied_to_fn_or_method(hir_id, attr, span, target) } /// Checks that the `#[rustc_lint_opt_ty]` attribute is only applied to a struct. - fn check_rustc_lint_opt_ty(&self, attr: &Attribute, span: Span, target: Target) -> bool { + fn check_rustc_lint_opt_ty(&self, attr: &Attribute, span: Span, target: Target) { match target { - Target::Struct => true, + Target::Struct => {} _ => { self.dcx().emit_err(errors::RustcLintOptTy { attr_span: attr.span, span }); - false } } } /// Checks that the `#[rustc_lint_opt_deny_field_access]` attribute is only applied to a field. - fn check_rustc_lint_opt_deny_field_access( - &self, - attr: &Attribute, - span: Span, - target: Target, - ) -> bool { + fn check_rustc_lint_opt_deny_field_access(&self, attr: &Attribute, span: Span, target: Target) { match target { - Target::Field => true, + Target::Field => {} _ => { self.tcx .dcx() .emit_err(errors::RustcLintOptDenyFieldAccess { attr_span: attr.span, span }); - false } } } /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph /// option is passed to the compiler. - fn check_rustc_dirty_clean(&self, attr: &Attribute) -> bool { - if self.tcx.sess.opts.unstable_opts.query_dep_graph { - true - } else { + fn check_rustc_dirty_clean(&self, attr: &Attribute) { + if !self.tcx.sess.opts.unstable_opts.query_dep_graph { self.dcx().emit_err(errors::RustcDirtyClean { span: attr.span }); - false } } /// Checks if the attribute is applied to a trait. - fn check_must_be_applied_to_trait(&self, attr: &Attribute, span: Span, target: Target) -> bool { + fn check_must_be_applied_to_trait(&self, attr: &Attribute, span: Span, target: Target) { match target { - Target::Trait => true, + Target::Trait => {} _ => { self.dcx().emit_err(errors::AttrShouldBeAppliedToTrait { attr_span: attr.span, defn_span: span, }); - false } } } @@ -1980,43 +1957,38 @@ impl<'tcx> CheckAttrVisitor<'tcx> { span: Span, target: Target, attrs: &[Attribute], - ) -> bool { + ) { debug!("Checking target: {:?}", target); match target { Target::Fn => { for attr in attrs { if attr.is_proc_macro_attr() { debug!("Is proc macro attr"); - return true; + return; } } debug!("Is not proc macro attr"); - false } - Target::MacroDef => true, + Target::MacroDef => {} // FIXME(#80564): We permit struct fields and match arms to have an // `#[allow_internal_unstable]` attribute with just a lint, because we previously // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. - Target::Field | Target::Arm => { - self.inline_attr_str_error_without_macro_def( - hir_id, - attr, - "allow_internal_unstable", - ); - true - } + Target::Field | Target::Arm => self.inline_attr_str_error_without_macro_def( + hir_id, + attr, + "allow_internal_unstable", + ), _ => { self.tcx .dcx() .emit_err(errors::AllowInternalUnstable { attr_span: attr.span, span }); - false } } } /// Checks if the items on the `#[debugger_visualizer]` attribute are valid. - fn check_debugger_visualizer(&self, attr: &Attribute, target: Target) -> bool { + fn check_debugger_visualizer(&self, attr: &Attribute, target: Target) { // Here we only check that the #[debugger_visualizer] attribute is attached // to nothing other than a module. All other checks are done in the // `debugger_visualizer` query where they need to be done for decoding @@ -2025,11 +1997,8 @@ impl<'tcx> CheckAttrVisitor<'tcx> { Target::Mod => {} _ => { self.dcx().emit_err(errors::DebugVisualizerPlacement { span: attr.span }); - return false; } } - - true } /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros. @@ -2040,26 +2009,21 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr: &Attribute, span: Span, target: Target, - ) -> bool { + ) { match target { Target::Fn | Target::Method(_) - if self.tcx.is_const_fn_raw(hir_id.expect_owner().to_def_id()) => - { - true - } + if self.tcx.is_const_fn_raw(hir_id.expect_owner().to_def_id()) => {} // FIXME(#80564): We permit struct fields and match arms to have an // `#[allow_internal_unstable]` attribute with just a lint, because we previously // erroneously allowed it and some crates used it accidentally, to be compatible // with crates depending on them, we can't throw an error here. Target::Field | Target::Arm | Target::MacroDef => { - self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable"); - true + self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable") } _ => { self.tcx .dcx() .emit_err(errors::RustcAllowConstFnUnstable { attr_span: attr.span, span }); - false } } } @@ -2070,65 +2034,56 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr: &Attribute, span: Span, target: Target, - ) -> bool { + ) { if let Target::ForeignFn = target && let hir::Node::Item(Item { kind: ItemKind::ForeignMod { abi: Abi::RustIntrinsic, .. }, .. }) = self.tcx.parent_hir_node(hir_id) { - return true; + return; } self.dcx().emit_err(errors::RustcSafeIntrinsic { attr_span: attr.span, span }); - false } - fn check_rustc_std_internal_symbol( - &self, - attr: &Attribute, - span: Span, - target: Target, - ) -> bool { + fn check_rustc_std_internal_symbol(&self, attr: &Attribute, span: Span, target: Target) { match target { - Target::Fn | Target::Static => true, + Target::Fn | Target::Static => {} _ => { self.tcx .dcx() .emit_err(errors::RustcStdInternalSymbol { attr_span: attr.span, span }); - false } } } - fn check_stability_promotable(&self, attr: &Attribute, target: Target) -> bool { + fn check_stability_promotable(&self, attr: &Attribute, target: Target) { match target { Target::Expression => { self.dcx().emit_err(errors::StabilityPromotable { attr_span: attr.span }); - false } - _ => true, + _ => {} } } - fn check_link_ordinal(&self, attr: &Attribute, _span: Span, target: Target) -> bool { + fn check_link_ordinal(&self, attr: &Attribute, _span: Span, target: Target) { match target { - Target::ForeignFn | Target::ForeignStatic => true, + Target::ForeignFn | Target::ForeignStatic => {} _ => { self.dcx().emit_err(errors::LinkOrdinal { attr_span: attr.span }); - false } } } - fn check_confusables(&self, attr: &Attribute, target: Target) -> bool { + fn check_confusables(&self, attr: &Attribute, target: Target) { match target { Target::Method(MethodKind::Inherent) => { let Some(meta) = attr.meta() else { - return false; + return; }; let ast::MetaItem { kind: MetaItemKind::List(ref metas), .. } = meta else { - return false; + return; }; let mut candidates = Vec::new(); @@ -2142,21 +2097,17 @@ impl<'tcx> CheckAttrVisitor<'tcx> { hi: meta.span().shrink_to_hi(), }, }); - return false; + return; }; candidates.push(meta_lit.symbol); } if candidates.is_empty() { self.dcx().emit_err(errors::EmptyConfusables { span: attr.span }); - return false; } - - true } _ => { self.dcx().emit_err(errors::Confusables { attr_span: attr.span }); - false } } } @@ -2383,6 +2334,15 @@ impl<'tcx> CheckAttrVisitor<'tcx> { self.abort.set(true); } } + + fn check_coroutine(&self, attr: &Attribute, target: Target) { + match target { + Target::Closure => return, + _ => { + self.dcx().emit_err(errors::CoroutineOnNonClosure { span: attr.span }); + } + } + } } impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> { diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index 3f6eccbd5a523..be6449ea8520a 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -7,8 +7,6 @@ //! errors. We still look for those primitives in the MIR const-checker to ensure nothing slips //! through, but errors for structured control flow in a `const` should be emitted here. -use rustc_attr as attr; -use rustc_hir as hir; use rustc_hir::def_id::{LocalDefId, LocalModDefId}; use rustc_hir::intravisit::{self, Visitor}; use rustc_middle::hir::nested_filter; @@ -17,6 +15,7 @@ use rustc_middle::span_bug; use rustc_middle::ty::TyCtxt; use rustc_session::parse::feature_err; use rustc_span::{sym, Span, Symbol}; +use {rustc_attr as attr, rustc_hir as hir}; use crate::errors::SkippingConstChecks; diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 55514883cb1f8..7ae5c9040042c 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -3,6 +3,8 @@ // expectations such as `#[expect(unused)]` and `#[expect(dead_code)]` is live, and everything else // is dead. +use std::mem; + use hir::def_id::{LocalDefIdMap, LocalDefIdSet}; use hir::ItemKind; use rustc_data_structures::unord::UnordSet; @@ -15,13 +17,12 @@ use rustc_hir::{Node, PatKind, TyKind}; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::middle::privacy::Level; use rustc_middle::query::Providers; -use rustc_middle::ty::{self, AssocItemContainer, TyCtxt}; +use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_session::lint; use rustc_session::lint::builtin::DEAD_CODE; use rustc_span::symbol::{sym, Symbol}; use rustc_target::abi::FieldIdx; -use std::mem; use crate::errors::{ ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment, @@ -43,63 +44,16 @@ fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { ) } -struct Publicness { - ty_is_public: bool, - ty_and_all_fields_are_public: bool, -} - -impl Publicness { - fn new(ty_is_public: bool, ty_and_all_fields_are_public: bool) -> Self { - Self { ty_is_public, ty_and_all_fields_are_public } - } -} - -fn struct_all_fields_are_public(tcx: TyCtxt<'_>, id: DefId) -> bool { - // treat PhantomData and positional ZST as public, - // we don't want to lint types which only have them, - // cause it's a common way to use such types to check things like well-formedness - tcx.adt_def(id).all_fields().all(|field| { - let field_type = tcx.type_of(field.did).instantiate_identity(); - if field_type.is_phantom_data() { - return true; - } - let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit()); - if is_positional - && tcx - .layout_of(tcx.param_env(field.did).and(field_type)) - .map_or(true, |layout| layout.is_zst()) - { - return true; - } - field.vis.is_public() - }) -} - -/// check struct and its fields are public or not, -/// for enum and union, just check they are public, -/// and doesn't solve types like &T for now, just skip them -fn ty_ref_to_pub_struct(tcx: TyCtxt<'_>, ty: &hir::Ty<'_>) -> Publicness { +fn ty_ref_to_pub_struct(tcx: TyCtxt<'_>, ty: &hir::Ty<'_>) -> bool { if let TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind && let Res::Def(def_kind, def_id) = path.res && def_id.is_local() + && matches!(def_kind, DefKind::Struct | DefKind::Enum | DefKind::Union) { - return match def_kind { - DefKind::Enum | DefKind::Union => { - let ty_is_public = tcx.visibility(def_id).is_public(); - Publicness::new(ty_is_public, ty_is_public) - } - DefKind::Struct => { - let ty_is_public = tcx.visibility(def_id).is_public(); - Publicness::new( - ty_is_public, - ty_is_public && struct_all_fields_are_public(tcx, def_id), - ) - } - _ => Publicness::new(true, true), - }; + tcx.visibility(def_id).is_public() + } else { + true } - - Publicness::new(true, true) } /// Determine if a work from the worklist is coming from a `#[allow]` @@ -155,10 +109,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { fn handle_res(&mut self, res: Res) { match res { - Res::Def( - DefKind::Const | DefKind::AssocConst | DefKind::AssocTy | DefKind::TyAlias, - def_id, - ) => { + Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::TyAlias, def_id) => { self.check_def_id(def_id); } _ if self.in_pat => {} @@ -277,10 +228,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { pats: &[hir::PatField<'_>], ) { let variant = match self.typeck_results().node_type(lhs.hir_id).kind() { - ty::Adt(adt, _) => { - self.check_def_id(adt.did()); - adt.variant_of_res(res) - } + ty::Adt(adt, _) => adt.variant_of_res(res), _ => span_bug!(lhs.span, "non-ADT in struct pattern"), }; for pat in pats { @@ -300,10 +248,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { dotdot: hir::DotDotPos, ) { let variant = match self.typeck_results().node_type(lhs.hir_id).kind() { - ty::Adt(adt, _) => { - self.check_def_id(adt.did()); - adt.variant_of_res(res) - } + ty::Adt(adt, _) => adt.variant_of_res(res), _ => { self.tcx.dcx().span_delayed_bug(lhs.span, "non-ADT in tuple struct pattern"); return; @@ -408,6 +353,31 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { return false; } + // don't ignore impls for Enums and pub Structs whose methods don't have self receiver, + // cause external crate may call such methods to construct values of these types + if let Some(local_impl_of) = impl_of.as_local() + && let Some(local_def_id) = def_id.as_local() + && let Some(fn_sig) = + self.tcx.hir().fn_sig_by_hir_id(self.tcx.local_def_id_to_hir_id(local_def_id)) + && matches!(fn_sig.decl.implicit_self, hir::ImplicitSelfKind::None) + && let TyKind::Path(hir::QPath::Resolved(_, path)) = + self.tcx.hir().expect_item(local_impl_of).expect_impl().self_ty.kind + && let Res::Def(def_kind, did) = path.res + { + match def_kind { + // for example, #[derive(Default)] pub struct T(i32); + // external crate can call T::default() to construct T, + // so that don't ignore impl Default for pub Enum and Structs + DefKind::Struct | DefKind::Union if self.tcx.visibility(did).is_public() => { + return false; + } + // don't ignore impl Default for Enums, + // cause we don't know which variant is constructed + DefKind::Enum => return false, + _ => (), + }; + } + if let Some(trait_of) = self.tcx.trait_id_of_impl(impl_of) && self.tcx.has_attr(trait_of, sym::rustc_trivial_field_reads) { @@ -450,7 +420,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { intravisit::walk_item(self, item) } hir::ItemKind::ForeignMod { .. } => {} - hir::ItemKind::Trait(_, _, _, _, trait_item_refs) => { + hir::ItemKind::Trait(..) => { for impl_def_id in self.tcx.all_impls(item.owner_id.to_def_id()) { if let Some(local_def_id) = impl_def_id.as_local() && let ItemKind::Impl(impl_ref) = @@ -463,12 +433,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { intravisit::walk_path(self, impl_ref.of_trait.unwrap().path); } } - // mark assoc ty live if the trait is live - for trait_item in trait_item_refs { - if let hir::AssocItemKind::Type = trait_item.kind { - self.check_def_id(trait_item.id.owner_id.to_def_id()); - } - } + intravisit::walk_item(self, item) } _ => intravisit::walk_item(self, item), @@ -485,12 +450,11 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { && let ItemKind::Impl(impl_ref) = self.tcx.hir().expect_item(local_impl_id).kind { - if !ty_ref_to_pub_struct(self.tcx, impl_ref.self_ty) - .ty_and_all_fields_are_public + if !matches!(trait_item.kind, hir::TraitItemKind::Type(..)) + && !ty_ref_to_pub_struct(self.tcx, impl_ref.self_ty) { - // skip impl-items of non pure pub ty, - // cause we don't know the ty is constructed or not, - // check these later in `solve_rest_impl_items` + // skip methods of private ty, + // they would be solved in `solve_rest_impl_items` continue; } @@ -571,21 +535,22 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { && let Some(local_def_id) = def_id.as_local() && matches!(def_kind, DefKind::Struct | DefKind::Enum | DefKind::Union) { + if self.tcx.visibility(impl_item_id).is_public() { + // for the public method, we don't know the trait item is used or not, + // so we mark the method live if the self is used + return self.live_symbols.contains(&local_def_id); + } + if let Some(trait_item_id) = self.tcx.associated_item(impl_item_id).trait_item_def_id && let Some(local_id) = trait_item_id.as_local() { - // for the local impl item, we can know the trait item is used or not, + // for the private method, we can know the trait item is used or not, // so we mark the method live if the self is used and the trait item is used - self.live_symbols.contains(&local_id) && self.live_symbols.contains(&local_def_id) - } else { - // for the foreign method and inherent pub method, - // we don't know the trait item or the method is used or not, - // so we mark the method live if the self is used - self.live_symbols.contains(&local_def_id) + return self.live_symbols.contains(&local_id) + && self.live_symbols.contains(&local_def_id); } - } else { - false } + false } } @@ -671,9 +636,6 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> { self.handle_field_pattern_match(pat, res, fields); } PatKind::Path(ref qpath) => { - if let ty::Adt(adt, _) = self.typeck_results().node_type(pat.hir_id).kind() { - self.check_def_id(adt.did()); - } let res = self.typeck_results().qpath_res(qpath, pat.hir_id); self.handle_res(res); } @@ -810,9 +772,7 @@ fn check_item<'tcx>( .iter() .filter_map(|def_id| def_id.as_local()); - let self_ty = tcx.hir().item(id).expect_impl().self_ty; - let Publicness { ty_is_public, ty_and_all_fields_are_public } = - ty_ref_to_pub_struct(tcx, self_ty); + let ty_is_pub = ty_ref_to_pub_struct(tcx, tcx.hir().item(id).expect_impl().self_ty); // And we access the Map here to get HirId from LocalDefId for local_def_id in local_def_ids { @@ -828,19 +788,18 @@ fn check_item<'tcx>( // for trait impl blocks, // mark the method live if the self_ty is public, // or the method is public and may construct self - if tcx.visibility(local_def_id).is_public() - && (ty_and_all_fields_are_public || (ty_is_public && may_construct_self)) + if of_trait + && (!matches!(tcx.def_kind(local_def_id), DefKind::AssocFn) + || tcx.visibility(local_def_id).is_public() + && (ty_is_pub || may_construct_self)) { - // if the impl item is public, - // and the ty may be constructed or can be constructed in foreign crates, - // mark the impl item live worklist.push((local_def_id, ComesFromAllowExpect::No)); } else if let Some(comes_from_allow) = has_allow_dead_code_or_lang_attr(tcx, local_def_id) { worklist.push((local_def_id, comes_from_allow)); - } else if of_trait || tcx.visibility(local_def_id).is_public() && ty_is_public { - // private impl items of traits || public impl items not constructs self + } else if of_trait { + // private method || public method not constructs self unsolved_impl_items.push((id, local_def_id)); } } @@ -866,13 +825,10 @@ fn check_trait_item( worklist: &mut Vec<(LocalDefId, ComesFromAllowExpect)>, id: hir::TraitItemId, ) { - use hir::TraitItemKind::{Const, Fn, Type}; - if matches!( - tcx.def_kind(id.owner_id), - DefKind::AssocConst | DefKind::AssocTy | DefKind::AssocFn - ) { + use hir::TraitItemKind::{Const, Fn}; + if matches!(tcx.def_kind(id.owner_id), DefKind::AssocConst | DefKind::AssocFn) { let trait_item = tcx.hir().trait_item(id); - if matches!(trait_item.kind, Const(_, Some(_)) | Type(_, Some(_)) | Fn(..)) + if matches!(trait_item.kind, Const(_, Some(_)) | Fn(..)) && let Some(comes_from_allow) = has_allow_dead_code_or_lang_attr(tcx, trait_item.owner_id.def_id) { @@ -910,14 +866,6 @@ fn create_and_seed_worklist( effective_vis .is_public_at_level(Level::Reachable) .then_some(id) - .filter(|&id| - // checks impls, impl-items and pub structs with all public fields later - match tcx.def_kind(id) { - DefKind::Impl { .. } => false, - DefKind::AssocConst | DefKind::AssocTy | DefKind::AssocFn => !matches!(tcx.associated_item(id).container, AssocItemContainer::ImplContainer), - DefKind::Struct => struct_all_fields_are_public(tcx, id.to_def_id()) || has_allow_dead_code_or_lang_attr(tcx, id).is_some(), - _ => true - }) .map(|id| (id, ComesFromAllowExpect::No)) }) // Seed entry point @@ -1201,7 +1149,6 @@ impl<'tcx> DeadVisitor<'tcx> { } match self.tcx.def_kind(def_id) { DefKind::AssocConst - | DefKind::AssocTy | DefKind::AssocFn | DefKind::Fn | DefKind::Static { .. } @@ -1243,14 +1190,10 @@ fn check_mod_deathness(tcx: TyCtxt<'_>, module: LocalModDefId) { || (def_kind == DefKind::Trait && live_symbols.contains(&item.owner_id.def_id)) { for &def_id in tcx.associated_item_def_ids(item.owner_id.def_id) { - // We have diagnosed unused assocs in traits + // We have diagnosed unused methods in traits if matches!(def_kind, DefKind::Impl { of_trait: true }) - && matches!(tcx.def_kind(def_id), DefKind::AssocConst | DefKind::AssocTy | DefKind::AssocFn) - // skip unused public inherent methods, - // cause we have diagnosed unconstructed struct - || matches!(def_kind, DefKind::Impl { of_trait: false }) - && tcx.visibility(def_id).is_public() - && ty_ref_to_pub_struct(tcx, tcx.hir().item(item).expect_impl().self_ty).ty_is_public + && tcx.def_kind(def_id) == DefKind::AssocFn + || def_kind == DefKind::Trait && tcx.def_kind(def_id) != DefKind::AssocFn { continue; } diff --git a/compiler/rustc_passes/src/debugger_visualizer.rs b/compiler/rustc_passes/src/debugger_visualizer.rs index 96893e585491f..0537d3a69f6dc 100644 --- a/compiler/rustc_passes/src/debugger_visualizer.rs +++ b/compiler/rustc_passes/src/debugger_visualizer.rs @@ -3,11 +3,9 @@ use rustc_ast::Attribute; use rustc_data_structures::sync::Lrc; use rustc_expand::base::resolve_path; -use rustc_middle::{ - middle::debugger_visualizer::{DebuggerVisualizerFile, DebuggerVisualizerType}, - query::{LocalCrate, Providers}, - ty::TyCtxt, -}; +use rustc_middle::middle::debugger_visualizer::{DebuggerVisualizerFile, DebuggerVisualizerType}; +use rustc_middle::query::{LocalCrate, Providers}; +use rustc_middle::ty::TyCtxt; use rustc_session::Session; use rustc_span::sym; diff --git a/compiler/rustc_passes/src/diagnostic_items.rs b/compiler/rustc_passes/src/diagnostic_items.rs index 906ecdfe5abae..659281c5e711f 100644 --- a/compiler/rustc_passes/src/diagnostic_items.rs +++ b/compiler/rustc_passes/src/diagnostic_items.rs @@ -12,8 +12,7 @@ use rustc_ast as ast; use rustc_hir::diagnostic_items::DiagnosticItems; use rustc_hir::OwnerId; -use rustc_middle::query::LocalCrate; -use rustc_middle::query::Providers; +use rustc_middle::query::{LocalCrate, Providers}; use rustc_middle::ty::TyCtxt; use rustc_span::def_id::{DefId, LOCAL_CRATE}; use rustc_span::symbol::{sym, Symbol}; diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index b43c8282db1db..48f55d4c3a0d5 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -6,8 +6,8 @@ use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; use rustc_hir::{ItemId, Node, CRATE_HIR_ID}; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; -use rustc_session::config::{sigpipe, CrateType, EntryFnType}; -use rustc_session::{config::RemapPathScopeComponents, RemapFileNameExt}; +use rustc_session::config::{sigpipe, CrateType, EntryFnType, RemapPathScopeComponents}; +use rustc_session::RemapFileNameExt; use rustc_span::symbol::sym; use rustc_span::{Span, Symbol}; diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 58d27d5b4bbaa..36dfc40e7628b 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1,13 +1,11 @@ -use std::{ - io::Error, - path::{Path, PathBuf}, -}; +use std::io::Error; +use std::path::{Path, PathBuf}; -use crate::fluent_generated as fluent; use rustc_ast::Label; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, Applicability, Diag, DiagCtxtHandle, DiagSymbolList, Diagnostic, EmissionGuarantee, - Level, MultiSpan, SubdiagMessageOp, Subdiagnostic, + Applicability, Diag, DiagCtxtHandle, DiagSymbolList, Diagnostic, EmissionGuarantee, Level, + MultiSpan, SubdiagMessageOp, Subdiagnostic, }; use rustc_hir::{self as hir, ExprKind, Target}; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; @@ -15,6 +13,7 @@ use rustc_middle::ty::{MainDefinition, Ty}; use rustc_span::{Span, Symbol, DUMMY_SP}; use crate::check_attr::ProcMacroKind; +use crate::fluent_generated as fluent; use crate::lang_items::Duplicate; #[derive(LintDiagnostic)] @@ -69,6 +68,10 @@ pub struct CoverageNotFnOrClosure { pub defn_span: Span, } +#[derive(LintDiagnostic)] +#[diag(passes_optimize_not_fn_or_closure)] +pub struct OptimizeNotFnOrClosure; + #[derive(Diagnostic)] #[diag(passes_should_be_applied_to_fn)] pub struct AttrShouldBeAppliedToFn { @@ -79,13 +82,6 @@ pub struct AttrShouldBeAppliedToFn { pub on_crate: bool, } -#[derive(Diagnostic)] -#[diag(passes_naked_tracked_caller, code = E0736)] -pub struct NakedTrackedCaller { - #[primary_span] - pub attr_span: Span, -} - #[derive(Diagnostic)] #[diag(passes_should_be_applied_to_fn, code = E0739)] pub struct TrackedCallerWrongLocation { @@ -640,6 +636,13 @@ pub struct Confusables { pub attr_span: Span, } +#[derive(Diagnostic)] +#[diag(passes_coroutine_on_non_closure)] +pub struct CoroutineOnNonClosure { + #[primary_span] + pub span: Span, +} + #[derive(Diagnostic)] #[diag(passes_empty_confusables)] pub(crate) struct EmptyConfusables { @@ -1124,13 +1127,6 @@ pub struct UnlabeledCfInWhileCondition<'a> { pub cf_type: &'a str, } -#[derive(Diagnostic)] -#[diag(passes_cannot_inline_naked_function)] -pub struct CannotInlineNakedFunction { - #[primary_span] - pub span: Span, -} - #[derive(LintDiagnostic)] #[diag(passes_undefined_naked_function_abi)] pub struct UndefinedNakedFunctionAbi; @@ -1196,6 +1192,17 @@ pub struct NakedFunctionsMustUseNoreturn { pub last_span: Span, } +#[derive(Diagnostic)] +#[diag(passes_naked_functions_incompatible_attribute, code = E0736)] +pub struct NakedFunctionIncompatibleAttribute { + #[primary_span] + #[label] + pub span: Span, + #[label(passes_naked_attribute)] + pub naked_span: Span, + pub attr: Symbol, +} + #[derive(Diagnostic)] #[diag(passes_attr_only_in_functions)] pub struct AttrOnlyInFunctions { diff --git a/compiler/rustc_passes/src/hir_stats.rs b/compiler/rustc_passes/src/hir_stats.rs index fb7529d93ed91..38e8c3cd12de4 100644 --- a/compiler/rustc_passes/src/hir_stats.rs +++ b/compiler/rustc_passes/src/hir_stats.rs @@ -2,13 +2,11 @@ // pieces of AST and HIR. The resulting numbers are good approximations but not // completely accurate (some things might be counted twice, others missed). -use rustc_ast::visit as ast_visit; use rustc_ast::visit::BoundKind; -use rustc_ast::{self as ast, AttrId, NodeId}; +use rustc_ast::{self as ast, visit as ast_visit, AttrId, NodeId}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; -use rustc_hir::intravisit as hir_visit; -use rustc_hir::HirId; +use rustc_hir::{intravisit as hir_visit, HirId}; use rustc_middle::hir::map::Map; use rustc_middle::ty::TyCtxt; use rustc_middle::util::common::to_readable_str; diff --git a/compiler/rustc_passes/src/lang_items.rs b/compiler/rustc_passes/src/lang_items.rs index b3722e99e1684..3f1be87a73f7f 100644 --- a/compiler/rustc_passes/src/lang_items.rs +++ b/compiler/rustc_passes/src/lang_items.rs @@ -7,23 +7,22 @@ //! * Traits that represent operators; e.g., `Add`, `Sub`, `Index`. //! * Functions called by the compiler itself. -use crate::errors::{ - DuplicateLangItem, IncorrectTarget, LangItemOnIncorrectTarget, UnknownLangItem, -}; -use crate::weak_lang_items; - use rustc_ast as ast; use rustc_ast::visit; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::{extract, GenericRequirement}; use rustc_hir::{LangItem, LanguageItems, MethodKind, Target}; +use rustc_middle::query::Providers; use rustc_middle::ty::{ResolverAstLowering, TyCtxt}; use rustc_session::cstore::ExternCrate; use rustc_span::symbol::kw::Empty; use rustc_span::Span; -use rustc_middle::query::Providers; +use crate::errors::{ + DuplicateLangItem, IncorrectTarget, LangItemOnIncorrectTarget, UnknownLangItem, +}; +use crate::weak_lang_items; pub(crate) enum Duplicate { Plain, diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index 6f59c782e0654..e1bc770d81731 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -9,7 +9,8 @@ use rustc_span::symbol::sym; use rustc_span::Span; use rustc_target::abi::{HasDataLayout, TargetDataLayout}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; -use rustc_trait_selection::{infer::TyCtxtInferExt, traits}; +use rustc_trait_selection::infer::TyCtxtInferExt; +use rustc_trait_selection::traits; use crate::errors::{ LayoutAbi, LayoutAlign, LayoutHomogeneousAggregate, LayoutInvalidAttribute, LayoutOf, diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index dfa7dfa339817..d3b85da4630ef 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -81,10 +81,9 @@ //! We generate various special nodes for various, well, special purposes. //! These are described in the `Liveness` struct. -use crate::errors; - -use self::LiveNodeKind::*; -use self::VarKind::*; +use std::io; +use std::io::prelude::*; +use std::rc::Rc; use rustc_data_structures::fx::FxIndexMap; use rustc_hir as hir; @@ -99,11 +98,12 @@ use rustc_middle::ty::{self, RootVariableMinCaptureList, Ty, TyCtxt}; use rustc_session::lint; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::{BytePos, Span}; -use std::io; -use std::io::prelude::*; -use std::rc::Rc; use tracing::{debug, instrument}; +use self::LiveNodeKind::*; +use self::VarKind::*; +use crate::errors; + mod rwu_table; rustc_index::newtype_index! { diff --git a/compiler/rustc_passes/src/liveness/rwu_table.rs b/compiler/rustc_passes/src/liveness/rwu_table.rs index 053bf5c234acf..6e2f976e5b08f 100644 --- a/compiler/rustc_passes/src/liveness/rwu_table.rs +++ b/compiler/rustc_passes/src/liveness/rwu_table.rs @@ -1,6 +1,7 @@ -use crate::liveness::{LiveNode, Variable}; use std::iter; +use crate::liveness::{LiveNode, Variable}; + #[derive(Clone, Copy)] pub(super) struct RWU { pub(super) reader: bool, diff --git a/compiler/rustc_passes/src/loops.rs b/compiler/rustc_passes/src/loops.rs index 2587a18b8c897..25115c5cafd89 100644 --- a/compiler/rustc_passes/src/loops.rs +++ b/compiler/rustc_passes/src/loops.rs @@ -1,6 +1,5 @@ use std::collections::BTreeMap; use std::fmt; -use Context::*; use rustc_hir as hir; use rustc_hir::def_id::{LocalDefId, LocalModDefId}; @@ -13,6 +12,7 @@ use rustc_middle::ty::TyCtxt; use rustc_session::Session; use rustc_span::hygiene::DesugaringKind; use rustc_span::{BytePos, Span}; +use Context::*; use crate::errors::{ BreakInsideClosure, BreakInsideCoroutine, BreakNonLoop, ContinueLabeledBlock, OutsideLoop, diff --git a/compiler/rustc_passes/src/naked_functions.rs b/compiler/rustc_passes/src/naked_functions.rs index d45ee32a624de..b72ce239c4a96 100644 --- a/compiler/rustc_passes/src/naked_functions.rs +++ b/compiler/rustc_passes/src/naked_functions.rs @@ -14,9 +14,8 @@ use rustc_span::Span; use rustc_target::spec::abi::Abi; use crate::errors::{ - CannotInlineNakedFunction, NakedFunctionsAsmBlock, NakedFunctionsAsmOptions, - NakedFunctionsMustUseNoreturn, NakedFunctionsOperands, NoPatterns, ParamsNotAllowed, - UndefinedNakedFunctionAbi, + NakedFunctionsAsmBlock, NakedFunctionsAsmOptions, NakedFunctionsMustUseNoreturn, + NakedFunctionsOperands, NoPatterns, ParamsNotAllowed, UndefinedNakedFunctionAbi, }; pub(crate) fn provide(providers: &mut Providers) { @@ -53,15 +52,6 @@ fn check_mod_naked_functions(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) { check_no_patterns(tcx, body.params); check_no_parameters_use(tcx, body); check_asm(tcx, def_id, body); - check_inline(tcx, def_id); - } -} - -/// Check that the function isn't inlined. -fn check_inline(tcx: TyCtxt<'_>, def_id: LocalDefId) { - let attrs = tcx.get_attrs(def_id, sym::inline); - for attr in attrs { - tcx.dcx().emit_err(CannotInlineNakedFunction { span: attr.span }); } } @@ -244,22 +234,16 @@ impl<'tcx> CheckInlineAssembly<'tcx> { self.tcx.dcx().emit_err(NakedFunctionsOperands { unsupported_operands }); } - let unsupported_options: Vec<&'static str> = [ - (InlineAsmOptions::MAY_UNWIND, "`may_unwind`"), - (InlineAsmOptions::NOMEM, "`nomem`"), - (InlineAsmOptions::NOSTACK, "`nostack`"), - (InlineAsmOptions::PRESERVES_FLAGS, "`preserves_flags`"), - (InlineAsmOptions::PURE, "`pure`"), - (InlineAsmOptions::READONLY, "`readonly`"), - ] - .iter() - .filter_map(|&(option, name)| if asm.options.contains(option) { Some(name) } else { None }) - .collect(); - + let unsupported_options = asm.options.difference(InlineAsmOptions::NAKED_OPTIONS); if !unsupported_options.is_empty() { self.tcx.dcx().emit_err(NakedFunctionsAsmOptions { span, - unsupported_options: unsupported_options.join(", "), + unsupported_options: unsupported_options + .human_readable_names() + .into_iter() + .map(|name| format!("`{name}`")) + .collect::>() + .join(", "), }); } diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 2c34f477de5c5..4d58590ca3b0e 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -1,7 +1,9 @@ //! A pass that annotates every item and method with its stability level, //! propagating default levels lexically from parent to children ast nodes. -use crate::errors; +use std::mem::replace; +use std::num::NonZero; + use rustc_attr::{ self as attr, ConstStability, DeprecatedSince, Stability, StabilityLevel, StableSince, Unstable, UnstableReason, VERSION_PLACEHOLDER, @@ -25,10 +27,10 @@ use rustc_session::lint::builtin::{INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPR use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; use rustc_target::spec::abi::Abi; -use std::mem::replace; -use std::num::NonZero; use tracing::{debug, info}; +use crate::errors; + #[derive(PartialEq)] enum AnnotationKind { /// Annotation is required if not inherited from unstable parents. diff --git a/compiler/rustc_pattern_analysis/src/constructor.rs b/compiler/rustc_pattern_analysis/src/constructor.rs index f3e8e547066c8..3a2a75a638f79 100644 --- a/compiler/rustc_pattern_analysis/src/constructor.rs +++ b/compiler/rustc_pattern_analysis/src/constructor.rs @@ -180,16 +180,14 @@ use std::cmp::{self, max, min, Ordering}; use std::fmt; use std::iter::once; -use smallvec::SmallVec; - use rustc_apfloat::ieee::{DoubleS, HalfS, IeeeFloat, QuadS, SingleS}; use rustc_index::bit_set::{BitSet, GrowableBitSet}; use rustc_index::IndexVec; +use smallvec::SmallVec; use self::Constructor::*; use self::MaybeInfiniteInt::*; use self::SliceKind::*; - use crate::PatCx; /// Whether we have seen a constructor in the column or not. diff --git a/compiler/rustc_pattern_analysis/src/errors.rs b/compiler/rustc_pattern_analysis/src/errors.rs index 27f227e6d9c11..1f7852e5190d2 100644 --- a/compiler/rustc_pattern_analysis/src/errors.rs +++ b/compiler/rustc_pattern_analysis/src/errors.rs @@ -1,6 +1,5 @@ use rustc_errors::{Diag, EmissionGuarantee, SubdiagMessageOp, Subdiagnostic}; use rustc_macros::{LintDiagnostic, Subdiagnostic}; -use rustc_middle::thir::Pat; use rustc_middle::ty::Ty; use rustc_span::Span; @@ -8,18 +7,18 @@ use crate::rustc::{RustcPatCtxt, WitnessPat}; #[derive(Subdiagnostic)] #[label(pattern_analysis_uncovered)] -pub struct Uncovered<'tcx> { +pub struct Uncovered { #[primary_span] span: Span, count: usize, - witness_1: Pat<'tcx>, - witness_2: Pat<'tcx>, - witness_3: Pat<'tcx>, + witness_1: String, // a printed pattern + witness_2: String, // a printed pattern + witness_3: String, // a printed pattern remainder: usize, } -impl<'tcx> Uncovered<'tcx> { - pub fn new<'p>( +impl Uncovered { + pub fn new<'p, 'tcx>( span: Span, cx: &RustcPatCtxt<'p, 'tcx>, witnesses: Vec>, @@ -27,19 +26,13 @@ impl<'tcx> Uncovered<'tcx> { where 'tcx: 'p, { - let witness_1 = cx.hoist_witness_pat(witnesses.get(0).unwrap()); + let witness_1 = cx.print_witness_pat(witnesses.get(0).unwrap()); Self { span, count: witnesses.len(), // Substitute dummy values if witnesses is smaller than 3. These will never be read. - witness_2: witnesses - .get(1) - .map(|w| cx.hoist_witness_pat(w)) - .unwrap_or_else(|| witness_1.clone()), - witness_3: witnesses - .get(2) - .map(|w| cx.hoist_witness_pat(w)) - .unwrap_or_else(|| witness_1.clone()), + witness_2: witnesses.get(1).map(|w| cx.print_witness_pat(w)).unwrap_or_default(), + witness_3: witnesses.get(2).map(|w| cx.print_witness_pat(w)).unwrap_or_default(), witness_1, remainder: witnesses.len().saturating_sub(3), } @@ -49,19 +42,19 @@ impl<'tcx> Uncovered<'tcx> { #[derive(LintDiagnostic)] #[diag(pattern_analysis_overlapping_range_endpoints)] #[note] -pub struct OverlappingRangeEndpoints<'tcx> { +pub struct OverlappingRangeEndpoints { #[label] pub range: Span, #[subdiagnostic] - pub overlap: Vec>, + pub overlap: Vec, } -pub struct Overlap<'tcx> { +pub struct Overlap { pub span: Span, - pub range: Pat<'tcx>, + pub range: String, // a printed pattern } -impl<'tcx> Subdiagnostic for Overlap<'tcx> { +impl Subdiagnostic for Overlap { fn add_to_diag_with>( self, diag: &mut Diag<'_, G>, @@ -78,38 +71,38 @@ impl<'tcx> Subdiagnostic for Overlap<'tcx> { #[derive(LintDiagnostic)] #[diag(pattern_analysis_excluside_range_missing_max)] -pub struct ExclusiveRangeMissingMax<'tcx> { +pub struct ExclusiveRangeMissingMax { #[label] #[suggestion(code = "{suggestion}", applicability = "maybe-incorrect")] /// This is an exclusive range that looks like `lo..max` (i.e. doesn't match `max`). pub first_range: Span, /// Suggest `lo..=max` instead. pub suggestion: String, - pub max: Pat<'tcx>, + pub max: String, // a printed pattern } #[derive(LintDiagnostic)] #[diag(pattern_analysis_excluside_range_missing_gap)] -pub struct ExclusiveRangeMissingGap<'tcx> { +pub struct ExclusiveRangeMissingGap { #[label] #[suggestion(code = "{suggestion}", applicability = "maybe-incorrect")] /// This is an exclusive range that looks like `lo..gap` (i.e. doesn't match `gap`). pub first_range: Span, - pub gap: Pat<'tcx>, + pub gap: String, // a printed pattern /// Suggest `lo..=gap` instead. pub suggestion: String, #[subdiagnostic] /// All these ranges skipped over `gap` which we think is probably a mistake. - pub gap_with: Vec>, + pub gap_with: Vec, } -pub struct GappedRange<'tcx> { +pub struct GappedRange { pub span: Span, - pub gap: Pat<'tcx>, - pub first_range: Pat<'tcx>, + pub gap: String, // a printed pattern + pub first_range: String, // a printed pattern } -impl<'tcx> Subdiagnostic for GappedRange<'tcx> { +impl Subdiagnostic for GappedRange { fn add_to_diag_with>( self, diag: &mut Diag<'_, G>, @@ -134,7 +127,7 @@ impl<'tcx> Subdiagnostic for GappedRange<'tcx> { pub(crate) struct NonExhaustiveOmittedPattern<'tcx> { pub scrut_ty: Ty<'tcx>, #[subdiagnostic] - pub uncovered: Uncovered<'tcx>, + pub uncovered: Uncovered, } #[derive(LintDiagnostic)] diff --git a/compiler/rustc_pattern_analysis/src/lib.rs b/compiler/rustc_pattern_analysis/src/lib.rs index 1b4bcb789d2da..a5c0b13c90be1 100644 --- a/compiler/rustc_pattern_analysis/src/lib.rs +++ b/compiler/rustc_pattern_analysis/src/lib.rs @@ -1,4 +1,6 @@ -//! Analysis of patterns, notably match exhaustiveness checking. +//! Analysis of patterns, notably match exhaustiveness checking. The main entrypoint for this crate +//! is [`usefulness::compute_match_usefulness`]. For rustc-specific types and entrypoints, see the +//! [`rustc`] module. // tidy-alphabetical-start #![allow(rustc::diagnostic_outside_of_impl)] @@ -23,14 +25,8 @@ use std::fmt; pub use rustc_index::{Idx, IndexVec}; // re-exported to avoid rustc_index version issues -#[cfg(feature = "rustc")] -use rustc_middle::ty::Ty; -#[cfg(feature = "rustc")] -use rustc_span::ErrorGuaranteed; - use crate::constructor::{Constructor, ConstructorSet, IntRange}; use crate::pat::DeconstructedPat; -use crate::pat_column::PatternColumn; pub trait Captures<'a> {} impl<'a, T: ?Sized> Captures<'a> for T {} @@ -128,30 +124,3 @@ impl<'p, Cx: PatCx> Clone for MatchArm<'p, Cx> { } impl<'p, Cx: PatCx> Copy for MatchArm<'p, Cx> {} - -/// The entrypoint for this crate. Computes whether a match is exhaustive and which of its arms are -/// useful, and runs some lints. -#[cfg(feature = "rustc")] -pub fn analyze_match<'p, 'tcx>( - tycx: &rustc::RustcPatCtxt<'p, 'tcx>, - arms: &[rustc::MatchArm<'p, 'tcx>], - scrut_ty: Ty<'tcx>, - pattern_complexity_limit: Option, -) -> Result, ErrorGuaranteed> { - use lints::lint_nonexhaustive_missing_variants; - use usefulness::{compute_match_usefulness, PlaceValidity}; - - let scrut_ty = tycx.reveal_opaque_ty(scrut_ty); - let scrut_validity = PlaceValidity::from_bool(tycx.known_valid_scrutinee); - let report = - compute_match_usefulness(tycx, arms, scrut_ty, scrut_validity, pattern_complexity_limit)?; - - // Run the non_exhaustive_omitted_patterns lint. Only run on refutable patterns to avoid hitting - // `if let`s. Only run if the match is exhaustive otherwise the error is redundant. - if tycx.refutable && report.non_exhaustiveness_witnesses.is_empty() { - let pat_column = PatternColumn::new(arms); - lint_nonexhaustive_missing_variants(tycx, arms, &pat_column, scrut_ty)?; - } - - Ok(report) -} diff --git a/compiler/rustc_pattern_analysis/src/lints.rs b/compiler/rustc_pattern_analysis/src/lints.rs index 892aacd7ac5d9..6bcef0ec879dd 100644 --- a/compiler/rustc_pattern_analysis/src/lints.rs +++ b/compiler/rustc_pattern_analysis/src/lints.rs @@ -1,11 +1,12 @@ +use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS; +use rustc_span::ErrorGuaranteed; +use tracing::instrument; + use crate::constructor::Constructor; use crate::errors::{NonExhaustiveOmittedPattern, NonExhaustiveOmittedPatternLintOnArm, Uncovered}; use crate::pat_column::PatternColumn; use crate::rustc::{RevealedTy, RustcPatCtxt, WitnessPat}; use crate::MatchArm; -use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS; -use rustc_span::ErrorGuaranteed; -use tracing::instrument; /// Traverse the patterns to collect any variants of a non_exhaustive enum that fail to be mentioned /// in a given column. diff --git a/compiler/rustc_pattern_analysis/src/pat.rs b/compiler/rustc_pattern_analysis/src/pat.rs index e8d6c542c5fd4..d91deab160c50 100644 --- a/compiler/rustc_pattern_analysis/src/pat.rs +++ b/compiler/rustc_pattern_analysis/src/pat.rs @@ -5,13 +5,12 @@ use std::fmt; use smallvec::{smallvec, SmallVec}; +use self::Constructor::*; use crate::constructor::{Constructor, Slice, SliceKind}; use crate::{PatCx, PrivateUninhabitedField}; -use self::Constructor::*; - /// A globally unique id to distinguish patterns. -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) struct PatId(u32); impl PatId { fn new() -> Self { @@ -147,6 +146,21 @@ impl fmt::Debug for DeconstructedPat { } } +/// Delegate to `uid`. +impl PartialEq for DeconstructedPat { + fn eq(&self, other: &Self) -> bool { + self.uid == other.uid + } +} +/// Delegate to `uid`. +impl Eq for DeconstructedPat {} +/// Delegate to `uid`. +impl std::hash::Hash for DeconstructedPat { + fn hash(&self, state: &mut H) { + self.uid.hash(state); + } +} + /// Represents either a pattern obtained from user input or a wildcard constructed during the /// algorithm. Do not use `Wild` to represent a wildcard pattern comping from user input. /// diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index 6ef2d69273ee7..6290aeb252312 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -7,7 +7,7 @@ use rustc_hir::HirId; use rustc_index::{Idx, IndexVec}; use rustc_middle::middle::stability::EvalResult; use rustc_middle::mir::{self, Const}; -use rustc_middle::thir::{self, FieldPat, Pat, PatKind, PatRange, PatRangeBoundary}; +use rustc_middle::thir::{self, Pat, PatKind, PatRange, PatRangeBoundary}; use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::{ self, FieldDef, OpaqueTypeKey, ScalarInt, Ty, TyCtxt, TypeVisitableExt, VariantDef, @@ -17,18 +17,24 @@ use rustc_session::lint; use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; use rustc_target::abi::{FieldIdx, Integer, VariantIdx, FIRST_VARIANT}; +use crate::constructor::Constructor::*; use crate::constructor::{ IntRange, MaybeInfiniteInt, OpaqueId, RangeEnd, Slice, SliceKind, VariantVisibility, }; +use crate::lints::lint_nonexhaustive_missing_variants; +use crate::pat_column::PatternColumn; +use crate::usefulness::{compute_match_usefulness, PlaceValidity}; use crate::{errors, Captures, PatCx, PrivateUninhabitedField}; -use crate::constructor::Constructor::*; +mod print; // Re-export rustc-specific versions of all these types. pub type Constructor<'p, 'tcx> = crate::constructor::Constructor>; pub type ConstructorSet<'p, 'tcx> = crate::constructor::ConstructorSet>; pub type DeconstructedPat<'p, 'tcx> = crate::pat::DeconstructedPat>; pub type MatchArm<'p, 'tcx> = crate::MatchArm<'p, RustcPatCtxt<'p, 'tcx>>; +pub type RedundancyExplanation<'p, 'tcx> = + crate::usefulness::RedundancyExplanation<'p, RustcPatCtxt<'p, 'tcx>>; pub type Usefulness<'p, 'tcx> = crate::usefulness::Usefulness<'p, RustcPatCtxt<'p, 'tcx>>; pub type UsefulnessReport<'p, 'tcx> = crate::usefulness::UsefulnessReport<'p, RustcPatCtxt<'p, 'tcx>>; @@ -739,7 +745,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { /// Note: it is possible to get `isize/usize::MAX+1` here, as explained in the doc for /// [`IntRange::split`]. This cannot be represented as a `Const`, so we represent it with /// `PosInfinity`. - pub(crate) fn hoist_pat_range_bdy( + fn hoist_pat_range_bdy( &self, miint: MaybeInfiniteInt, ty: RevealedTy<'tcx>, @@ -769,8 +775,9 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { } } - /// Convert back to a `thir::Pat` for diagnostic purposes. - pub(crate) fn hoist_pat_range(&self, range: &IntRange, ty: RevealedTy<'tcx>) -> Pat<'tcx> { + /// Convert to a [`print::Pat`] for diagnostic purposes. + fn hoist_pat_range(&self, range: &IntRange, ty: RevealedTy<'tcx>) -> print::Pat<'tcx> { + use print::{Pat, PatKind}; use MaybeInfiniteInt::*; let cx = self; let kind = if matches!((range.lo, range.hi), (NegInfinity, PosInfinity)) { @@ -804,11 +811,20 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { PatKind::Range(Box::new(PatRange { lo, hi, end, ty: ty.inner() })) }; - Pat { ty: ty.inner(), span: DUMMY_SP, kind } + Pat { ty: ty.inner(), kind } } - /// Convert back to a `thir::Pat` for diagnostic purposes. This panics for patterns that don't + + /// Prints a [`WitnessPat`] to an owned string, for diagnostic purposes. + pub fn print_witness_pat(&self, pat: &WitnessPat<'p, 'tcx>) -> String { + // This works by converting the witness pattern to a `print::Pat` + // and then printing that, but callers don't need to know that. + self.hoist_witness_pat(pat).to_string() + } + + /// Convert to a [`print::Pat`] for diagnostic purposes. This panics for patterns that don't /// appear in diagnostics, like float ranges. - pub fn hoist_witness_pat(&self, pat: &WitnessPat<'p, 'tcx>) -> Pat<'tcx> { + fn hoist_witness_pat(&self, pat: &WitnessPat<'p, 'tcx>) -> print::Pat<'tcx> { + use print::{FieldPat, Pat, PatKind}; let cx = self; let is_wildcard = |pat: &Pat<'_>| matches!(pat.kind, PatKind::Wild); let mut subpatterns = pat.iter_fields().map(|p| Box::new(cx.hoist_witness_pat(p))); @@ -828,7 +844,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { // the pattern is a box pattern. PatKind::Deref { subpattern: subpatterns.next().unwrap() } } - ty::Adt(adt_def, args) => { + ty::Adt(adt_def, _args) => { let variant_index = RustcPatCtxt::variant_index_for_adt(&pat.ctor(), *adt_def); let subpatterns = subpatterns .enumerate() @@ -836,7 +852,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { .collect(); if adt_def.is_enum() { - PatKind::Variant { adt_def: *adt_def, args, variant_index, subpatterns } + PatKind::Variant { adt_def: *adt_def, variant_index, subpatterns } } else { PatKind::Leaf { subpatterns } } @@ -873,7 +889,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { } } let suffix: Box<[_]> = subpatterns.collect(); - let wild = Pat::wildcard_from_ty(pat.ty().inner()); + let wild = Pat { ty: pat.ty().inner(), kind: PatKind::Wild }; PatKind::Slice { prefix: prefix.into_boxed_slice(), slice: Some(Box::new(wild)), @@ -894,7 +910,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { } }; - Pat { ty: pat.ty().inner(), span: DUMMY_SP, kind } + Pat { ty: pat.ty().inner(), kind } } } @@ -961,7 +977,7 @@ impl<'p, 'tcx: 'p> PatCx for RustcPatCtxt<'p, 'tcx> { let overlaps: Vec<_> = overlaps_with .iter() .map(|pat| pat.data().span) - .map(|span| errors::Overlap { range: overlap_as_pat.clone(), span }) + .map(|span| errors::Overlap { range: overlap_as_pat.to_string(), span }) .collect(); let pat_span = pat.data().span; self.tcx.emit_node_span_lint( @@ -991,12 +1007,11 @@ impl<'p, 'tcx: 'p> PatCx for RustcPatCtxt<'p, 'tcx> { } // `pat` is an exclusive range like `lo..gap`. `gapped_with` contains ranges that start with // `gap+1`. - let suggested_range: thir::Pat<'_> = { + let suggested_range: String = { // Suggest `lo..=gap` instead. - let mut suggested_range = thir_pat.clone(); - let thir::PatKind::Range(range) = &mut suggested_range.kind else { unreachable!() }; - range.end = rustc_hir::RangeEnd::Included; - suggested_range + let mut suggested_range = PatRange::clone(range); + suggested_range.end = rustc_hir::RangeEnd::Included; + suggested_range.to_string() }; let gap_as_pat = self.hoist_pat_range(&gap, *pat.ty()); if gapped_with.is_empty() { @@ -1009,9 +1024,9 @@ impl<'p, 'tcx: 'p> PatCx for RustcPatCtxt<'p, 'tcx> { // Point at this range. first_range: thir_pat.span, // That's the gap that isn't covered. - max: gap_as_pat.clone(), + max: gap_as_pat.to_string(), // Suggest `lo..=max` instead. - suggestion: suggested_range.to_string(), + suggestion: suggested_range, }, ); } else { @@ -1023,17 +1038,17 @@ impl<'p, 'tcx: 'p> PatCx for RustcPatCtxt<'p, 'tcx> { // Point at this range. first_range: thir_pat.span, // That's the gap that isn't covered. - gap: gap_as_pat.clone(), + gap: gap_as_pat.to_string(), // Suggest `lo..=gap` instead. - suggestion: suggested_range.to_string(), + suggestion: suggested_range, // All these ranges skipped over `gap` which we think is probably a // mistake. gap_with: gapped_with .iter() .map(|pat| errors::GappedRange { span: pat.data().span, - gap: gap_as_pat.clone(), - first_range: thir_pat.clone(), + gap: gap_as_pat.to_string(), + first_range: range.to_string(), }) .collect(), }, @@ -1058,3 +1073,26 @@ fn expand_or_pat<'p, 'tcx>(pat: &'p Pat<'tcx>) -> Vec<&'p Pat<'tcx>> { expand(pat, &mut pats); pats } + +/// The entrypoint for this crate. Computes whether a match is exhaustive and which of its arms are +/// useful, and runs some lints. +pub fn analyze_match<'p, 'tcx>( + tycx: &RustcPatCtxt<'p, 'tcx>, + arms: &[MatchArm<'p, 'tcx>], + scrut_ty: Ty<'tcx>, + pattern_complexity_limit: Option, +) -> Result, ErrorGuaranteed> { + let scrut_ty = tycx.reveal_opaque_ty(scrut_ty); + let scrut_validity = PlaceValidity::from_bool(tycx.known_valid_scrutinee); + let report = + compute_match_usefulness(tycx, arms, scrut_ty, scrut_validity, pattern_complexity_limit)?; + + // Run the non_exhaustive_omitted_patterns lint. Only run on refutable patterns to avoid hitting + // `if let`s. Only run if the match is exhaustive otherwise the error is redundant. + if tycx.refutable && report.non_exhaustiveness_witnesses.is_empty() { + let pat_column = PatternColumn::new(arms); + lint_nonexhaustive_missing_variants(tycx, arms, &pat_column, scrut_ty)?; + } + + Ok(report) +} diff --git a/compiler/rustc_pattern_analysis/src/rustc/print.rs b/compiler/rustc_pattern_analysis/src/rustc/print.rs new file mode 100644 index 0000000000000..4b76764e8b136 --- /dev/null +++ b/compiler/rustc_pattern_analysis/src/rustc/print.rs @@ -0,0 +1,193 @@ +//! Pattern analysis sometimes wants to print patterns as part of a user-visible +//! diagnostic. +//! +//! Historically it did so by creating a synthetic [`thir::Pat`](rustc_middle::thir::Pat) +//! and printing that, but doing so was making it hard to modify the THIR pattern +//! representation for other purposes. +//! +//! So this module contains a forked copy of `thir::Pat` that is used _only_ +//! for diagnostics, and has been partly simplified to remove things that aren't +//! needed for printing. + +use std::fmt; + +use rustc_middle::thir::PatRange; +use rustc_middle::ty::{self, AdtDef, Ty}; +use rustc_middle::{bug, mir}; +use rustc_span::sym; +use rustc_target::abi::{FieldIdx, VariantIdx}; + +#[derive(Clone, Debug)] +pub(crate) struct FieldPat<'tcx> { + pub(crate) field: FieldIdx, + pub(crate) pattern: Box>, +} + +#[derive(Clone, Debug)] +pub(crate) struct Pat<'tcx> { + pub(crate) ty: Ty<'tcx>, + pub(crate) kind: PatKind<'tcx>, +} + +#[derive(Clone, Debug)] +pub(crate) enum PatKind<'tcx> { + Wild, + + Variant { + adt_def: AdtDef<'tcx>, + variant_index: VariantIdx, + subpatterns: Vec>, + }, + + Leaf { + subpatterns: Vec>, + }, + + Deref { + subpattern: Box>, + }, + + Constant { + value: mir::Const<'tcx>, + }, + + Range(Box>), + + Slice { + prefix: Box<[Box>]>, + slice: Option>>, + suffix: Box<[Box>]>, + }, + + Never, +} + +impl<'tcx> fmt::Display for Pat<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Printing lists is a chore. + let mut first = true; + let mut start_or_continue = |s| { + if first { + first = false; + "" + } else { + s + } + }; + let mut start_or_comma = || start_or_continue(", "); + + match self.kind { + PatKind::Wild => write!(f, "_"), + PatKind::Never => write!(f, "!"), + PatKind::Variant { ref subpatterns, .. } | PatKind::Leaf { ref subpatterns } => { + let variant_and_name = match self.kind { + PatKind::Variant { adt_def, variant_index, .. } => ty::tls::with(|tcx| { + let variant = adt_def.variant(variant_index); + let adt_did = adt_def.did(); + let name = if tcx.get_diagnostic_item(sym::Option) == Some(adt_did) + || tcx.get_diagnostic_item(sym::Result) == Some(adt_did) + { + variant.name.to_string() + } else { + format!("{}::{}", tcx.def_path_str(adt_def.did()), variant.name) + }; + Some((variant, name)) + }), + _ => self.ty.ty_adt_def().and_then(|adt_def| { + if !adt_def.is_enum() { + ty::tls::with(|tcx| { + Some((adt_def.non_enum_variant(), tcx.def_path_str(adt_def.did()))) + }) + } else { + None + } + }), + }; + + if let Some((variant, name)) = &variant_and_name { + write!(f, "{name}")?; + + // Only for Adt we can have `S {...}`, + // which we handle separately here. + if variant.ctor.is_none() { + write!(f, " {{ ")?; + + let mut printed = 0; + for p in subpatterns { + if let PatKind::Wild = p.pattern.kind { + continue; + } + let name = variant.fields[p.field].name; + write!(f, "{}{}: {}", start_or_comma(), name, p.pattern)?; + printed += 1; + } + + let is_union = self.ty.ty_adt_def().is_some_and(|adt| adt.is_union()); + if printed < variant.fields.len() && (!is_union || printed == 0) { + write!(f, "{}..", start_or_comma())?; + } + + return write!(f, " }}"); + } + } + + let num_fields = + variant_and_name.as_ref().map_or(subpatterns.len(), |(v, _)| v.fields.len()); + if num_fields != 0 || variant_and_name.is_none() { + write!(f, "(")?; + for i in 0..num_fields { + write!(f, "{}", start_or_comma())?; + + // Common case: the field is where we expect it. + if let Some(p) = subpatterns.get(i) { + if p.field.index() == i { + write!(f, "{}", p.pattern)?; + continue; + } + } + + // Otherwise, we have to go looking for it. + if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) { + write!(f, "{}", p.pattern)?; + } else { + write!(f, "_")?; + } + } + write!(f, ")")?; + } + + Ok(()) + } + PatKind::Deref { ref subpattern } => { + match self.ty.kind() { + ty::Adt(def, _) if def.is_box() => write!(f, "box ")?, + ty::Ref(_, _, mutbl) => { + write!(f, "&{}", mutbl.prefix_str())?; + } + _ => bug!("{} is a bad Deref pattern type", self.ty), + } + write!(f, "{subpattern}") + } + PatKind::Constant { value } => write!(f, "{value}"), + PatKind::Range(ref range) => write!(f, "{range}"), + PatKind::Slice { ref prefix, ref slice, ref suffix } => { + write!(f, "[")?; + for p in prefix.iter() { + write!(f, "{}{}", start_or_comma(), p)?; + } + if let Some(ref slice) = *slice { + write!(f, "{}", start_or_comma())?; + match slice.kind { + PatKind::Wild => {} + _ => write!(f, "{slice}")?, + } + write!(f, "..")?; + } + for p in suffix.iter() { + write!(f, "{}{}", start_or_comma(), p)?; + } + write!(f, "]") + } + } + } +} diff --git a/compiler/rustc_pattern_analysis/src/usefulness.rs b/compiler/rustc_pattern_analysis/src/usefulness.rs index 8486792b5543f..9710c9e1303dd 100644 --- a/compiler/rustc_pattern_analysis/src/usefulness.rs +++ b/compiler/rustc_pattern_analysis/src/usefulness.rs @@ -709,35 +709,99 @@ //! I (Nadrieril) prefer to put new tests in `ui/pattern/usefulness` unless there's a specific //! reason not to, for example if they crucially depend on a particular feature like `or_patterns`. -use self::PlaceValidity::*; -use crate::constructor::{Constructor, ConstructorSet, IntRange}; -use crate::pat::{DeconstructedPat, PatId, PatOrWild, WitnessPat}; -use crate::{Captures, MatchArm, PatCx, PrivateUninhabitedField}; -use rustc_hash::FxHashSet; -use rustc_index::bit_set::BitSet; -use smallvec::{smallvec, SmallVec}; use std::fmt; -use tracing::{debug, instrument}; #[cfg(feature = "rustc")] use rustc_data_structures::stack::ensure_sufficient_stack; +use rustc_hash::{FxHashMap, FxHashSet}; +use rustc_index::bit_set::BitSet; +use smallvec::{smallvec, SmallVec}; +use tracing::{debug, instrument}; + +use self::PlaceValidity::*; +use crate::constructor::{Constructor, ConstructorSet, IntRange}; +use crate::pat::{DeconstructedPat, PatId, PatOrWild, WitnessPat}; +use crate::{Captures, MatchArm, PatCx, PrivateUninhabitedField}; #[cfg(not(feature = "rustc"))] pub fn ensure_sufficient_stack(f: impl FnOnce() -> R) -> R { f() } +/// A pattern is a "branch" if it is the immediate child of an or-pattern, or if it is the whole +/// pattern of a match arm. These are the patterns that can be meaningfully considered "redundant", +/// since e.g. `0` in `(0, 1)` cannot be redundant on its own. +/// +/// We track for each branch pattern whether it is useful, and if not why. +struct BranchPatUsefulness<'p, Cx: PatCx> { + /// Whether this pattern is useful. + useful: bool, + /// A set of patterns that: + /// - come before this one in the match; + /// - intersect this one; + /// - at the end of the algorithm, if `!self.useful`, their union covers this pattern. + covered_by: FxHashSet<&'p DeconstructedPat>, +} + +impl<'p, Cx: PatCx> BranchPatUsefulness<'p, Cx> { + /// Update `self` with the usefulness information found in `row`. + fn update(&mut self, row: &MatrixRow<'p, Cx>, matrix: &Matrix<'p, Cx>) { + self.useful |= row.useful; + // This deserves an explanation: `intersects_at_least` does not contain all intersections + // because we skip irrelevant values (see the docs for `intersects_at_least` for an + // example). Yet we claim this suffices to build a covering set. + // + // Let `p` be our pattern. Assume it is found not useful. For a value `v`, if the value was + // relevant then we explored that value and found that there was another pattern `q` before + // `p` that matches it too. We therefore recorded an intersection with `q`. If `v` was + // irrelevant, we know there's another value `v2` that matches strictly fewer rows (while + // still matching our row) and is relevant. Since `p` is not useful, there must have been a + // `q` before `p` that matches `v2`, and we recorded that intersection. Since `v2` matches + // strictly fewer rows than `v`, `q` also matches `v`. In either case, we recorded in + // `intersects_at_least` a pattern that matches `v`. Hence using `intersects_at_least` is + // sufficient to build a covering set. + for row_id in row.intersects_at_least.iter() { + let row = &matrix.rows[row_id]; + if row.useful && !row.is_under_guard { + if let PatOrWild::Pat(intersecting) = row.head() { + self.covered_by.insert(intersecting); + } + } + } + } + + /// Check whether this pattern is redundant, and if so explain why. + fn is_redundant(&self) -> Option> { + if self.useful { + None + } else { + // We avoid instability by sorting by `uid`. The order of `uid`s only depends on the + // pattern structure. + #[cfg_attr(feature = "rustc", allow(rustc::potential_query_instability))] + let mut covered_by: Vec<_> = self.covered_by.iter().copied().collect(); + covered_by.sort_by_key(|pat| pat.uid); // sort to avoid instability + Some(RedundancyExplanation { covered_by }) + } + } +} + +impl<'p, Cx: PatCx> Default for BranchPatUsefulness<'p, Cx> { + fn default() -> Self { + Self { useful: Default::default(), covered_by: Default::default() } + } +} + /// Context that provides information for usefulness checking. -struct UsefulnessCtxt<'a, Cx: PatCx> { +struct UsefulnessCtxt<'a, 'p, Cx: PatCx> { /// The context for type information. tycx: &'a Cx, - /// Collect the patterns found useful during usefulness checking. This is used to lint - /// unreachable (sub)patterns. - useful_subpatterns: FxHashSet, + /// Track information about the usefulness of branch patterns (see definition of "branch + /// pattern" at [`BranchPatUsefulness`]). + branch_usefulness: FxHashMap>, complexity_limit: Option, complexity_level: usize, } -impl<'a, Cx: PatCx> UsefulnessCtxt<'a, Cx> { +impl<'a, 'p, Cx: PatCx> UsefulnessCtxt<'a, 'p, Cx> { fn increase_complexity_level(&mut self, complexity_add: usize) -> Result<(), Cx::Error> { self.complexity_level += complexity_add; if self @@ -1051,14 +1115,40 @@ struct MatrixRow<'p, Cx: PatCx> { /// [`compute_exhaustiveness_and_usefulness`] if the arm is found to be useful. /// This is reset to `false` when specializing. useful: bool, - /// Tracks which rows above this one have an intersection with this one, i.e. such that there is - /// a value that matches both rows. - /// Note: Because of relevancy we may miss some intersections. The intersections we do find are - /// correct. - intersects: BitSet, + /// Tracks some rows above this one that have an intersection with this one, i.e. such that + /// there is a value that matches both rows. + /// Because of relevancy we may miss some intersections. The intersections we do find are + /// correct. In other words, this is an underapproximation of the real set of intersections. + /// + /// For example: + /// ```rust,ignore(illustrative) + /// match ... { + /// (true, _, _) => {} // `intersects_at_least = []` + /// (_, true, 0..=10) => {} // `intersects_at_least = []` + /// (_, true, 5..15) => {} // `intersects_at_least = [1]` + /// } + /// ``` + /// Here the `(true, true)` case is irrelevant. Since we skip it, we will not detect that row 0 + /// intersects rows 1 and 2. + intersects_at_least: BitSet, + /// Whether the head pattern is a branch (see definition of "branch pattern" at + /// [`BranchPatUsefulness`]) + head_is_branch: bool, } impl<'p, Cx: PatCx> MatrixRow<'p, Cx> { + fn new(arm: &MatchArm<'p, Cx>, arm_id: usize) -> Self { + MatrixRow { + pats: PatStack::from_pattern(arm.pat), + parent_row: arm_id, + is_under_guard: arm.has_guard, + useful: false, + intersects_at_least: BitSet::new_empty(0), // Initialized in `Matrix::push`. + // This pattern is a branch because it comes from a match arm. + head_is_branch: true, + } + } + fn len(&self) -> usize { self.pats.len() } @@ -1076,12 +1166,14 @@ impl<'p, Cx: PatCx> MatrixRow<'p, Cx> { &self, parent_row: usize, ) -> impl Iterator> + Captures<'_> { + let is_or_pat = self.pats.head().is_or_pat(); self.pats.expand_or_pat().map(move |patstack| MatrixRow { pats: patstack, parent_row, is_under_guard: self.is_under_guard, useful: false, - intersects: BitSet::new_empty(0), // Initialized in `Matrix::expand_and_push`. + intersects_at_least: BitSet::new_empty(0), // Initialized in `Matrix::push`. + head_is_branch: is_or_pat, }) } @@ -1100,7 +1192,8 @@ impl<'p, Cx: PatCx> MatrixRow<'p, Cx> { parent_row, is_under_guard: self.is_under_guard, useful: false, - intersects: BitSet::new_empty(0), // Initialized in `Matrix::push`. + intersects_at_least: BitSet::new_empty(0), // Initialized in `Matrix::push`. + head_is_branch: false, }) } } @@ -1138,7 +1231,7 @@ struct Matrix<'p, Cx: PatCx> { impl<'p, Cx: PatCx> Matrix<'p, Cx> { /// Pushes a new row to the matrix. Internal method, prefer [`Matrix::new`]. fn push(&mut self, mut row: MatrixRow<'p, Cx>) { - row.intersects = BitSet::new_empty(self.rows.len()); + row.intersects_at_least = BitSet::new_empty(self.rows.len()); self.rows.push(row); } @@ -1156,14 +1249,7 @@ impl<'p, Cx: PatCx> Matrix<'p, Cx> { wildcard_row_is_relevant: true, }; for (arm_id, arm) in arms.iter().enumerate() { - let v = MatrixRow { - pats: PatStack::from_pattern(arm.pat), - parent_row: arm_id, - is_under_guard: arm.has_guard, - useful: false, - intersects: BitSet::new_empty(0), // Initialized in `Matrix::push`. - }; - matrix.push(v); + matrix.push(MatrixRow::new(arm, arm_id)); } matrix } @@ -1242,12 +1328,12 @@ impl<'p, Cx: PatCx> Matrix<'p, Cx> { let parent_row = &mut self.rows[parent_row_id]; // A parent row is useful if any of its children is. parent_row.useful |= child_row.useful; - for child_intersection in child_row.intersects.iter() { + for child_intersection in child_row.intersects_at_least.iter() { // Convert the intersecting ids into ids for the parent matrix. let parent_intersection = specialized.rows[child_intersection].parent_row; // Note: self-intersection can happen with or-patterns. if parent_intersection != parent_row_id { - parent_row.intersects.insert(parent_intersection); + parent_row.intersects_at_least.insert(parent_intersection); } } } @@ -1544,7 +1630,7 @@ fn collect_overlapping_range_endpoints<'p, Cx: PatCx>( let overlaps_with: Vec<_> = prefixes .iter() .filter(|&&(other_child_row_id, _)| { - child_row.intersects.contains(other_child_row_id) + child_row.intersects_at_least.contains(other_child_row_id) }) .map(|&(_, pat)| pat) .collect(); @@ -1560,7 +1646,7 @@ fn collect_overlapping_range_endpoints<'p, Cx: PatCx>( let overlaps_with: Vec<_> = suffixes .iter() .filter(|&&(other_child_row_id, _)| { - child_row.intersects.contains(other_child_row_id) + child_row.intersects_at_least.contains(other_child_row_id) }) .map(|&(_, pat)| pat) .collect(); @@ -1603,8 +1689,8 @@ fn collect_non_contiguous_range_endpoints<'p, Cx: PatCx>( /// The core of the algorithm. /// /// This recursively computes witnesses of the non-exhaustiveness of `matrix` (if any). Also tracks -/// usefulness of each row in the matrix (in `row.useful`). We track usefulness of each subpattern -/// in `mcx.useful_subpatterns`. +/// usefulness of each row in the matrix (in `row.useful`). We track usefulness of subpatterns in +/// `mcx.branch_usefulness`. /// /// The input `Matrix` and the output `WitnessMatrix` together match the type exhaustively. /// @@ -1616,7 +1702,7 @@ fn collect_non_contiguous_range_endpoints<'p, Cx: PatCx>( /// This is all explained at the top of the file. #[instrument(level = "debug", skip(mcx), ret)] fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: PatCx>( - mcx: &mut UsefulnessCtxt<'a, Cx>, + mcx: &mut UsefulnessCtxt<'a, 'p, Cx>, matrix: &mut Matrix<'p, Cx>, ) -> Result, Cx::Error> { debug_assert!(matrix.rows().all(|r| r.len() == matrix.column_count())); @@ -1635,7 +1721,7 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: PatCx>( let mut useful = true; // Whether the next row is useful. for (i, row) in matrix.rows_mut().enumerate() { row.useful = useful; - row.intersects.insert_range(0..i); + row.intersects_at_least.insert_range(0..i); // The next rows stays useful if this one is under a guard. useful &= row.is_under_guard; } @@ -1677,7 +1763,7 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: PatCx>( if let Constructor::IntRange(overlap_range) = ctor { if overlap_range.is_singleton() && spec_matrix.rows.len() >= 2 - && spec_matrix.rows.iter().any(|row| !row.intersects.is_empty()) + && spec_matrix.rows.iter().any(|row| !row.intersects_at_least.is_empty()) { collect_overlapping_range_endpoints(mcx.tycx, overlap_range, matrix, &spec_matrix); } @@ -1697,14 +1783,11 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: PatCx>( } } - // Record usefulness in the patterns. + // Record usefulness of the branch patterns. for row in matrix.rows() { - if row.useful { + if row.head_is_branch { if let PatOrWild::Pat(pat) = row.head() { - let newly_useful = mcx.useful_subpatterns.insert(pat.uid); - if newly_useful { - debug!("newly useful: {pat:?}"); - } + mcx.branch_usefulness.entry(pat.uid).or_default().update(row, matrix); } } } @@ -1712,16 +1795,25 @@ fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: PatCx>( Ok(ret) } +/// Indicates why a given pattern is considered redundant. +#[derive(Clone, Debug)] +pub struct RedundancyExplanation<'p, Cx: PatCx> { + /// All the values matched by this pattern are already matched by the given set of patterns. + /// This list is not guaranteed to be minimal but the contained patterns are at least guaranteed + /// to intersect this pattern. + pub covered_by: Vec<&'p DeconstructedPat>, +} + /// Indicates whether or not a given arm is useful. #[derive(Clone, Debug)] pub enum Usefulness<'p, Cx: PatCx> { /// The arm is useful. This additionally carries a set of or-pattern branches that have been /// found to be redundant despite the overall arm being useful. Used only in the presence of /// or-patterns, otherwise it stays empty. - Useful(Vec<&'p DeconstructedPat>), + Useful(Vec<(&'p DeconstructedPat, RedundancyExplanation<'p, Cx>)>), /// The arm is redundant and can be removed without changing the behavior of the match /// expression. - Redundant, + Redundant(RedundancyExplanation<'p, Cx>), } /// The output of checking a match for exhaustiveness and arm usefulness. @@ -1747,7 +1839,7 @@ pub fn compute_match_usefulness<'p, Cx: PatCx>( ) -> Result, Cx::Error> { let mut cx = UsefulnessCtxt { tycx, - useful_subpatterns: FxHashSet::default(), + branch_usefulness: FxHashMap::default(), complexity_limit, complexity_level: 0, }; @@ -1760,26 +1852,32 @@ pub fn compute_match_usefulness<'p, Cx: PatCx>( .copied() .map(|arm| { debug!(?arm); - let usefulness = if cx.useful_subpatterns.contains(&arm.pat.uid) { + let usefulness = cx.branch_usefulness.get(&arm.pat.uid).unwrap(); + let usefulness = if let Some(explanation) = usefulness.is_redundant() { + Usefulness::Redundant(explanation) + } else { let mut redundant_subpats = Vec::new(); arm.pat.walk(&mut |subpat| { - if cx.useful_subpatterns.contains(&subpat.uid) { - true // keep recursing + if let Some(u) = cx.branch_usefulness.get(&subpat.uid) { + if let Some(explanation) = u.is_redundant() { + redundant_subpats.push((subpat, explanation)); + false // stop recursing + } else { + true // keep recursing + } } else { - redundant_subpats.push(subpat); - false // stop recursing + true // keep recursing } }); Usefulness::Useful(redundant_subpats) - } else { - Usefulness::Redundant }; debug!(?usefulness); (arm, usefulness) }) .collect(); - let arm_intersections: Vec<_> = matrix.rows().map(|row| row.intersects.clone()).collect(); + let arm_intersections: Vec<_> = + matrix.rows().map(|row| row.intersects_at_least.clone()).collect(); Ok(UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses, arm_intersections }) } diff --git a/compiler/rustc_pattern_analysis/tests/common/mod.rs b/compiler/rustc_pattern_analysis/tests/common/mod.rs index 6e8bb50500554..01a56eaa78fcc 100644 --- a/compiler/rustc_pattern_analysis/tests/common/mod.rs +++ b/compiler/rustc_pattern_analysis/tests/common/mod.rs @@ -1,10 +1,8 @@ -use rustc_pattern_analysis::{ - constructor::{ - Constructor, ConstructorSet, IntRange, MaybeInfiniteInt, RangeEnd, VariantVisibility, - }, - usefulness::{PlaceValidity, UsefulnessReport}, - Captures, MatchArm, PatCx, PrivateUninhabitedField, +use rustc_pattern_analysis::constructor::{ + Constructor, ConstructorSet, IntRange, MaybeInfiniteInt, RangeEnd, VariantVisibility, }; +use rustc_pattern_analysis::usefulness::{PlaceValidity, UsefulnessReport}; +use rustc_pattern_analysis::{Captures, MatchArm, PatCx, PrivateUninhabitedField}; /// Sets up `tracing` for easier debugging. Tries to look like the `rustc` setup. pub fn init_tracing() { @@ -25,7 +23,7 @@ pub fn init_tracing() { /// A simple set of types. #[allow(dead_code)] -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Ty { /// Booleans Bool, @@ -33,6 +31,8 @@ pub enum Ty { U8, /// Tuples. Tuple(&'static [Ty]), + /// Enum with one variant of each given type. + Enum(&'static [Ty]), /// A struct with `arity` fields of type `ty`. BigStruct { arity: usize, ty: &'static Ty }, /// A enum with `arity` variants of type `ty`. @@ -46,12 +46,23 @@ impl Ty { match (ctor, *self) { (Struct, Ty::Tuple(tys)) => tys.iter().copied().collect(), (Struct, Ty::BigStruct { arity, ty }) => (0..arity).map(|_| *ty).collect(), + (Variant(i), Ty::Enum(tys)) => vec![tys[*i]], (Variant(_), Ty::BigEnum { ty, .. }) => vec![*ty], (Bool(..) | IntRange(..) | NonExhaustive | Missing | Wildcard, _) => vec![], _ => panic!("Unexpected ctor {ctor:?} for type {self:?}"), } } + fn is_empty(&self) -> bool { + match *self { + Ty::Bool | Ty::U8 => false, + Ty::Tuple(tys) => tys.iter().any(|ty| ty.is_empty()), + Ty::Enum(tys) => tys.iter().all(|ty| ty.is_empty()), + Ty::BigStruct { arity, ty } => arity != 0 && ty.is_empty(), + Ty::BigEnum { arity, ty } => arity == 0 || ty.is_empty(), + } + } + pub fn ctor_set(&self) -> ConstructorSet { match *self { Ty::Bool => ConstructorSet::Bool, @@ -64,10 +75,32 @@ impl Ty { range_2: None, }, Ty::Tuple(..) | Ty::BigStruct { .. } => ConstructorSet::Struct { empty: false }, - Ty::BigEnum { arity, .. } => ConstructorSet::Variants { - variants: (0..arity).map(|_| VariantVisibility::Visible).collect(), + Ty::Enum(tys) if tys.is_empty() => ConstructorSet::NoConstructors, + Ty::Enum(tys) => ConstructorSet::Variants { + variants: tys + .iter() + .map(|ty| { + if ty.is_empty() { + VariantVisibility::Empty + } else { + VariantVisibility::Visible + } + }) + .collect(), non_exhaustive: false, }, + Ty::BigEnum { arity: 0, .. } => ConstructorSet::NoConstructors, + Ty::BigEnum { arity, ty } => { + let vis = if ty.is_empty() { + VariantVisibility::Empty + } else { + VariantVisibility::Visible + }; + ConstructorSet::Variants { + variants: (0..arity).map(|_| vis).collect(), + non_exhaustive: false, + } + } } } @@ -79,6 +112,7 @@ impl Ty { match (*self, ctor) { (Ty::Tuple(..), _) => Ok(()), (Ty::BigStruct { .. }, _) => write!(f, "BigStruct"), + (Ty::Enum(..), Constructor::Variant(i)) => write!(f, "Enum::Variant{i}"), (Ty::BigEnum { .. }, Constructor::Variant(i)) => write!(f, "BigEnum::Variant{i}"), _ => write!(f, "{:?}::{:?}", self, ctor), } @@ -119,7 +153,7 @@ impl PatCx for Cx { } fn is_min_exhaustive_patterns_feature_on(&self) -> bool { - false + true } fn ctor_arity(&self, ctor: &Constructor, ty: &Self::Ty) -> usize { diff --git a/compiler/rustc_pattern_analysis/tests/complexity.rs b/compiler/rustc_pattern_analysis/tests/complexity.rs index 19242d44e3524..3a9b9e9f07588 100644 --- a/compiler/rustc_pattern_analysis/tests/complexity.rs +++ b/compiler/rustc_pattern_analysis/tests/complexity.rs @@ -1,7 +1,9 @@ //! Test the pattern complexity limit. use common::*; -use rustc_pattern_analysis::{pat::DeconstructedPat, usefulness::PlaceValidity, MatchArm}; +use rustc_pattern_analysis::pat::DeconstructedPat; +use rustc_pattern_analysis::usefulness::PlaceValidity; +use rustc_pattern_analysis::MatchArm; #[macro_use] mod common; diff --git a/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs b/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs index 4f8d68d5514be..2192940d4d716 100644 --- a/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs +++ b/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs @@ -1,11 +1,9 @@ //! Test exhaustiveness checking. use common::*; -use rustc_pattern_analysis::{ - pat::{DeconstructedPat, WitnessPat}, - usefulness::PlaceValidity, - MatchArm, -}; +use rustc_pattern_analysis::pat::{DeconstructedPat, WitnessPat}; +use rustc_pattern_analysis::usefulness::PlaceValidity; +use rustc_pattern_analysis::MatchArm; #[macro_use] mod common; @@ -76,3 +74,17 @@ fn test_nested() { Struct(Variant.1, Variant.1), )); } + +#[test] +fn test_empty() { + // `TY = Result` + const TY: Ty = Ty::Enum(&[Ty::Bool, Ty::Enum(&[])]); + assert_exhaustive(pats!(TY; + Variant.0, + )); + let ty = Ty::Tuple(&[Ty::Bool, TY]); + assert_exhaustive(pats!(ty; + (true, Variant.0), + (false, Variant.0), + )); +} diff --git a/compiler/rustc_pattern_analysis/tests/intersection.rs b/compiler/rustc_pattern_analysis/tests/intersection.rs index 4a96b7248dae6..1c26e179f2ec7 100644 --- a/compiler/rustc_pattern_analysis/tests/intersection.rs +++ b/compiler/rustc_pattern_analysis/tests/intersection.rs @@ -1,7 +1,9 @@ //! Test the computation of arm intersections. use common::*; -use rustc_pattern_analysis::{pat::DeconstructedPat, usefulness::PlaceValidity, MatchArm}; +use rustc_pattern_analysis::pat::DeconstructedPat; +use rustc_pattern_analysis::usefulness::PlaceValidity; +use rustc_pattern_analysis::MatchArm; #[macro_use] mod common; @@ -67,4 +69,24 @@ fn test_nested() { ), &[&[], &[]], ); + let ty = Ty::Tuple(&[Ty::Bool; 3]); + assert_intersects( + pats!(ty; + (true, true, _), + (true, _, true), + (false, _, _), + ), + &[&[], &[], &[]], + ); + let ty = Ty::Tuple(&[Ty::Bool, Ty::Bool, Ty::U8]); + assert_intersects( + pats!(ty; + (true, _, _), + (_, true, 0..10), + (_, true, 10..), + (_, true, 3), + _, + ), + &[&[], &[], &[], &[1], &[0, 1, 2, 3]], + ); } diff --git a/compiler/rustc_privacy/src/errors.rs b/compiler/rustc_privacy/src/errors.rs index ee04c335f2bd1..89face1075091 100644 --- a/compiler/rustc_privacy/src/errors.rs +++ b/compiler/rustc_privacy/src/errors.rs @@ -1,4 +1,5 @@ -use rustc_errors::{codes::*, DiagArgFromDisplay}; +use rustc_errors::codes::*; +use rustc_errors::DiagArgFromDisplay; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_span::{Span, Symbol}; diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index d37056269385d..d1d1e5e901f29 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -10,12 +10,19 @@ mod errors; +use std::fmt; +use std::marker::PhantomData; +use std::ops::ControlFlow; + +use errors::{ + FieldIsPrivate, FieldIsPrivateLabel, FromPrivateDependencyInPublicInterface, InPublicInterface, + ItemIsPrivate, PrivateInterfacesOrBoundsLint, ReportEffectiveVisibility, UnnameableTypesLint, + UnnamedItemIsPrivate, +}; use rustc_ast::visit::{try_visit, VisitorResult}; use rustc_ast::MacroDef; -use rustc_attr as attr; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::intern::Interned; -use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId, CRATE_DEF_ID}; use rustc_hir::intravisit::{self, Visitor}; @@ -23,25 +30,17 @@ use rustc_hir::{AssocItemKind, ForeignItemKind, ItemId, ItemKind, PatKind}; use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level}; use rustc_middle::query::Providers; use rustc_middle::ty::print::PrintTraitRefExt as _; -use rustc_middle::ty::GenericArgs; -use rustc_middle::ty::{self, Const, GenericParamDefKind}; -use rustc_middle::ty::{TraitRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor}; +use rustc_middle::ty::{ + self, Const, GenericArgs, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeSuperVisitable, + TypeVisitable, TypeVisitor, +}; use rustc_middle::{bug, span_bug}; use rustc_session::lint; use rustc_span::hygiene::Transparency; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; use tracing::debug; - -use std::fmt; -use std::marker::PhantomData; -use std::ops::ControlFlow; - -use errors::{ - FieldIsPrivate, FieldIsPrivateLabel, FromPrivateDependencyInPublicInterface, InPublicInterface, - ItemIsPrivate, PrivateInterfacesOrBoundsLint, ReportEffectiveVisibility, UnnameableTypesLint, - UnnamedItemIsPrivate, -}; +use {rustc_attr as attr, rustc_hir as hir}; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_query_impl/src/lib.rs b/compiler/rustc_query_impl/src/lib.rs index 825c1e2e9bce1..18f97d6fb8f1b 100644 --- a/compiler/rustc_query_impl/src/lib.rs +++ b/compiler/rustc_query_impl/src/lib.rs @@ -10,20 +10,17 @@ #![feature(rustdoc_internals)] // tidy-alphabetical-end -use crate::plumbing::{__rust_begin_short_backtrace, encode_all_query_results, try_mark_green}; -use crate::profiling_support::QueryKeyStringCache; use field_offset::offset_of; use rustc_data_structures::stable_hasher::HashStable; use rustc_data_structures::sync::AtomicU64; use rustc_middle::arena::Arena; -use rustc_middle::dep_graph::DepNodeIndex; -use rustc_middle::dep_graph::{self, DepKind, DepKindStruct}; +use rustc_middle::dep_graph::{self, DepKind, DepKindStruct, DepNodeIndex}; use rustc_middle::query::erase::{erase, restore, Erase}; use rustc_middle::query::on_disk_cache::{CacheEncoder, EncodedDepNodeIndex, OnDiskCache}; use rustc_middle::query::plumbing::{DynamicQuery, QuerySystem, QuerySystemFns}; -use rustc_middle::query::AsLocalKey; use rustc_middle::query::{ - queries, DynamicQueries, ExternProviders, Providers, QueryCaches, QueryEngine, QueryStates, + queries, AsLocalKey, DynamicQueries, ExternProviders, Providers, QueryCaches, QueryEngine, + QueryStates, }; use rustc_middle::ty::TyCtxt; use rustc_query_system::dep_graph::SerializedDepNodeIndex; @@ -32,10 +29,12 @@ use rustc_query_system::query::{ get_query_incr, get_query_non_incr, CycleError, HashResult, QueryCache, QueryConfig, QueryMap, QueryMode, QueryState, }; -use rustc_query_system::HandleCycleError; -use rustc_query_system::Value; +use rustc_query_system::{HandleCycleError, Value}; use rustc_span::{ErrorGuaranteed, Span}; +use crate::plumbing::{__rust_begin_short_backtrace, encode_all_query_results, try_mark_green}; +use crate::profiling_support::QueryKeyStringCache; + #[macro_use] mod plumbing; pub use crate::plumbing::{query_key_hash_verify_all, QueryCtxt}; diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index 62e3937721471..b9e700c1938f2 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -2,19 +2,21 @@ //! generate the actual methods on tcx which find and execute the provider, //! manage the caches, and so forth. -use crate::QueryConfigRestored; +use std::num::NonZero; + use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher}; use rustc_data_structures::sync::Lock; use rustc_data_structures::unord::UnordMap; use rustc_errors::DiagInner; use rustc_index::Idx; use rustc_middle::bug; -use rustc_middle::dep_graph::dep_kinds; use rustc_middle::dep_graph::{ - self, DepContext, DepKind, DepKindStruct, DepNode, DepNodeIndex, SerializedDepNodeIndex, + self, dep_kinds, DepContext, DepKind, DepKindStruct, DepNode, DepNodeIndex, + SerializedDepNodeIndex, +}; +use rustc_middle::query::on_disk_cache::{ + AbsoluteBytePos, CacheDecoder, CacheEncoder, EncodedDepNodeIndex, }; -use rustc_middle::query::on_disk_cache::AbsoluteBytePos; -use rustc_middle::query::on_disk_cache::{CacheDecoder, CacheEncoder, EncodedDepNodeIndex}; use rustc_middle::query::Key; use rustc_middle::ty::print::with_reduced_queries; use rustc_middle::ty::tls::{self, ImplicitCtxt}; @@ -26,13 +28,13 @@ use rustc_query_system::query::{ QueryStackFrame, }; use rustc_query_system::{LayoutOfDepth, QueryOverflow}; -use rustc_serialize::Decodable; -use rustc_serialize::Encodable; +use rustc_serialize::{Decodable, Encodable}; use rustc_session::Limit; use rustc_span::def_id::LOCAL_CRATE; -use std::num::NonZero; use thin_vec::ThinVec; +use crate::QueryConfigRestored; + #[derive(Copy, Clone)] pub struct QueryCtxt<'tcx> { pub tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_query_impl/src/profiling_support.rs b/compiler/rustc_query_impl/src/profiling_support.rs index e0d7a4f0451a2..599316d0cadfd 100644 --- a/compiler/rustc_query_impl/src/profiling_support.rs +++ b/compiler/rustc_query_impl/src/profiling_support.rs @@ -1,3 +1,6 @@ +use std::fmt::Debug; +use std::io::Write; + use measureme::{StringComponent, StringId}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::profiling::SelfProfiler; @@ -5,8 +8,6 @@ use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, LOCAL_CRATE}; use rustc_hir::definitions::DefPathData; use rustc_middle::ty::TyCtxt; use rustc_query_system::query::QueryCache; -use std::fmt::Debug; -use std::io::Write; pub(crate) struct QueryKeyStringCache { def_id_cache: FxHashMap, diff --git a/compiler/rustc_query_system/src/cache.rs b/compiler/rustc_query_system/src/cache.rs index d8a5bdba7b8a7..1b8332ad9e015 100644 --- a/compiler/rustc_query_system/src/cache.rs +++ b/compiler/rustc_query_system/src/cache.rs @@ -1,11 +1,11 @@ //! Cache for candidate selection. -use crate::dep_graph::{DepContext, DepNodeIndex}; +use std::hash::Hash; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lock; -use std::hash::Hash; +use crate::dep_graph::{DepContext, DepNodeIndex}; pub struct Cache { hashmap: Lock>>, diff --git a/compiler/rustc_query_system/src/dep_graph/debug.rs b/compiler/rustc_query_system/src/dep_graph/debug.rs index 103a6c01bd274..4d009d63de59c 100644 --- a/compiler/rustc_query_system/src/dep_graph/debug.rs +++ b/compiler/rustc_query_system/src/dep_graph/debug.rs @@ -1,9 +1,11 @@ //! Code for debugging the dep-graph. -use super::{DepNode, DepNodeIndex}; +use std::error::Error; + use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lock; -use std::error::Error; + +use super::{DepNode, DepNodeIndex}; /// A dep-node filter goes from a user-defined string to a query over /// nodes. Right now the format is like this: diff --git a/compiler/rustc_query_system/src/dep_graph/dep_node.rs b/compiler/rustc_query_system/src/dep_graph/dep_node.rs index f2a68e3567158..dfd0527252d60 100644 --- a/compiler/rustc_query_system/src/dep_graph/dep_node.rs +++ b/compiler/rustc_query_system/src/dep_graph/dep_node.rs @@ -42,16 +42,17 @@ //! `DefId` it was computed from. In other cases, too much information gets //! lost during fingerprint computation. -use super::{DepContext, FingerprintStyle}; -use crate::ich::StableHashingContext; +use std::fmt; +use std::hash::Hash; use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableOrd, ToStableHashKey}; use rustc_data_structures::AtomicRef; use rustc_hir::definitions::DefPathHash; use rustc_macros::{Decodable, Encodable}; -use std::fmt; -use std::hash::Hash; + +use super::{DepContext, FingerprintStyle}; +use crate::ich::StableHashingContext; /// This serves as an index into arrays built by `make_dep_kind_array`. #[derive(Clone, Copy, PartialEq, Eq, Hash)] @@ -312,8 +313,9 @@ impl StableOrd for WorkProductId { // Some types are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(DepKind, 2); #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] diff --git a/compiler/rustc_query_system/src/dep_graph/edges.rs b/compiler/rustc_query_system/src/dep_graph/edges.rs index 63d46f47f5ce6..9a3763bd4eeb4 100644 --- a/compiler/rustc_query_system/src/dep_graph/edges.rs +++ b/compiler/rustc_query_system/src/dep_graph/edges.rs @@ -1,8 +1,10 @@ -use crate::dep_graph::DepNodeIndex; -use smallvec::SmallVec; use std::hash::{Hash, Hasher}; use std::ops::Deref; +use smallvec::SmallVec; + +use crate::dep_graph::DepNodeIndex; + #[derive(Default, Debug)] pub(crate) struct EdgesVec { max: u32, diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index 66fb3136805e1..b6aa1d5a43bb8 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -1,3 +1,11 @@ +use std::assert_matches::assert_matches; +use std::collections::hash_map::Entry; +use std::fmt::Debug; +use std::hash::Hash; +use std::marker::PhantomData; +use std::sync::atomic::Ordering; +use std::sync::Arc; + use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::profiling::{QueryInvocationId, SelfProfilerRef}; @@ -8,14 +16,9 @@ use rustc_data_structures::unord::UnordMap; use rustc_index::IndexVec; use rustc_macros::{Decodable, Encodable}; use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; -use std::assert_matches::assert_matches; -use std::collections::hash_map::Entry; -use std::fmt::Debug; -use std::hash::Hash; -use std::marker::PhantomData; -use std::sync::atomic::Ordering; -use std::sync::Arc; use tracing::{debug, instrument}; +#[cfg(debug_assertions)] +use {super::debug::EdgeFilter, std::env}; use super::query::DepGraphQuery; use super::serialized::{GraphEncoder, SerializedDepGraph, SerializedDepNodeIndex}; @@ -24,9 +27,6 @@ use crate::dep_graph::edges::EdgesVec; use crate::ich::StableHashingContext; use crate::query::{QueryContext, QuerySideEffects}; -#[cfg(debug_assertions)] -use {super::debug::EdgeFilter, std::env}; - #[derive(Clone)] pub struct DepGraph { data: Option>>, diff --git a/compiler/rustc_query_system/src/dep_graph/mod.rs b/compiler/rustc_query_system/src/dep_graph/mod.rs index cfb25ec905fb8..291f275ef3c6f 100644 --- a/compiler/rustc_query_system/src/dep_graph/mod.rs +++ b/compiler/rustc_query_system/src/dep_graph/mod.rs @@ -5,18 +5,19 @@ mod graph; mod query; mod serialized; +use std::panic; + pub use dep_node::{DepKind, DepKindStruct, DepNode, DepNodeParams, WorkProductId}; pub(crate) use graph::DepGraphData; pub use graph::{hash_result, DepGraph, DepNodeIndex, TaskDepsRef, WorkProduct, WorkProductMap}; pub use query::DepGraphQuery; +use rustc_data_structures::profiling::SelfProfilerRef; +use rustc_session::Session; pub use serialized::{SerializedDepGraph, SerializedDepNodeIndex}; +use tracing::instrument; use self::graph::{print_markframe_trace, MarkFrame}; use crate::ich::StableHashingContext; -use rustc_data_structures::profiling::SelfProfilerRef; -use rustc_session::Session; -use std::panic; -use tracing::instrument; pub trait DepContext: Copy { type Deps: Deps; diff --git a/compiler/rustc_query_system/src/dep_graph/serialized.rs b/compiler/rustc_query_system/src/dep_graph/serialized.rs index 8e91d9dd60b3c..ff1c3431b7c52 100644 --- a/compiler/rustc_query_system/src/dep_graph/serialized.rs +++ b/compiler/rustc_query_system/src/dep_graph/serialized.rs @@ -35,11 +35,11 @@ //! If the number of edges in this node does not fit in the bits available in the header, we //! store it directly after the header with leb128. -use super::query::DepGraphQuery; -use super::{DepKind, DepNode, DepNodeIndex, Deps}; -use crate::dep_graph::edges::EdgesVec; -use rustc_data_structures::fingerprint::Fingerprint; -use rustc_data_structures::fingerprint::PackedFingerprint; +use std::iter; +use std::marker::PhantomData; +use std::sync::Arc; + +use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::outline; use rustc_data_structures::profiling::SelfProfilerRef; @@ -48,11 +48,12 @@ use rustc_data_structures::unhash::UnhashMap; use rustc_index::{Idx, IndexVec}; use rustc_serialize::opaque::{FileEncodeResult, FileEncoder, IntEncodedWithFixedSize, MemDecoder}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; -use std::iter; -use std::marker::PhantomData; -use std::sync::Arc; use tracing::{debug, instrument}; +use super::query::DepGraphQuery; +use super::{DepKind, DepNode, DepNodeIndex, Deps}; +use crate::dep_graph::edges::EdgesVec; + // The maximum value of `SerializedDepNodeIndex` leaves the upper two bits // unused so that we can store multiple index types in `CompressedHybridIndex`, // and use those bits to encode which index type it contains. diff --git a/compiler/rustc_query_system/src/ich/hcx.rs b/compiler/rustc_query_system/src/ich/hcx.rs index e7eb9694f4738..756ad3b1a2dda 100644 --- a/compiler/rustc_query_system/src/ich/hcx.rs +++ b/compiler/rustc_query_system/src/ich/hcx.rs @@ -1,5 +1,3 @@ -use crate::ich; - use rustc_ast as ast; use rustc_data_structures::stable_hasher::{HashStable, HashingControls, StableHasher}; use rustc_data_structures::sync::Lrc; @@ -11,6 +9,8 @@ use rustc_span::source_map::SourceMap; use rustc_span::symbol::Symbol; use rustc_span::{BytePos, CachingSourceMapView, SourceFile, Span, SpanData, DUMMY_SP}; +use crate::ich; + /// This is the context state available during incr. comp. hashing. It contains /// enough information to transform `DefId`s and `HirId`s into stable `DefPath`s (i.e., /// a reference to the `TyCtxt`) and it holds a few caches for speeding up various diff --git a/compiler/rustc_query_system/src/ich/impls_syntax.rs b/compiler/rustc_query_system/src/ich/impls_syntax.rs index 5bd4fe04848fb..8d7a6e4fa9b0c 100644 --- a/compiler/rustc_query_system/src/ich/impls_syntax.rs +++ b/compiler/rustc_query_system/src/ich/impls_syntax.rs @@ -1,15 +1,15 @@ //! This module contains `HashStable` implementations for various data types //! from `rustc_ast` in no particular order. -use crate::ich::StableHashingContext; +use std::assert_matches::assert_matches; use rustc_ast as ast; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_span::SourceFile; -use std::assert_matches::assert_matches; - use smallvec::SmallVec; +use crate::ich::StableHashingContext; + impl<'ctx> rustc_target::HashStableContext for StableHashingContext<'ctx> {} impl<'a> HashStable> for [ast::Attribute] { @@ -73,7 +73,6 @@ impl<'a> HashStable> for SourceFile { source_len: _, lines: _, ref multibyte_chars, - ref non_narrow_chars, ref normalized_pos, } = *self; @@ -98,11 +97,6 @@ impl<'a> HashStable> for SourceFile { char_pos.hash_stable(hcx, hasher); } - non_narrow_chars.len().hash_stable(hcx, hasher); - for &char_pos in non_narrow_chars.iter() { - char_pos.hash_stable(hcx, hasher); - } - normalized_pos.len().hash_stable(hcx, hasher); for &char_pos in normalized_pos.iter() { char_pos.hash_stable(hcx, hasher); diff --git a/compiler/rustc_query_system/src/ich/mod.rs b/compiler/rustc_query_system/src/ich/mod.rs index 86e3ecb1eddb7..bae768851419a 100644 --- a/compiler/rustc_query_system/src/ich/mod.rs +++ b/compiler/rustc_query_system/src/ich/mod.rs @@ -1,8 +1,9 @@ //! ICH - Incremental Compilation Hash -pub use self::hcx::StableHashingContext; use rustc_span::symbol::{sym, Symbol}; +pub use self::hcx::StableHashingContext; + mod hcx; mod impls_syntax; diff --git a/compiler/rustc_query_system/src/lib.rs b/compiler/rustc_query_system/src/lib.rs index 41222e83f7c58..7a50a9534c21f 100644 --- a/compiler/rustc_query_system/src/lib.rs +++ b/compiler/rustc_query_system/src/lib.rs @@ -14,9 +14,7 @@ pub mod ich; pub mod query; mod values; -pub use error::HandleCycleError; -pub use error::LayoutOfDepth; -pub use error::QueryOverflow; +pub use error::{HandleCycleError, LayoutOfDepth, QueryOverflow}; pub use values::Value; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_query_system/src/query/caches.rs b/compiler/rustc_query_system/src/query/caches.rs index acc29b67cccec..a4ced3d2c2452 100644 --- a/compiler/rustc_query_system/src/query/caches.rs +++ b/compiler/rustc_query_system/src/query/caches.rs @@ -1,14 +1,14 @@ -use crate::dep_graph::DepNodeIndex; +use std::fmt::Debug; +use std::hash::Hash; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sharded::{self, Sharded}; use rustc_data_structures::sync::{Lock, OnceLock}; use rustc_hir::def_id::LOCAL_CRATE; use rustc_index::{Idx, IndexVec}; -use rustc_span::def_id::DefId; -use rustc_span::def_id::DefIndex; -use std::fmt::Debug; -use std::hash::Hash; +use rustc_span::def_id::{DefId, DefIndex}; + +use crate::dep_graph::DepNodeIndex; pub trait QueryCache: Sized { type Key: Hash + Eq + Copy + Debug; diff --git a/compiler/rustc_query_system/src/query/config.rs b/compiler/rustc_query_system/src/query/config.rs index 958d9fdb52ae5..371b896400a58 100644 --- a/compiler/rustc_query_system/src/query/config.rs +++ b/compiler/rustc_query_system/src/query/config.rs @@ -1,16 +1,16 @@ //! Query configuration and description traits. +use std::fmt::Debug; +use std::hash::Hash; + +use rustc_data_structures::fingerprint::Fingerprint; +use rustc_span::ErrorGuaranteed; + use crate::dep_graph::{DepKind, DepNode, DepNodeParams, SerializedDepNodeIndex}; use crate::error::HandleCycleError; use crate::ich::StableHashingContext; use crate::query::caches::QueryCache; -use crate::query::DepNodeIndex; -use crate::query::{CycleError, QueryContext, QueryState}; - -use rustc_data_structures::fingerprint::Fingerprint; -use rustc_span::ErrorGuaranteed; -use std::fmt::Debug; -use std::hash::Hash; +use crate::query::{CycleError, DepNodeIndex, QueryContext, QueryState}; pub type HashResult = Option, &V) -> Fingerprint>; diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index 3f44b11850e58..ca3efc11201e1 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -1,18 +1,12 @@ -use crate::dep_graph::DepContext; -use crate::error::CycleStack; -use crate::query::plumbing::CycleError; -use crate::query::DepKind; -use crate::query::{QueryContext, QueryStackFrame}; +use std::hash::Hash; +use std::io::Write; +use std::num::NonZero; + use rustc_data_structures::fx::FxHashMap; use rustc_errors::{Diag, DiagCtxtHandle}; use rustc_hir::def::DefKind; use rustc_session::Session; use rustc_span::Span; - -use std::hash::Hash; -use std::io::Write; -use std::num::NonZero; - #[cfg(parallel_compiler)] use { parking_lot::{Condvar, Mutex}, @@ -23,6 +17,11 @@ use { std::sync::Arc, }; +use crate::dep_graph::DepContext; +use crate::error::CycleStack; +use crate::query::plumbing::CycleError; +use crate::query::{DepKind, QueryContext, QueryStackFrame}; + /// Represents a span and a query key. #[derive(Clone, Debug)] pub struct QueryInfo { @@ -589,7 +588,7 @@ pub fn report_cycle<'a>( cycle_stack, stack_bottom: stack[0].query.description.to_owned(), alias, - cycle_usage: cycle_usage, + cycle_usage, stack_count, note_span: (), }; diff --git a/compiler/rustc_query_system/src/query/mod.rs b/compiler/rustc_query_system/src/query/mod.rs index ab4f48fcd3206..db00c26515996 100644 --- a/compiler/rustc_query_system/src/query/mod.rs +++ b/compiler/rustc_query_system/src/query/mod.rs @@ -12,10 +12,6 @@ mod caches; pub use self::caches::{DefIdCache, DefaultCache, QueryCache, SingleCache, VecCache}; mod config; -pub use self::config::{HashResult, QueryConfig}; - -use crate::dep_graph::DepKind; -use crate::dep_graph::{DepNodeIndex, HasDepContext, SerializedDepNodeIndex}; use rustc_data_structures::stable_hasher::Hash64; use rustc_data_structures::sync::Lock; use rustc_errors::DiagInner; @@ -25,6 +21,9 @@ use rustc_span::def_id::DefId; use rustc_span::Span; use thin_vec::ThinVec; +pub use self::config::{HashResult, QueryConfig}; +use crate::dep_graph::{DepKind, DepNodeIndex, HasDepContext, SerializedDepNodeIndex}; + /// Description of a frame in the query stack. /// /// This is mostly used in case of cycles for error reporting. diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index d37d5bce9cc36..8ef680cdb6c8b 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -2,16 +2,12 @@ //! generate the actual methods on tcx which find and execute the provider, //! manage the caches, and so forth. -use crate::dep_graph::DepGraphData; -use crate::dep_graph::{DepContext, DepNode, DepNodeIndex, DepNodeParams}; -use crate::ich::StableHashingContext; -use crate::query::caches::QueryCache; -#[cfg(parallel_compiler)] -use crate::query::job::QueryLatch; -use crate::query::job::{report_cycle, QueryInfo, QueryJob, QueryJobId, QueryJobInfo}; -use crate::query::SerializedDepNodeIndex; -use crate::query::{QueryContext, QueryMap, QuerySideEffects, QueryStackFrame}; -use crate::HandleCycleError; +use std::cell::Cell; +use std::collections::hash_map::Entry; +use std::fmt::Debug; +use std::hash::Hash; +use std::mem; + use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sharded::Sharded; @@ -21,15 +17,20 @@ use rustc_data_structures::sync::Lock; use rustc_data_structures::{outline, sync}; use rustc_errors::{Diag, FatalError, StashKey}; use rustc_span::{Span, DUMMY_SP}; -use std::cell::Cell; -use std::collections::hash_map::Entry; -use std::fmt::Debug; -use std::hash::Hash; -use std::mem; use thin_vec::ThinVec; use tracing::instrument; use super::QueryConfig; +use crate::dep_graph::{DepContext, DepGraphData, DepNode, DepNodeIndex, DepNodeParams}; +use crate::ich::StableHashingContext; +use crate::query::caches::QueryCache; +#[cfg(parallel_compiler)] +use crate::query::job::QueryLatch; +use crate::query::job::{report_cycle, QueryInfo, QueryJob, QueryJobId, QueryJobInfo}; +use crate::query::{ + QueryContext, QueryMap, QuerySideEffects, QueryStackFrame, SerializedDepNodeIndex, +}; +use crate::HandleCycleError; pub struct QueryState { active: Sharded>, diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index ced5ac17dacb9..2fa3692bb289f 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -5,18 +5,13 @@ //! unexpanded macros in the fragment are visited and registered. //! Imports are also considered items and placed into modules here, but not resolved yet. -use crate::def_collector::collect_definitions; -use crate::imports::{ImportData, ImportKind}; -use crate::macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; -use crate::Namespace::{MacroNS, TypeNS, ValueNS}; -use crate::{errors, BindingKey, MacroData, NameBindingData}; -use crate::{Determinacy, ExternPreludeEntry, Finalize, Module, ModuleKind, ModuleOrUniformRoot}; -use crate::{NameBinding, NameBindingKind, ParentScope, PathResult, ResolutionError}; -use crate::{Resolver, ResolverArenas, Segment, ToNameBinding, Used, VisResolutionError}; +use std::cell::Cell; use rustc_ast::visit::{self, AssocCtxt, Visitor, WalkItemKind}; -use rustc_ast::{self as ast, AssocItem, AssocItemKind, MetaItemKind, StmtKind}; -use rustc_ast::{Block, ForeignItem, ForeignItemKind, Impl, Item, ItemKind, NodeId}; +use rustc_ast::{ + self as ast, AssocItem, AssocItemKind, Block, ForeignItem, ForeignItemKind, Impl, Item, + ItemKind, MetaItemKind, NodeId, StmtKind, +}; use rustc_attr as attr; use rustc_data_structures::sync::Lrc; use rustc_expand::base::ResolverExpand; @@ -30,11 +25,18 @@ use rustc_middle::{bug, ty}; use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; - -use std::cell::Cell; - use tracing::debug; +use crate::def_collector::collect_definitions; +use crate::imports::{ImportData, ImportKind}; +use crate::macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; +use crate::Namespace::{MacroNS, TypeNS, ValueNS}; +use crate::{ + errors, BindingKey, Determinacy, ExternPreludeEntry, Finalize, MacroData, Module, ModuleKind, + ModuleOrUniformRoot, NameBinding, NameBindingData, NameBindingKind, ParentScope, PathResult, + ResolutionError, Resolver, ResolverArenas, Segment, ToNameBinding, Used, VisResolutionError, +}; + type Res = def::Res; impl<'a, Id: Into> ToNameBinding<'a> diff --git a/compiler/rustc_resolve/src/check_unused.rs b/compiler/rustc_resolve/src/check_unused.rs index fc3669fecc2ad..a819997156105 100644 --- a/compiler/rustc_resolve/src/check_unused.rs +++ b/compiler/rustc_resolve/src/check_unused.rs @@ -23,23 +23,22 @@ // - `check_unused` finally emits the diagnostics based on the data generated // in the last step -use crate::imports::{Import, ImportKind}; -use crate::module_to_string; -use crate::Resolver; - -use crate::{LexicalScopeBinding, NameBindingKind}; use rustc_ast as ast; use rustc_ast::visit::{self, Visitor}; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; use rustc_data_structures::unord::UnordSet; use rustc_errors::MultiSpan; use rustc_hir::def::{DefKind, Res}; -use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_EXTERN_CRATES}; -use rustc_session::lint::builtin::{UNUSED_IMPORTS, UNUSED_QUALIFICATIONS}; +use rustc_session::lint::builtin::{ + MACRO_USE_EXTERN_CRATE, UNUSED_EXTERN_CRATES, UNUSED_IMPORTS, UNUSED_QUALIFICATIONS, +}; use rustc_session::lint::BuiltinLintDiag; use rustc_span::symbol::{kw, Ident}; use rustc_span::{Span, DUMMY_SP}; +use crate::imports::{Import, ImportKind}; +use crate::{module_to_string, LexicalScopeBinding, NameBindingKind, Resolver}; + struct UnusedImport { use_tree: ast::UseTree, use_tree_id: ast::NodeId, diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index 1fb942de7343e..ed23870dfdf8b 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -1,4 +1,5 @@ -use crate::{ImplTraitContext, Resolver}; +use std::mem; + use rustc_ast::visit::FnKind; use rustc_ast::*; use rustc_expand::expand::AstFragment; @@ -8,9 +9,10 @@ use rustc_hir::def_id::LocalDefId; use rustc_span::hygiene::LocalExpnId; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; -use std::mem; use tracing::debug; +use crate::{ImplTraitContext, Resolver}; + pub(crate) fn collect_definitions( resolver: &mut Resolver<'_, '_>, fragment: &AstFragment, diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index bf7972e392c9a..8080bb60e415e 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1,12 +1,15 @@ use rustc_ast::expand::StrippedCfgItem; use rustc_ast::ptr::P; use rustc_ast::visit::{self, Visitor}; -use rustc_ast::{self as ast, Crate, ItemKind, ModKind, NodeId, Path, CRATE_NODE_ID}; -use rustc_ast::{MetaItemKind, NestedMetaItem}; +use rustc_ast::{ + self as ast, Crate, ItemKind, MetaItemKind, ModKind, NestedMetaItem, NodeId, Path, + CRATE_NODE_ID, +}; use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxHashSet; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, report_ambiguity_error, struct_span_code_err, Applicability, Diag, DiagCtxtHandle, + report_ambiguity_error, struct_span_code_err, Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, MultiSpan, SuggestionStyle, }; use rustc_feature::BUILTIN_ATTRIBUTES; @@ -16,9 +19,10 @@ use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; use rustc_hir::PrimTy; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; -use rustc_session::lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE; -use rustc_session::lint::builtin::AMBIGUOUS_GLOB_IMPORTS; -use rustc_session::lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS; +use rustc_session::lint::builtin::{ + ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS, + MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS, +}; use rustc_session::lint::{AmbiguityErrorDiag, BuiltinLintDiag}; use rustc_session::Session; use rustc_span::edit_distance::find_best_match_for_name; @@ -36,13 +40,13 @@ use crate::errors::{ }; use crate::imports::{Import, ImportKind}; use crate::late::{PatternSource, Rib}; -use crate::{errors as errs, BindingKey}; -use crate::{path_names_to_string, Used}; -use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize}; -use crate::{HasGenericParams, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot}; -use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, VisResolutionError}; -use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet}; -use crate::{Segment, UseError}; +use crate::{ + errors as errs, path_names_to_string, AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, + BindingError, BindingKey, Finalize, HasGenericParams, LexicalScopeBinding, MacroRulesScope, + Module, ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult, + PrivacyError, ResolutionError, Resolver, Scope, ScopeSet, Segment, UseError, Used, + VisResolutionError, +}; type Res = def::Res; @@ -1448,7 +1452,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { ); if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules { - err.subdiagnostic(MaybeMissingMacroRulesName { span: ident.span }); + let label_span = ident.span.shrink_to_hi(); + let mut spans = MultiSpan::from_span(label_span); + spans.push_span_label(label_span, "put a macro name here"); + err.subdiagnostic(MaybeMissingMacroRulesName { spans: spans }); return; } @@ -2012,21 +2019,24 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { ) } else if ident.name == sym::core { ( - format!("maybe a missing crate `{ident}`?"), + format!("you might be missing crate `{ident}`"), Some(( vec![(ident.span, "std".to_string())], "try using `std` instead of `core`".to_string(), Applicability::MaybeIncorrect, )), ) + } else if ident.name == kw::Underscore { + (format!("`_` is not a valid crate or module name"), None) } else if self.tcx.sess.is_rust_2015() { ( - format!("maybe a missing crate `{ident}`?"), + format!("you might be missing crate `{ident}`"), Some(( - vec![], - format!( - "consider adding `extern crate {ident}` to use the `{ident}` crate" - ), + vec![( + self.current_crate_outer_attr_insert_span, + format!("extern crate {ident};\n"), + )], + format!("consider importing the `{ident}` crate"), Applicability::MaybeIncorrect, )), ) diff --git a/compiler/rustc_resolve/src/effective_visibilities.rs b/compiler/rustc_resolve/src/effective_visibilities.rs index dabed23883866..5ee495da2d93d 100644 --- a/compiler/rustc_resolve/src/effective_visibilities.rs +++ b/compiler/rustc_resolve/src/effective_visibilities.rs @@ -1,18 +1,15 @@ -use crate::{NameBinding, NameBindingKind, Resolver}; -use rustc_ast::ast; -use rustc_ast::visit; +use std::mem; + use rustc_ast::visit::Visitor; -use rustc_ast::Crate; -use rustc_ast::EnumDef; +use rustc_ast::{ast, visit, Crate, EnumDef}; use rustc_data_structures::fx::FxHashSet; -use rustc_hir::def_id::LocalDefId; -use rustc_hir::def_id::CRATE_DEF_ID; -use rustc_middle::middle::privacy::Level; -use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility}; +use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; +use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level}; use rustc_middle::ty::Visibility; -use std::mem; use tracing::info; +use crate::{NameBinding, NameBindingKind, Resolver}; + #[derive(Clone, Copy)] enum ParentId<'a> { Def(LocalDefId), diff --git a/compiler/rustc_resolve/src/errors.rs b/compiler/rustc_resolve/src/errors.rs index 0a68231c6fee4..ad1841e3e8994 100644 --- a/compiler/rustc_resolve/src/errors.rs +++ b/compiler/rustc_resolve/src/errors.rs @@ -1,11 +1,11 @@ -use rustc_errors::{codes::*, Applicability, ElidedLifetimeInPathSubdiag, MultiSpan}; +use rustc_errors::codes::*; +use rustc_errors::{Applicability, ElidedLifetimeInPathSubdiag, MultiSpan}; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_span::{ - symbol::{Ident, Symbol}, - Span, -}; +use rustc_span::symbol::{Ident, Symbol}; +use rustc_span::Span; -use crate::{late::PatternSource, Res}; +use crate::late::PatternSource; +use crate::Res; #[derive(Diagnostic)] #[diag(resolve_generic_params_from_outer_item, code = E0401)] @@ -669,7 +669,7 @@ pub(crate) struct MacroSuggMovePosition { #[note(resolve_missing_macro_rules_name)] pub(crate) struct MaybeMissingMacroRulesName { #[primary_span] - pub(crate) span: Span, + pub(crate) spans: MultiSpan, } #[derive(Subdiagnostic)] diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index f1934ff184bc3..947ba569ab0e2 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -1,29 +1,27 @@ use rustc_ast::{self as ast, NodeId}; use rustc_errors::ErrorGuaranteed; use rustc_hir::def::{DefKind, Namespace, NonMacroAttrKind, PartialRes, PerNS}; -use rustc_middle::bug; -use rustc_middle::ty; +use rustc_middle::{bug, ty}; use rustc_session::lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK; use rustc_session::lint::BuiltinLintDiag; use rustc_session::parse::feature_err; use rustc_span::def_id::LocalDefId; use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext}; -use rustc_span::sym; use rustc_span::symbol::{kw, Ident}; -use rustc_span::Span; +use rustc_span::{sym, Span}; use tracing::{debug, instrument}; +use Determinacy::*; +use Namespace::*; use crate::errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst}; use crate::late::{ConstantHasGenerics, NoConstantGenericsReason, PathSource, Rib, RibKind}; use crate::macros::{sub_namespace_match, MacroRulesScope}; -use crate::{errors, AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, Determinacy, Finalize}; -use crate::{BindingKey, Used}; -use crate::{ImportKind, LexicalScopeBinding, Module, ModuleKind, ModuleOrUniformRoot}; -use crate::{NameBinding, NameBindingKind, ParentScope, PathResult, PrivacyError, Res}; -use crate::{ResolutionError, Resolver, Scope, ScopeSet, Segment, ToNameBinding, Weak}; - -use Determinacy::*; -use Namespace::*; +use crate::{ + errors, AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingKey, Determinacy, Finalize, + ImportKind, LexicalScopeBinding, Module, ModuleKind, ModuleOrUniformRoot, NameBinding, + NameBindingKind, ParentScope, PathResult, PrivacyError, Res, ResolutionError, Resolver, Scope, + ScopeSet, Segment, ToNameBinding, Used, Weak, +}; type Visibility = ty::Visibility; diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index d05326ee311d4..c7af21027b8d3 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -1,32 +1,20 @@ //! A bunch of methods and structures more or less related to resolving imports. -use crate::diagnostics::{import_candidates, DiagMode, Suggestion}; -use crate::errors::{ - CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS, CannotBeReexportedPrivate, - CannotBeReexportedPrivateNS, CannotDetermineImportResolution, CannotGlobImportAllCrates, - ConsiderAddingMacroExport, ConsiderMarkingAsPub, IsNotDirectlyImportable, - ItemsInTraitsAreNotImportable, -}; -use crate::Determinacy::{self, *}; -use crate::{module_to_string, names_to_string, ImportSuggestion}; -use crate::{AmbiguityError, Namespace::*}; -use crate::{AmbiguityKind, BindingKey, ResolutionError, Resolver, Segment}; -use crate::{Finalize, Module, ModuleOrUniformRoot, ParentScope, PerNS, ScopeSet}; -use crate::{NameBinding, NameBindingData, NameBindingKind, PathResult, Used}; +use std::cell::Cell; +use std::mem; use rustc_ast::NodeId; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::intern::Interned; -use rustc_errors::{codes::*, pluralize, struct_span_code_err, Applicability, MultiSpan}; +use rustc_errors::codes::*; +use rustc_errors::{pluralize, struct_span_code_err, Applicability, MultiSpan}; use rustc_hir::def::{self, DefKind, PartialRes}; use rustc_hir::def_id::DefId; -use rustc_middle::metadata::ModChild; -use rustc_middle::metadata::Reexport; -use rustc_middle::span_bug; -use rustc_middle::ty; +use rustc_middle::metadata::{ModChild, Reexport}; +use rustc_middle::{span_bug, ty}; use rustc_session::lint::builtin::{ AMBIGUOUS_GLOB_REEXPORTS, HIDDEN_GLOB_REEXPORTS, PUB_USE_OF_PRIVATE_EXTERN_CRATE, - UNUSED_IMPORTS, + REDUNDANT_IMPORTS, UNUSED_IMPORTS, }; use rustc_session::lint::BuiltinLintDiag; use rustc_span::edit_distance::find_best_match_for_name; @@ -36,8 +24,20 @@ use rustc_span::Span; use smallvec::SmallVec; use tracing::debug; -use std::cell::Cell; -use std::mem; +use crate::diagnostics::{import_candidates, DiagMode, Suggestion}; +use crate::errors::{ + CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS, CannotBeReexportedPrivate, + CannotBeReexportedPrivateNS, CannotDetermineImportResolution, CannotGlobImportAllCrates, + ConsiderAddingMacroExport, ConsiderMarkingAsPub, IsNotDirectlyImportable, + ItemsInTraitsAreNotImportable, +}; +use crate::Determinacy::{self, *}; +use crate::Namespace::*; +use crate::{ + module_to_string, names_to_string, AmbiguityError, AmbiguityKind, BindingKey, Finalize, + ImportSuggestion, Module, ModuleOrUniformRoot, NameBinding, NameBindingData, NameBindingKind, + ParentScope, PathResult, PerNS, ResolutionError, Resolver, ScopeSet, Segment, Used, +}; type Res = def::Res; @@ -48,6 +48,7 @@ pub(crate) enum ImportKind<'a> { /// `source` in `use prefix::source as target`. source: Ident, /// `target` in `use prefix::source as target`. + /// It will directly use `source` when the format is `use prefix::source`. target: Ident, /// Bindings to which `source` refers to. source_bindings: PerNS, Determinacy>>>, @@ -1387,14 +1388,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let mut redundant_spans: Vec<_> = redundant_span.present_items().collect(); redundant_spans.sort(); redundant_spans.dedup(); - /* FIXME(unused_imports): Add this back as a new lint - self.lint_buffer.buffer_lint_with_diagnostic( - UNUSED_IMPORTS, + self.lint_buffer.buffer_lint( + REDUNDANT_IMPORTS, id, import.span, BuiltinLintDiag::RedundantImport(redundant_spans, source), ); - */ return true; } diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 51414d785963d..f844930ad265e 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -6,16 +6,18 @@ //! If you wonder why there's no `early.rs`, that's because it's split into three files - //! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`. -use crate::{errors, path_names_to_string, rustdoc, BindingError, Finalize, LexicalScopeBinding}; -use crate::{BindingKey, Used}; -use crate::{Module, ModuleOrUniformRoot, NameBinding, ParentScope, PathResult}; -use crate::{ResolutionError, Resolver, Segment, TyCtxt, UseError}; +use std::assert_matches::debug_assert_matches; +use std::borrow::Cow; +use std::collections::hash_map::Entry; +use std::collections::BTreeSet; +use std::mem::{replace, swap, take}; use rustc_ast::ptr::P; use rustc_ast::visit::{visit_opt, walk_list, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor}; use rustc_ast::*; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; -use rustc_errors::{codes::*, Applicability, DiagArgValue, IntoDiagArg, StashKey}; +use rustc_errors::codes::*; +use rustc_errors::{Applicability, DiagArgValue, IntoDiagArg, StashKey}; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS}; use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; @@ -32,10 +34,11 @@ use rustc_span::{BytePos, Span, SyntaxContext}; use smallvec::{smallvec, SmallVec}; use tracing::{debug, instrument, trace}; -use std::assert_matches::debug_assert_matches; -use std::borrow::Cow; -use std::collections::{hash_map::Entry, BTreeSet}; -use std::mem::{replace, swap, take}; +use crate::{ + errors, path_names_to_string, rustdoc, BindingError, BindingKey, Finalize, LexicalScopeBinding, + Module, ModuleOrUniformRoot, NameBinding, ParentScope, PathResult, ResolutionError, Resolver, + Segment, TyCtxt, UseError, Used, +}; mod diagnostics; @@ -2668,17 +2671,17 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { // Store all seen lifetimes names from outer scopes. let mut seen_lifetimes = FxHashSet::default(); - // We also can't shadow bindings from the parent item - if let RibKind::AssocItem = kind { - let mut add_bindings_for_ns = |ns| { - let parent_rib = self.ribs[ns] - .iter() - .rfind(|r| matches!(r.kind, RibKind::Item(..))) - .expect("associated item outside of an item"); + // We also can't shadow bindings from associated parent items. + for ns in [ValueNS, TypeNS] { + for parent_rib in self.ribs[ns].iter().rev() { seen_bindings.extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span))); - }; - add_bindings_for_ns(ValueNS); - add_bindings_for_ns(TypeNS); + + // Break at mod level, to account for nested items which are + // allowed to shadow generic param names. + if matches!(parent_rib.kind, RibKind::Module(..)) { + break; + } + } } // Forbid shadowing lifetime bindings diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 941fb6436df92..f126563fe58f0 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -1,13 +1,8 @@ // ignore-tidy-filelength -use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion}; -use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind}; -use crate::late::{LifetimeBinderKind, LifetimeRes, LifetimeRibKind, LifetimeUseSet}; -use crate::ty::fast_reject::SimplifiedType; -use crate::{errors, path_names_to_string}; -use crate::{Module, ModuleKind, ModuleOrUniformRoot}; -use crate::{PathResult, PathSource, Segment}; -use rustc_hir::def::Namespace::{self, *}; +use std::borrow::Cow; +use std::iter; +use std::ops::Deref; use rustc_ast::ptr::P; use rustc_ast::visit::{walk_ty, FnCtxt, FnKind, LifetimeCtxt, Visitor}; @@ -16,34 +11,38 @@ use rustc_ast::{ MethodCall, NodeId, Path, Ty, TyKind, DUMMY_NODE_ID, }; use rustc_ast_pretty::pprust::where_bound_predicate_to_string; -use rustc_data_structures::fx::FxHashSet; -use rustc_data_structures::fx::FxIndexSet; +use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan, + pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan, SuggestionStyle, }; use rustc_hir as hir; +use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, CtorOf, DefKind}; use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; use rustc_hir::{MissingLifetimeKind, PrimTy}; -use rustc_session::lint; -use rustc_session::Session; +use rustc_middle::ty; +use rustc_session::{lint, Session}; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::edition::Edition; use rustc_span::hygiene::MacroKind; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; - -use rustc_middle::ty; - -use std::borrow::Cow; -use std::iter; -use std::ops::Deref; - use thin_vec::ThinVec; use tracing::debug; use super::NoConstantGenericsReason; +use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion}; +use crate::late::{ + AliasPossibility, LateResolutionVisitor, LifetimeBinderKind, LifetimeRes, LifetimeRibKind, + LifetimeUseSet, RibKind, +}; +use crate::ty::fast_reject::SimplifiedType; +use crate::{ + errors, path_names_to_string, Module, ModuleKind, ModuleOrUniformRoot, PathResult, PathSource, + Segment, +}; type Res = def::Res; diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 3dcb83d65b029..79d3bb685b384 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -23,11 +23,25 @@ #![feature(rustdoc_internals)] // tidy-alphabetical-end +use std::cell::{Cell, RefCell}; +use std::collections::BTreeSet; +use std::fmt; + +use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion}; +use effective_visibilities::EffectiveVisibilitiesVisitor; +use errors::{ + ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst, ParamKindInTyOfConstParam, +}; +use imports::{Import, ImportData, ImportKind, NameResolution}; +use late::{HasGenericParams, PathSource, PatternSource, UnnecessaryQualification}; +use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; use rustc_arena::{DroplessArena, TypedArena}; use rustc_ast::expand::StrippedCfgItem; use rustc_ast::node_id::NodeMap; -use rustc_ast::{self as ast, attr, NodeId, CRATE_NODE_ID}; -use rustc_ast::{AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, Path}; +use rustc_ast::{ + self as ast, attr, AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, + NodeId, Path, CRATE_NODE_ID, +}; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; use rustc_data_structures::steal::Steal; @@ -36,10 +50,10 @@ use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed}; use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind}; use rustc_feature::BUILTIN_ATTRIBUTES; use rustc_hir::def::Namespace::{self, *}; -use rustc_hir::def::NonMacroAttrKind; -use rustc_hir::def::{self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, PartialRes, PerNS}; -use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap}; -use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::def::{ + self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS, +}; +use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap, CRATE_DEF_ID, LOCAL_CRATE}; use rustc_hir::{PrimTy, TraitCandidate}; use rustc_index::IndexVec; use rustc_metadata::creader::{CStore, CrateLoader}; @@ -47,8 +61,10 @@ use rustc_middle::metadata::ModChild; use rustc_middle::middle::privacy::EffectiveVisibilities; use rustc_middle::query::Providers; use rustc_middle::span_bug; -use rustc_middle::ty::{self, DelegationFnSig, Feed, MainDefinition, RegisteredTools}; -use rustc_middle::ty::{ResolverGlobalCtxt, ResolverOutputs, TyCtxt, TyCtxtFeed}; +use rustc_middle::ty::{ + self, DelegationFnSig, Feed, MainDefinition, RegisteredTools, ResolverGlobalCtxt, + ResolverOutputs, TyCtxt, TyCtxtFeed, +}; use rustc_query_system::ich::StableHashingContext; use rustc_session::lint::builtin::PRIVATE_MACRO_USE; use rustc_session::lint::{BuiltinLintDiag, LintBuffer}; @@ -56,20 +72,8 @@ use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transpa use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; use smallvec::{smallvec, SmallVec}; -use std::cell::{Cell, RefCell}; -use std::collections::BTreeSet; -use std::fmt; use tracing::debug; -use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion}; -use effective_visibilities::EffectiveVisibilitiesVisitor; -use errors::{ - ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst, ParamKindInTyOfConstParam, -}; -use imports::{Import, ImportData, ImportKind, NameResolution}; -use late::{HasGenericParams, PathSource, PatternSource, UnnecessaryQualification}; -use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; - type Res = def::Res; mod build_reduced_graph; @@ -174,8 +178,8 @@ enum ImplTraitContext { /// Used for tracking import use types which will be used for redundant import checking. /// ### Used::Scope Example -/// ```rust,ignore (redundant_imports) -/// #![deny(unused_imports)] +/// ```rust,compile_fail +/// #![deny(redundant_imports)] /// use std::mem::drop; /// fn main() { /// let s = Box::new(32); @@ -1176,6 +1180,10 @@ pub struct Resolver<'a, 'tcx> { /// Simplified analogue of module `resolutions` but in trait impls, excluding glob delegations. /// Needed because glob delegations exclude explicitly defined names. impl_binding_keys: FxHashMap>, + + /// This is the `Span` where an `extern crate foo;` suggestion would be inserted, if `foo` + /// could be a crate that wasn't imported. For diagnostics use only. + current_crate_outer_attr_insert_span: Span, } /// Nothing really interesting here; it just provides memory for the rest of the crate. @@ -1338,6 +1346,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { tcx: TyCtxt<'tcx>, attrs: &[ast::Attribute], crate_span: Span, + current_crate_outer_attr_insert_span: Span, arenas: &'a ResolverArenas<'a>, ) -> Resolver<'a, 'tcx> { let root_def_id = CRATE_DEF_ID.to_def_id(); @@ -1521,6 +1530,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { glob_delegation_invoc_ids: Default::default(), impl_unexpanded_invocations: Default::default(), impl_binding_keys: Default::default(), + current_crate_outer_attr_insert_span, }; let root_parent_scope = ParentScope::module(graph_root, &resolver); diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index cb9bebd33d306..64ae0d82952d5 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -1,13 +1,9 @@ //! A bunch of methods and structures more or less related to resolving macros and //! interface provided by `Resolver` to macro expander. -use crate::errors::CannotDetermineMacroResolution; -use crate::errors::{self, AddAsNonDerive, CannotFindIdentInThisScope}; -use crate::errors::{MacroExpectedFound, RemoveSurroundingDerive}; -use crate::Namespace::*; -use crate::{BindingKey, BuiltinMacroState, Determinacy, MacroData, NameBindingKind, Used}; -use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet}; -use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment, ToNameBinding}; +use std::cell::Cell; +use std::mem; + use rustc_ast::expand::StrippedCfgItem; use rustc_ast::{self as ast, attr, Crate, Inline, ItemKind, ModKind, NodeId}; use rustc_ast_pretty::pprust; @@ -15,8 +11,10 @@ use rustc_attr::StabilityLevel; use rustc_data_structures::intern::Interned; use rustc_data_structures::sync::Lrc; use rustc_errors::{Applicability, StashKey}; -use rustc_expand::base::{Annotatable, DeriveResolution, Indeterminate, ResolverExpand}; -use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind}; +use rustc_expand::base::{ + Annotatable, DeriveResolution, Indeterminate, ResolverExpand, SyntaxExtension, + SyntaxExtensionKind, +}; use rustc_expand::compile_declarative_macro; use rustc_expand::expand::{ AstFragment, AstFragmentKind, Invocation, InvocationKind, SupportsMacroExpansion, @@ -24,8 +22,7 @@ use rustc_expand::expand::{ use rustc_hir::def::{self, DefKind, Namespace, NonMacroAttrKind}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_middle::middle::stability; -use rustc_middle::ty::RegisteredTools; -use rustc_middle::ty::{TyCtxt, Visibility}; +use rustc_middle::ty::{RegisteredTools, TyCtxt, Visibility}; use rustc_session::lint::builtin::{ LEGACY_DERIVE_HELPERS, OUT_OF_SCOPE_MACRO_CALLS, SOFT_UNSTABLE, UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, UNUSED_MACROS, UNUSED_MACRO_RULES, @@ -34,12 +31,20 @@ use rustc_session::lint::BuiltinLintDiag; use rustc_session::parse::feature_err; use rustc_span::edit_distance::edit_distance; use rustc_span::edition::Edition; -use rustc_span::hygiene::{self, ExpnData, ExpnKind, LocalExpnId}; -use rustc_span::hygiene::{AstPass, MacroKind}; +use rustc_span::hygiene::{self, AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; -use std::cell::Cell; -use std::mem; + +use crate::errors::{ + self, AddAsNonDerive, CannotDetermineMacroResolution, CannotFindIdentInThisScope, + MacroExpectedFound, RemoveSurroundingDerive, +}; +use crate::Namespace::*; +use crate::{ + BindingKey, BuiltinMacroState, DeriveData, Determinacy, Finalize, MacroData, ModuleKind, + ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult, ResolutionError, + Resolver, ScopeSet, Segment, ToNameBinding, Used, +}; type Res = def::Res; diff --git a/compiler/rustc_resolve/src/rustdoc.rs b/compiler/rustc_resolve/src/rustdoc.rs index 4c49c15c47258..de4fc5c27d40a 100644 --- a/compiler/rustc_resolve/src/rustdoc.rs +++ b/compiler/rustc_resolve/src/rustdoc.rs @@ -1,3 +1,6 @@ +use std::mem; +use std::ops::Range; + use pulldown_cmark::{ BrokenLink, BrokenLinkCallback, CowStr, Event, LinkType, Options, Parser, Tag, }; @@ -8,8 +11,6 @@ use rustc_middle::ty::TyCtxt; use rustc_span::def_id::DefId; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::{InnerSpan, Span, DUMMY_SP}; -use std::mem; -use std::ops::Range; use tracing::{debug, trace}; #[derive(Clone, Copy, PartialEq, Eq, Debug)] diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs index 190ea44318925..61de338eab1c0 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs @@ -5,9 +5,9 @@ //! For more information about LLVM CFI and cross-language LLVM CFI support for the Rust compiler, //! see design document in the tracking issue #89653. -use rustc_data_structures::base_n::ToBaseN; -use rustc_data_structures::base_n::ALPHANUMERIC_ONLY; -use rustc_data_structures::base_n::CASE_INSENSITIVE; +use std::fmt::Write as _; + +use rustc_data_structures::base_n::{ToBaseN, ALPHANUMERIC_ONLY, CASE_INSENSITIVE}; use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_middle::bug; @@ -20,7 +20,6 @@ use rustc_span::def_id::DefId; use rustc_span::sym; use rustc_target::abi::Integer; use rustc_target::spec::abi::Abi; -use std::fmt::Write as _; use tracing::instrument; use crate::cfi::typeid::itanium_cxx_abi::transform::{TransformTy, TransformTyOptions}; diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/mod.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/mod.rs index ac664c53f4454..cb15c67b895b8 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/mod.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/mod.rs @@ -6,7 +6,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_middle::bug; -use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable}; +use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; use rustc_target::abi::call::{Conv, FnAbi, PassMode}; use tracing::instrument; @@ -112,11 +112,12 @@ pub fn typeid_for_instance<'tcx>( instance: Instance<'tcx>, options: TypeIdOptions, ) -> String { + assert!(!instance.has_non_region_param(), "{instance:#?} must be fully monomorphic"); let transform_ty_options = TransformTyOptions::from_bits(options.bits()) .unwrap_or_else(|| bug!("typeid_for_instance: invalid option(s) `{:?}`", options.bits())); let instance = transform_instance(tcx, instance, transform_ty_options); let fn_abi = tcx - .fn_abi_of_instance(tcx.param_env(instance.def_id()).and((instance, ty::List::empty()))) + .fn_abi_of_instance(ty::ParamEnv::reveal_all().and((instance, ty::List::empty()))) .unwrap_or_else(|error| { bug!("typeid_for_instance: couldn't get fn_abi of instance {instance:?}: {error:?}") }); diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs index 9b05576d721c5..e628c17aca3cb 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs @@ -4,6 +4,8 @@ //! For more information about LLVM CFI and cross-language LLVM CFI support for the Rust compiler, //! see design document in the tracking issue #89653. +use std::iter; + use rustc_hir as hir; use rustc_hir::LangItem; use rustc_middle::bug; @@ -12,9 +14,9 @@ use rustc_middle::ty::{ self, ExistentialPredicateStableCmpExt as _, Instance, InstanceKind, IntTy, List, TraitRef, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, UintTy, }; -use rustc_span::{def_id::DefId, sym}; +use rustc_span::def_id::DefId; +use rustc_span::sym; use rustc_trait_selection::traits; -use std::iter; use tracing::{debug, instrument}; use crate::cfi::typeid::itanium_cxx_abi::encode::EncodeTyOptions; @@ -230,6 +232,7 @@ fn trait_object_ty<'tcx>(tcx: TyCtxt<'tcx>, poly_trait_ref: ty::PolyTraitRef<'tc tcx.associated_items(super_poly_trait_ref.def_id()) .in_definition_order() .filter(|item| item.kind == ty::AssocKind::Type) + .filter(|item| !tcx.generics_require_sized_self(item.def_id)) .map(move |assoc_ty| { super_poly_trait_ref.map_bound(|super_trait_ref| { let alias_ty = diff --git a/compiler/rustc_sanitizers/src/kcfi/typeid/mod.rs b/compiler/rustc_sanitizers/src/kcfi/typeid/mod.rs index bfe907e3cf6ae..b47a091ab64d2 100644 --- a/compiler/rustc_sanitizers/src/kcfi/typeid/mod.rs +++ b/compiler/rustc_sanitizers/src/kcfi/typeid/mod.rs @@ -4,9 +4,10 @@ //! For more information about LLVM KCFI and cross-language LLVM KCFI support for the Rust compiler, //! see the tracking issue #123479. +use std::hash::Hasher; + use rustc_middle::ty::{Instance, InstanceKind, ReifyReason, Ty, TyCtxt}; use rustc_target::abi::call::FnAbi; -use std::hash::Hasher; use twox_hash::XxHash64; pub use crate::cfi::typeid::{itanium_cxx_abi, TypeIdOptions}; diff --git a/compiler/rustc_serialize/src/leb128.rs b/compiler/rustc_serialize/src/leb128.rs index 4432480446822..aa7c285846661 100644 --- a/compiler/rustc_serialize/src/leb128.rs +++ b/compiler/rustc_serialize/src/leb128.rs @@ -1,9 +1,8 @@ -use crate::opaque::MemDecoder; -use crate::serialize::Decoder; - // This code is very hot and uses lots of arithmetic, avoid overflow checks for performance. // See https://github.com/rust-lang/rust/pull/119440#issuecomment-1874255727 use crate::int_overflow::DebugStrictAdd; +use crate::opaque::MemDecoder; +use crate::serialize::Decoder; /// Returns the length of the longest LEB128 encoding for `T`, assuming `T` is an integer type pub const fn max_leb128_len() -> usize { diff --git a/compiler/rustc_serialize/src/opaque.rs b/compiler/rustc_serialize/src/opaque.rs index d27dfd888245b..d8609ccfe429f 100644 --- a/compiler/rustc_serialize/src/opaque.rs +++ b/compiler/rustc_serialize/src/opaque.rs @@ -1,15 +1,14 @@ -use crate::leb128; -use crate::serialize::{Decodable, Decoder, Encodable, Encoder}; use std::fs::File; use std::io::{self, Write}; use std::marker::PhantomData; use std::ops::Range; -use std::path::Path; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; // This code is very hot and uses lots of arithmetic, avoid overflow checks for performance. // See https://github.com/rust-lang/rust/pull/119440#issuecomment-1874255727 use crate::int_overflow::DebugStrictAdd; +use crate::leb128; +use crate::serialize::{Decodable, Decoder, Encodable, Encoder}; // ----------------------------------------------------------------------------- // Encoder diff --git a/compiler/rustc_serialize/src/serialize.rs b/compiler/rustc_serialize/src/serialize.rs index c84bb26735c5b..2d37f5bdab800 100644 --- a/compiler/rustc_serialize/src/serialize.rs +++ b/compiler/rustc_serialize/src/serialize.rs @@ -1,6 +1,5 @@ //! Support code for encoding and decoding types. -use smallvec::{Array, SmallVec}; use std::borrow::Cow; use std::cell::{Cell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; @@ -10,6 +9,8 @@ use std::num::NonZero; use std::path; use std::rc::Rc; use std::sync::Arc; + +use smallvec::{Array, SmallVec}; use thin_vec::ThinVec; /// A byte that [cannot occur in UTF8 sequences][utf8]. Used to mark the end of a string. diff --git a/compiler/rustc_serialize/tests/leb128.rs b/compiler/rustc_serialize/tests/leb128.rs index fafe4b91a95d3..b06a28d7c95df 100644 --- a/compiler/rustc_serialize/tests/leb128.rs +++ b/compiler/rustc_serialize/tests/leb128.rs @@ -1,6 +1,5 @@ use rustc_serialize::leb128::*; -use rustc_serialize::opaque::MemDecoder; -use rustc_serialize::opaque::MAGIC_END_BYTES; +use rustc_serialize::opaque::{MemDecoder, MAGIC_END_BYTES}; use rustc_serialize::Decoder; macro_rules! impl_test_unsigned_leb128 { diff --git a/compiler/rustc_serialize/tests/opaque.rs b/compiler/rustc_serialize/tests/opaque.rs index 833151d82be35..0543e176ae5aa 100644 --- a/compiler/rustc_serialize/tests/opaque.rs +++ b/compiler/rustc_serialize/tests/opaque.rs @@ -1,10 +1,11 @@ #![allow(rustc::internal)] +use std::fmt::Debug; +use std::fs; + use rustc_macros::{Decodable_Generic, Encodable_Generic}; use rustc_serialize::opaque::{FileEncoder, MemDecoder}; use rustc_serialize::{Decodable, Encodable}; -use std::fmt::Debug; -use std::fs; #[derive(PartialEq, Clone, Debug, Encodable_Generic, Decodable_Generic)] struct Struct { diff --git a/compiler/rustc_session/src/code_stats.rs b/compiler/rustc_session/src/code_stats.rs index 93839fa1186af..3668fe4f0a807 100644 --- a/compiler/rustc_session/src/code_stats.rs +++ b/compiler/rustc_session/src/code_stats.rs @@ -1,9 +1,10 @@ +use std::cmp; + use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::sync::Lock; use rustc_span::def_id::DefId; use rustc_span::Symbol; use rustc_target::abi::{Align, Size}; -use std::cmp; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct VariantInfo { diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index e748d1ff47b63..f58a991a616da 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -3,13 +3,17 @@ #![allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable -pub use crate::options::*; +use std::collections::btree_map::{ + Iter as BTreeMapIter, Keys as BTreeMapKeysIter, Values as BTreeMapValuesIter, +}; +use std::collections::{BTreeMap, BTreeSet}; +use std::ffi::OsStr; +use std::hash::Hash; +use std::path::{Path, PathBuf}; +use std::str::{self, FromStr}; +use std::sync::LazyLock; +use std::{fmt, fs, iter}; -use crate::errors::FileWriteFail; -use crate::search_paths::SearchPath; -use crate::utils::{CanonicalizedPath, NativeLib, NativeLibKind}; -use crate::{filesearch, lint, HashStableContext}; -use crate::{EarlyDiagCtxt, Session}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::stable_hasher::{StableOrd, ToStableHashKey}; use rustc_errors::emitter::HumanReadableErrorType; @@ -19,22 +23,17 @@ use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_span::edition::{Edition, DEFAULT_EDITION, EDITION_NAME_LIST, LATEST_STABLE_EDITION}; use rustc_span::source_map::FilePathMapping; use rustc_span::{FileName, FileNameDisplayPreference, RealFileName, SourceFileHashAlgorithm}; -use rustc_target::spec::{FramePointer, LinkSelfContainedComponents, LinkerFeatures}; -use rustc_target::spec::{SplitDebuginfo, Target, TargetTriple}; -use std::collections::btree_map::{ - Iter as BTreeMapIter, Keys as BTreeMapKeysIter, Values as BTreeMapValuesIter, +use rustc_target::spec::{ + FramePointer, LinkSelfContainedComponents, LinkerFeatures, SplitDebuginfo, Target, TargetTriple, }; -use std::collections::{BTreeMap, BTreeSet}; -use std::ffi::OsStr; -use std::fmt; -use std::fs; -use std::hash::Hash; -use std::iter; -use std::path::{Path, PathBuf}; -use std::str::{self, FromStr}; -use std::sync::LazyLock; use tracing::debug; +use crate::errors::FileWriteFail; +pub use crate::options::*; +use crate::search_paths::SearchPath; +use crate::utils::{CanonicalizedPath, NativeLib, NativeLibKind}; +use crate::{filesearch, lint, EarlyDiagCtxt, HashStableContext, Session}; + mod cfg; pub mod sigpipe; @@ -2765,9 +2764,10 @@ pub fn parse_crate_types_from_list(list_list: Vec) -> Result bool { match_is_nightly_build(matches) @@ -2960,6 +2960,22 @@ pub enum WasiExecModel { /// we have an opt-in scheme here, so one is hopefully forced to think about /// how the hash should be calculated when adding a new command-line argument. pub(crate) mod dep_tracking { + use std::collections::BTreeMap; + use std::hash::{DefaultHasher, Hash}; + use std::num::NonZero; + use std::path::PathBuf; + + use rustc_data_structures::fx::FxIndexMap; + use rustc_data_structures::stable_hasher::Hash64; + use rustc_errors::LanguageIdentifier; + use rustc_feature::UnstableFeatures; + use rustc_span::edition::Edition; + use rustc_span::RealFileName; + use rustc_target::spec::{ + CodeModel, FramePointer, MergeFunctions, OnBrokenPipe, PanicStrategy, RelocModel, + RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, TargetTriple, TlsModel, WasmCAbi, + }; + use super::{ BranchProtection, CFGuard, CFProtection, CollapseMacroDebuginfo, CoverageOptions, CrateType, DebugInfo, DebugInfoCompression, ErrorOutputType, FunctionReturn, @@ -2971,20 +2987,6 @@ pub(crate) mod dep_tracking { }; use crate::lint; use crate::utils::NativeLib; - use rustc_data_structures::fx::FxIndexMap; - use rustc_data_structures::stable_hasher::Hash64; - use rustc_errors::LanguageIdentifier; - use rustc_feature::UnstableFeatures; - use rustc_span::edition::Edition; - use rustc_span::RealFileName; - use rustc_target::spec::{ - CodeModel, FramePointer, MergeFunctions, OnBrokenPipe, PanicStrategy, RelocModel, - RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, TargetTriple, TlsModel, WasmCAbi, - }; - use std::collections::BTreeMap; - use std::hash::{DefaultHasher, Hash}; - use std::num::NonZero; - use std::path::PathBuf; pub(crate) trait DepTrackingHash { fn hash( diff --git a/compiler/rustc_session/src/config/cfg.rs b/compiler/rustc_session/src/config/cfg.rs index 2fa04bbe345e8..4109ebb6d340a 100644 --- a/compiler/rustc_session/src/config/cfg.rs +++ b/compiler/rustc_session/src/config/cfg.rs @@ -19,18 +19,17 @@ //! so that the compiler can know the cfg is expected //! - Add the feature gating in `compiler/rustc_feature/src/builtin_attrs.rs` +use std::hash::Hash; +use std::iter; + use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_span::symbol::{sym, Symbol}; use rustc_target::abi::Align; -use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet}; -use rustc_target::spec::{Target, TargetTriple, TARGETS}; +use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, Target, TargetTriple, TARGETS}; use crate::config::CrateType; use crate::Session; -use std::hash::Hash; -use std::iter; - /// The parsed `--cfg` options that define the compilation environment of the /// crate, used to drive conditional compilation. /// diff --git a/compiler/rustc_session/src/cstore.rs b/compiler/rustc_session/src/cstore.rs index 2c20c3f0e1a34..da7a82fee94d0 100644 --- a/compiler/rustc_session/src/cstore.rs +++ b/compiler/rustc_session/src/cstore.rs @@ -2,8 +2,9 @@ //! are *mostly* used as a part of that interface, but these should //! probably get a better home if someone can find one. -use crate::search_paths::PathKind; -use crate::utils::NativeLibKind; +use std::any::Any; +use std::path::PathBuf; + use rustc_ast as ast; use rustc_data_structures::sync::{self, AppendOnlyIndexVec, FreezeLock}; use rustc_hir::def_id::{ @@ -15,8 +16,8 @@ use rustc_span::symbol::Symbol; use rustc_span::Span; use rustc_target::spec::abi::Abi; -use std::any::Any; -use std::path::PathBuf; +use crate::search_paths::PathKind; +use crate::utils::NativeLibKind; // lonely orphan structs and enums looking for a better home diff --git a/compiler/rustc_session/src/errors.rs b/compiler/rustc_session/src/errors.rs index 4cbc1b570225b..5cc54a5855bbe 100644 --- a/compiler/rustc_session/src/errors.rs +++ b/compiler/rustc_session/src/errors.rs @@ -2,15 +2,17 @@ use std::num::NonZero; use rustc_ast::token; use rustc_ast::util::literal::LitError; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, Diag, DiagCtxtHandle, DiagMessage, Diagnostic, EmissionGuarantee, ErrorGuaranteed, - Level, MultiSpan, + Diag, DiagCtxtHandle, DiagMessage, Diagnostic, EmissionGuarantee, ErrorGuaranteed, Level, + MultiSpan, }; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Span, Symbol}; use rustc_target::spec::{SplitDebuginfo, StackProtector, TargetTriple}; -use crate::{config::CrateType, parse::ParseSess}; +use crate::config::CrateType; +use crate::parse::ParseSess; pub(crate) struct FeatureGateError { pub(crate) span: MultiSpan, diff --git a/compiler/rustc_session/src/filesearch.rs b/compiler/rustc_session/src/filesearch.rs index 6f63776bedcc4..63ca5fefd9faf 100644 --- a/compiler/rustc_session/src/filesearch.rs +++ b/compiler/rustc_session/src/filesearch.rs @@ -1,13 +1,14 @@ //! A module for searching for libraries -use crate::search_paths::{PathKind, SearchPath}; +use std::path::{Path, PathBuf}; +use std::{env, fs}; + use rustc_fs_util::{fix_windows_verbatim_for_gcc, try_canonicalize}; use smallvec::{smallvec, SmallVec}; -use std::env; -use std::fs; -use std::path::{Path, PathBuf}; use tracing::debug; +use crate::search_paths::{PathKind, SearchPath}; + #[derive(Clone)] pub struct FileSearch<'a> { sysroot: &'a Path, @@ -18,6 +19,11 @@ pub struct FileSearch<'a> { } impl<'a> FileSearch<'a> { + pub fn cli_search_paths(&self) -> impl Iterator { + let kind = self.kind; + self.cli_search_paths.iter().filter(move |sp| sp.kind.matches(kind)) + } + pub fn search_paths(&self) -> impl Iterator { let kind = self.kind; self.cli_search_paths @@ -129,12 +135,10 @@ fn current_dll_path() -> Result { use std::io; use std::os::windows::prelude::*; - use windows::{ - core::PCWSTR, - Win32::Foundation::HMODULE, - Win32::System::LibraryLoader::{ - GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, - }, + use windows::core::PCWSTR; + use windows::Win32::Foundation::HMODULE; + use windows::Win32::System::LibraryLoader::{ + GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, }; let mut module = HMODULE::default(); diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 8fd1876ff1d29..bf54aae1cfeb0 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1,26 +1,26 @@ -use crate::config::*; -use crate::search_paths::SearchPath; -use crate::utils::NativeLib; -use crate::{lint, EarlyDiagCtxt}; +use std::collections::BTreeMap; +use std::hash::{DefaultHasher, Hasher}; +use std::num::{IntErrorKind, NonZero}; +use std::path::PathBuf; +use std::str; + use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::profiling::TimePassesFormat; use rustc_data_structures::stable_hasher::Hash64; -use rustc_errors::ColorConfig; -use rustc_errors::{LanguageIdentifier, TerminalUrl}; +use rustc_errors::{ColorConfig, LanguageIdentifier, TerminalUrl}; use rustc_feature::UnstableFeatures; use rustc_span::edition::Edition; -use rustc_span::RealFileName; -use rustc_span::SourceFileHashAlgorithm; +use rustc_span::{RealFileName, SourceFileHashAlgorithm}; use rustc_target::spec::{ CodeModel, FramePointer, LinkerFlavorCli, MergeFunctions, OnBrokenPipe, PanicStrategy, RelocModel, RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, TargetTriple, TlsModel, WasmCAbi, }; -use std::collections::BTreeMap; -use std::hash::{DefaultHasher, Hasher}; -use std::num::{IntErrorKind, NonZero}; -use std::path::PathBuf; -use std::str; + +use crate::config::*; +use crate::search_paths::SearchPath; +use crate::utils::NativeLib; +use crate::{lint, EarlyDiagCtxt}; macro_rules! insert { ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr) => { @@ -447,9 +447,10 @@ mod desc { } mod parse { - pub(crate) use super::*; use std::str::FromStr; + pub(crate) use super::*; + /// This is for boolean options that don't take a value and start with /// `no-`. This style of option is deprecated. pub(crate) fn parse_no_flag(slot: &mut bool, v: Option<&str>) -> bool { diff --git a/compiler/rustc_session/src/output.rs b/compiler/rustc_session/src/output.rs index 9a5314312e567..c2ca19e563cdd 100644 --- a/compiler/rustc_session/src/output.rs +++ b/compiler/rustc_session/src/output.rs @@ -1,16 +1,18 @@ //! Related to out filenames of compilation (e.g. binaries). +use std::path::Path; + +use rustc_ast::{self as ast, attr}; +use rustc_errors::FatalError; +use rustc_span::symbol::sym; +use rustc_span::{Span, Symbol}; + use crate::config::{self, CrateType, Input, OutFileName, OutputFilenames, OutputType}; use crate::errors::{ self, CrateNameDoesNotMatch, CrateNameEmpty, CrateNameInvalid, FileIsNotWriteable, InvalidCharacterInCrateName, InvalidCrateNameHelp, }; use crate::Session; -use rustc_ast::{self as ast, attr}; -use rustc_errors::FatalError; -use rustc_span::symbol::sym; -use rustc_span::{Span, Symbol}; -use std::path::Path; pub fn out_filename( sess: &Session, diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 200505aaea209..ebd5021dae1b9 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -1,15 +1,9 @@ //! Contains `ParseSess` which holds state living beyond what one `Parser` might. //! It also serves as an input to the parser itself. -use crate::config::{Cfg, CheckCfg}; -use crate::errors::{ - CliFeatureDiagnosticHelp, FeatureDiagnosticForIssue, FeatureDiagnosticHelp, - FeatureDiagnosticSuggestion, FeatureGateError, SuggestUpgradeCompiler, -}; -use crate::lint::{ - builtin::UNSTABLE_SYNTAX_PRE_EXPANSION, BufferedEarlyLint, BuiltinLintDiag, Lint, LintId, -}; -use crate::Session; +use std::str; + +use rustc_ast::attr::AttrIdGenerator; use rustc_ast::node_id::NodeId; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; use rustc_data_structures::sync::{AppendOnlyVec, Lock, Lrc}; @@ -24,8 +18,14 @@ use rustc_span::hygiene::ExpnId; use rustc_span::source_map::{FilePathMapping, SourceMap}; use rustc_span::{Span, Symbol}; -use rustc_ast::attr::AttrIdGenerator; -use std::str; +use crate::config::{Cfg, CheckCfg}; +use crate::errors::{ + CliFeatureDiagnosticHelp, FeatureDiagnosticForIssue, FeatureDiagnosticHelp, + FeatureDiagnosticSuggestion, FeatureGateError, SuggestUpgradeCompiler, +}; +use crate::lint::builtin::UNSTABLE_SYNTAX_PRE_EXPANSION; +use crate::lint::{BufferedEarlyLint, BuiltinLintDiag, Lint, LintId}; +use crate::Session; /// Collected spans during parsing for places where a certain feature was /// used and should be feature gated accordingly in `check_crate`. diff --git a/compiler/rustc_session/src/search_paths.rs b/compiler/rustc_session/src/search_paths.rs index 5e8adffc249e6..d65b1b8b3f15a 100644 --- a/compiler/rustc_session/src/search_paths.rs +++ b/compiler/rustc_session/src/search_paths.rs @@ -1,8 +1,10 @@ -use crate::filesearch::make_target_lib_path; -use crate::EarlyDiagCtxt; +use std::path::{Path, PathBuf}; + use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_target::spec::TargetTriple; -use std::path::{Path, PathBuf}; + +use crate::filesearch::make_target_lib_path; +use crate::EarlyDiagCtxt; #[derive(Clone, Debug)] pub struct SearchPath { diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 89d029fa6e0ed..be67baf57f6dc 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -1,14 +1,11 @@ -use crate::code_stats::CodeStats; -pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo}; -use crate::config::{ - self, CoverageLevel, CrateType, FunctionReturn, InstrumentCoverage, OptLevel, OutFileName, - OutputType, RemapPathScopeComponents, SwitchWithOptPath, -}; -use crate::config::{ErrorOutputType, Input}; -use crate::errors; -use crate::parse::{add_feature_diagnostics, ParseSess}; -use crate::search_paths::{PathKind, SearchPath}; -use crate::{filesearch, lint}; +use std::any::Any; +use std::ops::{Div, Mul}; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering::SeqCst; +use std::sync::Arc; +use std::{env, fmt, io}; use rustc_data_structures::flock; use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; @@ -18,33 +15,34 @@ use rustc_data_structures::sync::{ AtomicU64, DynSend, DynSync, Lock, Lrc, MappedReadGuard, ReadGuard, RwLock, }; use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter; +use rustc_errors::codes::*; use rustc_errors::emitter::{stderr_destination, DynEmitter, HumanEmitter, HumanReadableErrorType}; use rustc_errors::json::JsonEmitter; use rustc_errors::registry::Registry; use rustc_errors::{ - codes::*, fallback_fluent_bundle, Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, + fallback_fluent_bundle, Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort, FluentBundle, LazyFallbackBundle, TerminalUrl, }; use rustc_macros::HashStable_Generic; pub use rustc_span::def_id::StableCrateId; use rustc_span::edition::Edition; use rustc_span::source_map::{FilePathMapping, SourceMap}; -use rustc_span::{FileNameDisplayPreference, RealFileName}; -use rustc_span::{Span, Symbol}; +use rustc_span::{FileNameDisplayPreference, RealFileName, Span, Symbol}; use rustc_target::asm::InlineAsmArch; -use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel}; use rustc_target::spec::{ - DebuginfoKind, SanitizerSet, SplitDebuginfo, StackProtector, Target, TargetTriple, TlsModel, + CodeModel, DebuginfoKind, PanicStrategy, RelocModel, RelroLevel, SanitizerSet, SplitDebuginfo, + StackProtector, Target, TargetTriple, TlsModel, }; -use std::any::Any; -use std::env; -use std::fmt; -use std::io; -use std::ops::{Div, Mul}; -use std::path::{Path, PathBuf}; -use std::str::FromStr; -use std::sync::{atomic::AtomicBool, atomic::Ordering::SeqCst, Arc}; +use crate::code_stats::CodeStats; +pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo}; +use crate::config::{ + self, CoverageLevel, CrateType, ErrorOutputType, FunctionReturn, Input, InstrumentCoverage, + OptLevel, OutFileName, OutputType, RemapPathScopeComponents, SwitchWithOptPath, +}; +use crate::parse::{add_feature_diagnostics, ParseSess}; +use crate::search_paths::{PathKind, SearchPath}; +use crate::{errors, filesearch, lint}; struct OptimizationFuel { /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`. diff --git a/compiler/rustc_session/src/utils.rs b/compiler/rustc_session/src/utils.rs index f70a53eeb4108..37528a4425f58 100644 --- a/compiler/rustc_session/src/utils.rs +++ b/compiler/rustc_session/src/utils.rs @@ -1,11 +1,11 @@ -use crate::session::Session; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + use rustc_data_structures::profiling::VerboseTimingGuard; use rustc_fs_util::try_canonicalize; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use std::{ - path::{Path, PathBuf}, - sync::OnceLock, -}; + +use crate::session::Session; impl Session { pub fn timer(&self, what: &'static str) -> VerboseTimingGuard<'_> { diff --git a/compiler/rustc_session/src/version.rs b/compiler/rustc_session/src/version.rs index e244c77f7f95b..79f97fd327ac7 100644 --- a/compiler/rustc_session/src/version.rs +++ b/compiler/rustc_session/src/version.rs @@ -1,10 +1,8 @@ -use rustc_macros::{current_rustc_version, Decodable, Encodable, HashStable_Generic}; -use std::{ - borrow::Cow, - fmt::{self, Display}, -}; +use std::borrow::Cow; +use std::fmt::{self, Display}; use rustc_errors::IntoDiagArg; +use rustc_macros::{current_rustc_version, Decodable, Encodable, HashStable_Generic}; #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(HashStable_Generic)] diff --git a/compiler/rustc_smir/src/rustc_internal/internal.rs b/compiler/rustc_smir/src/rustc_internal/internal.rs index 854295dc04818..a4577461094bb 100644 --- a/compiler/rustc_smir/src/rustc_internal/internal.rs +++ b/compiler/rustc_smir/src/rustc_internal/internal.rs @@ -5,7 +5,6 @@ // Prefer importing stable_mir over internal rustc constructs to make this file more readable. -use crate::rustc_smir::Tables; use rustc_middle::ty::{self as rustc_ty, Const as InternalConst, Ty as InternalTy, TyCtxt}; use rustc_span::Symbol; use stable_mir::abi::Layout; @@ -21,6 +20,7 @@ use stable_mir::ty::{ use stable_mir::{CrateItem, CrateNum, DefId}; use super::RustcInternal; +use crate::rustc_smir::Tables; impl RustcInternal for CrateItem { type T<'tcx> = rustc_span::def_id::DefId; diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs index 810ffc142a09f..e997ea25ec863 100644 --- a/compiler/rustc_smir/src/rustc_internal/mod.rs +++ b/compiler/rustc_smir/src/rustc_internal/mod.rs @@ -3,7 +3,11 @@ //! For that, we define APIs that will temporarily be public to 3P that exposes rustc internal APIs //! until stable MIR is complete. -use crate::rustc_smir::{context::TablesWrapper, Stable, Tables}; +use std::cell::{Cell, RefCell}; +use std::fmt::Debug; +use std::hash::Hash; +use std::ops::Index; + use rustc_data_structures::fx; use rustc_data_structures::fx::FxIndexMap; use rustc_middle::mir::interpret::AllocId; @@ -15,11 +19,9 @@ use scoped_tls::scoped_thread_local; use stable_mir::abi::Layout; use stable_mir::ty::IndexedVal; use stable_mir::Error; -use std::cell::Cell; -use std::cell::RefCell; -use std::fmt::Debug; -use std::hash::Hash; -use std::ops::Index; + +use crate::rustc_smir::context::TablesWrapper; +use crate::rustc_smir::{Stable, Tables}; mod internal; pub mod pretty; diff --git a/compiler/rustc_smir/src/rustc_internal/pretty.rs b/compiler/rustc_smir/src/rustc_internal/pretty.rs index c0dce08b0d33a..b752ad71ecc64 100644 --- a/compiler/rustc_smir/src/rustc_internal/pretty.rs +++ b/compiler/rustc_smir/src/rustc_internal/pretty.rs @@ -1,8 +1,9 @@ use std::io; -use super::run; use rustc_middle::ty::TyCtxt; +use super::run; + pub fn write_smir_pretty<'tcx, W: io::Write>(tcx: TyCtxt<'tcx>, w: &mut W) -> io::Result<()> { writeln!( w, diff --git a/compiler/rustc_smir/src/rustc_smir/alloc.rs b/compiler/rustc_smir/src/rustc_smir/alloc.rs index 5d02e3d6e9213..0519722e4be71 100644 --- a/compiler/rustc_smir/src/rustc_smir/alloc.rs +++ b/compiler/rustc_smir/src/rustc_smir/alloc.rs @@ -1,12 +1,10 @@ -use rustc_middle::mir::{ - interpret::{alloc_range, AllocRange, Pointer}, - ConstValue, -}; +use rustc_middle::mir::interpret::{alloc_range, AllocRange, Pointer}; +use rustc_middle::mir::ConstValue; +use stable_mir::mir::Mutability; +use stable_mir::ty::{Allocation, ProvenanceMap}; use stable_mir::Error; use crate::rustc_smir::{Stable, Tables}; -use stable_mir::mir::Mutability; -use stable_mir::ty::{Allocation, ProvenanceMap}; /// Creates new empty `Allocation` from given `Align`. fn new_empty_allocation(align: rustc_target::abi::Align) -> Allocation { diff --git a/compiler/rustc_smir/src/rustc_smir/builder.rs b/compiler/rustc_smir/src/rustc_smir/builder.rs index 09866515a2ab5..883ab7c18b485 100644 --- a/compiler/rustc_smir/src/rustc_smir/builder.rs +++ b/compiler/rustc_smir/src/rustc_smir/builder.rs @@ -4,12 +4,13 @@ //! monomorphic body using internal representation. //! After that, we convert the internal representation into a stable one. -use crate::rustc_smir::{Stable, Tables}; use rustc_hir::def::DefKind; use rustc_middle::mir; use rustc_middle::mir::visit::MutVisitor; use rustc_middle::ty::{self, TyCtxt}; +use crate::rustc_smir::{Stable, Tables}; + /// Builds a monomorphic body for a given instance. pub struct BodyBuilder<'tcx> { tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_smir/src/rustc_smir/context.rs b/compiler/rustc_smir/src/rustc_smir/context.rs index b0ced8e920fe5..f9663f2dd30d9 100644 --- a/compiler/rustc_smir/src/rustc_smir/context.rs +++ b/compiler/rustc_smir/src/rustc_smir/context.rs @@ -5,6 +5,9 @@ #![allow(rustc::usage_of_qualified_ty)] +use std::cell::RefCell; +use std::iter; + use rustc_abi::HasDataLayout; use rustc_hir::LangItem; use rustc_middle::ty::layout::{ @@ -28,8 +31,6 @@ use stable_mir::ty::{ TyConst, TyKind, UintTy, VariantDef, }; use stable_mir::{Crate, CrateDef, CrateItem, CrateNum, DefId, Error, Filename, ItemKind, Symbol}; -use std::cell::RefCell; -use std::iter; use crate::rustc_internal::RustcInternal; use crate::rustc_smir::builder::BodyBuilder; diff --git a/compiler/rustc_smir/src/rustc_smir/convert/abi.rs b/compiler/rustc_smir/src/rustc_smir/convert/abi.rs index cbc3aae1703ea..9f554ec6c3593 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/abi.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/abi.rs @@ -2,7 +2,6 @@ #![allow(rustc::usage_of_qualified_ty)] -use crate::rustc_smir::{Stable, Tables}; use rustc_middle::ty; use rustc_target::abi::call::Conv; use stable_mir::abi::{ @@ -14,6 +13,8 @@ use stable_mir::opaque; use stable_mir::target::MachineSize as Size; use stable_mir::ty::{Align, IndexedVal, VariantIdx}; +use crate::rustc_smir::{Stable, Tables}; + impl<'tcx> Stable<'tcx> for rustc_target::abi::VariantIdx { type T = VariantIdx; fn stable(&self, _: &mut Tables<'_>) -> Self::T { diff --git a/compiler/rustc_smir/src/rustc_smir/convert/error.rs b/compiler/rustc_smir/src/rustc_smir/convert/error.rs index 3d68970891551..82ecfa630ddb0 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/error.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/error.rs @@ -2,10 +2,11 @@ //! //! Currently we encode everything as [stable_mir::Error], which is represented as a string. -use crate::rustc_smir::{Stable, Tables}; use rustc_middle::mir::interpret::AllocError; use rustc_middle::ty::layout::LayoutError; +use crate::rustc_smir::{Stable, Tables}; + impl<'tcx> Stable<'tcx> for LayoutError<'tcx> { type T = stable_mir::Error; diff --git a/compiler/rustc_smir/src/rustc_smir/convert/mir.rs b/compiler/rustc_smir/src/rustc_smir/convert/mir.rs index 8bfaa112c2fc3..da705e6f9598a 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/mir.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/mir.rs @@ -1,9 +1,8 @@ //! Conversion of internal Rust compiler `mir` items to stable ones. -use rustc_middle::bug; -use rustc_middle::mir; use rustc_middle::mir::interpret::alloc_range; use rustc_middle::mir::mono::MonoItem; +use rustc_middle::{bug, mir}; use stable_mir::mir::alloc::GlobalAlloc; use stable_mir::mir::{ConstOperand, Statement, UserTypeProjection, VarDebugInfoFragment}; use stable_mir::ty::{Allocation, ConstantKind, MirConst}; diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 82522e995d63f..41e9698242bbd 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -7,6 +7,8 @@ //! //! For now, we are developing everything inside `rustc`, thus, we keep this module private. +use std::ops::RangeInclusive; + use rustc_hir::def::DefKind; use rustc_middle::mir; use rustc_middle::mir::interpret::AllocId; @@ -16,7 +18,6 @@ use stable_mir::abi::Layout; use stable_mir::mir::mono::InstanceDef; use stable_mir::ty::{MirConstId, Span, TyConstId}; use stable_mir::{CtorKind, ItemKind}; -use std::ops::RangeInclusive; use tracing::debug; use crate::rustc_internal::IndexMap; diff --git a/compiler/rustc_span/Cargo.toml b/compiler/rustc_span/Cargo.toml index 83a554fe31de0..3fdfe77ead972 100644 --- a/compiler/rustc_span/Cargo.toml +++ b/compiler/rustc_span/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start -derivative = "2.2.0" +derive-where = "1.2.7" indexmap = { version = "2.0.0" } itoa = "1.0" md5 = { package = "md-5", version = "0.10.0" } diff --git a/compiler/rustc_span/src/analyze_source_file.rs b/compiler/rustc_span/src/analyze_source_file.rs index d9e1ebaf0bce0..ba7e0cec5bd80 100644 --- a/compiler/rustc_span/src/analyze_source_file.rs +++ b/compiler/rustc_span/src/analyze_source_file.rs @@ -1,5 +1,4 @@ use super::*; -use unicode_width::UnicodeWidthChar; #[cfg(test)] mod tests; @@ -9,15 +8,12 @@ mod tests; /// /// This function will use an SSE2 enhanced implementation if hardware support /// is detected at runtime. -pub fn analyze_source_file( - src: &str, -) -> (Vec, Vec, Vec) { +pub fn analyze_source_file(src: &str) -> (Vec, Vec) { let mut lines = vec![RelativeBytePos::from_u32(0)]; let mut multi_byte_chars = vec![]; - let mut non_narrow_chars = vec![]; // Calls the right implementation, depending on hardware support available. - analyze_source_file_dispatch(src, &mut lines, &mut multi_byte_chars, &mut non_narrow_chars); + analyze_source_file_dispatch(src, &mut lines, &mut multi_byte_chars); // The code above optimistically registers a new line *after* each \n // it encounters. If that point is already outside the source_file, remove @@ -30,7 +26,7 @@ pub fn analyze_source_file( } } - (lines, multi_byte_chars, non_narrow_chars) + (lines, multi_byte_chars) } cfg_match! { @@ -39,11 +35,10 @@ cfg_match! { src: &str, lines: &mut Vec, multi_byte_chars: &mut Vec, - non_narrow_chars: &mut Vec, ) { if is_x86_feature_detected!("sse2") { unsafe { - analyze_source_file_sse2(src, lines, multi_byte_chars, non_narrow_chars); + analyze_source_file_sse2(src, lines, multi_byte_chars); } } else { analyze_source_file_generic( @@ -52,7 +47,6 @@ cfg_match! { RelativeBytePos::from_u32(0), lines, multi_byte_chars, - non_narrow_chars, ); } } @@ -66,7 +60,6 @@ cfg_match! { src: &str, lines: &mut Vec, multi_byte_chars: &mut Vec, - non_narrow_chars: &mut Vec, ) { #[cfg(target_arch = "x86")] use std::arch::x86::*; @@ -159,7 +152,6 @@ cfg_match! { RelativeBytePos::from_usize(scan_start), lines, multi_byte_chars, - non_narrow_chars, ); } @@ -172,7 +164,6 @@ cfg_match! { RelativeBytePos::from_usize(tail_start), lines, multi_byte_chars, - non_narrow_chars, ); } } @@ -183,7 +174,6 @@ cfg_match! { src: &str, lines: &mut Vec, multi_byte_chars: &mut Vec, - non_narrow_chars: &mut Vec, ) { analyze_source_file_generic( src, @@ -191,7 +181,6 @@ cfg_match! { RelativeBytePos::from_u32(0), lines, multi_byte_chars, - non_narrow_chars, ); } } @@ -205,7 +194,6 @@ fn analyze_source_file_generic( output_offset: RelativeBytePos, lines: &mut Vec, multi_byte_chars: &mut Vec, - non_narrow_chars: &mut Vec, ) -> usize { assert!(src.len() >= scan_len); let mut i = 0; @@ -227,16 +215,8 @@ fn analyze_source_file_generic( let pos = RelativeBytePos::from_usize(i) + output_offset; - match byte { - b'\n' => { - lines.push(pos + RelativeBytePos(1)); - } - b'\t' => { - non_narrow_chars.push(NonNarrowChar::Tab(pos)); - } - _ => { - non_narrow_chars.push(NonNarrowChar::ZeroWidth(pos)); - } + if let b'\n' = byte { + lines.push(pos + RelativeBytePos(1)); } } else if byte >= 127 { // The slow path: @@ -252,14 +232,6 @@ fn analyze_source_file_generic( let mbc = MultiByteChar { pos, bytes: char_len as u8 }; multi_byte_chars.push(mbc); } - - // Assume control characters are zero width. - // FIXME: How can we decide between `width` and `width_cjk`? - let char_width = UnicodeWidthChar::width(c).unwrap_or(0); - - if char_width != 1 { - non_narrow_chars.push(NonNarrowChar::new(pos, char_width)); - } } i += char_len; diff --git a/compiler/rustc_span/src/analyze_source_file/tests.rs b/compiler/rustc_span/src/analyze_source_file/tests.rs index 0c77d080c17a0..e4a24239d8ea1 100644 --- a/compiler/rustc_span/src/analyze_source_file/tests.rs +++ b/compiler/rustc_span/src/analyze_source_file/tests.rs @@ -4,11 +4,10 @@ macro_rules! test { (case: $test_name:ident, text: $text:expr, lines: $lines:expr, - multi_byte_chars: $multi_byte_chars:expr, - non_narrow_chars: $non_narrow_chars:expr,) => { + multi_byte_chars: $multi_byte_chars:expr,) => { #[test] fn $test_name() { - let (lines, multi_byte_chars, non_narrow_chars) = analyze_source_file($text); + let (lines, multi_byte_chars) = analyze_source_file($text); let expected_lines: Vec = $lines.into_iter().map(RelativeBytePos).collect(); @@ -21,13 +20,6 @@ macro_rules! test { .collect(); assert_eq!(multi_byte_chars, expected_mbcs); - - let expected_nncs: Vec = $non_narrow_chars - .into_iter() - .map(|(pos, width)| NonNarrowChar::new(RelativeBytePos(pos), width)) - .collect(); - - assert_eq!(non_narrow_chars, expected_nncs); } }; } @@ -37,7 +29,6 @@ test!( text: "", lines: vec![], multi_byte_chars: vec![], - non_narrow_chars: vec![], ); test!( @@ -45,7 +36,6 @@ test!( text: "a\nc", lines: vec![0, 2], multi_byte_chars: vec![], - non_narrow_chars: vec![], ); test!( @@ -53,7 +43,6 @@ test!( text: "012345678\nabcdef012345678\na", lines: vec![0, 10, 26], multi_byte_chars: vec![], - non_narrow_chars: vec![], ); test!( @@ -61,7 +50,6 @@ test!( text: "01234β789\nbcdef0123456789abcdef", lines: vec![0, 11], multi_byte_chars: vec![(5, 2)], - non_narrow_chars: vec![], ); test!( @@ -69,7 +57,6 @@ test!( text: "01234\u{07}6789\nbcdef0123456789abcdef", lines: vec![0, 11], multi_byte_chars: vec![], - non_narrow_chars: vec![(5, 0)], ); test!( @@ -77,7 +64,6 @@ test!( text: "aβc", lines: vec![0], multi_byte_chars: vec![(1, 2)], - non_narrow_chars: vec![], ); test!( @@ -85,7 +71,6 @@ test!( text: "0123456789abcΔf012345β", lines: vec![0], multi_byte_chars: vec![(13, 2), (22, 2)], - non_narrow_chars: vec![], ); test!( @@ -93,7 +78,6 @@ test!( text: "0123456789abcdeΔ123456789abcdef01234", lines: vec![0], multi_byte_chars: vec![(15, 2)], - non_narrow_chars: vec![], ); test!( @@ -101,7 +85,6 @@ test!( text: "0123456789abcdeΔ....", lines: vec![0], multi_byte_chars: vec![(15, 2)], - non_narrow_chars: vec![], ); test!( @@ -109,7 +92,6 @@ test!( text: "0\t2", lines: vec![0], multi_byte_chars: vec![], - non_narrow_chars: vec![(1, 4)], ); test!( @@ -117,7 +99,6 @@ test!( text: "01\t3456789abcdef01234567\u{07}9", lines: vec![0], multi_byte_chars: vec![], - non_narrow_chars: vec![(2, 4), (24, 0)], ); test!( @@ -125,5 +106,4 @@ test!( text: "01\t345\n789abcΔf01234567\u{07}9\nbcΔf", lines: vec![0, 7, 27], multi_byte_chars: vec![(13, 2), (29, 2)], - non_narrow_chars: vec![(2, 4), (24, 0)], ); diff --git a/compiler/rustc_span/src/caching_source_map_view.rs b/compiler/rustc_span/src/caching_source_map_view.rs index 4c7029c4e520e..26aa782e5d7a8 100644 --- a/compiler/rustc_span/src/caching_source_map_view.rs +++ b/compiler/rustc_span/src/caching_source_map_view.rs @@ -1,7 +1,9 @@ +use std::ops::Range; + +use rustc_data_structures::sync::Lrc; + use crate::source_map::SourceMap; use crate::{BytePos, Pos, RelativeBytePos, SourceFile, SpanData}; -use rustc_data_structures::sync::Lrc; -use std::ops::Range; #[derive(Clone)] struct CacheEntry { diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index 5456303b36fe4..a45b676acae73 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -1,4 +1,6 @@ -use crate::{HashStableContext, SpanDecoder, SpanEncoder, Symbol}; +use std::fmt; +use std::hash::{BuildHasherDefault, Hash, Hasher}; + use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::stable_hasher::{ Hash64, HashStable, StableHasher, StableOrd, ToStableHashKey, @@ -8,8 +10,8 @@ use rustc_data_structures::AtomicRef; use rustc_index::Idx; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_serialize::{Decodable, Encodable}; -use std::fmt; -use std::hash::{BuildHasherDefault, Hash, Hasher}; + +use crate::{HashStableContext, SpanDecoder, SpanEncoder, Symbol}; pub type StableCrateIdMap = indexmap::IndexMap>; diff --git a/compiler/rustc_span/src/edit_distance.rs b/compiler/rustc_span/src/edit_distance.rs index 87a0ccbb1a56d..4f120db48f0eb 100644 --- a/compiler/rustc_span/src/edit_distance.rs +++ b/compiler/rustc_span/src/edit_distance.rs @@ -9,9 +9,10 @@ // algorithm should not matter to the caller of the methods, which is why it is not noted in the // documentation. -use crate::symbol::Symbol; use std::{cmp, mem}; +use crate::symbol::Symbol; + #[cfg(test)] mod tests; diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index 483e32c645393..434df35a5156f 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -24,10 +24,11 @@ // because getting it wrong can lead to nested `HygieneData::with` calls that // trigger runtime aborts. (Fortunately these are obvious and easy to fix.) -use crate::def_id::{CrateNum, DefId, StableCrateId, CRATE_DEF_ID, LOCAL_CRATE}; -use crate::edition::Edition; -use crate::symbol::{kw, sym, Symbol}; -use crate::{with_session_globals, HashStableContext, Span, SpanDecoder, SpanEncoder, DUMMY_SP}; +use std::cell::RefCell; +use std::collections::hash_map::Entry; +use std::fmt; +use std::hash::Hash; + use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::{Hash64, HashStable, HashingControls, StableHasher}; @@ -36,12 +37,13 @@ use rustc_data_structures::unhash::UnhashMap; use rustc_index::IndexVec; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; -use std::cell::RefCell; -use std::collections::hash_map::Entry; -use std::fmt; -use std::hash::Hash; use tracing::{debug, trace}; +use crate::def_id::{CrateNum, DefId, StableCrateId, CRATE_DEF_ID, LOCAL_CRATE}; +use crate::edition::Edition; +use crate::symbol::{kw, sym, Symbol}; +use crate::{with_session_globals, HashStableContext, Span, SpanDecoder, SpanEncoder, DUMMY_SP}; + /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks". #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct SyntaxContext(u32); diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 266956d63d710..35fe28c5d425b 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -38,6 +38,7 @@ // this crate without this line making `rustc_span` available. extern crate self as rustc_span; +use derive_where::derive_where; use rustc_data_structures::{outline, AtomicRef}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_serialize::opaque::{FileEncoder, MemDecoder}; @@ -46,15 +47,17 @@ use tracing::debug; mod caching_source_map_view; pub mod source_map; -pub use self::caching_source_map_view::CachingSourceMapView; use source_map::{SourceMap, SourceMapInputs}; +pub use self::caching_source_map_view::CachingSourceMapView; + pub mod edition; use edition::Edition; pub mod hygiene; use hygiene::Transparency; -pub use hygiene::{DesugaringKind, ExpnKind, MacroKind}; -pub use hygiene::{ExpnData, ExpnHash, ExpnId, LocalExpnId, SyntaxContext}; +pub use hygiene::{ + DesugaringKind, ExpnData, ExpnHash, ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext, +}; use rustc_data_structures::stable_hasher::HashingControls; pub mod def_id; use def_id::{CrateNum, DefId, DefIndex, DefPathHash, LocalDefId, StableCrateId, LOCAL_CRATE}; @@ -70,10 +73,6 @@ pub mod fatal_error; pub mod profiling; -use rustc_data_structures::fx::FxHashMap; -use rustc_data_structures::stable_hasher::{Hash128, Hash64, HashStable, StableHasher}; -use rustc_data_structures::sync::{FreezeLock, FreezeWriteGuard, Lock, Lrc}; - use std::borrow::Cow; use std::cmp::{self, Ordering}; use std::hash::Hash; @@ -82,8 +81,10 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use std::{fmt, iter}; -use md5::Digest; -use md5::Md5; +use md5::{Digest, Md5}; +use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::stable_hasher::{Hash128, Hash64, HashStable, StableHasher}; +use rustc_data_structures::sync::{FreezeLock, FreezeWriteGuard, Lock, Lrc}; use sha1::Sha1; use sha2::Sha256; @@ -467,18 +468,18 @@ impl FileName { /// `SpanData` is public because `Span` uses a thread-local interner and can't be /// sent to other threads, but some pieces of performance infra run in a separate thread. /// Using `Span` is generally preferred. -#[derive(Clone, Copy, Hash, PartialEq, Eq, derivative::Derivative)] -#[derivative(PartialOrd, Ord)] +#[derive(Clone, Copy, Hash, PartialEq, Eq)] +#[derive_where(PartialOrd, Ord)] pub struct SpanData { pub lo: BytePos, pub hi: BytePos, /// Information about where the macro came from, if this piece of /// code was created by a macro expansion. - #[derivative(PartialOrd = "ignore", Ord = "ignore")] + #[derive_where(skip)] // `SyntaxContext` does not implement `Ord`. // The other fields are enough to determine in-file order. pub ctxt: SyntaxContext, - #[derivative(PartialOrd = "ignore", Ord = "ignore")] + #[derive_where(skip)] // `LocalDefId` does not implement `Ord`. // The other fields are enough to determine in-file order. pub parent: Option, @@ -1345,68 +1346,6 @@ pub struct MultiByteChar { pub bytes: u8, } -/// Identifies an offset of a non-narrow character in a `SourceFile`. -#[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug, HashStable_Generic)] -pub enum NonNarrowChar { - /// Represents a zero-width character. - ZeroWidth(RelativeBytePos), - /// Represents a wide (full-width) character. - Wide(RelativeBytePos), - /// Represents a tab character, represented visually with a width of 4 characters. - Tab(RelativeBytePos), -} - -impl NonNarrowChar { - fn new(pos: RelativeBytePos, width: usize) -> Self { - match width { - 0 => NonNarrowChar::ZeroWidth(pos), - 2 => NonNarrowChar::Wide(pos), - 4 => NonNarrowChar::Tab(pos), - _ => panic!("width {width} given for non-narrow character"), - } - } - - /// Returns the relative offset of the character in the `SourceFile`. - pub fn pos(&self) -> RelativeBytePos { - match *self { - NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p, - } - } - - /// Returns the width of the character, 0 (zero-width) or 2 (wide). - pub fn width(&self) -> usize { - match *self { - NonNarrowChar::ZeroWidth(_) => 0, - NonNarrowChar::Wide(_) => 2, - NonNarrowChar::Tab(_) => 4, - } - } -} - -impl Add for NonNarrowChar { - type Output = Self; - - fn add(self, rhs: RelativeBytePos) -> Self { - match self { - NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs), - NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs), - NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs), - } - } -} - -impl Sub for NonNarrowChar { - type Output = Self; - - fn sub(self, rhs: RelativeBytePos) -> Self { - match self { - NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs), - NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs), - NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs), - } - } -} - /// Identifies an offset of a character that was normalized away from `SourceFile`. #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug, HashStable_Generic)] pub struct NormalizedPos { @@ -1581,8 +1520,6 @@ pub struct SourceFile { pub lines: FreezeLock, /// Locations of multi-byte characters in the source code. pub multibyte_chars: Vec, - /// Width of characters that are not narrow in the source code. - pub non_narrow_chars: Vec, /// Locations of characters removed during normalization. pub normalized_pos: Vec, /// A hash of the filename & crate-id, used for uniquely identifying source @@ -1604,7 +1541,6 @@ impl Clone for SourceFile { source_len: self.source_len, lines: self.lines.clone(), multibyte_chars: self.multibyte_chars.clone(), - non_narrow_chars: self.non_narrow_chars.clone(), normalized_pos: self.normalized_pos.clone(), stable_id: self.stable_id, cnum: self.cnum, @@ -1679,7 +1615,6 @@ impl Encodable for SourceFile { } self.multibyte_chars.encode(s); - self.non_narrow_chars.encode(s); self.stable_id.encode(s); self.normalized_pos.encode(s); self.cnum.encode(s); @@ -1706,7 +1641,6 @@ impl Decodable for SourceFile { } }; let multibyte_chars: Vec = Decodable::decode(d); - let non_narrow_chars: Vec = Decodable::decode(d); let stable_id = Decodable::decode(d); let normalized_pos: Vec = Decodable::decode(d); let cnum: CrateNum = Decodable::decode(d); @@ -1721,7 +1655,6 @@ impl Decodable for SourceFile { external_src: FreezeLock::frozen(ExternalSource::Unneeded), lines: FreezeLock::new(lines), multibyte_chars, - non_narrow_chars, normalized_pos, stable_id, cnum, @@ -1809,8 +1742,7 @@ impl SourceFile { let source_len = src.len(); let source_len = u32::try_from(source_len).map_err(|_| OffsetOverflowError)?; - let (lines, multibyte_chars, non_narrow_chars) = - analyze_source_file::analyze_source_file(&src); + let (lines, multibyte_chars) = analyze_source_file::analyze_source_file(&src); Ok(SourceFile { name, @@ -1821,7 +1753,6 @@ impl SourceFile { source_len: RelativeBytePos::from_u32(source_len), lines: FreezeLock::frozen(SourceFileLines::Lines(lines)), multibyte_chars, - non_narrow_chars, normalized_pos, stable_id, cnum: LOCAL_CRATE, @@ -2130,41 +2061,45 @@ impl SourceFile { let pos = self.relative_position(pos); let (line, col_or_chpos) = self.lookup_file_pos(pos); if line > 0 { - let col = col_or_chpos; - let linebpos = self.lines()[line - 1]; - let col_display = { - let start_width_idx = self - .non_narrow_chars - .binary_search_by_key(&linebpos, |x| x.pos()) - .unwrap_or_else(|x| x); - let end_width_idx = self - .non_narrow_chars - .binary_search_by_key(&pos, |x| x.pos()) - .unwrap_or_else(|x| x); - let special_chars = end_width_idx - start_width_idx; - let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] - .iter() - .map(|x| x.width()) - .sum(); - col.0 - special_chars + non_narrow + let Some(code) = self.get_line(line - 1) else { + // If we don't have the code available, it is ok as a fallback to return the bytepos + // instead of the "display" column, which is only used to properly show underlines + // in the terminal. + // FIXME: we'll want better handling of this in the future for the sake of tools + // that want to use the display col instead of byte offsets to modify Rust code, but + // that is a problem for another day, the previous code was already incorrect for + // both displaying *and* third party tools using the json output naïvely. + tracing::info!("couldn't find line {line} {:?}", self.name); + return (line, col_or_chpos, col_or_chpos.0); }; - (line, col, col_display) + let display_col = code.chars().take(col_or_chpos.0).map(|ch| char_width(ch)).sum(); + (line, col_or_chpos, display_col) } else { - let chpos = col_or_chpos; - let col_display = { - let end_width_idx = self - .non_narrow_chars - .binary_search_by_key(&pos, |x| x.pos()) - .unwrap_or_else(|x| x); - let non_narrow: usize = - self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum(); - chpos.0 - end_width_idx + non_narrow - }; - (0, chpos, col_display) + // This is never meant to happen? + (0, col_or_chpos, col_or_chpos.0) } } } +pub fn char_width(ch: char) -> usize { + // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is. For now, + // just accept that sometimes the code line will be longer than desired. + match ch { + '\t' => 4, + // Keep the following list in sync with `rustc_errors::emitter::OUTPUT_REPLACEMENTS`. These + // are control points that we replace before printing with a visible codepoint for the sake + // of being able to point at them with underlines. + '\u{0000}' | '\u{0001}' | '\u{0002}' | '\u{0003}' | '\u{0004}' | '\u{0005}' + | '\u{0006}' | '\u{0007}' | '\u{0008}' | '\u{000B}' | '\u{000C}' | '\u{000D}' + | '\u{000E}' | '\u{000F}' | '\u{0010}' | '\u{0011}' | '\u{0012}' | '\u{0013}' + | '\u{0014}' | '\u{0015}' | '\u{0016}' | '\u{0017}' | '\u{0018}' | '\u{0019}' + | '\u{001A}' | '\u{001B}' | '\u{001C}' | '\u{001D}' | '\u{001E}' | '\u{001F}' + | '\u{007F}' | '\u{202A}' | '\u{202B}' | '\u{202D}' | '\u{202E}' | '\u{2066}' + | '\u{2067}' | '\u{2068}' | '\u{202C}' | '\u{2069}' => 1, + _ => unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1), + } +} + /// Normalizes the source code and records the normalizations. fn normalize_src(src: &mut String) -> Vec { let mut normalized_pos = vec![]; diff --git a/compiler/rustc_span/src/profiling.rs b/compiler/rustc_span/src/profiling.rs index 66e5369da3ae1..c5a8bd3b15be9 100644 --- a/compiler/rustc_span/src/profiling.rs +++ b/compiler/rustc_span/src/profiling.rs @@ -1,9 +1,9 @@ -use crate::source_map::SourceMap; - use std::borrow::Borrow; use rustc_data_structures::profiling::EventArgRecorder; +use crate::source_map::SourceMap; + /// Extension trait for self-profiling purposes: allows to record spans within a generic activity's /// event arguments. pub trait SpannedEventArgRecorder { diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index fb212d67997a7..f914e8dc1baaa 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -9,15 +9,16 @@ //! within the `SourceMap`, which upon request can be converted to line and column //! information, source code snippets, etc. -use crate::*; +use std::io::{self, BorrowedBuf, Read}; +use std::{fs, path}; + use rustc_data_structures::sync::{IntoDynSyncSend, MappedReadGuard, ReadGuard, RwLock}; use rustc_data_structures::unhash::UnhashMap; use rustc_macros::{Decodable, Encodable}; -use std::fs; -use std::io::{self, BorrowedBuf, Read}; -use std::path; use tracing::{debug, instrument, trace}; +use crate::*; + #[cfg(test)] mod tests; @@ -330,7 +331,6 @@ impl SourceMap { cnum: CrateNum, file_local_lines: FreezeLock, multibyte_chars: Vec, - non_narrow_chars: Vec, normalized_pos: Vec, metadata_index: u32, ) -> Lrc { @@ -348,7 +348,6 @@ impl SourceMap { source_len, lines: file_local_lines, multibyte_chars, - non_narrow_chars, normalized_pos, stable_id, cnum, diff --git a/compiler/rustc_span/src/source_map/tests.rs b/compiler/rustc_span/src/source_map/tests.rs index dcb02da371921..0c818b94b85a3 100644 --- a/compiler/rustc_span/src/source_map/tests.rs +++ b/compiler/rustc_span/src/source_map/tests.rs @@ -232,7 +232,6 @@ fn t10() { source_len, lines, multibyte_chars, - non_narrow_chars, normalized_pos, stable_id, .. @@ -246,7 +245,6 @@ fn t10() { CrateNum::ZERO, FreezeLock::new(lines.read().clone()), multibyte_chars, - non_narrow_chars, normalized_pos, 0, ); diff --git a/compiler/rustc_span/src/span_encoding.rs b/compiler/rustc_span/src/span_encoding.rs index 53d7b7511a621..8988becb17126 100644 --- a/compiler/rustc_span/src/span_encoding.rs +++ b/compiler/rustc_span/src/span_encoding.rs @@ -1,14 +1,12 @@ -use crate::def_id::{DefIndex, LocalDefId}; -use crate::hygiene::SyntaxContext; -use crate::SPAN_TRACK; -use crate::{BytePos, SpanData}; - use rustc_data_structures::fx::FxIndexSet; - // This code is very hot and uses lots of arithmetic, avoid overflow checks for performance. // See https://github.com/rust-lang/rust/pull/119440#issuecomment-1874255727 use rustc_serialize::int_overflow::DebugStrictAdd; +use crate::def_id::{DefIndex, LocalDefId}; +use crate::hygiene::SyntaxContext; +use crate::{BytePos, SpanData, SPAN_TRACK}; + /// A compressed span. /// /// [`SpanData`] is 16 bytes, which is too big to stick everywhere. `Span` only diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 2b30ca8a89478..94cf21da4efb8 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -2,6 +2,9 @@ //! allows bidirectional lookup; i.e., given a value, one can easily find the //! type, and vice versa. +use std::hash::{Hash, Hasher}; +use std::{fmt, str}; + use rustc_arena::DroplessArena; use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::stable_hasher::{ @@ -10,10 +13,6 @@ use rustc_data_structures::stable_hasher::{ use rustc_data_structures::sync::Lock; use rustc_macros::{symbols, Decodable, Encodable, HashStable_Generic}; -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::str; - use crate::{with_session_globals, Edition, Span, DUMMY_SP}; #[cfg(test)] @@ -557,6 +556,7 @@ symbols! { clobber_abi, clone, clone_closures, + clone_fn, clone_from, closure, closure_lifetime_binder, @@ -1216,6 +1216,7 @@ symbols! { mir_static_mut, mir_storage_dead, mir_storage_live, + mir_tail_call, mir_unreachable, mir_unwind_cleanup, mir_unwind_continue, @@ -1229,6 +1230,7 @@ symbols! { modifiers, module, module_path, + more_maybe_bounds, more_qualified_paths, more_struct_aliases, movbe_target_feature, @@ -1700,9 +1702,11 @@ symbols! { saturating_add, saturating_div, saturating_sub, + select_unpredictable, self_in_typedefs, self_struct_ctor, semitransparent, + sha512_sm_x86, shadow_call_stack, shl, shl_assign, @@ -2444,13 +2448,11 @@ pub mod kw { /// Given that `sym` is imported, use them like `sym::symbol_name`. /// For example `sym::rustfmt` or `sym::u8`. pub mod sym { - use super::Symbol; - - #[doc(inline)] - pub use super::sym_generated::*; - // Used from a macro in `librustc_feature/accepted.rs` pub use super::kw::MacroRules as macro_rules; + #[doc(inline)] + pub use super::sym_generated::*; + use super::Symbol; /// Get the symbol for an integer. /// diff --git a/compiler/rustc_span/src/symbol/tests.rs b/compiler/rustc_span/src/symbol/tests.rs index 4366c5a2c26d2..c6aa7627b2b54 100644 --- a/compiler/rustc_span/src/symbol/tests.rs +++ b/compiler/rustc_span/src/symbol/tests.rs @@ -1,5 +1,4 @@ use super::*; - use crate::create_default_session_globals_then; #[test] diff --git a/compiler/rustc_symbol_mangling/src/errors.rs b/compiler/rustc_symbol_mangling/src/errors.rs index 9b87a1419fa30..775f3112ed5f7 100644 --- a/compiler/rustc_symbol_mangling/src/errors.rs +++ b/compiler/rustc_symbol_mangling/src/errors.rs @@ -1,8 +1,9 @@ //! Errors emitted by symbol_mangling. +use std::fmt; + use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level}; use rustc_span::Span; -use std::fmt; pub struct TestOutput { pub span: Span, diff --git a/compiler/rustc_symbol_mangling/src/hashed.rs b/compiler/rustc_symbol_mangling/src/hashed.rs index d4cd6161ac040..8e2f94991cf90 100644 --- a/compiler/rustc_symbol_mangling/src/hashed.rs +++ b/compiler/rustc_symbol_mangling/src/hashed.rs @@ -1,9 +1,10 @@ -use crate::v0; +use std::fmt::Write; + use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher}; use rustc_hir::def_id::CrateNum; use rustc_middle::ty::{Instance, TyCtxt}; -use std::fmt::Write; +use crate::v0; pub(super) fn mangle<'tcx>( tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index 5aa46cc0deae0..0f91684a3a48b 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -1,12 +1,14 @@ +use std::fmt::{self, Write}; +use std::mem::{self, discriminant}; + use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher}; use rustc_hir::def_id::CrateNum; use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; use rustc_middle::bug; use rustc_middle::ty::print::{PrettyPrinter, Print, PrintError, Printer}; -use rustc_middle::ty::{self, Instance, ReifyReason, Ty, TyCtxt, TypeVisitableExt}; -use rustc_middle::ty::{GenericArg, GenericArgKind}; -use std::fmt::{self, Write}; -use std::mem::{self, discriminant}; +use rustc_middle::ty::{ + self, GenericArg, GenericArgKind, Instance, ReifyReason, Ty, TyCtxt, TypeVisitableExt, +}; use tracing::debug; pub(super) fn mangle<'tcx>( diff --git a/compiler/rustc_symbol_mangling/src/lib.rs b/compiler/rustc_symbol_mangling/src/lib.rs index e65d3080a0a19..dea4eb08c7615 100644 --- a/compiler/rustc_symbol_mangling/src/lib.rs +++ b/compiler/rustc_symbol_mangling/src/lib.rs @@ -97,8 +97,7 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::{CrateNum, LOCAL_CRATE}; -use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; +use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs}; use rustc_middle::mir::mono::{InstantiationMode, MonoItem}; use rustc_middle::query::Providers; use rustc_middle::ty::{self, Instance, TyCtxt}; diff --git a/compiler/rustc_symbol_mangling/src/test.rs b/compiler/rustc_symbol_mangling/src/test.rs index f0fb87fe83c86..774d0b5a6125b 100644 --- a/compiler/rustc_symbol_mangling/src/test.rs +++ b/compiler/rustc_symbol_mangling/src/test.rs @@ -4,12 +4,13 @@ //! def-path. This is used for unit testing the code that generates //! paths etc in all kinds of annoying scenarios. -use crate::errors::{Kind, TestOutput}; use rustc_hir::def_id::LocalDefId; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{GenericArgs, Instance, TyCtxt}; use rustc_span::symbol::{sym, Symbol}; +use crate::errors::{Kind, TestOutput}; + const SYMBOL_NAME: Symbol = sym::rustc_symbol_name; const DEF_PATH: Symbol = sym::rustc_def_path; diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 5f8029af02044..c2451c08d1158 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -1,3 +1,7 @@ +use std::fmt::Write; +use std::iter; +use std::ops::Range; + use rustc_data_structures::base_n::ToBaseN; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::intern::Interned; @@ -9,18 +13,13 @@ use rustc_middle::bug; use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::print::{Print, PrintError, Printer}; use rustc_middle::ty::{ - self, EarlyBinder, FloatTy, Instance, IntTy, ReifyReason, Ty, TyCtxt, TypeVisitable, - TypeVisitableExt, UintTy, + self, EarlyBinder, FloatTy, GenericArg, GenericArgKind, Instance, IntTy, ReifyReason, Ty, + TyCtxt, TypeVisitable, TypeVisitableExt, UintTy, }; -use rustc_middle::ty::{GenericArg, GenericArgKind}; use rustc_span::symbol::kw; use rustc_target::abi::Integer; use rustc_target::spec::abi::Abi; -use std::fmt::Write; -use std::iter; -use std::ops::Range; - pub(super) fn mangle<'tcx>( tcx: TyCtxt<'tcx>, instance: Instance<'tcx>, diff --git a/compiler/rustc_target/Cargo.toml b/compiler/rustc_target/Cargo.toml index 2cb8ac7e8bfb3..c7d24154e8bd4 100644 --- a/compiler/rustc_target/Cargo.toml +++ b/compiler/rustc_target/Cargo.toml @@ -22,5 +22,5 @@ tracing = "0.1" # tidy-alphabetical-start default-features = false features = ["elf", "macho"] -version = "0.32.0" +version = "0.36.2" # tidy-alphabetical-end diff --git a/compiler/rustc_target/src/abi/call/mod.rs b/compiler/rustc_target/src/abi/call/mod.rs index 9f13c195e4ce6..5bfc528dffc83 100644 --- a/compiler/rustc_target/src/abi/call/mod.rs +++ b/compiler/rustc_target/src/abi/call/mod.rs @@ -1,11 +1,12 @@ -use crate::abi::{self, Abi, Align, FieldsShape, Size}; -use crate::abi::{HasDataLayout, TyAbiInterface, TyAndLayout}; -use crate::spec::{self, HasTargetSpec, HasWasmCAbiOpt, WasmCAbi}; -use rustc_macros::HashStable_Generic; -use rustc_span::Symbol; use std::fmt; use std::str::FromStr; +use rustc_macros::HashStable_Generic; +use rustc_span::Symbol; + +use crate::abi::{self, Abi, Align, FieldsShape, HasDataLayout, Size, TyAbiInterface, TyAndLayout}; +use crate::spec::{self, HasTargetSpec, HasWasmCAbiOpt, WasmCAbi}; + mod aarch64; mod amdgpu; mod arm; @@ -237,8 +238,10 @@ impl Reg { _ => panic!("unsupported integer: {self:?}"), }, RegKind::Float => match self.size.bits() { + 16 => dl.f16_align.abi, 32 => dl.f32_align.abi, 64 => dl.f64_align.abi, + 128 => dl.f128_align.abi, _ => panic!("unsupported float: {self:?}"), }, RegKind::Vector => dl.vector_align(self.size).abi, @@ -967,8 +970,9 @@ impl FromStr for Conv { // Some types are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(ArgAbi<'_, usize>, 56); static_assert_size!(FnAbi<'_, usize>, 80); diff --git a/compiler/rustc_target/src/abi/call/nvptx64.rs b/compiler/rustc_target/src/abi/call/nvptx64.rs index ac68e8879f69a..27d197af7925b 100644 --- a/compiler/rustc_target/src/abi/call/nvptx64.rs +++ b/compiler/rustc_target/src/abi/call/nvptx64.rs @@ -1,8 +1,7 @@ +use super::{ArgAttribute, ArgAttributes, ArgExtension, CastTarget}; use crate::abi::call::{ArgAbi, FnAbi, PassMode, Reg, Size, Uniform}; use crate::abi::{HasDataLayout, TyAbiInterface}; -use super::{ArgAttribute, ArgAttributes, ArgExtension, CastTarget}; - fn classify_ret(ret: &mut ArgAbi<'_, Ty>) { if ret.layout.is_aggregate() && ret.layout.is_sized() { classify_aggregate(ret) diff --git a/compiler/rustc_target/src/abi/call/x86_win64.rs b/compiler/rustc_target/src/abi/call/x86_win64.rs index 90de1a42bc06b..4e19460bd28c2 100644 --- a/compiler/rustc_target/src/abi/call/x86_win64.rs +++ b/compiler/rustc_target/src/abi/call/x86_win64.rs @@ -1,5 +1,5 @@ use crate::abi::call::{ArgAbi, FnAbi, Reg}; -use crate::abi::Abi; +use crate::abi::{Abi, Float, Primitive}; // Win64 ABI: https://docs.microsoft.com/en-us/cpp/build/parameter-passing @@ -18,8 +18,12 @@ pub fn compute_abi_info(fn_abi: &mut FnAbi<'_, Ty>) { // FIXME(eddyb) there should be a size cap here // (probably what clang calls "illegal vectors"). } - Abi::Scalar(_) => { - if a.layout.size.bytes() > 8 { + Abi::Scalar(scalar) => { + // Match what LLVM does for `f128` so that `compiler-builtins` builtins match up + // with what LLVM expects. + if a.layout.size.bytes() > 8 + && !matches!(scalar.primitive(), Primitive::Float(Float::F128)) + { a.make_indirect(); } else { a.extend_integer_width_to(32); diff --git a/compiler/rustc_target/src/abi/mod.rs b/compiler/rustc_target/src/abi/mod.rs index 737e9a8eab022..9bd0aff1d3bc4 100644 --- a/compiler/rustc_target/src/abi/mod.rs +++ b/compiler/rustc_target/src/abi/mod.rs @@ -1,15 +1,14 @@ +use std::fmt; +use std::ops::Deref; + use rustc_data_structures::intern::Interned; +use rustc_macros::HashStable_Generic; pub use Float::*; pub use Integer::*; pub use Primitive::*; use crate::json::{Json, ToJson}; -use std::fmt; -use std::ops::Deref; - -use rustc_macros::HashStable_Generic; - pub mod call; // Explicitly import `Float` to avoid ambiguity with `Primitive::Float`. diff --git a/compiler/rustc_target/src/asm/aarch64.rs b/compiler/rustc_target/src/asm/aarch64.rs index 1a3218da1af04..358efb4174df0 100644 --- a/compiler/rustc_target/src/asm/aarch64.rs +++ b/compiler/rustc_target/src/asm/aarch64.rs @@ -1,8 +1,10 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use crate::spec::{RelocModel, Target}; +use std::fmt; + use rustc_data_structures::fx::FxIndexSet; use rustc_span::Symbol; -use std::fmt; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; +use crate::spec::{RelocModel, Target}; def_reg_class! { AArch64 AArch64InlineAsmRegClass { diff --git a/compiler/rustc_target/src/asm/arm.rs b/compiler/rustc_target/src/asm/arm.rs index 70fcaab184757..f8d0d40e8a742 100644 --- a/compiler/rustc_target/src/asm/arm.rs +++ b/compiler/rustc_target/src/asm/arm.rs @@ -1,8 +1,10 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use crate::spec::{RelocModel, Target}; +use std::fmt; + use rustc_data_structures::fx::FxIndexSet; use rustc_span::{sym, Symbol}; -use std::fmt; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; +use crate::spec::{RelocModel, Target}; def_reg_class! { Arm ArmInlineAsmRegClass { diff --git a/compiler/rustc_target/src/asm/avr.rs b/compiler/rustc_target/src/asm/avr.rs index 6943fd9b5d72a..276f376b297e6 100644 --- a/compiler/rustc_target/src/asm/avr.rs +++ b/compiler/rustc_target/src/asm/avr.rs @@ -1,7 +1,9 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use rustc_span::Symbol; use std::fmt; +use rustc_span::Symbol; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { Avr AvrInlineAsmRegClass { reg, diff --git a/compiler/rustc_target/src/asm/bpf.rs b/compiler/rustc_target/src/asm/bpf.rs index faaeabb3c901b..500fb4173e49c 100644 --- a/compiler/rustc_target/src/asm/bpf.rs +++ b/compiler/rustc_target/src/asm/bpf.rs @@ -1,7 +1,9 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use rustc_span::Symbol; use std::fmt; +use rustc_span::Symbol; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { Bpf BpfInlineAsmRegClass { reg, diff --git a/compiler/rustc_target/src/asm/csky.rs b/compiler/rustc_target/src/asm/csky.rs index db6cdecfe1909..a4913ed76abc0 100644 --- a/compiler/rustc_target/src/asm/csky.rs +++ b/compiler/rustc_target/src/asm/csky.rs @@ -1,7 +1,9 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use rustc_span::Symbol; use std::fmt; +use rustc_span::Symbol; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { CSKY CSKYInlineAsmRegClass { reg, diff --git a/compiler/rustc_target/src/asm/hexagon.rs b/compiler/rustc_target/src/asm/hexagon.rs index 7a809efee6f4d..f7e726c33768d 100644 --- a/compiler/rustc_target/src/asm/hexagon.rs +++ b/compiler/rustc_target/src/asm/hexagon.rs @@ -1,7 +1,9 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use rustc_span::Symbol; use std::fmt; +use rustc_span::Symbol; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { Hexagon HexagonInlineAsmRegClass { reg, diff --git a/compiler/rustc_target/src/asm/loongarch.rs b/compiler/rustc_target/src/asm/loongarch.rs index 534b696f7edf0..b1c01d27cadd6 100644 --- a/compiler/rustc_target/src/asm/loongarch.rs +++ b/compiler/rustc_target/src/asm/loongarch.rs @@ -1,7 +1,9 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use rustc_span::Symbol; use std::fmt; +use rustc_span::Symbol; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { LoongArch LoongArchInlineAsmRegClass { reg, diff --git a/compiler/rustc_target/src/asm/m68k.rs b/compiler/rustc_target/src/asm/m68k.rs index ea367e3d2f94e..680404bf35592 100644 --- a/compiler/rustc_target/src/asm/m68k.rs +++ b/compiler/rustc_target/src/asm/m68k.rs @@ -1,7 +1,9 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use rustc_span::Symbol; use std::fmt; +use rustc_span::Symbol; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { M68k M68kInlineAsmRegClass { reg, diff --git a/compiler/rustc_target/src/asm/mips.rs b/compiler/rustc_target/src/asm/mips.rs index f0d659c9b9796..e28b8453b4784 100644 --- a/compiler/rustc_target/src/asm/mips.rs +++ b/compiler/rustc_target/src/asm/mips.rs @@ -1,7 +1,9 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use rustc_span::Symbol; use std::fmt; +use rustc_span::Symbol; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { Mips MipsInlineAsmRegClass { reg, diff --git a/compiler/rustc_target/src/asm/mod.rs b/compiler/rustc_target/src/asm/mod.rs index b057bf94a087a..4d8c5cea8a830 100644 --- a/compiler/rustc_target/src/asm/mod.rs +++ b/compiler/rustc_target/src/asm/mod.rs @@ -1,10 +1,12 @@ -use crate::spec::Target; -use crate::{abi::Size, spec::RelocModel}; +use std::fmt; +use std::str::FromStr; + use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_span::Symbol; -use std::fmt; -use std::str::FromStr; + +use crate::abi::Size; +use crate::spec::{RelocModel, Target}; pub struct ModifierInfo { pub modifier: char, diff --git a/compiler/rustc_target/src/asm/msp430.rs b/compiler/rustc_target/src/asm/msp430.rs index 14013cd8a7b41..5ed2023e3843a 100644 --- a/compiler/rustc_target/src/asm/msp430.rs +++ b/compiler/rustc_target/src/asm/msp430.rs @@ -1,7 +1,9 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use rustc_span::Symbol; use std::fmt; +use rustc_span::Symbol; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { Msp430 Msp430InlineAsmRegClass { reg, diff --git a/compiler/rustc_target/src/asm/nvptx.rs b/compiler/rustc_target/src/asm/nvptx.rs index 6c066ad7ac8fc..da8b79d8935be 100644 --- a/compiler/rustc_target/src/asm/nvptx.rs +++ b/compiler/rustc_target/src/asm/nvptx.rs @@ -1,6 +1,7 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; use rustc_span::Symbol; +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { Nvptx NvptxInlineAsmRegClass { reg16, diff --git a/compiler/rustc_target/src/asm/powerpc.rs b/compiler/rustc_target/src/asm/powerpc.rs index 45e9ace0f291b..b2416466132d7 100644 --- a/compiler/rustc_target/src/asm/powerpc.rs +++ b/compiler/rustc_target/src/asm/powerpc.rs @@ -1,7 +1,9 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use rustc_span::Symbol; use std::fmt; +use rustc_span::Symbol; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { PowerPC PowerPCInlineAsmRegClass { reg, diff --git a/compiler/rustc_target/src/asm/riscv.rs b/compiler/rustc_target/src/asm/riscv.rs index 02a4a5e2ece59..2b9d6114930fc 100644 --- a/compiler/rustc_target/src/asm/riscv.rs +++ b/compiler/rustc_target/src/asm/riscv.rs @@ -1,8 +1,10 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use crate::spec::{RelocModel, Target}; +use std::fmt; + use rustc_data_structures::fx::FxIndexSet; use rustc_span::{sym, Symbol}; -use std::fmt; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; +use crate::spec::{RelocModel, Target}; def_reg_class! { RiscV RiscVInlineAsmRegClass { diff --git a/compiler/rustc_target/src/asm/s390x.rs b/compiler/rustc_target/src/asm/s390x.rs index 2bab41cd8a1b4..4258b23ac57eb 100644 --- a/compiler/rustc_target/src/asm/s390x.rs +++ b/compiler/rustc_target/src/asm/s390x.rs @@ -1,7 +1,9 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use rustc_span::Symbol; use std::fmt; +use rustc_span::Symbol; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { S390x S390xInlineAsmRegClass { reg, diff --git a/compiler/rustc_target/src/asm/spirv.rs b/compiler/rustc_target/src/asm/spirv.rs index f242faec0266d..c050c4e36b70e 100644 --- a/compiler/rustc_target/src/asm/spirv.rs +++ b/compiler/rustc_target/src/asm/spirv.rs @@ -1,6 +1,7 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; use rustc_span::Symbol; +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { SpirV SpirVInlineAsmRegClass { reg, diff --git a/compiler/rustc_target/src/asm/wasm.rs b/compiler/rustc_target/src/asm/wasm.rs index b5f4d10fb2b4b..0fbfa527bc45d 100644 --- a/compiler/rustc_target/src/asm/wasm.rs +++ b/compiler/rustc_target/src/asm/wasm.rs @@ -1,6 +1,7 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; use rustc_span::Symbol; +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; + def_reg_class! { Wasm WasmInlineAsmRegClass { local, diff --git a/compiler/rustc_target/src/asm/x86.rs b/compiler/rustc_target/src/asm/x86.rs index 8452961c17c0f..15c1925bcdafd 100644 --- a/compiler/rustc_target/src/asm/x86.rs +++ b/compiler/rustc_target/src/asm/x86.rs @@ -1,8 +1,10 @@ -use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; -use crate::spec::{RelocModel, Target}; +use std::fmt; + use rustc_data_structures::fx::FxIndexSet; use rustc_span::Symbol; -use std::fmt; + +use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; +use crate::spec::{RelocModel, Target}; def_reg_class! { X86 X86InlineAsmRegClass { diff --git a/compiler/rustc_target/src/spec/base/apple/mod.rs b/compiler/rustc_target/src/spec/base/apple/mod.rs index 055420090835d..39d7cf7d0971c 100644 --- a/compiler/rustc_target/src/spec/base/apple/mod.rs +++ b/compiler/rustc_target/src/spec/base/apple/mod.rs @@ -1,8 +1,10 @@ -use std::{borrow::Cow, env}; +use std::borrow::Cow; +use std::env; -use crate::spec::{add_link_args, add_link_args_iter}; -use crate::spec::{cvs, Cc, DebuginfoKind, FramePointer, LinkArgs, LinkerFlavor, Lld}; -use crate::spec::{SplitDebuginfo, StackProbeType, StaticCow, Target, TargetOptions}; +use crate::spec::{ + add_link_args, add_link_args_iter, cvs, Cc, DebuginfoKind, FramePointer, LinkArgs, + LinkerFlavor, Lld, SplitDebuginfo, StackProbeType, StaticCow, Target, TargetOptions, +}; #[cfg(test)] mod tests; diff --git a/compiler/rustc_target/src/spec/base/avr_gnu.rs b/compiler/rustc_target/src/spec/base/avr_gnu.rs index 211d52f5b07ed..c3d0344ea6c13 100644 --- a/compiler/rustc_target/src/spec/base/avr_gnu.rs +++ b/compiler/rustc_target/src/spec/base/avr_gnu.rs @@ -1,6 +1,7 @@ -use crate::spec::{Cc, LinkerFlavor, Lld, RelocModel, Target, TargetOptions}; use object::elf; +use crate::spec::{Cc, LinkerFlavor, Lld, RelocModel, Target, TargetOptions}; + /// A base target for AVR devices using the GNU toolchain. /// /// Requires GNU avr-gcc and avr-binutils on the host system. diff --git a/compiler/rustc_target/src/spec/base/linux.rs b/compiler/rustc_target/src/spec/base/linux.rs index df8e848124a9b..34b2eb0f64174 100644 --- a/compiler/rustc_target/src/spec/base/linux.rs +++ b/compiler/rustc_target/src/spec/base/linux.rs @@ -1,6 +1,7 @@ -use crate::spec::{cvs, RelroLevel, SplitDebuginfo, TargetOptions}; use std::borrow::Cow; +use crate::spec::{cvs, RelroLevel, SplitDebuginfo, TargetOptions}; + pub fn opts() -> TargetOptions { TargetOptions { os: "linux".into(), diff --git a/compiler/rustc_target/src/spec/base/linux_musl.rs b/compiler/rustc_target/src/spec/base/linux_musl.rs index 5117cadbee0e6..42aa1e1a6daf4 100644 --- a/compiler/rustc_target/src/spec/base/linux_musl.rs +++ b/compiler/rustc_target/src/spec/base/linux_musl.rs @@ -1,5 +1,4 @@ -use crate::spec::crt_objects; -use crate::spec::{base, LinkSelfContainedDefault, TargetOptions}; +use crate::spec::{base, crt_objects, LinkSelfContainedDefault, TargetOptions}; pub fn opts() -> TargetOptions { let mut base = base::linux::opts(); diff --git a/compiler/rustc_target/src/spec/base/msvc.rs b/compiler/rustc_target/src/spec/base/msvc.rs index 44fc376fea084..720cf03005a5e 100644 --- a/compiler/rustc_target/src/spec/base/msvc.rs +++ b/compiler/rustc_target/src/spec/base/msvc.rs @@ -1,6 +1,7 @@ -use crate::spec::{DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions}; use std::borrow::Cow; +use crate::spec::{DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions}; + pub fn opts() -> TargetOptions { // Suppress the verbose logo and authorship debugging output, which would needlessly // clog any log files. diff --git a/compiler/rustc_target/src/spec/base/windows_gnu.rs b/compiler/rustc_target/src/spec/base/windows_gnu.rs index 1357de2dad126..7346e42dd9100 100644 --- a/compiler/rustc_target/src/spec/base/windows_gnu.rs +++ b/compiler/rustc_target/src/spec/base/windows_gnu.rs @@ -1,8 +1,10 @@ -use crate::spec::LinkSelfContainedDefault; -use crate::spec::{add_link_args, crt_objects}; -use crate::spec::{cvs, Cc, DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions}; use std::borrow::Cow; +use crate::spec::{ + add_link_args, crt_objects, cvs, Cc, DebuginfoKind, LinkSelfContainedDefault, LinkerFlavor, + Lld, SplitDebuginfo, TargetOptions, +}; + pub fn opts() -> TargetOptions { let mut pre_link_args = TargetOptions::link_args( LinkerFlavor::Gnu(Cc::No, Lld::No), diff --git a/compiler/rustc_target/src/spec/base/windows_gnullvm.rs b/compiler/rustc_target/src/spec/base/windows_gnullvm.rs index b1d8e2be5a61f..88c3b8a81ad22 100644 --- a/compiler/rustc_target/src/spec/base/windows_gnullvm.rs +++ b/compiler/rustc_target/src/spec/base/windows_gnullvm.rs @@ -1,6 +1,7 @@ -use crate::spec::{cvs, Cc, DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions}; use std::borrow::Cow; +use crate::spec::{cvs, Cc, DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions}; + pub fn opts() -> TargetOptions { // We cannot use `-nodefaultlibs` because compiler-rt has to be passed // as a path since it's not added to linker search path by the default. diff --git a/compiler/rustc_target/src/spec/crt_objects.rs b/compiler/rustc_target/src/spec/crt_objects.rs index 53f710b8f9e14..e3b6430a46371 100644 --- a/compiler/rustc_target/src/spec/crt_objects.rs +++ b/compiler/rustc_target/src/spec/crt_objects.rs @@ -40,10 +40,11 @@ //! but not gcc's. As a result rustc cannot link with C++ static libraries (#36710) //! when linking in self-contained mode. -use crate::spec::LinkOutputKind; use std::borrow::Cow; use std::collections::BTreeMap; +use crate::spec::LinkOutputKind; + pub type CrtObjects = BTreeMap>>; pub(super) fn new(obj_table: &[(LinkOutputKind, &[&'static str])]) -> CrtObjects { diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 0efe68252af20..946947124c6eb 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -34,16 +34,6 @@ //! the target's settings, though `target-feature` and `link-args` will *add* //! to the list specified by the target, rather than replace. -use crate::abi::call::Conv; -use crate::abi::{Endian, Integer, Size, TargetDataLayout, TargetDataLayoutErrors}; -use crate::json::{Json, ToJson}; -use crate::spec::abi::Abi; -use crate::spec::crt_objects::CrtObjects; -use rustc_fs_util::try_canonicalize; -use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; -use rustc_span::symbol::{kw, sym, Symbol}; -use serde_json::Value; use std::borrow::Cow; use std::collections::BTreeMap; use std::hash::{Hash, Hasher}; @@ -51,15 +41,28 @@ use std::ops::{Deref, DerefMut}; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::{fmt, io}; + +use rustc_fs_util::try_canonicalize; +use rustc_macros::{Decodable, Encodable, HashStable_Generic}; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; +use rustc_span::symbol::{kw, sym, Symbol}; +use serde_json::Value; use tracing::debug; +use crate::abi::call::Conv; +use crate::abi::{Endian, Integer, Size, TargetDataLayout, TargetDataLayoutErrors}; +use crate::json::{Json, ToJson}; +use crate::spec::abi::Abi; +use crate::spec::crt_objects::CrtObjects; + pub mod abi; pub mod crt_objects; mod base; -pub use base::apple::deployment_target as current_apple_deployment_target; -pub use base::apple::platform as current_apple_platform; -pub use base::apple::sdk_version as current_apple_sdk_version; +pub use base::apple::{ + deployment_target as current_apple_deployment_target, platform as current_apple_platform, + sdk_version as current_apple_sdk_version, +}; pub use base::avr_gnu::ef_avr_arch; /// Linker is called through a C/C++ compiler. @@ -3353,8 +3356,7 @@ impl Target { target_triple: &TargetTriple, sysroot: &Path, ) -> Result<(Target, TargetWarnings), String> { - use std::env; - use std::fs; + use std::{env, fs}; fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> { let contents = fs::read_to_string(path).map_err(|e| e.to_string())?; diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_ohos.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_ohos.rs index 5924e4f57579f..726a85c81f39f 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_ohos.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_ohos.rs @@ -1,5 +1,4 @@ -use crate::spec::SanitizerSet; -use crate::spec::{base, StackProbeType, Target, TargetOptions}; +use crate::spec::{base, SanitizerSet, StackProbeType, Target, TargetOptions}; pub fn target() -> Target { let mut base = base::linux_ohos::opts(); diff --git a/compiler/rustc_target/src/spec/targets/bpfeb_unknown_none.rs b/compiler/rustc_target/src/spec/targets/bpfeb_unknown_none.rs index 8cddb6fe005c4..eb223af8cf44f 100644 --- a/compiler/rustc_target/src/spec/targets/bpfeb_unknown_none.rs +++ b/compiler/rustc_target/src/spec/targets/bpfeb_unknown_none.rs @@ -1,5 +1,5 @@ -use crate::spec::Target; -use crate::{abi::Endian, spec::base}; +use crate::abi::Endian; +use crate::spec::{base, Target}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/bpfel_unknown_none.rs b/compiler/rustc_target/src/spec/targets/bpfel_unknown_none.rs index d070aa0ec44be..12164adc00f25 100644 --- a/compiler/rustc_target/src/spec/targets/bpfel_unknown_none.rs +++ b/compiler/rustc_target/src/spec/targets/bpfel_unknown_none.rs @@ -1,5 +1,5 @@ -use crate::spec::Target; -use crate::{abi::Endian, spec::base}; +use crate::abi::Endian; +use crate::spec::{base, Target}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs index 19b04607f0e0b..f7a6e0bd857f5 100644 --- a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs @@ -4,10 +4,10 @@ pub fn target() -> Target { Target { llvm_target: "loongarch64-unknown-linux-musl".into(), metadata: crate::spec::TargetMetadata { - description: Some("LoongArch64 Linux (LP64D ABI) with musl 1.2.3".into()), - tier: Some(3), - host_tools: Some(false), - std: None, // ? + description: Some("LoongArch64 Linux (LP64D ABI) with musl 1.2.5".into()), + tier: Some(2), + host_tools: Some(true), + std: Some(true), }, pointer_width: 64, data_layout: "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128".into(), diff --git a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_none.rs b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_none.rs index 744ffff721fe7..c7f47da6972e7 100644 --- a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_none.rs +++ b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_none.rs @@ -1,11 +1,12 @@ -use crate::spec::{Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel}; -use crate::spec::{Target, TargetOptions}; +use crate::spec::{ + Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions, +}; pub fn target() -> Target { Target { llvm_target: "loongarch64-unknown-none".into(), metadata: crate::spec::TargetMetadata { - description: None, + description: Some("Freestanding/bare-metal LoongArch64".into()), tier: Some(2), host_tools: Some(false), std: Some(false), diff --git a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_none_softfloat.rs b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_none_softfloat.rs index a382e7a53fbdf..21e4f4a2b057b 100644 --- a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_none_softfloat.rs +++ b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_none_softfloat.rs @@ -1,11 +1,12 @@ -use crate::spec::{Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel}; -use crate::spec::{Target, TargetOptions}; +use crate::spec::{ + Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions, +}; pub fn target() -> Target { Target { llvm_target: "loongarch64-unknown-none".into(), metadata: crate::spec::TargetMetadata { - description: None, + description: Some("Freestanding/bare-metal LoongArch64 softfloat".into()), tier: Some(2), host_tools: Some(false), std: Some(false), diff --git a/compiler/rustc_target/src/spec/targets/nvptx64_nvidia_cuda.rs b/compiler/rustc_target/src/spec/targets/nvptx64_nvidia_cuda.rs index 15156fbcfc9e7..ec5edfb6e42c2 100644 --- a/compiler/rustc_target/src/spec/targets/nvptx64_nvidia_cuda.rs +++ b/compiler/rustc_target/src/spec/targets/nvptx64_nvidia_cuda.rs @@ -1,5 +1,6 @@ -use crate::spec::LinkSelfContainedDefault; -use crate::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, Target, TargetOptions}; +use crate::spec::{ + LinkSelfContainedDefault, LinkerFlavor, MergeFunctions, PanicStrategy, Target, TargetOptions, +}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv32im_risc0_zkvm_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32im_risc0_zkvm_elf.rs index 726778aca0d89..8aa5e0988902e 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32im_risc0_zkvm_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32im_risc0_zkvm_elf.rs @@ -1,5 +1,4 @@ -use crate::spec::{Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel}; -use crate::spec::{Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_musl.rs index 3e575fdd528de..8b40132986867 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_musl.rs @@ -21,6 +21,7 @@ pub fn target() -> Target { llvm_abiname: "lp64d".into(), max_atomic_width: Some(64), supported_split_debuginfo: Cow::Borrowed(&[SplitDebuginfo::Off]), + crt_static_default: false, ..base::linux_musl::opts() }, } diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_none_elf.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_none_elf.rs index a75f8969a7393..bfd88bd042e62 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_none_elf.rs @@ -1,6 +1,7 @@ -use crate::spec::SanitizerSet; -use crate::spec::{Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy}; -use crate::spec::{RelocModel, Target, TargetOptions}; +use crate::spec::{ + Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel, SanitizerSet, Target, + TargetOptions, +}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_nuttx_elf.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_nuttx_elf.rs index 6a468227ba69b..5bea708e0dd23 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_nuttx_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_nuttx_elf.rs @@ -1,6 +1,7 @@ -use crate::spec::SanitizerSet; -use crate::spec::{cvs, Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy}; -use crate::spec::{RelocModel, Target, TargetOptions}; +use crate::spec::{ + cvs, Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel, SanitizerSet, Target, + TargetOptions, +}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs index ba9a10e663319..fa3f1eff45781 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs @@ -1,5 +1,7 @@ -use crate::spec::{Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy}; -use crate::spec::{RelocModel, SanitizerSet, Target, TargetOptions}; +use crate::spec::{ + Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel, SanitizerSet, Target, + TargetOptions, +}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs index 1e18466c2067d..215c0724f91de 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs @@ -1,6 +1,7 @@ -use crate::spec::SanitizerSet; -use crate::spec::{cvs, Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy}; -use crate::spec::{RelocModel, Target, TargetOptions}; +use crate::spec::{ + cvs, Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel, SanitizerSet, Target, + TargetOptions, +}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv4t_none_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv4t_none_eabi.rs index 96dd8588d4f66..8806f3e87fa2a 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv4t_none_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv4t_none_eabi.rs @@ -9,8 +9,7 @@ //! The default link script is very likely wrong, so you should use //! `-Clink-arg=-Tmy_script.ld` to override that with a correct linker script. -use crate::spec::{base, PanicStrategy, RelocModel, Target, TargetOptions}; -use crate::spec::{cvs, FramePointer}; +use crate::spec::{base, cvs, FramePointer, PanicStrategy, RelocModel, Target, TargetOptions}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/wasm32_wasip1.rs b/compiler/rustc_target/src/spec/targets/wasm32_wasip1.rs index a8e7f22c06894..29e6dff2068fc 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32_wasip1.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32_wasip1.rs @@ -10,9 +10,7 @@ //! was since renamed to `wasm32-wasip1` after the preview2 target was //! introduced. -use crate::spec::crt_objects; -use crate::spec::LinkSelfContainedDefault; -use crate::spec::{base, Cc, LinkerFlavor, Target}; +use crate::spec::{base, crt_objects, Cc, LinkSelfContainedDefault, LinkerFlavor, Target}; pub fn target() -> Target { let mut options = base::wasm::options(); diff --git a/compiler/rustc_target/src/spec/targets/wasm32_wasip2.rs b/compiler/rustc_target/src/spec/targets/wasm32_wasip2.rs index 63d1f4869be4d..489bae4fedf17 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32_wasip2.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32_wasip2.rs @@ -16,9 +16,7 @@ //! You can see more about wasi at and the component model at //! . -use crate::spec::crt_objects; -use crate::spec::LinkSelfContainedDefault; -use crate::spec::{base, RelocModel, Target}; +use crate::spec::{base, crt_objects, LinkSelfContainedDefault, RelocModel, Target}; pub fn target() -> Target { let mut options = base::wasm::options(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_apple_darwin.rs b/compiler/rustc_target/src/spec/targets/x86_64_apple_darwin.rs index 94638ae62f834..c3a52a506bc9d 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_apple_darwin.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_apple_darwin.rs @@ -1,6 +1,5 @@ use crate::spec::base::apple::{macos_llvm_target, opts, Arch, TargetAbi}; -use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, SanitizerSet}; -use crate::spec::{Target, TargetOptions}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, SanitizerSet, Target, TargetOptions}; pub fn target() -> Target { let arch = Arch::X86_64; diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_none.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_none.rs index 549706998d463..175a53f237da1 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_none.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_none.rs @@ -4,8 +4,10 @@ // `target-cpu` compiler flags to opt-in more hardware-specific // features. -use crate::spec::{Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy}; -use crate::spec::{RelroLevel, SanitizerSet, StackProbeType, Target, TargetOptions}; +use crate::spec::{ + Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelroLevel, SanitizerSet, StackProbeType, + Target, TargetOptions, +}; pub fn target() -> Target { let opts = TargetOptions { diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs index 6da1fcca58c87..2933da92fcc31 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs @@ -5,10 +5,8 @@ // The win64 ABI is used. It differs from the sysv64 ABI, so we must use a windows target with // LLVM. "x86_64-unknown-windows" is used to get the minimal subset of windows-specific features. -use crate::{ - abi::call::Conv, - spec::{base, Target}, -}; +use crate::abi::call::Conv; +use crate::spec::{base, Target}; pub fn target() -> Target { let mut base = base::uefi_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64h_apple_darwin.rs b/compiler/rustc_target/src/spec/targets/x86_64h_apple_darwin.rs index 72cbc1be9310b..a932d4a3cb466 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64h_apple_darwin.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64h_apple_darwin.rs @@ -1,6 +1,5 @@ use crate::spec::base::apple::{macos_llvm_target, opts, Arch, TargetAbi}; -use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, SanitizerSet}; -use crate::spec::{Target, TargetOptions}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, SanitizerSet, Target, TargetOptions}; pub fn target() -> Target { let arch = Arch::X86_64h; diff --git a/compiler/rustc_target/src/spec/targets/xtensa_esp32_espidf.rs b/compiler/rustc_target/src/spec/targets/xtensa_esp32_espidf.rs index 1b66fdbd2afd6..f041e791a9b0f 100644 --- a/compiler/rustc_target/src/spec/targets/xtensa_esp32_espidf.rs +++ b/compiler/rustc_target/src/spec/targets/xtensa_esp32_espidf.rs @@ -1,5 +1,6 @@ use crate::abi::Endian; -use crate::spec::{base::xtensa, cvs, Target, TargetOptions}; +use crate::spec::base::xtensa; +use crate::spec::{cvs, Target, TargetOptions}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/xtensa_esp32_none_elf.rs b/compiler/rustc_target/src/spec/targets/xtensa_esp32_none_elf.rs index bf5237163139f..05666bd81aa13 100644 --- a/compiler/rustc_target/src/spec/targets/xtensa_esp32_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/xtensa_esp32_none_elf.rs @@ -1,4 +1,5 @@ -use crate::spec::{base::xtensa, Target, TargetOptions}; +use crate::spec::base::xtensa; +use crate::spec::{Target, TargetOptions}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_espidf.rs b/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_espidf.rs index ad5fda8a4ae14..83ef520551f55 100644 --- a/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_espidf.rs +++ b/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_espidf.rs @@ -1,5 +1,6 @@ use crate::abi::Endian; -use crate::spec::{base::xtensa, cvs, Target, TargetOptions}; +use crate::spec::base::xtensa; +use crate::spec::{cvs, Target, TargetOptions}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_none_elf.rs b/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_none_elf.rs index 219b2aa48c1fb..aa125eb1ba689 100644 --- a/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_none_elf.rs @@ -1,4 +1,5 @@ -use crate::spec::{base::xtensa, Target, TargetOptions}; +use crate::spec::base::xtensa; +use crate::spec::{Target, TargetOptions}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_espidf.rs b/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_espidf.rs index ab1d1df43dd99..e18acfccf5ff2 100644 --- a/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_espidf.rs +++ b/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_espidf.rs @@ -1,5 +1,6 @@ use crate::abi::Endian; -use crate::spec::{base::xtensa, cvs, Target, TargetOptions}; +use crate::spec::base::xtensa; +use crate::spec::{cvs, Target, TargetOptions}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_none_elf.rs b/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_none_elf.rs index 632eef3a5842c..ecbb51dfb665d 100644 --- a/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_none_elf.rs @@ -1,4 +1,5 @@ -use crate::spec::{base::xtensa, Target, TargetOptions}; +use crate::spec::base::xtensa; +use crate::spec::{Target, TargetOptions}; pub fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/tests/tests_impl.rs b/compiler/rustc_target/src/spec/tests/tests_impl.rs index 3be18ef3127d5..fc5bd846e0241 100644 --- a/compiler/rustc_target/src/spec/tests/tests_impl.rs +++ b/compiler/rustc_target/src/spec/tests/tests_impl.rs @@ -1,6 +1,7 @@ -use super::super::*; use std::assert_matches::assert_matches; +use super::super::*; + // Test target self-consistency and JSON encoding/decoding roundtrip. pub(super) fn test_target(mut target: Target) { let recycled_target = Target::from_json(target.to_json()).map(|(j, _)| j); diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index 4fb0323b6cfa1..4e2617c467949 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -1,5 +1,4 @@ -use rustc_span::symbol::sym; -use rustc_span::symbol::Symbol; +use rustc_span::symbol::{sym, Symbol}; /// Features that control behaviour of rustc, rather than the codegen. pub const RUSTC_SPECIFIC_FEATURES: &[&str] = &["crt-static"]; @@ -239,6 +238,9 @@ const X86_ALLOWED_FEATURES: &[(&str, Stability)] = &[ ("rdseed", Stable), ("rtm", Unstable(sym::rtm_target_feature)), ("sha", Stable), + ("sha512", Unstable(sym::sha512_sm_x86)), + ("sm3", Unstable(sym::sha512_sm_x86)), + ("sm4", Unstable(sym::sha512_sm_x86)), ("sse", Stable), ("sse2", Stable), ("sse3", Stable), @@ -331,12 +333,14 @@ const WASM_ALLOWED_FEATURES: &[(&str, Stability)] = &[ ("mutable-globals", Stable), ("nontrapping-fptoint", Stable), ("reference-types", Unstable(sym::wasm_target_feature)), - ("relaxed-simd", Unstable(sym::wasm_target_feature)), + ("relaxed-simd", Stable), ("sign-ext", Stable), ("simd128", Stable), // tidy-alphabetical-end ]; +const WASM_IMPLICIT_FEATURES: &[(&str, &str)] = &[("relaxed-simd", "simd128")]; + const BPF_ALLOWED_FEATURES: &[(&str, Stability)] = &[("alu32", Unstable(sym::bpf_target_feature))]; const CSKY_ALLOWED_FEATURES: &[(&str, Stability)] = &[ @@ -453,4 +457,13 @@ impl super::spec::Target { _ => &[], } } + + /// Returns a list of target features. Each items first target feature + /// implicitly enables the second one. + pub fn implicit_target_features(&self) -> &'static [(&'static str, &'static str)] { + match &*self.arch { + "wasm32" | "wasm64" => WASM_IMPLICIT_FEATURES, + _ => &[], + } + } } diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index daabdec8f9ea2..8ccb2a8483ae3 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -60,12 +60,11 @@ use rustc_hir::{self as hir}; use rustc_macros::extension; use rustc_middle::bug; use rustc_middle::dep_graph::DepContext; -use rustc_middle::ty::error::ExpectedFound; -use rustc_middle::ty::error::TypeErrorToStringExt; +use rustc_middle::ty::error::{ExpectedFound, TypeError, TypeErrorToStringExt}; use rustc_middle::ty::print::{with_forced_trimmed_paths, PrintError, PrintTraitRefExt as _}; use rustc_middle::ty::{ - self, error::TypeError, List, Region, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, - TypeVisitable, TypeVisitableExt, + self, List, Region, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, TypeVisitable, + TypeVisitableExt, }; use rustc_span::{sym, BytePos, DesugaringKind, Pos, Span}; use rustc_target::spec::abi; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs index 56ea70bcf1d52..f6dd7898fb28e 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs @@ -1,13 +1,11 @@ -use crate::error_reporting::TypeErrCtxt; -use crate::errors::{ - AmbiguousImpl, AmbiguousReturn, AnnotationRequired, InferenceBadError, - SourceKindMultiSuggestion, SourceKindSubdiag, -}; -use crate::infer::InferCtxt; -use rustc_errors::{codes::*, Diag, IntoDiagArg}; +use std::borrow::Cow; +use std::iter; +use std::path::PathBuf; + +use rustc_errors::codes::*; +use rustc_errors::{Diag, IntoDiagArg}; use rustc_hir as hir; -use rustc_hir::def::Res; -use rustc_hir::def::{CtorOf, DefKind, Namespace}; +use rustc_hir::def::{CtorOf, DefKind, Namespace, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{Body, Closure, Expr, ExprKind, FnRetTy, HirId, LetStmt, LocalSource}; @@ -21,9 +19,13 @@ use rustc_middle::ty::{ }; use rustc_span::symbol::{sym, Ident}; use rustc_span::{BytePos, Span, DUMMY_SP}; -use std::borrow::Cow; -use std::iter; -use std::path::PathBuf; + +use crate::error_reporting::TypeErrCtxt; +use crate::errors::{ + AmbiguousImpl, AmbiguousReturn, AnnotationRequired, InferenceBadError, + SourceKindMultiSuggestion, SourceKindSubdiag, +}; +use crate::infer::InferCtxt; pub enum TypeAnnotationNeeded { /// ```compile_fail,E0282 @@ -932,13 +934,13 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { // which makes this somewhat difficult and prevents us from just // using `self.path_inferred_arg_iter` here. hir::ExprKind::Struct(&hir::QPath::Resolved(_self_ty, path), _, _) - // FIXME(TaKO8Ki): Ideally we should support this. For that - // we have to map back from the self type to the - // type alias though. That's difficult. + // FIXME(TaKO8Ki): Ideally we should support other kinds, + // such as `TyAlias` or `AssocTy`. For that we have to map + // back from the self type to the type alias though. That's difficult. // // See the `need_type_info/issue-103053.rs` test for // a example. - if !matches!(path.res, Res::Def(DefKind::TyAlias, _)) => { + if matches!(path.res, Res::Def(DefKind::Struct | DefKind::Enum | DefKind::Union, _)) => { if let Some(ty) = self.opt_node_type(expr.hir_id) && let ty::Adt(_, args) = ty.kind() { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/different_lifetimes.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/different_lifetimes.rs index 74dcde03639d6..8f84d77121605 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/different_lifetimes.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/different_lifetimes.rs @@ -1,21 +1,17 @@ //! Error Reporting for Anonymous Region Lifetime Errors //! where both the regions are anonymous. -use crate::error_reporting::infer::nice_region_error::find_anon_type::find_anon_type; -use crate::error_reporting::infer::nice_region_error::util::AnonymousParamInfo; -use crate::error_reporting::infer::nice_region_error::NiceRegionError; -use crate::errors::AddLifetimeParamsSuggestion; -use crate::errors::LifetimeMismatch; -use crate::errors::LifetimeMismatchLabels; -use crate::infer::RegionResolutionError; -use crate::infer::SubregionOrigin; - -use rustc_errors::Subdiagnostic; -use rustc_errors::{Diag, ErrorGuaranteed}; +use rustc_errors::{Diag, ErrorGuaranteed, Subdiagnostic}; use rustc_hir::def_id::LocalDefId; use rustc_hir::Ty; use rustc_middle::ty::{Region, TyCtxt}; +use crate::error_reporting::infer::nice_region_error::find_anon_type::find_anon_type; +use crate::error_reporting::infer::nice_region_error::util::AnonymousParamInfo; +use crate::error_reporting::infer::nice_region_error::NiceRegionError; +use crate::errors::{AddLifetimeParamsSuggestion, LifetimeMismatch, LifetimeMismatchLabels}; +use crate::infer::{RegionResolutionError, SubregionOrigin}; + impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when both the concerned regions are anonymous. /// diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/find_anon_type.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/find_anon_type.rs index b91b755d68370..3f35391be1355 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/find_anon_type.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/find_anon_type.rs @@ -1,4 +1,5 @@ use core::ops::ControlFlow; + use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, Visitor}; @@ -84,7 +85,7 @@ impl<'tcx> Visitor<'tcx> for FindNestedTypeVisitor<'tcx> { } hir::TyKind::TraitObject(bounds, ..) => { - for bound in bounds { + for (bound, _) in bounds { self.current_index.shift_in(1); self.visit_poly_trait_ref(bound); self.current_index.shift_out(1); diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs index 550cc455e0181..221f6675d22cc 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs @@ -1,14 +1,6 @@ //! Error Reporting for when the lifetime for a type doesn't match the `impl` selected for a predicate //! to hold. -use crate::error_reporting::infer::nice_region_error::NiceRegionError; -use crate::errors::{note_and_explain, IntroducesStaticBecauseUnmetLifetimeReq}; -use crate::errors::{ - DoesNotOutliveStaticFromImpl, ImplicitStaticLifetimeSubdiag, MismatchedStaticLifetime, -}; -use crate::infer::RegionResolutionError; -use crate::infer::{SubregionOrigin, TypeTrace}; -use crate::traits::ObligationCauseCode; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{ErrorGuaranteed, MultiSpan}; use rustc_hir as hir; @@ -16,6 +8,14 @@ use rustc_hir::intravisit::Visitor; use rustc_middle::bug; use rustc_middle::ty::TypeVisitor; +use crate::error_reporting::infer::nice_region_error::NiceRegionError; +use crate::errors::{ + note_and_explain, DoesNotOutliveStaticFromImpl, ImplicitStaticLifetimeSubdiag, + IntroducesStaticBecauseUnmetLifetimeReq, MismatchedStaticLifetime, +}; +use crate::infer::{RegionResolutionError, SubregionOrigin, TypeTrace}; +use crate::traits::ObligationCauseCode; + impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { pub(super) fn try_report_mismatched_static_lifetime(&self) -> Option { let error = self.error.as_ref()?; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs index b83ecd8320c6e..79a770ac9b300 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs @@ -1,11 +1,12 @@ -use crate::error_reporting::TypeErrCtxt; -use crate::infer::RegionResolutionError; -use crate::infer::RegionResolutionError::*; use rustc_errors::{Diag, ErrorGuaranteed}; use rustc_hir::def_id::LocalDefId; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::Span; +use crate::error_reporting::TypeErrCtxt; +use crate::infer::RegionResolutionError; +use crate::infer::RegionResolutionError::*; + mod different_lifetimes; pub mod find_anon_type; mod mismatched_static_lifetime; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/named_anon_conflict.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/named_anon_conflict.rs index d1802d2f5eeb0..f91a81f76f425 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/named_anon_conflict.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/named_anon_conflict.rs @@ -1,13 +1,14 @@ //! Error Reporting for Anonymous Region Lifetime Errors //! where one region is named and the other is anonymous. -use crate::error_reporting::infer::nice_region_error::find_anon_type::find_anon_type; -use crate::error_reporting::infer::nice_region_error::NiceRegionError; -use crate::errors::ExplicitLifetimeRequired; use rustc_errors::Diag; use rustc_middle::ty; use rustc_span::symbol::kw; +use crate::error_reporting::infer::nice_region_error::find_anon_type::find_anon_type; +use crate::error_reporting::infer::nice_region_error::NiceRegionError; +use crate::errors::ExplicitLifetimeRequired; + impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// When given a `ConcreteFailure` for a function with parameters containing a named region and /// an anonymous region, emit an descriptive diagnostic error. diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs index 476ac3f1720b8..8da0edbeb02aa 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs @@ -1,12 +1,5 @@ -use crate::error_reporting::infer::nice_region_error::NiceRegionError; -use crate::errors::{ - ActualImplExpectedKind, ActualImplExpectedLifetimeKind, ActualImplExplNotes, - TraitPlaceholderMismatch, TyOrSig, -}; -use crate::infer::RegionResolutionError; -use crate::infer::ValuePairs; -use crate::infer::{SubregionOrigin, TypeTrace}; -use crate::traits::{ObligationCause, ObligationCauseCode}; +use std::fmt; + use rustc_data_structures::intern::Interned; use rustc_errors::{Diag, IntoDiagArg}; use rustc_hir::def::Namespace; @@ -14,10 +7,15 @@ use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; use rustc_middle::bug; use rustc_middle::ty::error::ExpectedFound; use rustc_middle::ty::print::{FmtPrinter, Print, PrintTraitRefExt as _, RegionHighlightMode}; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, RePlaceholder, Region, TyCtxt}; +use rustc_middle::ty::{self, GenericArgsRef, RePlaceholder, Region, TyCtxt}; -use std::fmt; +use crate::error_reporting::infer::nice_region_error::NiceRegionError; +use crate::errors::{ + ActualImplExpectedKind, ActualImplExpectedLifetimeKind, ActualImplExplNotes, + TraitPlaceholderMismatch, TyOrSig, +}; +use crate::infer::{RegionResolutionError, SubregionOrigin, TypeTrace, ValuePairs}; +use crate::traits::{ObligationCause, ObligationCauseCode}; // HACK(eddyb) maybe move this in a more central location. #[derive(Copy, Clone)] diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_relation.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_relation.rs index e9f17a3e3e2d0..9c772f42ccaa3 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_relation.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_relation.rs @@ -1,10 +1,11 @@ -use crate::error_reporting::infer::nice_region_error::NiceRegionError; -use crate::errors::PlaceholderRelationLfNotSatisfied; -use crate::infer::{RegionResolutionError, SubregionOrigin}; use rustc_data_structures::intern::Interned; use rustc_errors::Diag; use rustc_middle::ty::{self, RePlaceholder, Region}; +use crate::error_reporting::infer::nice_region_error::NiceRegionError; +use crate::errors::PlaceholderRelationLfNotSatisfied; +use crate::infer::{RegionResolutionError, SubregionOrigin}; + impl<'tcx> NiceRegionError<'_, 'tcx> { /// Emitted wwhen given a `ConcreteFailure` when relating two placeholders. pub(super) fn try_report_placeholder_relation(&self) -> Option> { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs index ce157ff3dc8d9..dc775b824da47 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs @@ -1,13 +1,5 @@ //! Error Reporting for static impl Traits. -use crate::error_reporting::infer::nice_region_error::NiceRegionError; -use crate::errors::{ - ButCallingIntroduces, ButNeedsToSatisfy, DynTraitConstraintSuggestion, MoreTargeted, - ReqIntroducedLocations, -}; -use crate::infer::RegionResolutionError; -use crate::infer::{SubregionOrigin, TypeTrace}; -use crate::traits::{ObligationCauseCode, UnifyReceiverContext}; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, Subdiagnostic}; use rustc_hir::def_id::DefId; @@ -19,10 +11,17 @@ use rustc_hir::{ use rustc_middle::ty::{ self, AssocItemContainer, StaticLifetimeVisitor, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor, }; +use rustc_span::def_id::LocalDefId; use rustc_span::symbol::Ident; use rustc_span::Span; -use rustc_span::def_id::LocalDefId; +use crate::error_reporting::infer::nice_region_error::NiceRegionError; +use crate::errors::{ + ButCallingIntroduces, ButNeedsToSatisfy, DynTraitConstraintSuggestion, MoreTargeted, + ReqIntroducedLocations, +}; +use crate::infer::{RegionResolutionError, SubregionOrigin, TypeTrace}; +use crate::traits::{ObligationCauseCode, UnifyReceiverContext}; impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when the return type is a static `impl Trait`, @@ -607,7 +606,7 @@ impl<'a, 'tcx> Visitor<'tcx> for HirTraitObjectVisitor<'a> { _, ) = t.kind { - for ptr in poly_trait_refs { + for (ptr, _) in poly_trait_refs { if Some(self.1) == ptr.trait_ref.trait_def_id() { self.0.push(ptr.span); } diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs index c58c7e1355174..09af00beba7ad 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs @@ -1,9 +1,5 @@ //! Error Reporting for `impl` items that do not match the obligations from their `trait`. -use crate::error_reporting::infer::nice_region_error::NiceRegionError; -use crate::errors::{ConsiderBorrowingParamHelp, RelationshipHelp, TraitImplDiff}; -use crate::infer::RegionResolutionError; -use crate::infer::{Subtype, ValuePairs}; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; use rustc_hir::def::Res; @@ -16,6 +12,10 @@ use rustc_middle::ty::print::RegionHighlightMode; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitor}; use rustc_span::Span; +use crate::error_reporting::infer::nice_region_error::NiceRegionError; +use crate::errors::{ConsiderBorrowingParamHelp, RelationshipHelp, TraitImplDiff}; +use crate::infer::{RegionResolutionError, Subtype, ValuePairs}; + impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when the `impl` doesn't conform to the `trait`. pub(super) fn try_report_impl_not_conforming_to_trait(&self) -> Option { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note.rs index aeb3049c2ae96..04e1be22a4d06 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note.rs @@ -1,10 +1,3 @@ -use crate::error_reporting::infer::{note_and_explain_region, TypeErrCtxt}; -use crate::errors::{ - note_and_explain, FulfillReqLifetime, LfBoundNotSatisfied, OutlivesBound, OutlivesContent, - RefLongerThanData, RegionOriginNote, WhereClauseSuggestions, -}; -use crate::fluent_generated as fluent; -use crate::infer::{self, SubregionOrigin}; use rustc_errors::{Diag, Subdiagnostic}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::traits::ObligationCauseCode; @@ -13,6 +6,13 @@ use rustc_middle::ty::{self, IsSuggestable, Region, Ty}; use rustc_span::symbol::kw; use super::ObligationCauseAsDiagArg; +use crate::error_reporting::infer::{note_and_explain_region, TypeErrCtxt}; +use crate::errors::{ + note_and_explain, FulfillReqLifetime, LfBoundNotSatisfied, OutlivesBound, OutlivesContent, + RefLongerThanData, RegionOriginNote, WhereClauseSuggestions, +}; +use crate::fluent_generated as fluent; +use crate::infer::{self, SubregionOrigin}; impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { pub(super) fn note_region_origin(&self, err: &mut Diag<'_>, origin: &SubregionOrigin<'tcx>) { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs index f9110cfb3b970..864510bb65047 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs @@ -2,14 +2,12 @@ use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect}; use rustc_errors::{pluralize, Diag, MultiSpan}; use rustc_hir as hir; use rustc_hir::def::DefKind; -use rustc_middle::traits::ObligationCauseCode; -use rustc_middle::ty::error::ExpectedFound; -use rustc_middle::ty::print::Printer; -use rustc_middle::{ - traits::ObligationCause, - ty::{self, error::TypeError, print::FmtPrinter, suggest_constraining_type_param, Ty}, -}; -use rustc_span::{def_id::DefId, sym, BytePos, Span, Symbol}; +use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; +use rustc_middle::ty::error::{ExpectedFound, TypeError}; +use rustc_middle::ty::print::{FmtPrinter, Printer}; +use rustc_middle::ty::{self, suggest_constraining_type_param, Ty}; +use rustc_span::def_id::DefId; +use rustc_span::{sym, BytePos, Span, Symbol}; use crate::error_reporting::TypeErrCtxt; use crate::infer::InferCtxtExt; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs index 1ef32d110b31a..ee159aa0b77a6 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs @@ -1,5 +1,5 @@ -use crate::error_reporting::infer::hir::Path; use core::ops::ControlFlow; + use hir::def::CtorKind; use hir::intravisit::{walk_expr, walk_stmt, Visitor}; use hir::{LetStmt, QPath}; @@ -7,8 +7,7 @@ use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{Applicability, Diag}; use rustc_hir as hir; use rustc_hir::def::Res; -use rustc_hir::MatchSource; -use rustc_hir::Node; +use rustc_hir::{MatchSource, Node}; use rustc_middle::traits::{ IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode, StatementAsExpression, @@ -17,6 +16,7 @@ use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self as ty, GenericArgKind, IsSuggestable, Ty, TypeVisitableExt}; use rustc_span::{sym, Span}; +use crate::error_reporting::infer::hir::Path; use crate::error_reporting::TypeErrCtxt; use crate::errors::{ ConsiderAddingAwait, FnConsiderCasting, FnItemsAreDistinct, FnUniqTypes, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index a7ea308a818b4..2ce1b955af521 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -1,31 +1,16 @@ -use super::on_unimplemented::{AppendConstMessage, OnUnimplementedNote}; -use super::suggestions::get_explanation_based_on_obligation; -use crate::error_reporting::infer::TyCategory; -use crate::error_reporting::traits::report_object_safety_error; -use crate::error_reporting::TypeErrCtxt; -use crate::errors::{ - AsyncClosureNotFn, ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch, -}; -use crate::infer::InferCtxtExt as _; -use crate::infer::{self, InferCtxt}; -use crate::traits::query::evaluate_obligation::InferCtxtExt as _; -use crate::traits::NormalizeExt; -use crate::traits::{ - elaborate, MismatchedProjectionTypes, Obligation, ObligationCause, ObligationCauseCode, - ObligationCtxt, Overflow, PredicateObligation, SelectionError, SignatureMismatch, - TraitNotObjectSafe, -}; use core::ops::ControlFlow; +use std::borrow::Cow; + use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::unord::UnordSet; use rustc_errors::codes::*; -use rustc_errors::{pluralize, struct_span_code_err, Applicability, StringPart}; -use rustc_errors::{Diag, ErrorGuaranteed, StashKey}; +use rustc_errors::{ + pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, StashKey, StringPart, +}; use rustc_hir::def::Namespace; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::Visitor; -use rustc_hir::Node; -use rustc_hir::{self as hir, LangItem}; +use rustc_hir::{self as hir, LangItem, Node}; use rustc_infer::infer::{InferOk, TypeTrace}; use rustc_middle::traits::select::OverflowError; use rustc_middle::traits::SignatureMismatchData; @@ -42,11 +27,25 @@ use rustc_middle::ty::{ use rustc_middle::{bug, span_bug}; use rustc_span::symbol::sym; use rustc_span::{BytePos, Span, Symbol, DUMMY_SP}; -use std::borrow::Cow; +use super::on_unimplemented::{AppendConstMessage, OnUnimplementedNote}; +use super::suggestions::get_explanation_based_on_obligation; use super::{ ArgKind, CandidateSimilarity, GetSafeTransmuteErrorAndReason, ImplCandidate, UnsatisfiedConst, }; +use crate::error_reporting::infer::TyCategory; +use crate::error_reporting::traits::report_object_safety_error; +use crate::error_reporting::TypeErrCtxt; +use crate::errors::{ + AsyncClosureNotFn, ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch, +}; +use crate::infer::{self, InferCtxt, InferCtxtExt as _}; +use crate::traits::query::evaluate_obligation::InferCtxtExt as _; +use crate::traits::{ + elaborate, MismatchedProjectionTypes, NormalizeExt, Obligation, ObligationCause, + ObligationCauseCode, ObligationCtxt, Overflow, PredicateObligation, SelectionError, + SignatureMismatch, TraitNotObjectSafe, +}; impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { /// The `root_obligation` parameter should be the `root_obligation` field diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs index 87fdc5ddff85c..40a1c1840099e 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs @@ -19,11 +19,10 @@ use rustc_middle::ty::print::{with_no_trimmed_paths, PrintTraitRefExt as _}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::{ErrorGuaranteed, ExpnKind, Span}; +pub use self::overflow::*; use crate::error_reporting::TypeErrCtxt; use crate::traits::{FulfillmentError, FulfillmentErrorCode}; -pub use self::overflow::*; - // When outputting impl candidates, prefer showing those that are more similar. // // We also compare candidates after skipping lifetimes, which has a lower @@ -437,7 +436,7 @@ pub fn report_object_safety_error<'tcx>( if tcx.parent_hir_node(hir_id).fn_sig().is_some() { // Do not suggest `impl Trait` when dealing with things like super-traits. err.span_suggestion_verbose( - ty.span.until(trait_ref.span), + ty.span.until(trait_ref.0.span), "consider using an opaque type instead", "impl ", Applicability::MaybeIncorrect, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs index f65de590ccf2f..3a082893c5c66 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs @@ -1,29 +1,27 @@ -use super::{ObligationCauseCode, PredicateObligation}; -use crate::error_reporting::TypeErrCtxt; -use crate::errors::{ - EmptyOnClauseInOnUnimplemented, InvalidOnClauseInOnUnimplemented, NoValueInOnUnimplemented, -}; -use crate::infer::InferCtxtExt; -use rustc_ast::AttrArgs; -use rustc_ast::AttrArgsEq; -use rustc_ast::AttrKind; -use rustc_ast::{Attribute, MetaItem, NestedMetaItem}; -use rustc_attr as attr; +use std::iter; +use std::path::PathBuf; + +use rustc_ast::{AttrArgs, AttrArgsEq, AttrKind, Attribute, MetaItem, NestedMetaItem}; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::{codes::*, struct_span_code_err, ErrorGuaranteed}; -use rustc_hir as hir; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, ErrorGuaranteed}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_macros::LintDiagnostic; use rustc_middle::bug; use rustc_middle::ty::print::PrintTraitRefExt as _; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, GenericParamDefKind, TyCtxt}; +use rustc_middle::ty::{self, GenericArgsRef, GenericParamDefKind, TyCtxt}; use rustc_parse_format::{ParseMode, Parser, Piece, Position}; use rustc_session::lint::builtin::UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; -use std::iter; -use std::path::PathBuf; +use {rustc_attr as attr, rustc_hir as hir}; + +use super::{ObligationCauseCode, PredicateObligation}; +use crate::error_reporting::TypeErrCtxt; +use crate::errors::{ + EmptyOnClauseInOnUnimplemented, InvalidOnClauseInOnUnimplemented, NoValueInOnUnimplemented, +}; +use crate::infer::InferCtxtExt; /// The symbols which are always allowed in a format string static ALLOWED_FORMAT_SYMBOLS: &[Symbol] = &[ diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 885216e62165e..0d15ef55e24e7 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -1,34 +1,33 @@ // ignore-tidy-filelength -use super::{ - DefIdOrName, FindExprBySpan, ImplCandidate, Obligation, ObligationCause, ObligationCauseCode, - PredicateObligation, -}; - -use crate::error_reporting::TypeErrCtxt; -use crate::errors; -use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt}; +use std::assert_matches::debug_assert_matches; +use std::borrow::Cow; +use std::iter; +use itertools::{EitherOrBoth, Itertools}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::stack::ensure_sufficient_stack; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, pluralize, struct_span_code_err, Applicability, Diag, EmissionGuarantee, MultiSpan, - Style, SuggestionStyle, + pluralize, struct_span_code_err, Applicability, Diag, EmissionGuarantee, MultiSpan, Style, + SuggestionStyle, }; use rustc_hir as hir; -use rustc_hir::def::CtorOf; -use rustc_hir::def::{DefKind, Res}; +use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::Visitor; -use rustc_hir::is_range_literal; use rustc_hir::lang_items::LangItem; -use rustc_hir::{CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, HirId, Node}; -use rustc_infer::infer::InferCtxt; -use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk}; +use rustc_hir::{ + is_range_literal, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, HirId, Node, +}; +use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk}; use rustc_middle::hir::map; use rustc_middle::traits::IsConstable; use rustc_middle::ty::error::TypeError; -use rustc_middle::ty::print::PrintPolyTraitRefExt; +use rustc_middle::ty::print::{ + with_forced_trimmed_paths, with_no_trimmed_paths, PrintPolyTraitPredicateExt as _, + PrintPolyTraitRefExt, PrintTraitPredicateExt as _, +}; use rustc_middle::ty::{ self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, GenericArgs, InferTy, IsSuggestable, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable, TypeFolder, @@ -39,19 +38,16 @@ use rustc_span::def_id::LocalDefId; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{BytePos, DesugaringKind, ExpnKind, MacroKind, Span, DUMMY_SP}; use rustc_target::spec::abi; -use std::assert_matches::debug_assert_matches; -use std::borrow::Cow; -use std::iter; +use super::{ + DefIdOrName, FindExprBySpan, ImplCandidate, Obligation, ObligationCause, ObligationCauseCode, + PredicateObligation, +}; +use crate::error_reporting::TypeErrCtxt; +use crate::errors; use crate::infer::InferCtxtExt as _; use crate::traits::query::evaluate_obligation::InferCtxtExt as _; -use rustc_middle::ty::print::{ - with_forced_trimmed_paths, with_no_trimmed_paths, PrintPolyTraitPredicateExt as _, - PrintTraitPredicateExt as _, -}; - -use itertools::EitherOrBoth; -use itertools::Itertools; +use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt}; #[derive(Debug)] pub enum CoroutineInteriorOrUpvar { @@ -3040,11 +3036,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { match ty.kind { hir::TyKind::TraitObject(traits, _, _) => { let (span, kw) = match traits { - [first, ..] if first.span.lo() == ty.span.lo() => { + [(first, _), ..] if first.span.lo() == ty.span.lo() => { // Missing `dyn` in front of trait object. (ty.span.shrink_to_lo(), "dyn ") } - [first, ..] => (ty.span.until(first.span), ""), + [(first, _), ..] => (ty.span.until(first.span), ""), [] => span_bug!(ty.span, "trait object with no traits: {ty:?}"), }; let needs_parens = traits.len() != 1; diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index 0ee4485a36543..78f1f7d9b9b59 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -1,19 +1,18 @@ +use std::path::PathBuf; + use rustc_data_structures::fx::FxHashSet; +use rustc_errors::codes::*; use rustc_errors::{ - codes::*, Applicability, Diag, DiagCtxtHandle, DiagMessage, DiagStyledString, Diagnostic, + Applicability, Diag, DiagCtxtHandle, DiagMessage, DiagStyledString, Diagnostic, EmissionGuarantee, IntoDiagArg, Level, MultiSpan, SubdiagMessageOp, Subdiagnostic, }; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{walk_ty, Visitor}; -use rustc_hir::FnRetTy; -use rustc_hir::GenericParamKind; +use rustc_hir::{FnRetTy, GenericParamKind}; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_middle::ty::print::TraitRefPrintOnlyTraitPath; -use rustc_middle::ty::{ - self, print::PrintTraitRefExt as _, Binder, ClosureKind, FnSig, PolyTraitRef, Region, Ty, - TyCtxt, -}; +use rustc_middle::ty::print::{PrintTraitRefExt as _, TraitRefPrintOnlyTraitPath}; +use rustc_middle::ty::{self, Binder, ClosureKind, FnSig, PolyTraitRef, Region, Ty, TyCtxt}; use rustc_span::symbol::{kw, Ident, Symbol}; use rustc_span::{BytePos, Span}; @@ -22,8 +21,6 @@ use crate::error_reporting::infer::nice_region_error::placeholder_error::Highlig use crate::error_reporting::infer::ObligationCauseAsDiagArg; use crate::fluent_generated as fluent; -use std::path::PathBuf; - pub mod note_and_explain; #[derive(Diagnostic)] @@ -1585,10 +1582,7 @@ pub enum TypeErrorAdditionalDiags { span: Span, code: String, }, - #[multipart_suggestion( - trait_selection_meant_str_literal, - applicability = "machine-applicable" - )] + #[multipart_suggestion(trait_selection_meant_str_literal, applicability = "machine-applicable")] MeantStrLiteral { #[suggestion_part(code = "\"")] start: Span, diff --git a/compiler/rustc_trait_selection/src/errors/note_and_explain.rs b/compiler/rustc_trait_selection/src/errors/note_and_explain.rs index 1f18cd8c8d816..b14777630283f 100644 --- a/compiler/rustc_trait_selection/src/errors/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/errors/note_and_explain.rs @@ -1,10 +1,12 @@ -use crate::error_reporting::infer::nice_region_error::find_anon_type; -use crate::fluent_generated as fluent; use rustc_errors::{Diag, EmissionGuarantee, IntoDiagArg, SubdiagMessageOp, Subdiagnostic}; use rustc_hir::def_id::LocalDefId; use rustc_middle::bug; use rustc_middle::ty::{self, TyCtxt}; -use rustc_span::{symbol::kw, Span}; +use rustc_span::symbol::kw; +use rustc_span::Span; + +use crate::error_reporting::infer::nice_region_error::find_anon_type; +use crate::fluent_generated as fluent; struct DescriptionCtx<'a> { span: Option, diff --git a/compiler/rustc_trait_selection/src/infer.rs b/compiler/rustc_trait_selection/src/infer.rs index ad087620ae06d..c22925b73e351 100644 --- a/compiler/rustc_trait_selection/src/infer.rs +++ b/compiler/rustc_trait_selection/src/infer.rs @@ -1,20 +1,18 @@ -use crate::infer::at::ToTrace; -use crate::traits::query::evaluate_obligation::InferCtxtExt as _; -use crate::traits::{self, Obligation, ObligationCause, ObligationCtxt, SelectionContext}; +use std::fmt::Debug; use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; +pub use rustc_infer::infer::*; use rustc_macros::extension; use rustc_middle::arena::ArenaAllocatable; use rustc_middle::infer::canonical::{Canonical, CanonicalQueryResponse, QueryResponse}; use rustc_middle::traits::query::NoSolution; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; -use rustc_middle::ty::{GenericArg, Upcast}; +use rustc_middle::ty::{self, GenericArg, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, Upcast}; use rustc_span::DUMMY_SP; -use std::fmt::Debug; - -pub use rustc_infer::infer::*; +use crate::infer::at::ToTrace; +use crate::traits::query::evaluate_obligation::InferCtxtExt as _; +use crate::traits::{self, Obligation, ObligationCause, ObligationCtxt, SelectionContext}; #[extension(pub trait InferCtxtExt<'tcx>)] impl<'tcx> InferCtxt<'tcx> { diff --git a/compiler/rustc_trait_selection/src/regions.rs b/compiler/rustc_trait_selection/src/regions.rs index 5f986e22f5130..65762cfcd2ebf 100644 --- a/compiler/rustc_trait_selection/src/regions.rs +++ b/compiler/rustc_trait_selection/src/regions.rs @@ -1,10 +1,11 @@ -use crate::traits::ScrubbedTraitError; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{InferCtxt, RegionResolutionError}; use rustc_macros::extension; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::ObligationCause; +use crate::traits::ScrubbedTraitError; + #[extension(pub trait InferCtxtRegionExt<'tcx>)] impl<'tcx> InferCtxt<'tcx> { /// Resolve regions, using the deep normalizer to normalize any type-outlives diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index 76b88aeb0f7e6..49fa775a0a191 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -15,11 +15,10 @@ use rustc_middle::ty::{self, TyCtxt}; use rustc_next_trait_solver::solve::{GenerateProofTree, SolverDelegateEvalExt as _}; use rustc_span::symbol::sym; -use crate::traits::{FulfillmentError, FulfillmentErrorCode, ScrubbedTraitError}; - use super::delegate::SolverDelegate; use super::inspect::{self, ProofTreeInferCtxtExt, ProofTreeVisitor}; use super::Certainty; +use crate::traits::{FulfillmentError, FulfillmentErrorCode, ScrubbedTraitError}; /// A trait engine using the new trait solver. /// diff --git a/compiler/rustc_trait_selection/src/solve/normalize.rs b/compiler/rustc_trait_selection/src/solve/normalize.rs index ddaef7c159f32..419d7e704dee3 100644 --- a/compiler/rustc_trait_selection/src/solve/normalize.rs +++ b/compiler/rustc_trait_selection/src/solve/normalize.rs @@ -1,20 +1,21 @@ use std::fmt::Debug; use std::marker::PhantomData; -use crate::error_reporting::traits::OverflowCause; -use crate::error_reporting::InferCtxtErrorExt; -use crate::traits::query::evaluate_obligation::InferCtxtExt; -use crate::traits::{BoundVarReplacer, PlaceholderReplacer, ScrubbedTraitError}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_infer::infer::at::At; use rustc_infer::infer::InferCtxt; use rustc_infer::traits::{FromSolverError, Obligation, TraitEngine}; use rustc_middle::traits::ObligationCause; -use rustc_middle::ty::{self, Ty, TyCtxt, UniverseIndex}; -use rustc_middle::ty::{FallibleTypeFolder, TypeFolder, TypeSuperFoldable}; -use rustc_middle::ty::{TypeFoldable, TypeVisitableExt}; +use rustc_middle::ty::{ + self, FallibleTypeFolder, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, + TypeVisitableExt, UniverseIndex, +}; use super::{FulfillmentCtxt, NextSolverError}; +use crate::error_reporting::traits::OverflowCause; +use crate::error_reporting::InferCtxtErrorExt; +use crate::traits::query::evaluate_obligation::InferCtxtExt; +use crate::traits::{BoundVarReplacer, PlaceholderReplacer, ScrubbedTraitError}; /// Deeply normalize all aliases in `value`. This does not handle inference and expects /// its input to be already fully resolved. diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index 796f7fd5a54d1..29f78f9d5f0a1 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -1,11 +1,8 @@ //! Support code for rustdoc and external tools. //! You really don't want to be using this unless you need to. -use super::*; - -use crate::errors::UnableToConstructConstantValue; -use crate::infer::region_constraints::{Constraint, RegionConstraintData}; -use crate::traits::project::ProjectAndUnifyResult; +use std::collections::VecDeque; +use std::iter; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet, IndexEntry}; use rustc_data_structures::unord::UnordSet; @@ -13,8 +10,10 @@ use rustc_infer::infer::DefineOpaqueTypes; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::{Region, RegionVid}; -use std::collections::VecDeque; -use std::iter; +use super::*; +use crate::errors::UnableToConstructConstantValue; +use crate::infer::region_constraints::{Constraint, RegionConstraintData}; +use crate::traits::project::ProjectAndUnifyResult; // FIXME(twk): this is obviously not nice to duplicate like that #[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)] diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 7e996c5c5ef6e..2d843d8f17406 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -4,15 +4,8 @@ //! [trait-resolution]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html //! [trait-specialization]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html -use crate::infer::outlives::env::OutlivesEnvironment; -use crate::infer::InferOk; -use crate::solve::inspect::{InspectGoal, ProofTreeInferCtxtExt, ProofTreeVisitor}; -use crate::solve::{deeply_normalize_for_diagnostics, inspect}; -use crate::traits::select::IntercrateAmbiguityCause; -use crate::traits::NormalizeExt; -use crate::traits::SkipLeakCheck; -use crate::traits::{util, FulfillmentErrorCode}; -use crate::traits::{Obligation, ObligationCause, PredicateObligation, SelectionContext}; +use std::fmt::Debug; + use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{Diag, EmissionGuarantee}; use rustc_hir::def::DefKind; @@ -28,10 +21,18 @@ use rustc_middle::ty::{self, Ty, TyCtxt}; pub use rustc_next_trait_solver::coherence::*; use rustc_span::symbol::sym; use rustc_span::{Span, DUMMY_SP}; -use std::fmt::Debug; use super::ObligationCtxt; use crate::error_reporting::traits::suggest_new_overflow_limit; +use crate::infer::outlives::env::OutlivesEnvironment; +use crate::infer::InferOk; +use crate::solve::inspect::{InspectGoal, ProofTreeInferCtxtExt, ProofTreeVisitor}; +use crate::solve::{deeply_normalize_for_diagnostics, inspect}; +use crate::traits::select::IntercrateAmbiguityCause; +use crate::traits::{ + util, FulfillmentErrorCode, NormalizeExt, Obligation, ObligationCause, PredicateObligation, + SelectionContext, SkipLeakCheck, +}; pub struct OverlapResult<'tcx> { pub impl_header: ty::ImplHeader<'tcx>, diff --git a/compiler/rustc_trait_selection/src/traits/engine.rs b/compiler/rustc_trait_selection/src/traits/engine.rs index 49730b532a3c5..de1d4ef15aced 100644 --- a/compiler/rustc_trait_selection/src/traits/engine.rs +++ b/compiler/rustc_trait_selection/src/traits/engine.rs @@ -1,16 +1,6 @@ use std::cell::RefCell; use std::fmt::Debug; -use super::{FromSolverError, TraitEngine}; -use super::{FulfillmentContext, ScrubbedTraitError}; -use crate::error_reporting::InferCtxtErrorExt; -use crate::regions::InferCtxtRegionExt; -use crate::solve::FulfillmentCtxt as NextFulfillmentCtxt; -use crate::solve::NextSolverError; -use crate::traits::fulfill::OldSolverError; -use crate::traits::NormalizeExt; -use crate::traits::StructurallyNormalizeExt; -use crate::traits::{FulfillmentError, Obligation, ObligationCause, PredicateObligation}; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::ErrorGuaranteed; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -19,16 +9,22 @@ use rustc_infer::infer::canonical::{ Canonical, CanonicalQueryResponse, CanonicalVarValues, QueryResponse, }; use rustc_infer::infer::outlives::env::OutlivesEnvironment; -use rustc_infer::infer::RegionResolutionError; -use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, InferOk}; +use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, InferOk, RegionResolutionError}; use rustc_macros::extension; use rustc_middle::arena::ArenaAllocatable; use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::error::TypeError; -use rustc_middle::ty::TypeFoldable; -use rustc_middle::ty::Upcast; -use rustc_middle::ty::Variance; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, Upcast, Variance}; + +use super::{FromSolverError, FulfillmentContext, ScrubbedTraitError, TraitEngine}; +use crate::error_reporting::InferCtxtErrorExt; +use crate::regions::InferCtxtRegionExt; +use crate::solve::{FulfillmentCtxt as NextFulfillmentCtxt, NextSolverError}; +use crate::traits::fulfill::OldSolverError; +use crate::traits::{ + FulfillmentError, NormalizeExt, Obligation, ObligationCause, PredicateObligation, + StructurallyNormalizeExt, +}; #[extension(pub trait TraitEngineExt<'tcx, E>)] impl<'tcx, E> dyn TraitEngine<'tcx, E> diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index cc0bb7a60b248..a6db22ec15a37 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -1,32 +1,29 @@ -use crate::infer::{InferCtxt, TyOrConstInferVar}; -use crate::traits::normalize::normalize_with_depth_to; +use std::marker::PhantomData; + use rustc_data_structures::captures::Captures; -use rustc_data_structures::obligation_forest::ProcessResult; -use rustc_data_structures::obligation_forest::{Error, ForestObligation, Outcome}; -use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor}; +use rustc_data_structures::obligation_forest::{ + Error, ForestObligation, ObligationForest, ObligationProcessor, Outcome, ProcessResult, +}; use rustc_infer::infer::DefineOpaqueTypes; -use rustc_infer::traits::{FromSolverError, ProjectionCacheKey}; -use rustc_infer::traits::{PolyTraitObligation, SelectionError, TraitEngine}; +use rustc_infer::traits::{ + FromSolverError, PolyTraitObligation, ProjectionCacheKey, SelectionError, TraitEngine, +}; use rustc_middle::bug; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::abstract_const::NotConstEvaluatable; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, Binder, Const, TypeVisitableExt}; -use std::marker::PhantomData; +use rustc_middle::ty::{self, Binder, Const, GenericArgsRef, TypeVisitableExt}; use super::project::{self, ProjectAndUnifyResult}; use super::select::SelectionContext; -use super::wf; -use super::EvaluationResult; -use super::PredicateObligation; -use super::Unimplemented; -use super::{const_evaluatable, ScrubbedTraitError}; -use super::{FulfillmentError, FulfillmentErrorCode}; - +use super::{ + const_evaluatable, wf, EvaluationResult, FulfillmentError, FulfillmentErrorCode, + PredicateObligation, ScrubbedTraitError, Unimplemented, +}; use crate::error_reporting::InferCtxtErrorExt; -use crate::traits::project::PolyProjectionObligation; -use crate::traits::project::ProjectionCacheKeyExt as _; +use crate::infer::{InferCtxt, TyOrConstInferVar}; +use crate::traits::normalize::normalize_with_depth_to; +use crate::traits::project::{PolyProjectionObligation, ProjectionCacheKeyExt as _}; use crate::traits::query::evaluate_obligation::InferCtxtExt; impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> { diff --git a/compiler/rustc_trait_selection/src/traits/misc.rs b/compiler/rustc_trait_selection/src/traits/misc.rs index d749b68680339..9a127e752a61a 100644 --- a/compiler/rustc_trait_selection/src/traits/misc.rs +++ b/compiler/rustc_trait_selection/src/traits/misc.rs @@ -1,8 +1,5 @@ //! Miscellaneous type-system utilities that are too small to deserve their own modules. -use crate::regions::InferCtxtRegionExt; -use crate::traits::{self, FulfillmentError, ObligationCause}; - use hir::LangItem; use rustc_ast::Mutability; use rustc_data_structures::fx::FxIndexSet; @@ -12,6 +9,8 @@ use rustc_infer::infer::{RegionResolutionError, TyCtxtInferExt}; use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt, TypeVisitableExt}; use super::outlives_bounds::InferCtxtExt; +use crate::regions::InferCtxtRegionExt; +use crate::traits::{self, FulfillmentError, ObligationCause}; pub enum CopyImplementationError<'tcx> { InfringingFields(Vec<(&'tcx ty::FieldDef, Ty<'tcx>, InfringingFieldsReason<'tcx>)>), diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index c57ca01479982..a350b76a7049a 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -22,51 +22,55 @@ mod util; pub mod vtable; pub mod wf; -use crate::error_reporting::InferCtxtErrorExt; -use crate::infer::outlives::env::OutlivesEnvironment; -use crate::infer::{InferCtxt, TyCtxtInferExt}; -use crate::regions::InferCtxtRegionExt; -use crate::traits::query::evaluate_obligation::InferCtxtExt as _; +use std::fmt::Debug; +use std::ops::ControlFlow; + use rustc_errors::ErrorGuaranteed; +pub use rustc_infer::traits::*; use rustc_middle::query::Providers; use rustc_middle::span_bug; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeFolder, TypeSuperVisitable, Upcast}; -use rustc_middle::ty::{GenericArgs, GenericArgsRef}; +use rustc_middle::ty::{ + self, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFolder, TypeSuperVisitable, Upcast, +}; use rustc_span::def_id::DefId; use rustc_span::Span; -use std::fmt::Debug; -use std::ops::ControlFlow; - -pub use self::coherence::{add_placeholder_note, orphan_check_trait_ref, overlapping_impls}; -pub use self::coherence::{InCrate, IsFirstInputType, UncoveredTyParams}; -pub use self::coherence::{OrphanCheckErr, OrphanCheckMode, OverlapResult}; +pub use self::coherence::{ + add_placeholder_note, orphan_check_trait_ref, overlapping_impls, InCrate, IsFirstInputType, + OrphanCheckErr, OrphanCheckMode, OverlapResult, UncoveredTyParams, +}; pub use self::engine::{ObligationCtxt, TraitEngineExt}; pub use self::fulfill::{FulfillmentContext, OldSolverError, PendingPredicateObligation}; pub use self::normalize::NormalizeExt; -pub use self::object_safety::hir_ty_lowering_object_safety_violations; -pub use self::object_safety::is_vtable_safe_method; -pub use self::object_safety::object_safety_violations_for_assoc_item; -pub use self::object_safety::ObjectSafetyViolation; +pub use self::object_safety::{ + hir_ty_lowering_object_safety_violations, is_vtable_safe_method, + object_safety_violations_for_assoc_item, ObjectSafetyViolation, +}; pub use self::project::{normalize_inherent_projection, normalize_projection_ty}; -pub use self::select::{EvaluationCache, SelectionCache, SelectionContext}; -pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError}; -pub use self::specialize::specialization_graph::FutureCompatOverlapError; -pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind; +pub use self::select::{ + EvaluationCache, EvaluationResult, IntercrateAmbiguityCause, OverflowError, SelectionCache, + SelectionContext, +}; +pub use self::specialize::specialization_graph::{ + FutureCompatOverlapError, FutureCompatOverlapErrorKind, +}; pub use self::specialize::{ specialization_graph, translate_args, translate_args_with_cause, OverlapError, }; pub use self::structural_normalize::StructurallyNormalizeExt; -pub use self::util::elaborate; -pub use self::util::{expand_trait_aliases, TraitAliasExpander, TraitAliasExpansionInfo}; -pub use self::util::{impl_item_is_final, upcast_choices}; -pub use self::util::{supertraits, transitive_bounds, transitive_bounds_that_define_assoc_item}; -pub use self::util::{with_replaced_escaping_bound_vars, BoundVarReplacer, PlaceholderReplacer}; - -pub use rustc_infer::traits::*; +pub use self::util::{ + elaborate, expand_trait_aliases, impl_item_is_final, supertraits, + transitive_bounds_that_define_assoc_item, upcast_choices, with_replaced_escaping_bound_vars, + BoundVarReplacer, PlaceholderReplacer, TraitAliasExpander, TraitAliasExpansionInfo, +}; +use crate::error_reporting::InferCtxtErrorExt; +use crate::infer::outlives::env::OutlivesEnvironment; +use crate::infer::{InferCtxt, TyCtxtInferExt}; +use crate::regions::InferCtxtRegionExt; +use crate::traits::query::evaluate_obligation::InferCtxtExt as _; pub struct FulfillmentError<'tcx> { pub obligation: PredicateObligation<'tcx>, diff --git a/compiler/rustc_trait_selection/src/traits/normalize.rs b/compiler/rustc_trait_selection/src/traits/normalize.rs index 26cb9bb5a3db6..81f8633ba955f 100644 --- a/compiler/rustc_trait_selection/src/traits/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/normalize.rs @@ -1,20 +1,24 @@ //! Deeply normalize types using the old trait solver. -use super::SelectionContext; -use super::{project, with_replaced_escaping_bound_vars, BoundVarReplacer, PlaceholderReplacer}; -use crate::error_reporting::traits::OverflowCause; -use crate::error_reporting::InferCtxtErrorExt; -use crate::solve::NextSolverError; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_infer::infer::at::At; use rustc_infer::infer::InferOk; -use rustc_infer::traits::FromSolverError; -use rustc_infer::traits::PredicateObligation; -use rustc_infer::traits::{Normalized, Obligation, TraitEngine}; +use rustc_infer::traits::{ + FromSolverError, Normalized, Obligation, PredicateObligation, TraitEngine, +}; use rustc_macros::extension; use rustc_middle::traits::{ObligationCause, ObligationCauseCode, Reveal}; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeFolder}; -use rustc_middle::ty::{TypeFoldable, TypeSuperFoldable, TypeVisitable, TypeVisitableExt}; +use rustc_middle::ty::{ + self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, +}; + +use super::{ + project, with_replaced_escaping_bound_vars, BoundVarReplacer, PlaceholderReplacer, + SelectionContext, +}; +use crate::error_reporting::traits::OverflowCause; +use crate::error_reporting::InferCtxtErrorExt; +use crate::solve::NextSolverError; #[extension(pub trait NormalizeExt<'tcx>)] impl<'tcx> At<'_, 'tcx> { diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index 1c6993bdd3729..8e1fc0d7fe687 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -8,29 +8,27 @@ //! - not reference the erased type `Self` except for in this receiver; //! - not have generic type parameters. -use super::elaborate; +use std::iter; +use std::ops::ControlFlow; -use crate::infer::TyCtxtInferExt; -use crate::traits::query::evaluate_obligation::InferCtxtExt; -use crate::traits::{self, Obligation, ObligationCause}; use rustc_errors::FatalError; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::query::Providers; use rustc_middle::ty::{ - self, EarlyBinder, ExistentialPredicateStableCmpExt as _, Ty, TyCtxt, TypeSuperVisitable, - TypeVisitable, TypeVisitor, + self, EarlyBinder, ExistentialPredicateStableCmpExt as _, GenericArgs, Ty, TyCtxt, + TypeFoldable, TypeFolder, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, + TypeVisitableExt, TypeVisitor, Upcast, }; -use rustc_middle::ty::{GenericArg, GenericArgs}; -use rustc_middle::ty::{TypeVisitableExt, Upcast}; use rustc_span::symbol::Symbol; use rustc_span::Span; use rustc_target::abi::Abi; use smallvec::SmallVec; -use std::iter; -use std::ops::ControlFlow; - +use super::elaborate; +use crate::infer::TyCtxtInferExt; +use crate::traits::query::evaluate_obligation::InferCtxtExt; +use crate::traits::{util, Obligation, ObligationCause}; pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation}; /// Returns the object safety violations that affect HIR ty lowering. @@ -195,7 +193,13 @@ fn predicates_reference_self( .predicates .iter() .map(|&(predicate, sp)| (predicate.instantiate_supertrait(tcx, trait_ref), sp)) - .filter_map(|predicate| predicate_references_self(tcx, predicate)) + .filter_map(|(clause, sp)| { + // Super predicates cannot allow self projections, since they're + // impossible to make into existential bounds without eager resolution + // or something. + // e.g. `trait A: B`. + predicate_references_self(tcx, trait_def_id, clause, sp, AllowSelfProjections::No) + }) .collect() } @@ -204,20 +208,25 @@ fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span .in_definition_order() .filter(|item| item.kind == ty::AssocKind::Type) .flat_map(|item| tcx.explicit_item_bounds(item.def_id).iter_identity_copied()) - .filter_map(|c| predicate_references_self(tcx, c)) + .filter_map(|(clause, sp)| { + // Item bounds *can* have self projections, since they never get + // their self type erased. + predicate_references_self(tcx, trait_def_id, clause, sp, AllowSelfProjections::Yes) + }) .collect() } fn predicate_references_self<'tcx>( tcx: TyCtxt<'tcx>, - (predicate, sp): (ty::Clause<'tcx>, Span), + trait_def_id: DefId, + predicate: ty::Clause<'tcx>, + sp: Span, + allow_self_projections: AllowSelfProjections, ) -> Option { - let self_ty = tcx.types.self_param; - let has_self_ty = |arg: &GenericArg<'tcx>| arg.walk().any(|arg| arg == self_ty.into()); match predicate.kind().skip_binder() { ty::ClauseKind::Trait(ref data) => { // In the case of a trait predicate, we can skip the "self" type. - data.trait_ref.args[1..].iter().any(has_self_ty).then_some(sp) + data.trait_ref.args[1..].iter().any(|&arg| contains_illegal_self_type_reference(tcx, trait_def_id, arg, allow_self_projections)).then_some(sp) } ty::ClauseKind::Projection(ref data) => { // And similarly for projections. This should be redundant with @@ -235,9 +244,9 @@ fn predicate_references_self<'tcx>( // // This is ALT2 in issue #56288, see that for discussion of the // possible alternatives. - data.projection_term.args[1..].iter().any(has_self_ty).then_some(sp) + data.projection_term.args[1..].iter().any(|&arg| contains_illegal_self_type_reference(tcx, trait_def_id, arg, allow_self_projections)).then_some(sp) } - ty::ClauseKind::ConstArgHasType(_ct, ty) => has_self_ty(&ty.into()).then_some(sp), + ty::ClauseKind::ConstArgHasType(_ct, ty) => contains_illegal_self_type_reference(tcx, trait_def_id, ty, allow_self_projections).then_some(sp), ty::ClauseKind::WellFormed(..) | ty::ClauseKind::TypeOutlives(..) @@ -383,7 +392,12 @@ fn virtual_call_violations_for_method<'tcx>( let mut errors = Vec::new(); for (i, &input_ty) in sig.skip_binder().inputs().iter().enumerate().skip(1) { - if contains_illegal_self_type_reference(tcx, trait_def_id, sig.rebind(input_ty)) { + if contains_illegal_self_type_reference( + tcx, + trait_def_id, + sig.rebind(input_ty), + AllowSelfProjections::Yes, + ) { let span = if let Some(hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(sig, _), .. @@ -396,7 +410,12 @@ fn virtual_call_violations_for_method<'tcx>( errors.push(MethodViolationCode::ReferencesSelfInput(span)); } } - if contains_illegal_self_type_reference(tcx, trait_def_id, sig.output()) { + if contains_illegal_self_type_reference( + tcx, + trait_def_id, + sig.output(), + AllowSelfProjections::Yes, + ) { errors.push(MethodViolationCode::ReferencesSelfOutput); } if let Some(code) = contains_illegal_impl_trait_in_trait(tcx, method.def_id, sig.output()) { @@ -482,7 +501,7 @@ fn virtual_call_violations_for_method<'tcx>( return false; } - contains_illegal_self_type_reference(tcx, trait_def_id, pred) + contains_illegal_self_type_reference(tcx, trait_def_id, pred, AllowSelfProjections::Yes) }) { errors.push(MethodViolationCode::WhereClauseReferencesSelf); } @@ -711,121 +730,181 @@ fn receiver_is_dispatchable<'tcx>( infcx.predicate_must_hold_modulo_regions(&obligation) } +#[derive(Copy, Clone)] +enum AllowSelfProjections { + Yes, + No, +} + +/// This is somewhat subtle. In general, we want to forbid +/// references to `Self` in the argument and return types, +/// since the value of `Self` is erased. However, there is one +/// exception: it is ok to reference `Self` in order to access +/// an associated type of the current trait, since we retain +/// the value of those associated types in the object type +/// itself. +/// +/// ```rust,ignore (example) +/// trait SuperTrait { +/// type X; +/// } +/// +/// trait Trait : SuperTrait { +/// type Y; +/// fn foo(&self, x: Self) // bad +/// fn foo(&self) -> Self // bad +/// fn foo(&self) -> Option // bad +/// fn foo(&self) -> Self::Y // OK, desugars to next example +/// fn foo(&self) -> ::Y // OK +/// fn foo(&self) -> Self::X // OK, desugars to next example +/// fn foo(&self) -> ::X // OK +/// } +/// ``` +/// +/// However, it is not as simple as allowing `Self` in a projected +/// type, because there are illegal ways to use `Self` as well: +/// +/// ```rust,ignore (example) +/// trait Trait : SuperTrait { +/// ... +/// fn foo(&self) -> ::X; +/// } +/// ``` +/// +/// Here we will not have the type of `X` recorded in the +/// object type, and we cannot resolve `Self as SomeOtherTrait` +/// without knowing what `Self` is. fn contains_illegal_self_type_reference<'tcx, T: TypeVisitable>>( tcx: TyCtxt<'tcx>, trait_def_id: DefId, value: T, + allow_self_projections: AllowSelfProjections, ) -> bool { - // This is somewhat subtle. In general, we want to forbid - // references to `Self` in the argument and return types, - // since the value of `Self` is erased. However, there is one - // exception: it is ok to reference `Self` in order to access - // an associated type of the current trait, since we retain - // the value of those associated types in the object type - // itself. - // - // ```rust - // trait SuperTrait { - // type X; - // } - // - // trait Trait : SuperTrait { - // type Y; - // fn foo(&self, x: Self) // bad - // fn foo(&self) -> Self // bad - // fn foo(&self) -> Option // bad - // fn foo(&self) -> Self::Y // OK, desugars to next example - // fn foo(&self) -> ::Y // OK - // fn foo(&self) -> Self::X // OK, desugars to next example - // fn foo(&self) -> ::X // OK - // } - // ``` - // - // However, it is not as simple as allowing `Self` in a projected - // type, because there are illegal ways to use `Self` as well: - // - // ```rust - // trait Trait : SuperTrait { - // ... - // fn foo(&self) -> ::X; - // } - // ``` - // - // Here we will not have the type of `X` recorded in the - // object type, and we cannot resolve `Self as SomeOtherTrait` - // without knowing what `Self` is. - - struct IllegalSelfTypeVisitor<'tcx> { - tcx: TyCtxt<'tcx>, - trait_def_id: DefId, - supertraits: Option>, - } + value + .visit_with(&mut IllegalSelfTypeVisitor { + tcx, + trait_def_id, + supertraits: None, + allow_self_projections, + }) + .is_break() +} + +struct IllegalSelfTypeVisitor<'tcx> { + tcx: TyCtxt<'tcx>, + trait_def_id: DefId, + supertraits: Option>>, + allow_self_projections: AllowSelfProjections, +} - impl<'tcx> TypeVisitor> for IllegalSelfTypeVisitor<'tcx> { - type Result = ControlFlow<()>; +impl<'tcx> TypeVisitor> for IllegalSelfTypeVisitor<'tcx> { + type Result = ControlFlow<()>; - fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result { - match t.kind() { - ty::Param(_) => { - if t == self.tcx.types.self_param { - ControlFlow::Break(()) - } else { - ControlFlow::Continue(()) - } - } - ty::Alias(ty::Projection, ref data) - if self.tcx.is_impl_trait_in_trait(data.def_id) => - { - // We'll deny these later in their own pass + fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result { + match t.kind() { + ty::Param(_) => { + if t == self.tcx.types.self_param { + ControlFlow::Break(()) + } else { ControlFlow::Continue(()) } - ty::Alias(ty::Projection, ref data) => { - // This is a projected type `::X`. - - // Compute supertraits of current trait lazily. - if self.supertraits.is_none() { - let trait_ref = - ty::Binder::dummy(ty::TraitRef::identity(self.tcx, self.trait_def_id)); - self.supertraits = Some( - traits::supertraits(self.tcx, trait_ref).map(|t| t.def_id()).collect(), - ); - } + } + ty::Alias(ty::Projection, ref data) if self.tcx.is_impl_trait_in_trait(data.def_id) => { + // We'll deny these later in their own pass + ControlFlow::Continue(()) + } + ty::Alias(ty::Projection, ref data) => { + match self.allow_self_projections { + AllowSelfProjections::Yes => { + // This is a projected type `::X`. + + // Compute supertraits of current trait lazily. + if self.supertraits.is_none() { + self.supertraits = Some( + util::supertraits( + self.tcx, + ty::Binder::dummy(ty::TraitRef::identity( + self.tcx, + self.trait_def_id, + )), + ) + .map(|trait_ref| { + self.tcx.erase_regions( + self.tcx.instantiate_bound_regions_with_erased(trait_ref), + ) + }) + .collect(), + ); + } - // Determine whether the trait reference `Foo as - // SomeTrait` is in fact a supertrait of the - // current trait. In that case, this type is - // legal, because the type `X` will be specified - // in the object type. Note that we can just use - // direct equality here because all of these types - // are part of the formal parameter listing, and - // hence there should be no inference variables. - let is_supertrait_of_current_trait = self - .supertraits - .as_ref() - .unwrap() - .contains(&data.trait_ref(self.tcx).def_id); - - // only walk contained types if it's not a super trait - if is_supertrait_of_current_trait { - ControlFlow::Continue(()) - } else { - t.super_visit_with(self) // POSSIBLY reporting an error + // Determine whether the trait reference `Foo as + // SomeTrait` is in fact a supertrait of the + // current trait. In that case, this type is + // legal, because the type `X` will be specified + // in the object type. Note that we can just use + // direct equality here because all of these types + // are part of the formal parameter listing, and + // hence there should be no inference variables. + let is_supertrait_of_current_trait = + self.supertraits.as_ref().unwrap().contains( + &data.trait_ref(self.tcx).fold_with( + &mut EraseEscapingBoundRegions { + tcx: self.tcx, + binder: ty::INNERMOST, + }, + ), + ); + + // only walk contained types if it's not a super trait + if is_supertrait_of_current_trait { + ControlFlow::Continue(()) + } else { + t.super_visit_with(self) // POSSIBLY reporting an error + } } + AllowSelfProjections::No => t.super_visit_with(self), } - _ => t.super_visit_with(self), // walk contained types, if any } + _ => t.super_visit_with(self), } + } - fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result { - // Constants can only influence object safety if they are generic and reference `Self`. - // This is only possible for unevaluated constants, so we walk these here. - self.tcx.expand_abstract_consts(ct).super_visit_with(self) - } + fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result { + // Constants can only influence object safety if they are generic and reference `Self`. + // This is only possible for unevaluated constants, so we walk these here. + self.tcx.expand_abstract_consts(ct).super_visit_with(self) } +} - value - .visit_with(&mut IllegalSelfTypeVisitor { tcx, trait_def_id, supertraits: None }) - .is_break() +struct EraseEscapingBoundRegions<'tcx> { + tcx: TyCtxt<'tcx>, + binder: ty::DebruijnIndex, +} + +impl<'tcx> TypeFolder> for EraseEscapingBoundRegions<'tcx> { + fn cx(&self) -> TyCtxt<'tcx> { + self.tcx + } + + fn fold_binder(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T> + where + T: TypeFoldable>, + { + self.binder.shift_in(1); + let result = t.super_fold_with(self); + self.binder.shift_out(1); + result + } + + fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { + if let ty::ReBound(debruijn, _) = *r + && debruijn < self.binder + { + r + } else { + self.tcx.lifetimes.re_erased + } + } } pub fn contains_illegal_impl_trait_in_trait<'tcx>( diff --git a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs index 1dc2ebfaa7a30..0fe7505990406 100644 --- a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs @@ -1,15 +1,15 @@ -use crate::infer::InferCtxt; -use crate::traits::{ObligationCause, ObligationCtxt}; use rustc_data_structures::fx::FxIndexSet; use rustc_infer::infer::resolve::OpportunisticRegionResolver; use rustc_infer::infer::InferOk; use rustc_macros::extension; use rustc_middle::infer::canonical::{OriginalQueryValues, QueryRegionConstraints}; use rustc_middle::span_bug; +pub use rustc_middle::traits::query::OutlivesBound; use rustc_middle::ty::{self, ParamEnv, Ty, TypeFolder, TypeVisitableExt}; use rustc_span::def_id::LocalDefId; -pub use rustc_middle::traits::query::OutlivesBound; +use crate::infer::InferCtxt; +use crate::traits::{ObligationCause, ObligationCtxt}; pub type BoundsCompat<'a, 'tcx: 'a> = impl Iterator> + 'a; pub type Bounds<'a, 'tcx: 'a> = impl Iterator> + 'a; diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 1d7a05150444f..4b62a5c59b2f0 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -2,29 +2,6 @@ use std::ops::ControlFlow; -use super::specialization_graph; -use super::translate_args; -use super::util; -use super::MismatchedProjectionTypes; -use super::Obligation; -use super::ObligationCause; -use super::PredicateObligation; -use super::Selection; -use super::SelectionContext; -use super::SelectionError; -use super::{Normalized, NormalizedTerm, ProjectionCacheEntry, ProjectionCacheKey}; -use rustc_infer::traits::ObligationCauseCode; -use rustc_middle::traits::BuiltinImplSource; -use rustc_middle::traits::ImplSource; -use rustc_middle::traits::ImplSourceUserDefinedData; -use rustc_middle::{bug, span_bug}; - -use crate::errors::InherentProjectionNormalizationOverflow; -use crate::infer::{BoundRegionConversionTime, InferOk}; -use crate::traits::normalize::normalize_with_depth; -use crate::traits::normalize::normalize_with_depth_to; -use crate::traits::query::evaluate_obligation::InferCtxtExt as _; -use crate::traits::select::ProjectionMatchesProjection; use rustc_data_structures::sso::SsoHashSet; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::ErrorGuaranteed; @@ -32,13 +9,26 @@ use rustc_hir::def::DefKind; use rustc_hir::lang_items::LangItem; use rustc_infer::infer::resolve::OpportunisticRegionResolver; use rustc_infer::infer::DefineOpaqueTypes; +use rustc_infer::traits::ObligationCauseCode; use rustc_middle::traits::select::OverflowError; +pub use rustc_middle::traits::Reveal; +use rustc_middle::traits::{BuiltinImplSource, ImplSource, ImplSourceUserDefinedData}; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::visit::{MaxUniverse, TypeVisitable, TypeVisitableExt}; use rustc_middle::ty::{self, Term, Ty, TyCtxt, Upcast}; +use rustc_middle::{bug, span_bug}; use rustc_span::symbol::sym; -pub use rustc_middle::traits::Reveal; +use super::{ + specialization_graph, translate_args, util, MismatchedProjectionTypes, Normalized, + NormalizedTerm, Obligation, ObligationCause, PredicateObligation, ProjectionCacheEntry, + ProjectionCacheKey, Selection, SelectionContext, SelectionError, +}; +use crate::errors::InherentProjectionNormalizationOverflow; +use crate::infer::{BoundRegionConversionTime, InferOk}; +use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to}; +use crate::traits::query::evaluate_obligation::InferCtxtExt as _; +use crate::traits::select::ProjectionMatchesProjection; pub type PolyProjectionObligation<'tcx> = Obligation<'tcx, ty::PolyProjectionPredicate<'tcx>>; @@ -1202,6 +1192,12 @@ fn assemble_candidates_from_impls<'cx, 'tcx>( false } } + } else if tcx.trait_is_auto(trait_ref.def_id) { + tcx.dcx().span_delayed_bug( + tcx.def_span(obligation.predicate.def_id), + "associated types not allowed on auto traits", + ); + false } else { bug!("unexpected builtin trait with associated type: {trait_ref:?}") } diff --git a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs index 7dc051e6fe959..d3a1ed52d2e62 100644 --- a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs @@ -1,12 +1,12 @@ -use crate::traits::query::normalize::QueryNormalizeExt; -use crate::traits::query::NoSolution; -use crate::traits::{Normalized, ObligationCause, ObligationCtxt}; - use rustc_data_structures::fx::FxHashSet; use rustc_middle::traits::query::{DropckConstraint, DropckOutlivesResult}; use rustc_middle::ty::{self, EarlyBinder, ParamEnvAnd, Ty, TyCtxt}; use rustc_span::{Span, DUMMY_SP}; +use crate::traits::query::normalize::QueryNormalizeExt; +use crate::traits::query::NoSolution; +use crate::traits::{Normalized, ObligationCause, ObligationCtxt}; + /// This returns true if the type `ty` is "trivial" for /// dropck-outlives -- that is, if it doesn't require any types to /// outlive. This is similar but not *quite* the same as the @@ -42,8 +42,15 @@ pub fn trivial_dropck_outlives<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { | ty::Foreign(..) | ty::Error(_) => true, - // `T is PAT`, `[T; N]`, and `[T]` have same properties as T. - ty::Pat(ty, _) | ty::Array(ty, _) | ty::Slice(ty) => trivial_dropck_outlives(tcx, *ty), + // `T is PAT` and `[T]` have same properties as T. + ty::Pat(ty, _) | ty::Slice(ty) => trivial_dropck_outlives(tcx, *ty), + ty::Array(ty, size) => { + // Empty array never has a dtor. See issue #110288. + match size.try_to_target_usize(tcx) { + Some(0) => true, + _ => trivial_dropck_outlives(tcx, *ty), + } + } // (T1..Tn) and closures have same properties as T1..Tn -- // check if *all* of them are trivial. diff --git a/compiler/rustc_trait_selection/src/traits/query/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/normalize.rs index 75f1af7fcf5c4..247b6e4823c4b 100644 --- a/compiler/rustc_trait_selection/src/traits/query/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/normalize.rs @@ -2,26 +2,26 @@ //! which folds deeply, invoking the underlying //! `normalize_canonicalized_projection_ty` query when it encounters projections. -use crate::error_reporting::traits::OverflowCause; -use crate::error_reporting::InferCtxtErrorExt; -use crate::infer::at::At; -use crate::infer::canonical::OriginalQueryValues; -use crate::infer::{InferCtxt, InferOk}; -use crate::traits::normalize::needs_normalization; -use crate::traits::Normalized; -use crate::traits::{BoundVarReplacer, PlaceholderReplacer, ScrubbedTraitError}; -use crate::traits::{ObligationCause, PredicateObligation, Reveal}; use rustc_data_structures::sso::SsoHashMap; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_macros::extension; +pub use rustc_middle::traits::query::NormalizationResult; use rustc_middle::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeSuperFoldable}; use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitor}; use rustc_span::DUMMY_SP; use super::NoSolution; - -pub use rustc_middle::traits::query::NormalizationResult; +use crate::error_reporting::traits::OverflowCause; +use crate::error_reporting::InferCtxtErrorExt; +use crate::infer::at::At; +use crate::infer::canonical::OriginalQueryValues; +use crate::infer::{InferCtxt, InferOk}; +use crate::traits::normalize::needs_normalization; +use crate::traits::{ + BoundVarReplacer, Normalized, ObligationCause, PlaceholderReplacer, PredicateObligation, + Reveal, ScrubbedTraitError, +}; #[extension(pub trait QueryNormalizeExt<'tcx>)] impl<'cx, 'tcx> At<'cx, 'tcx> { diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs index aca16950223c5..5e4de43d04fc8 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs @@ -1,14 +1,14 @@ -use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; -use crate::traits::ObligationCtxt; use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; use rustc_infer::traits::Obligation; +pub use rustc_middle::traits::query::type_op::AscribeUserType; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, UserArgs, UserSelfTy, UserType}; - -pub use rustc_middle::traits::query::type_op::AscribeUserType; use rustc_span::{Span, DUMMY_SP}; +use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; +use crate::traits::ObligationCtxt; + impl<'tcx> super::QueryTypeOp<'tcx> for AscribeUserType<'tcx> { type QueryResponse = (); diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs index d533e69a4fa7f..34e678e93d1e7 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs @@ -1,14 +1,15 @@ -use crate::infer::canonical::query_response; -use crate::infer::InferCtxt; -use crate::traits::query::type_op::TypeOpOutput; -use crate::traits::ObligationCtxt; +use std::fmt; + use rustc_errors::ErrorGuaranteed; use rustc_infer::infer::region_constraints::RegionConstraintData; use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::{TyCtxt, TypeFoldable}; use rustc_span::Span; -use std::fmt; +use crate::infer::canonical::query_response; +use crate::infer::InferCtxt; +use crate::traits::query::type_op::TypeOpOutput; +use crate::traits::ObligationCtxt; pub struct CustomTypeOp { closure: F, diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/eq.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/eq.rs index 57e649f3e43d0..656130cda19eb 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/eq.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/eq.rs @@ -1,10 +1,10 @@ -use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; -use crate::traits::ObligationCtxt; +pub use rustc_middle::traits::query::type_op::Eq; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; -pub use rustc_middle::traits::query::type_op::Eq; +use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; +use crate::traits::ObligationCtxt; impl<'tcx> super::QueryTypeOp<'tcx> for Eq<'tcx> { type QueryResponse = (); diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs index 8525215a3bc61..b5b209c1af79e 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs @@ -1,7 +1,3 @@ -use crate::traits::query::NoSolution; -use crate::traits::wf; -use crate::traits::ObligationCtxt; - use rustc_infer::infer::canonical::Canonical; use rustc_infer::infer::resolve::OpportunisticRegionResolver; use rustc_infer::traits::query::OutlivesBound; @@ -14,6 +10,9 @@ use rustc_span::DUMMY_SP; use rustc_type_ir::outlives::{push_outlives_components, Component}; use smallvec::{smallvec, SmallVec}; +use crate::traits::query::NoSolution; +use crate::traits::{wf, ObligationCtxt}; + #[derive(Copy, Clone, Debug, HashStable, TypeFoldable, TypeVisitable)] pub struct ImpliedOutlivesBounds<'tcx> { pub ty: Ty<'tcx>, diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs index c1b1bfd300ba5..2f64ed963f967 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs @@ -1,8 +1,5 @@ -use crate::infer::canonical::{ - Canonical, CanonicalQueryResponse, OriginalQueryValues, QueryRegionConstraints, -}; -use crate::infer::{InferCtxt, InferOk}; -use crate::traits::{ObligationCause, ObligationCtxt}; +use std::fmt; + use rustc_errors::ErrorGuaranteed; use rustc_infer::infer::canonical::Certainty; use rustc_infer::traits::PredicateObligation; @@ -10,7 +7,12 @@ use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_span::Span; -use std::fmt; + +use crate::infer::canonical::{ + Canonical, CanonicalQueryResponse, OriginalQueryValues, QueryRegionConstraints, +}; +use crate::infer::{InferCtxt, InferOk}; +use crate::traits::{ObligationCause, ObligationCtxt}; pub mod ascribe_user_type; pub mod custom; diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs index e9948bf1f7158..41c34f6da2955 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs @@ -1,12 +1,13 @@ -use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; -use crate::traits::ObligationCtxt; +use std::fmt; + +pub use rustc_middle::traits::query::type_op::Normalize; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{self, Lift, ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt}; -use std::fmt; -pub use rustc_middle::traits::query::type_op::Normalize; +use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; +use crate::traits::ObligationCtxt; impl<'tcx, T> super::QueryTypeOp<'tcx> for Normalize where diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs index 3e7aa52dcfeac..49d324fa62ecd 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs @@ -1,11 +1,12 @@ +use rustc_macros::{HashStable, TypeFoldable, TypeVisitable}; +use rustc_middle::traits::query::{DropckOutlivesResult, NoSolution}; +use rustc_middle::ty::{ParamEnvAnd, Ty, TyCtxt}; + use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; use crate::traits::query::dropck_outlives::{ compute_dropck_outlives_inner, trivial_dropck_outlives, }; use crate::traits::ObligationCtxt; -use rustc_macros::{HashStable, TypeFoldable, TypeVisitable}; -use rustc_middle::traits::query::{DropckOutlivesResult, NoSolution}; -use rustc_middle::ty::{ParamEnvAnd, Ty, TyCtxt}; #[derive(Copy, Clone, Debug, HashStable, TypeFoldable, TypeVisitable)] pub struct DropckOutlives<'tcx> { 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 63289746f5e5d..294c6bfc1243d 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 @@ -1,11 +1,11 @@ -use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; -use crate::traits::ObligationCtxt; use rustc_infer::traits::Obligation; +pub use rustc_middle::traits::query::type_op::ProvePredicate; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::{self, ParamEnvAnd, TyCtxt}; -pub use rustc_middle::traits::query::type_op::ProvePredicate; +use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; +use crate::traits::ObligationCtxt; impl<'tcx> super::QueryTypeOp<'tcx> for ProvePredicate<'tcx> { type QueryResponse = (); diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/subtype.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/subtype.rs index ae11b0825bd0e..892c2a1f11309 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/subtype.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/subtype.rs @@ -1,10 +1,10 @@ -use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; -use crate::traits::ObligationCtxt; +pub use rustc_middle::traits::query::type_op::Subtype; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; -pub use rustc_middle::traits::query::type_op::Subtype; +use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; +use crate::traits::ObligationCtxt; impl<'tcx> super::QueryTypeOp<'tcx> for Subtype<'tcx> { type QueryResponse = (); diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 4c3d833b0f90f..2085d3da44341 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -12,20 +12,17 @@ use hir::def_id::DefId; use hir::LangItem; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_hir as hir; -use rustc_infer::traits::ObligationCause; -use rustc_infer::traits::{Obligation, PolyTraitObligation, SelectionError}; +use rustc_infer::traits::{Obligation, ObligationCause, PolyTraitObligation, SelectionError}; use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams}; use rustc_middle::ty::{self, ToPolyTraitRef, Ty, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; +use super::SelectionCandidate::*; +use super::{BuiltinImplConditions, SelectionCandidateSet, SelectionContext, TraitObligationStack}; use crate::traits; use crate::traits::query::evaluate_obligation::InferCtxtExt; use crate::traits::util; -use super::BuiltinImplConditions; -use super::SelectionCandidate::*; -use super::{SelectionCandidateSet, SelectionContext, TraitObligationStack}; - impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { #[instrument(skip(self, stack), level = "debug")] pub(super) fn assemble_candidates<'o>( @@ -772,7 +769,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ); } - ty::Alias(ty::Opaque, _) => { + ty::Alias(ty::Opaque, alias) => { if candidates.vec.iter().any(|c| matches!(c, ProjectionCandidate(_))) { // We do not generate an auto impl candidate for `impl Trait`s which already // reference our auto trait. @@ -787,6 +784,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // We do not emit auto trait candidates for opaque types in coherence. // Doing so can result in weird dependency cycles. candidates.ambiguous = true; + } else if self.infcx.can_define_opaque_ty(alias.def_id) { + // We do not emit auto trait candidates for opaque types in their defining scope, as + // we need to know the hidden type first, which we can't reliably know within the defining + // scope. + candidates.ambiguous = true; } else { candidates.vec.push(AutoImplCandidate) } diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 9508a3e8e1509..ddd8b970cc813 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -7,11 +7,13 @@ //! [rustc dev guide]: //! https://rustc-dev-guide.rust-lang.org/traits/resolution.html#confirmation +use std::iter; +use std::ops::ControlFlow; + use rustc_ast::Mutability; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir::lang_items::LangItem; -use rustc_infer::infer::HigherRankedType; -use rustc_infer::infer::{DefineOpaqueTypes, InferOk}; +use rustc_infer::infer::{DefineOpaqueTypes, HigherRankedType, InferOk}; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::traits::{BuiltinImplSource, SignatureMismatchData}; use rustc_middle::ty::{ @@ -21,6 +23,8 @@ use rustc_middle::ty::{ use rustc_middle::{bug, span_bug}; use rustc_span::def_id::DefId; +use super::SelectionCandidate::{self, *}; +use super::{BuiltinImplConditions, SelectionContext}; use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to}; use crate::traits::util::{self, closure_trait_ref_and_return_type}; use crate::traits::{ @@ -29,13 +33,6 @@ use crate::traits::{ SignatureMismatch, TraitNotObjectSafe, TraitObligation, Unimplemented, }; -use super::BuiltinImplConditions; -use super::SelectionCandidate::{self, *}; -use super::SelectionContext; - -use std::iter; -use std::ops::ControlFlow; - impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { #[instrument(level = "debug", skip(self))] pub(super) fn confirm_candidate( diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 02ad361f9f59f..1d9a90f0300ab 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2,31 +2,12 @@ //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection -use self::EvaluationResult::*; -use self::SelectionCandidate::*; - -use super::coherence::{self, Conflict}; -use super::const_evaluatable; -use super::project; -use super::project::ProjectionTermObligation; -use super::util; -use super::util::closure_trait_ref_and_return_type; -use super::wf; -use super::{ - ImplDerivedCause, Normalized, Obligation, ObligationCause, ObligationCauseCode, Overflow, - PolyTraitObligation, PredicateObligation, Selection, SelectionError, SelectionResult, - TraitQueryMode, -}; +use std::cell::{Cell, RefCell}; +use std::fmt::{self, Display}; +use std::ops::ControlFlow; +use std::{cmp, iter}; -use crate::error_reporting::InferCtxtErrorExt; -use crate::infer::{InferCtxt, InferCtxtExt, InferOk, TypeFreshener}; -use crate::solve::InferCtxtSelectExt as _; -use crate::traits::normalize::normalize_with_depth; -use crate::traits::normalize::normalize_with_depth_to; -use crate::traits::project::ProjectAndUnifyResult; -use crate::traits::project::ProjectionCacheKeyExt; -use crate::traits::ProjectionCacheKey; -use crate::traits::Unimplemented; +use hir::def::DefKind; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::{Diag, EmissionGuarantee}; @@ -34,31 +15,40 @@ use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::LangItem; use rustc_infer::infer::relate::TypeRelation; -use rustc_infer::infer::BoundRegionConversionTime; -use rustc_infer::infer::BoundRegionConversionTime::HigherRankedType; +use rustc_infer::infer::BoundRegionConversionTime::{self, HigherRankedType}; use rustc_infer::infer::DefineOpaqueTypes; +use rustc_infer::traits::util::elaborate; use rustc_infer::traits::TraitObligation; use rustc_middle::bug; -use rustc_middle::dep_graph::dep_kinds; -use rustc_middle::dep_graph::DepNodeIndex; +use rustc_middle::dep_graph::{dep_kinds, DepNodeIndex}; use rustc_middle::mir::interpret::ErrorHandled; +pub use rustc_middle::traits::select::*; use rustc_middle::ty::abstract_const::NotConstEvaluatable; use rustc_middle::ty::error::TypeErrorToStringExt; -use rustc_middle::ty::print::PrintTraitRefExt as _; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, PolyProjectionPredicate, Upcast}; -use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; +use rustc_middle::ty::print::{with_no_trimmed_paths, PrintTraitRefExt as _}; +use rustc_middle::ty::{ + self, GenericArgsRef, PolyProjectionPredicate, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, + Upcast, +}; use rustc_span::symbol::sym; use rustc_span::Symbol; -use std::cell::{Cell, RefCell}; -use std::cmp; -use std::fmt::{self, Display}; -use std::iter; -use std::ops::ControlFlow; - -pub use rustc_middle::traits::select::*; -use rustc_middle::ty::print::with_no_trimmed_paths; +use self::EvaluationResult::*; +use self::SelectionCandidate::*; +use super::coherence::{self, Conflict}; +use super::project::ProjectionTermObligation; +use super::util::closure_trait_ref_and_return_type; +use super::{ + const_evaluatable, project, util, wf, ImplDerivedCause, Normalized, Obligation, + ObligationCause, ObligationCauseCode, Overflow, PolyTraitObligation, PredicateObligation, + Selection, SelectionError, SelectionResult, TraitQueryMode, +}; +use crate::error_reporting::InferCtxtErrorExt; +use crate::infer::{InferCtxt, InferCtxtExt, InferOk, TypeFreshener}; +use crate::solve::InferCtxtSelectExt as _; +use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to}; +use crate::traits::project::{ProjectAndUnifyResult, ProjectionCacheKeyExt}; +use crate::traits::{ProjectionCacheKey, Unimplemented}; mod _match; mod candidate_assembly; @@ -2262,8 +2252,21 @@ impl<'tcx> SelectionContext<'_, 'tcx> { } } - // FIXME(async_closures): These are never clone, for now. - ty::CoroutineClosure(_, _) => None, + ty::CoroutineClosure(_, args) => { + // (*) binder moved here + let ty = self.infcx.shallow_resolve(args.as_coroutine_closure().tupled_upvars_ty()); + if let ty::Infer(ty::TyVar(_)) = ty.kind() { + // Not yet resolved. + Ambiguous + } else { + Where( + obligation + .predicate + .rebind(args.as_coroutine_closure().upvar_tys().to_vec()), + ) + } + } + // `Copy` and `Clone` are automatically implemented for an anonymous adt // if all of its fields are `Copy` and `Clone` ty::Adt(adt, args) if adt.is_anonymous() => { @@ -2386,13 +2389,17 @@ impl<'tcx> SelectionContext<'_, 'tcx> { } ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { - // We can resolve the `impl Trait` to its concrete type, - // which enforces a DAG between the functions requiring - // the auto trait bounds in question. - match self.tcx().type_of_opaque(def_id) { - Ok(ty) => t.rebind(vec![ty.instantiate(self.tcx(), args)]), - Err(_) => { - return Err(SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id)); + if self.infcx.can_define_opaque_ty(def_id) { + unreachable!() + } else { + // We can resolve the `impl Trait` to its concrete type, + // which enforces a DAG between the functions requiring + // the auto trait bounds in question. + match self.tcx().type_of_opaque(def_id) { + Ok(ty) => t.rebind(vec![ty.instantiate(self.tcx(), args)]), + Err(_) => { + return Err(SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id)); + } } } } @@ -2793,6 +2800,35 @@ impl<'tcx> SelectionContext<'_, 'tcx> { }); } + // Register any outlives obligations from the trait here, cc #124336. + if matches!(self.tcx().def_kind(def_id), DefKind::Impl { of_trait: true }) + && let Some(header) = self.tcx().impl_trait_header(def_id) + { + let trait_clause: ty::Clause<'tcx> = + header.trait_ref.instantiate(self.tcx(), args).upcast(self.tcx()); + for clause in elaborate(self.tcx(), [trait_clause]) { + if matches!( + clause.kind().skip_binder(), + ty::ClauseKind::TypeOutlives(..) | ty::ClauseKind::RegionOutlives(..) + ) { + let clause = normalize_with_depth_to( + self, + param_env, + cause.clone(), + recursion_depth, + clause, + &mut obligations, + ); + obligations.push(Obligation { + cause: cause.clone(), + recursion_depth, + param_env, + predicate: clause.as_predicate(), + }); + } + } + } + obligations } } diff --git a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs index 3c33d13567d78..4c8c5a2eb17fe 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs @@ -10,28 +10,25 @@ //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html pub mod specialization_graph; +use rustc_data_structures::fx::FxIndexSet; +use rustc_errors::codes::*; +use rustc_errors::{Diag, EmissionGuarantee}; +use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_infer::infer::DefineOpaqueTypes; +use rustc_middle::bug; +use rustc_middle::query::LocalCrate; use rustc_middle::ty::print::PrintTraitRefExt as _; +use rustc_middle::ty::{self, GenericArgsRef, ImplSubject, Ty, TyCtxt, TypeVisitableExt}; +use rustc_session::lint::builtin::{COHERENCE_LEAK_CHECK, ORDER_DEPENDENT_TRAIT_OBJECTS}; +use rustc_span::{sym, ErrorGuaranteed, Span, DUMMY_SP}; use specialization_graph::GraphExt; +use super::{util, SelectionContext}; use crate::error_reporting::traits::to_pretty_impl_header; use crate::errors::NegativePositiveConflict; use crate::infer::{InferCtxt, InferOk, TyCtxtInferExt}; use crate::traits::select::IntercrateAmbiguityCause; use crate::traits::{coherence, FutureCompatOverlapErrorKind, ObligationCause, ObligationCtxt}; -use rustc_data_structures::fx::FxIndexSet; -use rustc_errors::{codes::*, Diag, EmissionGuarantee}; -use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_middle::bug; -use rustc_middle::query::LocalCrate; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, ImplSubject, Ty, TyCtxt, TypeVisitableExt}; -use rustc_session::lint::builtin::COHERENCE_LEAK_CHECK; -use rustc_session::lint::builtin::ORDER_DEPENDENT_TRAIT_OBJECTS; -use rustc_span::{sym, ErrorGuaranteed, Span, DUMMY_SP}; - -use super::util; -use super::SelectionContext; /// Information pertinent to an overlapping impl error. #[derive(Debug)] diff --git a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs index 90f2c7ad213b9..732f1b0a3d7cc 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs @@ -1,14 +1,13 @@ -use super::OverlapError; - -use crate::traits; use rustc_errors::ErrorGuaranteed; use rustc_hir::def_id::DefId; use rustc_macros::extension; use rustc_middle::bug; +pub use rustc_middle::traits::specialization_graph::*; use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams}; use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; -pub use rustc_middle::traits::specialization_graph::*; +use super::OverlapError; +use crate::traits; #[derive(Copy, Clone, Debug)] pub enum FutureCompatOverlapErrorKind { diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index 951af4b0920cb..52f87699b164f 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -1,19 +1,19 @@ use std::collections::BTreeMap; -use super::NormalizeExt; -use super::{ObligationCause, PredicateObligation, SelectionContext}; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::Diag; use rustc_hir::def_id::DefId; use rustc_infer::infer::{InferCtxt, InferOk}; +pub use rustc_infer::traits::util::*; use rustc_middle::bug; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, ImplSubject, Ty, TyCtxt, TypeVisitableExt, Upcast}; -use rustc_middle::ty::{TypeFoldable, TypeFolder, TypeSuperFoldable}; +use rustc_middle::ty::{ + self, GenericArgsRef, ImplSubject, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, + TypeVisitableExt, Upcast, +}; use rustc_span::Span; use smallvec::{smallvec, SmallVec}; -pub use rustc_infer::traits::util::*; +use super::{NormalizeExt, ObligationCause, PredicateObligation, SelectionContext}; /////////////////////////////////////////////////////////////////////////// // `TraitAliasExpander` iterator diff --git a/compiler/rustc_trait_selection/src/traits/vtable.rs b/compiler/rustc_trait_selection/src/traits/vtable.rs index 4645d8284612e..1729d8d307a51 100644 --- a/compiler/rustc_trait_selection/src/traits/vtable.rs +++ b/compiler/rustc_trait_selection/src/traits/vtable.rs @@ -1,16 +1,18 @@ -use crate::errors::DumpVTableEntries; -use crate::traits::{impossible_predicates, is_vtable_safe_method}; +use std::fmt::Debug; +use std::ops::ControlFlow; + use rustc_hir::def_id::DefId; use rustc_infer::traits::util::PredicateSet; use rustc_middle::bug; use rustc_middle::query::Providers; -use rustc_middle::ty::{self, GenericParamDefKind, Ty, TyCtxt, Upcast, VtblEntry}; -use rustc_middle::ty::{GenericArgs, TypeVisitableExt}; +use rustc_middle::ty::{ + self, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeVisitableExt, Upcast, VtblEntry, +}; use rustc_span::{sym, Span, DUMMY_SP}; use smallvec::{smallvec, SmallVec}; -use std::fmt::Debug; -use std::ops::ControlFlow; +use crate::errors::DumpVTableEntries; +use crate::traits::{impossible_predicates, is_vtable_safe_method}; #[derive(Clone, Debug)] pub enum VtblSegment<'tcx> { diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index e77a05dd8e63c..7e5fe7e3c942b 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -1,17 +1,18 @@ -use crate::infer::InferCtxt; -use crate::traits; +use std::iter; + use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::bug; use rustc_middle::ty::{ - self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, + self, GenericArg, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeSuperVisitable, + TypeVisitable, TypeVisitableExt, TypeVisitor, }; -use rustc_middle::ty::{GenericArg, GenericArgKind, GenericArgsRef}; use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_span::{Span, DUMMY_SP}; -use std::iter; +use crate::infer::InferCtxt; +use crate::traits; /// Returns the set of obligations needed to make `arg` well-formed. /// If `arg` contains unresolved inference variables, this may include /// further WF obligations. However, if `arg` IS an unresolved diff --git a/compiler/rustc_traits/src/dropck_outlives.rs b/compiler/rustc_traits/src/dropck_outlives.rs index 55abd6098ec97..add7ec50a1e64 100644 --- a/compiler/rustc_traits/src/dropck_outlives.rs +++ b/compiler/rustc_traits/src/dropck_outlives.rs @@ -5,8 +5,7 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::bug; use rustc_middle::query::Providers; use rustc_middle::traits::query::{DropckConstraint, DropckOutlivesResult}; -use rustc_middle::ty::GenericArgs; -use rustc_middle::ty::TyCtxt; +use rustc_middle::ty::{GenericArgs, TyCtxt}; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::traits::query::dropck_outlives::{ compute_dropck_outlives_inner, dtorck_constraint_for_ty_inner, diff --git a/compiler/rustc_traits/src/lib.rs b/compiler/rustc_traits/src/lib.rs index fdeda34d29462..697c839180312 100644 --- a/compiler/rustc_traits/src/lib.rs +++ b/compiler/rustc_traits/src/lib.rs @@ -12,11 +12,10 @@ mod normalize_erasing_regions; mod normalize_projection_ty; mod type_op; +use rustc_middle::query::Providers; pub use rustc_trait_selection::traits::query::type_op::ascribe_user_type::type_op_ascribe_user_type_with_span; pub use type_op::type_op_prove_predicate_with_cause; -use rustc_middle::query::Providers; - pub fn provide(p: &mut Providers) { dropck_outlives::provide(p); evaluate_obligation::provide(p); diff --git a/compiler/rustc_traits/src/normalize_projection_ty.rs b/compiler/rustc_traits/src/normalize_projection_ty.rs index 06cd6389efc00..0dff4751262f1 100644 --- a/compiler/rustc_traits/src/normalize_projection_ty.rs +++ b/compiler/rustc_traits/src/normalize_projection_ty.rs @@ -4,9 +4,8 @@ use rustc_middle::query::Providers; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::InferCtxtBuilderExt; -use rustc_trait_selection::traits::query::{ - normalize::NormalizationResult, CanonicalAliasGoal, NoSolution, -}; +use rustc_trait_selection::traits::query::normalize::NormalizationResult; +use rustc_trait_selection::traits::query::{CanonicalAliasGoal, NoSolution}; use rustc_trait_selection::traits::{self, ObligationCause, ScrubbedTraitError, SelectionContext}; use tracing::debug; diff --git a/compiler/rustc_traits/src/type_op.rs b/compiler/rustc_traits/src/type_op.rs index b6a59a4ad3a4c..5affadaac38c3 100644 --- a/compiler/rustc_traits/src/type_op.rs +++ b/compiler/rustc_traits/src/type_op.rs @@ -1,9 +1,10 @@ +use std::fmt; + use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::query::Providers; use rustc_middle::traits::query::NoSolution; -use rustc_middle::ty::{Clause, ParamEnvAnd}; -use rustc_middle::ty::{FnSig, PolyFnSig, Ty, TyCtxt, TypeFoldable}; +use rustc_middle::ty::{Clause, FnSig, ParamEnvAnd, PolyFnSig, Ty, TyCtxt, TypeFoldable}; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt; use rustc_trait_selection::traits::query::type_op::ascribe_user_type::{ @@ -14,7 +15,6 @@ use rustc_trait_selection::traits::query::type_op::normalize::Normalize; use rustc_trait_selection::traits::query::type_op::prove_predicate::ProvePredicate; use rustc_trait_selection::traits::query::type_op::subtype::Subtype; use rustc_trait_selection::traits::{Normalized, Obligation, ObligationCause, ObligationCtxt}; -use std::fmt; pub(crate) fn provide(p: &mut Providers) { *p = Providers { diff --git a/compiler/rustc_transmute/src/layout/dfa.rs b/compiler/rustc_transmute/src/layout/dfa.rs index 3378d1c6754db..58bd517d7e89f 100644 --- a/compiler/rustc_transmute/src/layout/dfa.rs +++ b/compiler/rustc_transmute/src/layout/dfa.rs @@ -1,9 +1,11 @@ -use super::{nfa, Byte, Nfa, Ref}; -use crate::Map; use std::fmt; use std::sync::atomic::{AtomicU32, Ordering}; + use tracing::instrument; +use super::{nfa, Byte, Nfa, Ref}; +use crate::Map; + #[derive(PartialEq, Clone, Debug)] pub(crate) struct Dfa where diff --git a/compiler/rustc_transmute/src/layout/mod.rs b/compiler/rustc_transmute/src/layout/mod.rs index 0377ed5d4c57a..bbf155581f98b 100644 --- a/compiler/rustc_transmute/src/layout/mod.rs +++ b/compiler/rustc_transmute/src/layout/mod.rs @@ -60,9 +60,10 @@ impl Ref for ! { #[cfg(feature = "rustc")] pub mod rustc { + use std::fmt::{self, Write}; + use rustc_middle::mir::Mutability; use rustc_middle::ty::{self, Ty}; - use std::fmt::{self, Write}; /// A reference in the layout. #[derive(Debug, Hash, Eq, PartialEq, Clone, Copy)] diff --git a/compiler/rustc_transmute/src/layout/nfa.rs b/compiler/rustc_transmute/src/layout/nfa.rs index 3c5963202c638..0dd26badc885f 100644 --- a/compiler/rustc_transmute/src/layout/nfa.rs +++ b/compiler/rustc_transmute/src/layout/nfa.rs @@ -1,8 +1,9 @@ -use super::{Byte, Ref, Tree, Uninhabited}; -use crate::{Map, Set}; use std::fmt; use std::sync::atomic::{AtomicU32, Ordering}; +use super::{Byte, Ref, Tree, Uninhabited}; +use crate::{Map, Set}; + /// A non-deterministic finite automaton (NFA) that represents the layout of a type. /// The transmutability of two given types is computed by comparing their `Nfa`s. #[derive(PartialEq, Debug)] diff --git a/compiler/rustc_transmute/src/layout/tree.rs b/compiler/rustc_transmute/src/layout/tree.rs index 865f9487213f8..5c25f913ffe38 100644 --- a/compiler/rustc_transmute/src/layout/tree.rs +++ b/compiler/rustc_transmute/src/layout/tree.rs @@ -1,6 +1,7 @@ -use super::{Byte, Def, Ref}; use std::ops::ControlFlow; +use super::{Byte, Def, Ref}; + #[cfg(test)] mod tests; @@ -170,24 +171,14 @@ where #[cfg(feature = "rustc")] pub(crate) mod rustc { + use rustc_middle::ty::layout::{HasTyCtxt, LayoutCx, LayoutError, LayoutOf}; + use rustc_middle::ty::{self, AdtDef, AdtKind, List, ScalarInt, Ty, TyCtxt, TypeVisitableExt}; + use rustc_span::ErrorGuaranteed; + use rustc_target::abi::{FieldsShape, Size, TyAndLayout, Variants}; + use super::Tree; use crate::layout::rustc::{Def, Ref}; - use rustc_middle::ty::layout::HasTyCtxt; - use rustc_middle::ty::layout::LayoutCx; - use rustc_middle::ty::layout::LayoutError; - use rustc_middle::ty::layout::LayoutOf; - use rustc_middle::ty::AdtDef; - use rustc_middle::ty::AdtKind; - use rustc_middle::ty::List; - use rustc_middle::ty::ScalarInt; - use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; - use rustc_span::ErrorGuaranteed; - use rustc_target::abi::FieldsShape; - use rustc_target::abi::Size; - use rustc_target::abi::TyAndLayout; - use rustc_target::abi::Variants; - #[derive(Debug, Copy, Clone)] pub(crate) enum Err { /// The layout of the type is not yet supported. diff --git a/compiler/rustc_transmute/src/lib.rs b/compiler/rustc_transmute/src/lib.rs index 2b052412e6b61..31664ee6c4f7e 100644 --- a/compiler/rustc_transmute/src/lib.rs +++ b/compiler/rustc_transmute/src/lib.rs @@ -79,19 +79,15 @@ pub enum Reason { #[cfg(feature = "rustc")] mod rustc { - use super::*; - use rustc_hir::lang_items::LangItem; use rustc_infer::infer::InferCtxt; use rustc_macros::TypeVisitable; use rustc_middle::traits::ObligationCause; - use rustc_middle::ty::Const; - use rustc_middle::ty::ParamEnv; - use rustc_middle::ty::Ty; - use rustc_middle::ty::TyCtxt; - use rustc_middle::ty::ValTree; + use rustc_middle::ty::{Const, ParamEnv, Ty, TyCtxt, ValTree}; use rustc_span::DUMMY_SP; + use super::*; + /// The source and destination types of a transmutation. #[derive(TypeVisitable, Debug, Clone, Copy)] pub struct Types<'tcx> { diff --git a/compiler/rustc_transmute/src/maybe_transmutable/mod.rs b/compiler/rustc_transmute/src/maybe_transmutable/mod.rs index dee5a72c3bcca..7c66a827db9a3 100644 --- a/compiler/rustc_transmute/src/maybe_transmutable/mod.rs +++ b/compiler/rustc_transmute/src/maybe_transmutable/mod.rs @@ -4,11 +4,9 @@ pub(crate) mod query_context; #[cfg(test)] mod tests; -use crate::{ - layout::{self, dfa, Byte, Def, Dfa, Nfa, Ref, Tree, Uninhabited}, - maybe_transmutable::query_context::QueryContext, - Answer, Condition, Map, Reason, -}; +use crate::layout::{self, dfa, Byte, Def, Dfa, Nfa, Ref, Tree, Uninhabited}; +use crate::maybe_transmutable::query_context::QueryContext; +use crate::{Answer, Condition, Map, Reason}; pub(crate) struct MaybeTransmutableQuery where @@ -32,15 +30,12 @@ where // FIXME: Nix this cfg, so we can write unit tests independently of rustc #[cfg(feature = "rustc")] mod rustc { + use rustc_middle::ty::layout::{LayoutCx, LayoutOf}; + use rustc_middle::ty::{ParamEnv, Ty, TyCtxt}; + use super::*; use crate::layout::tree::rustc::Err; - use rustc_middle::ty::layout::LayoutCx; - use rustc_middle::ty::layout::LayoutOf; - use rustc_middle::ty::ParamEnv; - use rustc_middle::ty::Ty; - use rustc_middle::ty::TyCtxt; - impl<'tcx> MaybeTransmutableQuery, TyCtxt<'tcx>> { /// This method begins by converting `src` and `dst` from `Ty`s to `Tree`s, /// then computes an answer using those trees. diff --git a/compiler/rustc_transmute/src/maybe_transmutable/query_context.rs b/compiler/rustc_transmute/src/maybe_transmutable/query_context.rs index 1ccb6f36c8ef5..95373916a71ae 100644 --- a/compiler/rustc_transmute/src/maybe_transmutable/query_context.rs +++ b/compiler/rustc_transmute/src/maybe_transmutable/query_context.rs @@ -34,9 +34,10 @@ pub(crate) mod test { #[cfg(feature = "rustc")] mod rustc { - use super::*; use rustc_middle::ty::{Ty, TyCtxt}; + use super::*; + impl<'tcx> super::QueryContext for TyCtxt<'tcx> { type Def = layout::rustc::Def<'tcx>; type Ref = layout::rustc::Ref<'tcx>; diff --git a/compiler/rustc_transmute/src/maybe_transmutable/tests.rs b/compiler/rustc_transmute/src/maybe_transmutable/tests.rs index 9c7abf1cbd636..c3be4203cceb9 100644 --- a/compiler/rustc_transmute/src/maybe_transmutable/tests.rs +++ b/compiler/rustc_transmute/src/maybe_transmutable/tests.rs @@ -1,12 +1,12 @@ +use itertools::Itertools; + use super::query_context::test::{Def, UltraMinimal}; use crate::maybe_transmutable::MaybeTransmutableQuery; use crate::{layout, Reason}; -use itertools::Itertools; mod safety { - use crate::Answer; - use super::*; + use crate::Answer; type Tree = layout::Tree; @@ -63,9 +63,8 @@ mod safety { } mod bool { - use crate::Answer; - use super::*; + use crate::Answer; #[test] fn should_permit_identity_transmutation_tree() { diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index 1dced9cf7cd28..f1675f80717f0 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -1,3 +1,5 @@ +use std::iter; + use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_middle::bug; @@ -16,8 +18,6 @@ use rustc_target::abi::*; use rustc_target::spec::abi::Abi as SpecAbi; use tracing::debug; -use std::iter; - pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { fn_abi_of_fn_ptr, fn_abi_of_instance, ..*providers }; } diff --git a/compiler/rustc_ty_utils/src/consts.rs b/compiler/rustc_ty_utils/src/consts.rs index 58f812fc7cfa1..2492688352342 100644 --- a/compiler/rustc_ty_utils/src/consts.rs +++ b/compiler/rustc_ty_utils/src/consts.rs @@ -1,20 +1,19 @@ +use std::iter; + use rustc_errors::ErrorGuaranteed; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; -use rustc_middle::bug; use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput}; use rustc_middle::query::Providers; use rustc_middle::thir::visit; use rustc_middle::thir::visit::Visitor; use rustc_middle::ty::abstract_const::CastKind; use rustc_middle::ty::{self, Expr, TyCtxt, TypeVisitableExt}; -use rustc_middle::{mir, thir}; +use rustc_middle::{bug, mir, thir}; use rustc_span::Span; use rustc_target::abi::{VariantIdx, FIRST_VARIANT}; use tracing::{debug, instrument}; -use std::iter; - use crate::errors::{GenericConstantTooComplex, GenericConstantTooComplexSub}; /// Destructures array, ADT or tuple constants into the constants diff --git a/compiler/rustc_ty_utils/src/implied_bounds.rs b/compiler/rustc_ty_utils/src/implied_bounds.rs index 6f71951b51629..8812260b3af31 100644 --- a/compiler/rustc_ty_utils/src/implied_bounds.rs +++ b/compiler/rustc_ty_utils/src/implied_bounds.rs @@ -1,3 +1,5 @@ +use std::iter; + use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_hir::def::DefKind; @@ -6,7 +8,6 @@ use rustc_middle::bug; use rustc_middle::query::Providers; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::Span; -use std::iter; pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index 7b6d86d22a578..43e491387091e 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -6,8 +6,7 @@ use rustc_middle::bug; use rustc_middle::query::Providers; use rustc_middle::traits::{BuiltinImplSource, CodegenObligationError}; use rustc_middle::ty::util::AsyncDropGlueMorphology; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, Instance, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, GenericArgsRef, Instance, TyCtxt, TypeVisitableExt}; use rustc_span::sym; use rustc_trait_selection::traits; use rustc_type_ir::ClosureKind; @@ -191,11 +190,22 @@ fn resolve_associated_item<'tcx>( // Any final impl is required to define all associated items. if !leaf_def.item.defaultness(tcx).has_value() { - let guard = tcx.dcx().span_delayed_bug( + let guar = tcx.dcx().span_delayed_bug( tcx.def_span(leaf_def.item.def_id), "missing value for assoc item in impl", ); - return Err(guard); + return Err(guar); + } + + // Make sure that we're projecting to an item that has compatible args. + // This may happen if we are resolving an instance before codegen, such + // as during inlining. This check is also done in projection. + if !tcx.check_args_compatible(leaf_def.item.def_id, args) { + let guar = tcx.dcx().span_delayed_bug( + tcx.def_span(leaf_def.item.def_id), + "missing value for assoc item in impl", + ); + return Err(guar); } let args = tcx.erase_regions(args); diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 6045abc50a9da..3ef10f4e43c4b 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -1,3 +1,6 @@ +use std::fmt::Debug; +use std::iter; + use hir::def_id::DefId; use rustc_hir as hir; use rustc_index::bit_set::BitSet; @@ -19,9 +22,6 @@ use rustc_span::symbol::Symbol; use rustc_target::abi::*; use tracing::{debug, instrument, trace}; -use std::fmt::Debug; -use std::iter; - use crate::errors::{ MultipleArrayFieldsSimdType, NonPrimitiveSimdType, OversizedSimdType, ZeroLengthSimdType, }; @@ -733,9 +733,7 @@ fn coroutine_saved_local_eligibility( // point, so it is no longer a candidate. trace!( "removing local {:?} in >1 variant ({:?}, {:?})", - local, - variant_index, - idx + local, variant_index, idx ); ineligible_locals.insert(*local); assignments[*local] = Ineligible(None); diff --git a/compiler/rustc_ty_utils/src/layout_sanity_check.rs b/compiler/rustc_ty_utils/src/layout_sanity_check.rs index ab7d1be226b3c..d8e0443c50b85 100644 --- a/compiler/rustc_ty_utils/src/layout_sanity_check.rs +++ b/compiler/rustc_ty_utils/src/layout_sanity_check.rs @@ -1,12 +1,10 @@ +use std::assert_matches::assert_matches; + use rustc_middle::bug; -use rustc_middle::ty::{ - layout::{LayoutCx, TyAndLayout}, - TyCtxt, -}; +use rustc_middle::ty::layout::{LayoutCx, TyAndLayout}; +use rustc_middle::ty::TyCtxt; use rustc_target::abi::*; -use std::assert_matches::assert_matches; - /// Enforce some basic invariants on layouts. pub(super) fn sanity_check_layout<'tcx>( cx: &LayoutCx<'tcx, TyCtxt<'tcx>>, diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index 205b3f2760f36..d274a934d5297 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -5,8 +5,7 @@ use rustc_hir::def_id::DefId; use rustc_middle::bug; use rustc_middle::query::Providers; use rustc_middle::ty::util::{needs_drop_components, AlwaysRequiresDrop}; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::{self, EarlyBinder, Ty, TyCtxt}; +use rustc_middle::ty::{self, EarlyBinder, GenericArgsRef, Ty, TyCtxt}; use rustc_session::Limit; use rustc_span::sym; use tracing::debug; diff --git a/compiler/rustc_ty_utils/src/opaque_types.rs b/compiler/rustc_ty_utils/src/opaque_types.rs index 5e91320f89753..6680b451b7cc7 100644 --- a/compiler/rustc_ty_utils/src/opaque_types.rs +++ b/compiler/rustc_ty_utils/src/opaque_types.rs @@ -1,12 +1,12 @@ use rustc_data_structures::fx::FxHashSet; +use rustc_hir::def::DefKind; +use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::Visitor; -use rustc_hir::{def::DefKind, def_id::LocalDefId}; use rustc_hir::{intravisit, CRATE_HIR_ID}; use rustc_middle::bug; use rustc_middle::query::Providers; use rustc_middle::ty::util::{CheckRegions, NotUniqueParam}; -use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_middle::ty::{TypeSuperVisitable, TypeVisitable, TypeVisitor}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor}; use rustc_span::Span; use tracing::{instrument, trace}; diff --git a/compiler/rustc_ty_utils/src/sig_types.rs b/compiler/rustc_ty_utils/src/sig_types.rs index eb6cb369974fd..568b9383ffbc4 100644 --- a/compiler/rustc_ty_utils/src/sig_types.rs +++ b/compiler/rustc_ty_utils/src/sig_types.rs @@ -3,7 +3,8 @@ use rustc_ast_ir::try_visit; use rustc_ast_ir::visit::VisitorResult; -use rustc_hir::{def::DefKind, def_id::LocalDefId}; +use rustc_hir::def::DefKind; +use rustc_hir::def_id::LocalDefId; use rustc_middle::span_bug; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::Span; diff --git a/compiler/rustc_ty_utils/src/structural_match.rs b/compiler/rustc_ty_utils/src/structural_match.rs index 241aff9c30a00..1ead7b731e76c 100644 --- a/compiler/rustc_ty_utils/src/structural_match.rs +++ b/compiler/rustc_ty_utils/src/structural_match.rs @@ -1,8 +1,7 @@ use rustc_hir::lang_items::LangItem; +use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::query::Providers; use rustc_middle::ty::{self, Ty, TyCtxt}; - -use rustc_infer::infer::TyCtxtInferExt; use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt}; /// This method returns true if and only if `adt_ty` itself has been marked as diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index 38950c97c9d58..aba2acd1842f1 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -5,8 +5,10 @@ use rustc_hir::LangItem; use rustc_index::bit_set::BitSet; use rustc_middle::bug; use rustc_middle::query::Providers; -use rustc_middle::ty::{self, EarlyBinder, Ty, TyCtxt, TypeVisitableExt, TypeVisitor}; -use rustc_middle::ty::{TypeSuperVisitable, TypeVisitable, Upcast}; +use rustc_middle::ty::{ + self, EarlyBinder, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, + TypeVisitor, Upcast, +}; use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_span::DUMMY_SP; use rustc_trait_selection::traits; diff --git a/compiler/rustc_type_ir/Cargo.toml b/compiler/rustc_type_ir/Cargo.toml index 769e350b835cf..2750838bbe99f 100644 --- a/compiler/rustc_type_ir/Cargo.toml +++ b/compiler/rustc_type_ir/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" [dependencies] # tidy-alphabetical-start bitflags = "2.4.1" -derivative = "2.2.0" +derive-where = "1.2.7" indexmap = "2.0.0" rustc_ast_ir = { path = "../rustc_ast_ir", default-features = false } rustc_data_structures = { path = "../rustc_data_structures", optional = true } diff --git a/compiler/rustc_type_ir/src/binder.rs b/compiler/rustc_type_ir/src/binder.rs index 17b35a2807a2d..c1f6fb36324ed 100644 --- a/compiler/rustc_type_ir/src/binder.rs +++ b/compiler/rustc_type_ir/src/binder.rs @@ -3,6 +3,7 @@ use std::hash::Hash; use std::marker::PhantomData; use std::ops::{ControlFlow, Deref}; +use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; #[cfg(feature = "nightly")] @@ -25,15 +26,12 @@ use crate::{self as ty, Interner}; /// e.g., `liberate_late_bound_regions`). /// /// `Decodable` and `Encodable` are implemented for `Binder` using the `impl_binder_encode_decode!` macro. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = "T: Clone"), - Copy(bound = "T: Copy"), - Hash(bound = "T: Hash"), - PartialEq(bound = "T: PartialEq"), - Eq(bound = "T: Eq"), - Debug(bound = "T: Debug") -)] +#[derive_where(Clone; I: Interner, T: Clone)] +#[derive_where(Copy; I: Interner, T: Copy)] +#[derive_where(Hash; I: Interner, T: Hash)] +#[derive_where(PartialEq; I: Interner, T: PartialEq)] +#[derive_where(Eq; I: Interner, T: Eq)] +#[derive_where(Debug; I: Interner, T: Debug)] #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] pub struct Binder { value: T, @@ -351,21 +349,18 @@ impl TypeVisitor for ValidateBoundVars { /// /// If you don't have anything to `instantiate`, you may be looking for /// [`instantiate_identity`](EarlyBinder::instantiate_identity) or [`skip_binder`](EarlyBinder::skip_binder). -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = "T: Clone"), - Copy(bound = "T: Copy"), - PartialEq(bound = "T: PartialEq"), - Eq(bound = "T: Eq"), - Ord(bound = "T: Ord"), - PartialOrd(bound = "T: Ord"), - Hash(bound = "T: Hash"), - Debug(bound = "T: Debug") -)] +#[derive_where(Clone; I: Interner, T: Clone)] +#[derive_where(Copy; I: Interner, T: Copy)] +#[derive_where(PartialEq; I: Interner, T: PartialEq)] +#[derive_where(Eq; I: Interner, T: Eq)] +#[derive_where(Ord; I: Interner, T: Ord)] +#[derive_where(PartialOrd; I: Interner, T: Ord)] +#[derive_where(Hash; I: Interner, T: Hash)] +#[derive_where(Debug; I: Interner, T: Debug)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] pub struct EarlyBinder { value: T, - #[derivative(Debug = "ignore")] + #[derive_where(skip(Debug))] _tcx: PhantomData, } diff --git a/compiler/rustc_type_ir/src/canonical.rs b/compiler/rustc_type_ir/src/canonical.rs index a9252711b2b66..d609e5add14b9 100644 --- a/compiler/rustc_type_ir/src/canonical.rs +++ b/compiler/rustc_type_ir/src/canonical.rs @@ -1,25 +1,24 @@ -#[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; -use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; use std::fmt; use std::hash::Hash; use std::ops::Index; +use derive_where::derive_where; +#[cfg(feature = "nightly")] +use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; + use crate::inherent::*; use crate::{self as ty, Interner, UniverseIndex}; /// A "canonicalized" type `V` is one where all free inference /// variables have been rewritten to "canonical vars". These are /// numbered starting from 0 in order of first appearance. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = "V: Clone"), - Hash(bound = "V: Hash"), - PartialEq(bound = "V: PartialEq"), - Eq(bound = "V: Eq"), - Debug(bound = "V: fmt::Debug"), - Copy(bound = "V: Copy") -)] +#[derive_where(Clone; I: Interner, V: Clone)] +#[derive_where(Hash; I: Interner, V: Hash)] +#[derive_where(PartialEq; I: Interner, V: PartialEq)] +#[derive_where(Eq; I: Interner, V: Eq)] +#[derive_where(Debug; I: Interner, V: fmt::Debug)] +#[derive_where(Copy; I: Interner, V: Copy)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] pub struct Canonical { @@ -84,15 +83,7 @@ impl fmt::Display for Canonical { /// canonical value. This is sufficient information for code to create /// a copy of the canonical value in some other inference context, /// with fresh inference variables replacing the canonical values. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - Debug(bound = ""), - Eq(bound = ""), - PartialEq(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct CanonicalVarInfo { @@ -149,8 +140,7 @@ impl CanonicalVarInfo { /// Describes the "kind" of the canonical variable. This is a "kind" /// in the type-theory sense of the term -- i.e., a "meta" type system /// that analyzes type-like values. -#[derive(derivative::Derivative)] -#[derivative(Clone(bound = ""), Copy(bound = ""), Hash(bound = ""), Debug(bound = ""))] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub enum CanonicalVarKind { @@ -178,20 +168,6 @@ pub enum CanonicalVarKind { PlaceholderConst(I::PlaceholderConst), } -impl PartialEq for CanonicalVarKind { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Self::Ty(l0), Self::Ty(r0)) => l0 == r0, - (Self::PlaceholderTy(l0), Self::PlaceholderTy(r0)) => l0 == r0, - (Self::Region(l0), Self::Region(r0)) => l0 == r0, - (Self::PlaceholderRegion(l0), Self::PlaceholderRegion(r0)) => l0 == r0, - (Self::Const(l0), Self::Const(r0)) => l0 == r0, - (Self::PlaceholderConst(l0), Self::PlaceholderConst(r0)) => l0 == r0, - _ => std::mem::discriminant(self) == std::mem::discriminant(other), - } - } -} - impl CanonicalVarKind { pub fn universe(self) -> UniverseIndex { match self { @@ -266,15 +242,7 @@ pub enum CanonicalTyVarKind { /// vectors with the original values that were replaced by canonical /// variables. You will need to supply it later to instantiate the /// canonicalized query response. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Hash(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] pub struct CanonicalVarValues { diff --git a/compiler/rustc_type_ir/src/codec.rs b/compiler/rustc_type_ir/src/codec.rs index 71f9eb0ef8a82..f443f596373fb 100644 --- a/compiler/rustc_type_ir/src/codec.rs +++ b/compiler/rustc_type_ir/src/codec.rs @@ -1,8 +1,8 @@ -use crate::{Interner, PredicateKind}; - use rustc_data_structures::fx::FxHashMap; use rustc_span::{SpanDecoder, SpanEncoder}; +use crate::{Interner, PredicateKind}; + /// The shorthand encoding uses an enum's variant index `usize` /// and is offset by this value so it never matches a real variant. /// This offset is also chosen so that the first byte is never < 0x80. diff --git a/compiler/rustc_type_ir/src/const_kind.rs b/compiler/rustc_type_ir/src/const_kind.rs index 1a51c95ecdff6..7a8c612057fa2 100644 --- a/compiler/rustc_type_ir/src/const_kind.rs +++ b/compiler/rustc_type_ir/src/const_kind.rs @@ -1,17 +1,16 @@ +use std::fmt; + +use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; #[cfg(feature = "nightly")] use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; -use std::fmt; use crate::{self as ty, DebruijnIndex, Interner}; -use self::ConstKind::*; - /// Represents a constant in Rust. -#[derive(derivative::Derivative)] -#[derivative(Clone(bound = ""), Copy(bound = ""), Hash(bound = ""), Eq(bound = ""))] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] pub enum ConstKind { /// A const generic parameter. @@ -43,22 +42,6 @@ pub enum ConstKind { Expr(I::ExprConst), } -impl PartialEq for ConstKind { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Param(l0), Param(r0)) => l0 == r0, - (Infer(l0), Infer(r0)) => l0 == r0, - (Bound(l0, l1), Bound(r0, r1)) => l0 == r0 && l1 == r1, - (Placeholder(l0), Placeholder(r0)) => l0 == r0, - (Unevaluated(l0), Unevaluated(r0)) => l0 == r0, - (Value(l0, l1), Value(r0, r1)) => l0 == r0 && l1 == r1, - (Error(l0), Error(r0)) => l0 == r0, - (Expr(l0), Expr(r0)) => l0 == r0, - _ => false, - } - } -} - impl fmt::Debug for ConstKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { use ConstKind::*; @@ -77,14 +60,7 @@ impl fmt::Debug for ConstKind { } /// An unevaluated (potentially generic) constant used in the type-system. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = "") -)] +#[derive_where(Clone, Copy, Debug, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct UnevaluatedConst { @@ -99,15 +75,6 @@ impl UnevaluatedConst { } } -impl fmt::Debug for UnevaluatedConst { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("UnevaluatedConst") - .field("def", &self.def) - .field("args", &self.args) - .finish() - } -} - rustc_index::newtype_index! { /// A **`const`** **v**ariable **ID**. #[encodable] diff --git a/compiler/rustc_type_ir/src/data_structures.rs b/compiler/rustc_type_ir/src/data_structures.rs index 6d8ab61b722fd..4ca97c0c86c0f 100644 --- a/compiler/rustc_type_ir/src/data_structures.rs +++ b/compiler/rustc_type_ir/src/data_structures.rs @@ -1,25 +1,20 @@ #[cfg(feature = "nightly")] mod impl_ { - pub use rustc_data_structures::fx::FxHashMap as HashMap; - pub use rustc_data_structures::fx::FxHashSet as HashSet; - pub use rustc_data_structures::fx::FxIndexMap as IndexMap; - pub use rustc_data_structures::fx::FxIndexSet as IndexSet; - pub use rustc_data_structures::sso::SsoHashMap; - pub use rustc_data_structures::sso::SsoHashSet; + pub use rustc_data_structures::fx::{ + FxHashMap as HashMap, FxHashSet as HashSet, FxIndexMap as IndexMap, FxIndexSet as IndexSet, + }; + pub use rustc_data_structures::sso::{SsoHashMap, SsoHashSet}; pub use rustc_data_structures::stack::ensure_sufficient_stack; pub use rustc_data_structures::sync::Lrc; } #[cfg(not(feature = "nightly"))] mod impl_ { - pub use indexmap::IndexMap; - pub use indexmap::IndexSet; - pub use std::collections::HashMap; - pub use std::collections::HashMap as SsoHashMap; - pub use std::collections::HashSet; - pub use std::collections::HashSet as SsoHashSet; + pub use std::collections::{HashMap, HashMap as SsoHashMap, HashSet, HashSet as SsoHashSet}; pub use std::sync::Arc as Lrc; + pub use indexmap::{IndexMap, IndexSet}; + #[inline] pub fn ensure_sufficient_stack(f: impl FnOnce() -> R) -> R { f() diff --git a/compiler/rustc_type_ir/src/elaborate.rs b/compiler/rustc_type_ir/src/elaborate.rs index 7dd2f3de3f824..f30419c801f18 100644 --- a/compiler/rustc_type_ir/src/elaborate.rs +++ b/compiler/rustc_type_ir/src/elaborate.rs @@ -3,9 +3,9 @@ use std::marker::PhantomData; use smallvec::smallvec; use crate::data_structures::HashSet; +use crate::inherent::*; use crate::outlives::{push_outlives_components, Component}; -use crate::{self as ty, Interner}; -use crate::{inherent::*, Upcast as _}; +use crate::{self as ty, Interner, Upcast as _}; /// "Elaboration" is the process of identifying all the predicates that /// are implied by a source predicate. Currently, this basically means @@ -264,15 +264,6 @@ pub fn supertraits( elaborate(cx, [trait_ref.upcast(cx)]).filter_only_self().filter_to_traits() } -pub fn transitive_bounds( - cx: I, - trait_refs: impl Iterator>>, -) -> FilterToTraits> { - elaborate(cx, trait_refs.map(|trait_ref| trait_ref.upcast(cx))) - .filter_only_self() - .filter_to_traits() -} - impl Elaborator { fn filter_to_traits(self) -> FilterToTraits { FilterToTraits { _cx: PhantomData, base_iterator: self } diff --git a/compiler/rustc_type_ir/src/error.rs b/compiler/rustc_type_ir/src/error.rs index 8b59e9a6f481c..8a6d37b7d23f6 100644 --- a/compiler/rustc_type_ir/src/error.rs +++ b/compiler/rustc_type_ir/src/error.rs @@ -1,3 +1,4 @@ +use derive_where::derive_where; use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; use crate::solve::NoSolution; @@ -21,14 +22,7 @@ impl ExpectedFound { } // Data structures used in type unification -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic)] #[cfg_attr(feature = "nightly", rustc_pass_by_value)] pub enum TypeError { diff --git a/compiler/rustc_type_ir/src/fold.rs b/compiler/rustc_type_ir/src/fold.rs index a4d8dafb246e5..16dcf76e73eb8 100644 --- a/compiler/rustc_type_ir/src/fold.rs +++ b/compiler/rustc_type_ir/src/fold.rs @@ -45,8 +45,9 @@ //! - u.fold_with(folder) //! ``` -use rustc_index::{Idx, IndexVec}; use std::mem; + +use rustc_index::{Idx, IndexVec}; use tracing::debug; use crate::data_structures::Lrc; diff --git a/compiler/rustc_type_ir/src/generic_arg.rs b/compiler/rustc_type_ir/src/generic_arg.rs index b158f0f5eee9f..008268c3bffad 100644 --- a/compiler/rustc_type_ir/src/generic_arg.rs +++ b/compiler/rustc_type_ir/src/generic_arg.rs @@ -1,16 +1,10 @@ +use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; use crate::Interner; -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Debug(bound = ""), - Eq(bound = ""), - PartialEq(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Debug; I: Interner)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub enum GenericArgKind { Lifetime(I::Region), @@ -18,14 +12,7 @@ pub enum GenericArgKind { Const(I::Const), } -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Debug(bound = ""), - Eq(bound = ""), - PartialEq(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Debug; I: Interner)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub enum TermKind { Ty(I::Ty), diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index 63ad36efc8529..263ba676427c5 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -432,6 +432,7 @@ pub trait Predicate>: + UpcastFrom> + UpcastFrom> + IntoKind>> + + Elaboratable { fn as_clause(self) -> Option; @@ -450,6 +451,8 @@ pub trait Clause>: + UpcastFrom>> + UpcastFrom> + UpcastFrom>> + + UpcastFrom> + + UpcastFrom>> + UpcastFrom> + UpcastFrom>> + IntoKind>> diff --git a/compiler/rustc_type_ir/src/interner.rs b/compiler/rustc_type_ir/src/interner.rs index 14ebbb12fe2f0..c251540c0fc29 100644 --- a/compiler/rustc_type_ir/src/interner.rs +++ b/compiler/rustc_type_ir/src/interner.rs @@ -1,22 +1,24 @@ -use rustc_ast_ir::Movability; -use rustc_index::bit_set::BitSet; -use smallvec::SmallVec; use std::fmt::Debug; use std::hash::Hash; use std::ops::Deref; +use rustc_ast_ir::Movability; +use rustc_index::bit_set::BitSet; +use smallvec::SmallVec; + use crate::fold::TypeFoldable; use crate::inherent::*; use crate::ir_print::IrPrint; use crate::lang_items::TraitSolverLangItem; use crate::relate::Relate; -use crate::search_graph; use crate::solve::inspect::CanonicalGoalEvaluationStep; use crate::solve::{ CanonicalInput, ExternalConstraintsData, PredefinedOpaquesData, QueryResult, SolverMode, }; use crate::visit::{Flags, TypeSuperVisitable, TypeVisitable}; -use crate::{self as ty}; +use crate::{ + search_graph, {self as ty}, +}; pub trait Interner: Sized diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index 80e970a23a9d1..de41d2f3cc512 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -9,11 +9,12 @@ extern crate self as rustc_type_ir; -#[cfg(feature = "nightly")] -use rustc_macros::{Decodable, Encodable, HashStable_NoContext}; use std::fmt; use std::hash::Hash; +#[cfg(feature = "nightly")] +use rustc_macros::{Decodable, Encodable, HashStable_NoContext}; + // These modules are `pub` since they are not glob-imported. #[macro_use] pub mod visit; diff --git a/compiler/rustc_type_ir/src/opaque_ty.rs b/compiler/rustc_type_ir/src/opaque_ty.rs index e5d18fcb3d1e1..6d61a52723aeb 100644 --- a/compiler/rustc_type_ir/src/opaque_ty.rs +++ b/compiler/rustc_type_ir/src/opaque_ty.rs @@ -1,3 +1,4 @@ +use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; @@ -5,15 +6,7 @@ use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; use crate::inherent::*; use crate::{self as ty, Interner}; -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = ""), - Copy(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] pub struct OpaqueTypeKey { diff --git a/compiler/rustc_type_ir/src/outlives.rs b/compiler/rustc_type_ir/src/outlives.rs index eb84f3dd58731..2f26a43918383 100644 --- a/compiler/rustc_type_ir/src/outlives.rs +++ b/compiler/rustc_type_ir/src/outlives.rs @@ -2,6 +2,7 @@ //! refers to rules defined in RFC 1214 (`OutlivesFooBar`), so see that //! RFC for reference. +use derive_where::derive_where; use smallvec::{smallvec, SmallVec}; use crate::data_structures::SsoHashSet; @@ -9,8 +10,7 @@ use crate::inherent::*; use crate::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt as _, TypeVisitor}; use crate::{self as ty, Interner}; -#[derive(derivative::Derivative)] -#[derivative(Debug(bound = ""))] +#[derive_where(Debug; I: Interner)] pub enum Component { Region(I::Region), Param(I::ParamTy), diff --git a/compiler/rustc_type_ir/src/predicate.rs b/compiler/rustc_type_ir/src/predicate.rs index e03f521c5b105..b30346ffc53dc 100644 --- a/compiler/rustc_type_ir/src/predicate.rs +++ b/compiler/rustc_type_ir/src/predicate.rs @@ -1,6 +1,7 @@ use std::fmt; use std::hash::Hash; +use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_macros::{Decodable, Encodable, HashStable_NoContext, TyDecodable, TyEncodable}; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; @@ -12,15 +13,12 @@ use crate::visit::TypeVisitableExt as _; use crate::{self as ty, Interner}; /// `A: 'region` -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = "A: Clone"), - Copy(bound = "A: Copy"), - Hash(bound = "A: Hash"), - PartialEq(bound = "A: PartialEq"), - Eq(bound = "A: Eq"), - Debug(bound = "A: fmt::Debug") -)] +#[derive_where(Clone; I: Interner, A: Clone)] +#[derive_where(Copy; I: Interner, A: Copy)] +#[derive_where(Hash; I: Interner, A: Hash)] +#[derive_where(PartialEq; I: Interner, A: PartialEq)] +#[derive_where(Eq; I: Interner, A: Eq)] +#[derive_where(Debug; I: Interner, A: fmt::Debug)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct OutlivesPredicate(pub A, pub I::Region); @@ -50,14 +48,7 @@ where /// /// Trait references also appear in object types like `Foo`, but in /// that case the `Self` parameter is absent from the generic parameters. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct TraitRef { @@ -122,14 +113,7 @@ impl ty::Binder> { } } -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct TraitPredicate { @@ -243,15 +227,7 @@ impl fmt::Display for PredicatePolarity { } } -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub enum ExistentialPredicate { @@ -296,14 +272,7 @@ impl ty::Binder> { /// ``` /// The generic parameters don't include the erased `Self`, only trait /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above). -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct ExistentialTraitRef { @@ -349,14 +318,7 @@ impl ty::Binder> { } /// A `ProjectionPredicate` for an `ExistentialTraitRef`. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct ExistentialProjection { @@ -452,15 +414,7 @@ impl AliasTermKind { /// * For a projection, this would be `>::N<...>`. /// * For an inherent projection, this would be `Ty::N<...>`. /// * For an opaque type, there is no explicit syntax. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct AliasTerm { @@ -489,7 +443,7 @@ pub struct AliasTerm { pub def_id: I::DefId, /// This field exists to prevent the creation of `AliasTerm` without using [`AliasTerm::new_from_args`]. - #[derivative(Debug = "ignore")] + #[derive_where(skip(Debug))] _use_alias_term_new_instead: (), } @@ -631,14 +585,7 @@ impl From> for AliasTerm { /// equality between arbitrary types. Processing an instance of /// Form #2 eventually yields one of these `ProjectionPredicate` /// instances to normalize the LHS. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct ProjectionPredicate { @@ -706,14 +653,7 @@ impl fmt::Debug for ProjectionPredicate { /// Used by the new solver. Unlike a `ProjectionPredicate` this can only be /// proven by actually normalizing `alias`. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct NormalizesTo { @@ -748,15 +688,7 @@ impl fmt::Debug for NormalizesTo { /// Encodes that `a` must be a subtype of `b`. The `a_is_expected` flag indicates /// whether the `a` type is the type that we should label as "expected" when /// presenting user diagnostics. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct SubtypePredicate { @@ -766,15 +698,7 @@ pub struct SubtypePredicate { } /// Encodes that we have to coerce *from* the `a` type to the `b` type. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct CoercePredicate { diff --git a/compiler/rustc_type_ir/src/predicate_kind.rs b/compiler/rustc_type_ir/src/predicate_kind.rs index b1d0f8d19b396..c8a2102858832 100644 --- a/compiler/rustc_type_ir/src/predicate_kind.rs +++ b/compiler/rustc_type_ir/src/predicate_kind.rs @@ -1,14 +1,15 @@ +use std::fmt; + +use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_macros::{Decodable, Encodable, HashStable_NoContext, TyDecodable, TyEncodable}; use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; -use std::fmt; use crate::{self as ty, Interner}; /// A clause is something that can appear in where bounds or be inferred /// by implied bounds. -#[derive(derivative::Derivative)] -#[derivative(Clone(bound = ""), Copy(bound = ""), Hash(bound = ""), Eq(bound = ""))] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] pub enum ClauseKind { @@ -38,29 +39,7 @@ pub enum ClauseKind { ConstEvaluatable(I::Const), } -impl PartialEq for ClauseKind { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Self::Trait(l0), Self::Trait(r0)) => l0 == r0, - (Self::RegionOutlives(l0), Self::RegionOutlives(r0)) => l0 == r0, - (Self::TypeOutlives(l0), Self::TypeOutlives(r0)) => l0 == r0, - (Self::Projection(l0), Self::Projection(r0)) => l0 == r0, - (Self::ConstArgHasType(l0, l1), Self::ConstArgHasType(r0, r1)) => l0 == r0 && l1 == r1, - (Self::WellFormed(l0), Self::WellFormed(r0)) => l0 == r0, - (Self::ConstEvaluatable(l0), Self::ConstEvaluatable(r0)) => l0 == r0, - _ => false, - } - } -} - -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] pub enum PredicateKind { diff --git a/compiler/rustc_type_ir/src/region_kind.rs b/compiler/rustc_type_ir/src/region_kind.rs index 140c89af147d0..e0b3973700783 100644 --- a/compiler/rustc_type_ir/src/region_kind.rs +++ b/compiler/rustc_type_ir/src/region_kind.rs @@ -1,12 +1,13 @@ +use std::fmt; + +use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; #[cfg(feature = "nightly")] use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; -use std::fmt; - -use crate::{DebruijnIndex, Interner}; use self::RegionKind::*; +use crate::{DebruijnIndex, Interner}; rustc_index::newtype_index! { /// A **region** **v**ariable **ID**. @@ -124,8 +125,7 @@ rustc_index::newtype_index! { /// [1]: https://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/ /// [2]: https://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/ /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html -#[derive(derivative::Derivative)] -#[derivative(Clone(bound = ""), Copy(bound = ""), Hash(bound = ""), Eq(bound = ""))] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable))] pub enum RegionKind { /// A region parameter; for example `'a` in `impl<'a> Trait for &'a ()`. @@ -177,47 +177,6 @@ pub enum RegionKind { ReError(I::ErrorGuaranteed), } -// This is manually implemented for `RegionKind` because `std::mem::discriminant` -// returns an opaque value that is `PartialEq` but not `PartialOrd` -#[inline] -const fn regionkind_discriminant(value: &RegionKind) -> usize { - match value { - ReEarlyParam(_) => 0, - ReBound(_, _) => 1, - ReLateParam(_) => 2, - ReStatic => 3, - ReVar(_) => 4, - RePlaceholder(_) => 5, - ReErased => 6, - ReError(_) => 7, - } -} - -// This is manually implemented because a derive would require `I: PartialEq` -impl PartialEq for RegionKind { - #[inline] - fn eq(&self, other: &RegionKind) -> bool { - regionkind_discriminant(self) == regionkind_discriminant(other) - && match (self, other) { - (ReEarlyParam(a_r), ReEarlyParam(b_r)) => a_r == b_r, - (ReBound(a_d, a_r), ReBound(b_d, b_r)) => a_d == b_d && a_r == b_r, - (ReLateParam(a_r), ReLateParam(b_r)) => a_r == b_r, - (ReStatic, ReStatic) => true, - (ReVar(a_r), ReVar(b_r)) => a_r == b_r, - (RePlaceholder(a_r), RePlaceholder(b_r)) => a_r == b_r, - (ReErased, ReErased) => true, - (ReError(_), ReError(_)) => true, - _ => { - debug_assert!( - false, - "This branch must be unreachable, maybe the match is missing an arm? self = {self:?}, other = {other:?}" - ); - true - } - } - } -} - impl fmt::Debug for RegionKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { diff --git a/compiler/rustc_type_ir/src/relate.rs b/compiler/rustc_type_ir/src/relate.rs index ae840ec021033..9fd3534d1fa6b 100644 --- a/compiler/rustc_type_ir/src/relate.rs +++ b/compiler/rustc_type_ir/src/relate.rs @@ -1,5 +1,6 @@ use std::iter; +use derive_where::derive_where; use rustc_ast_ir::Mutability; use tracing::{instrument, trace}; @@ -17,19 +18,11 @@ pub type RelateResult = Result>; /// a miscompilation or unsoundness. /// /// When in doubt, use `VarianceDiagInfo::default()` -#[derive(derivative::Derivative)] -#[derivative( - Copy(bound = ""), - Clone(bound = ""), - Debug(bound = ""), - Default(bound = ""), - PartialEq(bound = ""), - Eq(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Debug, Default; I: Interner)] pub enum VarianceDiagInfo { /// No additional information - this is the default. /// We will not add any additional information to error messages. - #[derivative(Default)] + #[derive_where(default)] None, /// We switched our variance because a generic argument occurs inside /// the invariant generic argument of another type. diff --git a/compiler/rustc_type_ir/src/search_graph/global_cache.rs b/compiler/rustc_type_ir/src/search_graph/global_cache.rs index 5ccda931f9c5f..be4f1069cd167 100644 --- a/compiler/rustc_type_ir/src/search_graph/global_cache.rs +++ b/compiler/rustc_type_ir/src/search_graph/global_cache.rs @@ -1,10 +1,10 @@ +use derive_where::derive_where; use rustc_index::IndexVec; use super::{AvailableDepth, Cx, StackDepth, StackEntry}; use crate::data_structures::{HashMap, HashSet}; -#[derive(derivative::Derivative)] -#[derivative(Debug(bound = ""), Clone(bound = ""), Copy(bound = ""))] +#[derive_where(Debug, Clone, Copy; X: Cx)] struct QueryData { result: X::Result, proof_tree: X::ProofTree, @@ -20,8 +20,7 @@ struct Success { /// This contains results whose computation never hit the /// recursion limit in `success`, and all results which hit /// the recursion limit in `with_overflow`. -#[derive(derivative::Derivative)] -#[derivative(Default(bound = ""))] +#[derive_where(Default; X: Cx)] struct CacheEntry { success: Option>, /// We have to be careful when caching roots of cycles. @@ -32,8 +31,7 @@ struct CacheEntry { with_overflow: HashMap>>, } -#[derive(derivative::Derivative)] -#[derivative(Debug(bound = ""))] +#[derive_where(Debug; X: Cx)] pub(super) struct CacheData<'a, X: Cx> { pub(super) result: X::Result, pub(super) proof_tree: X::ProofTree, @@ -41,11 +39,10 @@ pub(super) struct CacheData<'a, X: Cx> { pub(super) encountered_overflow: bool, // FIXME: This is currently unused, but impacts the design // by requiring a closure for `Cx::with_global_cache`. + #[allow(dead_code)] pub(super) nested_goals: &'a HashSet, } - -#[derive(derivative::Derivative)] -#[derivative(Default(bound = ""))] +#[derive_where(Default; X: Cx)] pub struct GlobalCache { map: HashMap>, } diff --git a/compiler/rustc_type_ir/src/search_graph/mod.rs b/compiler/rustc_type_ir/src/search_graph/mod.rs index c2204becdfd71..4abf99b1ded8a 100644 --- a/compiler/rustc_type_ir/src/search_graph/mod.rs +++ b/compiler/rustc_type_ir/src/search_graph/mod.rs @@ -3,6 +3,7 @@ use std::hash::Hash; use std::marker::PhantomData; use std::mem; +use derive_where::derive_where; use rustc_index::{Idx, IndexVec}; use tracing::debug; @@ -153,8 +154,7 @@ rustc_index::newtype_index! { pub struct StackDepth {} } -#[derive(derivative::Derivative)] -#[derivative(Debug(bound = ""))] +#[derive_where(Debug; X: Cx)] struct StackEntry { input: X::Input, @@ -226,8 +226,7 @@ struct DetachedEntry { /// /// The provisional cache can theoretically result in changes to the observable behavior, /// see tests/ui/traits/next-solver/cycles/provisional-cache-impacts-behavior.rs. -#[derive(derivative::Derivative)] -#[derivative(Default(bound = ""))] +#[derive_where(Default; X: Cx)] struct ProvisionalCacheEntry { stack_depth: Option, with_inductive_stack: Option>, diff --git a/compiler/rustc_type_ir/src/solve/inspect.rs b/compiler/rustc_type_ir/src/solve/inspect.rs index 0733c730064b0..47d5e0dace71f 100644 --- a/compiler/rustc_type_ir/src/solve/inspect.rs +++ b/compiler/rustc_type_ir/src/solve/inspect.rs @@ -17,13 +17,16 @@ //! //! [canonicalized]: https://rustc-dev-guide.rust-lang.org/solve/canonicalization.html +use std::fmt::Debug; +use std::hash::Hash; + +use derive_where::derive_where; +use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; + use crate::solve::{ CandidateSource, CanonicalInput, Certainty, Goal, GoalSource, QueryInput, QueryResult, }; use crate::{Canonical, CanonicalVarValues, Interner}; -use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; -use std::fmt::Debug; -use std::hash::Hash; /// Some `data` together with information about how they relate to the input /// of the canonical query. @@ -31,15 +34,12 @@ use std::hash::Hash; /// This is only ever used as [CanonicalState]. Any type information in proof /// trees used mechanically has to be canonicalized as we otherwise leak /// inference variables from a nested `InferCtxt`. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = "T: Clone"), - Copy(bound = "T: Copy"), - PartialEq(bound = "T: PartialEq"), - Eq(bound = "T: Eq"), - Hash(bound = "T: Hash"), - Debug(bound = "T: Debug") -)] +#[derive_where(Clone; I: Interner, T: Clone)] +#[derive_where(Copy; I: Interner, T: Copy)] +#[derive_where(PartialEq; I: Interner, T: PartialEq)] +#[derive_where(Eq; I: Interner, T: Eq)] +#[derive_where(Hash; I: Interner, T: Hash)] +#[derive_where(Debug; I: Interner, T: Debug)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] pub struct State { pub var_values: CanonicalVarValues, @@ -52,24 +52,21 @@ pub type CanonicalState = Canonical>; /// for the `CanonicalVarValues` of the canonicalized goal. /// We use this to map any [CanonicalState] from the local `InferCtxt` /// of the solver query to the `InferCtxt` of the caller. -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""), Hash(bound = ""))] +#[derive_where(PartialEq, Eq, Hash; I: Interner)] pub struct GoalEvaluation { pub uncanonicalized_goal: Goal, pub orig_values: Vec, pub evaluation: CanonicalGoalEvaluation, } -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""), Hash(bound = ""), Debug(bound = ""))] +#[derive_where(PartialEq, Eq, Hash, Debug; I: Interner)] pub struct CanonicalGoalEvaluation { pub goal: CanonicalInput, pub kind: CanonicalGoalEvaluationKind, pub result: QueryResult, } -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""), Hash(bound = ""), Debug(bound = ""))] +#[derive_where(PartialEq, Eq, Hash, Debug; I: Interner)] pub enum CanonicalGoalEvaluationKind { Overflow, CycleInStack, @@ -77,8 +74,7 @@ pub enum CanonicalGoalEvaluationKind { Evaluation { final_revision: I::CanonicalGoalEvaluationStepRef }, } -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""), Hash(bound = ""), Debug(bound = ""))] +#[derive_where(PartialEq, Eq, Hash, Debug; I: Interner)] pub struct CanonicalGoalEvaluationStep { pub instantiated_goal: QueryInput, @@ -89,8 +85,7 @@ pub struct CanonicalGoalEvaluationStep { /// A self-contained computation during trait solving. This either /// corresponds to a `EvalCtxt::probe(_X)` call or the root evaluation /// of a goal. -#[derive(derivative::Derivative)] -#[derivative(Debug(bound = ""), PartialEq(bound = ""), Eq(bound = ""), Hash(bound = ""))] +#[derive_where(PartialEq, Eq, Hash, Debug; I: Interner)] pub struct Probe { /// What happened inside of this probe in chronological order. pub steps: Vec>, @@ -98,8 +93,7 @@ pub struct Probe { pub final_state: CanonicalState, } -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""), Hash(bound = ""), Debug(bound = ""))] +#[derive_where(PartialEq, Eq, Hash, Debug; I: Interner)] pub enum ProbeStep { /// We added a goal to the `EvalCtxt` which will get proven /// the next time `EvalCtxt::try_evaluate_added_goals` is called. @@ -121,15 +115,7 @@ pub enum ProbeStep { /// What kind of probe we're in. In case the probe represents a candidate, or /// the final result of the current goal - via [ProbeKind::Root] - we also /// store the [QueryResult]. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Hash(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] pub enum ProbeKind { /// The root inference context while proving a goal. diff --git a/compiler/rustc_type_ir/src/solve/mod.rs b/compiler/rustc_type_ir/src/solve/mod.rs index 2449ac47db6fa..444fd01f01281 100644 --- a/compiler/rustc_type_ir/src/solve/mod.rs +++ b/compiler/rustc_type_ir/src/solve/mod.rs @@ -3,6 +3,7 @@ pub mod inspect; use std::fmt; use std::hash::Hash; +use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; @@ -89,15 +90,12 @@ pub struct NoSolution; /// /// Most of the time the `param_env` contains the `where`-bounds of the function /// we're currently typechecking while the `predicate` is some trait bound. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = "P: Clone"), - Copy(bound = "P: Copy"), - Hash(bound = "P: Hash"), - PartialEq(bound = "P: PartialEq"), - Eq(bound = "P: Eq"), - Debug(bound = "P: fmt::Debug") -)] +#[derive_where(Clone; I: Interner, P: Clone)] +#[derive_where(Copy; I: Interner, P: Copy)] +#[derive_where(Hash; I: Interner, P: Hash)] +#[derive_where(PartialEq; I: Interner, P: PartialEq)] +#[derive_where(Eq; I: Interner, P: Eq)] +#[derive_where(Debug; I: Interner, P: fmt::Debug)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct Goal { @@ -140,15 +138,12 @@ pub enum GoalSource { InstantiateHigherRanked, } -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = "Goal: Clone"), - Copy(bound = "Goal: Copy"), - Hash(bound = "Goal: Hash"), - PartialEq(bound = "Goal: PartialEq"), - Eq(bound = "Goal: Eq"), - Debug(bound = "Goal: fmt::Debug") -)] +#[derive_where(Clone; I: Interner, Goal: Clone)] +#[derive_where(Copy; I: Interner, Goal: Copy)] +#[derive_where(Hash; I: Interner, Goal: Hash)] +#[derive_where(PartialEq; I: Interner, Goal: PartialEq)] +#[derive_where(Eq; I: Interner, Goal: Eq)] +#[derive_where(Debug; I: Interner, Goal: fmt::Debug)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct QueryInput { @@ -157,15 +152,7 @@ pub struct QueryInput { } /// Opaques that are defined in the inference context before a query is called. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = ""), - Default(bound = "") -)] +#[derive_where(Clone, Hash, PartialEq, Eq, Debug, Default; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct PredefinedOpaquesData { @@ -173,15 +160,7 @@ pub struct PredefinedOpaquesData { } /// Possible ways the given goal can be proven. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] pub enum CandidateSource { /// A user written impl. /// @@ -265,15 +244,7 @@ pub enum BuiltinImplSource { TupleUnsizing, } -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] pub struct Response { @@ -284,15 +255,7 @@ pub struct Response { } /// Additional constraints returned on success. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = ""), - Default(bound = "") -)] +#[derive_where(Clone, Hash, PartialEq, Eq, Debug, Default; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] pub struct ExternalConstraintsData { @@ -301,15 +264,7 @@ pub struct ExternalConstraintsData { pub normalization_nested_goals: NestedNormalizationGoals, } -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = ""), - Default(bound = "") -)] +#[derive_where(Clone, Hash, PartialEq, Eq, Debug, Default; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] pub struct NestedNormalizationGoals(pub Vec<(GoalSource, Goal)>); @@ -386,8 +341,7 @@ impl MaybeCause { } } -#[derive(derivative::Derivative)] -#[derivative(PartialEq(bound = ""), Eq(bound = ""), Debug(bound = ""))] +#[derive_where(PartialEq, Eq, Debug; I: Interner)] pub struct CacheData { pub result: QueryResult, pub proof_tree: Option, diff --git a/compiler/rustc_type_ir/src/ty_info.rs b/compiler/rustc_type_ir/src/ty_info.rs index 0e4930552c211..a999566745070 100644 --- a/compiler/rustc_type_ir/src/ty_info.rs +++ b/compiler/rustc_type_ir/src/ty_info.rs @@ -1,10 +1,11 @@ +use std::cmp::Ordering; +use std::hash::{Hash, Hasher}; +use std::ops::Deref; + #[cfg(feature = "nightly")] use rustc_data_structures::fingerprint::Fingerprint; #[cfg(feature = "nightly")] use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use std::cmp::Ordering; -use std::hash::{Hash, Hasher}; -use std::ops::Deref; use crate::{DebruijnIndex, TypeFlags}; diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index 9896425a34110..7e48f1b20a868 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -1,3 +1,7 @@ +use std::fmt; + +use derive_where::derive_where; +use rustc_ast_ir::Mutability; #[cfg(feature = "nightly")] use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; #[cfg(feature = "nightly")] @@ -5,15 +9,12 @@ use rustc_data_structures::unify::{NoError, UnifyKey, UnifyValue}; #[cfg(feature = "nightly")] use rustc_macros::{Decodable, Encodable, HashStable_NoContext, TyDecodable, TyEncodable}; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; -use std::fmt; pub use self::closure::*; use self::TyKind::*; use crate::inherent::*; use crate::{self as ty, DebruijnIndex, Interner}; -use rustc_ast_ir::Mutability; - mod closure; /// Specifies how a trait object is represented. @@ -64,8 +65,7 @@ impl AliasTyKind { /// Types written by the user start out as `hir::TyKind` and get /// converted to this representation using `::lower_ty`. #[cfg_attr(feature = "nightly", rustc_diagnostic_item = "IrTyKind")] -#[derive(derivative::Derivative)] -#[derivative(Clone(bound = ""), Copy(bound = ""), Hash(bound = ""), Eq(bound = ""))] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] pub enum TyKind { /// The primitive boolean type. Written as `bool`. @@ -256,91 +256,6 @@ impl TyKind { } } -// This is manually implemented for `TyKind` because `std::mem::discriminant` -// returns an opaque value that is `PartialEq` but not `PartialOrd` -#[inline] -const fn tykind_discriminant(value: &TyKind) -> usize { - match value { - Bool => 0, - Char => 1, - Int(_) => 2, - Uint(_) => 3, - Float(_) => 4, - Adt(_, _) => 5, - Foreign(_) => 6, - Str => 7, - Array(_, _) => 8, - Slice(_) => 9, - RawPtr(_, _) => 10, - Ref(_, _, _) => 11, - FnDef(_, _) => 12, - FnPtr(_) => 13, - Dynamic(..) => 14, - Closure(_, _) => 15, - CoroutineClosure(_, _) => 16, - Coroutine(_, _) => 17, - CoroutineWitness(_, _) => 18, - Never => 19, - Tuple(_) => 20, - Pat(_, _) => 21, - Alias(_, _) => 22, - Param(_) => 23, - Bound(_, _) => 24, - Placeholder(_) => 25, - Infer(_) => 26, - Error(_) => 27, - } -} - -// This is manually implemented because a derive would require `I: PartialEq` -impl PartialEq for TyKind { - #[inline] - fn eq(&self, other: &TyKind) -> bool { - // You might expect this `match` to be preceded with this: - // - // tykind_discriminant(self) == tykind_discriminant(other) && - // - // but the data patterns in practice are such that a comparison - // succeeds 99%+ of the time, and it's faster to omit it. - match (self, other) { - (Int(a_i), Int(b_i)) => a_i == b_i, - (Uint(a_u), Uint(b_u)) => a_u == b_u, - (Float(a_f), Float(b_f)) => a_f == b_f, - (Adt(a_d, a_s), Adt(b_d, b_s)) => a_d == b_d && a_s == b_s, - (Foreign(a_d), Foreign(b_d)) => a_d == b_d, - (Array(a_t, a_c), Array(b_t, b_c)) => a_t == b_t && a_c == b_c, - (Pat(a_t, a_c), Pat(b_t, b_c)) => a_t == b_t && a_c == b_c, - (Slice(a_t), Slice(b_t)) => a_t == b_t, - (RawPtr(a_t, a_m), RawPtr(b_t, b_m)) => a_t == b_t && a_m == b_m, - (Ref(a_r, a_t, a_m), Ref(b_r, b_t, b_m)) => a_r == b_r && a_t == b_t && a_m == b_m, - (FnDef(a_d, a_s), FnDef(b_d, b_s)) => a_d == b_d && a_s == b_s, - (FnPtr(a_s), FnPtr(b_s)) => a_s == b_s, - (Dynamic(a_p, a_r, a_repr), Dynamic(b_p, b_r, b_repr)) => { - a_p == b_p && a_r == b_r && a_repr == b_repr - } - (Closure(a_d, a_s), Closure(b_d, b_s)) => a_d == b_d && a_s == b_s, - (CoroutineClosure(a_d, a_s), CoroutineClosure(b_d, b_s)) => a_d == b_d && a_s == b_s, - (Coroutine(a_d, a_s), Coroutine(b_d, b_s)) => a_d == b_d && a_s == b_s, - (CoroutineWitness(a_d, a_s), CoroutineWitness(b_d, b_s)) => a_d == b_d && a_s == b_s, - (Tuple(a_t), Tuple(b_t)) => a_t == b_t, - (Alias(a_i, a_p), Alias(b_i, b_p)) => a_i == b_i && a_p == b_p, - (Param(a_p), Param(b_p)) => a_p == b_p, - (Bound(a_d, a_b), Bound(b_d, b_b)) => a_d == b_d && a_b == b_b, - (Placeholder(a_p), Placeholder(b_p)) => a_p == b_p, - (Infer(a_t), Infer(b_t)) => a_t == b_t, - (Error(a_e), Error(b_e)) => a_e == b_e, - (Bool, Bool) | (Char, Char) | (Str, Str) | (Never, Never) => true, - _ => { - debug_assert!( - tykind_discriminant(self) != tykind_discriminant(other), - "This branch must be unreachable, maybe the match is missing an arm? self = {self:?}, other = {other:?}" - ); - false - } - } - } -} - // This is manually implemented because a derive would require `I: Debug` impl fmt::Debug for TyKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -414,15 +329,7 @@ impl fmt::Debug for TyKind { /// * For a projection, this would be `>::N<...>`. /// * For an inherent projection, this would be `Ty::N<...>`. /// * For an opaque type, there is no explicit syntax. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] pub struct AliasTy { @@ -451,7 +358,7 @@ pub struct AliasTy { pub def_id: I::DefId, /// This field exists to prevent the creation of `AliasTy` without using [`AliasTy::new_from_args`]. - #[derivative(Debug = "ignore")] + #[derive_where(skip(Debug))] pub(crate) _use_alias_ty_new_instead: (), } @@ -942,15 +849,7 @@ impl fmt::Debug for InferTy { } } -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Hash(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] pub struct TypeAndMut { @@ -958,14 +857,7 @@ pub struct TypeAndMut { pub mutbl: Mutability, } -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Hash(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Hash; I: Interner)] #[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] pub struct FnSig { diff --git a/compiler/rustc_type_ir/src/ty_kind/closure.rs b/compiler/rustc_type_ir/src/ty_kind/closure.rs index 6c5bbbfd59ba9..81717ce4a2266 100644 --- a/compiler/rustc_type_ir/src/ty_kind/closure.rs +++ b/compiler/rustc_type_ir/src/ty_kind/closure.rs @@ -1,5 +1,6 @@ use std::ops::ControlFlow; +use derive_where::derive_where; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; use crate::fold::{shift_region, TypeFoldable, TypeFolder, TypeSuperFoldable}; @@ -100,15 +101,7 @@ use crate::{self as ty, Interner}; /// * `GR`: The "return type", which is the type of value returned upon /// completion of the coroutine. /// * `GW`: The "coroutine witness". -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] pub struct ClosureArgs { /// Lifetime and type parameters from the enclosing function, @@ -210,15 +203,7 @@ impl ClosureArgs { } } -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] pub struct CoroutineClosureArgs { pub args: I::GenericArgs, @@ -370,15 +355,7 @@ impl TypeVisitor for HasRegionsBoundAt { } } -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] pub struct CoroutineClosureSignature { pub interior: I::Ty, @@ -552,15 +529,7 @@ impl TypeFolder for FoldEscapingRegions { } } -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] pub struct GenSig { pub resume_ty: I::Ty, @@ -569,15 +538,7 @@ pub struct GenSig { } /// Similar to `ClosureArgs`; see the above documentation for more. -#[derive(derivative::Derivative)] -#[derivative( - Clone(bound = ""), - Copy(bound = ""), - Hash(bound = ""), - PartialEq(bound = ""), - Eq(bound = ""), - Debug(bound = "") -)] +#[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] pub struct CoroutineArgs { pub args: I::GenericArgs, diff --git a/compiler/rustc_type_ir/src/visit.rs b/compiler/rustc_type_ir/src/visit.rs index 6ec38b78fc22a..0ba7e2bd5523a 100644 --- a/compiler/rustc_type_ir/src/visit.rs +++ b/compiler/rustc_type_ir/src/visit.rs @@ -41,11 +41,12 @@ //! - u.visit_with(visitor) //! ``` +use std::fmt; +use std::ops::ControlFlow; + use rustc_ast_ir::visit::VisitorResult; use rustc_ast_ir::{try_visit, walk_visitable_list}; use rustc_index::{Idx, IndexVec}; -use std::fmt; -use std::ops::ControlFlow; use crate::data_structures::Lrc; use crate::inherent::*; @@ -241,10 +242,6 @@ pub trait TypeVisitableExt: TypeVisitable { self.has_type_flags(TypeFlags::HAS_ALIAS) } - fn has_inherent_projections(&self) -> bool { - self.has_type_flags(TypeFlags::HAS_TY_INHERENT) - } - fn has_opaque_types(&self) -> bool { self.has_type_flags(TypeFlags::HAS_TY_OPAQUE) } diff --git a/compiler/rustc_type_ir_macros/src/lib.rs b/compiler/rustc_type_ir_macros/src/lib.rs index f5b90424afbc6..2bfbfaa498bf3 100644 --- a/compiler/rustc_type_ir_macros/src/lib.rs +++ b/compiler/rustc_type_ir_macros/src/lib.rs @@ -1,5 +1,6 @@ use quote::quote; -use syn::{parse_quote, visit_mut::VisitMut}; +use syn::parse_quote; +use syn::visit_mut::VisitMut; use synstructure::decl_derive; decl_derive!( diff --git a/compiler/stable_mir/Cargo.toml b/compiler/stable_mir/Cargo.toml index 4ed6115273653..2edb3f140d7ac 100644 --- a/compiler/stable_mir/Cargo.toml +++ b/compiler/stable_mir/Cargo.toml @@ -5,3 +5,4 @@ edition = "2021" [dependencies] scoped-tls = "1.0" +serde = { version = "1.0.125", features = [ "derive" ] } diff --git a/compiler/stable_mir/src/abi.rs b/compiler/stable_mir/src/abi.rs index e1c14fe0b380b..9d3b40e5eea7b 100644 --- a/compiler/stable_mir/src/abi.rs +++ b/compiler/stable_mir/src/abi.rs @@ -1,16 +1,17 @@ +use std::fmt::{self, Debug}; +use std::num::NonZero; +use std::ops::RangeInclusive; + +use serde::Serialize; + use crate::compiler_interface::with; -use crate::error; use crate::mir::FieldIdx; use crate::target::{MachineInfo, MachineSize as Size}; use crate::ty::{Align, IndexedVal, Ty, VariantIdx}; -use crate::Error; -use crate::Opaque; -use std::fmt::{self, Debug}; -use std::num::NonZero; -use std::ops::RangeInclusive; +use crate::{error, Error, Opaque}; /// A function ABI definition. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub struct FnAbi { /// The types of each argument. pub args: Vec, @@ -31,7 +32,7 @@ pub struct FnAbi { } /// Information about the ABI of a function's argument, or return value. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub struct ArgAbi { pub ty: Ty, pub layout: Layout, @@ -39,7 +40,7 @@ pub struct ArgAbi { } /// How a function argument should be passed in to the target function. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub enum PassMode { /// Ignore the argument. /// @@ -60,14 +61,14 @@ pub enum PassMode { } /// The layout of a type, alongside the type itself. -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub struct TyAndLayout { pub ty: Ty, pub layout: Layout, } /// The layout of a type in memory. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub struct LayoutShape { /// The fields location withing the layout pub fields: FieldsShape, @@ -108,7 +109,7 @@ impl LayoutShape { } } -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub struct Layout(usize); impl Layout { @@ -127,7 +128,7 @@ impl IndexedVal for Layout { } /// Describes how the fields of a type are shaped in memory. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub enum FieldsShape { /// Scalar primitives and `!`, which never have fields. Primitive, @@ -177,7 +178,7 @@ impl FieldsShape { } } -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub enum VariantsShape { /// Single enum variants, structs/tuples, unions, and all non-ADTs. Single { index: VariantIdx }, @@ -196,7 +197,7 @@ pub enum VariantsShape { }, } -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub enum TagEncoding { /// The tag directly stores the discriminant, but possibly with a smaller layout /// (so converting the tag to the discriminant can require sign extension). @@ -221,7 +222,7 @@ pub enum TagEncoding { /// Describes how values of the type are passed by target ABIs, /// in terms of categories of C types there are ABI rules for. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub enum ValueAbi { Uninhabited, Scalar(Scalar), @@ -250,7 +251,7 @@ impl ValueAbi { } /// Information about one scalar component of a Rust type. -#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize)] pub enum Scalar { Initialized { /// The primitive type used to represent this value. @@ -280,7 +281,7 @@ impl Scalar { } /// Fundamental unit of memory access and layout. -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Serialize)] pub enum Primitive { /// The `bool` is the signedness of the `Integer` type. /// @@ -310,7 +311,7 @@ impl Primitive { } /// Enum representing the existing integer lengths. -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Serialize)] pub enum IntegerLength { I8, I16, @@ -320,7 +321,7 @@ pub enum IntegerLength { } /// Enum representing the existing float lengths. -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Serialize)] pub enum FloatLength { F16, F32, @@ -354,7 +355,7 @@ impl FloatLength { /// An identifier that specifies the address space that some operation /// should operate on. Special address spaces have an effect on code generation, /// depending on the target and the address spaces it implements. -#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] pub struct AddressSpace(pub u32); impl AddressSpace { @@ -369,7 +370,7 @@ impl AddressSpace { /// sequence: /// /// 254 (-2), 255 (-1), 0, 1, 2 -#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize)] pub struct WrappingRange { pub start: u128, pub end: u128, @@ -420,7 +421,7 @@ impl Debug for WrappingRange { } /// General language calling conventions. -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub enum CallConvention { C, Rust, diff --git a/compiler/stable_mir/src/crate_def.rs b/compiler/stable_mir/src/crate_def.rs index d9b987c28a26a..2882fdf7bed86 100644 --- a/compiler/stable_mir/src/crate_def.rs +++ b/compiler/stable_mir/src/crate_def.rs @@ -1,11 +1,13 @@ //! Module that define a common trait for things that represent a crate definition, //! such as, a function, a trait, an enum, and any other definitions. +use serde::Serialize; + use crate::ty::{GenericArgs, Span, Ty}; use crate::{with, Crate, Symbol}; /// A unique identification number for each item accessible for the current compilation unit. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize)] pub struct DefId(pub(crate) usize); /// A trait for retrieving information about a particular definition. diff --git a/compiler/stable_mir/src/lib.rs b/compiler/stable_mir/src/lib.rs index 8385856ae532d..b523e949cde3e 100644 --- a/compiler/stable_mir/src/lib.rs +++ b/compiler/stable_mir/src/lib.rs @@ -17,15 +17,15 @@ //! The goal is to eventually be published on //! [crates.io](https://crates.io). -use std::fmt; use std::fmt::Debug; -use std::io; +use std::{fmt, io}; + +use serde::Serialize; use crate::compiler_interface::with; pub use crate::crate_def::{CrateDef, CrateDefType, DefId}; pub use crate::error::*; -use crate::mir::Body; -use crate::mir::Mutability; +use crate::mir::{Body, Mutability}; use crate::ty::{ForeignModuleDef, ImplDef, IndexedVal, Span, TraitDef, Ty}; pub mod abi; @@ -74,7 +74,7 @@ pub type TraitDecls = Vec; pub type ImplTraitDecls = Vec; /// Holds information about a crate. -#[derive(Clone, PartialEq, Eq, Debug)] +#[derive(Clone, PartialEq, Eq, Debug, Serialize)] pub struct Crate { pub id: CrateNum, pub name: Symbol, @@ -98,7 +98,7 @@ impl Crate { } } -#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] +#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, Serialize)] pub enum ItemKind { Fn, Static, @@ -106,7 +106,7 @@ pub enum ItemKind { Ctor(CtorKind), } -#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] +#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, Serialize)] pub enum CtorKind { Const, Fn, @@ -116,6 +116,7 @@ pub type Filename = String; crate_def_with_ty! { /// Holds information about an item in a crate. + #[derive(Serialize)] pub CrateItem; } @@ -188,7 +189,7 @@ pub fn all_trait_impls() -> ImplTraitDecls { } /// A type that provides internal information but that can still be used for debug purpose. -#[derive(Clone, PartialEq, Eq, Hash)] +#[derive(Clone, PartialEq, Eq, Hash, Serialize)] pub struct Opaque(String); impl std::fmt::Display for Opaque { diff --git a/compiler/stable_mir/src/mir/alloc.rs b/compiler/stable_mir/src/mir/alloc.rs index ef1568151f2e6..a3768f8e01c9b 100644 --- a/compiler/stable_mir/src/mir/alloc.rs +++ b/compiler/stable_mir/src/mir/alloc.rs @@ -1,14 +1,17 @@ //! This module provides methods to retrieve allocation information, such as static variables. +use std::io::Read; + +use serde::Serialize; + use crate::mir::mono::{Instance, StaticDef}; use crate::target::{Endian, MachineInfo}; use crate::ty::{Allocation, Binder, ExistentialTraitRef, IndexedVal, Ty}; use crate::{with, Error}; -use std::io::Read; /// An allocation in the SMIR global memory can be either a function pointer, /// a static, or a "real" allocation with some data in it. -#[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Debug, Clone, Eq, PartialEq, Serialize)] pub enum GlobalAlloc { /// The alloc ID is used as a function pointer. Function(Instance), @@ -41,7 +44,7 @@ impl GlobalAlloc { } /// A unique identification number for each provenance -#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Serialize)] pub struct AllocId(usize); impl IndexedVal for AllocId { diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs index e0f9e7ae67a0f..7c09fe1a08541 100644 --- a/compiler/stable_mir/src/mir/body.rs +++ b/compiler/stable_mir/src/mir/body.rs @@ -1,3 +1,7 @@ +use std::io; + +use serde::Serialize; + use crate::compiler_interface::with; use crate::mir::pretty::function_body; use crate::ty::{ @@ -5,10 +9,9 @@ use crate::ty::{ TyConst, TyKind, VariantIdx, }; use crate::{Error, Opaque, Span, Symbol}; -use std::io; /// The SMIR representation of a single function. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Serialize)] pub struct Body { pub blocks: Vec, @@ -104,20 +107,20 @@ impl Body { type LocalDecls = Vec; -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct LocalDecl { pub ty: Ty, pub span: Span, pub mutability: Mutability, } -#[derive(Clone, PartialEq, Eq, Debug)] +#[derive(Clone, PartialEq, Eq, Debug, Serialize)] pub struct BasicBlock { pub statements: Vec, pub terminator: Terminator, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct Terminator { pub kind: TerminatorKind, pub span: Span, @@ -131,7 +134,7 @@ impl Terminator { pub type Successors = Vec; -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum TerminatorKind { Goto { target: BasicBlockIdx, @@ -221,7 +224,7 @@ impl TerminatorKind { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct InlineAsmOperand { pub in_value: Option, pub out_place: Option, @@ -230,7 +233,7 @@ pub struct InlineAsmOperand { pub raw_rpr: String, } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub enum UnwindAction { Continue, Unreachable, @@ -238,7 +241,7 @@ pub enum UnwindAction { Cleanup(BasicBlockIdx), } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum AssertMessage { BoundsCheck { len: Operand, index: Operand }, Overflow(BinOp, Operand, Operand), @@ -307,7 +310,7 @@ impl AssertMessage { } } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub enum BinOp { Add, AddUnchecked, @@ -342,7 +345,7 @@ impl BinOp { } } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub enum UnOp { Not, Neg, @@ -357,20 +360,20 @@ impl UnOp { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum CoroutineKind { Desugared(CoroutineDesugaring, CoroutineSource), Coroutine(Movability), } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub enum CoroutineSource { Block, Closure, Fn, } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub enum CoroutineDesugaring { Async, @@ -386,7 +389,7 @@ pub(crate) type LocalDefId = Opaque; pub(crate) type Coverage = Opaque; /// The FakeReadCause describes the type of pattern why a FakeRead statement exists. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum FakeReadCause { ForMatchGuard, ForMatchedPlace(LocalDefId), @@ -396,7 +399,7 @@ pub enum FakeReadCause { } /// Describes what kind of retag is to be performed -#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Serialize)] pub enum RetagKind { FnEntry, TwoPhase, @@ -404,7 +407,7 @@ pub enum RetagKind { Default, } -#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Serialize)] pub enum Variance { Covariant, Invariant, @@ -412,26 +415,26 @@ pub enum Variance { Bivariant, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct CopyNonOverlapping { pub src: Operand, pub dst: Operand, pub count: Operand, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum NonDivergingIntrinsic { Assume(Operand), CopyNonOverlapping(CopyNonOverlapping), } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct Statement { pub kind: StatementKind, pub span: Span, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum StatementKind { Assign(Place, Rvalue), FakeRead(FakeReadCause, Place), @@ -448,7 +451,7 @@ pub enum StatementKind { Nop, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum Rvalue { /// Creates a pointer with the indicated mutability to the place. /// @@ -622,7 +625,7 @@ impl Rvalue { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum AggregateKind { Array(Ty), Tuple, @@ -633,14 +636,14 @@ pub enum AggregateKind { RawPtr(Ty, Mutability), } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum Operand { Copy(Place), Move(Place), Constant(ConstOperand), } -#[derive(Clone, Eq, PartialEq)] +#[derive(Clone, Eq, PartialEq, Serialize)] pub struct Place { pub local: Local, /// projection out of a place (access a field, deref a pointer, etc) @@ -653,7 +656,7 @@ impl From for Place { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct ConstOperand { pub span: Span, pub user_ty: Option, @@ -661,7 +664,7 @@ pub struct ConstOperand { } /// Debug information pertaining to a user variable. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct VarDebugInfo { /// The variable name. pub name: Symbol, @@ -703,19 +706,19 @@ impl VarDebugInfo { pub type SourceScope = u32; -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct SourceInfo { pub span: Span, pub scope: SourceScope, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct VarDebugInfoFragment { pub ty: Ty, pub projection: Vec, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum VarDebugInfoContents { Place(Place), Const(ConstOperand), @@ -726,7 +729,7 @@ pub enum VarDebugInfoContents { // ProjectionElem) and user-provided type annotations (for which the projection elements // are of type ProjectionElem<(), ()>). In SMIR we don't need this generality, so we just use // ProjectionElem for Places. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum ProjectionElem { /// Dereference projections (e.g. `*_1`) project to the address referenced by the base place. Deref, @@ -800,7 +803,7 @@ pub enum ProjectionElem { Subtype(Ty), } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct UserTypeProjection { pub base: UserTypeAnnotationIndex, @@ -830,7 +833,7 @@ pub type FieldIdx = usize; type UserTypeAnnotationIndex = usize; /// The possible branch sites of a [TerminatorKind::SwitchInt]. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct SwitchTargets { /// The conditional branches where the first element represents the value that guards this /// branch, and the second element is the branch target. @@ -867,7 +870,7 @@ impl SwitchTargets { } } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub enum BorrowKind { /// Data must be immutable and is aliasable. Shared, @@ -894,14 +897,14 @@ impl BorrowKind { } } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub enum MutBorrowKind { Default, TwoPhaseBorrow, ClosureCapture, } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub enum FakeBorrowKind { /// A shared (deep) borrow. Data must be immutable and is aliasable. Deep, @@ -912,19 +915,19 @@ pub enum FakeBorrowKind { Shallow, } -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub enum Mutability { Not, Mut, } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub enum Safety { Safe, Unsafe, } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub enum PointerCoercion { /// Go from a fn-item type to a fn-pointer type. ReifyFnPointer, @@ -951,7 +954,7 @@ pub enum PointerCoercion { Unsize, } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub enum CastKind { // FIXME(smir-rename): rename this to PointerExposeProvenance PointerExposeAddress, @@ -967,7 +970,7 @@ pub enum CastKind { Transmute, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum NullOp { /// Returns the size of a value of that type. SizeOf, diff --git a/compiler/stable_mir/src/mir/mono.rs b/compiler/stable_mir/src/mir/mono.rs index 572f1499c5a5c..cd02844453112 100644 --- a/compiler/stable_mir/src/mir/mono.rs +++ b/compiler/stable_mir/src/mir/mono.rs @@ -1,19 +1,22 @@ +use std::fmt::{Debug, Formatter}; +use std::io; + +use serde::Serialize; + use crate::abi::FnAbi; use crate::crate_def::CrateDef; use crate::mir::Body; use crate::ty::{Allocation, ClosureDef, ClosureKind, FnDef, GenericArgs, IndexedVal, Ty}; use crate::{with, CrateItem, DefId, Error, ItemKind, Opaque, Symbol}; -use std::fmt::{Debug, Formatter}; -use std::io; -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub enum MonoItem { Fn(Instance), Static(StaticDef), GlobalAsm(Opaque), } -#[derive(Copy, Clone, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, PartialEq, Eq, Hash, Serialize)] pub struct Instance { /// The type of instance. pub kind: InstanceKind, @@ -22,7 +25,7 @@ pub struct Instance { pub def: InstanceDef, } -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub enum InstanceKind { /// A user defined item. Item, @@ -240,7 +243,7 @@ impl From for CrateItem { } } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] pub struct InstanceDef(usize); impl CrateDef for InstanceDef { @@ -251,6 +254,7 @@ impl CrateDef for InstanceDef { crate_def! { /// Holds information about a static variable definition. + #[derive(Serialize)] pub StaticDef; } diff --git a/compiler/stable_mir/src/mir/pretty.rs b/compiler/stable_mir/src/mir/pretty.rs index 18ecccb453663..dec0068ef7ef2 100644 --- a/compiler/stable_mir/src/mir/pretty.rs +++ b/compiler/stable_mir/src/mir/pretty.rs @@ -1,14 +1,13 @@ -use crate::mir::{Operand, Place, Rvalue, StatementKind, UnwindAction, VarDebugInfoContents}; -use crate::ty::{IndexedVal, MirConst, Ty, TyConst}; -use crate::{with, Body, Mutability}; -use fmt::{Display, Formatter}; use std::fmt::Debug; use std::io::Write; use std::{fmt, io, iter}; -use super::{AssertMessage, BinOp, TerminatorKind}; +use fmt::{Display, Formatter}; -use super::{BorrowKind, FakeBorrowKind}; +use super::{AssertMessage, BinOp, BorrowKind, FakeBorrowKind, TerminatorKind}; +use crate::mir::{Operand, Place, Rvalue, StatementKind, UnwindAction, VarDebugInfoContents}; +use crate::ty::{IndexedVal, MirConst, Ty, TyConst}; +use crate::{with, Body, Mutability}; impl Display for Ty { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { diff --git a/compiler/stable_mir/src/target.rs b/compiler/stable_mir/src/target.rs index e00a418c54039..32c3a2a9122e3 100644 --- a/compiler/stable_mir/src/target.rs +++ b/compiler/stable_mir/src/target.rs @@ -1,9 +1,11 @@ //! Provide information about the machine that this is being compiled into. +use serde::Serialize; + use crate::compiler_interface::with; /// The properties of the target machine being compiled into. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Serialize)] pub struct MachineInfo { pub endian: Endian, pub pointer_width: MachineSize, @@ -23,14 +25,14 @@ impl MachineInfo { } } -#[derive(Copy, Clone, PartialEq, Eq)] +#[derive(Copy, Clone, PartialEq, Eq, Serialize)] pub enum Endian { Little, Big, } /// Represent the size of a component. -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Serialize)] pub struct MachineSize { num_bits: usize, } diff --git a/compiler/stable_mir/src/ty.rs b/compiler/stable_mir/src/ty.rs index 9b912d1607426..2f36aa5182965 100644 --- a/compiler/stable_mir/src/ty.rs +++ b/compiler/stable_mir/src/ty.rs @@ -1,17 +1,18 @@ -use super::{ - mir::{Body, Mutability, Safety}, - with, DefId, Error, Symbol, -}; +use std::fmt::{self, Debug, Display, Formatter}; +use std::ops::Range; + +use serde::Serialize; + +use super::mir::{Body, Mutability, Safety}; +use super::{with, DefId, Error, Symbol}; use crate::abi::{FnAbi, Layout}; use crate::crate_def::{CrateDef, CrateDefType}; use crate::mir::alloc::{read_target_int, read_target_uint, AllocId}; use crate::mir::mono::StaticDef; use crate::target::MachineInfo; use crate::{Filename, Opaque}; -use std::fmt::{self, Debug, Display, Formatter}; -use std::ops::Range; -#[derive(Copy, Clone, Eq, PartialEq, Hash)] +#[derive(Copy, Clone, Eq, PartialEq, Hash, Serialize)] pub struct Ty(usize); impl Debug for Ty { @@ -100,13 +101,13 @@ impl Ty { } /// Represents a pattern in the type system -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum Pattern { Range { start: Option, end: Option, include_end: bool }, } /// Represents a constant in the type system -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct TyConst { pub(crate) kind: TyConstKind, pub id: TyConstId, @@ -133,7 +134,7 @@ impl TyConst { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum TyConstKind { Param(ParamConst), Bound(DebruijnIndex, BoundVar), @@ -144,11 +145,11 @@ pub enum TyConstKind { ZSTValue(Ty), } -#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize)] pub struct TyConstId(usize); /// Represents a constant in MIR -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct MirConst { /// The constant kind. pub(crate) kind: ConstantKind, @@ -205,17 +206,17 @@ impl MirConst { } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] pub struct MirConstId(usize); type Ident = Opaque; -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct Region { pub kind: RegionKind, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum RegionKind { ReEarlyParam(EarlyParamRegion), ReBound(DebruijnIndex, BoundRegion), @@ -226,7 +227,7 @@ pub enum RegionKind { pub(crate) type DebruijnIndex = u32; -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct EarlyParamRegion { pub index: u32, pub name: Symbol, @@ -234,7 +235,7 @@ pub struct EarlyParamRegion { pub(crate) type BoundVar = u32; -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct BoundRegion { pub var: BoundVar, pub kind: BoundRegionKind, @@ -242,13 +243,13 @@ pub struct BoundRegion { pub(crate) type UniverseIndex = u32; -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct Placeholder { pub universe: UniverseIndex, pub bound: T, } -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy, PartialEq, Eq, Serialize)] pub struct Span(usize); impl Debug for Span { @@ -272,7 +273,7 @@ impl Span { } } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, Serialize)] /// Information you get from `Span` in a struct form. /// Line and col start from 1. pub struct LineInfo { @@ -282,7 +283,7 @@ pub struct LineInfo { pub end_col: usize, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum TyKind { RigidTy(RigidTy), Alias(AliasKind, AliasTy), @@ -521,7 +522,7 @@ pub struct TypeAndMut { pub mutability: Mutability, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum RigidTy { Bool, Char, @@ -560,7 +561,7 @@ impl From for TyKind { } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] pub enum IntTy { Isize, I8, @@ -583,7 +584,7 @@ impl IntTy { } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] pub enum UintTy { Usize, U8, @@ -606,7 +607,7 @@ impl UintTy { } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] pub enum FloatTy { F16, F32, @@ -614,13 +615,14 @@ pub enum FloatTy { F128, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] pub enum Movability { Static, Movable, } crate_def! { + #[derive(Serialize)] pub ForeignModuleDef; } @@ -643,6 +645,7 @@ impl ForeignModule { crate_def_with_ty! { /// Hold information about a ForeignItem in a crate. + #[derive(Serialize)] pub ForeignDef; } @@ -652,7 +655,7 @@ impl ForeignDef { } } -#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Serialize)] pub enum ForeignItemKind { Fn(FnDef), Static(StaticDef), @@ -661,6 +664,7 @@ pub enum ForeignItemKind { crate_def_with_ty! { /// Hold information about a function definition in a crate. + #[derive(Serialize)] pub FnDef; } @@ -694,6 +698,7 @@ impl FnDef { } crate_def_with_ty! { + #[derive(Serialize)] pub IntrinsicDef; } @@ -718,26 +723,31 @@ impl From for FnDef { } crate_def! { + #[derive(Serialize)] pub ClosureDef; } crate_def! { + #[derive(Serialize)] pub CoroutineDef; } crate_def! { + #[derive(Serialize)] pub ParamDef; } crate_def! { + #[derive(Serialize)] pub BrNamedDef; } -crate_def_with_ty! { +crate_def! { + #[derive(Serialize)] pub AdtDef; } -#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Serialize)] pub enum AdtKind { Enum, Union, @@ -791,7 +801,7 @@ impl AdtDef { } /// Definition of a variant, which can be either a struct / union field or an enum variant. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] pub struct VariantDef { /// The variant index. /// @@ -820,7 +830,7 @@ impl VariantDef { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct FieldDef { /// The field definition. /// @@ -871,11 +881,13 @@ impl AdtKind { } crate_def! { + #[derive(Serialize)] pub AliasDef; } crate_def! { /// A trait's definition. + #[derive(Serialize)] pub TraitDef; } @@ -886,15 +898,18 @@ impl TraitDef { } crate_def! { + #[derive(Serialize)] pub GenericDef; } crate_def_with_ty! { + #[derive(Serialize)] pub ConstDef; } crate_def! { /// A trait impl definition. + #[derive(Serialize)] pub ImplDef; } @@ -906,15 +921,17 @@ impl ImplDef { } crate_def! { + #[derive(Serialize)] pub RegionDef; } crate_def! { + #[derive(Serialize)] pub CoroutineWitnessDef; } /// A list of generic arguments. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct GenericArgs(pub Vec); impl std::ops::Index for GenericArgs { @@ -933,7 +950,7 @@ impl std::ops::Index for GenericArgs { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum GenericArgKind { Lifetime(Region), Type(Ty), @@ -970,13 +987,13 @@ impl GenericArgKind { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum TermKind { Type(Ty), Const(TyConst), } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum AliasKind { Projection, Inherent, @@ -984,13 +1001,13 @@ pub enum AliasKind { Weak, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct AliasTy { pub def_id: AliasDef, pub args: GenericArgs, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct AliasTerm { pub def_id: AliasDef, pub args: GenericArgs, @@ -1008,7 +1025,7 @@ impl PolyFnSig { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct FnSig { pub inputs_and_output: Vec, pub c_variadic: bool, @@ -1026,7 +1043,7 @@ impl FnSig { } } -#[derive(Clone, PartialEq, Eq, Debug)] +#[derive(Clone, PartialEq, Eq, Debug, Serialize)] pub enum Abi { Rust, C { unwind: bool }, @@ -1055,7 +1072,7 @@ pub enum Abi { } /// A binder represents a possibly generic type and its bound vars. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct Binder { pub value: T, pub bound_vars: Vec, @@ -1095,38 +1112,38 @@ impl Binder { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct EarlyBinder { pub value: T, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum BoundVariableKind { Ty(BoundTyKind), Region(BoundRegionKind), Const, } -#[derive(Clone, PartialEq, Eq, Debug)] +#[derive(Clone, PartialEq, Eq, Debug, Serialize)] pub enum BoundTyKind { Anon, Param(ParamDef, String), } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum BoundRegionKind { BrAnon, BrNamed(BrNamedDef, String), BrEnv, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum DynKind { Dyn, DynStar, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum ExistentialPredicate { Trait(ExistentialTraitRef), Projection(ExistentialProjection), @@ -1136,7 +1153,7 @@ pub enum ExistentialPredicate { /// An existential reference to a trait where `Self` is not included. /// /// The `generic_args` will include any other known argument. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct ExistentialTraitRef { pub def_id: TraitDef, pub generic_args: GenericArgs, @@ -1154,20 +1171,20 @@ impl ExistentialTraitRef { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct ExistentialProjection { pub def_id: TraitDef, pub generic_args: GenericArgs, pub term: TermKind, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct ParamTy { pub index: u32, pub name: String, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct BoundTy { pub var: usize, pub kind: BoundTyKind, @@ -1178,7 +1195,7 @@ pub type Bytes = Vec>; /// Size in bytes. pub type Size = usize; -#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Serialize)] pub struct Prov(pub AllocId); pub type Align = u64; @@ -1186,14 +1203,14 @@ pub type Promoted = u32; pub type InitMaskMaterialized = Vec; /// Stores the provenance information of pointers stored in memory. -#[derive(Clone, Debug, Eq, PartialEq, Hash)] +#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)] pub struct ProvenanceMap { /// Provenance in this map applies from the given offset for an entire pointer-size worth of /// bytes. Two entries in this map are always at least a pointer size apart. pub ptrs: Vec<(Size, Prov)>, } -#[derive(Clone, Debug, Eq, PartialEq, Hash)] +#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize)] pub struct Allocation { pub bytes: Bytes, pub provenance: ProvenanceMap, @@ -1269,7 +1286,7 @@ impl Allocation { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum ConstantKind { Ty(TyConst), Allocated(Allocation), @@ -1280,27 +1297,27 @@ pub enum ConstantKind { ZeroSized, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct ParamConst { pub index: u32, pub name: String, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct UnevaluatedConst { pub def: ConstDef, pub args: GenericArgs, pub promoted: Option, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] pub enum TraitSpecializationKind { None, Marker, AlwaysApplicable, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct TraitDecl { pub def_id: TraitDef, pub safety: Safety, @@ -1333,7 +1350,7 @@ impl TraitDecl { pub type ImplTrait = EarlyBinder; /// A complete reference to a trait, i.e., one where `Self` is known. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct TraitRef { pub def_id: TraitDef, /// The generic arguments for this definition. @@ -1367,7 +1384,7 @@ impl TraitRef { } } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct Generics { pub parent: Option, pub parent_count: usize, @@ -1378,14 +1395,14 @@ pub struct Generics { pub host_effect_index: Option, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum GenericParamDefKind { Lifetime, Type { has_default: bool, synthetic: bool }, Const { has_default: bool }, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct GenericParamDef { pub name: super::Symbol, pub def_id: GenericDef, @@ -1399,7 +1416,7 @@ pub struct GenericPredicates { pub predicates: Vec<(PredicateKind, Span)>, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum PredicateKind { Clause(ClauseKind), ObjectSafe(TraitDef), @@ -1410,7 +1427,7 @@ pub enum PredicateKind { AliasRelate(TermKind, TermKind, AliasRelationDirection), } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum ClauseKind { Trait(TraitPredicate), RegionOutlives(RegionOutlivesPredicate), @@ -1421,57 +1438,57 @@ pub enum ClauseKind { ConstEvaluatable(TyConst), } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum ClosureKind { Fn, FnMut, FnOnce, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct SubtypePredicate { pub a: Ty, pub b: Ty, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct CoercePredicate { pub a: Ty, pub b: Ty, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum AliasRelationDirection { Equate, Subtype, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct TraitPredicate { pub trait_ref: TraitRef, pub polarity: PredicatePolarity, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct OutlivesPredicate(pub A, pub B); pub type RegionOutlivesPredicate = OutlivesPredicate; pub type TypeOutlivesPredicate = OutlivesPredicate; -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct ProjectionPredicate { pub projection_term: AliasTerm, pub term: TermKind, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum ImplPolarity { Positive, Negative, Reservation, } -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub enum PredicatePolarity { Positive, Negative, @@ -1514,7 +1531,7 @@ index_impl!(Span); /// `a` is in the variant with the `VariantIdx` of `0`, /// `c` is in the variant with the `VariantIdx` of `1`, and /// `g` is in the variant with the `VariantIdx` of `0`. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] pub struct VariantIdx(usize); index_impl!(VariantIdx); diff --git a/compiler/stable_mir/src/visitor.rs b/compiler/stable_mir/src/visitor.rs index fc1da8fafe486..72cf84acb856a 100644 --- a/compiler/stable_mir/src/visitor.rs +++ b/compiler/stable_mir/src/visitor.rs @@ -1,11 +1,11 @@ use std::ops::ControlFlow; -use crate::{ty::TyConst, Opaque}; - use super::ty::{ Allocation, Binder, ConstDef, ExistentialPredicate, FnSig, GenericArgKind, GenericArgs, MirConst, Promoted, Region, RigidTy, TermKind, Ty, UnevaluatedConst, }; +use crate::ty::TyConst; +use crate::Opaque; pub trait Visitor: Sized { type Break; diff --git a/config.example.toml b/config.example.toml index 26687bcfb370f..1a7bdc4737fbf 100644 --- a/config.example.toml +++ b/config.example.toml @@ -395,7 +395,7 @@ #metrics = false # Specify the location of the Android NDK. Used when targeting Android. -#android-ndk = "/path/to/android-ndk-r25b" +#android-ndk = "/path/to/android-ndk-r26d" # ============================================================================= # General install configuration options @@ -472,7 +472,8 @@ # This is mostly useful for tools; if you have changes to `compiler/` or `library/` they will be ignored. # # Set this to "if-unchanged" to only download if the compiler and standard library have not been modified. -# Set this to `true` to download unconditionally (useful if e.g. you are only changing doc-comments). +# Set this to `true` to download unconditionally. This is useful if you are working on tools, doc-comments, +# or library (you will be able to build the standard library without needing to build the compiler). #download-rustc = false # Number of codegen units to use for each compiler invocation. A value of 0 @@ -578,7 +579,10 @@ # The "channel" for the Rust build to produce. The stable/beta channels only # allow using stable features, whereas the nightly and dev channels allow using # nightly features -#channel = "dev" +# +# If using tarball sources, default value for `channel` is taken from the `src/ci/channel` file; +# otherwise, it's "dev". +#channel = if "is a tarball source" { content of `src/ci/channel` file } else { "dev" } # A descriptive string to be appended to `rustc --version` output, which is # also used in places like debuginfo `DW_AT_producer`. This may be useful for diff --git a/library/Cargo.lock b/library/Cargo.lock new file mode 100644 index 0000000000000..223b61456c267 --- /dev/null +++ b/library/Cargo.lock @@ -0,0 +1,489 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "addr2line" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" +dependencies = [ + "compiler_builtins", + "gimli 0.29.0", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-core", +] + +[[package]] +name = "alloc" +version = "0.0.0" +dependencies = [ + "compiler_builtins", + "core", + "rand", + "rand_xorshift", +] + +[[package]] +name = "allocator-api2" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" + +[[package]] +name = "cc" +version = "1.0.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c51067fd44124faa7f870b4b1c969379ad32b2ba805aa959430ceaa384f695" + +[[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.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb58b199190fcfe0846f55a3b545cd6b07a34bdd5930a476ff856f3ebcc5558a" +dependencies = [ + "cc", + "rustc-std-workspace-core", +] + +[[package]] +name = "core" +version = "0.0.0" +dependencies = [ + "rand", + "rand_xorshift", +] + +[[package]] +name = "dlmalloc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3264b043b8e977326c1ee9e723da2c1f8d09a99df52cacf00b4dbce5ac54414d" +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.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "gimli" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "allocator-api2", + "compiler_builtins", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "libc" +version = "0.2.155" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" +dependencies = [ + "rustc-std-workspace-core", +] + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-core", +] + +[[package]] +name = "miniz_oxide" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" +dependencies = [ + "adler", + "compiler_builtins", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "object" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f203fa8daa7bb185f760ae12bd8e097f63d17041dcdcaf675ac54cdf863170e" +dependencies = [ + "compiler_builtins", + "memchr", + "rustc-std-workspace-alloc", + "rustc-std-workspace-core", +] + +[[package]] +name = "panic_abort" +version = "0.0.0" +dependencies = [ + "alloc", + "cfg-if", + "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", + "std", +] + +[[package]] +name = "profiler_builtins" +version = "0.0.0" +dependencies = [ + "cc", + "compiler_builtins", + "core", +] + +[[package]] +name = "r-efi" +version = "4.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9e935efc5854715dfc0a4c9ef18dc69dee0ec3bf9cc3ab740db831c0fdd86a3" +dependencies = [ + "compiler_builtins", + "rustc-std-workspace-core", +] + +[[package]] +name = "r-efi-alloc" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31d6f09fe2b6ad044bc3d2c34ce4979796581afd2f1ebc185837e02421e02fd7" +dependencies = [ + "compiler_builtins", + "r-efi", + "rustc-std-workspace-core", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "rand_xorshift" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f" +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-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 = "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", + "profiler_builtins", + "r-efi", + "r-efi-alloc", + "rand", + "rand_xorshift", + "rustc-demangle", + "std_detect", + "unwind", + "wasi", +] + +[[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", + "std", + "test", +] + +[[package]] +name = "test" +version = "0.0.0" +dependencies = [ + "core", + "getopts", + "libc", + "std", +] + +[[package]] +name = "unicode-width" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d" +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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37a19a21a537f635c16c7576f22d0f2f7d63353c1337ad4ce0d8001c7952a25b" +dependencies = [ + "compiler_builtins", + "gimli 0.28.1", + "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.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" +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.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" diff --git a/library/Cargo.toml b/library/Cargo.toml new file mode 100644 index 0000000000000..c4513b4c127d8 --- /dev/null +++ b/library/Cargo.toml @@ -0,0 +1,44 @@ +[workspace] +resolver = "1" +members = [ + "std", + "sysroot", +] + +exclude = [ + # stdarch has its own Cargo workspace + "stdarch", +] + +[profile.release.package.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. +codegen-units = 10000 + +# These dependencies of the standard library implement symbolication for +# backtraces on most platforms. Their debuginfo causes both linking to be slower +# (more data to chew through) and binaries to be larger without really all that +# much benefit. This section turns them all to down to have no debuginfo which +# helps to improve link times a little bit. +[profile.release.package] +addr2line.debug = 0 +adler.debug = 0 +gimli.debug = 0 +miniz_oxide.debug = 0 +object.debug = 0 +rustc-demangle.debug = 0 + +[patch.crates-io] +# See comments in `library/rustc-std-workspace-core/README.md` for what's going on +# here +rustc-std-workspace-core = { path = 'rustc-std-workspace-core' } +rustc-std-workspace-alloc = { path = 'rustc-std-workspace-alloc' } +rustc-std-workspace-std = { path = 'rustc-std-workspace-std' } diff --git a/library/alloc/Cargo.toml b/library/alloc/Cargo.toml index 612452a960a37..479eb0a2ba743 100644 --- a/library/alloc/Cargo.toml +++ b/library/alloc/Cargo.toml @@ -10,7 +10,10 @@ edition = "2021" [dependencies] core = { path = "../core" } -compiler_builtins = { version = "0.1.40", features = ['rustc-dep-of-std'] } +compiler_builtins = { version = "0.1.114", features = ['rustc-dep-of-std'] } + +[target.'cfg(not(any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")))'.dependencies] +compiler_builtins = { version = "0.1.114", features = ["no-f16-f128"] } [dev-dependencies] rand = { version = "0.8.5", default-features = false, features = ["alloc"] } @@ -38,8 +41,8 @@ harness = false compiler-builtins-mem = ['compiler_builtins/mem'] compiler-builtins-c = ["compiler_builtins/c"] compiler-builtins-no-asm = ["compiler_builtins/no-asm"] +compiler-builtins-no-f16-f128 = ["compiler_builtins/no-f16-f128"] compiler-builtins-mangled-names = ["compiler_builtins/mangled-names"] -compiler-builtins-weak-intrinsics = ["compiler_builtins/weak-intrinsics"] # Make panics and failed asserts immediately abort without formatting any message panic_immediate_abort = ["core/panic_immediate_abort"] # Choose algorithms that are optimized for binary size instead of runtime performance diff --git a/library/alloc/benches/btree/map.rs b/library/alloc/benches/btree/map.rs index 4fe07eb02139f..3bddef5045a00 100644 --- a/library/alloc/benches/btree/map.rs +++ b/library/alloc/benches/btree/map.rs @@ -1,7 +1,8 @@ use std::collections::BTreeMap; use std::ops::RangeBounds; -use rand::{seq::SliceRandom, Rng}; +use rand::seq::SliceRandom; +use rand::Rng; use test::{black_box, Bencher}; macro_rules! map_insert_rand_bench { diff --git a/library/alloc/benches/linked_list.rs b/library/alloc/benches/linked_list.rs index 29c5ad2bc6eb2..b9322b6d4c3ea 100644 --- a/library/alloc/benches/linked_list.rs +++ b/library/alloc/benches/linked_list.rs @@ -1,4 +1,5 @@ use std::collections::LinkedList; + use test::Bencher; #[bench] diff --git a/library/alloc/benches/string.rs b/library/alloc/benches/string.rs index 5c95160ba2d14..e0dbe80d28896 100644 --- a/library/alloc/benches/string.rs +++ b/library/alloc/benches/string.rs @@ -1,4 +1,5 @@ use std::iter::repeat; + use test::{black_box, Bencher}; #[bench] diff --git a/library/alloc/benches/vec.rs b/library/alloc/benches/vec.rs index 8ebfe313dc5d5..13d784d3fd40e 100644 --- a/library/alloc/benches/vec.rs +++ b/library/alloc/benches/vec.rs @@ -1,5 +1,6 @@ -use rand::RngCore; use std::iter::repeat; + +use rand::RngCore; use test::{black_box, Bencher}; #[bench] diff --git a/library/alloc/benches/vec_deque.rs b/library/alloc/benches/vec_deque.rs index 35939f489b45d..fb1e2685cc333 100644 --- a/library/alloc/benches/vec_deque.rs +++ b/library/alloc/benches/vec_deque.rs @@ -1,7 +1,6 @@ -use std::{ - collections::{vec_deque, VecDeque}, - mem, -}; +use std::collections::{vec_deque, VecDeque}; +use std::mem; + use test::{black_box, Bencher}; #[bench] diff --git a/library/alloc/benches/vec_deque_append.rs b/library/alloc/benches/vec_deque_append.rs index 30b6e600e5adc..7c805da973763 100644 --- a/library/alloc/benches/vec_deque_append.rs +++ b/library/alloc/benches/vec_deque_append.rs @@ -1,4 +1,5 @@ -use std::{collections::VecDeque, time::Instant}; +use std::collections::VecDeque; +use std::time::Instant; const VECDEQUE_LEN: i32 = 100000; const WARMUP_N: usize = 100; diff --git a/library/alloc/src/alloc.rs b/library/alloc/src/alloc.rs index 1833a7f477f00..db2d752cfde1c 100644 --- a/library/alloc/src/alloc.rs +++ b/library/alloc/src/alloc.rs @@ -2,16 +2,14 @@ #![stable(feature = "alloc_module", since = "1.28.0")] +#[stable(feature = "alloc_module", since = "1.28.0")] +#[doc(inline)] +pub use core::alloc::*; #[cfg(not(test))] use core::hint; - #[cfg(not(test))] use core::ptr::{self, NonNull}; -#[stable(feature = "alloc_module", since = "1.28.0")] -#[doc(inline)] -pub use core::alloc::*; - #[cfg(test)] mod tests; @@ -57,7 +55,7 @@ pub struct Global; #[cfg(test)] pub use std::alloc::Global; -/// Allocate memory with the global allocator. +/// Allocates memory with the global allocator. /// /// This function forwards calls to the [`GlobalAlloc::alloc`] method /// of the allocator registered with the `#[global_allocator]` attribute @@ -101,7 +99,7 @@ pub unsafe fn alloc(layout: Layout) -> *mut u8 { } } -/// Deallocate memory with the global allocator. +/// Deallocates memory with the global allocator. /// /// This function forwards calls to the [`GlobalAlloc::dealloc`] method /// of the allocator registered with the `#[global_allocator]` attribute @@ -119,7 +117,7 @@ pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) { unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) } } -/// Reallocate memory with the global allocator. +/// Reallocates memory with the global allocator. /// /// This function forwards calls to the [`GlobalAlloc::realloc`] method /// of the allocator registered with the `#[global_allocator]` attribute @@ -138,7 +136,7 @@ pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) } } -/// Allocate zero-initialized memory with the global allocator. +/// Allocates zero-initialized memory with the global allocator. /// /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method /// of the allocator registered with the `#[global_allocator]` attribute @@ -345,7 +343,7 @@ extern "Rust" { fn __rust_alloc_error_handler(size: usize, align: usize) -> !; } -/// Signal a memory allocation error. +/// Signals a memory allocation error. /// /// Callers of memory allocation APIs wishing to cease execution /// in response to an allocation error are encouraged to call this function, diff --git a/library/alloc/src/alloc/tests.rs b/library/alloc/src/alloc/tests.rs index 1a5938fd34cf1..5d6077f057a2c 100644 --- a/library/alloc/src/alloc/tests.rs +++ b/library/alloc/src/alloc/tests.rs @@ -1,9 +1,10 @@ use super::*; extern crate test; -use crate::boxed::Box; use test::Bencher; +use crate::boxed::Box; + #[test] fn allocate_zeroed() { unsafe { diff --git a/library/alloc/src/borrow.rs b/library/alloc/src/borrow.rs index 42f8a08a9e4ee..f86face3f90cb 100644 --- a/library/alloc/src/borrow.rs +++ b/library/alloc/src/borrow.rs @@ -2,21 +2,20 @@ #![stable(feature = "rust1", since = "1.0.0")] +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::borrow::{Borrow, BorrowMut}; use core::cmp::Ordering; use core::hash::{Hash, Hasher}; #[cfg(not(no_global_oom_handling))] use core::ops::{Add, AddAssign}; use core::ops::{Deref, DerefPure}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::borrow::{Borrow, BorrowMut}; +use Cow::*; use crate::fmt; #[cfg(not(no_global_oom_handling))] use crate::string::String; -use Cow::*; - #[stable(feature = "rust1", since = "1.0.0")] impl<'a, B: ?Sized> Borrow for Cow<'a, B> where diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 405430377e551..38f50955b122e 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -187,26 +187,26 @@ use core::any::Any; use core::async_iter::AsyncIterator; -use core::borrow; #[cfg(not(no_global_oom_handling))] use core::clone::CloneToUninit; use core::cmp::Ordering; use core::error::Error; -use core::fmt; use core::future::Future; use core::hash::{Hash, Hasher}; use core::iter::FusedIterator; -use core::marker::Tuple; -use core::marker::Unsize; +use core::marker::{Tuple, Unsize}; use core::mem::{self, SizedTypeProperties}; -use core::ops::{AsyncFn, AsyncFnMut, AsyncFnOnce}; use core::ops::{ - CoerceUnsized, Coroutine, CoroutineState, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver, + AsyncFn, AsyncFnMut, AsyncFnOnce, CoerceUnsized, Coroutine, CoroutineState, Deref, DerefMut, + DerefPure, DispatchFromDyn, Receiver, }; use core::pin::Pin; use core::ptr::{self, addr_of_mut, NonNull, Unique}; -use core::slice; use core::task::{Context, Poll}; +use core::{borrow, fmt, slice}; + +#[unstable(feature = "thin_box", issue = "92791")] +pub use thin::ThinBox; #[cfg(not(no_global_oom_handling))] use crate::alloc::handle_alloc_error; @@ -222,9 +222,6 @@ use crate::vec; #[cfg(not(no_global_oom_handling))] use crate::vec::Vec; -#[unstable(feature = "thin_box", issue = "92791")] -pub use thin::ThinBox; - mod thin; /// A pointer type that uniquely owns a heap allocation of type `T`. @@ -1176,6 +1173,7 @@ impl Box { /// ``` /// /// [memory layout]: self#memory-layout + #[must_use = "losing the pointer will leak memory"] #[stable(feature = "box_raw", since = "1.4.0")] #[inline] pub fn into_raw(b: Self) -> *mut T { @@ -1229,6 +1227,7 @@ impl Box { /// ``` /// /// [memory layout]: self#memory-layout + #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "allocator_api", issue = "32838")] #[inline] pub fn into_raw_with_allocator(b: Self) -> (*mut T, A) { @@ -1268,9 +1267,11 @@ impl Box { } /// Consumes and leaks the `Box`, returning a mutable reference, - /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime - /// `'a`. If the type has only static references, or none at all, then this - /// may be chosen to be `'static`. + /// `&'a mut T`. + /// + /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type + /// has only static references, or none at all, then this may be chosen to be + /// `'static`. /// /// This function is mainly useful for data that lives for the remainder of /// the program's life. Dropping the returned reference will cause a memory @@ -1853,7 +1854,7 @@ impl TryFrom> for Box<[T; N]> { } impl Box { - /// Attempt to downcast the box to a concrete type. + /// Attempts to downcast the box to a concrete type. /// /// # Examples /// @@ -1912,7 +1913,7 @@ impl Box { } impl Box { - /// Attempt to downcast the box to a concrete type. + /// Attempts to downcast the box to a concrete type. /// /// # Examples /// @@ -1971,7 +1972,7 @@ impl Box { } impl Box { - /// Attempt to downcast the box to a concrete type. + /// Attempts to downcast the box to a concrete type. /// /// # Examples /// diff --git a/library/alloc/src/boxed/thin.rs b/library/alloc/src/boxed/thin.rs index e9bfecba160a0..9baded3a52141 100644 --- a/library/alloc/src/boxed/thin.rs +++ b/library/alloc/src/boxed/thin.rs @@ -2,7 +2,6 @@ //! //! by matthieu-m -use crate::alloc::{self, Layout, LayoutError}; use core::error::Error; use core::fmt::{self, Debug, Display, Formatter}; #[cfg(not(no_global_oom_handling))] @@ -14,8 +13,9 @@ use core::mem; #[cfg(not(no_global_oom_handling))] use core::mem::SizedTypeProperties; use core::ops::{Deref, DerefMut}; -use core::ptr::Pointee; -use core::ptr::{self, NonNull}; +use core::ptr::{self, NonNull, Pointee}; + +use crate::alloc::{self, Layout, LayoutError}; /// ThinBox. /// diff --git a/library/alloc/src/collections/binary_heap/mod.rs b/library/alloc/src/collections/binary_heap/mod.rs index fe1ff24139554..cc5f33c368542 100644 --- a/library/alloc/src/collections/binary_heap/mod.rs +++ b/library/alloc/src/collections/binary_heap/mod.rs @@ -144,12 +144,11 @@ #![stable(feature = "rust1", since = "1.0.0")] use core::alloc::Allocator; -use core::fmt; use core::iter::{FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen}; use core::mem::{self, swap, ManuallyDrop}; use core::num::NonZero; use core::ops::{Deref, DerefMut}; -use core::ptr; +use core::{fmt, ptr}; use crate::alloc::Global; use crate::collections::TryReserveError; @@ -965,6 +964,7 @@ impl BinaryHeap { } /// Returns an iterator which retrieves elements in heap order. + /// /// This method consumes the original heap. /// /// # Examples @@ -1361,7 +1361,7 @@ struct Hole<'a, T: 'a> { } impl<'a, T> Hole<'a, T> { - /// Create a new `Hole` at index `pos`. + /// Creates a new `Hole` at index `pos`. /// /// Unsafe because pos must be within the data slice. #[inline] diff --git a/library/alloc/src/collections/binary_heap/tests.rs b/library/alloc/src/collections/binary_heap/tests.rs index d4bc6226a14a8..1cb07c6214953 100644 --- a/library/alloc/src/collections/binary_heap/tests.rs +++ b/library/alloc/src/collections/binary_heap/tests.rs @@ -1,7 +1,8 @@ +use std::panic::{catch_unwind, AssertUnwindSafe}; + use super::*; use crate::boxed::Box; use crate::testing::crash_test::{CrashTestDummy, Panic}; -use std::panic::{catch_unwind, AssertUnwindSafe}; #[test] fn test_iterator() { @@ -504,11 +505,12 @@ fn test_retain_catch_unwind() { #[cfg(not(target_os = "emscripten"))] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn panic_safe() { - use rand::seq::SliceRandom; use std::cmp; use std::panic::{self, AssertUnwindSafe}; use std::sync::atomic::{AtomicUsize, Ordering}; + use rand::seq::SliceRandom; + static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0); #[derive(Eq, PartialEq, Ord, Clone, Debug)] diff --git a/library/alloc/src/collections/btree/append.rs b/library/alloc/src/collections/btree/append.rs index b6989afb6255d..47372938fbeda 100644 --- a/library/alloc/src/collections/btree/append.rs +++ b/library/alloc/src/collections/btree/append.rs @@ -1,8 +1,9 @@ -use super::merge_iter::MergeIterInner; -use super::node::{self, Root}; use core::alloc::Allocator; use core::iter::FusedIterator; +use super::merge_iter::MergeIterInner; +use super::node::{self, Root}; + impl Root { /// Appends all key-value pairs from the union of two ascending iterators, /// incrementing a `length` variable along the way. The latter makes it diff --git a/library/alloc/src/collections/btree/fix.rs b/library/alloc/src/collections/btree/fix.rs index 91b61218005a6..4c1e19ead4031 100644 --- a/library/alloc/src/collections/btree/fix.rs +++ b/library/alloc/src/collections/btree/fix.rs @@ -1,7 +1,10 @@ -use super::map::MIN_LEN; -use super::node::{marker, ForceResult::*, Handle, LeftOrRight::*, NodeRef, Root}; use core::alloc::Allocator; +use super::map::MIN_LEN; +use super::node::ForceResult::*; +use super::node::LeftOrRight::*; +use super::node::{marker, Handle, NodeRef, Root}; + impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { /// Stocks up a possibly underfull node by merging with or stealing from a /// sibling. If successful but at the cost of shrinking the parent node, diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs index 3875f61efafdf..d84654e36d776 100644 --- a/library/alloc/src/collections/btree/map.rs +++ b/library/alloc/src/collections/btree/map.rs @@ -1,4 +1,3 @@ -use crate::vec::Vec; use core::borrow::Borrow; use core::cmp::Ordering; use core::error::Error; @@ -10,20 +9,21 @@ use core::mem::{self, ManuallyDrop}; use core::ops::{Bound, Index, RangeBounds}; use core::ptr; -use crate::alloc::{Allocator, Global}; - use super::borrow::DormantMutRef; use super::dedup_sorted_iter::DedupSortedIter; use super::navigate::{LazyLeafRange, LeafRange}; -use super::node::{self, marker, ForceResult::*, Handle, NodeRef, Root}; -use super::search::{SearchBound, SearchResult::*}; +use super::node::ForceResult::*; +use super::node::{self, marker, Handle, NodeRef, Root}; +use super::search::SearchBound; +use super::search::SearchResult::*; use super::set_val::SetValZST; +use crate::alloc::{Allocator, Global}; +use crate::vec::Vec; mod entry; #[stable(feature = "rust1", since = "1.0.0")] pub use entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry}; - use Entry::*; /// Minimum number of elements in a node that is not a root. @@ -2921,7 +2921,7 @@ impl<'a, K, V> Cursor<'a, K, V> { /// Returns a reference to the key and value of the next element without /// moving the cursor. /// - /// If the cursor is at the end of the map then `None` is returned + /// If the cursor is at the end of the map then `None` is returned. #[unstable(feature = "btree_cursors", issue = "107540")] pub fn peek_next(&self) -> Option<(&'a K, &'a V)> { self.clone().next() @@ -2963,7 +2963,7 @@ impl<'a, K, V, A> CursorMut<'a, K, V, A> { /// Returns a reference to the key and value of the next element without /// moving the cursor. /// - /// If the cursor is at the end of the map then `None` is returned + /// If the cursor is at the end of the map then `None` is returned. #[unstable(feature = "btree_cursors", issue = "107540")] pub fn peek_next(&mut self) -> Option<(&K, &mut V)> { let (k, v) = self.inner.peek_next()?; @@ -3061,7 +3061,7 @@ impl<'a, K, V, A> CursorMutKey<'a, K, V, A> { /// Returns a reference to the key and value of the next element without /// moving the cursor. /// - /// If the cursor is at the end of the map then `None` is returned + /// If the cursor is at the end of the map then `None` is returned. #[unstable(feature = "btree_cursors", issue = "107540")] pub fn peek_next(&mut self) -> Option<(&mut K, &mut V)> { let current = self.current.as_mut()?; diff --git a/library/alloc/src/collections/btree/map/entry.rs b/library/alloc/src/collections/btree/map/entry.rs index 66eb991c6d4b8..d128ad8ee5f6d 100644 --- a/library/alloc/src/collections/btree/map/entry.rs +++ b/library/alloc/src/collections/btree/map/entry.rs @@ -2,13 +2,12 @@ use core::fmt::{self, Debug}; use core::marker::PhantomData; use core::mem; -use crate::alloc::{Allocator, Global}; +use Entry::*; use super::super::borrow::DormantMutRef; use super::super::node::{marker, Handle, NodeRef}; use super::BTreeMap; - -use Entry::*; +use crate::alloc::{Allocator, Global}; /// A view into a single entry in a map, which may either be vacant or occupied. /// @@ -189,6 +188,7 @@ impl<'a, K: Ord, V, A: Allocator + Clone> Entry<'a, K, V, A> { } /// Ensures a value is in the entry by inserting, if empty, the result of the default function. + /// /// This method allows for generating key-derived values for insertion by providing the default /// function a reference to the key that was moved during the `.entry(key)` method call. /// diff --git a/library/alloc/src/collections/btree/map/tests.rs b/library/alloc/src/collections/btree/map/tests.rs index ba1f38dcc3e52..ff1254a5a0c42 100644 --- a/library/alloc/src/collections/btree/map/tests.rs +++ b/library/alloc/src/collections/btree/map/tests.rs @@ -1,3 +1,10 @@ +use core::assert_matches::assert_matches; +use std::iter; +use std::ops::Bound::{Excluded, Included, Unbounded}; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering::SeqCst; + use super::*; use crate::boxed::Box; use crate::fmt::Debug; @@ -6,11 +13,6 @@ use crate::string::{String, ToString}; use crate::testing::crash_test::{CrashTestDummy, Panic}; use crate::testing::ord_chaos::{Cyclic3, Governed, Governor}; use crate::testing::rng::DeterministicRng; -use core::assert_matches::assert_matches; -use std::iter; -use std::ops::Bound::{Excluded, Included, Unbounded}; -use std::panic::{catch_unwind, AssertUnwindSafe}; -use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; // Minimum number of elements to insert, to guarantee a tree with 2 levels, // i.e., a tree who's root is an internal node at height 1, with edges to leaf nodes. diff --git a/library/alloc/src/collections/btree/mem.rs b/library/alloc/src/collections/btree/mem.rs index e1363d1ae1f6b..d738c5c47b4cc 100644 --- a/library/alloc/src/collections/btree/mem.rs +++ b/library/alloc/src/collections/btree/mem.rs @@ -1,6 +1,4 @@ -use core::intrinsics; -use core::mem; -use core::ptr; +use core::{intrinsics, mem, ptr}; /// This replaces the value behind the `v` unique reference by calling the /// relevant function. diff --git a/library/alloc/src/collections/btree/navigate.rs b/library/alloc/src/collections/btree/navigate.rs index 5e6a26f65c41e..f5c621e2c1759 100644 --- a/library/alloc/src/collections/btree/navigate.rs +++ b/library/alloc/src/collections/btree/navigate.rs @@ -1,11 +1,10 @@ use core::borrow::Borrow; -use core::hint; use core::ops::RangeBounds; -use core::ptr; +use core::{hint, ptr}; -use super::node::{marker, ForceResult::*, Handle, NodeRef}; +use super::node::ForceResult::*; +use super::node::{marker, Handle, NodeRef}; use super::search::SearchBound; - use crate::alloc::Allocator; // `front` and `back` are always both `None` or both `Some`. pub struct LeafRange { diff --git a/library/alloc/src/collections/btree/remove.rs b/library/alloc/src/collections/btree/remove.rs index 0904299254f0a..c46422c2f1d45 100644 --- a/library/alloc/src/collections/btree/remove.rs +++ b/library/alloc/src/collections/btree/remove.rs @@ -1,7 +1,10 @@ -use super::map::MIN_LEN; -use super::node::{marker, ForceResult::*, Handle, LeftOrRight::*, NodeRef}; use core::alloc::Allocator; +use super::map::MIN_LEN; +use super::node::ForceResult::*; +use super::node::LeftOrRight::*; +use super::node::{marker, Handle, NodeRef}; + impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::KV> { /// Removes a key-value pair from the tree, and returns that pair, as well as /// the leaf edge corresponding to that former pair. It's possible this empties diff --git a/library/alloc/src/collections/btree/search.rs b/library/alloc/src/collections/btree/search.rs index ad3522b4e0418..1d5c927175ea6 100644 --- a/library/alloc/src/collections/btree/search.rs +++ b/library/alloc/src/collections/btree/search.rs @@ -2,11 +2,12 @@ use core::borrow::Borrow; use core::cmp::Ordering; use core::ops::{Bound, RangeBounds}; -use super::node::{marker, ForceResult::*, Handle, NodeRef}; - use SearchBound::*; use SearchResult::*; +use super::node::ForceResult::*; +use super::node::{marker, Handle, NodeRef}; + pub enum SearchBound { /// An inclusive bound to look for, just like `Bound::Included(T)`. Included(T), diff --git a/library/alloc/src/collections/btree/set.rs b/library/alloc/src/collections/btree/set.rs index b0bd6ef2d3c63..973e7c660670c 100644 --- a/library/alloc/src/collections/btree/set.rs +++ b/library/alloc/src/collections/btree/set.rs @@ -1,4 +1,3 @@ -use crate::vec::Vec; use core::borrow::Borrow; use core::cmp::Ordering::{self, Equal, Greater, Less}; use core::cmp::{max, min}; @@ -6,14 +5,14 @@ use core::fmt::{self, Debug}; use core::hash::{Hash, Hasher}; use core::iter::{FusedIterator, Peekable}; use core::mem::ManuallyDrop; -use core::ops::{BitAnd, BitOr, BitXor, RangeBounds, Sub}; +use core::ops::{BitAnd, BitOr, BitXor, Bound, RangeBounds, Sub}; use super::map::{BTreeMap, Keys}; use super::merge_iter::MergeIterInner; use super::set_val::SetValZST; use super::Recover; - use crate::alloc::{Allocator, Global}; +use crate::vec::Vec; /// An ordered set based on a B-Tree. /// @@ -1183,6 +1182,178 @@ impl BTreeSet { pub const fn is_empty(&self) -> bool { self.len() == 0 } + + /// Returns a [`Cursor`] pointing at the gap before the smallest element + /// greater than the given bound. + /// + /// Passing `Bound::Included(x)` will return a cursor pointing to the + /// gap before the smallest element greater than or equal to `x`. + /// + /// Passing `Bound::Excluded(x)` will return a cursor pointing to the + /// gap before the smallest element greater than `x`. + /// + /// Passing `Bound::Unbounded` will return a cursor pointing to the + /// gap before the smallest element in the set. + /// + /// # Examples + /// + /// ``` + /// #![feature(btree_cursors)] + /// + /// use std::collections::BTreeSet; + /// use std::ops::Bound; + /// + /// let set = BTreeSet::from([1, 2, 3, 4]); + /// + /// let cursor = set.lower_bound(Bound::Included(&2)); + /// assert_eq!(cursor.peek_prev(), Some(&1)); + /// assert_eq!(cursor.peek_next(), Some(&2)); + /// + /// let cursor = set.lower_bound(Bound::Excluded(&2)); + /// assert_eq!(cursor.peek_prev(), Some(&2)); + /// assert_eq!(cursor.peek_next(), Some(&3)); + /// + /// let cursor = set.lower_bound(Bound::Unbounded); + /// assert_eq!(cursor.peek_prev(), None); + /// assert_eq!(cursor.peek_next(), Some(&1)); + /// ``` + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn lower_bound(&self, bound: Bound<&Q>) -> Cursor<'_, T> + where + T: Borrow + Ord, + Q: Ord, + { + Cursor { inner: self.map.lower_bound(bound) } + } + + /// Returns a [`CursorMut`] pointing at the gap before the smallest element + /// greater than the given bound. + /// + /// Passing `Bound::Included(x)` will return a cursor pointing to the + /// gap before the smallest element greater than or equal to `x`. + /// + /// Passing `Bound::Excluded(x)` will return a cursor pointing to the + /// gap before the smallest element greater than `x`. + /// + /// Passing `Bound::Unbounded` will return a cursor pointing to the + /// gap before the smallest element in the set. + /// + /// # Examples + /// + /// ``` + /// #![feature(btree_cursors)] + /// + /// use std::collections::BTreeSet; + /// use std::ops::Bound; + /// + /// let mut set = BTreeSet::from([1, 2, 3, 4]); + /// + /// let mut cursor = set.lower_bound_mut(Bound::Included(&2)); + /// assert_eq!(cursor.peek_prev(), Some(&1)); + /// assert_eq!(cursor.peek_next(), Some(&2)); + /// + /// let mut cursor = set.lower_bound_mut(Bound::Excluded(&2)); + /// assert_eq!(cursor.peek_prev(), Some(&2)); + /// assert_eq!(cursor.peek_next(), Some(&3)); + /// + /// let mut cursor = set.lower_bound_mut(Bound::Unbounded); + /// assert_eq!(cursor.peek_prev(), None); + /// assert_eq!(cursor.peek_next(), Some(&1)); + /// ``` + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn lower_bound_mut(&mut self, bound: Bound<&Q>) -> CursorMut<'_, T, A> + where + T: Borrow + Ord, + Q: Ord, + { + CursorMut { inner: self.map.lower_bound_mut(bound) } + } + + /// Returns a [`Cursor`] pointing at the gap after the greatest element + /// smaller than the given bound. + /// + /// Passing `Bound::Included(x)` will return a cursor pointing to the + /// gap after the greatest element smaller than or equal to `x`. + /// + /// Passing `Bound::Excluded(x)` will return a cursor pointing to the + /// gap after the greatest element smaller than `x`. + /// + /// Passing `Bound::Unbounded` will return a cursor pointing to the + /// gap after the greatest element in the set. + /// + /// # Examples + /// + /// ``` + /// #![feature(btree_cursors)] + /// + /// use std::collections::BTreeSet; + /// use std::ops::Bound; + /// + /// let set = BTreeSet::from([1, 2, 3, 4]); + /// + /// let cursor = set.upper_bound(Bound::Included(&3)); + /// assert_eq!(cursor.peek_prev(), Some(&3)); + /// assert_eq!(cursor.peek_next(), Some(&4)); + /// + /// let cursor = set.upper_bound(Bound::Excluded(&3)); + /// assert_eq!(cursor.peek_prev(), Some(&2)); + /// assert_eq!(cursor.peek_next(), Some(&3)); + /// + /// let cursor = set.upper_bound(Bound::Unbounded); + /// assert_eq!(cursor.peek_prev(), Some(&4)); + /// assert_eq!(cursor.peek_next(), None); + /// ``` + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn upper_bound(&self, bound: Bound<&Q>) -> Cursor<'_, T> + where + T: Borrow + Ord, + Q: Ord, + { + Cursor { inner: self.map.upper_bound(bound) } + } + + /// Returns a [`CursorMut`] pointing at the gap after the greatest element + /// smaller than the given bound. + /// + /// Passing `Bound::Included(x)` will return a cursor pointing to the + /// gap after the greatest element smaller than or equal to `x`. + /// + /// Passing `Bound::Excluded(x)` will return a cursor pointing to the + /// gap after the greatest element smaller than `x`. + /// + /// Passing `Bound::Unbounded` will return a cursor pointing to the + /// gap after the greatest element in the set. + /// + /// # Examples + /// + /// ``` + /// #![feature(btree_cursors)] + /// + /// use std::collections::BTreeSet; + /// use std::ops::Bound; + /// + /// let mut set = BTreeSet::from([1, 2, 3, 4]); + /// + /// let mut cursor = unsafe { set.upper_bound_mut(Bound::Included(&3)) }; + /// assert_eq!(cursor.peek_prev(), Some(&3)); + /// assert_eq!(cursor.peek_next(), Some(&4)); + /// + /// let mut cursor = unsafe { set.upper_bound_mut(Bound::Excluded(&3)) }; + /// assert_eq!(cursor.peek_prev(), Some(&2)); + /// assert_eq!(cursor.peek_next(), Some(&3)); + /// + /// let mut cursor = unsafe { set.upper_bound_mut(Bound::Unbounded) }; + /// assert_eq!(cursor.peek_prev(), Some(&4)); + /// assert_eq!(cursor.peek_next(), None); + /// ``` + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn upper_bound_mut(&mut self, bound: Bound<&Q>) -> CursorMut<'_, T, A> + where + T: Borrow + Ord, + Q: Ord, + { + CursorMut { inner: self.map.upper_bound_mut(bound) } + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -1817,5 +1988,414 @@ impl<'a, T: Ord> Iterator for Union<'a, T> { #[stable(feature = "fused", since = "1.26.0")] impl FusedIterator for Union<'_, T> {} +/// A cursor over a `BTreeSet`. +/// +/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth. +/// +/// Cursors always point to a gap between two elements in the set, and can +/// operate on the two immediately adjacent elements. +/// +/// A `Cursor` is created with the [`BTreeSet::lower_bound`] and [`BTreeSet::upper_bound`] methods. +#[derive(Clone)] +#[unstable(feature = "btree_cursors", issue = "107540")] +pub struct Cursor<'a, K: 'a> { + inner: super::map::Cursor<'a, K, SetValZST>, +} + +#[unstable(feature = "btree_cursors", issue = "107540")] +impl Debug for Cursor<'_, K> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Cursor") + } +} + +/// A cursor over a `BTreeSet` with editing operations. +/// +/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can +/// safely mutate the set during iteration. This is because the lifetime of its yielded +/// references is tied to its own lifetime, instead of just the underlying map. This means +/// cursors cannot yield multiple elements at once. +/// +/// Cursors always point to a gap between two elements in the set, and can +/// operate on the two immediately adjacent elements. +/// +/// A `CursorMut` is created with the [`BTreeSet::lower_bound_mut`] and [`BTreeSet::upper_bound_mut`] +/// methods. +#[unstable(feature = "btree_cursors", issue = "107540")] +pub struct CursorMut<'a, K: 'a, #[unstable(feature = "allocator_api", issue = "32838")] A = Global> +{ + inner: super::map::CursorMut<'a, K, SetValZST, A>, +} + +#[unstable(feature = "btree_cursors", issue = "107540")] +impl Debug for CursorMut<'_, K, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CursorMut") + } +} + +/// A cursor over a `BTreeSet` with editing operations, and which allows +/// mutating elements. +/// +/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can +/// safely mutate the set during iteration. This is because the lifetime of its yielded +/// references is tied to its own lifetime, instead of just the underlying set. This means +/// cursors cannot yield multiple elements at once. +/// +/// Cursors always point to a gap between two elements in the set, and can +/// operate on the two immediately adjacent elements. +/// +/// A `CursorMutKey` is created from a [`CursorMut`] with the +/// [`CursorMut::with_mutable_key`] method. +/// +/// # Safety +/// +/// Since this cursor allows mutating elements, you must ensure that the +/// `BTreeSet` invariants are maintained. Specifically: +/// +/// * The newly inserted element must be unique in the tree. +/// * All elements in the tree must remain in sorted order. +#[unstable(feature = "btree_cursors", issue = "107540")] +pub struct CursorMutKey< + 'a, + K: 'a, + #[unstable(feature = "allocator_api", issue = "32838")] A = Global, +> { + inner: super::map::CursorMutKey<'a, K, SetValZST, A>, +} + +#[unstable(feature = "btree_cursors", issue = "107540")] +impl Debug for CursorMutKey<'_, K, A> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CursorMutKey") + } +} + +impl<'a, K> Cursor<'a, K> { + /// Advances the cursor to the next gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the end of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn next(&mut self) -> Option<&'a K> { + self.inner.next().map(|(k, _)| k) + } + + /// Advances the cursor to the previous gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the start of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn prev(&mut self) -> Option<&'a K> { + self.inner.prev().map(|(k, _)| k) + } + + /// Returns a reference to next element without moving the cursor. + /// + /// If the cursor is at the end of the set then `None` is returned + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_next(&self) -> Option<&'a K> { + self.inner.peek_next().map(|(k, _)| k) + } + + /// Returns a reference to the previous element without moving the cursor. + /// + /// If the cursor is at the start of the set then `None` is returned. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_prev(&self) -> Option<&'a K> { + self.inner.peek_prev().map(|(k, _)| k) + } +} + +impl<'a, T, A> CursorMut<'a, T, A> { + /// Advances the cursor to the next gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the end of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn next(&mut self) -> Option<&T> { + self.inner.next().map(|(k, _)| k) + } + + /// Advances the cursor to the previous gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the start of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn prev(&mut self) -> Option<&T> { + self.inner.prev().map(|(k, _)| k) + } + + /// Returns a reference to the next element without moving the cursor. + /// + /// If the cursor is at the end of the set then `None` is returned. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_next(&mut self) -> Option<&T> { + self.inner.peek_next().map(|(k, _)| k) + } + + /// Returns a reference to the previous element without moving the cursor. + /// + /// If the cursor is at the start of the set then `None` is returned. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_prev(&mut self) -> Option<&T> { + self.inner.peek_prev().map(|(k, _)| k) + } + + /// Returns a read-only cursor pointing to the same location as the + /// `CursorMut`. + /// + /// The lifetime of the returned `Cursor` is bound to that of the + /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the + /// `CursorMut` is frozen for the lifetime of the `Cursor`. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn as_cursor(&self) -> Cursor<'_, T> { + Cursor { inner: self.inner.as_cursor() } + } + + /// Converts the cursor into a [`CursorMutKey`], which allows mutating + /// elements in the tree. + /// + /// # Safety + /// + /// Since this cursor allows mutating elements, you must ensure that the + /// `BTreeSet` invariants are maintained. Specifically: + /// + /// * The newly inserted element must be unique in the tree. + /// * All elements in the tree must remain in sorted order. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, T, A> { + CursorMutKey { inner: unsafe { self.inner.with_mutable_key() } } + } +} + +impl<'a, T, A> CursorMutKey<'a, T, A> { + /// Advances the cursor to the next gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the end of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn next(&mut self) -> Option<&mut T> { + self.inner.next().map(|(k, _)| k) + } + + /// Advances the cursor to the previous gap, returning the element that it + /// moved over. + /// + /// If the cursor is already at the start of the set then `None` is returned + /// and the cursor is not moved. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn prev(&mut self) -> Option<&mut T> { + self.inner.prev().map(|(k, _)| k) + } + + /// Returns a reference to the next element without moving the cursor. + /// + /// If the cursor is at the end of the set then `None` is returned + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_next(&mut self) -> Option<&mut T> { + self.inner.peek_next().map(|(k, _)| k) + } + + /// Returns a reference to the previous element without moving the cursor. + /// + /// If the cursor is at the start of the set then `None` is returned. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn peek_prev(&mut self) -> Option<&mut T> { + self.inner.peek_prev().map(|(k, _)| k) + } + + /// Returns a read-only cursor pointing to the same location as the + /// `CursorMutKey`. + /// + /// The lifetime of the returned `Cursor` is bound to that of the + /// `CursorMutKey`, which means it cannot outlive the `CursorMutKey` and that the + /// `CursorMutKey` is frozen for the lifetime of the `Cursor`. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn as_cursor(&self) -> Cursor<'_, T> { + Cursor { inner: self.inner.as_cursor() } + } +} + +impl<'a, T: Ord, A: Allocator + Clone> CursorMut<'a, T, A> { + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap before the + /// newly inserted element. + /// + /// # Safety + /// + /// You must ensure that the `BTreeSet` invariants are maintained. + /// Specifically: + /// + /// * The newly inserted element must be unique in the tree. + /// * All elements in the tree must remain in sorted order. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn insert_after_unchecked(&mut self, value: T) { + unsafe { self.inner.insert_after_unchecked(value, SetValZST) } + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap after the + /// newly inserted element. + /// + /// # Safety + /// + /// You must ensure that the `BTreeSet` invariants are maintained. + /// Specifically: + /// + /// * The newly inserted element must be unique in the tree. + /// * All elements in the tree must remain in sorted order. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn insert_before_unchecked(&mut self, value: T) { + unsafe { self.inner.insert_before_unchecked(value, SetValZST) } + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap before the + /// newly inserted element. + /// + /// If the inserted element is not greater than the element before the + /// cursor (if any), or if it not less than the element after the cursor (if + /// any), then an [`UnorderedKeyError`] is returned since this would + /// invalidate the [`Ord`] invariant between the elements of the set. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn insert_after(&mut self, value: T) -> Result<(), UnorderedKeyError> { + self.inner.insert_after(value, SetValZST) + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap after the + /// newly inserted element. + /// + /// If the inserted element is not greater than the element before the + /// cursor (if any), or if it not less than the element after the cursor (if + /// any), then an [`UnorderedKeyError`] is returned since this would + /// invalidate the [`Ord`] invariant between the elements of the set. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn insert_before(&mut self, value: T) -> Result<(), UnorderedKeyError> { + self.inner.insert_before(value, SetValZST) + } + + /// Removes the next element from the `BTreeSet`. + /// + /// The element that was removed is returned. The cursor position is + /// unchanged (before the removed element). + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn remove_next(&mut self) -> Option { + self.inner.remove_next().map(|(k, _)| k) + } + + /// Removes the precending element from the `BTreeSet`. + /// + /// The element that was removed is returned. The cursor position is + /// unchanged (after the removed element). + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn remove_prev(&mut self) -> Option { + self.inner.remove_prev().map(|(k, _)| k) + } +} + +impl<'a, T: Ord, A: Allocator + Clone> CursorMutKey<'a, T, A> { + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap before the + /// newly inserted element. + /// + /// # Safety + /// + /// You must ensure that the `BTreeSet` invariants are maintained. + /// Specifically: + /// + /// * The key of the newly inserted element must be unique in the tree. + /// * All elements in the tree must remain in sorted order. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn insert_after_unchecked(&mut self, value: T) { + unsafe { self.inner.insert_after_unchecked(value, SetValZST) } + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap after the + /// newly inserted element. + /// + /// # Safety + /// + /// You must ensure that the `BTreeSet` invariants are maintained. + /// Specifically: + /// + /// * The newly inserted element must be unique in the tree. + /// * All elements in the tree must remain in sorted order. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub unsafe fn insert_before_unchecked(&mut self, value: T) { + unsafe { self.inner.insert_before_unchecked(value, SetValZST) } + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap before the + /// newly inserted element. + /// + /// If the inserted element is not greater than the element before the + /// cursor (if any), or if it not less than the element after the cursor (if + /// any), then an [`UnorderedKeyError`] is returned since this would + /// invalidate the [`Ord`] invariant between the elements of the set. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn insert_after(&mut self, value: T) -> Result<(), UnorderedKeyError> { + self.inner.insert_after(value, SetValZST) + } + + /// Inserts a new element into the set in the gap that the + /// cursor is currently pointing to. + /// + /// After the insertion the cursor will be pointing at the gap after the + /// newly inserted element. + /// + /// If the inserted element is not greater than the element before the + /// cursor (if any), or if it not less than the element after the cursor (if + /// any), then an [`UnorderedKeyError`] is returned since this would + /// invalidate the [`Ord`] invariant between the elements of the set. + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn insert_before(&mut self, value: T) -> Result<(), UnorderedKeyError> { + self.inner.insert_before(value, SetValZST) + } + + /// Removes the next element from the `BTreeSet`. + /// + /// The element that was removed is returned. The cursor position is + /// unchanged (before the removed element). + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn remove_next(&mut self) -> Option { + self.inner.remove_next().map(|(k, _)| k) + } + + /// Removes the precending element from the `BTreeSet`. + /// + /// The element that was removed is returned. The cursor position is + /// unchanged (after the removed element). + #[unstable(feature = "btree_cursors", issue = "107540")] + pub fn remove_prev(&mut self) -> Option { + self.inner.remove_prev().map(|(k, _)| k) + } +} + +#[unstable(feature = "btree_cursors", issue = "107540")] +pub use super::map::UnorderedKeyError; + #[cfg(test)] mod tests; diff --git a/library/alloc/src/collections/btree/set/tests.rs b/library/alloc/src/collections/btree/set/tests.rs index 48bf767413835..f947b6108c9a7 100644 --- a/library/alloc/src/collections/btree/set/tests.rs +++ b/library/alloc/src/collections/btree/set/tests.rs @@ -1,8 +1,9 @@ +use std::ops::Bound::{Excluded, Included}; +use std::panic::{catch_unwind, AssertUnwindSafe}; + use super::*; use crate::testing::crash_test::{CrashTestDummy, Panic}; use crate::testing::rng::DeterministicRng; -use std::ops::Bound::{Excluded, Included}; -use std::panic::{catch_unwind, AssertUnwindSafe}; #[test] fn test_clone_eq() { diff --git a/library/alloc/src/collections/btree/split.rs b/library/alloc/src/collections/btree/split.rs index 638dc98fc3e41..c188ed1da6113 100644 --- a/library/alloc/src/collections/btree/split.rs +++ b/library/alloc/src/collections/btree/split.rs @@ -1,8 +1,10 @@ -use super::node::{ForceResult::*, Root}; -use super::search::SearchResult::*; use core::alloc::Allocator; use core::borrow::Borrow; +use super::node::ForceResult::*; +use super::node::Root; +use super::search::SearchResult::*; + impl Root { /// Calculates the length of both trees that result from splitting up /// a given number of distinct key-value pairs. diff --git a/library/alloc/src/collections/linked_list.rs b/library/alloc/src/collections/linked_list.rs index 077483a174b10..0cd410c0fb7c1 100644 --- a/library/alloc/src/collections/linked_list.rs +++ b/library/alloc/src/collections/linked_list.rs @@ -13,12 +13,11 @@ #![stable(feature = "rust1", since = "1.0.0")] use core::cmp::Ordering; -use core::fmt; use core::hash::{Hash, Hasher}; use core::iter::FusedIterator; use core::marker::PhantomData; -use core::mem; use core::ptr::NonNull; +use core::{fmt, mem}; use super::SpecExtend; use crate::alloc::{Allocator, Global}; diff --git a/library/alloc/src/collections/linked_list/tests.rs b/library/alloc/src/collections/linked_list/tests.rs index d3744c5a9d0c9..9b3c9ac5ce52e 100644 --- a/library/alloc/src/collections/linked_list/tests.rs +++ b/library/alloc/src/collections/linked_list/tests.rs @@ -1,12 +1,12 @@ -use super::*; -use crate::testing::crash_test::{CrashTestDummy, Panic}; -use crate::vec::Vec; - use std::panic::{catch_unwind, AssertUnwindSafe}; use std::thread; use rand::RngCore; +use super::*; +use crate::testing::crash_test::{CrashTestDummy, Panic}; +use crate::vec::Vec; + #[test] fn test_basic() { let mut m = LinkedList::>::new(); @@ -1167,9 +1167,7 @@ fn test_drop_panic() { #[test] fn test_allocator() { - use core::alloc::AllocError; - use core::alloc::Allocator; - use core::alloc::Layout; + use core::alloc::{AllocError, Allocator, Layout}; use core::cell::Cell; struct A { diff --git a/library/alloc/src/collections/mod.rs b/library/alloc/src/collections/mod.rs index 705b81535c279..020cf4d736510 100644 --- a/library/alloc/src/collections/mod.rs +++ b/library/alloc/src/collections/mod.rs @@ -27,33 +27,30 @@ pub mod btree_set { pub use super::btree::set::*; } +use core::fmt::Display; + #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use binary_heap::BinaryHeap; - #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use btree_map::BTreeMap; - #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use btree_set::BTreeSet; - #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use linked_list::LinkedList; - #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] pub use vec_deque::VecDeque; use crate::alloc::{Layout, LayoutError}; -use core::fmt::Display; /// The error type for `try_reserve` methods. #[derive(Clone, PartialEq, Eq, Debug)] diff --git a/library/alloc/src/collections/vec_deque/drain.rs b/library/alloc/src/collections/vec_deque/drain.rs index 1373e60149274..44fcef4ed7dc4 100644 --- a/library/alloc/src/collections/vec_deque/drain.rs +++ b/library/alloc/src/collections/vec_deque/drain.rs @@ -4,9 +4,8 @@ use core::mem::{self, SizedTypeProperties}; use core::ptr::NonNull; use core::{fmt, ptr}; -use crate::alloc::{Allocator, Global}; - use super::VecDeque; +use crate::alloc::{Allocator, Global}; /// A draining iterator over the elements of a `VecDeque`. /// diff --git a/library/alloc/src/collections/vec_deque/into_iter.rs b/library/alloc/src/collections/vec_deque/into_iter.rs index 4747517393c66..2d283dac9a97a 100644 --- a/library/alloc/src/collections/vec_deque/into_iter.rs +++ b/library/alloc/src/collections/vec_deque/into_iter.rs @@ -1,10 +1,11 @@ use core::iter::{FusedIterator, TrustedLen}; +use core::mem::MaybeUninit; use core::num::NonZero; -use core::{array, fmt, mem::MaybeUninit, ops::Try, ptr}; - -use crate::alloc::{Allocator, Global}; +use core::ops::Try; +use core::{array, fmt, ptr}; use super::VecDeque; +use crate::alloc::{Allocator, Global}; /// An owning iterator over the elements of a `VecDeque`. /// diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index a07f250d7d88c..dc725ec0f56e4 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -8,23 +8,19 @@ #![stable(feature = "rust1", since = "1.0.0")] use core::cmp::{self, Ordering}; -use core::fmt; use core::hash::{Hash, Hasher}; use core::iter::{repeat_n, repeat_with, ByRefSized}; -use core::mem::{ManuallyDrop, SizedTypeProperties}; -use core::ops::{Index, IndexMut, Range, RangeBounds}; -use core::ptr; -use core::slice; - // This is used in a bunch of intra-doc links. // FIXME: For some reason, `#[cfg(doc)]` wasn't sufficient, resulting in // failures in linkchecker even though rustdoc built the docs just fine. #[allow(unused_imports)] use core::mem; +use core::mem::{ManuallyDrop, SizedTypeProperties}; +use core::ops::{Index, IndexMut, Range, RangeBounds}; +use core::{fmt, ptr, slice}; use crate::alloc::{Allocator, Global}; -use crate::collections::TryReserveError; -use crate::collections::TryReserveErrorKind; +use crate::collections::{TryReserveError, TryReserveErrorKind}; use crate::raw_vec::RawVec; use crate::vec::Vec; diff --git a/library/alloc/src/collections/vec_deque/spec_extend.rs b/library/alloc/src/collections/vec_deque/spec_extend.rs index 6a89abc3ef9b6..a9b0fd073b548 100644 --- a/library/alloc/src/collections/vec_deque/spec_extend.rs +++ b/library/alloc/src/collections/vec_deque/spec_extend.rs @@ -1,9 +1,9 @@ -use crate::alloc::Allocator; -use crate::vec; use core::iter::TrustedLen; use core::slice; use super::VecDeque; +use crate::alloc::Allocator; +use crate::vec; // Specialization trait used for VecDeque::extend pub(super) trait SpecExtend { diff --git a/library/alloc/src/ffi/c_str.rs b/library/alloc/src/ffi/c_str.rs index f1eb195b88462..e32676a65432b 100644 --- a/library/alloc/src/ffi/c_str.rs +++ b/library/alloc/src/ffi/c_str.rs @@ -3,25 +3,21 @@ #[cfg(test)] mod tests; -use crate::borrow::{Cow, ToOwned}; -use crate::boxed::Box; -use crate::rc::Rc; -use crate::slice::hack::into_vec; -use crate::string::String; -use crate::vec::Vec; use core::borrow::Borrow; use core::ffi::{c_char, CStr}; -use core::fmt; -use core::mem; use core::num::NonZero; -use core::ops; -use core::ptr; -use core::slice; use core::slice::memchr; use core::str::{self, Utf8Error}; +use core::{fmt, mem, ops, ptr, slice}; +use crate::borrow::{Cow, ToOwned}; +use crate::boxed::Box; +use crate::rc::Rc; +use crate::slice::hack::into_vec; +use crate::string::String; #[cfg(target_has_atomic = "ptr")] use crate::sync::Arc; +use crate::vec::Vec; /// A type representing an owned, C-compatible, nul-terminated string with no nul bytes in the /// middle. diff --git a/library/alloc/src/ffi/c_str/tests.rs b/library/alloc/src/ffi/c_str/tests.rs index 9f51e17a427f5..8b7172b3f20a9 100644 --- a/library/alloc/src/ffi/c_str/tests.rs +++ b/library/alloc/src/ffi/c_str/tests.rs @@ -1,10 +1,10 @@ -use super::*; use core::assert_matches::assert_matches; use core::ffi::FromBytesUntilNulError; -use core::hash::{Hash, Hasher}; - #[allow(deprecated)] use core::hash::SipHasher13 as DefaultHasher; +use core::hash::{Hash, Hasher}; + +use super::*; #[test] fn c_to_rust() { diff --git a/library/alloc/src/ffi/mod.rs b/library/alloc/src/ffi/mod.rs index 9fc1acc231bff..4f9dc40a3cfc9 100644 --- a/library/alloc/src/ffi/mod.rs +++ b/library/alloc/src/ffi/mod.rs @@ -80,13 +80,12 @@ #![stable(feature = "alloc_ffi", since = "1.64.0")] -#[doc(no_inline)] -#[stable(feature = "alloc_c_string", since = "1.64.0")] -pub use self::c_str::{FromVecWithNulError, IntoStringError, NulError}; - #[doc(inline)] #[stable(feature = "alloc_c_string", since = "1.64.0")] pub use self::c_str::CString; +#[doc(no_inline)] +#[stable(feature = "alloc_c_string", since = "1.64.0")] +pub use self::c_str::{FromVecWithNulError, IntoStringError, NulError}; #[unstable(feature = "c_str_module", issue = "112134")] pub mod c_str; diff --git a/library/alloc/src/fmt.rs b/library/alloc/src/fmt.rs index c6bba619ae646..4b9b90fc1f157 100644 --- a/library/alloc/src/fmt.rs +++ b/library/alloc/src/fmt.rs @@ -600,8 +600,7 @@ pub use core::fmt::{LowerHex, Pointer, UpperHex}; #[cfg(not(no_global_oom_handling))] use crate::string; -/// The `format` function takes an [`Arguments`] struct and returns the resulting -/// formatted string. +/// Takes an [`Arguments`] struct and returns the resulting formatted string. /// /// The [`Arguments`] instance can be created with the [`format_args!`] macro. /// diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index a7715740cbd8f..28b08ef561143 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -86,13 +86,13 @@ #![warn(multiple_supertrait_upcastable)] #![allow(internal_features)] #![allow(rustdoc::redundant_explicit_links)] +#![warn(rustdoc::unescaped_backticks)] #![deny(ffi_unwind_calls)] // // Library features: // tidy-alphabetical-start #![cfg_attr(not(no_global_oom_handling), feature(const_alloc_error))] #![cfg_attr(not(no_global_oom_handling), feature(const_btree_len))] -#![cfg_attr(test, feature(is_sorted))] #![cfg_attr(test, feature(new_uninit))] #![feature(alloc_layout_extra)] #![feature(allocator_api)] @@ -101,6 +101,7 @@ #![feature(array_windows)] #![feature(ascii_char)] #![feature(assert_matches)] +#![feature(async_closure)] #![feature(async_fn_traits)] #![feature(async_iterator)] #![feature(clone_to_uninit)] @@ -116,7 +117,6 @@ #![feature(const_pin)] #![feature(const_refs_to_cell)] #![feature(const_size_of_val)] -#![feature(const_waker)] #![feature(core_intrinsics)] #![feature(deprecated_suggestion)] #![feature(deref_pure_trait)] @@ -165,7 +165,6 @@ // // Language features: // tidy-alphabetical-start -#![cfg_attr(bootstrap, feature(c_unwind))] #![cfg_attr(not(test), feature(coroutine_trait))] #![cfg_attr(test, feature(panic_update_hook))] #![cfg_attr(test, feature(test))] diff --git a/library/alloc/src/raw_vec.rs b/library/alloc/src/raw_vec.rs index 7b7dae5a057f0..5b84df9ecef30 100644 --- a/library/alloc/src/raw_vec.rs +++ b/library/alloc/src/raw_vec.rs @@ -1,10 +1,9 @@ #![unstable(feature = "raw_vec_internals", reason = "unstable const warnings", issue = "none")] use core::alloc::LayoutError; -use core::cmp; -use core::hint; use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties}; use core::ptr::{self, NonNull, Unique}; +use core::{cmp, hint}; #[cfg(not(no_global_oom_handling))] use crate::alloc::handle_alloc_error; @@ -52,7 +51,7 @@ impl Cap { /// * Produces `Unique::dangling()` on zero-length allocations. /// * Avoids freeing `Unique::dangling()`. /// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics). -/// * Guards against 32-bit systems allocating more than isize::MAX bytes. +/// * Guards against 32-bit systems allocating more than `isize::MAX` bytes. /// * Guards against overflowing your length. /// * Calls `handle_alloc_error` for fallible allocations. /// * Contains a `ptr::Unique` and thus endows the user with all related benefits. @@ -484,7 +483,7 @@ impl RawVec { // `finish_grow` is non-generic over `T`. let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; - // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than isize::MAX items + // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than `isize::MAX` items unsafe { self.set_ptr_and_cap(ptr, cap) }; Ok(()) } @@ -504,7 +503,7 @@ impl RawVec { // `finish_grow` is non-generic over `T`. let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; - // SAFETY: finish_grow would have resulted in a capacity overflow if we tried to allocate more than isize::MAX items + // SAFETY: `finish_grow` would have resulted in a capacity overflow if we tried to allocate more than `isize::MAX` items unsafe { self.set_ptr_and_cap(ptr, cap); } diff --git a/library/alloc/src/raw_vec/tests.rs b/library/alloc/src/raw_vec/tests.rs index 4194be530612d..48c6e5f46f8db 100644 --- a/library/alloc/src/raw_vec/tests.rs +++ b/library/alloc/src/raw_vec/tests.rs @@ -1,7 +1,8 @@ -use super::*; use core::mem::size_of; use std::cell::Cell; +use super::*; + #[test] fn allocator_param() { use crate::alloc::AllocError; diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 9982c8ea6dcbe..13d218e43a7af 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -241,25 +241,17 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[cfg(not(test))] -use crate::boxed::Box; -#[cfg(test)] -use std::boxed::Box; - use core::any::Any; -use core::borrow; use core::cell::Cell; #[cfg(not(no_global_oom_handling))] use core::clone::CloneToUninit; use core::cmp::Ordering; -use core::fmt; use core::hash::{Hash, Hasher}; -use core::hint; use core::intrinsics::abort; #[cfg(not(no_global_oom_handling))] use core::iter; use core::marker::{PhantomData, Unsize}; -use core::mem::{self, align_of_val_raw, forget, ManuallyDrop}; +use core::mem::{self, align_of_val_raw, ManuallyDrop}; use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver}; use core::panic::{RefUnwindSafe, UnwindSafe}; #[cfg(not(no_global_oom_handling))] @@ -267,11 +259,16 @@ use core::pin::Pin; use core::ptr::{self, drop_in_place, NonNull}; #[cfg(not(no_global_oom_handling))] use core::slice::from_raw_parts_mut; +use core::{borrow, fmt, hint}; +#[cfg(test)] +use std::boxed::Box; #[cfg(not(no_global_oom_handling))] use crate::alloc::handle_alloc_error; use crate::alloc::{AllocError, Allocator, Global, Layout}; use crate::borrow::{Cow, ToOwned}; +#[cfg(not(test))] +use crate::boxed::Box; #[cfg(not(no_global_oom_handling))] use crate::string::String; #[cfg(not(no_global_oom_handling))] @@ -439,7 +436,7 @@ impl Rc { /// } /// /// impl Gadget { - /// /// Construct a reference counted Gadget. + /// /// Constructs a reference counted Gadget. /// fn new() -> Rc { /// // `me` is a `Weak` pointing at the new allocation of the /// // `Rc` we're constructing. @@ -449,7 +446,7 @@ impl Rc { /// }) /// } /// - /// /// Return a reference counted pointer to Self. + /// /// Returns a reference counted pointer to Self. /// fn me(&self) -> Rc { /// self.me.upgrade().unwrap() /// } @@ -908,19 +905,18 @@ impl Rc { #[stable(feature = "rc_unique", since = "1.4.0")] pub fn try_unwrap(this: Self) -> Result { if Rc::strong_count(&this) == 1 { - unsafe { - let val = ptr::read(&*this); // copy the contained object - let alloc = ptr::read(&this.alloc); // copy the allocator - - // Indicate to Weaks that they can't be promoted by decrementing - // the strong count, and then remove the implicit "strong weak" - // pointer while also handling drop logic by just crafting a - // fake Weak. - this.inner().dec_strong(); - let _weak = Weak { ptr: this.ptr, alloc }; - forget(this); - Ok(val) - } + let this = ManuallyDrop::new(this); + + let val: T = unsafe { ptr::read(&**this) }; // copy the contained object + let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator + + // Indicate to Weaks that they can't be promoted by decrementing + // the strong count, and then remove the implicit "strong weak" + // pointer while also handling drop logic by just crafting a + // fake Weak. + this.inner().dec_strong(); + let _weak = Weak { ptr: this.ptr, alloc }; + Ok(val) } else { Err(this) } @@ -1354,9 +1350,8 @@ impl Rc { #[stable(feature = "rc_raw", since = "1.17.0")] #[rustc_never_returns_null_ptr] pub fn into_raw(this: Self) -> *const T { - let ptr = Self::as_ptr(&this); - mem::forget(this); - ptr + let this = ManuallyDrop::new(this); + Self::as_ptr(&*this) } /// Consumes the `Rc`, returning the wrapped pointer and allocator. @@ -1377,6 +1372,7 @@ impl Rc { /// let x = unsafe { Rc::from_raw_in(ptr, alloc) }; /// assert_eq!(&*x, "hello"); /// ``` + #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "allocator_api", issue = "32838")] pub fn into_raw_with_allocator(this: Self) -> (*const T, A) { let this = mem::ManuallyDrop::new(this); @@ -1902,7 +1898,7 @@ impl Rc { } impl Rc { - /// Attempt to downcast the `Rc` to a concrete type. + /// Attempts to downcast the `Rc` to a concrete type. /// /// # Examples /// @@ -2127,7 +2123,7 @@ impl Rc<[T]> { } // All clear. Forget the guard so it doesn't free the new RcBox. - forget(guard); + mem::forget(guard); Self::from_ptr(ptr) } @@ -2588,7 +2584,7 @@ impl From<[T; N]> for Rc<[T]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From<&[T]> for Rc<[T]> { - /// Allocate a reference-counted slice and fill it by cloning `v`'s items. + /// Allocates a reference-counted slice and fills it by cloning `v`'s items. /// /// # Example /// @@ -2607,7 +2603,7 @@ impl From<&[T]> for Rc<[T]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From<&str> for Rc { - /// Allocate a reference-counted string slice and copy `v` into it. + /// Allocates a reference-counted string slice and copies `v` into it. /// /// # Example /// @@ -2626,7 +2622,7 @@ impl From<&str> for Rc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From for Rc { - /// Allocate a reference-counted string slice and copy `v` into it. + /// Allocates a reference-counted string slice and copies `v` into it. /// /// # Example /// @@ -2664,7 +2660,7 @@ impl From> for Rc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From> for Rc<[T], A> { - /// Allocate a reference-counted slice and move `v`'s items into it. + /// Allocates a reference-counted slice and moves `v`'s items into it. /// /// # Example /// @@ -2697,8 +2693,8 @@ where B: ToOwned + ?Sized, Rc: From<&'a B> + From, { - /// Create a reference-counted pointer from - /// a clone-on-write pointer by copying its content. + /// Creates a reference-counted pointer from a clone-on-write pointer by + /// copying its content. /// /// # Example /// @@ -3080,9 +3076,7 @@ impl Weak { #[must_use = "losing the pointer will leak memory"] #[stable(feature = "weak_into_raw", since = "1.45.0")] pub fn into_raw(self) -> *const T { - let result = self.as_ptr(); - mem::forget(self); - result + mem::ManuallyDrop::new(self).as_ptr() } /// Consumes the `Weak`, returning the wrapped pointer and allocator. @@ -3114,6 +3108,7 @@ impl Weak { /// /// [`from_raw_in`]: Weak::from_raw_in /// [`as_ptr`]: Weak::as_ptr + #[must_use = "losing the pointer will leak memory"] #[inline] #[unstable(feature = "allocator_api", issue = "32838")] pub fn into_raw_with_allocator(self) -> (*const T, A) { @@ -3530,7 +3525,7 @@ impl AsRef for Rc { #[stable(feature = "pin", since = "1.33.0")] impl Unpin for Rc {} -/// Get the offset within an `RcBox` for the payload behind a pointer. +/// Gets the offset within an `RcBox` for the payload behind a pointer. /// /// # Safety /// @@ -3738,7 +3733,7 @@ struct UniqueRcUninit { #[cfg(not(no_global_oom_handling))] impl UniqueRcUninit { - /// Allocate a RcBox with layout suitable to contain `for_value` or a clone of it. + /// Allocates a RcBox with layout suitable to contain `for_value` or a clone of it. fn new(for_value: &T, alloc: A) -> UniqueRcUninit { let layout = Layout::for_value(for_value); let ptr = unsafe { @@ -3762,10 +3757,11 @@ impl UniqueRcUninit { /// # Safety /// /// The data must have been initialized (by writing to [`Self::data_ptr()`]). - unsafe fn into_rc(mut self) -> Rc { - let ptr = self.ptr; - let alloc = self.alloc.take().unwrap(); - mem::forget(self); + unsafe fn into_rc(self) -> Rc { + let mut this = ManuallyDrop::new(self); + let ptr = this.ptr; + let alloc = this.alloc.take().unwrap(); + // SAFETY: The pointer is valid as per `UniqueRcUninit::new`, and the caller is responsible // for having initialized the data. unsafe { Rc::from_ptr_in(ptr.as_ptr(), alloc) } diff --git a/library/alloc/src/rc/tests.rs b/library/alloc/src/rc/tests.rs index 5e2e4beb94a2b..84e8b325f71fc 100644 --- a/library/alloc/src/rc/tests.rs +++ b/library/alloc/src/rc/tests.rs @@ -1,8 +1,8 @@ -use super::*; - use std::cell::RefCell; use std::clone::Clone; +use super::*; + #[test] fn test_clone() { let x = Rc::new(RefCell::new(5)); diff --git a/library/alloc/src/slice.rs b/library/alloc/src/slice.rs index c7960b3fb49c3..7dcf344cdc5e0 100644 --- a/library/alloc/src/slice.rs +++ b/library/alloc/src/slice.rs @@ -78,7 +78,6 @@ pub use core::slice::{SplitInclusive, SplitInclusiveMut}; // N.B., see the `hack` module in this file for more details. #[cfg(test)] pub use hack::into_vec; - // HACK(japaric) needed for the implementation of `Vec::clone` during testing // N.B., see the `hack` module in this file for more details. #[cfg(test)] diff --git a/library/alloc/src/slice/tests.rs b/library/alloc/src/slice/tests.rs index 0b972a13898eb..786704caeb0ad 100644 --- a/library/alloc/src/slice/tests.rs +++ b/library/alloc/src/slice/tests.rs @@ -1,18 +1,21 @@ +use core::cell::Cell; +use core::cmp::Ordering::{self, Equal, Greater, Less}; +use core::convert::identity; +use core::sync::atomic::AtomicUsize; +use core::sync::atomic::Ordering::Relaxed; +use core::{fmt, mem}; +use std::panic; + +use rand::distributions::Standard; +use rand::prelude::*; +use rand::{Rng, RngCore}; + use crate::borrow::ToOwned; use crate::rc::Rc; use crate::string::ToString; use crate::test_helpers::test_rng; use crate::vec::Vec; -use core::cell::Cell; -use core::cmp::Ordering::{self, Equal, Greater, Less}; -use core::convert::identity; -use core::fmt; -use core::mem; -use core::sync::atomic::{AtomicUsize, Ordering::Relaxed}; -use rand::{distributions::Standard, prelude::*, Rng, RngCore}; -use std::panic; - macro_rules! do_test { ($input:ident, $func:ident) => { let len = $input.len(); diff --git a/library/alloc/src/str.rs b/library/alloc/src/str.rs index 94053ef83a0e0..d7fba3ae159c6 100644 --- a/library/alloc/src/str.rs +++ b/library/alloc/src/str.rs @@ -9,19 +9,9 @@ use core::borrow::{Borrow, BorrowMut}; use core::iter::FusedIterator; -use core::mem; -use core::ptr; -use core::str::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher}; -use core::unicode::conversions; - -use crate::borrow::ToOwned; -use crate::boxed::Box; -use crate::slice::{Concat, Join, SliceIndex}; -use crate::string::String; -use crate::vec::Vec; - #[stable(feature = "rust1", since = "1.0.0")] pub use core::str::pattern; +use core::str::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher}; #[stable(feature = "encode_utf16", since = "1.8.0")] pub use core::str::EncodeUtf16; #[stable(feature = "split_ascii_whitespace", since = "1.34.0")] @@ -55,6 +45,14 @@ pub use core::str::{RSplitN, SplitN}; pub use core::str::{RSplitTerminator, SplitTerminator}; #[stable(feature = "utf8_chunks", since = "1.79.0")] pub use core::str::{Utf8Chunk, Utf8Chunks}; +use core::unicode::conversions; +use core::{mem, ptr}; + +use crate::borrow::ToOwned; +use crate::boxed::Box; +use crate::slice::{Concat, Join, SliceIndex}; +use crate::string::String; +use crate::vec::Vec; /// Note: `str` in `Concat` is not meaningful here. /// This type parameter of the trait only exists to enable another impl. diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 0ff66167a46ae..124230812df56 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -43,8 +43,6 @@ #![stable(feature = "rust1", since = "1.0.0")] use core::error::Error; -use core::fmt; -use core::hash; #[cfg(not(no_global_oom_handling))] use core::iter::from_fn; use core::iter::FusedIterator; @@ -55,9 +53,8 @@ use core::ops::AddAssign; #[cfg(not(no_global_oom_handling))] use core::ops::Bound::{Excluded, Included, Unbounded}; use core::ops::{self, Range, RangeBounds}; -use core::ptr; -use core::slice; use core::str::pattern::Pattern; +use core::{fmt, hash, ptr, slice}; #[cfg(not(no_global_oom_handling))] use crate::alloc::Allocator; @@ -903,7 +900,7 @@ impl String { /// let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) }; /// assert_eq!(rebuilt, "hello"); /// ``` - #[must_use = "`self` will be dropped if the result is not used"] + #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")] pub fn into_raw_parts(self) -> (*mut u8, usize, usize) { self.vec.into_raw_parts() diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index a905a1e6b7e62..3ad0dae77dbde 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -9,18 +9,15 @@ //! `#[cfg(target_has_atomic = "ptr")]`. use core::any::Any; -use core::borrow; #[cfg(not(no_global_oom_handling))] use core::clone::CloneToUninit; use core::cmp::Ordering; -use core::fmt; use core::hash::{Hash, Hasher}; -use core::hint; use core::intrinsics::abort; #[cfg(not(no_global_oom_handling))] use core::iter; use core::marker::{PhantomData, Unsize}; -use core::mem::{self, align_of_val_raw}; +use core::mem::{self, align_of_val_raw, ManuallyDrop}; use core::ops::{CoerceUnsized, Deref, DerefPure, DispatchFromDyn, Receiver}; use core::panic::{RefUnwindSafe, UnwindSafe}; use core::pin::Pin; @@ -29,6 +26,7 @@ use core::ptr::{self, NonNull}; use core::slice::from_raw_parts_mut; use core::sync::atomic; use core::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use core::{borrow, fmt, hint}; #[cfg(not(no_global_oom_handling))] use crate::alloc::handle_alloc_error; @@ -428,7 +426,7 @@ impl Arc { /// } /// /// impl Gadget { - /// /// Construct a reference counted Gadget. + /// /// Constructs a reference counted Gadget. /// fn new() -> Arc { /// // `me` is a `Weak` pointing at the new allocation of the /// // `Arc` we're constructing. @@ -438,7 +436,7 @@ impl Arc { /// }) /// } /// - /// /// Return a reference counted pointer to Self. + /// /// Returns a reference counted pointer to Self. /// fn me(&self) -> Arc { /// self.me.upgrade().unwrap() /// } @@ -960,16 +958,14 @@ impl Arc { acquire!(this.inner().strong); - unsafe { - let elem = ptr::read(&this.ptr.as_ref().data); - let alloc = ptr::read(&this.alloc); // copy the allocator + let this = ManuallyDrop::new(this); + let elem: T = unsafe { ptr::read(&this.ptr.as_ref().data) }; + let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator - // Make a weak pointer to clean up the implicit strong-weak reference - let _weak = Weak { ptr: this.ptr, alloc }; - mem::forget(this); + // Make a weak pointer to clean up the implicit strong-weak reference + let _weak = Weak { ptr: this.ptr, alloc }; - Ok(elem) - } + Ok(elem) } /// Returns the inner value, if the `Arc` has exactly one strong reference. @@ -1493,9 +1489,8 @@ impl Arc { #[stable(feature = "rc_raw", since = "1.17.0")] #[rustc_never_returns_null_ptr] pub fn into_raw(this: Self) -> *const T { - let ptr = Self::as_ptr(&this); - mem::forget(this); - ptr + let this = ManuallyDrop::new(this); + Self::as_ptr(&*this) } /// Consumes the `Arc`, returning the wrapped pointer and allocator. @@ -2534,7 +2529,7 @@ unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Arc { } impl Arc { - /// Attempt to downcast the `Arc` to a concrete type. + /// Attempts to downcast the `Arc` to a concrete type. /// /// # Examples /// @@ -2801,9 +2796,7 @@ impl Weak { #[must_use = "losing the pointer will leak memory"] #[stable(feature = "weak_into_raw", since = "1.45.0")] pub fn into_raw(self) -> *const T { - let result = self.as_ptr(); - mem::forget(self); - result + ManuallyDrop::new(self).as_ptr() } /// Consumes the `Weak`, returning the wrapped pointer and allocator. @@ -3550,7 +3543,7 @@ impl From<[T; N]> for Arc<[T]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From<&[T]> for Arc<[T]> { - /// Allocate a reference-counted slice and fill it by cloning `v`'s items. + /// Allocates a reference-counted slice and fills it by cloning `v`'s items. /// /// # Example /// @@ -3569,7 +3562,7 @@ impl From<&[T]> for Arc<[T]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From<&str> for Arc { - /// Allocate a reference-counted `str` and copy `v` into it. + /// Allocates a reference-counted `str` and copies `v` into it. /// /// # Example /// @@ -3588,7 +3581,7 @@ impl From<&str> for Arc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From for Arc { - /// Allocate a reference-counted `str` and copy `v` into it. + /// Allocates a reference-counted `str` and copies `v` into it. /// /// # Example /// @@ -3626,7 +3619,7 @@ impl From> for Arc { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_slice", since = "1.21.0")] impl From> for Arc<[T], A> { - /// Allocate a reference-counted slice and move `v`'s items into it. + /// Allocates a reference-counted slice and moves `v`'s items into it. /// /// # Example /// @@ -3659,8 +3652,8 @@ where B: ToOwned + ?Sized, Arc: From<&'a B> + From, { - /// Create an atomically reference-counted pointer from - /// a clone-on-write pointer by copying its content. + /// Creates an atomically reference-counted pointer from a clone-on-write + /// pointer by copying its content. /// /// # Example /// @@ -3816,7 +3809,7 @@ impl AsRef for Arc { #[stable(feature = "pin", since = "1.33.0")] impl Unpin for Arc {} -/// Get the offset within an `ArcInner` for the payload behind a pointer. +/// Gets the offset within an `ArcInner` for the payload behind a pointer. /// /// # Safety /// @@ -3838,7 +3831,7 @@ fn data_offset_align(align: usize) -> usize { layout.size() + layout.padding_needed_for(align) } -/// A unique owning pointer to a [`ArcInner`] **that does not imply the contents are initialized,** +/// A unique owning pointer to an [`ArcInner`] **that does not imply the contents are initialized,** /// but will deallocate it (without dropping the value) when dropped. /// /// This is a helper for [`Arc::make_mut()`] to ensure correct cleanup on panic. @@ -3851,7 +3844,7 @@ struct UniqueArcUninit { #[cfg(not(no_global_oom_handling))] impl UniqueArcUninit { - /// Allocate a ArcInner with layout suitable to contain `for_value` or a clone of it. + /// Allocates an ArcInner with layout suitable to contain `for_value` or a clone of it. fn new(for_value: &T, alloc: A) -> UniqueArcUninit { let layout = Layout::for_value(for_value); let ptr = unsafe { @@ -3875,13 +3868,14 @@ impl UniqueArcUninit { /// # Safety /// /// The data must have been initialized (by writing to [`Self::data_ptr()`]). - unsafe fn into_arc(mut self) -> Arc { - let ptr = self.ptr; - let alloc = self.alloc.take().unwrap(); - mem::forget(self); + unsafe fn into_arc(self) -> Arc { + let mut this = ManuallyDrop::new(self); + let ptr = this.ptr.as_ptr(); + let alloc = this.alloc.take().unwrap(); + // SAFETY: The pointer is valid as per `UniqueArcUninit::new`, and the caller is responsible // for having initialized the data. - unsafe { Arc::from_ptr_in(ptr.as_ptr(), alloc) } + unsafe { Arc::from_ptr_in(ptr, alloc) } } } diff --git a/library/alloc/src/sync/tests.rs b/library/alloc/src/sync/tests.rs index 1b123aa58f205..d6b3de875771e 100644 --- a/library/alloc/src/sync/tests.rs +++ b/library/alloc/src/sync/tests.rs @@ -1,5 +1,3 @@ -use super::*; - use std::clone::Clone; use std::mem::MaybeUninit; use std::option::Option::None; @@ -9,6 +7,8 @@ use std::sync::mpsc::channel; use std::sync::Mutex; use std::thread; +use super::*; + struct Canary(*mut AtomicUsize); impl Drop for Canary { diff --git a/library/alloc/src/task.rs b/library/alloc/src/task.rs index a3fa6585a37f8..27589aed2f97c 100644 --- a/library/alloc/src/task.rs +++ b/library/alloc/src/task.rs @@ -7,14 +7,14 @@ //! This may be detected at compile time using //! `#[cfg(target_has_atomic = "ptr")]`. -use crate::rc::Rc; use core::mem::ManuallyDrop; +#[cfg(target_has_atomic = "ptr")] +use core::task::Waker; use core::task::{LocalWaker, RawWaker, RawWakerVTable}; +use crate::rc::Rc; #[cfg(target_has_atomic = "ptr")] use crate::sync::Arc; -#[cfg(target_has_atomic = "ptr")] -use core::task::Waker; /// The implementation of waking a task on an executor. /// diff --git a/library/alloc/src/testing/crash_test.rs b/library/alloc/src/testing/crash_test.rs index ff72f99b2cbed..684bac60d9a86 100644 --- a/library/alloc/src/testing/crash_test.rs +++ b/library/alloc/src/testing/crash_test.rs @@ -1,6 +1,8 @@ -use crate::fmt::Debug; // the `Debug` trait is the only thing we use from `crate::fmt` use std::cmp::Ordering; -use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering::SeqCst; + +use crate::fmt::Debug; // the `Debug` trait is the only thing we use from `crate::fmt` /// A blueprint for crash test dummy instances that monitor particular events. /// Some instances may be configured to panic at some point. diff --git a/library/alloc/src/tests.rs b/library/alloc/src/tests.rs index ab256ceaec353..b95d11cb07ec8 100644 --- a/library/alloc/src/tests.rs +++ b/library/alloc/src/tests.rs @@ -2,7 +2,6 @@ use core::any::Any; use core::ops::Deref; - use std::boxed::Box; #[test] diff --git a/library/alloc/src/vec/cow.rs b/library/alloc/src/vec/cow.rs index 3fe83242a30ad..c18091705a636 100644 --- a/library/alloc/src/vec/cow.rs +++ b/library/alloc/src/vec/cow.rs @@ -1,6 +1,5 @@ -use crate::borrow::Cow; - use super::Vec; +use crate::borrow::Cow; #[stable(feature = "cow_from_vec", since = "1.8.0")] impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> { diff --git a/library/alloc/src/vec/drain.rs b/library/alloc/src/vec/drain.rs index f0b63759ac70f..9362cef2a1b00 100644 --- a/library/alloc/src/vec/drain.rs +++ b/library/alloc/src/vec/drain.rs @@ -1,4 +1,3 @@ -use crate::alloc::{Allocator, Global}; use core::fmt; use core::iter::{FusedIterator, TrustedLen}; use core::mem::{self, ManuallyDrop, SizedTypeProperties}; @@ -6,6 +5,7 @@ use core::ptr::{self, NonNull}; use core::slice::{self}; use super::Vec; +use crate::alloc::{Allocator, Global}; /// A draining iterator for `Vec`. /// diff --git a/library/alloc/src/vec/extract_if.rs b/library/alloc/src/vec/extract_if.rs index 118cfdb36b9c2..72d51e8904488 100644 --- a/library/alloc/src/vec/extract_if.rs +++ b/library/alloc/src/vec/extract_if.rs @@ -1,8 +1,7 @@ -use crate::alloc::{Allocator, Global}; -use core::ptr; -use core::slice; +use core::{ptr, slice}; use super::Vec; +use crate::alloc::{Allocator, Global}; /// An iterator which uses a closure to determine if an element should be removed. /// diff --git a/library/alloc/src/vec/in_place_collect.rs b/library/alloc/src/vec/in_place_collect.rs index 0dc193d82c535..d119e6ca397c5 100644 --- a/library/alloc/src/vec/in_place_collect.rs +++ b/library/alloc/src/vec/in_place_collect.rs @@ -155,9 +155,7 @@ //! vec.truncate(write_idx); //! ``` -use crate::alloc::{handle_alloc_error, Global}; -use core::alloc::Allocator; -use core::alloc::Layout; +use core::alloc::{Allocator, Layout}; use core::iter::{InPlaceIterable, SourceIter, TrustedRandomAccessNoCoerce}; use core::marker::PhantomData; use core::mem::{self, ManuallyDrop, SizedTypeProperties}; @@ -165,6 +163,7 @@ use core::num::NonZero; use core::ptr; use super::{InPlaceDrop, InPlaceDstDataSrcBufDrop, SpecFromIter, SpecFromIterNested, Vec}; +use crate::alloc::{handle_alloc_error, Global}; const fn in_place_collectible( step_merge: Option>, diff --git a/library/alloc/src/vec/in_place_drop.rs b/library/alloc/src/vec/in_place_drop.rs index 4050c250130bb..27f7597931045 100644 --- a/library/alloc/src/vec/in_place_drop.rs +++ b/library/alloc/src/vec/in_place_drop.rs @@ -1,6 +1,5 @@ use core::marker::PhantomData; -use core::ptr::NonNull; -use core::ptr::{self, drop_in_place}; +use core::ptr::{self, drop_in_place, NonNull}; use core::slice::{self}; use crate::alloc::Global; diff --git a/library/alloc/src/vec/into_iter.rs b/library/alloc/src/vec/into_iter.rs index 10f62e4bb62d8..fad8abad49353 100644 --- a/library/alloc/src/vec/into_iter.rs +++ b/library/alloc/src/vec/into_iter.rs @@ -1,11 +1,3 @@ -#[cfg(not(no_global_oom_handling))] -use super::AsVecIntoIter; -use crate::alloc::{Allocator, Global}; -#[cfg(not(no_global_oom_handling))] -use crate::collections::VecDeque; -use crate::raw_vec::RawVec; -use core::array; -use core::fmt; use core::iter::{ FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen, TrustedRandomAccessNoCoerce, @@ -17,6 +9,14 @@ use core::num::NonZero; use core::ops::Deref; use core::ptr::{self, NonNull}; use core::slice::{self}; +use core::{array, fmt}; + +#[cfg(not(no_global_oom_handling))] +use super::AsVecIntoIter; +use crate::alloc::{Allocator, Global}; +#[cfg(not(no_global_oom_handling))] +use crate::collections::VecDeque; +use crate::raw_vec::RawVec; macro non_null { (mut $place:expr, $t:ident) => {{ @@ -114,8 +114,9 @@ impl IntoIter { } /// Drops remaining elements and relinquishes the backing allocation. - /// This method guarantees it won't panic before relinquishing - /// the backing allocation. + /// + /// This method guarantees it won't panic before relinquishing the backing + /// allocation. /// /// This is roughly equivalent to the following, but more efficient /// diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 729d5dd4fe4d2..b4e0bc5fcbe41 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -66,15 +66,14 @@ use core::ops::{self, Index, IndexMut, Range, RangeBounds}; use core::ptr::{self, NonNull}; use core::slice::{self, SliceIndex}; +#[unstable(feature = "extract_if", reason = "recently added", issue = "43244")] +pub use self::extract_if::ExtractIf; use crate::alloc::{Allocator, Global}; use crate::borrow::{Cow, ToOwned}; use crate::boxed::Box; use crate::collections::TryReserveError; use crate::raw_vec::RawVec; -#[unstable(feature = "extract_if", reason = "recently added", issue = "43244")] -pub use self::extract_if::ExtractIf; - mod extract_if; #[cfg(not(no_global_oom_handling))] @@ -879,6 +878,7 @@ impl Vec { /// }; /// assert_eq!(rebuilt, [4294967295, 0, 1]); /// ``` + #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")] pub fn into_raw_parts(self) -> (*mut T, usize, usize) { let mut me = ManuallyDrop::new(self); @@ -922,6 +922,7 @@ impl Vec { /// }; /// assert_eq!(rebuilt, [4294967295, 0, 1]); /// ``` + #[must_use = "losing the pointer will leak memory"] #[unstable(feature = "allocator_api", issue = "32838")] // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")] pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) { @@ -1277,7 +1278,7 @@ impl Vec { /// valid for zero sized reads if the vector didn't allocate. /// /// The caller must ensure that the vector outlives the pointer this - /// function returns, or else it will end up pointing to garbage. + /// function returns, or else it will end up dangling. /// Modifying the vector may cause its buffer to be reallocated, /// which would also make any pointers to it invalid. /// @@ -1337,7 +1338,7 @@ impl Vec { /// raw pointer valid for zero sized reads if the vector didn't allocate. /// /// The caller must ensure that the vector outlives the pointer this - /// function returns, or else it will end up pointing to garbage. + /// function returns, or else it will end up dangling. /// Modifying the vector may cause its buffer to be reallocated, /// which would also make any pointers to it invalid. /// @@ -1711,6 +1712,12 @@ impl Vec { F: FnMut(&mut T) -> bool, { let original_len = self.len(); + + if original_len == 0 { + // Empty case: explicit return allows better optimization, vs letting compiler infer it + return; + } + // Avoid double drop if the drop guard is not executed, // since we may make some holes during the process. unsafe { self.set_len(0) }; @@ -2373,9 +2380,11 @@ impl Vec { } /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, - /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime - /// `'a`. If the type has only static references, or none at all, then this - /// may be chosen to be `'static`. + /// `&'a mut [T]`. + /// + /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type + /// has only static references, or none at all, then this may be chosen to be + /// `'static`. /// /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, /// so the leaked allocation may include unused capacity that is not part @@ -3359,7 +3368,7 @@ impl AsMut<[T]> for Vec { #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl From<&[T]> for Vec { - /// Allocate a `Vec` and fill it by cloning `s`'s items. + /// Allocates a `Vec` and fills it by cloning `s`'s items. /// /// # Examples /// @@ -3379,7 +3388,7 @@ impl From<&[T]> for Vec { #[cfg(not(no_global_oom_handling))] #[stable(feature = "vec_from_mut", since = "1.19.0")] impl From<&mut [T]> for Vec { - /// Allocate a `Vec` and fill it by cloning `s`'s items. + /// Allocates a `Vec` and fills it by cloning `s`'s items. /// /// # Examples /// @@ -3399,7 +3408,7 @@ impl From<&mut [T]> for Vec { #[cfg(not(no_global_oom_handling))] #[stable(feature = "vec_from_array_ref", since = "1.74.0")] impl From<&[T; N]> for Vec { - /// Allocate a `Vec` and fill it by cloning `s`'s items. + /// Allocates a `Vec` and fills it by cloning `s`'s items. /// /// # Examples /// @@ -3414,7 +3423,7 @@ impl From<&[T; N]> for Vec { #[cfg(not(no_global_oom_handling))] #[stable(feature = "vec_from_array_ref", since = "1.74.0")] impl From<&mut [T; N]> for Vec { - /// Allocate a `Vec` and fill it by cloning `s`'s items. + /// Allocates a `Vec` and fills it by cloning `s`'s items. /// /// # Examples /// @@ -3429,7 +3438,7 @@ impl From<&mut [T; N]> for Vec { #[cfg(not(no_global_oom_handling))] #[stable(feature = "vec_from_array", since = "1.44.0")] impl From<[T; N]> for Vec { - /// Allocate a `Vec` and move `s`'s items into it. + /// Allocates a `Vec` and moves `s`'s items into it. /// /// # Examples /// @@ -3452,7 +3461,7 @@ impl<'a, T> From> for Vec where [T]: ToOwned>, { - /// Convert a clone-on-write slice into a vector. + /// Converts a clone-on-write slice into a vector. /// /// If `s` already owns a `Vec`, it will be returned directly. /// If `s` is borrowing a slice, a new `Vec` will be allocated and @@ -3475,7 +3484,7 @@ where #[cfg(not(test))] #[stable(feature = "vec_from_box", since = "1.18.0")] impl From> for Vec { - /// Convert a boxed slice into a vector by transferring ownership of + /// Converts a boxed slice into a vector by transferring ownership of /// the existing heap allocation. /// /// # Examples @@ -3494,7 +3503,7 @@ impl From> for Vec { #[cfg(not(test))] #[stable(feature = "box_from_vec", since = "1.20.0")] impl From> for Box<[T], A> { - /// Convert a vector into a boxed slice. + /// Converts a vector into a boxed slice. /// /// Before doing the conversion, this method discards excess capacity like [`Vec::shrink_to_fit`]. /// @@ -3522,7 +3531,7 @@ impl From> for Box<[T], A> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] impl From<&str> for Vec { - /// Allocate a `Vec` and fill it with a UTF-8 string. + /// Allocates a `Vec` and fills it with a UTF-8 string. /// /// # Examples /// diff --git a/library/alloc/src/vec/partial_eq.rs b/library/alloc/src/vec/partial_eq.rs index b0cf72577a1be..5e620c4b2efe7 100644 --- a/library/alloc/src/vec/partial_eq.rs +++ b/library/alloc/src/vec/partial_eq.rs @@ -1,9 +1,8 @@ +use super::Vec; use crate::alloc::Allocator; #[cfg(not(no_global_oom_handling))] use crate::borrow::Cow; -use super::Vec; - macro_rules! __impl_slice_eq1 { ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => { #[$stability] diff --git a/library/alloc/src/vec/spec_extend.rs b/library/alloc/src/vec/spec_extend.rs index e2f865d0f7167..7085bceef5baa 100644 --- a/library/alloc/src/vec/spec_extend.rs +++ b/library/alloc/src/vec/spec_extend.rs @@ -1,8 +1,8 @@ -use crate::alloc::Allocator; use core::iter::TrustedLen; use core::slice::{self}; use super::{IntoIter, Vec}; +use crate::alloc::Allocator; // Specialization trait used for Vec::extend pub(super) trait SpecExtend { diff --git a/library/alloc/src/vec/spec_from_elem.rs b/library/alloc/src/vec/spec_from_elem.rs index 01a6db14474bb..96d701e15d487 100644 --- a/library/alloc/src/vec/spec_from_elem.rs +++ b/library/alloc/src/vec/spec_from_elem.rs @@ -1,10 +1,9 @@ use core::ptr; +use super::{IsZero, Vec}; use crate::alloc::Allocator; use crate::raw_vec::RawVec; -use super::{IsZero, Vec}; - // Specialization trait used for Vec::from_elem pub(super) trait SpecFromElem: Sized { fn from_elem(elem: Self, n: usize, alloc: A) -> Vec; diff --git a/library/alloc/src/vec/spec_from_iter_nested.rs b/library/alloc/src/vec/spec_from_iter_nested.rs index f915ebb86e5a5..77f7761d22f95 100644 --- a/library/alloc/src/vec/spec_from_iter_nested.rs +++ b/library/alloc/src/vec/spec_from_iter_nested.rs @@ -1,10 +1,8 @@ -use core::cmp; use core::iter::TrustedLen; -use core::ptr; - -use crate::raw_vec::RawVec; +use core::{cmp, ptr}; use super::{SpecExtend, Vec}; +use crate::raw_vec::RawVec; /// Another specialization trait for Vec::from_iter /// necessary to manually prioritize overlapping specializations diff --git a/library/alloc/src/vec/splice.rs b/library/alloc/src/vec/splice.rs index 852fdcc3f5ce7..9e36377c148d2 100644 --- a/library/alloc/src/vec/splice.rs +++ b/library/alloc/src/vec/splice.rs @@ -1,8 +1,8 @@ -use crate::alloc::{Allocator, Global}; use core::ptr::{self}; use core::slice::{self}; use super::{Drain, Vec}; +use crate::alloc::{Allocator, Global}; /// A splicing iterator for `Vec`. /// diff --git a/library/alloc/tests/btree_set_hash.rs b/library/alloc/tests/btree_set_hash.rs index ab275ac4353ac..71a3a143209ff 100644 --- a/library/alloc/tests/btree_set_hash.rs +++ b/library/alloc/tests/btree_set_hash.rs @@ -1,6 +1,7 @@ -use crate::hash; use std::collections::BTreeSet; +use crate::hash; + #[test] fn test_hash() { let mut x = BTreeSet::new(); diff --git a/library/alloc/tests/slice.rs b/library/alloc/tests/slice.rs index c0f7a11a93e12..df5a8af16fd70 100644 --- a/library/alloc/tests/slice.rs +++ b/library/alloc/tests/slice.rs @@ -1,9 +1,7 @@ use std::cmp::Ordering::{Equal, Greater, Less}; use std::convert::identity; -use std::fmt; -use std::mem; -use std::panic; use std::rc::Rc; +use std::{fmt, mem, panic}; fn square(n: usize) -> usize { n * n @@ -911,8 +909,7 @@ fn test_split_iterators_size_hint() { // become maximally long, so the size_hint upper bounds are tight ((|_| true) as fn(&_) -> _, Bounds::Upper), ] { - use assert_tight_size_hints as a; - use format_args as f; + use {assert_tight_size_hints as a, format_args as f}; a(v.split(p), b, "split"); a(v.split_mut(p), b, "split_mut"); diff --git a/library/alloc/tests/str.rs b/library/alloc/tests/str.rs index de5d3991c9143..a6b1fe5b97945 100644 --- a/library/alloc/tests/str.rs +++ b/library/alloc/tests/str.rs @@ -165,7 +165,8 @@ fn test_join_for_different_lengths_with_long_separator() { #[test] fn test_join_issue_80335() { - use core::{borrow::Borrow, cell::Cell}; + use core::borrow::Borrow; + use core::cell::Cell; struct WeirdBorrow { state: Cell, diff --git a/library/alloc/tests/string.rs b/library/alloc/tests/string.rs index e20ceae87b0d5..c5bc4185a3670 100644 --- a/library/alloc/tests/string.rs +++ b/library/alloc/tests/string.rs @@ -2,11 +2,9 @@ use std::assert_matches::assert_matches; use std::borrow::Cow; use std::cell::Cell; use std::collections::TryReserveErrorKind::*; -use std::ops::Bound; use std::ops::Bound::*; -use std::ops::RangeBounds; -use std::panic; -use std::str; +use std::ops::{Bound, RangeBounds}; +use std::{panic, str}; pub trait IntoCow<'a, B: ?Sized> where diff --git a/library/alloc/tests/vec.rs b/library/alloc/tests/vec.rs index 71d79893e01d7..fd2ddbf59e42d 100644 --- a/library/alloc/tests/vec.rs +++ b/library/alloc/tests/vec.rs @@ -8,15 +8,14 @@ use std::borrow::Cow; use std::cell::Cell; use std::collections::TryReserveErrorKind::*; use std::fmt::Debug; -use std::hint; use std::iter::InPlaceIterable; -use std::mem; use std::mem::{size_of, swap}; use std::ops::Bound::*; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::rc::Rc; use std::sync::atomic::{AtomicU32, Ordering}; use std::vec::{Drain, IntoIter}; +use std::{hint, mem}; struct DropCounter<'a> { count: &'a mut u32, @@ -2572,7 +2571,8 @@ fn test_into_flattened_size_overflow() { #[test] fn test_box_zero_allocator() { - use core::{alloc::AllocError, cell::RefCell}; + use core::alloc::AllocError; + use core::cell::RefCell; use std::collections::HashSet; // Track ZST allocations and ensure that they all have a matching free. diff --git a/library/alloc/tests/vec_deque.rs b/library/alloc/tests/vec_deque.rs index cea5de4dd5984..db972122fef2a 100644 --- a/library/alloc/tests/vec_deque.rs +++ b/library/alloc/tests/vec_deque.rs @@ -1,16 +1,17 @@ use core::num::NonZero; use std::assert_matches::assert_matches; +use std::collections::vec_deque::Drain; use std::collections::TryReserveErrorKind::*; -use std::collections::{vec_deque::Drain, VecDeque}; +use std::collections::VecDeque; use std::fmt::Debug; use std::ops::Bound::*; use std::panic::{catch_unwind, AssertUnwindSafe}; -use crate::hash; - use Taggy::*; use Taggypar::*; +use crate::hash; + #[test] fn test_simple() { let mut d = VecDeque::new(); diff --git a/library/alloc/tests/vec_deque_alloc_error.rs b/library/alloc/tests/vec_deque_alloc_error.rs index 8b516ddbc5c55..c41d8266eb457 100644 --- a/library/alloc/tests/vec_deque_alloc_error.rs +++ b/library/alloc/tests/vec_deque_alloc_error.rs @@ -1,11 +1,9 @@ #![feature(alloc_error_hook, allocator_api)] -use std::{ - alloc::{set_alloc_error_hook, AllocError, Allocator, Layout, System}, - collections::VecDeque, - panic::{catch_unwind, AssertUnwindSafe}, - ptr::NonNull, -}; +use std::alloc::{set_alloc_error_hook, AllocError, Allocator, Layout, System}; +use std::collections::VecDeque; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::ptr::NonNull; #[test] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] diff --git a/library/core/benches/any.rs b/library/core/benches/any.rs index 53099b78266f8..f6be41bcdbfa7 100644 --- a/library/core/benches/any.rs +++ b/library/core/benches/any.rs @@ -1,4 +1,5 @@ use core::any::*; + use test::{black_box, Bencher}; #[bench] diff --git a/library/core/benches/array.rs b/library/core/benches/array.rs index d8cc44d05c4ba..b1a41a088c493 100644 --- a/library/core/benches/array.rs +++ b/library/core/benches/array.rs @@ -1,5 +1,4 @@ -use test::black_box; -use test::Bencher; +use test::{black_box, Bencher}; macro_rules! map_array { ($func_name:ident, $start_item: expr, $map_item: expr, $arr_size: expr) => { diff --git a/library/core/benches/ascii.rs b/library/core/benches/ascii.rs index 71ec9fed2fe75..61bf8bbf411d5 100644 --- a/library/core/benches/ascii.rs +++ b/library/core/benches/ascii.rs @@ -64,8 +64,8 @@ macro_rules! benches { } use std::fmt::Write; -use test::black_box; -use test::Bencher; + +use test::{black_box, Bencher}; const ASCII_CASE_MASK: u8 = 0b0010_0000; diff --git a/library/core/benches/ascii/is_ascii.rs b/library/core/benches/ascii/is_ascii.rs index a42a1dcfe3988..05f60a46f8be2 100644 --- a/library/core/benches/ascii/is_ascii.rs +++ b/library/core/benches/ascii/is_ascii.rs @@ -1,6 +1,6 @@ +use test::{black_box, Bencher}; + use super::{LONG, MEDIUM, SHORT}; -use test::black_box; -use test::Bencher; macro_rules! benches { ($( fn $name: ident($arg: ident: &[u8]) $body: block )+) => { diff --git a/library/core/benches/fmt.rs b/library/core/benches/fmt.rs index d1cdb12e50f8c..906d7ac3eef28 100644 --- a/library/core/benches/fmt.rs +++ b/library/core/benches/fmt.rs @@ -1,5 +1,6 @@ use std::fmt::{self, Write as FmtWrite}; use std::io::{self, Write as IoWrite}; + use test::{black_box, Bencher}; #[bench] diff --git a/library/core/benches/hash/sip.rs b/library/core/benches/hash/sip.rs index 725c864dce9f1..8e8c07b6ee4c3 100644 --- a/library/core/benches/hash/sip.rs +++ b/library/core/benches/hash/sip.rs @@ -1,6 +1,7 @@ #![allow(deprecated)] use core::hash::*; + use test::{black_box, Bencher}; fn hash_bytes(mut s: H, x: &[u8]) -> u64 { diff --git a/library/core/benches/iter.rs b/library/core/benches/iter.rs index c1cec5e6d3c8c..24469ba0c4262 100644 --- a/library/core/benches/iter.rs +++ b/library/core/benches/iter.rs @@ -3,6 +3,7 @@ use core::iter::*; use core::mem; use core::num::Wrapping; use core::ops::Range; + use test::{black_box, Bencher}; #[bench] diff --git a/library/core/benches/num/flt2dec/mod.rs b/library/core/benches/num/flt2dec/mod.rs index b1a9fc56bae54..6c7de5dcd2286 100644 --- a/library/core/benches/num/flt2dec/mod.rs +++ b/library/core/benches/num/flt2dec/mod.rs @@ -3,9 +3,9 @@ mod strategy { mod grisu; } -use core::num::flt2dec::MAX_SIG_DIGITS; -use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded}; +use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded, MAX_SIG_DIGITS}; use std::io::Write; + use test::{black_box, Bencher}; pub fn decode_finite(v: T) -> Decoded { diff --git a/library/core/benches/num/flt2dec/strategy/dragon.rs b/library/core/benches/num/flt2dec/strategy/dragon.rs index babedc6c0ec80..4526697140365 100644 --- a/library/core/benches/num/flt2dec/strategy/dragon.rs +++ b/library/core/benches/num/flt2dec/strategy/dragon.rs @@ -1,7 +1,8 @@ -use super::super::*; use core::num::flt2dec::strategy::dragon::*; use std::mem::MaybeUninit; +use super::super::*; + #[bench] fn bench_small_shortest(b: &mut Bencher) { let decoded = decode_finite(3.141592f64); diff --git a/library/core/benches/num/flt2dec/strategy/grisu.rs b/library/core/benches/num/flt2dec/strategy/grisu.rs index b5bddb2c7c746..d20f9b02f7e74 100644 --- a/library/core/benches/num/flt2dec/strategy/grisu.rs +++ b/library/core/benches/num/flt2dec/strategy/grisu.rs @@ -1,7 +1,8 @@ -use super::super::*; use core::num::flt2dec::strategy::grisu::*; use std::mem::MaybeUninit; +use super::super::*; + pub fn decode_finite(v: T) -> Decoded { match decode(v).1 { FullDecoded::Finite(decoded) => decoded, diff --git a/library/core/benches/num/mod.rs b/library/core/benches/num/mod.rs index 4922ee150d95f..c1dc3a3062256 100644 --- a/library/core/benches/num/mod.rs +++ b/library/core/benches/num/mod.rs @@ -4,6 +4,7 @@ mod int_log; mod int_pow; use std::str::FromStr; + use test::{black_box, Bencher}; const ASCII_NUMBERS: [&str; 19] = [ diff --git a/library/core/benches/ops.rs b/library/core/benches/ops.rs index 0a2be8a28819f..3d0b3302957bf 100644 --- a/library/core/benches/ops.rs +++ b/library/core/benches/ops.rs @@ -1,4 +1,5 @@ use core::ops::*; + use test::Bencher; // Overhead of dtors diff --git a/library/core/benches/pattern.rs b/library/core/benches/pattern.rs index 480ac6f36d202..0d60b005feb32 100644 --- a/library/core/benches/pattern.rs +++ b/library/core/benches/pattern.rs @@ -1,5 +1,4 @@ -use test::black_box; -use test::Bencher; +use test::{black_box, Bencher}; #[bench] fn starts_with_char(b: &mut Bencher) { diff --git a/library/core/benches/slice.rs b/library/core/benches/slice.rs index 8f87a211449c0..2741dbd53f14c 100644 --- a/library/core/benches/slice.rs +++ b/library/core/benches/slice.rs @@ -1,6 +1,6 @@ use core::ptr::NonNull; -use test::black_box; -use test::Bencher; + +use test::{black_box, Bencher}; enum Cache { L1, diff --git a/library/core/benches/str.rs b/library/core/benches/str.rs index 0f14809444bc5..a8178f9c18752 100644 --- a/library/core/benches/str.rs +++ b/library/core/benches/str.rs @@ -1,4 +1,5 @@ use std::str; + use test::{black_box, Bencher}; mod char_count; diff --git a/library/core/benches/str/char_count.rs b/library/core/benches/str/char_count.rs index 25d9b2e299223..b87ad0f6adf24 100644 --- a/library/core/benches/str/char_count.rs +++ b/library/core/benches/str/char_count.rs @@ -1,6 +1,7 @@ -use super::corpora::*; use test::{black_box, Bencher}; +use super::corpora::*; + macro_rules! define_benches { ($( fn $name: ident($arg: ident: &str) $body: block )+) => { define_benches!(mod en_tiny, en::TINY, $($name $arg $body)+); diff --git a/library/core/benches/str/debug.rs b/library/core/benches/str/debug.rs index cb91169eed8eb..6dbf4e92c084b 100644 --- a/library/core/benches/str/debug.rs +++ b/library/core/benches/str/debug.rs @@ -4,6 +4,7 @@ //! we should still try to minimize those calls over time rather than regress them. use std::fmt::{self, Write}; + use test::{black_box, Bencher}; #[derive(Default)] diff --git a/library/core/benches/str/iter.rs b/library/core/benches/str/iter.rs index 58ae71fc10f12..f6e73e48d8e7d 100644 --- a/library/core/benches/str/iter.rs +++ b/library/core/benches/str/iter.rs @@ -1,6 +1,7 @@ -use super::corpora; use test::{black_box, Bencher}; +use super::corpora; + #[bench] fn chars_advance_by_1000(b: &mut Bencher) { b.iter(|| black_box(corpora::ru::LARGE).chars().advance_by(1000)); diff --git a/library/core/src/alloc/global.rs b/library/core/src/alloc/global.rs index 8df3ace54ffe1..a6f799c4a7deb 100644 --- a/library/core/src/alloc/global.rs +++ b/library/core/src/alloc/global.rs @@ -1,6 +1,5 @@ use crate::alloc::Layout; -use crate::cmp; -use crate::ptr; +use crate::{cmp, ptr}; /// A memory allocator that can be registered as the standard library’s default /// through the `#[global_allocator]` attribute. @@ -118,7 +117,7 @@ use crate::ptr; /// having side effects. #[stable(feature = "global_alloc", since = "1.28.0")] pub unsafe trait GlobalAlloc { - /// Allocate memory as described by the given `layout`. + /// Allocates memory as described by the given `layout`. /// /// Returns a pointer to newly-allocated memory, /// or null to indicate allocation failure. @@ -153,7 +152,7 @@ pub unsafe trait GlobalAlloc { #[stable(feature = "global_alloc", since = "1.28.0")] unsafe fn alloc(&self, layout: Layout) -> *mut u8; - /// Deallocate the block of memory at the given `ptr` pointer with the given `layout`. + /// Deallocates the block of memory at the given `ptr` pointer with the given `layout`. /// /// # Safety /// @@ -200,7 +199,7 @@ pub unsafe trait GlobalAlloc { ptr } - /// Shrink or grow a block of memory to the given `new_size` in bytes. + /// Shrinks or grows a block of memory to the given `new_size` in bytes. /// The block is described by the given `ptr` pointer and `layout`. /// /// If this returns a non-null pointer, then ownership of the memory block @@ -232,7 +231,7 @@ pub unsafe trait GlobalAlloc { /// * `new_size` must be greater than zero. /// /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`, - /// must not overflow isize (i.e., the rounded value must be less than or + /// must not overflow `isize` (i.e., the rounded value must be less than or /// equal to `isize::MAX`). /// /// (Extension subtraits might provide more specific bounds on diff --git a/library/core/src/alloc/layout.rs b/library/core/src/alloc/layout.rs index 0b92767c93205..549a4bc6727fc 100644 --- a/library/core/src/alloc/layout.rs +++ b/library/core/src/alloc/layout.rs @@ -4,11 +4,9 @@ // collections, resulting in having to optimize down excess IR multiple times. // Your performance intuition is useless. Run perf. -use crate::cmp; use crate::error::Error; -use crate::fmt; -use crate::mem; use crate::ptr::{Alignment, NonNull}; +use crate::{cmp, fmt, mem}; // While this function is used in one place and its implementation // could be inlined, the previous attempts to do so made rustc @@ -26,7 +24,7 @@ const fn size_align() -> (usize, usize) { /// You build a `Layout` up as an input to give to an allocator. /// /// All layouts have an associated size and a power-of-two alignment. The size, when rounded up to -/// the nearest multiple of `align`, does not overflow isize (i.e., the rounded value will always be +/// the nearest multiple of `align`, does not overflow `isize` (i.e., the rounded value will always be /// less than or equal to `isize::MAX`). /// /// (Note that layouts are *not* required to have non-zero size, @@ -61,7 +59,7 @@ impl Layout { /// * `align` must be a power of two, /// /// * `size`, when rounded up to the nearest multiple of `align`, - /// must not overflow isize (i.e., the rounded value must be + /// must not overflow `isize` (i.e., the rounded value must be /// less than or equal to `isize::MAX`). #[stable(feature = "alloc_layout", since = "1.28.0")] #[rustc_const_stable(feature = "const_alloc_layout_size_align", since = "1.50.0")] @@ -183,6 +181,8 @@ impl Layout { /// - a [slice], then the length of the slice tail must be an initialized /// integer, and the size of the *entire value* /// (dynamic tail length + statically sized prefix) must fit in `isize`. + /// For the special case where the dynamic tail length is 0, this function + /// is safe to call. /// - a [trait object], then the vtable part of the pointer must point /// to a valid vtable for the type `T` acquired by an unsizing coercion, /// and the size of the *entire value* diff --git a/library/core/src/alloc/mod.rs b/library/core/src/alloc/mod.rs index 1c8e667654469..aa841db045ce7 100644 --- a/library/core/src/alloc/mod.rs +++ b/library/core/src/alloc/mod.rs @@ -17,10 +17,8 @@ pub use self::layout::Layout; )] #[allow(deprecated, deprecated_in_future)] pub use self::layout::LayoutErr; - #[stable(feature = "alloc_layout_error", since = "1.50.0")] pub use self::layout::LayoutError; - use crate::error::Error; use crate::fmt; use crate::ptr::{self, NonNull}; diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 59f3b6841d531..58107b1e7d074 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -86,9 +86,7 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::fmt; -use crate::hash; -use crate::intrinsics; +use crate::{fmt, hash, intrinsics}; /////////////////////////////////////////////////////////////////////////////// // Any trait diff --git a/library/core/src/arch.rs b/library/core/src/arch.rs index 31d6bc36fc8b9..d681bd124fe13 100644 --- a/library/core/src/arch.rs +++ b/library/core/src/arch.rs @@ -4,6 +4,15 @@ #[stable(feature = "simd_arch", since = "1.27.0")] pub use crate::core_arch::arch::*; +#[cfg(bootstrap)] +#[allow(dead_code)] +#[unstable(feature = "sha512_sm_x86", issue = "126624")] +fn dummy() { + // AArch64 also has a target feature named `sm4`, so we need `#![feature(sha512_sm_x86)]` in lib.rs + // But as the bootstrap compiler doesn't know about this feature yet, we need to convert it to a + // library feature until bootstrap gets bumped +} + /// Inline assembly. /// /// Refer to [Rust By Example] for a usage guide and the [reference] for diff --git a/library/core/src/array/ascii.rs b/library/core/src/array/ascii.rs index 3fea9a44049fb..05797b042ee4a 100644 --- a/library/core/src/array/ascii.rs +++ b/library/core/src/array/ascii.rs @@ -2,7 +2,7 @@ use crate::ascii; #[cfg(not(test))] impl [u8; N] { - /// Converts this array of bytes into a array of ASCII characters, + /// Converts this array of bytes into an array of ASCII characters, /// or returns `None` if any of the characters is non-ASCII. /// /// # Examples @@ -29,7 +29,7 @@ impl [u8; N] { } } - /// Converts this array of bytes into a array of ASCII characters, + /// Converts this array of bytes into an array of ASCII characters, /// without checking whether they're valid. /// /// # Safety diff --git a/library/core/src/array/iter.rs b/library/core/src/array/iter.rs index 3585bf07b597c..2d19e4876f680 100644 --- a/library/core/src/array/iter.rs +++ b/library/core/src/array/iter.rs @@ -1,14 +1,11 @@ //! Defines the `IntoIter` owned iterator for arrays. +use crate::intrinsics::transmute_unchecked; +use crate::iter::{self, FusedIterator, TrustedLen, TrustedRandomAccessNoCoerce}; +use crate::mem::MaybeUninit; use crate::num::NonZero; -use crate::{ - fmt, - intrinsics::transmute_unchecked, - iter::{self, FusedIterator, TrustedLen, TrustedRandomAccessNoCoerce}, - mem::MaybeUninit, - ops::{IndexRange, Range}, - ptr, -}; +use crate::ops::{IndexRange, Range}; +use crate::{fmt, ptr}; /// A by-value [array] iterator. #[stable(feature = "array_value_iter", since = "1.51.0")] @@ -47,8 +44,10 @@ impl IntoIterator for [T; N] { type IntoIter = IntoIter; /// Creates a consuming iterator, that is, one that moves each value out of - /// the array (from start to end). The array cannot be used after calling - /// this unless `T` implements `Copy`, so the whole array is copied. + /// the array (from start to end). + /// + /// The array cannot be used after calling this unless `T` implements + /// `Copy`, so the whole array is copied. /// /// Arrays have special behavior when calling `.into_iter()` prior to the /// 2021 edition -- see the [array] Editions section for more information. diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index 8285c64ed2966..5c826b9993f86 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -23,7 +23,6 @@ mod equality; mod iter; pub(crate) use drain::drain_array_with; - #[stable(feature = "array_value_iter", since = "1.51.0")] pub use iter::IntoIter; diff --git a/library/core/src/ascii.rs b/library/core/src/ascii.rs index e9f4d0f93ed49..5b3711b4071ab 100644 --- a/library/core/src/ascii.rs +++ b/library/core/src/ascii.rs @@ -9,10 +9,9 @@ #![stable(feature = "core_ascii", since = "1.26.0")] -use crate::escape; -use crate::fmt; use crate::iter::FusedIterator; use crate::num::NonZero; +use crate::{escape, fmt}; mod ascii_char; #[unstable(feature = "ascii_char", issue = "110998")] diff --git a/library/core/src/asserting.rs b/library/core/src/asserting.rs index 212b637d34365..3015aa562e6c0 100644 --- a/library/core/src/asserting.rs +++ b/library/core/src/asserting.rs @@ -9,10 +9,8 @@ #![doc(hidden)] #![unstable(feature = "generic_assert_internals", issue = "44838")] -use crate::{ - fmt::{Debug, Formatter}, - marker::PhantomData, -}; +use crate::fmt::{Debug, Formatter}; +use crate::marker::PhantomData; // ***** TryCapture - Generic ***** diff --git a/library/core/src/async_iter/async_iter.rs b/library/core/src/async_iter/async_iter.rs index a0ffb6d47507b..069c50c2531b0 100644 --- a/library/core/src/async_iter/async_iter.rs +++ b/library/core/src/async_iter/async_iter.rs @@ -18,7 +18,7 @@ pub trait AsyncIterator { /// The type of items yielded by the async iterator. type Item; - /// Attempt to pull out the next value of this async iterator, registering the + /// Attempts to pull out the next value of this async iterator, registering the /// current task for wakeup if the value is not yet available, and returning /// `None` if the async iterator is exhausted. /// @@ -139,7 +139,7 @@ impl Poll> { pub const FINISHED: Self = Poll::Ready(None); } -/// Convert something into an async iterator +/// Converts something into an async iterator #[unstable(feature = "async_iterator", issue = "79024")] pub trait IntoAsyncIterator { /// The type of the item yielded by the iterator diff --git a/library/core/src/async_iter/from_iter.rs b/library/core/src/async_iter/from_iter.rs index 3180187afc8c9..f4e10bdffea2f 100644 --- a/library/core/src/async_iter/from_iter.rs +++ b/library/core/src/async_iter/from_iter.rs @@ -1,6 +1,5 @@ -use crate::pin::Pin; - use crate::async_iter::AsyncIterator; +use crate::pin::Pin; use crate::task::{Context, Poll}; /// An async iterator that was created from iterator. diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index b3189f14f9e47..0d66c2b52c84e 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -427,7 +427,9 @@ impl Cell { } /// Swaps the values of two `Cell`s. - /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference. + /// + /// The difference with `std::mem::swap` is that this function doesn't + /// require a `&mut` reference. /// /// # Panics /// @@ -1579,7 +1581,7 @@ impl<'b, T: ?Sized> Ref<'b, T> { ) } - /// Convert into a reference to the underlying data. + /// Converts into a reference to the underlying data. /// /// The underlying `RefCell` can never be mutably borrowed from again and will always appear /// already immutably borrowed. It is not a good idea to leak more than a constant number of @@ -1747,7 +1749,7 @@ impl<'b, T: ?Sized> RefMut<'b, T> { ) } - /// Convert into a mutable reference to the underlying data. + /// Converts into a mutable reference to the underlying data. /// /// The underlying `RefCell` can not be borrowed from again and will always appear already /// mutably borrowed, making the returned reference the only to the interior. @@ -1879,7 +1881,7 @@ impl fmt::Display for RefMut<'_, T> { /// /// If you have a reference `&T`, then normally in Rust the compiler performs optimizations based on /// the knowledge that `&T` points to immutable data. Mutating that data, for example through an -/// alias or by transmuting an `&T` into an `&mut T`, is considered undefined behavior. +/// alias or by transmuting a `&T` into a `&mut T`, is considered undefined behavior. /// `UnsafeCell` opts-out of the immutability guarantee for `&T`: a shared reference /// `&UnsafeCell` may point to data that is being mutated. This is called "interior mutability". /// @@ -1936,7 +1938,7 @@ impl fmt::Display for RefMut<'_, T> { /// to have multiple `&mut UnsafeCell` aliases. That is, `UnsafeCell` is a wrapper /// designed to have a special interaction with _shared_ accesses (_i.e._, through an /// `&UnsafeCell<_>` reference); there is no magic whatsoever when dealing with _exclusive_ -/// accesses (_e.g._, through an `&mut UnsafeCell<_>`): neither the cell nor the wrapped value +/// accesses (_e.g._, through a `&mut UnsafeCell<_>`): neither the cell nor the wrapped value /// may be aliased for the duration of that `&mut` borrow. /// This is showcased by the [`.get_mut()`] accessor, which is a _safe_ getter that yields /// a `&mut T`. diff --git a/library/core/src/cell/lazy.rs b/library/core/src/cell/lazy.rs index 21452d40f9ded..6ec1d2a33bef5 100644 --- a/library/core/src/cell/lazy.rs +++ b/library/core/src/cell/lazy.rs @@ -1,8 +1,7 @@ +use super::UnsafeCell; use crate::ops::Deref; use crate::{fmt, mem}; -use super::UnsafeCell; - enum State { Uninit(F), Init(T), diff --git a/library/core/src/cell/once.rs b/library/core/src/cell/once.rs index 872b4da4dbfda..097fa86c93814 100644 --- a/library/core/src/cell/once.rs +++ b/library/core/src/cell/once.rs @@ -1,6 +1,5 @@ use crate::cell::UnsafeCell; -use crate::fmt; -use crate::mem; +use crate::{fmt, mem}; /// A cell which can nominally be written to only once. /// diff --git a/library/core/src/char/methods.rs b/library/core/src/char/methods.rs index 4186565c131ed..41a19665779b6 100644 --- a/library/core/src/char/methods.rs +++ b/library/core/src/char/methods.rs @@ -1,12 +1,11 @@ //! impl char {} +use super::*; use crate::slice; use crate::str::from_utf8_unchecked_mut; use crate::unicode::printable::is_printable; use crate::unicode::{self, conversions}; -use super::*; - impl char { /// The lowest valid code point a `char` can have, `'\0'`. /// @@ -223,10 +222,7 @@ impl char { /// assert_eq!('❤', c); /// ``` #[stable(feature = "assoc_char_funcs", since = "1.52.0")] - #[rustc_const_stable( - feature = "const_char_from_u32_unchecked", - since = "CURRENT_RUSTC_VERSION" - )] + #[rustc_const_stable(feature = "const_char_from_u32_unchecked", since = "1.81.0")] #[must_use] #[inline] pub const unsafe fn from_u32_unchecked(i: u32) -> char { diff --git a/library/core/src/char/mod.rs b/library/core/src/char/mod.rs index 3c641a2e01c93..e6574ac3c7278 100644 --- a/library/core/src/char/mod.rs +++ b/library/core/src/char/mod.rs @@ -24,6 +24,8 @@ mod convert; mod decode; mod methods; +// stable re-exports +#[rustfmt::skip] #[stable(feature = "try_from", since = "1.34.0")] pub use self::convert::CharTryFromError; #[stable(feature = "char_from_str", since = "1.20.0")] @@ -31,20 +33,22 @@ pub use self::convert::ParseCharError; #[stable(feature = "decode_utf16", since = "1.9.0")] pub use self::decode::{DecodeUtf16, DecodeUtf16Error}; +// perma-unstable re-exports +#[rustfmt::skip] #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] pub use self::methods::encode_utf16_raw; // perma-unstable #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] pub use self::methods::encode_utf8_raw; // perma-unstable +#[rustfmt::skip] use crate::ascii; +pub(crate) use self::methods::EscapeDebugExtArgs; use crate::error::Error; use crate::escape; use crate::fmt::{self, Write}; use crate::iter::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use crate::num::NonZero; -pub(crate) use self::methods::EscapeDebugExtArgs; - // UTF-8 ranges and tags for encoding characters const TAG_CONT: u8 = 0b1000_0000; const TAG_TWO_B: u8 = 0b1100_0000; @@ -121,7 +125,7 @@ pub const fn from_u32(i: u32) -> Option { /// Converts a `u32` to a `char`, ignoring validity. Use [`char::from_u32_unchecked`]. /// instead. #[stable(feature = "char_from_unchecked", since = "1.5.0")] -#[rustc_const_stable(feature = "const_char_from_u32_unchecked", since = "CURRENT_RUSTC_VERSION")] +#[rustc_const_stable(feature = "const_char_from_u32_unchecked", since = "1.81.0")] #[must_use] #[inline] pub const unsafe fn from_u32_unchecked(i: u32) -> char { diff --git a/library/core/src/clone.rs b/library/core/src/clone.rs index 939b2be6dfaf1..76a89eaaff86e 100644 --- a/library/core/src/clone.rs +++ b/library/core/src/clone.rs @@ -160,6 +160,9 @@ pub trait Clone: Sized { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use = "cloning is often expensive and is not expected to have side effects"] + // Clone::clone is special because the compiler generates MIR to implement it for some types. + // See InstanceKind::CloneShim. + #[cfg_attr(not(bootstrap), lang = "clone_fn")] fn clone(&self) -> Self; /// Performs copy-assignment from `source`. diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index cff75870790c5..a1ed993b7d9bf 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -246,15 +246,14 @@ use self::Ordering::*; )] #[rustc_diagnostic_item = "PartialEq"] pub trait PartialEq { - /// This method tests for `self` and `other` values to be equal, and is used - /// by `==`. + /// Tests for `self` and `other` values to be equal, and is used by `==`. #[must_use] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_diagnostic_item = "cmp_partialeq_eq"] fn eq(&self, other: &Rhs) -> bool; - /// This method tests for `!=`. The default implementation is almost always - /// sufficient, and should not be overridden without very good reason. + /// Tests for `!=`. The default implementation is almost always sufficient, + /// and should not be overridden without very good reason. #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] @@ -1163,7 +1162,7 @@ pub trait PartialOrd: PartialEq { #[rustc_diagnostic_item = "cmp_partialord_cmp"] fn partial_cmp(&self, other: &Rhs) -> Option; - /// This method tests less than (for `self` and `other`) and is used by the `<` operator. + /// Tests less than (for `self` and `other`) and is used by the `<` operator. /// /// # Examples /// @@ -1180,8 +1179,8 @@ pub trait PartialOrd: PartialEq { matches!(self.partial_cmp(other), Some(Less)) } - /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=` - /// operator. + /// Tests less than or equal to (for `self` and `other`) and is used by the + /// `<=` operator. /// /// # Examples /// @@ -1198,7 +1197,8 @@ pub trait PartialOrd: PartialEq { matches!(self.partial_cmp(other), Some(Less | Equal)) } - /// This method tests greater than (for `self` and `other`) and is used by the `>` operator. + /// Tests greater than (for `self` and `other`) and is used by the `>` + /// operator. /// /// # Examples /// @@ -1215,8 +1215,8 @@ pub trait PartialOrd: PartialEq { matches!(self.partial_cmp(other), Some(Greater)) } - /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` - /// operator. + /// Tests greater than or equal to (for `self` and `other`) and is used by + /// the `>=` operator. /// /// # Examples /// diff --git a/library/core/src/convert/num.rs b/library/core/src/convert/num.rs index 86c4ea9fab088..0246d0627cafe 100644 --- a/library/core/src/convert/num.rs +++ b/library/core/src/convert/num.rs @@ -208,7 +208,7 @@ macro_rules! impl_try_from_unbounded { impl TryFrom<$source> for $target { type Error = TryFromIntError; - /// Try to create the target number type from a source + /// Tries to create the target number type from a source /// number type. This returns an error if the source value /// is outside of the range of the target type. #[inline] @@ -226,7 +226,7 @@ macro_rules! impl_try_from_lower_bounded { impl TryFrom<$source> for $target { type Error = TryFromIntError; - /// Try to create the target number type from a source + /// Tries to create the target number type from a source /// number type. This returns an error if the source value /// is outside of the range of the target type. #[inline] @@ -248,7 +248,7 @@ macro_rules! impl_try_from_upper_bounded { impl TryFrom<$source> for $target { type Error = TryFromIntError; - /// Try to create the target number type from a source + /// Tries to create the target number type from a source /// number type. This returns an error if the source value /// is outside of the range of the target type. #[inline] @@ -270,7 +270,7 @@ macro_rules! impl_try_from_both_bounded { impl TryFrom<$source> for $target { type Error = TryFromIntError; - /// Try to create the target number type from a source + /// Tries to create the target number type from a source /// number type. This returns an error if the source value /// is outside of the range of the target type. #[inline] diff --git a/library/core/src/default.rs b/library/core/src/default.rs index 4524b352ec817..5cacedcb241a5 100644 --- a/library/core/src/default.rs +++ b/library/core/src/default.rs @@ -103,6 +103,7 @@ use crate::ascii::Char as AsciiChar; /// ``` #[cfg_attr(not(test), rustc_diagnostic_item = "Default")] #[stable(feature = "rust1", since = "1.0.0")] +#[cfg_attr(not(bootstrap), rustc_trivial_field_reads)] pub trait Default: Sized { /// Returns the "default value" for a type. /// diff --git a/library/core/src/error.rs b/library/core/src/error.rs index ca8983d4cbcfe..6cc91849e1dc9 100644 --- a/library/core/src/error.rs +++ b/library/core/src/error.rs @@ -1,5 +1,5 @@ #![doc = include_str!("error.md")] -#![stable(feature = "error_in_core", since = "CURRENT_RUSTC_VERSION")] +#![stable(feature = "error_in_core", since = "1.81.0")] #[cfg(test)] mod tests; @@ -30,7 +30,7 @@ use crate::fmt::{Debug, Display, Formatter, Result}; #[rustc_has_incoherent_inherent_impls] #[allow(multiple_supertrait_upcastable)] pub trait Error: Debug + Display { - /// The lower-level source of this error, if any. + /// Returns the lower-level source of this error, if any. /// /// # Examples /// @@ -121,7 +121,7 @@ pub trait Error: Debug + Display { self.source() } - /// Provides type based access to context intended for error reports. + /// Provides type-based access to context intended for error reports. /// /// Used in conjunction with [`Request::provide_value`] and [`Request::provide_ref`] to extract /// references to member variables from `dyn Error` trait objects. @@ -353,7 +353,7 @@ impl dyn Error { } } -/// Request a value of type `T` from the given `impl Error`. +/// Requests a value of type `T` from the given `impl Error`. /// /// # Examples /// @@ -376,7 +376,7 @@ where request_by_type_tag::<'a, tags::Value>(err) } -/// Request a reference of type `T` from the given `impl Error`. +/// Requests a reference of type `T` from the given `impl Error`. /// /// # Examples /// @@ -506,11 +506,11 @@ where /// ``` /// #[unstable(feature = "error_generic_member_access", issue = "99301")] -#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/90435 +#[repr(transparent)] pub struct Request<'a>(Tagged + 'a>); impl<'a> Request<'a> { - /// Provide a value or other type with only static lifetimes. + /// Provides a value or other type with only static lifetimes. /// /// # Examples /// @@ -544,7 +544,7 @@ impl<'a> Request<'a> { self.provide::>(value) } - /// Provide a value or other type with only static lifetimes computed using a closure. + /// Provides a value or other type with only static lifetimes computed using a closure. /// /// # Examples /// @@ -578,7 +578,7 @@ impl<'a> Request<'a> { self.provide_with::>(fulfil) } - /// Provide a reference. The referee type must be bounded by `'static`, + /// Provides a reference. The referee type must be bounded by `'static`, /// but may be unsized. /// /// # Examples @@ -610,7 +610,7 @@ impl<'a> Request<'a> { self.provide::>>(value) } - /// Provide a reference computed using a closure. The referee type + /// Provides a reference computed using a closure. The referee type /// must be bounded by `'static`, but may be unsized. /// /// # Examples @@ -652,7 +652,7 @@ impl<'a> Request<'a> { self.provide_with::>>(fulfil) } - /// Provide a value with the given `Type` tag. + /// Provides a value with the given `Type` tag. fn provide(&mut self, value: I::Reified) -> &mut Self where I: tags::Type<'a>, @@ -663,7 +663,7 @@ impl<'a> Request<'a> { self } - /// Provide a value with the given `Type` tag, using a closure to prevent unnecessary work. + /// Provides a value with the given `Type` tag, using a closure to prevent unnecessary work. fn provide_with(&mut self, fulfil: impl FnOnce() -> I::Reified) -> &mut Self where I: tags::Type<'a>, @@ -674,13 +674,13 @@ impl<'a> Request<'a> { self } - /// Check if the `Request` would be satisfied if provided with a + /// Checks if the `Request` would be satisfied if provided with a /// value of the specified type. If the type does not match or has /// already been provided, returns false. /// /// # Examples /// - /// Check if an `u8` still needs to be provided and then provides + /// Checks if a `u8` still needs to be provided and then provides /// it. /// /// ```rust @@ -761,13 +761,14 @@ impl<'a> Request<'a> { self.would_be_satisfied_by::>() } - /// Check if the `Request` would be satisfied if provided with a - /// reference to a value of the specified type. If the type does - /// not match or has already been provided, returns false. + /// Checks if the `Request` would be satisfied if provided with a + /// reference to a value of the specified type. + /// + /// If the type does not match or has already been provided, returns false. /// /// # Examples /// - /// Check if a `&str` still needs to be provided and then provides + /// Checks if a `&str` still needs to be provided and then provides /// it. /// /// ```rust diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index 563f0a324e3f1..22084dcff8f88 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -3,16 +3,11 @@ use crate::cmp::Ordering; use crate::error::Error; use crate::ffi::c_char; -use crate::fmt; -use crate::intrinsics; use crate::iter::FusedIterator; use crate::marker::PhantomData; -use crate::ops; -use crate::ptr::addr_of; -use crate::ptr::NonNull; -use crate::slice; +use crate::ptr::{addr_of, NonNull}; use crate::slice::memchr; -use crate::str; +use crate::{fmt, intrinsics, ops, slice, str}; // FIXME: because this is doc(inline)d, we *have* to use intra-doc links because the actual link // depends on where the item is being documented. however, since this is libcore, we can't @@ -94,7 +89,7 @@ use crate::str; /// ``` /// /// [str]: prim@str "str" -#[derive(Hash)] +#[derive(PartialEq, Eq, Hash)] #[stable(feature = "core_c_str", since = "1.64.0")] #[rustc_has_incoherent_inherent_impls] #[lang = "CStr"] @@ -103,8 +98,7 @@ use crate::str; // However, `CStr` layout is considered an implementation detail and must not be relied upon. We // want `repr(transparent)` but we don't want it to show up in rustdoc, so we hide it under // `cfg(doc)`. This is an ad-hoc implementation of attribute privacy. -#[cfg_attr(not(doc), repr(transparent))] -#[allow(clippy::derived_hash_with_manual_eq)] +#[repr(transparent)] pub struct CStr { // FIXME: this should not be represented with a DST slice but rather with // just a raw `c_char` along with some form of marker to make @@ -278,7 +272,7 @@ impl CStr { #[inline] // inline is necessary for codegen to see strlen. #[must_use] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")] pub const unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr { // SAFETY: The caller has provided a pointer that points to a valid C // string with a NUL terminator less than `isize::MAX` from `ptr`. @@ -540,7 +534,7 @@ impl CStr { #[must_use] #[doc(alias("len", "strlen"))] #[stable(feature = "cstr_count_bytes", since = "1.79.0")] - #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")] pub const fn count_bytes(&self) -> usize { self.inner.len() - 1 } @@ -678,15 +672,9 @@ impl CStr { } } -#[stable(feature = "rust1", since = "1.0.0")] -impl PartialEq for CStr { - #[inline] - fn eq(&self, other: &CStr) -> bool { - self.to_bytes().eq(other.to_bytes()) - } -} -#[stable(feature = "rust1", since = "1.0.0")] -impl Eq for CStr {} +// `.to_bytes()` representations are compared instead of the inner `[c_char]`s, +// because `c_char` is `i8` (not `u8`) on some platforms. +// That is why this is implemented manually and not derived. #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for CStr { #[inline] @@ -741,7 +729,7 @@ impl AsRef for CStr { /// located within `isize::MAX` from `ptr`. #[inline] #[unstable(feature = "cstr_internals", issue = "none")] -#[rustc_const_stable(feature = "const_cstr_from_ptr", since = "CURRENT_RUSTC_VERSION")] +#[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")] #[rustc_allow_const_fn_unstable(const_eval_select)] const unsafe fn strlen(ptr: *const c_char) -> usize { const fn strlen_ct(s: *const c_char) -> usize { diff --git a/library/core/src/ffi/mod.rs b/library/core/src/ffi/mod.rs index 88adc378477fd..ec1f9052a1564 100644 --- a/library/core/src/ffi/mod.rs +++ b/library/core/src/ffi/mod.rs @@ -9,19 +9,16 @@ #![stable(feature = "core_ffi", since = "1.30.0")] #![allow(non_camel_case_types)] -use crate::fmt; - -#[doc(no_inline)] +#[doc(inline)] #[stable(feature = "core_c_str", since = "1.64.0")] -pub use self::c_str::FromBytesWithNulError; - +pub use self::c_str::CStr; #[doc(no_inline)] #[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")] pub use self::c_str::FromBytesUntilNulError; - -#[doc(inline)] +#[doc(no_inline)] #[stable(feature = "core_c_str", since = "1.64.0")] -pub use self::c_str::CStr; +pub use self::c_str::FromBytesWithNulError; +use crate::fmt; #[unstable(feature = "c_str_module", issue = "112134")] pub mod c_str; @@ -191,7 +188,7 @@ mod c_long_definition { // be UB. #[doc = include_str!("c_void.md")] #[lang = "c_void"] -#[cfg_attr(not(doc), repr(u8))] // work around https://github.com/rust-lang/rust/issues/90435 +#[cfg_attr(not(doc), repr(u8))] // An implementation detail we don't want to show up in rustdoc #[stable(feature = "core_c_void", since = "1.30.0")] pub enum c_void { #[unstable( diff --git a/library/core/src/ffi/va_list.rs b/library/core/src/ffi/va_list.rs index 6a2e8b67d0c2a..3a224e4d8fe5f 100644 --- a/library/core/src/ffi/va_list.rs +++ b/library/core/src/ffi/va_list.rs @@ -3,7 +3,6 @@ //! Better known as "varargs". use crate::ffi::c_void; - #[allow(unused_imports)] use crate::fmt; use crate::marker::PhantomData; @@ -23,7 +22,7 @@ use crate::ops::{Deref, DerefMut}; target_os = "uefi", windows, ))] -#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/90435 +#[repr(transparent)] #[lang = "va_list"] pub struct VaListImpl<'f> { ptr: *mut c_void, @@ -115,7 +114,7 @@ pub struct VaListImpl<'f> { } /// A wrapper for a `va_list` -#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/90435 +#[repr(transparent)] #[derive(Debug)] pub struct VaList<'a, 'f: 'a> { #[cfg(any( @@ -162,7 +161,7 @@ pub struct VaList<'a, 'f: 'a> { windows, ))] impl<'f> VaListImpl<'f> { - /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`. + /// Converts a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`. #[inline] pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> { VaList { inner: VaListImpl { ..*self }, _marker: PhantomData } @@ -182,7 +181,7 @@ impl<'f> VaListImpl<'f> { not(windows), ))] impl<'f> VaListImpl<'f> { - /// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`. + /// Converts a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`. #[inline] pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> { VaList { inner: self, _marker: PhantomData } diff --git a/library/core/src/fmt/builders.rs b/library/core/src/fmt/builders.rs index 36fae1c15960e..794ca1851b13d 100644 --- a/library/core/src/fmt/builders.rs +++ b/library/core/src/fmt/builders.rs @@ -402,6 +402,7 @@ impl<'a, 'b: 'a> DebugTuple<'a, 'b> { } } +/// A helper used to print list-like items with no special formatting. struct DebugInner<'a, 'b: 'a> { fmt: &'a mut fmt::Formatter<'b>, result: fmt::Result, @@ -578,7 +579,8 @@ impl<'a, 'b: 'a> DebugSet<'a, 'b> { /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn finish(&mut self) -> fmt::Result { - self.inner.result.and_then(|_| self.inner.fmt.write_str("}")) + self.inner.result = self.inner.result.and_then(|_| self.inner.fmt.write_str("}")); + self.inner.result } } @@ -721,7 +723,8 @@ impl<'a, 'b: 'a> DebugList<'a, 'b> { /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn finish(&mut self) -> fmt::Result { - self.inner.result.and_then(|_| self.inner.fmt.write_str("]")) + self.inner.result = self.inner.result.and_then(|_| self.inner.fmt.write_str("]")); + self.inner.result } } @@ -1002,11 +1005,12 @@ impl<'a, 'b: 'a> DebugMap<'a, 'b> { /// ``` #[stable(feature = "debug_builders", since = "1.2.0")] pub fn finish(&mut self) -> fmt::Result { - self.result.and_then(|_| { + self.result = self.result.and_then(|_| { assert!(!self.has_key, "attempted to finish a map with a partial entry"); self.fmt.write_str("}") - }) + }); + self.result } fn is_pretty(&self) -> bool { diff --git a/library/core/src/fmt/float.rs b/library/core/src/fmt/float.rs index 80c45fce2f0a0..20ea0352c2dce 100644 --- a/library/core/src/fmt/float.rs +++ b/library/core/src/fmt/float.rs @@ -1,7 +1,6 @@ use crate::fmt::{Debug, Display, Formatter, LowerExp, Result, UpperExp}; use crate::mem::MaybeUninit; -use crate::num::flt2dec; -use crate::num::fmt as numfmt; +use crate::num::{flt2dec, fmt as numfmt}; #[doc(hidden)] trait GeneralFormat: PartialOrd { diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index 25ab5b2db9641..60c0dc7685253 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -4,13 +4,10 @@ use crate::cell::{Cell, Ref, RefCell, RefMut, SyncUnsafeCell, UnsafeCell}; use crate::char::EscapeDebugExtArgs; -use crate::iter; use crate::marker::PhantomData; -use crate::mem; use crate::num::fmt as numfmt; use crate::ops::Deref; -use crate::result; -use crate::str; +use crate::{iter, mem, result, str}; mod builders; #[cfg(not(no_fp_fmt_parse))] @@ -36,11 +33,10 @@ pub enum Alignment { Center, } -#[stable(feature = "debug_builders", since = "1.2.0")] -pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; - #[unstable(feature = "debug_closure_helpers", issue = "117729")] pub use self::builders::FormatterFn; +#[stable(feature = "debug_builders", since = "1.2.0")] +pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; /// The type returned by formatter methods. /// @@ -354,7 +350,7 @@ impl<'a> Arguments<'a> { Arguments { pieces, fmt: None, args } } - /// This function is used to specify nonstandard formatting parameters. + /// Specifies nonstandard formatting parameters. /// /// An `rt::UnsafeArg` is required because the following invariants must be held /// in order for this function to be safe: @@ -396,7 +392,7 @@ impl<'a> Arguments<'a> { } impl<'a> Arguments<'a> { - /// Get the formatted string, if it has no arguments to be formatted at runtime. + /// Gets the formatted string, if it has no arguments to be formatted at runtime. /// /// This can be used to avoid allocations in some cases. /// @@ -1129,8 +1125,8 @@ pub trait UpperExp { fn fmt(&self, f: &mut Formatter<'_>) -> Result; } -/// The `write` function takes an output stream, and an `Arguments` struct -/// that can be precompiled with the `format_args!` macro. +/// Takes an output stream and an `Arguments` struct that can be precompiled with +/// the `format_args!` macro. /// /// The arguments will be formatted according to the specified format string /// into the output stream provided. @@ -1257,7 +1253,7 @@ impl PostPadding { PostPadding { fill, padding } } - /// Write this post padding. + /// Writes this post padding. pub(crate) fn write(self, f: &mut Formatter<'_>) -> Result { for _ in 0..self.padding { f.buf.write_char(self.fill)?; @@ -1398,9 +1394,10 @@ impl<'a> Formatter<'a> { } } - /// This function takes a string slice and emits it to the internal buffer - /// after applying the relevant formatting flags specified. The flags - /// recognized for generic strings are: + /// Takes a string slice and emits it to the internal buffer after applying + /// the relevant formatting flags specified. + /// + /// The flags recognized for generic strings are: /// /// * width - the minimum width of what to emit /// * fill/align - what to emit and where to emit it if the string @@ -1474,9 +1471,10 @@ impl<'a> Formatter<'a> { } } - /// Write the pre-padding and return the unwritten post-padding. Callers are - /// responsible for ensuring post-padding is written after the thing that is - /// being padded. + /// Writes the pre-padding and returns the unwritten post-padding. + /// + /// Callers are responsible for ensuring post-padding is written after the + /// thing that is being padded. pub(crate) fn padding( &mut self, padding: usize, @@ -1503,6 +1501,7 @@ impl<'a> Formatter<'a> { } /// Takes the formatted parts and applies the padding. + /// /// Assumes that the caller already has rendered the parts with required precision, /// so that `self.precision` can be ignored. /// @@ -1655,7 +1654,7 @@ impl<'a> Formatter<'a> { } } - /// Flags for formatting + /// Returns flags for formatting. #[must_use] #[stable(feature = "rust1", since = "1.0.0")] #[deprecated( @@ -1667,7 +1666,7 @@ impl<'a> Formatter<'a> { self.flags } - /// Character used as 'fill' whenever there is alignment. + /// Returns the character used as 'fill' whenever there is alignment. /// /// # Examples /// @@ -1700,7 +1699,7 @@ impl<'a> Formatter<'a> { self.fill } - /// Flag indicating what form of alignment was requested. + /// Returns a flag indicating what form of alignment was requested. /// /// # Examples /// @@ -1740,7 +1739,7 @@ impl<'a> Formatter<'a> { } } - /// Optionally specified integer width that the output should be. + /// Returns the optionally specified integer width that the output should be. /// /// # Examples /// @@ -1770,8 +1769,8 @@ impl<'a> Formatter<'a> { self.width } - /// Optionally specified precision for numeric types. Alternatively, the - /// maximum width for string types. + /// Returns the optionally specified precision for numeric types. + /// Alternatively, the maximum width for string types. /// /// # Examples /// @@ -1967,8 +1966,9 @@ impl<'a> Formatter<'a> { builders::debug_struct_new(self, name) } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_struct_fields_finish` is more general, but this is faster for 1 field. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_struct_fields_finish` is more general, but this is + /// faster for 1 field. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_struct_field1_finish<'b>( @@ -1982,8 +1982,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_struct_fields_finish` is more general, but this is faster for 2 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_struct_fields_finish` is more general, but this is + /// faster for 2 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_struct_field2_finish<'b>( @@ -2000,8 +2001,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_struct_fields_finish` is more general, but this is faster for 3 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_struct_fields_finish` is more general, but this is + /// faster for 3 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_struct_field3_finish<'b>( @@ -2021,8 +2023,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_struct_fields_finish` is more general, but this is faster for 4 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_struct_fields_finish` is more general, but this is + /// faster for 4 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_struct_field4_finish<'b>( @@ -2045,8 +2048,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_struct_fields_finish` is more general, but this is faster for 5 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_struct_fields_finish` is more general, but this is + /// faster for 5 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_struct_field5_finish<'b>( @@ -2072,7 +2076,7 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller binaries. /// For the cases not covered by `debug_struct_field[12345]_finish`. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] @@ -2121,8 +2125,9 @@ impl<'a> Formatter<'a> { builders::debug_tuple_new(self, name) } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_tuple_fields_finish` is more general, but this is faster for 1 field. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_tuple_fields_finish` is more general, but this is faster + /// for 1 field. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_field1_finish<'b>(&'b mut self, name: &str, value1: &dyn Debug) -> Result { @@ -2131,8 +2136,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_tuple_fields_finish` is more general, but this is faster for 2 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_tuple_fields_finish` is more general, but this is faster + /// for 2 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_field2_finish<'b>( @@ -2147,8 +2153,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_tuple_fields_finish` is more general, but this is faster for 3 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_tuple_fields_finish` is more general, but this is faster + /// for 3 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_field3_finish<'b>( @@ -2165,8 +2172,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_tuple_fields_finish` is more general, but this is faster for 4 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_tuple_fields_finish` is more general, but this is faster + /// for 4 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_field4_finish<'b>( @@ -2185,8 +2193,9 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// `debug_tuple_fields_finish` is more general, but this is faster for 5 fields. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. `debug_tuple_fields_finish` is more general, but this is faster + /// for 5 fields. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_field5_finish<'b>( @@ -2207,8 +2216,8 @@ impl<'a> Formatter<'a> { builder.finish() } - /// Used to shrink `derive(Debug)` code, for faster compilation and smaller binaries. - /// For the cases not covered by `debug_tuple_field[12345]_finish`. + /// Shrinks `derive(Debug)` code, for faster compilation and smaller + /// binaries. For the cases not covered by `debug_tuple_field[12345]_finish`. #[doc(hidden)] #[unstable(feature = "fmt_helpers_for_derive", issue = "none")] pub fn debug_tuple_fields_finish<'b>( @@ -2496,8 +2505,9 @@ impl Pointer for *const T { } } -/// Since the formatting will be identical for all pointer types, use a non-monomorphized -/// implementation for the actual formatting to reduce the amount of codegen work needed. +/// Since the formatting will be identical for all pointer types, uses a +/// non-monomorphized implementation for the actual formatting to reduce the +/// amount of codegen work needed. /// /// This uses `ptr_addr: usize` and not `ptr: *const ()` to be able to use this for /// `fn(...) -> ...` without using [problematic] "Oxford Casts". diff --git a/library/core/src/fmt/num.rs b/library/core/src/fmt/num.rs index 3a5a5af8bf5d3..e7726da8d91f2 100644 --- a/library/core/src/fmt/num.rs +++ b/library/core/src/fmt/num.rs @@ -1,12 +1,9 @@ //! Integer and floating-point number formatting -use crate::fmt; use crate::mem::MaybeUninit; use crate::num::fmt as numfmt; use crate::ops::{Div, Rem, Sub}; -use crate::ptr; -use crate::slice; -use crate::str; +use crate::{fmt, ptr, slice, str}; #[doc(hidden)] trait DisplayInt: diff --git a/library/core/src/future/async_drop.rs b/library/core/src/future/async_drop.rs index 63193bbfb35e8..8971a2c0aafd1 100644 --- a/library/core/src/future/async_drop.rs +++ b/library/core/src/future/async_drop.rs @@ -205,7 +205,7 @@ async unsafe fn slice(s: *mut [T]) { } } -/// Construct a chain of two futures, which awaits them sequentially as +/// Constructs a chain of two futures, which awaits them sequentially as /// a future. #[lang = "async_drop_chain"] async fn chain(first: F, last: G) @@ -235,8 +235,8 @@ async unsafe fn defer(to_drop: *mut T) { /// /// # Safety /// -/// User should carefully manage returned future, since it would -/// try creating an immutable referece from `this` and get pointee's +/// Users should carefully manage the returned future, since it would +/// try creating an immutable reference from `this` and get pointee's /// discriminant. // FIXME(zetanumbers): Send and Sync impls #[lang = "async_drop_either"] diff --git a/library/core/src/future/future.rs b/library/core/src/future/future.rs index c80cfdcebf70d..ca1c2d1ca1f2e 100644 --- a/library/core/src/future/future.rs +++ b/library/core/src/future/future.rs @@ -38,7 +38,7 @@ pub trait Future { #[lang = "future_output"] type Output; - /// Attempt to resolve the future to a final value, registering + /// Attempts to resolve the future to a final value, registering /// the current task for wakeup if the value is not yet available. /// /// # Return value diff --git a/library/core/src/future/into_future.rs b/library/core/src/future/into_future.rs index eb5a9b72dd0f2..aa546b940b23a 100644 --- a/library/core/src/future/into_future.rs +++ b/library/core/src/future/into_future.rs @@ -40,7 +40,7 @@ use crate::future::Future; /// } /// /// impl Multiply { -/// /// Construct a new instance of `Multiply`. +/// /// Constructs a new instance of `Multiply`. /// pub fn new(num: u16, factor: u16) -> Self { /// Self { num, factor } /// } @@ -89,7 +89,7 @@ use crate::future::Future; /// ```rust /// use std::future::IntoFuture; /// -/// /// Convert the output of a future to a string. +/// /// Converts the output of a future to a string. /// async fn fut_to_string(fut: Fut) -> String /// where /// Fut: IntoFuture, diff --git a/library/core/src/future/mod.rs b/library/core/src/future/mod.rs index 3a1451abfa40b..d188f1c713079 100644 --- a/library/core/src/future/mod.rs +++ b/library/core/src/future/mod.rs @@ -20,25 +20,21 @@ mod pending; mod poll_fn; mod ready; -#[stable(feature = "futures_api", since = "1.36.0")] -pub use self::future::Future; - -#[unstable(feature = "future_join", issue = "91642")] -pub use self::join::join; - +#[unstable(feature = "async_drop", issue = "126482")] +pub use async_drop::{async_drop, async_drop_in_place, AsyncDrop, AsyncDropInPlace}; #[stable(feature = "into_future", since = "1.64.0")] pub use into_future::IntoFuture; - #[stable(feature = "future_readiness_fns", since = "1.48.0")] pub use pending::{pending, Pending}; -#[stable(feature = "future_readiness_fns", since = "1.48.0")] -pub use ready::{ready, Ready}; - #[stable(feature = "future_poll_fn", since = "1.64.0")] pub use poll_fn::{poll_fn, PollFn}; +#[stable(feature = "future_readiness_fns", since = "1.48.0")] +pub use ready::{ready, Ready}; -#[unstable(feature = "async_drop", issue = "126482")] -pub use async_drop::{async_drop, async_drop_in_place, AsyncDrop, AsyncDropInPlace}; +#[stable(feature = "futures_api", since = "1.36.0")] +pub use self::future::Future; +#[unstable(feature = "future_join", issue = "91642")] +pub use self::join::join; /// This type is needed because: /// diff --git a/library/core/src/hash/mod.rs b/library/core/src/hash/mod.rs index da734466263ab..061690e88ddf8 100644 --- a/library/core/src/hash/mod.rs +++ b/library/core/src/hash/mod.rs @@ -83,17 +83,14 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::fmt; -use crate::marker; - #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] pub use self::sip::SipHasher; - #[unstable(feature = "hashmap_internals", issue = "none")] #[allow(deprecated)] #[doc(hidden)] pub use self::sip::SipHasher13; +use crate::{fmt, marker}; mod sip; @@ -806,10 +803,8 @@ impl PartialEq for BuildHasherDefault { impl Eq for BuildHasherDefault {} mod impls { - use crate::mem; - use crate::slice; - use super::*; + use crate::{mem, slice}; macro_rules! impl_write { ($(($ty:ident, $meth:ident),)*) => {$( diff --git a/library/core/src/hash/sip.rs b/library/core/src/hash/sip.rs index 0d1ac64aa56cf..17f2caaa0c083 100644 --- a/library/core/src/hash/sip.rs +++ b/library/core/src/hash/sip.rs @@ -2,10 +2,8 @@ #![allow(deprecated)] // the types in this module are deprecated -use crate::cmp; use crate::marker::PhantomData; -use crate::mem; -use crate::ptr; +use crate::{cmp, mem, ptr}; /// An implementation of SipHash 1-3. /// diff --git a/library/core/src/hint.rs b/library/core/src/hint.rs index b3e36e6fbc4ac..6ca5e53df3b01 100644 --- a/library/core/src/hint.rs +++ b/library/core/src/hint.rs @@ -3,8 +3,7 @@ //! Hints to compiler that affects how code should be emitted or optimized. //! Hints may be compile time or runtime. -use crate::intrinsics; -use crate::ub_checks; +use crate::{intrinsics, ub_checks}; /// Informs the compiler that the site which is calling this function is not /// reachable, possibly enabling further optimizations. @@ -195,8 +194,8 @@ pub const unsafe fn unreachable_unchecked() -> ! { #[track_caller] #[inline(always)] #[doc(alias = "assume")] -#[stable(feature = "hint_assert_unchecked", since = "CURRENT_RUSTC_VERSION")] -#[rustc_const_stable(feature = "hint_assert_unchecked", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "hint_assert_unchecked", since = "1.81.0")] +#[rustc_const_stable(feature = "hint_assert_unchecked", since = "1.81.0")] pub const unsafe fn assert_unchecked(cond: bool) { // SAFETY: The caller promised `cond` is true. unsafe { diff --git a/library/core/src/internal_macros.rs b/library/core/src/internal_macros.rs index bf53b2245ac59..fe4fa80263c28 100644 --- a/library/core/src/internal_macros.rs +++ b/library/core/src/internal_macros.rs @@ -80,7 +80,7 @@ macro_rules! forward_ref_op_assign { } } -/// Create a zero-size type similar to a closure type, but named. +/// Creates a zero-size type similar to a closure type, but named. macro_rules! impl_fn_for_zst { ($( $( #[$attr: meta] )* diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index c4c6388338949..e9eacbcd25a0a 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -63,10 +63,8 @@ )] #![allow(missing_docs)] -use crate::marker::DiscriminantKind; -use crate::marker::Tuple; -use crate::ptr; -use crate::ub_checks; +use crate::marker::{DiscriminantKind, Tuple}; +use crate::{ptr, ub_checks}; pub mod mir; pub mod simd; @@ -1010,6 +1008,34 @@ pub const fn unlikely(b: bool) -> bool { b } +/// Returns either `true_val` or `false_val` depending on condition `b` with a +/// hint to the compiler that this condition is unlikely to be correctly +/// predicted by a CPU's branch predictor (e.g. a binary search). +/// +/// This is otherwise functionally equivalent to `if b { true_val } else { false_val }`. +/// +/// Note that, unlike most intrinsics, this is safe to call; +/// it does not require an `unsafe` block. +/// Therefore, implementations must not require the user to uphold +/// any safety invariants. +/// +/// This intrinsic does not have a stable counterpart. +#[cfg(not(bootstrap))] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_intrinsic] +#[rustc_nounwind] +#[miri::intrinsic_fallback_is_spec] +#[inline] +pub fn select_unpredictable(b: bool, true_val: T, false_val: T) -> T { + if b { true_val } else { false_val } +} + +#[cfg(bootstrap)] +#[inline] +pub fn select_unpredictable(b: bool, true_val: T, false_val: T) -> T { + if b { true_val } else { false_val } +} + extern "rust-intrinsic" { /// Executes a breakpoint trap, for inspection by a debugger. /// @@ -1017,45 +1043,6 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn breakpoint(); - #[cfg(bootstrap)] - #[rustc_const_stable(feature = "const_size_of", since = "1.40.0")] - #[rustc_safe_intrinsic] - #[rustc_nounwind] - pub fn size_of() -> usize; - - #[cfg(bootstrap)] - #[rustc_const_stable(feature = "const_min_align_of", since = "1.40.0")] - #[rustc_safe_intrinsic] - #[rustc_nounwind] - pub fn min_align_of() -> usize; - - #[cfg(bootstrap)] - #[rustc_const_unstable(feature = "const_pref_align_of", issue = "91971")] - #[rustc_nounwind] - pub fn pref_align_of() -> usize; - - #[cfg(bootstrap)] - #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")] - #[rustc_nounwind] - pub fn size_of_val(_: *const T) -> usize; - - #[cfg(bootstrap)] - #[rustc_const_unstable(feature = "const_align_of_val", issue = "46571")] - #[rustc_nounwind] - pub fn min_align_of_val(_: *const T) -> usize; - - #[cfg(bootstrap)] - #[rustc_const_unstable(feature = "const_type_name", issue = "63084")] - #[rustc_safe_intrinsic] - #[rustc_nounwind] - pub fn type_name() -> &'static str; - - #[cfg(bootstrap)] - #[rustc_const_unstable(feature = "const_type_id", issue = "77125")] - #[rustc_safe_intrinsic] - #[rustc_nounwind] - pub fn type_id() -> u128; - /// A guard for unsafe functions that cannot ever be executed if `T` is uninhabited: /// This will statically either panic, or do nothing. /// @@ -1252,7 +1239,7 @@ extern "rust-intrinsic" { /// - If the code actually wants to work on the address the pointer points to, it can use `as` /// casts or [`ptr.addr()`][pointer::addr]. /// - /// Turning a `*mut T` into an `&mut T`: + /// Turning a `*mut T` into a `&mut T`: /// /// ``` /// let ptr: *mut i32 = &mut 0; @@ -1264,7 +1251,7 @@ extern "rust-intrinsic" { /// let ref_casted = unsafe { &mut *ptr }; /// ``` /// - /// Turning an `&mut T` into an `&mut U`: + /// Turning a `&mut T` into a `&mut U`: /// /// ``` /// let ptr = &mut 0; @@ -1277,7 +1264,7 @@ extern "rust-intrinsic" { /// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) }; /// ``` /// - /// Turning an `&str` into a `&[u8]`: + /// Turning a `&str` into a `&[u8]`: /// /// ``` /// // this is not a good way to do this. @@ -1363,7 +1350,7 @@ extern "rust-intrinsic" { /// } /// /// // This gets rid of the type safety problems; `&mut *` will *only* give - /// // you an `&mut T` from an `&mut T` or `*mut T`. + /// // you a `&mut T` from a `&mut T` or `*mut T`. /// fn split_at_mut_casts(slice: &mut [T], mid: usize) /// -> (&mut [T], &mut [T]) { /// let len = slice.len(); @@ -1944,7 +1931,7 @@ extern "rust-intrinsic" { #[rustc_safe_intrinsic] pub fn frem_algebraic(a: T, b: T) -> T; - /// Convert with LLVM’s fptoui/fptosi, which may return undef for values out of range + /// Converts with LLVM’s fptoui/fptosi, which may return undef for values out of range /// () /// /// Stabilized as [`f32::to_int_unchecked`] and [`f64::to_int_unchecked`]. @@ -2385,12 +2372,6 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn discriminant_value(v: &T) -> ::Discriminant; - #[cfg(bootstrap)] - #[rustc_const_unstable(feature = "variant_count", issue = "73662")] - #[rustc_safe_intrinsic] - #[rustc_nounwind] - pub fn variant_count() -> usize; - /// Rust's "try catch" construct for unwinding. Invokes the function pointer `try_fn` with the /// data pointer `data`, and calls `catch_fn` if unwinding occurs while `try_fn` runs. /// @@ -2455,11 +2436,13 @@ extern "rust-intrinsic" { /// /// # Safety /// - /// It's UB to call this if any of the *bytes* in `*a` or `*b` are uninitialized or carry a - /// pointer value. + /// It's UB to call this if any of the *bytes* in `*a` or `*b` are uninitialized. /// Note that this is a stricter criterion than just the *values* being /// fully-initialized: if `T` has padding, it's UB to call this intrinsic. /// + /// At compile-time, it is furthermore UB to call this if any of the bytes + /// in `*a` or `*b` have provenance. + /// /// (The implementation is allowed to branch on the results of comparisons, /// which is UB if any of their inputs are `undef`.) #[rustc_const_unstable(feature = "const_intrinsic_raw_eq", issue = "none")] @@ -2768,7 +2751,6 @@ pub unsafe fn vtable_align(_ptr: *const ()) -> usize { #[rustc_const_stable(feature = "const_size_of", since = "1.40.0")] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] -#[cfg(not(bootstrap))] pub const fn size_of() -> usize { unreachable!() } @@ -2786,7 +2768,6 @@ pub const fn size_of() -> usize { #[rustc_const_stable(feature = "const_min_align_of", since = "1.40.0")] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] -#[cfg(not(bootstrap))] pub const fn min_align_of() -> usize { unreachable!() } @@ -2800,7 +2781,6 @@ pub const fn min_align_of() -> usize { #[rustc_const_unstable(feature = "const_pref_align_of", issue = "91971")] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] -#[cfg(not(bootstrap))] pub const unsafe fn pref_align_of() -> usize { unreachable!() } @@ -2819,7 +2799,6 @@ pub const unsafe fn pref_align_of() -> usize { #[rustc_const_unstable(feature = "variant_count", issue = "73662")] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] -#[cfg(not(bootstrap))] pub const fn variant_count() -> usize { unreachable!() } @@ -2836,7 +2815,6 @@ pub const fn variant_count() -> usize { #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] -#[cfg(not(bootstrap))] pub const unsafe fn size_of_val(_ptr: *const T) -> usize { unreachable!() } @@ -2853,7 +2831,6 @@ pub const unsafe fn size_of_val(_ptr: *const T) -> usize { #[rustc_const_unstable(feature = "const_align_of_val", issue = "46571")] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] -#[cfg(not(bootstrap))] pub const unsafe fn min_align_of_val(_ptr: *const T) -> usize { unreachable!() } @@ -2871,7 +2848,6 @@ pub const unsafe fn min_align_of_val(_ptr: *const T) -> usize { #[rustc_const_unstable(feature = "const_type_name", issue = "63084")] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] -#[cfg(not(bootstrap))] pub const fn type_name() -> &'static str { unreachable!() } @@ -2891,7 +2867,6 @@ pub const fn type_name() -> &'static str { #[rustc_const_unstable(feature = "const_type_id", issue = "77125")] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] -#[cfg(not(bootstrap))] pub const fn type_id() -> u128 { unreachable!() } diff --git a/library/core/src/intrinsics/mir.rs b/library/core/src/intrinsics/mir.rs index 1daf1d723fb95..c7cec396e1f2e 100644 --- a/library/core/src/intrinsics/mir.rs +++ b/library/core/src/intrinsics/mir.rs @@ -247,6 +247,8 @@ //! otherwise branch. //! - [`Call`] has an associated function as well, with special syntax: //! `Call(ret_val = function(arg1, arg2, ...), ReturnTo(next_block), UnwindContinue())`. +//! - [`TailCall`] does not have a return destination or next block, so its syntax is just +//! `TailCall(function(arg1, arg2, ...))`. #![unstable( feature = "custom_mir", @@ -276,8 +278,7 @@ pub enum UnwindTerminateReason { InCleanup, } -pub use UnwindTerminateReason::Abi as ReasonAbi; -pub use UnwindTerminateReason::InCleanup as ReasonInCleanup; +pub use UnwindTerminateReason::{Abi as ReasonAbi, InCleanup as ReasonInCleanup}; macro_rules! define { ($name:literal, $( #[ $meta:meta ] )* fn $($sig:tt)*) => { @@ -351,6 +352,12 @@ define!("mir_call", /// - [`UnwindCleanup`] fn Call(call: (), goto: ReturnToArg, unwind_action: UnwindActionArg) ); +define!("mir_tail_call", + /// Call a function. + /// + /// The argument must be of the form `fun(arg1, arg2, ...)`. + fn TailCall(call: T) +); define!("mir_unwind_resume", /// A terminator that resumes the unwinding. fn UnwindResume() diff --git a/library/core/src/intrinsics/simd.rs b/library/core/src/intrinsics/simd.rs index 30734c020b39b..221724d7b4ae9 100644 --- a/library/core/src/intrinsics/simd.rs +++ b/library/core/src/intrinsics/simd.rs @@ -3,7 +3,7 @@ //! In this module, a "vector" is any `repr(simd)` type. extern "rust-intrinsic" { - /// Insert an element into a vector, returning the updated vector. + /// Inserts an element into a vector, returning the updated vector. /// /// `T` must be a vector with element type `U`. /// @@ -13,7 +13,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_insert(x: T, idx: u32, val: U) -> T; - /// Extract an element from a vector. + /// Extracts an element from a vector. /// /// `T` must be a vector with element type `U`. /// @@ -23,25 +23,25 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_extract(x: T, idx: u32) -> U; - /// Add two simd vectors elementwise. + /// Adds two simd vectors elementwise. /// /// `T` must be a vector of integer or floating point primitive types. #[rustc_nounwind] pub fn simd_add(x: T, y: T) -> T; - /// Subtract `rhs` from `lhs` elementwise. + /// Subtracts `rhs` from `lhs` elementwise. /// /// `T` must be a vector of integer or floating point primitive types. #[rustc_nounwind] pub fn simd_sub(lhs: T, rhs: T) -> T; - /// Multiply two simd vectors elementwise. + /// Multiplies two simd vectors elementwise. /// /// `T` must be a vector of integer or floating point primitive types. #[rustc_nounwind] pub fn simd_mul(x: T, y: T) -> T; - /// Divide `lhs` by `rhs` elementwise. + /// Divides `lhs` by `rhs` elementwise. /// /// `T` must be a vector of integer or floating point primitive types. /// @@ -51,7 +51,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_div(lhs: T, rhs: T) -> T; - /// Remainder of two vectors elementwise + /// Returns remainder of two vectors elementwise. /// /// `T` must be a vector of integer or floating point primitive types. /// @@ -61,9 +61,9 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_rem(lhs: T, rhs: T) -> T; - /// Elementwise vector left shift, with UB on overflow. + /// Shifts vector left elementwise, with UB on overflow. /// - /// Shift `lhs` left by `rhs`, shifting in sign bits for signed types. + /// Shifts `lhs` left by `rhs`, shifting in sign bits for signed types. /// /// `T` must be a vector of integer primitive types. /// @@ -73,11 +73,11 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_shl(lhs: T, rhs: T) -> T; - /// Elementwise vector right shift, with UB on overflow. + /// Shifts vector right elementwise, with UB on overflow. /// /// `T` must be a vector of integer primitive types. /// - /// Shift `lhs` right by `rhs`, shifting in sign bits for signed types. + /// Shifts `lhs` right by `rhs`, shifting in sign bits for signed types. /// /// # Safety /// @@ -85,25 +85,25 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_shr(lhs: T, rhs: T) -> T; - /// Elementwise vector "and". + /// "Ands" vectors elementwise. /// /// `T` must be a vector of integer primitive types. #[rustc_nounwind] pub fn simd_and(x: T, y: T) -> T; - /// Elementwise vector "or". + /// "Ors" vectors elementwise. /// /// `T` must be a vector of integer primitive types. #[rustc_nounwind] pub fn simd_or(x: T, y: T) -> T; - /// Elementwise vector "exclusive or". + /// "Exclusive ors" vectors elementwise. /// /// `T` must be a vector of integer primitive types. #[rustc_nounwind] pub fn simd_xor(x: T, y: T) -> T; - /// Numerically cast a vector, elementwise. + /// Numerically casts a vector, elementwise. /// /// `T` and `U` must be vectors of integer or floating point primitive types, and must have the /// same length. @@ -124,7 +124,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_cast(x: T) -> U; - /// Numerically cast a vector, elementwise. + /// Numerically casts a vector, elementwise. /// /// `T` and `U` be a vectors of integer or floating point primitive types, and must have the /// same length. @@ -138,7 +138,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_as(x: T) -> U; - /// Elementwise negation of a vector. + /// Negates a vector elementwise. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -146,13 +146,13 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_neg(x: T) -> T; - /// Elementwise absolute value of a vector. + /// Returns absolute value of a vector, elementwise. /// /// `T` must be a vector of floating-point primitive types. #[rustc_nounwind] pub fn simd_fabs(x: T) -> T; - /// Elementwise minimum of two vectors. + /// Returns the minimum of two vectors, elementwise. /// /// `T` must be a vector of floating-point primitive types. /// @@ -160,7 +160,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_fmin(x: T, y: T) -> T; - /// Elementwise maximum of two vectors. + /// Returns the maximum of two vectors, elementwise. /// /// `T` must be a vector of floating-point primitive types. /// @@ -228,7 +228,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_ge(x: T, y: T) -> U; - /// Shuffle two vectors by const indices. + /// Shuffles two vectors by const indices. /// /// `T` must be a vector. /// @@ -243,19 +243,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_shuffle(x: T, y: T, idx: U) -> V; - /// Shuffle two vectors by const indices. - /// - /// `T` must be a vector. - /// - /// `U` must be a vector with the same element type as `T` and the same length as `IDX`. - /// - /// Returns a new vector such that element `i` is selected from `xy[IDX[i]]`, where `xy` - /// is the concatenation of `x` and `y`. It is a compile-time error if `IDX[i]` is out-of-bounds - /// of `xy`. - #[rustc_nounwind] - pub fn simd_shuffle_generic(x: T, y: T) -> U; - - /// Read a vector of pointers. + /// Reads a vector of pointers. /// /// `T` must be a vector. /// @@ -275,7 +263,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_gather(val: T, ptr: U, mask: V) -> T; - /// Write to a vector of pointers. + /// Writes to a vector of pointers. /// /// `T` must be a vector. /// @@ -298,7 +286,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_scatter(val: T, ptr: U, mask: V); - /// Read a vector of pointers. + /// Reads a vector of pointers. /// /// `T` must be a vector. /// @@ -320,7 +308,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_masked_load(mask: V, ptr: U, val: T) -> T; - /// Write to a vector of pointers. + /// Writes to a vector of pointers. /// /// `T` must be a vector. /// @@ -341,13 +329,13 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_masked_store(mask: V, ptr: U, val: T); - /// Add two simd vectors elementwise, with saturation. + /// Adds two simd vectors elementwise, with saturation. /// /// `T` must be a vector of integer primitive types. #[rustc_nounwind] pub fn simd_saturating_add(x: T, y: T) -> T; - /// Subtract two simd vectors elementwise, with saturation. + /// Subtracts two simd vectors elementwise, with saturation. /// /// `T` must be a vector of integer primitive types. /// @@ -355,7 +343,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_saturating_sub(lhs: T, rhs: T) -> T; - /// Add elements within a vector from left to right. + /// Adds elements within a vector from left to right. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -365,7 +353,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_add_ordered(x: T, y: U) -> U; - /// Add elements within a vector in arbitrary order. May also be re-associated with + /// Adds elements within a vector in arbitrary order. May also be re-associated with /// unordered additions on the inputs/outputs. /// /// `T` must be a vector of integer or floating-point primitive types. @@ -374,7 +362,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_add_unordered(x: T) -> U; - /// Multiply elements within a vector from left to right. + /// Multiplies elements within a vector from left to right. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -384,7 +372,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_mul_ordered(x: T, y: U) -> U; - /// Multiply elements within a vector in arbitrary order. May also be re-associated with + /// Multiplies elements within a vector in arbitrary order. May also be re-associated with /// unordered additions on the inputs/outputs. /// /// `T` must be a vector of integer or floating-point primitive types. @@ -393,7 +381,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_mul_unordered(x: T) -> U; - /// Check if all mask values are true. + /// Checks if all mask values are true. /// /// `T` must be a vector of integer primitive types. /// @@ -402,7 +390,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_all(x: T) -> bool; - /// Check if any mask value is true. + /// Checks if any mask value is true. /// /// `T` must be a vector of integer primitive types. /// @@ -411,7 +399,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_any(x: T) -> bool; - /// Return the maximum element of a vector. + /// Returns the maximum element of a vector. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -421,7 +409,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_max(x: T) -> U; - /// Return the minimum element of a vector. + /// Returns the minimum element of a vector. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -431,7 +419,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_min(x: T) -> U; - /// Logical "and" all elements together. + /// Logical "ands" all elements together. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -439,7 +427,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_and(x: T) -> U; - /// Logical "or" all elements together. + /// Logical "ors" all elements together. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -447,7 +435,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_or(x: T) -> U; - /// Logical "exclusive or" all elements together. + /// Logical "exclusive ors" all elements together. /// /// `T` must be a vector of integer or floating-point primitive types. /// @@ -455,7 +443,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_reduce_xor(x: T) -> U; - /// Truncate an integer vector to a bitmask. + /// Truncates an integer vector to a bitmask. /// /// `T` must be an integer vector. /// @@ -491,7 +479,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_bitmask(x: T) -> U; - /// Select elements from a mask. + /// Selects elements from a mask. /// /// `M` must be an integer vector. /// @@ -506,7 +494,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_select(mask: M, if_true: T, if_false: T) -> T; - /// Select elements from a bitmask. + /// Selects elements from a bitmask. /// /// `M` must be an unsigned integer or array of `u8`, matching `simd_bitmask`. /// @@ -523,7 +511,8 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_select_bitmask(m: M, yes: T, no: T) -> T; - /// Elementwise calculates the offset from a pointer vector, potentially wrapping. + /// Calculates the offset from a pointer vector elementwise, potentially + /// wrapping. /// /// `T` must be a vector of pointers. /// @@ -533,13 +522,13 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_arith_offset(ptr: T, offset: U) -> T; - /// Cast a vector of pointers. + /// Casts a vector of pointers. /// /// `T` and `U` must be vectors of pointers with the same number of elements. #[rustc_nounwind] pub fn simd_cast_ptr(ptr: T) -> U; - /// Expose a vector of pointers as a vector of addresses. + /// Exposes a vector of pointers as a vector of addresses. /// /// `T` must be a vector of pointers. /// @@ -547,7 +536,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_expose_provenance(ptr: T) -> U; - /// Create a vector of pointers from a vector of addresses. + /// Creates a vector of pointers from a vector of addresses. /// /// `T` must be a vector of `usize`. /// @@ -555,56 +544,56 @@ extern "rust-intrinsic" { #[rustc_nounwind] pub fn simd_with_exposed_provenance(addr: T) -> U; - /// Swap bytes of each element. + /// Swaps bytes of each element. /// /// `T` must be a vector of integers. #[rustc_nounwind] pub fn simd_bswap(x: T) -> T; - /// Reverse bits of each element. + /// Reverses bits of each element. /// /// `T` must be a vector of integers. #[rustc_nounwind] pub fn simd_bitreverse(x: T) -> T; - /// Count the leading zeros of each element. + /// Counts the leading zeros of each element. /// /// `T` must be a vector of integers. #[rustc_nounwind] pub fn simd_ctlz(x: T) -> T; - /// Count the number of ones in each element. + /// Counts the number of ones in each element. /// /// `T` must be a vector of integers. #[rustc_nounwind] pub fn simd_ctpop(x: T) -> T; - /// Count the trailing zeros of each element. + /// Counts the trailing zeros of each element. /// /// `T` must be a vector of integers. #[rustc_nounwind] pub fn simd_cttz(x: T) -> T; - /// Round up each element to the next highest integer-valued float. + /// Rounds up each element to the next highest integer-valued float. /// /// `T` must be a vector of floats. #[rustc_nounwind] pub fn simd_ceil(x: T) -> T; - /// Round down each element to the next lowest integer-valued float. + /// Rounds down each element to the next lowest integer-valued float. /// /// `T` must be a vector of floats. #[rustc_nounwind] pub fn simd_floor(x: T) -> T; - /// Round each element to the closest integer-valued float. + /// Rounds each element to the closest integer-valued float. /// Ties are resolved by rounding away from 0. /// /// `T` must be a vector of floats. #[rustc_nounwind] pub fn simd_round(x: T) -> T; - /// Return the integer part of each element as an integer-valued float. + /// Returns the integer part of each element as an integer-valued float. /// In other words, non-integer values are truncated towards zero. /// /// `T` must be a vector of floats. diff --git a/library/core/src/io/borrowed_buf.rs b/library/core/src/io/borrowed_buf.rs index d497da33dd923..dbc60aa8154c6 100644 --- a/library/core/src/io/borrowed_buf.rs +++ b/library/core/src/io/borrowed_buf.rs @@ -44,7 +44,7 @@ impl Debug for BorrowedBuf<'_> { } } -/// Create a new `BorrowedBuf` from a fully initialized slice. +/// Creates a new `BorrowedBuf` from a fully initialized slice. impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data> { #[inline] fn from(slice: &'data mut [u8]) -> BorrowedBuf<'data> { @@ -59,7 +59,7 @@ impl<'data> From<&'data mut [u8]> for BorrowedBuf<'data> { } } -/// Create a new `BorrowedBuf` from an uninitialized buffer. +/// Creates a new `BorrowedBuf` from an uninitialized buffer. /// /// Use `set_init` if part of the buffer is known to be already initialized. impl<'data> From<&'data mut [MaybeUninit]> for BorrowedBuf<'data> { @@ -174,7 +174,7 @@ pub struct BorrowedCursor<'a> { } impl<'a> BorrowedCursor<'a> { - /// Reborrow this cursor by cloning it with a smaller lifetime. + /// Reborrows this cursor by cloning it with a smaller lifetime. /// /// Since a cursor maintains unique access to its underlying buffer, the borrowed cursor is /// not accessible while the new cursor exists. @@ -247,7 +247,7 @@ impl<'a> BorrowedCursor<'a> { unsafe { self.buf.buf.get_unchecked_mut(self.buf.filled..) } } - /// Advance the cursor by asserting that `n` bytes have been filled. + /// Advances the cursor by asserting that `n` bytes have been filled. /// /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements @@ -268,7 +268,7 @@ impl<'a> BorrowedCursor<'a> { self } - /// Advance the cursor by asserting that `n` bytes have been filled. + /// Advances the cursor by asserting that `n` bytes have been filled. /// /// After advancing, the `n` bytes are no longer accessible via the cursor and can only be /// accessed via the underlying buffer. I.e., the buffer's filled portion grows by `n` elements diff --git a/library/core/src/iter/adapters/cloned.rs b/library/core/src/iter/adapters/cloned.rs index 1a106ef97942b..aea6d64281aec 100644 --- a/library/core/src/iter/adapters/cloned.rs +++ b/library/core/src/iter/adapters/cloned.rs @@ -1,9 +1,9 @@ -use crate::iter::adapters::{ - zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce, -}; +use core::num::NonZero; + +use crate::iter::adapters::zip::try_get_unchecked; +use crate::iter::adapters::{SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen, UncheckedIterator}; use crate::ops::Try; -use core::num::NonZero; /// An iterator that clones the elements of an underlying iterator. /// diff --git a/library/core/src/iter/adapters/copied.rs b/library/core/src/iter/adapters/copied.rs index d772e7b36e09e..23e4e25ab5388 100644 --- a/library/core/src/iter/adapters/copied.rs +++ b/library/core/src/iter/adapters/copied.rs @@ -1,9 +1,7 @@ -use crate::iter::adapters::{ - zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce, -}; +use crate::iter::adapters::zip::try_get_unchecked; +use crate::iter::adapters::{SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedLen}; -use crate::mem::MaybeUninit; -use crate::mem::SizedTypeProperties; +use crate::mem::{MaybeUninit, SizedTypeProperties}; use crate::num::NonZero; use crate::ops::Try; use crate::{array, ptr}; diff --git a/library/core/src/iter/adapters/cycle.rs b/library/core/src/iter/adapters/cycle.rs index b35ed8442032d..6cb1a3a46763e 100644 --- a/library/core/src/iter/adapters/cycle.rs +++ b/library/core/src/iter/adapters/cycle.rs @@ -1,5 +1,6 @@ +use crate::iter::FusedIterator; use crate::num::NonZero; -use crate::{iter::FusedIterator, ops::Try}; +use crate::ops::Try; /// An iterator that repeats endlessly. /// diff --git a/library/core/src/iter/adapters/enumerate.rs b/library/core/src/iter/adapters/enumerate.rs index 7adbabf69e490..ac15e3767fc09 100644 --- a/library/core/src/iter/adapters/enumerate.rs +++ b/library/core/src/iter/adapters/enumerate.rs @@ -1,6 +1,5 @@ -use crate::iter::adapters::{ - zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce, -}; +use crate::iter::adapters::zip::try_get_unchecked; +use crate::iter::adapters::{SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused, TrustedLen}; use crate::num::NonZero; use crate::ops::Try; diff --git a/library/core/src/iter/adapters/filter.rs b/library/core/src/iter/adapters/filter.rs index ba49070329c22..dd08cd6f61c4c 100644 --- a/library/core/src/iter/adapters/filter.rs +++ b/library/core/src/iter/adapters/filter.rs @@ -1,11 +1,13 @@ -use crate::fmt; -use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; -use crate::num::NonZero; -use crate::ops::Try; use core::array; use core::mem::MaybeUninit; use core::ops::ControlFlow; +use crate::fmt; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused}; +use crate::num::NonZero; +use crate::ops::Try; + /// An iterator that filters the elements of `iter` with `predicate`. /// /// This `struct` is created by the [`filter`] method on [`Iterator`]. See its diff --git a/library/core/src/iter/adapters/filter_map.rs b/library/core/src/iter/adapters/filter_map.rs index 2126619a58a87..914ef6131771f 100644 --- a/library/core/src/iter/adapters/filter_map.rs +++ b/library/core/src/iter/adapters/filter_map.rs @@ -1,4 +1,5 @@ -use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused}; use crate::mem::{ManuallyDrop, MaybeUninit}; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/library/core/src/iter/adapters/flatten.rs b/library/core/src/iter/adapters/flatten.rs index 145c9d3dacc84..0023b46031f12 100644 --- a/library/core/src/iter/adapters/flatten.rs +++ b/library/core/src/iter/adapters/flatten.rs @@ -1,13 +1,11 @@ use crate::iter::adapters::SourceIter; use crate::iter::{ - Cloned, Copied, Filter, FilterMap, Fuse, FusedIterator, InPlaceIterable, Map, TrustedFused, - TrustedLen, + Cloned, Copied, Empty, Filter, FilterMap, Fuse, FusedIterator, InPlaceIterable, Map, Once, + OnceWith, TrustedFused, TrustedLen, }; -use crate::iter::{Empty, Once, OnceWith}; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; -use crate::result; -use crate::{array, fmt, option}; +use crate::{array, fmt, option, result}; /// An iterator that maps each element to an iterator, and yields the elements /// of the produced iterators. diff --git a/library/core/src/iter/adapters/inspect.rs b/library/core/src/iter/adapters/inspect.rs index 1c4656a649a37..0e2a68a503e44 100644 --- a/library/core/src/iter/adapters/inspect.rs +++ b/library/core/src/iter/adapters/inspect.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused}; use crate::num::NonZero; use crate::ops::Try; diff --git a/library/core/src/iter/adapters/map.rs b/library/core/src/iter/adapters/map.rs index 6e163e20d8ec4..007c2d5acc2d0 100644 --- a/library/core/src/iter/adapters/map.rs +++ b/library/core/src/iter/adapters/map.rs @@ -1,7 +1,6 @@ use crate::fmt; -use crate::iter::adapters::{ - zip::try_get_unchecked, SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce, -}; +use crate::iter::adapters::zip::try_get_unchecked; +use crate::iter::adapters::{SourceIter, TrustedRandomAccess, TrustedRandomAccessNoCoerce}; use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, UncheckedIterator}; use crate::num::NonZero; use crate::ops::Try; diff --git a/library/core/src/iter/adapters/map_while.rs b/library/core/src/iter/adapters/map_while.rs index 9ad50048c25ea..4e7327938d72a 100644 --- a/library/core/src/iter/adapters/map_while.rs +++ b/library/core/src/iter/adapters/map_while.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::iter::{adapters::SourceIter, InPlaceIterable}; +use crate::iter::adapters::SourceIter; +use crate::iter::InPlaceIterable; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/library/core/src/iter/adapters/map_windows.rs b/library/core/src/iter/adapters/map_windows.rs index 182775121369e..cb13023c85c41 100644 --- a/library/core/src/iter/adapters/map_windows.rs +++ b/library/core/src/iter/adapters/map_windows.rs @@ -1,9 +1,6 @@ -use crate::{ - fmt, - iter::FusedIterator, - mem::{self, MaybeUninit}, - ptr, -}; +use crate::iter::FusedIterator; +use crate::mem::{self, MaybeUninit}; +use crate::{fmt, ptr}; /// An iterator over the mapped windows of another iterator. /// diff --git a/library/core/src/iter/adapters/mod.rs b/library/core/src/iter/adapters/mod.rs index 1bde4488cc9de..96158c43318ea 100644 --- a/library/core/src/iter/adapters/mod.rs +++ b/library/core/src/iter/adapters/mod.rs @@ -28,51 +28,38 @@ mod take; mod take_while; mod zip; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::{ - chain::Chain, cycle::Cycle, enumerate::Enumerate, filter::Filter, filter_map::FilterMap, - flatten::FlatMap, fuse::Fuse, inspect::Inspect, map::Map, peekable::Peekable, rev::Rev, - scan::Scan, skip::Skip, skip_while::SkipWhile, take::Take, take_while::TakeWhile, zip::Zip, -}; - #[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] pub use self::array_chunks::ArrayChunks; - #[unstable(feature = "std_internals", issue = "none")] pub use self::by_ref_sized::ByRefSized; - #[unstable(feature = "iter_chain", reason = "recently added", issue = "125964")] pub use self::chain::chain; - #[stable(feature = "iter_cloned", since = "1.1.0")] pub use self::cloned::Cloned; - -#[stable(feature = "iterator_step_by", since = "1.28.0")] -pub use self::step_by::StepBy; - -#[stable(feature = "iterator_flatten", since = "1.29.0")] -pub use self::flatten::Flatten; - #[stable(feature = "iter_copied", since = "1.36.0")] pub use self::copied::Copied; - +#[stable(feature = "iterator_flatten", since = "1.29.0")] +pub use self::flatten::Flatten; #[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] pub use self::intersperse::{Intersperse, IntersperseWith}; - #[stable(feature = "iter_map_while", since = "1.57.0")] pub use self::map_while::MapWhile; - #[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] pub use self::map_windows::MapWindows; - +#[stable(feature = "iterator_step_by", since = "1.28.0")] +pub use self::step_by::StepBy; +#[stable(feature = "iter_zip", since = "1.59.0")] +pub use self::zip::zip; #[unstable(feature = "trusted_random_access", issue = "none")] pub use self::zip::TrustedRandomAccess; - #[unstable(feature = "trusted_random_access", issue = "none")] pub use self::zip::TrustedRandomAccessNoCoerce; - -#[stable(feature = "iter_zip", since = "1.59.0")] -pub use self::zip::zip; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::{ + chain::Chain, cycle::Cycle, enumerate::Enumerate, filter::Filter, filter_map::FilterMap, + flatten::FlatMap, fuse::Fuse, inspect::Inspect, map::Map, peekable::Peekable, rev::Rev, + scan::Scan, skip::Skip, skip_while::SkipWhile, take::Take, take_while::TakeWhile, zip::Zip, +}; /// This trait provides transitive access to source-stage in an iterator-adapter pipeline /// under the conditions that diff --git a/library/core/src/iter/adapters/peekable.rs b/library/core/src/iter/adapters/peekable.rs index 65ba42920c93d..a11b73cbe8e2d 100644 --- a/library/core/src/iter/adapters/peekable.rs +++ b/library/core/src/iter/adapters/peekable.rs @@ -1,4 +1,5 @@ -use crate::iter::{adapters::SourceIter, FusedIterator, TrustedLen}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, TrustedLen}; use crate::ops::{ControlFlow, Try}; /// An iterator with a `peek()` that returns an optional reference to the next diff --git a/library/core/src/iter/adapters/scan.rs b/library/core/src/iter/adapters/scan.rs index d261a535b183a..7ba7ed2fdd0d5 100644 --- a/library/core/src/iter/adapters/scan.rs +++ b/library/core/src/iter/adapters/scan.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::iter::{adapters::SourceIter, InPlaceIterable}; +use crate::iter::adapters::SourceIter; +use crate::iter::InPlaceIterable; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/library/core/src/iter/adapters/skip.rs b/library/core/src/iter/adapters/skip.rs index f51a2c39b8e28..8ba2e2a8f2dd7 100644 --- a/library/core/src/iter/adapters/skip.rs +++ b/library/core/src/iter/adapters/skip.rs @@ -1,8 +1,8 @@ use crate::intrinsics::unlikely; use crate::iter::adapters::zip::try_get_unchecked; -use crate::iter::TrustedFused; +use crate::iter::adapters::SourceIter; use crate::iter::{ - adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedLen, TrustedRandomAccess, + FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, }; use crate::num::NonZero; diff --git a/library/core/src/iter/adapters/skip_while.rs b/library/core/src/iter/adapters/skip_while.rs index 8001e6e64713a..8ae453e76fa0d 100644 --- a/library/core/src/iter/adapters/skip_while.rs +++ b/library/core/src/iter/adapters/skip_while.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused}; use crate::num::NonZero; use crate::ops::Try; diff --git a/library/core/src/iter/adapters/step_by.rs b/library/core/src/iter/adapters/step_by.rs index abdf2f415fe55..72eb72a76c66c 100644 --- a/library/core/src/iter/adapters/step_by.rs +++ b/library/core/src/iter/adapters/step_by.rs @@ -1,9 +1,7 @@ -use crate::{ - intrinsics, - iter::{from_fn, TrustedLen, TrustedRandomAccess}, - num::NonZero, - ops::{Range, Try}, -}; +use crate::intrinsics; +use crate::iter::{from_fn, TrustedLen, TrustedRandomAccess}; +use crate::num::NonZero; +use crate::ops::{Range, Try}; /// An iterator for stepping iterators by a custom amount. /// @@ -414,9 +412,9 @@ unsafe impl StepByBackImpl for St /// These only work for unsigned types, and will need to be reworked /// if you want to use it to specialize on signed types. /// -/// Currently these are only implemented for integers up to usize due to -/// correctness issues around ExactSizeIterator impls on 16bit platforms. -/// And since ExactSizeIterator is a prerequisite for backwards iteration +/// Currently these are only implemented for integers up to `usize` due to +/// correctness issues around `ExactSizeIterator` impls on 16bit platforms. +/// And since `ExactSizeIterator` is a prerequisite for backwards iteration /// and we must consistently specialize backwards and forwards iteration /// that makes the situation complicated enough that it's not covered /// for now. diff --git a/library/core/src/iter/adapters/take.rs b/library/core/src/iter/adapters/take.rs index 6870c677b1e07..297dd0acaddc1 100644 --- a/library/core/src/iter/adapters/take.rs +++ b/library/core/src/iter/adapters/take.rs @@ -1,8 +1,6 @@ use crate::cmp; -use crate::iter::{ - adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, - TrustedRandomAccess, -}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, TrustedRandomAccess}; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/library/core/src/iter/adapters/take_while.rs b/library/core/src/iter/adapters/take_while.rs index d3f09ab356ad8..06028ea98e7fd 100644 --- a/library/core/src/iter/adapters/take_while.rs +++ b/library/core/src/iter/adapters/take_while.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; +use crate::iter::adapters::SourceIter; +use crate::iter::{FusedIterator, InPlaceIterable, TrustedFused}; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/library/core/src/iter/adapters/zip.rs b/library/core/src/iter/adapters/zip.rs index 2e885f06b5272..0c38811590877 100644 --- a/library/core/src/iter/adapters/zip.rs +++ b/library/core/src/iter/adapters/zip.rs @@ -1,7 +1,8 @@ use crate::cmp; use crate::fmt::{self, Debug}; -use crate::iter::{FusedIterator, TrustedFused}; -use crate::iter::{InPlaceIterable, SourceIter, TrustedLen, UncheckedIterator}; +use crate::iter::{ + FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen, UncheckedIterator, +}; use crate::num::NonZero; /// An iterator that iterates two other iterators simultaneously. diff --git a/library/core/src/iter/mod.rs b/library/core/src/iter/mod.rs index 921c75c85f161..1f2bf49d2b729 100644 --- a/library/core/src/iter/mod.rs +++ b/library/core/src/iter/mod.rs @@ -380,16 +380,46 @@ macro_rules! impl_fold_via_try_fold { }; } +#[unstable(feature = "iter_chain", reason = "recently added", issue = "125964")] +pub use self::adapters::chain; +pub(crate) use self::adapters::try_process; +#[stable(feature = "iter_zip", since = "1.59.0")] +pub use self::adapters::zip; +#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] +pub use self::adapters::ArrayChunks; +#[unstable(feature = "std_internals", issue = "none")] +pub use self::adapters::ByRefSized; +#[stable(feature = "iter_cloned", since = "1.1.0")] +pub use self::adapters::Cloned; +#[stable(feature = "iter_copied", since = "1.36.0")] +pub use self::adapters::Copied; +#[stable(feature = "iterator_flatten", since = "1.29.0")] +pub use self::adapters::Flatten; +#[stable(feature = "iter_map_while", since = "1.57.0")] +pub use self::adapters::MapWhile; +#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] +pub use self::adapters::MapWindows; +#[unstable(feature = "inplace_iteration", issue = "none")] +pub use self::adapters::SourceIter; +#[stable(feature = "iterator_step_by", since = "1.28.0")] +pub use self::adapters::StepBy; +#[unstable(feature = "trusted_random_access", issue = "none")] +pub use self::adapters::TrustedRandomAccess; +#[unstable(feature = "trusted_random_access", issue = "none")] +pub use self::adapters::TrustedRandomAccessNoCoerce; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::traits::Iterator; - +pub use self::adapters::{ + Chain, Cycle, Enumerate, Filter, FilterMap, FlatMap, Fuse, Inspect, Map, Peekable, Rev, Scan, + Skip, SkipWhile, Take, TakeWhile, Zip, +}; +#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] +pub use self::adapters::{Intersperse, IntersperseWith}; #[unstable( feature = "step_trait", reason = "likely to be replaced by finer-grained traits", issue = "42168" )] pub use self::range::Step; - #[unstable( feature = "iter_from_coroutine", issue = "43122", @@ -412,59 +442,24 @@ pub use self::sources::{repeat_n, RepeatN}; pub use self::sources::{repeat_with, RepeatWith}; #[stable(feature = "iter_successors", since = "1.34.0")] pub use self::sources::{successors, Successors}; - #[stable(feature = "fused", since = "1.26.0")] pub use self::traits::FusedIterator; #[unstable(issue = "none", feature = "inplace_iteration")] pub use self::traits::InPlaceIterable; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::traits::Iterator; #[unstable(issue = "none", feature = "trusted_fused")] pub use self::traits::TrustedFused; #[unstable(feature = "trusted_len", issue = "37572")] pub use self::traits::TrustedLen; #[unstable(feature = "trusted_step", issue = "85731")] pub use self::traits::TrustedStep; +pub(crate) use self::traits::UncheckedIterator; #[stable(feature = "rust1", since = "1.0.0")] pub use self::traits::{ DoubleEndedIterator, ExactSizeIterator, Extend, FromIterator, IntoIterator, Product, Sum, }; -#[unstable(feature = "iter_chain", reason = "recently added", issue = "125964")] -pub use self::adapters::chain; -#[stable(feature = "iter_zip", since = "1.59.0")] -pub use self::adapters::zip; -#[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] -pub use self::adapters::ArrayChunks; -#[unstable(feature = "std_internals", issue = "none")] -pub use self::adapters::ByRefSized; -#[stable(feature = "iter_cloned", since = "1.1.0")] -pub use self::adapters::Cloned; -#[stable(feature = "iter_copied", since = "1.36.0")] -pub use self::adapters::Copied; -#[stable(feature = "iterator_flatten", since = "1.29.0")] -pub use self::adapters::Flatten; -#[stable(feature = "iter_map_while", since = "1.57.0")] -pub use self::adapters::MapWhile; -#[unstable(feature = "iter_map_windows", reason = "recently added", issue = "87155")] -pub use self::adapters::MapWindows; -#[unstable(feature = "inplace_iteration", issue = "none")] -pub use self::adapters::SourceIter; -#[stable(feature = "iterator_step_by", since = "1.28.0")] -pub use self::adapters::StepBy; -#[unstable(feature = "trusted_random_access", issue = "none")] -pub use self::adapters::TrustedRandomAccess; -#[unstable(feature = "trusted_random_access", issue = "none")] -pub use self::adapters::TrustedRandomAccessNoCoerce; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::adapters::{ - Chain, Cycle, Enumerate, Filter, FilterMap, FlatMap, Fuse, Inspect, Map, Peekable, Rev, Scan, - Skip, SkipWhile, Take, TakeWhile, Zip, -}; -#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")] -pub use self::adapters::{Intersperse, IntersperseWith}; - -pub(crate) use self::adapters::try_process; -pub(crate) use self::traits::UncheckedIterator; - mod adapters; mod range; mod sources; diff --git a/library/core/src/iter/range.rs b/library/core/src/iter/range.rs index 644a169294396..da4f68a0de4fb 100644 --- a/library/core/src/iter/range.rs +++ b/library/core/src/iter/range.rs @@ -1,13 +1,12 @@ +use super::{ + FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, TrustedStep, +}; use crate::ascii::Char as AsciiChar; use crate::mem; use crate::net::{Ipv4Addr, Ipv6Addr}; use crate::num::NonZero; use crate::ops::{self, Try}; -use super::{ - FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, TrustedStep, -}; - // Safety: All invariants are upheld. macro_rules! unsafe_impl_trusted_step { ($($type:ty)*) => {$( diff --git a/library/core/src/iter/sources.rs b/library/core/src/iter/sources.rs index 56c1f86079a3a..6a94051b7c7b8 100644 --- a/library/core/src/iter/sources.rs +++ b/library/core/src/iter/sources.rs @@ -8,33 +8,25 @@ mod repeat_n; mod repeat_with; mod successors; -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::repeat::{repeat, Repeat}; - #[stable(feature = "iter_empty", since = "1.2.0")] pub use self::empty::{empty, Empty}; - -#[stable(feature = "iter_once", since = "1.2.0")] -pub use self::once::{once, Once}; - -#[unstable(feature = "iter_repeat_n", issue = "104434")] -pub use self::repeat_n::{repeat_n, RepeatN}; - -#[stable(feature = "iterator_repeat_with", since = "1.28.0")] -pub use self::repeat_with::{repeat_with, RepeatWith}; - -#[stable(feature = "iter_from_fn", since = "1.34.0")] -pub use self::from_fn::{from_fn, FromFn}; - #[unstable( feature = "iter_from_coroutine", issue = "43122", reason = "coroutines are unstable" )] pub use self::from_coroutine::from_coroutine; - -#[stable(feature = "iter_successors", since = "1.34.0")] -pub use self::successors::{successors, Successors}; - +#[stable(feature = "iter_from_fn", since = "1.34.0")] +pub use self::from_fn::{from_fn, FromFn}; +#[stable(feature = "iter_once", since = "1.2.0")] +pub use self::once::{once, Once}; #[stable(feature = "iter_once_with", since = "1.43.0")] pub use self::once_with::{once_with, OnceWith}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::repeat::{repeat, Repeat}; +#[unstable(feature = "iter_repeat_n", issue = "104434")] +pub use self::repeat_n::{repeat_n, RepeatN}; +#[stable(feature = "iterator_repeat_with", since = "1.28.0")] +pub use self::repeat_with::{repeat_with, RepeatWith}; +#[stable(feature = "iter_successors", since = "1.34.0")] +pub use self::successors::{successors, Successors}; diff --git a/library/core/src/iter/sources/empty.rs b/library/core/src/iter/sources/empty.rs index 438e046a4dfdc..3c3acceded889 100644 --- a/library/core/src/iter/sources/empty.rs +++ b/library/core/src/iter/sources/empty.rs @@ -1,6 +1,5 @@ -use crate::fmt; use crate::iter::{FusedIterator, TrustedLen}; -use crate::marker; +use crate::{fmt, marker}; /// Creates an iterator that yields nothing. /// diff --git a/library/core/src/iter/sources/repeat_n.rs b/library/core/src/iter/sources/repeat_n.rs index 8390dab8e543e..4c4ae39f836ca 100644 --- a/library/core/src/iter/sources/repeat_n.rs +++ b/library/core/src/iter/sources/repeat_n.rs @@ -114,19 +114,12 @@ impl Iterator for RepeatN { #[inline] fn next(&mut self) -> Option { - if self.count == 0 { - return None; - } - - self.count -= 1; - Some(if self.count == 0 { - // SAFETY: the check above ensured that the count used to be non-zero, - // so element hasn't been dropped yet, and we just lowered the count to - // zero so it won't be dropped later, and thus it's okay to take it here. - unsafe { ManuallyDrop::take(&mut self.element) } + if self.count > 0 { + // SAFETY: Just checked it's not empty + unsafe { Some(self.next_unchecked()) } } else { - A::clone(&self.element) - }) + None + } } #[inline] @@ -194,4 +187,18 @@ impl FusedIterator for RepeatN {} #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl TrustedLen for RepeatN {} #[unstable(feature = "trusted_len_next_unchecked", issue = "37572")] -impl UncheckedIterator for RepeatN {} +impl UncheckedIterator for RepeatN { + #[inline] + unsafe fn next_unchecked(&mut self) -> Self::Item { + // SAFETY: The caller promised the iterator isn't empty + self.count = unsafe { self.count.unchecked_sub(1) }; + if self.count == 0 { + // SAFETY: the check above ensured that the count used to be non-zero, + // so element hasn't been dropped yet, and we just lowered the count to + // zero so it won't be dropped later, and thus it's okay to take it here. + unsafe { ManuallyDrop::take(&mut self.element) } + } else { + A::clone(&self.element) + } + } +} diff --git a/library/core/src/iter/sources/successors.rs b/library/core/src/iter/sources/successors.rs index 7f7b2c7756628..36bc4035039e6 100644 --- a/library/core/src/iter/sources/successors.rs +++ b/library/core/src/iter/sources/successors.rs @@ -1,4 +1,5 @@ -use crate::{fmt, iter::FusedIterator}; +use crate::fmt; +use crate::iter::FusedIterator; /// Creates a new iterator where each successive item is computed based on the preceding one. /// diff --git a/library/core/src/iter/traits/accum.rs b/library/core/src/iter/traits/accum.rs index f9c7eb8f9383e..c97cd042ab459 100644 --- a/library/core/src/iter/traits/accum.rs +++ b/library/core/src/iter/traits/accum.rs @@ -15,8 +15,8 @@ use crate::num::Wrapping; label = "value of type `{Self}` cannot be made by summing a `std::iter::Iterator`" )] pub trait Sum: Sized { - /// Method which takes an iterator and generates `Self` from the elements by - /// "summing up" the items. + /// Takes an iterator and generates `Self` from the elements by "summing up" + /// the items. #[stable(feature = "iter_arith_traits", since = "1.12.0")] fn sum>(iter: I) -> Self; } @@ -36,8 +36,8 @@ pub trait Sum: Sized { label = "value of type `{Self}` cannot be made by multiplying all elements from a `std::iter::Iterator`" )] pub trait Product: Sized { - /// Method which takes an iterator and generates `Self` from the elements by - /// multiplying the items. + /// Takes an iterator and generates `Self` from the elements by multiplying + /// the items. #[stable(feature = "iter_arith_traits", since = "1.12.0")] fn product>(iter: I) -> Self; } diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 733d414d44465..50a2d952e5b36 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -1,19 +1,14 @@ +use super::super::{ + try_process, ArrayChunks, ByRefSized, Chain, Cloned, Copied, Cycle, Enumerate, Filter, + FilterMap, FlatMap, Flatten, Fuse, Inspect, Intersperse, IntersperseWith, Map, MapWhile, + MapWindows, Peekable, Product, Rev, Scan, Skip, SkipWhile, StepBy, Sum, Take, TakeWhile, + TrustedRandomAccessNoCoerce, Zip, +}; use crate::array; use crate::cmp::{self, Ordering}; use crate::num::NonZero; use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try}; -use super::super::try_process; -use super::super::ByRefSized; -use super::super::TrustedRandomAccessNoCoerce; -use super::super::{ArrayChunks, Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse}; -use super::super::{FlatMap, Flatten}; -use super::super::{ - Inspect, Map, MapWhile, MapWindows, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, - TakeWhile, -}; -use super::super::{Intersperse, IntersperseWith, Product, Sum, Zip}; - fn _assert_is_object_safe(_: &dyn Iterator) {} /// A trait for dealing with iterators. @@ -823,7 +818,7 @@ pub trait Iterator { /// /// Given an element the closure must return `true` or `false`. The returned /// iterator will yield only the elements for which the closure returns - /// true. + /// `true`. /// /// # Examples /// @@ -3951,8 +3946,6 @@ pub trait Iterator { /// # Examples /// /// ``` - /// #![feature(is_sorted)] - /// /// assert!([1, 2, 2, 9].iter().is_sorted()); /// assert!(![1, 3, 2, 4].iter().is_sorted()); /// assert!([0].iter().is_sorted()); @@ -3960,7 +3953,7 @@ pub trait Iterator { /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted()); /// ``` #[inline] - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[rustc_do_not_const_check] fn is_sorted(self) -> bool where @@ -3978,8 +3971,6 @@ pub trait Iterator { /// # Examples /// /// ``` - /// #![feature(is_sorted)] - /// /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a <= b)); /// assert!(![1, 2, 2, 9].iter().is_sorted_by(|a, b| a < b)); /// @@ -3989,7 +3980,7 @@ pub trait Iterator { /// assert!(std::iter::empty::().is_sorted_by(|a, b| false)); /// assert!(std::iter::empty::().is_sorted_by(|a, b| true)); /// ``` - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[rustc_do_not_const_check] fn is_sorted_by(mut self, compare: F) -> bool where @@ -4030,13 +4021,11 @@ pub trait Iterator { /// # Examples /// /// ``` - /// #![feature(is_sorted)] - /// /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len())); /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs())); /// ``` #[inline] - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[rustc_do_not_const_check] fn is_sorted_by_key(self, f: F) -> bool where diff --git a/library/core/src/iter/traits/mod.rs b/library/core/src/iter/traits/mod.rs index d4c9cc4b16037..b330e9ffe21ac 100644 --- a/library/core/src/iter/traits/mod.rs +++ b/library/core/src/iter/traits/mod.rs @@ -6,6 +6,13 @@ mod iterator; mod marker; mod unchecked_iterator; +#[unstable(issue = "none", feature = "inplace_iteration")] +pub use self::marker::InPlaceIterable; +#[unstable(issue = "none", feature = "trusted_fused")] +pub use self::marker::TrustedFused; +#[unstable(feature = "trusted_step", issue = "85731")] +pub use self::marker::TrustedStep; +pub(crate) use self::unchecked_iterator::UncheckedIterator; #[stable(feature = "rust1", since = "1.0.0")] pub use self::{ accum::{Product, Sum}, @@ -15,12 +22,3 @@ pub use self::{ iterator::Iterator, marker::{FusedIterator, TrustedLen}, }; - -#[unstable(issue = "none", feature = "inplace_iteration")] -pub use self::marker::InPlaceIterable; -#[unstable(issue = "none", feature = "trusted_fused")] -pub use self::marker::TrustedFused; -#[unstable(feature = "trusted_step", issue = "85731")] -pub use self::marker::TrustedStep; - -pub(crate) use self::unchecked_iterator::UncheckedIterator; diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 0ec46412e9522..e74900ff7471b 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -103,9 +103,11 @@ #![deny(ffi_unwind_calls)] // Do not check link redundancy on bootstraping phase #![allow(rustdoc::redundant_explicit_links)] +#![warn(rustdoc::unescaped_backticks)] // // Library features: // tidy-alphabetical-start +#![cfg_attr(bootstrap, feature(offset_of_nested))] #![feature(array_ptr_get)] #![feature(asm_experimental_arch)] #![feature(char_indices_offset)] @@ -127,7 +129,6 @@ #![feature(const_hash)] #![feature(const_heap)] #![feature(const_index_range_slice_index)] -#![feature(const_int_from_str)] #![feature(const_intrinsic_copy)] #![feature(const_intrinsic_forget)] #![feature(const_ipv4)] @@ -163,7 +164,6 @@ #![feature(const_ub_checks)] #![feature(const_unicode_case_lookup)] #![feature(const_unsafecell_get_mut)] -#![feature(const_waker)] #![feature(coverage_attribute)] #![feature(do_not_recommend)] #![feature(duration_consts_float)] @@ -173,7 +173,6 @@ #![feature(isqrt)] #![feature(link_cfg)] #![feature(offset_of_enum)] -#![feature(offset_of_nested)] #![feature(panic_internals)] #![feature(ptr_alignment_type)] #![feature(ptr_metadata)] @@ -193,8 +192,6 @@ // // Language features: // tidy-alphabetical-start -#![cfg_attr(bootstrap, feature(c_unwind))] -#![cfg_attr(bootstrap, feature(effects))] #![feature(abi_unadjusted)] #![feature(adt_const_params)] #![feature(allow_internal_unsafe)] @@ -249,7 +246,6 @@ #![feature(transparent_unions)] #![feature(try_blocks)] #![feature(unboxed_closures)] -#![feature(unsized_const_params)] #![feature(unsized_fn_params)] #![feature(with_negative_coherence)] // tidy-alphabetical-end @@ -264,9 +260,11 @@ #![feature(powerpc_target_feature)] #![feature(riscv_target_feature)] #![feature(rtm_target_feature)] +#![feature(sha512_sm_x86)] #![feature(sse4a_target_feature)] #![feature(tbm_target_feature)] #![feature(wasm_target_feature)] +#![feature(x86_amx_intrinsics)] // tidy-alphabetical-end // allow using `core::` in intra-doc links diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index 0d4ca4d5f01e4..ac51a40d9f478 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -14,6 +14,12 @@ macro_rules! panic { /// Asserts that two expressions are equal to each other (using [`PartialEq`]). /// +/// Assertions are always checked in both debug and release builds, and cannot +/// be disabled. See [`debug_assert_eq!`] for assertions that are disabled in +/// release builds by default. +/// +/// [`debug_assert_eq!`]: crate::debug_assert_eq +/// /// On panic, this macro will print the values of the expressions with their /// debug representations. /// @@ -64,6 +70,12 @@ macro_rules! assert_eq { /// Asserts that two expressions are not equal to each other (using [`PartialEq`]). /// +/// Assertions are always checked in both debug and release builds, and cannot +/// be disabled. See [`debug_assert_ne!`] for assertions that are disabled in +/// release builds by default. +/// +/// [`debug_assert_ne!`]: crate::debug_assert_ne +/// /// On panic, this macro will print the values of the expressions with their /// debug representations. /// @@ -122,6 +134,12 @@ macro_rules! assert_ne { /// optional if guard can be used to add additional checks that must be true for the matched value, /// otherwise this macro will panic. /// +/// Assertions are always checked in both debug and release builds, and cannot +/// be disabled. See [`debug_assert_matches!`] for assertions that are disabled in +/// release builds by default. +/// +/// [`debug_assert_matches!`]: crate::assert_matches::debug_assert_matches +/// /// On panic, this macro will print the value of the expression with its debug representation. /// /// Like [`assert!`], this macro has a second form, where a custom panic message can be provided. @@ -633,7 +651,7 @@ macro_rules! write { }; } -/// Write formatted data into a buffer, with a newline appended. +/// Writes formatted data into a buffer, with a newline appended. /// /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone /// (no additional CARRIAGE RETURN (`\r`/`U+000D`). diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index a87528033c03b..6a83ec2eb1e0e 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -9,8 +9,7 @@ use crate::cell::UnsafeCell; use crate::cmp; use crate::fmt::Debug; -use crate::hash::Hash; -use crate::hash::Hasher; +use crate::hash::{Hash, Hasher}; /// Implements a given marker trait for multiple types at the same time. /// @@ -42,6 +41,8 @@ use crate::hash::Hasher; /// } /// ``` #[unstable(feature = "internal_impls_macro", issue = "none")] +// Allow implementations of `UnsizedConstParamTy` even though std cannot use that feature. +#[allow_internal_unstable(unsized_const_params)] macro marker_impls { ( $(#[$($meta:tt)*])* $Trait:ident for $({$($bounds:tt)*})? $T:ty $(, $($rest:tt)*)? ) => { $(#[$($meta)*])* impl< $($($bounds)*)? > $Trait for $T {} @@ -869,7 +870,7 @@ marker_impls! { /// /// *However*, you cannot use [`mem::replace`] on `!Unpin` data which is *pinned* by being wrapped /// inside a [`Pin`] pointing at it. This is because you cannot (safely) use a -/// [`Pin`] to get an `&mut T` to its pointee value, which you would need to call +/// [`Pin`] to get a `&mut T` to its pointee value, which you would need to call /// [`mem::replace`], and *that* is what makes this system work. /// /// So this, for example, can only be done on types implementing `Unpin`: @@ -1059,7 +1060,6 @@ pub trait FnPtr: Copy + Clone { } /// Derive macro generating impls of traits related to smart pointers. -#[cfg(not(bootstrap))] #[rustc_builtin_macro] #[allow_internal_unstable(dispatch_from_dyn, coerce_unsized, unsize)] #[unstable(feature = "derive_smart_pointer", issue = "123430")] @@ -1077,7 +1077,6 @@ pub macro SmartPointer($item:item) { reason = "internal module for implementing effects" )] #[allow(missing_debug_implementations)] // these unit structs don't need `Debug` impls. -#[cfg(not(bootstrap))] pub mod effects { #[lang = "EffectsNoRuntime"] pub struct NoRuntime; diff --git a/library/core/src/mem/manually_drop.rs b/library/core/src/mem/manually_drop.rs index 997f088c6d687..00c837041b697 100644 --- a/library/core/src/mem/manually_drop.rs +++ b/library/core/src/mem/manually_drop.rs @@ -118,10 +118,12 @@ impl ManuallyDrop { } impl ManuallyDrop { - /// Manually drops the contained value. This is exactly equivalent to calling - /// [`ptr::drop_in_place`] with a pointer to the contained value. As such, unless - /// the contained value is a packed struct, the destructor will be called in-place - /// without moving the value, and thus can be used to safely drop [pinned] data. + /// Manually drops the contained value. + /// + /// This is exactly equivalent to calling [`ptr::drop_in_place`] with a + /// pointer to the contained value. As such, unless the contained value is a + /// packed struct, the destructor will be called in-place without moving the + /// value, and thus can be used to safely drop [pinned] data. /// /// If you have ownership of the value, you can use [`ManuallyDrop::into_inner`] instead. /// diff --git a/library/core/src/mem/maybe_uninit.rs b/library/core/src/mem/maybe_uninit.rs index dd40f57dc8707..f920ab1792daf 100644 --- a/library/core/src/mem/maybe_uninit.rs +++ b/library/core/src/mem/maybe_uninit.rs @@ -1,9 +1,6 @@ use crate::any::type_name; -use crate::fmt; -use crate::intrinsics; use crate::mem::{self, ManuallyDrop}; -use crate::ptr; -use crate::slice; +use crate::{fmt, intrinsics, ptr, slice}; /// A wrapper type to construct uninitialized instances of `T`. /// @@ -310,7 +307,7 @@ impl MaybeUninit { MaybeUninit { uninit: () } } - /// Create a new array of `MaybeUninit` items, in an uninitialized state. + /// Creates a new array of `MaybeUninit` items, in an uninitialized state. /// /// Note: in a future Rust version this method may become unnecessary /// when Rust allows diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index dd4b6e823434e..ea2dcdce6e89e 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -5,13 +5,8 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::clone; -use crate::cmp; -use crate::fmt; -use crate::hash; -use crate::intrinsics; use crate::marker::DiscriminantKind; -use crate::ptr; +use crate::{clone, cmp, fmt, hash, intrinsics, ptr}; mod manually_drop; #[stable(feature = "manually_drop", since = "1.20.0")] @@ -359,6 +354,12 @@ pub const fn size_of_val(val: &T) -> usize { /// - a [slice], then the length of the slice tail must be an initialized /// integer, and the size of the *entire value* /// (dynamic tail length + statically sized prefix) must fit in `isize`. +/// For the special case where the dynamic tail length is 0, this function +/// is safe to call. +// NOTE: the reason this is safe is that if an overflow were to occur already with size 0, +// then we would stop compilation as even the "statically known" part of the type would +// already be too big (or the call may be in dead code and optimized away, but then it +// doesn't matter). /// - a [trait object], then the vtable part of the pointer must point /// to a valid vtable acquired by an unsizing coercion, and the size /// of the *entire value* (dynamic tail length + statically sized prefix) @@ -506,6 +507,8 @@ pub const fn align_of_val(val: &T) -> usize { /// - a [slice], then the length of the slice tail must be an initialized /// integer, and the size of the *entire value* /// (dynamic tail length + statically sized prefix) must fit in `isize`. +/// For the special case where the dynamic tail length is 0, this function +/// is safe to call. /// - a [trait object], then the vtable part of the pointer must point /// to a valid vtable acquired by an unsizing coercion, and the size /// of the *entire value* (dynamic tail length + statically sized prefix) @@ -1318,7 +1321,8 @@ impl SizedTypeProperties for T {} /// # Examples /// /// ``` -/// #![feature(offset_of_enum, offset_of_nested)] +/// # #![cfg_attr(bootstrap, feature(offset_of_nested))] +/// #![feature(offset_of_enum)] /// /// use std::mem; /// #[repr(C)] diff --git a/library/core/src/net/display_buffer.rs b/library/core/src/net/display_buffer.rs index 6619c85f483ef..bab84a97308b3 100644 --- a/library/core/src/net/display_buffer.rs +++ b/library/core/src/net/display_buffer.rs @@ -1,6 +1,5 @@ -use crate::fmt; use crate::mem::MaybeUninit; -use crate::str; +use crate::{fmt, str}; /// Used for slow path in `Display` implementations when alignment is required. pub struct DisplayBuffer { diff --git a/library/core/src/net/ip_addr.rs b/library/core/src/net/ip_addr.rs index c11a508a135b3..3e036b88128c7 100644 --- a/library/core/src/net/ip_addr.rs +++ b/library/core/src/net/ip_addr.rs @@ -1,11 +1,10 @@ +use super::display_buffer::DisplayBuffer; use crate::cmp::Ordering; use crate::fmt::{self, Write}; use crate::iter; use crate::mem::transmute; use crate::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not}; -use super::display_buffer::DisplayBuffer; - /// An IP address, either IPv4 or IPv6. /// /// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their @@ -406,8 +405,8 @@ impl IpAddr { matches!(self, IpAddr::V6(_)) } - /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped IPv6 address, otherwise it - /// returns `self` as-is. + /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped IPv6 + /// address, otherwise returns `self` as-is. /// /// # Examples /// @@ -549,7 +548,7 @@ impl Ipv4Addr { #[stable(feature = "ip_constructors", since = "1.30.0")] pub const UNSPECIFIED: Self = Ipv4Addr::new(0, 0, 0, 0); - /// An IPv4 address representing the broadcast address: `255.255.255.255` + /// An IPv4 address representing the broadcast address: `255.255.255.255`. /// /// # Examples /// @@ -686,10 +685,10 @@ impl Ipv4Addr { /// Returns [`true`] if the address appears to be globally reachable /// as specified by the [IANA IPv4 Special-Purpose Address Registry]. - /// Whether or not an address is practically reachable will depend on your network configuration. /// - /// Most IPv4 addresses are globally reachable; - /// unless they are specifically defined as *not* globally reachable. + /// Whether or not an address is practically reachable will depend on your + /// network configuration. Most IPv4 addresses are globally reachable, unless + /// they are specifically defined as *not* globally reachable. /// /// Non-exhaustive list of notable addresses that are not globally reachable: /// @@ -802,8 +801,10 @@ impl Ipv4Addr { } /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for - /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0` - /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`. + /// network devices benchmarking. + /// + /// This range is defined in [IETF RFC 2544] as `192.18.0.0` through + /// `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`. /// /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544 /// [errata 423]: https://www.rfc-editor.org/errata/eid423 @@ -827,10 +828,12 @@ impl Ipv4Addr { self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18 } - /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112] - /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the - /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since - /// it is obviously not reserved for future use. + /// Returns [`true`] if this address is reserved by IANA for future use. + /// + /// [IETF RFC 1112] defines the block of reserved addresses as `240.0.0.0/4`. + /// This range normally includes the broadcast address `255.255.255.255`, but + /// this implementation explicitly excludes it, since it is obviously not + /// reserved for future use. /// /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112 /// @@ -1328,7 +1331,7 @@ impl Ipv6Addr { #[stable(feature = "ip_constructors", since = "1.30.0")] pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); - /// An IPv6 address representing the unspecified address: `::` + /// An IPv6 address representing the unspecified address: `::`. /// /// This corresponds to constant `IN6ADDR_ANY_INIT` or `in6addr_any` in other languages. /// @@ -1424,10 +1427,10 @@ impl Ipv6Addr { /// Returns [`true`] if the address appears to be globally reachable /// as specified by the [IANA IPv6 Special-Purpose Address Registry]. - /// Whether or not an address is practically reachable will depend on your network configuration. /// - /// Most IPv6 addresses are globally reachable; - /// unless they are specifically defined as *not* globally reachable. + /// Whether or not an address is practically reachable will depend on your + /// network configuration. Most IPv6 addresses are globally reachable, unless + /// they are specifically defined as *not* globally reachable. /// /// Non-exhaustive list of notable addresses that are not globally reachable: /// - The [unspecified address] ([`is_unspecified`](Ipv6Addr::is_unspecified)) @@ -1879,8 +1882,8 @@ impl Ipv6Addr { } } - /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped address, otherwise it - /// returns self wrapped in an `IpAddr::V6`. + /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped address, + /// otherwise returns self wrapped in an `IpAddr::V6`. /// /// # Examples /// @@ -1919,7 +1922,7 @@ impl Ipv6Addr { } } -/// Write an Ipv6Addr, conforming to the canonical style described by +/// Writes an Ipv6Addr, conforming to the canonical style described by /// [RFC 5952](https://tools.ietf.org/html/rfc5952). #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for Ipv6Addr { @@ -1962,7 +1965,7 @@ impl fmt::Display for Ipv6Addr { longest }; - /// Write a colon-separated part of the address + /// Writes a colon-separated part of the address. #[inline] fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result { if let Some((first, tail)) = chunk.split_first() { diff --git a/library/core/src/net/parser.rs b/library/core/src/net/parser.rs index deea821244859..a8ec71f0dd801 100644 --- a/library/core/src/net/parser.rs +++ b/library/core/src/net/parser.rs @@ -68,7 +68,7 @@ impl<'a> Parser<'a> { self.state.first().map(|&b| char::from(b)) } - /// Read the next character from the input + /// Reads the next character from the input fn read_char(&mut self) -> Option { self.state.split_first().map(|(&b, tail)| { self.state = tail; @@ -77,7 +77,7 @@ impl<'a> Parser<'a> { } #[must_use] - /// Read the next character from the input if it matches the target. + /// Reads the next character from the input if it matches the target. fn read_given_char(&mut self, target: char) -> Option<()> { self.read_atomically(|p| { p.read_char().and_then(|c| if c == target { Some(()) } else { None }) @@ -165,7 +165,7 @@ impl<'a> Parser<'a> { } } - /// Read an IPv4 address. + /// Reads an IPv4 address. fn read_ipv4_addr(&mut self) -> Option { self.read_atomically(|p| { let mut groups = [0; 4]; @@ -182,7 +182,7 @@ impl<'a> Parser<'a> { }) } - /// Read an IPv6 Address. + /// Reads an IPv6 address. fn read_ipv6_addr(&mut self) -> Option { /// Read a chunk of an IPv6 address into `groups`. Returns the number /// of groups read, along with a bool indicating if an embedded @@ -249,12 +249,12 @@ impl<'a> Parser<'a> { }) } - /// Read an IP Address, either IPv4 or IPv6. + /// Reads an IP address, either IPv4 or IPv6. fn read_ip_addr(&mut self) -> Option { self.read_ipv4_addr().map(IpAddr::V4).or_else(move || self.read_ipv6_addr().map(IpAddr::V6)) } - /// Read a `:` followed by a port in base 10. + /// Reads a `:` followed by a port in base 10. fn read_port(&mut self) -> Option { self.read_atomically(|p| { p.read_given_char(':')?; @@ -262,7 +262,7 @@ impl<'a> Parser<'a> { }) } - /// Read a `%` followed by a scope ID in base 10. + /// Reads a `%` followed by a scope ID in base 10. fn read_scope_id(&mut self) -> Option { self.read_atomically(|p| { p.read_given_char('%')?; @@ -270,7 +270,7 @@ impl<'a> Parser<'a> { }) } - /// Read an IPv4 address with a port. + /// Reads an IPv4 address with a port. fn read_socket_addr_v4(&mut self) -> Option { self.read_atomically(|p| { let ip = p.read_ipv4_addr()?; @@ -279,7 +279,7 @@ impl<'a> Parser<'a> { }) } - /// Read an IPv6 address with a port. + /// Reads an IPv6 address with a port. fn read_socket_addr_v6(&mut self) -> Option { self.read_atomically(|p| { p.read_given_char('[')?; @@ -292,7 +292,7 @@ impl<'a> Parser<'a> { }) } - /// Read an IP address with a port + /// Reads an IP address with a port. fn read_socket_addr(&mut self) -> Option { self.read_socket_addr_v4() .map(SocketAddr::V4) diff --git a/library/core/src/net/socket_addr.rs b/library/core/src/net/socket_addr.rs index c24d8f5519504..4e339172b682f 100644 --- a/library/core/src/net/socket_addr.rs +++ b/library/core/src/net/socket_addr.rs @@ -1,8 +1,7 @@ +use super::display_buffer::DisplayBuffer; use crate::fmt::{self, Write}; use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -use super::display_buffer::DisplayBuffer; - /// An internet socket address, either IPv4 or IPv6. /// /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well diff --git a/library/core/src/num/bignum.rs b/library/core/src/num/bignum.rs index d2a21b6b38260..2a47c89e2aee2 100644 --- a/library/core/src/num/bignum.rs +++ b/library/core/src/num/bignum.rs @@ -145,8 +145,7 @@ macro_rules! define_bignum { /// Adds `other` to itself and returns its own mutable reference. pub fn add<'a>(&'a mut self, other: &$name) -> &'a mut $name { - use crate::cmp; - use crate::iter; + use crate::{cmp, iter}; let mut sz = cmp::max(self.size, other.size); let mut carry = false; @@ -181,8 +180,7 @@ macro_rules! define_bignum { /// Subtracts `other` from itself and returns its own mutable reference. pub fn sub<'a>(&'a mut self, other: &$name) -> &'a mut $name { - use crate::cmp; - use crate::iter; + use crate::{cmp, iter}; let sz = cmp::max(self.size, other.size); let mut noborrow = true; diff --git a/library/core/src/num/dec2flt/common.rs b/library/core/src/num/dec2flt/common.rs index c85727b493816..4dadf406ae8c7 100644 --- a/library/core/src/num/dec2flt/common.rs +++ b/library/core/src/num/dec2flt/common.rs @@ -2,10 +2,10 @@ /// Helper methods to process immutable bytes. pub(crate) trait ByteSlice { - /// Read 8 bytes as a 64-bit integer in little-endian order. + /// Reads 8 bytes as a 64-bit integer in little-endian order. fn read_u64(&self) -> u64; - /// Write a 64-bit integer as 8 bytes in little-endian order. + /// Writes a 64-bit integer as 8 bytes in little-endian order. fn write_u64(&mut self, value: u64); /// Calculate the offset of a slice from another. diff --git a/library/core/src/num/dec2flt/float.rs b/library/core/src/num/dec2flt/float.rs index 1c9d68999d6f8..da57aa9a546af 100644 --- a/library/core/src/num/dec2flt/float.rs +++ b/library/core/src/num/dec2flt/float.rs @@ -81,7 +81,7 @@ pub trait RawFloat: // Maximum mantissa for the fast-path (`1 << 53` for f64). const MAX_MANTISSA_FAST_PATH: u64 = 2_u64 << Self::MANTISSA_EXPLICIT_BITS; - /// Convert integer into float through an as cast. + /// Converts integer into float through an as cast. /// This is only called in the fast-path algorithm, and therefore /// will not lose precision, since the value will always have /// only if the value is <= Self::MAX_MANTISSA_FAST_PATH. @@ -90,7 +90,7 @@ pub trait RawFloat: /// Performs a raw transmutation from an integer. fn from_u64_bits(v: u64) -> Self; - /// Get a small power-of-ten for fast-path multiplication. + /// Gets a small power-of-ten for fast-path multiplication. fn pow10_fast_path(exponent: usize) -> Self; /// Returns the category that this number falls into. diff --git a/library/core/src/num/dec2flt/mod.rs b/library/core/src/num/dec2flt/mod.rs index 9aac2332dce0d..87bfd0d256634 100644 --- a/library/core/src/num/dec2flt/mod.rs +++ b/library/core/src/num/dec2flt/mod.rs @@ -75,15 +75,14 @@ issue = "none" )] -use crate::error::Error; -use crate::fmt; -use crate::str::FromStr; - use self::common::BiasedFp; use self::float::RawFloat; use self::lemire::compute_float; use self::parse::{parse_inf_nan, parse_number}; use self::slow::parse_long_mantissa; +use crate::error::Error; +use crate::fmt; +use crate::str::FromStr; mod common; mod decimal; diff --git a/library/core/src/num/error.rs b/library/core/src/num/error.rs index a2d7e6f7b0754..b8e22a8aef955 100644 --- a/library/core/src/num/error.rs +++ b/library/core/src/num/error.rs @@ -113,7 +113,7 @@ pub enum IntErrorKind { impl ParseIntError { /// Outputs the detailed cause of parsing an integer failing. #[must_use] - #[rustc_const_unstable(feature = "const_int_from_str", issue = "59133")] + #[rustc_const_stable(feature = "const_int_from_str", since = "CURRENT_RUSTC_VERSION")] #[stable(feature = "int_error_matching", since = "1.55.0")] pub const fn kind(&self) -> &IntErrorKind { &self.kind diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs index 05dc1e97852e0..6a24748fd9e87 100644 --- a/library/core/src/num/f128.rs +++ b/library/core/src/num/f128.rs @@ -234,24 +234,20 @@ impl f128 { /// This constant isn't guaranteed to equal to any specific NaN bitpattern, /// and the stability of its representation over Rust versions /// and target platforms isn't guaranteed. - #[cfg(not(bootstrap))] #[allow(clippy::eq_op)] #[rustc_diagnostic_item = "f128_nan"] #[unstable(feature = "f128", issue = "116909")] pub const NAN: f128 = 0.0_f128 / 0.0_f128; /// Infinity (∞). - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] pub const INFINITY: f128 = 1.0_f128 / 0.0_f128; /// Negative infinity (−∞). - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] pub const NEG_INFINITY: f128 = -1.0_f128 / 0.0_f128; /// Sign bit - #[cfg(not(bootstrap))] pub(crate) const SIGN_MASK: u128 = 0x8000_0000_0000_0000_0000_0000_0000_0000; /// Exponent mask @@ -261,11 +257,9 @@ impl f128 { pub(crate) const MAN_MASK: u128 = 0x0000_ffff_ffff_ffff_ffff_ffff_ffff_ffff; /// Minimum representable positive value (min subnormal) - #[cfg(not(bootstrap))] const TINY_BITS: u128 = 0x1; /// Minimum representable negative value (min negative subnormal) - #[cfg(not(bootstrap))] const NEG_TINY_BITS: u128 = Self::TINY_BITS | Self::SIGN_MASK; /// Returns `true` if this value is NaN. @@ -284,7 +278,6 @@ impl f128 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :) pub const fn is_nan(self) -> bool { @@ -295,7 +288,6 @@ impl f128 { // concerns about portability, so this implementation is for // private use internally. #[inline] - #[cfg(not(bootstrap))] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub(crate) const fn abs_private(self) -> f128 { // SAFETY: This transmutation is fine. Probably. For the reasons std is using it. @@ -326,7 +318,6 @@ impl f128 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_infinite(self) -> bool { @@ -354,7 +345,6 @@ impl f128 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_finite(self) -> bool { @@ -389,7 +379,6 @@ impl f128 { /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_subnormal(self) -> bool { @@ -422,7 +411,6 @@ impl f128 { /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_normal(self) -> bool { @@ -448,7 +436,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn classify(self) -> FpCategory { @@ -557,7 +544,6 @@ impl f128 { /// [`MIN`]: Self::MIN /// [`MAX`]: Self::MAX #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] // #[unstable(feature = "float_next_up_down", issue = "91399")] pub fn next_up(self) -> Self { @@ -612,7 +598,6 @@ impl f128 { /// [`MIN`]: Self::MIN /// [`MAX`]: Self::MAX #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] // #[unstable(feature = "float_next_up_down", issue = "91399")] pub fn next_down(self) -> Self { @@ -649,7 +634,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn recip(self) -> Self { @@ -670,7 +654,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn to_degrees(self) -> Self { @@ -694,7 +677,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn to_radians(self) -> f128 { @@ -898,7 +880,7 @@ impl f128 { intrinsics::const_eval_select((v,), ct_u128_to_f128, rt_u128_to_f128) } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// big-endian (network) byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -924,7 +906,7 @@ impl f128 { self.to_bits().to_be_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// little-endian byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -950,7 +932,7 @@ impl f128 { self.to_bits().to_le_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -987,7 +969,7 @@ impl f128 { self.to_bits().to_ne_bytes() } - /// Create a floating point value from its representation as a byte array in big endian. + /// Creates a floating point value from its representation as a byte array in big endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1014,7 +996,7 @@ impl f128 { Self::from_bits(u128::from_be_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in little endian. + /// Creates a floating point value from its representation as a byte array in little endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1041,7 +1023,7 @@ impl f128 { Self::from_bits(u128::from_le_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in native endian. + /// Creates a floating point value from its representation as a byte array in native endian. /// /// As the target platform's native endianness is used, portable code /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as @@ -1078,7 +1060,7 @@ impl f128 { Self::from_bits(u128::from_ne_bytes(bytes)) } - /// Return the ordering between `self` and `other`. + /// Returns the ordering between `self` and `other`. /// /// Unlike the standard partial comparison between floating point numbers, /// this comparison always produces an ordering in accordance to @@ -1141,7 +1123,6 @@ impl f128 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering { let mut left = self.to_bits() as i128; @@ -1201,7 +1182,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f128", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] pub fn clamp(mut self, min: f128, max: f128) -> f128 { diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs index 2a8ede9383844..054897b3c96bc 100644 --- a/library/core/src/num/f16.rs +++ b/library/core/src/num/f16.rs @@ -229,24 +229,20 @@ impl f16 { /// This constant isn't guaranteed to equal to any specific NaN bitpattern, /// and the stability of its representation over Rust versions /// and target platforms isn't guaranteed. - #[cfg(not(bootstrap))] #[allow(clippy::eq_op)] #[rustc_diagnostic_item = "f16_nan"] #[unstable(feature = "f16", issue = "116909")] pub const NAN: f16 = 0.0_f16 / 0.0_f16; /// Infinity (∞). - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] pub const INFINITY: f16 = 1.0_f16 / 0.0_f16; /// Negative infinity (−∞). - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] pub const NEG_INFINITY: f16 = -1.0_f16 / 0.0_f16; /// Sign bit - #[cfg(not(bootstrap))] pub(crate) const SIGN_MASK: u16 = 0x8000; /// Exponent mask @@ -256,11 +252,9 @@ impl f16 { pub(crate) const MAN_MASK: u16 = 0x03ff; /// Minimum representable positive value (min subnormal) - #[cfg(not(bootstrap))] const TINY_BITS: u16 = 0x1; /// Minimum representable negative value (min negative subnormal) - #[cfg(not(bootstrap))] const NEG_TINY_BITS: u16 = Self::TINY_BITS | Self::SIGN_MASK; /// Returns `true` if this value is NaN. @@ -278,7 +272,6 @@ impl f16 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :) pub const fn is_nan(self) -> bool { @@ -289,7 +282,6 @@ impl f16 { // concerns about portability, so this implementation is for // private use internally. #[inline] - #[cfg(not(bootstrap))] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub(crate) const fn abs_private(self) -> f16 { // SAFETY: This transmutation is fine. Probably. For the reasons std is using it. @@ -317,7 +309,6 @@ impl f16 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_infinite(self) -> bool { @@ -344,7 +335,6 @@ impl f16 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_finite(self) -> bool { @@ -377,7 +367,6 @@ impl f16 { /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_subnormal(self) -> bool { @@ -408,7 +397,6 @@ impl f16 { /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn is_normal(self) -> bool { @@ -433,7 +421,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] pub const fn classify(self) -> FpCategory { @@ -478,7 +465,6 @@ impl f16 { /// but getting floats correct is important for not accidentally leaking const eval /// runtime-deviating logic which may or may not be acceptable. #[inline] - #[cfg(not(bootstrap))] #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")] const unsafe fn partial_classify(self) -> FpCategory { // SAFETY: The caller is not asking questions for which this will tell lies. @@ -593,7 +579,6 @@ impl f16 { /// [`MIN`]: Self::MIN /// [`MAX`]: Self::MAX #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] // #[unstable(feature = "float_next_up_down", issue = "91399")] pub fn next_up(self) -> Self { @@ -648,7 +633,6 @@ impl f16 { /// [`MIN`]: Self::MIN /// [`MAX`]: Self::MAX #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] // #[unstable(feature = "float_next_up_down", issue = "91399")] pub fn next_down(self) -> Self { @@ -685,7 +669,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn recip(self) -> Self { @@ -706,7 +689,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn to_degrees(self) -> Self { @@ -730,7 +712,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[must_use = "this returns the result of the operation, without modifying the original"] pub fn to_radians(self) -> f16 { @@ -933,7 +914,7 @@ impl f16 { intrinsics::const_eval_select((v,), ct_u16_to_f16, rt_u16_to_f16) } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// big-endian (network) byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -958,7 +939,7 @@ impl f16 { self.to_bits().to_be_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// little-endian byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -983,7 +964,7 @@ impl f16 { self.to_bits().to_le_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -1021,7 +1002,7 @@ impl f16 { self.to_bits().to_ne_bytes() } - /// Create a floating point value from its representation as a byte array in big endian. + /// Creates a floating point value from its representation as a byte array in big endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1044,7 +1025,7 @@ impl f16 { Self::from_bits(u16::from_be_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in little endian. + /// Creates a floating point value from its representation as a byte array in little endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1067,7 +1048,7 @@ impl f16 { Self::from_bits(u16::from_le_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in native endian. + /// Creates a floating point value from its representation as a byte array in native endian. /// /// As the target platform's native endianness is used, portable code /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as @@ -1101,7 +1082,7 @@ impl f16 { Self::from_bits(u16::from_ne_bytes(bytes)) } - /// Return the ordering between `self` and `other`. + /// Returns the ordering between `self` and `other`. /// /// Unlike the standard partial comparison between floating point numbers, /// this comparison always produces an ordering in accordance to @@ -1167,7 +1148,6 @@ impl f16 { /// ``` #[inline] #[must_use] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering { let mut left = self.to_bits() as i16; @@ -1226,7 +1206,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[unstable(feature = "f16", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] pub fn clamp(mut self, min: f16, max: f16) -> f16 { diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs index b9c84a66ed138..08d863f17caf7 100644 --- a/library/core/src/num/f32.rs +++ b/library/core/src/num/f32.rs @@ -721,11 +721,13 @@ impl f32 { } /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with - /// positive sign bit and positive infinity. Note that IEEE 754 doesn't assign any - /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that - /// the bit pattern of NaNs are conserved over arithmetic operations, the result of - /// `is_sign_positive` on a NaN might produce an unexpected result in some cases. - /// See [explanation of NaN as a special value](f32) for more info. + /// positive sign bit and positive infinity. + /// + /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of + /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are + /// conserved over arithmetic operations, the result of `is_sign_positive` on + /// a NaN might produce an unexpected result in some cases. See [explanation + /// of NaN as a special value](f32) for more info. /// /// ``` /// let f = 7.0_f32; @@ -743,11 +745,13 @@ impl f32 { } /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with - /// negative sign bit and negative infinity. Note that IEEE 754 doesn't assign any - /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that - /// the bit pattern of NaNs are conserved over arithmetic operations, the result of - /// `is_sign_negative` on a NaN might produce an unexpected result in some cases. - /// See [explanation of NaN as a special value](f32) for more info. + /// negative sign bit and negative infinity. + /// + /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of + /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are + /// conserved over arithmetic operations, the result of `is_sign_negative` on + /// a NaN might produce an unexpected result in some cases. See [explanation + /// of NaN as a special value](f32) for more info. /// /// ``` /// let f = 7.0f32; @@ -1274,7 +1278,7 @@ impl f32 { intrinsics::const_eval_select((v,), ct_u32_to_f32, rt_u32_to_f32) } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// big-endian (network) byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -1295,7 +1299,7 @@ impl f32 { self.to_bits().to_be_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// little-endian byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -1316,7 +1320,7 @@ impl f32 { self.to_bits().to_le_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -1350,7 +1354,7 @@ impl f32 { self.to_bits().to_ne_bytes() } - /// Create a floating point value from its representation as a byte array in big endian. + /// Creates a floating point value from its representation as a byte array in big endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1369,7 +1373,7 @@ impl f32 { Self::from_bits(u32::from_be_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in little endian. + /// Creates a floating point value from its representation as a byte array in little endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1388,7 +1392,7 @@ impl f32 { Self::from_bits(u32::from_le_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in native endian. + /// Creates a floating point value from its representation as a byte array in native endian. /// /// As the target platform's native endianness is used, portable code /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as @@ -1418,7 +1422,7 @@ impl f32 { Self::from_bits(u32::from_ne_bytes(bytes)) } - /// Return the ordering between `self` and `other`. + /// Returns the ordering between `self` and `other`. /// /// Unlike the standard partial comparison between floating point numbers, /// this comparison always produces an ordering in accordance to diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs index f8e4555fc44f2..5d33eea6d011f 100644 --- a/library/core/src/num/f64.rs +++ b/library/core/src/num/f64.rs @@ -711,11 +711,13 @@ impl f64 { } /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with - /// positive sign bit and positive infinity. Note that IEEE 754 doesn't assign any - /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that - /// the bit pattern of NaNs are conserved over arithmetic operations, the result of - /// `is_sign_positive` on a NaN might produce an unexpected result in some cases. - /// See [explanation of NaN as a special value](f32) for more info. + /// positive sign bit and positive infinity. + /// + /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of + /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are + /// conserved over arithmetic operations, the result of `is_sign_positive` on + /// a NaN might produce an unexpected result in some cases. See [explanation + /// of NaN as a special value](f32) for more info. /// /// ``` /// let f = 7.0_f64; @@ -742,11 +744,13 @@ impl f64 { } /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with - /// negative sign bit and negative infinity. Note that IEEE 754 doesn't assign any - /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that - /// the bit pattern of NaNs are conserved over arithmetic operations, the result of - /// `is_sign_negative` on a NaN might produce an unexpected result in some cases. - /// See [explanation of NaN as a special value](f32) for more info. + /// negative sign bit and negative infinity. + /// + /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of + /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are + /// conserved over arithmetic operations, the result of `is_sign_negative` on + /// a NaN might produce an unexpected result in some cases. See [explanation + /// of NaN as a special value](f32) for more info. /// /// ``` /// let f = 7.0_f64; @@ -1252,7 +1256,7 @@ impl f64 { intrinsics::const_eval_select((v,), ct_u64_to_f64, rt_u64_to_f64) } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// big-endian (network) byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -1273,7 +1277,7 @@ impl f64 { self.to_bits().to_be_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// little-endian byte order. /// /// See [`from_bits`](Self::from_bits) for some discussion of the @@ -1294,7 +1298,7 @@ impl f64 { self.to_bits().to_le_bytes() } - /// Return the memory representation of this floating point number as a byte array in + /// Returns the memory representation of this floating point number as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -1328,7 +1332,7 @@ impl f64 { self.to_bits().to_ne_bytes() } - /// Create a floating point value from its representation as a byte array in big endian. + /// Creates a floating point value from its representation as a byte array in big endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1347,7 +1351,7 @@ impl f64 { Self::from_bits(u64::from_be_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in little endian. + /// Creates a floating point value from its representation as a byte array in little endian. /// /// See [`from_bits`](Self::from_bits) for some discussion of the /// portability of this operation (there are almost no issues). @@ -1366,7 +1370,7 @@ impl f64 { Self::from_bits(u64::from_le_bytes(bytes)) } - /// Create a floating point value from its representation as a byte array in native endian. + /// Creates a floating point value from its representation as a byte array in native endian. /// /// As the target platform's native endianness is used, portable code /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as @@ -1396,7 +1400,7 @@ impl f64 { Self::from_bits(u64::from_ne_bytes(bytes)) } - /// Return the ordering between `self` and `other`. + /// Returns the ordering between `self` and `other`. /// /// Unlike the standard partial comparison between floating point numbers, /// this comparison always produces an ordering in accordance to diff --git a/library/core/src/num/flt2dec/mod.rs b/library/core/src/num/flt2dec/mod.rs index 1ff2e8c8228c9..7d923a2652f28 100644 --- a/library/core/src/num/flt2dec/mod.rs +++ b/library/core/src/num/flt2dec/mod.rs @@ -123,7 +123,6 @@ functions. )] pub use self::decoder::{decode, DecodableFloat, Decoded, FullDecoded}; - use super::fmt::{Formatted, Part}; use crate::mem::MaybeUninit; diff --git a/library/core/src/num/flt2dec/strategy/dragon.rs b/library/core/src/num/flt2dec/strategy/dragon.rs index 71b14d0ae3f4c..f8db6370653ab 100644 --- a/library/core/src/num/flt2dec/strategy/dragon.rs +++ b/library/core/src/num/flt2dec/strategy/dragon.rs @@ -6,56 +6,57 @@ use crate::cmp::Ordering; use crate::mem::MaybeUninit; - -use crate::num::bignum::Big32x40 as Big; -use crate::num::bignum::Digit32 as Digit; +use crate::num::bignum::{Big32x40 as Big, Digit32 as Digit}; use crate::num::flt2dec::estimator::estimate_scaling_factor; use crate::num::flt2dec::{round_up, Decoded, MAX_SIG_DIGITS}; static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; -static TWOPOW10: [Digit; 10] = - [2, 20, 200, 2000, 20000, 200000, 2000000, 20000000, 200000000, 2000000000]; - -// precalculated arrays of `Digit`s for 10^(2^n) -static POW10TO16: [Digit; 2] = [0x6fc10000, 0x2386f2]; -static POW10TO32: [Digit; 4] = [0, 0x85acef81, 0x2d6d415b, 0x4ee]; -static POW10TO64: [Digit; 7] = [0, 0, 0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; -static POW10TO128: [Digit; 14] = [ - 0, 0, 0, 0, 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, - 0xa6337f19, 0xe91f2603, 0x24e, +// precalculated arrays of `Digit`s for 5^(2^n). +static POW5TO16: [Digit; 2] = [0x86f26fc1, 0x23]; +static POW5TO32: [Digit; 3] = [0x85acef81, 0x2d6d415b, 0x4ee]; +static POW5TO64: [Digit; 5] = [0xbf6a1f01, 0x6e38ed64, 0xdaa797ed, 0xe93ff9f4, 0x184f03]; +static POW5TO128: [Digit; 10] = [ + 0x2e953e01, 0x3df9909, 0xf1538fd, 0x2374e42f, 0xd3cff5ec, 0xc404dc08, 0xbccdb0da, 0xa6337f19, + 0xe91f2603, 0x24e, ]; -static POW10TO256: [Digit; 27] = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, - 0xd595d80f, 0x26b2716e, 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, - 0x55bc28f2, 0x80dcc7f7, 0xf46eeddc, 0x5fdcefce, 0x553f7, +static POW5TO256: [Digit; 19] = [ + 0x982e7c01, 0xbed3875b, 0xd8d99f72, 0x12152f87, 0x6bde50c6, 0xcf4a6e70, 0xd595d80f, 0x26b2716e, + 0xadc666b0, 0x1d153624, 0x3c42d35a, 0x63ff540e, 0xcc5573c0, 0x65f9ef17, 0x55bc28f2, 0x80dcc7f7, + 0xf46eeddc, 0x5fdcefce, 0x553f7, ]; #[doc(hidden)] pub fn mul_pow10(x: &mut Big, n: usize) -> &mut Big { debug_assert!(n < 512); + // Save ourself the left shift for the smallest cases. + if n < 8 { + return x.mul_small(POW10[n & 7]); + } + // Multiply by the powers of 5 and shift the 2s in at the end. + // This keeps the intermediate products smaller and faster. if n & 7 != 0 { - x.mul_small(POW10[n & 7]); + x.mul_small(POW10[n & 7] >> (n & 7)); } if n & 8 != 0 { - x.mul_small(POW10[8]); + x.mul_small(POW10[8] >> 8); } if n & 16 != 0 { - x.mul_digits(&POW10TO16); + x.mul_digits(&POW5TO16); } if n & 32 != 0 { - x.mul_digits(&POW10TO32); + x.mul_digits(&POW5TO32); } if n & 64 != 0 { - x.mul_digits(&POW10TO64); + x.mul_digits(&POW5TO64); } if n & 128 != 0 { - x.mul_digits(&POW10TO128); + x.mul_digits(&POW5TO128); } if n & 256 != 0 { - x.mul_digits(&POW10TO256); + x.mul_digits(&POW5TO256); } - x + x.mul_pow2(n) } fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big { @@ -64,7 +65,7 @@ fn div_2pow10(x: &mut Big, mut n: usize) -> &mut Big { x.div_rem_small(POW10[largest]); n -= largest; } - x.div_rem_small(TWOPOW10[n]); + x.div_rem_small(POW10[n] << 1); x } diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index d40e02352a1d0..dd88e859b30e7 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -1223,6 +1223,7 @@ macro_rules! int_impl { /// ``` #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")] #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);")] + #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(", stringify!($BITS_MINUS_ONE), "), Some(0));")] /// ``` #[stable(feature = "wrapping", since = "1.7.0")] #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] @@ -2196,10 +2197,11 @@ macro_rules! int_impl { acc.wrapping_mul(base) } - /// Calculates `self` + `rhs` + /// Calculates `self` + `rhs`. /// - /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would - /// occur. If an overflow would have occurred then the wrapped value is returned. + /// Returns a tuple of the addition along with a boolean indicating + /// whether an arithmetic overflow would occur. If an overflow would have + /// occurred then the wrapped value is returned. /// /// # Examples /// @@ -2277,7 +2279,7 @@ macro_rules! int_impl { (c, b != d) } - /// Calculates `self` + `rhs` with an unsigned `rhs` + /// Calculates `self` + `rhs` with an unsigned `rhs`. /// /// Returns a tuple of the addition along with a boolean indicating /// whether an arithmetic overflow would occur. If an overflow would @@ -2600,6 +2602,7 @@ macro_rules! int_impl { /// ``` #[doc = concat!("assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));")] /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true)); + #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shl(", stringify!($BITS_MINUS_ONE), "), (0, false));")] /// ``` #[stable(feature = "wrapping", since = "1.7.0")] #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")] @@ -3389,7 +3392,7 @@ macro_rules! int_impl { #[inline(always)] pub const fn is_negative(self) -> bool { self < 0 } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// big-endian (network) byte order. /// #[doc = $to_xe_bytes_doc] @@ -3409,7 +3412,7 @@ macro_rules! int_impl { self.to_be().to_ne_bytes() } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// little-endian byte order. /// #[doc = $to_xe_bytes_doc] @@ -3429,7 +3432,7 @@ macro_rules! int_impl { self.to_le().to_ne_bytes() } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -3467,7 +3470,7 @@ macro_rules! int_impl { unsafe { mem::transmute(self) } } - /// Create an integer value from its representation as a byte array in + /// Creates an integer value from its representation as a byte array in /// big endian. /// #[doc = $from_xe_bytes_doc] @@ -3496,7 +3499,7 @@ macro_rules! int_impl { Self::from_be(Self::from_ne_bytes(bytes)) } - /// Create an integer value from its representation as a byte array in + /// Creates an integer value from its representation as a byte array in /// little endian. /// #[doc = $from_xe_bytes_doc] @@ -3525,7 +3528,7 @@ macro_rules! int_impl { Self::from_le(Self::from_ne_bytes(bytes)) } - /// Create an integer value from its memory representation as a byte + /// Creates an integer value from its memory representation as a byte /// array in native endianness. /// /// As the target platform's native endianness is used, portable code diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index 4e8e0ecdde998..309e1ba958aee 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -2,11 +2,9 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::ascii; -use crate::intrinsics; -use crate::mem; use crate::str::FromStr; use crate::ub_checks::assert_unsafe_precondition; +use crate::{ascii, intrinsics, mem}; // Used because the `?` operator is not allowed in a const context. macro_rules! try_opt { @@ -48,39 +46,31 @@ mod overflow_panic; mod saturating; mod wrapping; -#[stable(feature = "saturating_int_impl", since = "1.74.0")] -pub use saturating::Saturating; -#[stable(feature = "rust1", since = "1.0.0")] -pub use wrapping::Wrapping; - #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(no_fp_fmt_parse))] pub use dec2flt::ParseFloatError; - +#[stable(feature = "int_error_matching", since = "1.55.0")] +pub use error::IntErrorKind; #[stable(feature = "rust1", since = "1.0.0")] pub use error::ParseIntError; - +#[stable(feature = "try_from", since = "1.34.0")] +pub use error::TryFromIntError; +#[stable(feature = "generic_nonzero", since = "1.79.0")] +pub use nonzero::NonZero; #[unstable( feature = "nonzero_internals", reason = "implementation detail which may disappear or be replaced at any time", issue = "none" )] pub use nonzero::ZeroablePrimitive; - -#[stable(feature = "generic_nonzero", since = "1.79.0")] -pub use nonzero::NonZero; - #[stable(feature = "signed_nonzero", since = "1.34.0")] pub use nonzero::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize}; - #[stable(feature = "nonzero", since = "1.28.0")] pub use nonzero::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize}; - -#[stable(feature = "try_from", since = "1.34.0")] -pub use error::TryFromIntError; - -#[stable(feature = "int_error_matching", since = "1.55.0")] -pub use error::IntErrorKind; +#[stable(feature = "saturating_int_impl", since = "1.74.0")] +pub use saturating::Saturating; +#[stable(feature = "rust1", since = "1.0.0")] +pub use wrapping::Wrapping; macro_rules! usize_isize_to_xe_bytes_doc { () => { @@ -483,6 +473,7 @@ impl u8 { ActualT = u8, SignedT = i8, BITS = 8, + BITS_MINUS_ONE = 7, MAX = 255, rot = 2, rot_op = "0x82", @@ -1097,6 +1088,7 @@ impl u16 { ActualT = u16, SignedT = i16, BITS = 16, + BITS_MINUS_ONE = 15, MAX = 65535, rot = 4, rot_op = "0xa003", @@ -1145,6 +1137,7 @@ impl u32 { ActualT = u32, SignedT = i32, BITS = 32, + BITS_MINUS_ONE = 31, MAX = 4294967295, rot = 8, rot_op = "0x10000b3", @@ -1168,6 +1161,7 @@ impl u64 { ActualT = u64, SignedT = i64, BITS = 64, + BITS_MINUS_ONE = 63, MAX = 18446744073709551615, rot = 12, rot_op = "0xaa00000000006e1", @@ -1191,6 +1185,7 @@ impl u128 { ActualT = u128, SignedT = i128, BITS = 128, + BITS_MINUS_ONE = 127, MAX = 340282366920938463463374607431768211455, rot = 16, rot_op = "0x13f40000000000000000000000004f76", @@ -1216,6 +1211,7 @@ impl usize { ActualT = u16, SignedT = isize, BITS = 16, + BITS_MINUS_ONE = 15, MAX = 65535, rot = 4, rot_op = "0xa003", @@ -1240,6 +1236,7 @@ impl usize { ActualT = u32, SignedT = isize, BITS = 32, + BITS_MINUS_ONE = 31, MAX = 4294967295, rot = 8, rot_op = "0x10000b3", @@ -1264,6 +1261,7 @@ impl usize { ActualT = u64, SignedT = isize, BITS = 64, + BITS_MINUS_ONE = 63, MAX = 18446744073709551615, rot = 12, rot_op = "0xaa00000000006e1", @@ -1386,6 +1384,7 @@ from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 } #[doc(hidden)] #[inline(always)] #[unstable(issue = "none", feature = "std_internals")] +#[rustc_const_stable(feature = "const_int_from_str", since = "CURRENT_RUSTC_VERSION")] pub const fn can_not_overflow(radix: u32, is_signed_ty: bool, digits: &[u8]) -> bool { radix <= 16 && digits.len() <= mem::size_of::() * 2 - is_signed_ty as usize } @@ -1435,7 +1434,7 @@ macro_rules! from_str_radix { #[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_str_radix(\"A\", 16), Ok(10));")] /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_int_from_str", issue = "59133")] + #[rustc_const_stable(feature = "const_int_from_str", since = "CURRENT_RUSTC_VERSION")] pub const fn from_str_radix(src: &str, radix: u32) -> Result<$int_ty, ParseIntError> { use self::IntErrorKind::*; use self::ParseIntError as PIE; @@ -1565,7 +1564,7 @@ macro_rules! from_str_radix_size_impl { #[doc = concat!("assert_eq!(", stringify!($size), "::from_str_radix(\"A\", 16), Ok(10));")] /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_int_from_str", issue = "59133")] + #[rustc_const_stable(feature = "const_int_from_str", since = "CURRENT_RUSTC_VERSION")] pub const fn from_str_radix(src: &str, radix: u32) -> Result<$size, ParseIntError> { match <$t>::from_str_radix(src, radix) { Ok(x) => Ok(x as $size), diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index d80d3241b1eee..c6e9c249048a7 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -1,18 +1,13 @@ //! Definitions of integer that is known not to equal zero. +use super::{IntErrorKind, ParseIntError}; use crate::cmp::Ordering; -use crate::fmt; use crate::hash::{Hash, Hasher}; -use crate::hint; -use crate::intrinsics; use crate::marker::{Freeze, StructuralPartialEq}; use crate::ops::{BitOr, BitOrAssign, Div, DivAssign, Neg, Rem, RemAssign}; use crate::panic::{RefUnwindSafe, UnwindSafe}; -use crate::ptr; use crate::str::FromStr; -use crate::ub_checks; - -use super::{IntErrorKind, ParseIntError}; +use crate::{fmt, hint, intrinsics, ptr, ub_checks}; /// A marker trait for primitive types which can be zero. /// @@ -455,6 +450,12 @@ macro_rules! nonzero_integer { UnsignedPrimitive = $Uint:ty, // Used in doc comments. + rot = $rot:literal, + rot_op = $rot_op:literal, + rot_result = $rot_result:literal, + swap_op = $swap_op:literal, + swapped = $swapped:literal, + reversed = $reversed:literal, leading_zeros_test = $leading_zeros_test:expr, ) => { /// An integer that is known not to equal zero. @@ -604,6 +605,270 @@ macro_rules! nonzero_integer { unsafe { NonZero::new_unchecked(self.get().count_ones()) } } + /// Shifts the bits to the left by a specified amount, `n`, + /// wrapping the truncated bits to the end of the resulting integer. + /// + /// Please note this isn't the same operation as the `<<` shifting operator! + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(", $rot_op, stringify!($Int), ")?;")] + #[doc = concat!("let m = NonZero::new(", $rot_result, ")?;")] + /// + #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")] + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn rotate_left(self, n: u32) -> Self { + let result = self.get().rotate_left(n); + // SAFETY: Rotating bits preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Shifts the bits to the right by a specified amount, `n`, + /// wrapping the truncated bits to the beginning of the resulting + /// integer. + /// + /// Please note this isn't the same operation as the `>>` shifting operator! + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(", $rot_result, stringify!($Int), ")?;")] + #[doc = concat!("let m = NonZero::new(", $rot_op, ")?;")] + /// + #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")] + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn rotate_right(self, n: u32) -> Self { + let result = self.get().rotate_right(n); + // SAFETY: Rotating bits preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Reverses the byte order of the integer. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(", $swap_op, stringify!($Int), ")?;")] + /// let m = n.swap_bytes(); + /// + #[doc = concat!("assert_eq!(m, NonZero::new(", $swapped, ")?);")] + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn swap_bytes(self) -> Self { + let result = self.get().swap_bytes(); + // SAFETY: Shuffling bytes preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit, + /// second least-significant bit becomes second most-significant bit, etc. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(", $swap_op, stringify!($Int), ")?;")] + /// let m = n.reverse_bits(); + /// + #[doc = concat!("assert_eq!(m, NonZero::new(", $reversed, ")?);")] + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn reverse_bits(self) -> Self { + let result = self.get().reverse_bits(); + // SAFETY: Reversing bits preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Converts an integer from big endian to the target's endianness. + /// + /// On big endian this is a no-op. On little endian the bytes are + /// swapped. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + #[doc = concat!("use std::num::", stringify!($Ty), ";")] + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")] + /// + /// if cfg!(target_endian = "big") { + #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_be(n), n)")] + /// } else { + #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_be(n), n.swap_bytes())")] + /// } + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use] + #[inline(always)] + pub const fn from_be(x: Self) -> Self { + let result = $Int::from_be(x.get()); + // SAFETY: Shuffling bytes preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Converts an integer from little endian to the target's endianness. + /// + /// On little endian this is a no-op. On big endian the bytes are + /// swapped. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + #[doc = concat!("use std::num::", stringify!($Ty), ";")] + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")] + /// + /// if cfg!(target_endian = "little") { + #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_le(n), n)")] + /// } else { + #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_le(n), n.swap_bytes())")] + /// } + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use] + #[inline(always)] + pub const fn from_le(x: Self) -> Self { + let result = $Int::from_le(x.get()); + // SAFETY: Shuffling bytes preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Converts `self` to big endian from the target's endianness. + /// + /// On big endian this is a no-op. On little endian the bytes are + /// swapped. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")] + /// + /// if cfg!(target_endian = "big") { + /// assert_eq!(n.to_be(), n) + /// } else { + /// assert_eq!(n.to_be(), n.swap_bytes()) + /// } + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn to_be(self) -> Self { + let result = self.get().to_be(); + // SAFETY: Shuffling bytes preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + + /// Converts `self` to little endian from the target's endianness. + /// + /// On little endian this is a no-op. On big endian the bytes are + /// swapped. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(nonzero_bitwise)] + /// # use std::num::NonZero; + /// # + /// # fn main() { test().unwrap(); } + /// # fn test() -> Option<()> { + #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")] + /// + /// if cfg!(target_endian = "little") { + /// assert_eq!(n.to_le(), n) + /// } else { + /// assert_eq!(n.to_le(), n.swap_bytes()) + /// } + /// # Some(()) + /// # } + /// ``` + #[unstable(feature = "nonzero_bitwise", issue = "128281")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn to_le(self) -> Self { + let result = self.get().to_le(); + // SAFETY: Shuffling bytes preserves the property int > 0. + unsafe { Self::new_unchecked(result) } + } + nonzero_integer_signedness_dependent_methods! { Primitive = $signedness $Int, UnsignedPrimitive = $Uint, @@ -826,22 +1091,54 @@ macro_rules! nonzero_integer { nonzero_integer_signedness_dependent_impls!($signedness $Int); }; - (Self = $Ty:ident, Primitive = unsigned $Int:ident $(,)?) => { + ( + Self = $Ty:ident, + Primitive = unsigned $Int:ident, + rot = $rot:literal, + rot_op = $rot_op:literal, + rot_result = $rot_result:literal, + swap_op = $swap_op:literal, + swapped = $swapped:literal, + reversed = $reversed:literal, + $(,)? + ) => { nonzero_integer! { #[stable(feature = "nonzero", since = "1.28.0")] Self = $Ty, Primitive = unsigned $Int, UnsignedPrimitive = $Int, + rot = $rot, + rot_op = $rot_op, + rot_result = $rot_result, + swap_op = $swap_op, + swapped = $swapped, + reversed = $reversed, leading_zeros_test = concat!(stringify!($Int), "::MAX"), } }; - (Self = $Ty:ident, Primitive = signed $Int:ident, $($rest:tt)*) => { + ( + Self = $Ty:ident, + Primitive = signed $Int:ident, + UnsignedPrimitive = $UInt:ident, + rot = $rot:literal, + rot_op = $rot_op:literal, + rot_result = $rot_result:literal, + swap_op = $swap_op:literal, + swapped = $swapped:literal, + reversed = $reversed:literal, + ) => { nonzero_integer! { #[stable(feature = "signed_nonzero", since = "1.34.0")] Self = $Ty, Primitive = signed $Int, - $($rest)* + UnsignedPrimitive = $UInt, + rot = $rot, + rot_op = $rot_op, + rot_result = $rot_result, + swap_op = $swap_op, + swapped = $swapped, + reversed = $reversed, leading_zeros_test = concat!("-1", stringify!($Int)), } }; @@ -1241,6 +1538,7 @@ macro_rules! nonzero_integer_signedness_dependent_methods { /// assert_eq!(ten.isqrt(), three); /// # Some(()) /// # } + /// ``` #[unstable(feature = "isqrt", issue = "116226")] #[rustc_const_unstable(feature = "isqrt", issue = "116226")] #[must_use = "this returns the result of the operation, \ @@ -1704,65 +2002,189 @@ macro_rules! sign_dependent_expr { nonzero_integer! { Self = NonZeroU8, Primitive = unsigned u8, + rot = 2, + rot_op = "0x82", + rot_result = "0xa", + swap_op = "0x12", + swapped = "0x12", + reversed = "0x48", } nonzero_integer! { Self = NonZeroU16, Primitive = unsigned u16, + rot = 4, + rot_op = "0xa003", + rot_result = "0x3a", + swap_op = "0x1234", + swapped = "0x3412", + reversed = "0x2c48", } nonzero_integer! { Self = NonZeroU32, Primitive = unsigned u32, + rot = 8, + rot_op = "0x10000b3", + rot_result = "0xb301", + swap_op = "0x12345678", + swapped = "0x78563412", + reversed = "0x1e6a2c48", } nonzero_integer! { Self = NonZeroU64, Primitive = unsigned u64, + rot = 12, + rot_op = "0xaa00000000006e1", + rot_result = "0x6e10aa", + swap_op = "0x1234567890123456", + swapped = "0x5634129078563412", + reversed = "0x6a2c48091e6a2c48", } nonzero_integer! { Self = NonZeroU128, Primitive = unsigned u128, + rot = 16, + rot_op = "0x13f40000000000000000000000004f76", + rot_result = "0x4f7613f4", + swap_op = "0x12345678901234567890123456789012", + swapped = "0x12907856341290785634129078563412", + reversed = "0x48091e6a2c48091e6a2c48091e6a2c48", +} + +#[cfg(target_pointer_width = "16")] +nonzero_integer! { + Self = NonZeroUsize, + Primitive = unsigned usize, + rot = 4, + rot_op = "0xa003", + rot_result = "0x3a", + swap_op = "0x1234", + swapped = "0x3412", + reversed = "0x2c48", } +#[cfg(target_pointer_width = "32")] nonzero_integer! { Self = NonZeroUsize, Primitive = unsigned usize, + rot = 8, + rot_op = "0x10000b3", + rot_result = "0xb301", + swap_op = "0x12345678", + swapped = "0x78563412", + reversed = "0x1e6a2c48", +} + +#[cfg(target_pointer_width = "64")] +nonzero_integer! { + Self = NonZeroUsize, + Primitive = unsigned usize, + rot = 12, + rot_op = "0xaa00000000006e1", + rot_result = "0x6e10aa", + swap_op = "0x1234567890123456", + swapped = "0x5634129078563412", + reversed = "0x6a2c48091e6a2c48", } nonzero_integer! { Self = NonZeroI8, Primitive = signed i8, UnsignedPrimitive = u8, + rot = 2, + rot_op = "-0x7e", + rot_result = "0xa", + swap_op = "0x12", + swapped = "0x12", + reversed = "0x48", } nonzero_integer! { Self = NonZeroI16, Primitive = signed i16, UnsignedPrimitive = u16, + rot = 4, + rot_op = "-0x5ffd", + rot_result = "0x3a", + swap_op = "0x1234", + swapped = "0x3412", + reversed = "0x2c48", } nonzero_integer! { Self = NonZeroI32, Primitive = signed i32, UnsignedPrimitive = u32, + rot = 8, + rot_op = "0x10000b3", + rot_result = "0xb301", + swap_op = "0x12345678", + swapped = "0x78563412", + reversed = "0x1e6a2c48", } nonzero_integer! { Self = NonZeroI64, Primitive = signed i64, UnsignedPrimitive = u64, + rot = 12, + rot_op = "0xaa00000000006e1", + rot_result = "0x6e10aa", + swap_op = "0x1234567890123456", + swapped = "0x5634129078563412", + reversed = "0x6a2c48091e6a2c48", } nonzero_integer! { Self = NonZeroI128, Primitive = signed i128, UnsignedPrimitive = u128, + rot = 16, + rot_op = "0x13f40000000000000000000000004f76", + rot_result = "0x4f7613f4", + swap_op = "0x12345678901234567890123456789012", + swapped = "0x12907856341290785634129078563412", + reversed = "0x48091e6a2c48091e6a2c48091e6a2c48", +} + +#[cfg(target_pointer_width = "16")] +nonzero_integer! { + Self = NonZeroIsize, + Primitive = signed isize, + UnsignedPrimitive = usize, + rot = 4, + rot_op = "-0x5ffd", + rot_result = "0x3a", + swap_op = "0x1234", + swapped = "0x3412", + reversed = "0x2c48", +} + +#[cfg(target_pointer_width = "32")] +nonzero_integer! { + Self = NonZeroIsize, + Primitive = signed isize, + UnsignedPrimitive = usize, + rot = 8, + rot_op = "0x10000b3", + rot_result = "0xb301", + swap_op = "0x12345678", + swapped = "0x78563412", + reversed = "0x1e6a2c48", } +#[cfg(target_pointer_width = "64")] nonzero_integer! { Self = NonZeroIsize, Primitive = signed isize, UnsignedPrimitive = usize, + rot = 12, + rot_op = "0xaa00000000006e1", + rot_result = "0x6e10aa", + swap_op = "0x1234567890123456", + swapped = "0x5634129078563412", + reversed = "0x6a2c48091e6a2c48", } diff --git a/library/core/src/num/saturating.rs b/library/core/src/num/saturating.rs index d040539ebe556..3f4791e163e69 100644 --- a/library/core/src/num/saturating.rs +++ b/library/core/src/num/saturating.rs @@ -1,10 +1,10 @@ //! Definitions of `Saturating`. use crate::fmt; -use crate::ops::{Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign}; -use crate::ops::{BitXor, BitXorAssign, Div, DivAssign}; -use crate::ops::{Mul, MulAssign, Neg, Not, Rem, RemAssign}; -use crate::ops::{Sub, SubAssign}; +use crate::ops::{ + Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, + Mul, MulAssign, Neg, Not, Rem, RemAssign, Sub, SubAssign, +}; /// Provides intentionally-saturating arithmetic on `T`. /// diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index d50bcde01571c..a2e17fae76873 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -9,6 +9,7 @@ macro_rules! uint_impl { // literal is fine if they need to be multiple code tokens. // In non-comments, use the associated constants rather than these. BITS = $BITS:literal, + BITS_MINUS_ONE = $BITS_MINUS_ONE:literal, MAX = $MaxV:literal, rot = $rot:literal, rot_op = $rot_op:literal, @@ -65,8 +66,13 @@ macro_rules! uint_impl { /// /// ``` #[doc = concat!("let n = 0b01001100", stringify!($SelfT), ";")] - /// /// assert_eq!(n.count_ones(), 3); + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + #[doc = concat!("assert_eq!(max.count_ones(), ", stringify!($BITS), ");")] + /// + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + /// assert_eq!(zero.count_ones(), 0); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_math", since = "1.32.0")] @@ -86,7 +92,11 @@ macro_rules! uint_impl { /// Basic usage: /// /// ``` - #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);")] + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + #[doc = concat!("assert_eq!(zero.count_zeros(), ", stringify!($BITS), ");")] + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + /// assert_eq!(max.count_zeros(), 0); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_math", since = "1.32.0")] @@ -108,8 +118,13 @@ macro_rules! uint_impl { /// /// ``` #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")] - /// /// assert_eq!(n.leading_zeros(), 2); + /// + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + #[doc = concat!("assert_eq!(zero.leading_zeros(), ", stringify!($BITS), ");")] + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + /// assert_eq!(max.leading_zeros(), 0); /// ``` #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")] #[stable(feature = "rust1", since = "1.0.0")] @@ -130,8 +145,13 @@ macro_rules! uint_impl { /// /// ``` #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")] - /// /// assert_eq!(n.trailing_zeros(), 3); + /// + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + #[doc = concat!("assert_eq!(zero.trailing_zeros(), ", stringify!($BITS), ");")] + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + #[doc = concat!("assert_eq!(max.trailing_zeros(), 0);")] /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_math", since = "1.32.0")] @@ -150,8 +170,13 @@ macro_rules! uint_impl { /// /// ``` #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")] - /// /// assert_eq!(n.leading_ones(), 2); + /// + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + /// assert_eq!(zero.leading_ones(), 0); + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + #[doc = concat!("assert_eq!(max.leading_ones(), ", stringify!($BITS), ");")] /// ``` #[stable(feature = "leading_trailing_ones", since = "1.46.0")] #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")] @@ -171,8 +196,13 @@ macro_rules! uint_impl { /// /// ``` #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")] - /// /// assert_eq!(n.trailing_ones(), 3); + /// + #[doc = concat!("let zero = 0", stringify!($SelfT), ";")] + /// assert_eq!(zero.trailing_ones(), 0); + /// + #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")] + #[doc = concat!("assert_eq!(max.trailing_ones(), ", stringify!($BITS), ");")] /// ``` #[stable(feature = "leading_trailing_ones", since = "1.46.0")] #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")] @@ -736,6 +766,67 @@ macro_rules! uint_impl { } } + #[doc = concat!( + "Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`", + stringify!($SignedT), "`], returning `None` if overflow occurred." + )] + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(unsigned_signed_diff)] + #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_signed_diff(2), Some(8));")] + #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_signed_diff(10), Some(-8));")] + #[doc = concat!( + "assert_eq!(", + stringify!($SelfT), + "::MAX.checked_signed_diff(", + stringify!($SignedT), + "::MAX as ", + stringify!($SelfT), + "), None);" + )] + #[doc = concat!( + "assert_eq!((", + stringify!($SignedT), + "::MAX as ", + stringify!($SelfT), + ").checked_signed_diff(", + stringify!($SelfT), + "::MAX), Some(", + stringify!($SignedT), + "::MIN));" + )] + #[doc = concat!( + "assert_eq!((", + stringify!($SignedT), + "::MAX as ", + stringify!($SelfT), + " + 1).checked_signed_diff(0), None);" + )] + #[doc = concat!( + "assert_eq!(", + stringify!($SelfT), + "::MAX.checked_signed_diff(", + stringify!($SelfT), + "::MAX), Some(0));" + )] + /// ``` + #[unstable(feature = "unsigned_signed_diff", issue = "126041")] + #[inline] + pub const fn checked_signed_diff(self, rhs: Self) -> Option<$SignedT> { + let res = self.wrapping_sub(rhs) as $SignedT; + let overflow = (self >= rhs) == (res < 0); + + if !overflow { + Some(res) + } else { + None + } + } + /// Checked integer multiplication. Computes `self * rhs`, returning /// `None` if overflow occurred. /// @@ -859,10 +950,10 @@ macro_rules! uint_impl { } /// Strict integer division. Computes `self / rhs`. - /// Strict division on unsigned types is just normal division. - /// There's no way overflow could ever happen. - /// This function exists, so that all operations - /// are accounted for in the strict operations. + /// + /// Strict division on unsigned types is just normal division. There's no + /// way overflow could ever happen. This function exists so that all + /// operations are accounted for in the strict operations. /// /// # Panics /// @@ -918,12 +1009,11 @@ macro_rules! uint_impl { } /// Strict Euclidean division. Computes `self.div_euclid(rhs)`. - /// Strict division on unsigned types is just normal division. - /// There's no way overflow could ever happen. - /// This function exists, so that all operations - /// are accounted for in the strict operations. - /// Since, for the positive integers, all common - /// definitions of division are equal, this + /// + /// Strict division on unsigned types is just normal division. There's no + /// way overflow could ever happen. This function exists so that all + /// operations are accounted for in the strict operations. Since, for the + /// positive integers, all common definitions of division are equal, this /// is exactly equal to `self.strict_div(rhs)`. /// /// # Panics @@ -981,11 +1071,11 @@ macro_rules! uint_impl { } /// Strict integer remainder. Computes `self % rhs`. - /// Strict remainder calculation on unsigned types is - /// just the regular remainder calculation. - /// There's no way overflow could ever happen. - /// This function exists, so that all operations - /// are accounted for in the strict operations. + /// + /// Strict remainder calculation on unsigned types is just the regular + /// remainder calculation. There's no way overflow could ever happen. + /// This function exists so that all operations are accounted for in the + /// strict operations. /// /// # Panics /// @@ -1041,14 +1131,13 @@ macro_rules! uint_impl { } /// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`. - /// Strict modulo calculation on unsigned types is - /// just the regular remainder calculation. - /// There's no way overflow could ever happen. - /// This function exists, so that all operations - /// are accounted for in the strict operations. - /// Since, for the positive integers, all common - /// definitions of division are equal, this - /// is exactly equal to `self.strict_rem(rhs)`. + /// + /// Strict modulo calculation on unsigned types is just the regular + /// remainder calculation. There's no way overflow could ever happen. + /// This function exists so that all operations are accounted for in the + /// strict operations. Since, for the positive integers, all common + /// definitions of division are equal, this is exactly equal to + /// `self.strict_rem(rhs)`. /// /// # Panics /// @@ -1323,6 +1412,7 @@ macro_rules! uint_impl { /// ``` #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")] #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")] + #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(", stringify!($BITS_MINUS_ONE), "), Some(0));")] /// ``` #[stable(feature = "wrapping", since = "1.7.0")] #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] @@ -1824,10 +1914,10 @@ macro_rules! uint_impl { } /// Wrapping (modular) division. Computes `self / rhs`. - /// Wrapped division on unsigned types is just normal division. - /// There's no way wrapping could ever happen. - /// This function exists, so that all operations - /// are accounted for in the wrapping operations. + /// + /// Wrapped division on unsigned types is just normal division. There's + /// no way wrapping could ever happen. This function exists so that all + /// operations are accounted for in the wrapping operations. /// /// # Panics /// @@ -1851,13 +1941,12 @@ macro_rules! uint_impl { } /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`. - /// Wrapped division on unsigned types is just normal division. - /// There's no way wrapping could ever happen. - /// This function exists, so that all operations - /// are accounted for in the wrapping operations. - /// Since, for the positive integers, all common - /// definitions of division are equal, this - /// is exactly equal to `self.wrapping_div(rhs)`. + /// + /// Wrapped division on unsigned types is just normal division. There's + /// no way wrapping could ever happen. This function exists so that all + /// operations are accounted for in the wrapping operations. Since, for + /// the positive integers, all common definitions of division are equal, + /// this is exactly equal to `self.wrapping_div(rhs)`. /// /// # Panics /// @@ -1881,11 +1970,11 @@ macro_rules! uint_impl { } /// Wrapping (modular) remainder. Computes `self % rhs`. - /// Wrapped remainder calculation on unsigned types is - /// just the regular remainder calculation. - /// There's no way wrapping could ever happen. - /// This function exists, so that all operations - /// are accounted for in the wrapping operations. + /// + /// Wrapped remainder calculation on unsigned types is just the regular + /// remainder calculation. There's no way wrapping could ever happen. + /// This function exists so that all operations are accounted for in the + /// wrapping operations. /// /// # Panics /// @@ -1909,14 +1998,13 @@ macro_rules! uint_impl { } /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`. - /// Wrapped modulo calculation on unsigned types is - /// just the regular remainder calculation. - /// There's no way wrapping could ever happen. - /// This function exists, so that all operations - /// are accounted for in the wrapping operations. - /// Since, for the positive integers, all common - /// definitions of division are equal, this - /// is exactly equal to `self.wrapping_rem(rhs)`. + /// + /// Wrapped modulo calculation on unsigned types is just the regular + /// remainder calculation. There's no way wrapping could ever happen. + /// This function exists so that all operations are accounted for in the + /// wrapping operations. Since, for the positive integers, all common + /// definitions of division are equal, this is exactly equal to + /// `self.wrapping_rem(rhs)`. /// /// # Panics /// @@ -2072,7 +2160,7 @@ macro_rules! uint_impl { acc.wrapping_mul(base) } - /// Calculates `self` + `rhs` + /// Calculates `self` + `rhs`. /// /// Returns a tuple of the addition along with a boolean indicating /// whether an arithmetic overflow would occur. If an overflow would @@ -2146,7 +2234,7 @@ macro_rules! uint_impl { (c, b || d) } - /// Calculates `self` + `rhs` with a signed `rhs` + /// Calculates `self` + `rhs` with a signed `rhs`. /// /// Returns a tuple of the addition along with a boolean indicating /// whether an arithmetic overflow would occur. If an overflow would @@ -2451,6 +2539,7 @@ macro_rules! uint_impl { /// ``` #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")] #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")] + #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shl(", stringify!($BITS_MINUS_ONE), "), (0, false));")] /// ``` #[stable(feature = "wrapping", since = "1.7.0")] #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] @@ -2764,6 +2853,35 @@ macro_rules! uint_impl { } } + /// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise. + /// + /// This function is equivalent to `self % rhs == 0`, except that it will not panic + /// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`, + /// `n.is_multiple_of(0) == false`. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(unsigned_is_multiple_of)] + #[doc = concat!("assert!(6_", stringify!($SelfT), ".is_multiple_of(2));")] + #[doc = concat!("assert!(!5_", stringify!($SelfT), ".is_multiple_of(2));")] + /// + #[doc = concat!("assert!(0_", stringify!($SelfT), ".is_multiple_of(0));")] + #[doc = concat!("assert!(!6_", stringify!($SelfT), ".is_multiple_of(0));")] + /// ``` + #[unstable(feature = "unsigned_is_multiple_of", issue = "128101")] + #[must_use] + #[inline] + #[rustc_inherit_overflow_checks] + pub const fn is_multiple_of(self, rhs: Self) -> bool { + match rhs { + 0 => self == 0, + _ => self % rhs == 0, + } + } + /// Returns `true` if and only if `self == 2^k` for some `k`. /// /// # Examples @@ -2877,7 +2995,7 @@ macro_rules! uint_impl { self.one_less_than_next_power_of_two().wrapping_add(1) } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// big-endian (network) byte order. /// #[doc = $to_xe_bytes_doc] @@ -2897,7 +3015,7 @@ macro_rules! uint_impl { self.to_be().to_ne_bytes() } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// little-endian byte order. /// #[doc = $to_xe_bytes_doc] @@ -2917,7 +3035,7 @@ macro_rules! uint_impl { self.to_le().to_ne_bytes() } - /// Return the memory representation of this integer as a byte array in + /// Returns the memory representation of this integer as a byte array in /// native byte order. /// /// As the target platform's native endianness is used, portable code @@ -2955,7 +3073,7 @@ macro_rules! uint_impl { unsafe { mem::transmute(self) } } - /// Create a native endian integer value from its representation + /// Creates a native endian integer value from its representation /// as a byte array in big endian. /// #[doc = $from_xe_bytes_doc] @@ -2984,7 +3102,7 @@ macro_rules! uint_impl { Self::from_be(Self::from_ne_bytes(bytes)) } - /// Create a native endian integer value from its representation + /// Creates a native endian integer value from its representation /// as a byte array in little endian. /// #[doc = $from_xe_bytes_doc] @@ -3013,7 +3131,7 @@ macro_rules! uint_impl { Self::from_le(Self::from_ne_bytes(bytes)) } - /// Create a native endian integer value from its memory representation + /// Creates a native endian integer value from its memory representation /// as a byte array in native endianness. /// /// As the target platform's native endianness is used, portable code diff --git a/library/core/src/num/wrapping.rs b/library/core/src/num/wrapping.rs index 16f0b6d913dfb..1ac6d3161c2f9 100644 --- a/library/core/src/num/wrapping.rs +++ b/library/core/src/num/wrapping.rs @@ -1,10 +1,10 @@ //! Definitions of `Wrapping`. use crate::fmt; -use crate::ops::{Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign}; -use crate::ops::{BitXor, BitXorAssign, Div, DivAssign}; -use crate::ops::{Mul, MulAssign, Neg, Not, Rem, RemAssign}; -use crate::ops::{Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign}; +use crate::ops::{ + Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign, + Mul, MulAssign, Neg, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign, +}; /// Provides intentionally-wrapped arithmetic on `T`. /// diff --git a/library/core/src/ops/async_function.rs b/library/core/src/ops/async_function.rs index 48d1042d9df4a..37fac2b126fac 100644 --- a/library/core/src/ops/async_function.rs +++ b/library/core/src/ops/async_function.rs @@ -4,7 +4,7 @@ use crate::marker::Tuple; /// An async-aware version of the [`Fn`](crate::ops::Fn) trait. /// /// All `async fn` and functions returning futures implement this trait. -#[unstable(feature = "async_fn_traits", issue = "none")] +#[unstable(feature = "async_closure", issue = "62290")] #[rustc_paren_sugar] #[fundamental] #[must_use = "async closures are lazy and do nothing unless called"] @@ -18,7 +18,7 @@ pub trait AsyncFn: AsyncFnMut { /// An async-aware version of the [`FnMut`](crate::ops::FnMut) trait. /// /// All `async fn` and functions returning futures implement this trait. -#[unstable(feature = "async_fn_traits", issue = "none")] +#[unstable(feature = "async_closure", issue = "62290")] #[rustc_paren_sugar] #[fundamental] #[must_use = "async closures are lazy and do nothing unless called"] @@ -39,7 +39,7 @@ pub trait AsyncFnMut: AsyncFnOnce { /// An async-aware version of the [`FnOnce`](crate::ops::FnOnce) trait. /// /// All `async fn` and functions returning futures implement this trait. -#[unstable(feature = "async_fn_traits", issue = "none")] +#[unstable(feature = "async_closure", issue = "62290")] #[rustc_paren_sugar] #[fundamental] #[must_use = "async closures are lazy and do nothing unless called"] diff --git a/library/core/src/ops/control_flow.rs b/library/core/src/ops/control_flow.rs index e10c438ef4300..a2709c66b06ad 100644 --- a/library/core/src/ops/control_flow.rs +++ b/library/core/src/ops/control_flow.rs @@ -238,7 +238,7 @@ impl ControlFlow { /// They have mediocre names and non-obvious semantics, so aren't /// currently on a path to potential stabilization. impl ControlFlow { - /// Create a `ControlFlow` from any type implementing `Try`. + /// Creates a `ControlFlow` from any type implementing `Try`. #[inline] pub(crate) fn from_try(r: R) -> Self { match R::branch(r) { @@ -247,7 +247,7 @@ impl ControlFlow { } } - /// Convert a `ControlFlow` into any type implementing `Try`; + /// Converts a `ControlFlow` into any type implementing `Try`. #[inline] pub(crate) fn into_try(self) -> R { match self { diff --git a/library/core/src/ops/coroutine.rs b/library/core/src/ops/coroutine.rs index 753f14c6b85ec..13df888d24c5c 100644 --- a/library/core/src/ops/coroutine.rs +++ b/library/core/src/ops/coroutine.rs @@ -76,7 +76,7 @@ pub trait Coroutine { /// values which are allowed to be returned each time a coroutine yields. /// For example an iterator-as-a-coroutine would likely have this type as /// `T`, the type being iterated over. - #[cfg_attr(not(bootstrap), lang = "coroutine_yield")] + #[lang = "coroutine_yield"] type Yield; /// The type of value this coroutine returns. @@ -85,7 +85,7 @@ pub trait Coroutine { /// `return` statement or implicitly as the last expression of a coroutine /// literal. For example futures would use this as `Result` as it /// represents a completed future. - #[cfg_attr(not(bootstrap), lang = "coroutine_return")] + #[lang = "coroutine_return"] type Return; /// Resumes the execution of this coroutine. diff --git a/library/core/src/ops/deref.rs b/library/core/src/ops/deref.rs index 9849410d484ca..f0d2c761ef35b 100644 --- a/library/core/src/ops/deref.rs +++ b/library/core/src/ops/deref.rs @@ -282,7 +282,7 @@ impl DerefMut for &mut T { /// FIXME(deref_patterns): The precise semantics are undecided; the rough idea is that /// successive calls to `deref`/`deref_mut` without intermediate mutation should be /// idempotent, in the sense that they return the same value as far as pattern-matching -/// is concerned. Calls to `deref`/`deref_mut`` must leave the pointer itself likewise +/// is concerned. Calls to `deref`/`deref_mut` must leave the pointer itself likewise /// unchanged. #[unstable(feature = "deref_pure_trait", issue = "87121")] #[lang = "deref_pure"] diff --git a/library/core/src/ops/drop.rs b/library/core/src/ops/drop.rs index 36ae581e3f723..c6083a121d107 100644 --- a/library/core/src/ops/drop.rs +++ b/library/core/src/ops/drop.rs @@ -171,12 +171,13 @@ /// still be live when `T` gets dropped. The exact details of this analysis are not yet /// stably guaranteed and **subject to change**. Currently, the analysis works as follows: /// - If `T` has no drop glue, then trivially nothing is required to be live. This is the case if -/// neither `T` nor any of its (recursive) fields have a destructor (`impl Drop`). [`PhantomData`] -/// and [`ManuallyDrop`] are considered to never have a destructor, no matter their field type. +/// neither `T` nor any of its (recursive) fields have a destructor (`impl Drop`). [`PhantomData`], +/// arrays of length 0 and [`ManuallyDrop`] are considered to never have a destructor, no matter +/// their field type. /// - If `T` has drop glue, then, for all types `U` that are *owned* by any field of `T`, /// recursively add the types and lifetimes that need to be live when `U` gets dropped. The set of /// owned types is determined by recursively traversing `T`: -/// - Recursively descend through `PhantomData`, `Box`, tuples, and arrays (including arrays of +/// - Recursively descend through `PhantomData`, `Box`, tuples, and arrays (excluding arrays of /// length 0). /// - Stop at reference and raw pointer types as well as function pointers and function items; /// they do not own anything. diff --git a/library/core/src/ops/mod.rs b/library/core/src/ops/mod.rs index 7bcfaadbe372b..98d41b71e8eb8 100644 --- a/library/core/src/ops/mod.rs +++ b/library/core/src/ops/mod.rs @@ -156,65 +156,44 @@ mod unsize; pub use self::arith::{Add, Div, Mul, Neg, Rem, Sub}; #[stable(feature = "op_assign_traits", since = "1.8.0")] pub use self::arith::{AddAssign, DivAssign, MulAssign, RemAssign, SubAssign}; - +#[unstable(feature = "async_fn_traits", issue = "none")] +pub use self::async_function::{AsyncFn, AsyncFnMut, AsyncFnOnce}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::bit::{BitAnd, BitOr, BitXor, Not, Shl, Shr}; #[stable(feature = "op_assign_traits", since = "1.8.0")] pub use self::bit::{BitAndAssign, BitOrAssign, BitXorAssign, ShlAssign, ShrAssign}; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::deref::{Deref, DerefMut}; - +#[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")] +pub use self::control_flow::ControlFlow; +#[unstable(feature = "coroutine_trait", issue = "43122")] +pub use self::coroutine::{Coroutine, CoroutineState}; #[unstable(feature = "deref_pure_trait", issue = "87121")] pub use self::deref::DerefPure; - #[unstable(feature = "receiver_trait", issue = "none")] pub use self::deref::Receiver; - #[stable(feature = "rust1", since = "1.0.0")] -pub use self::drop::Drop; - +pub use self::deref::{Deref, DerefMut}; pub(crate) use self::drop::fallback_surface_drop; - +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::drop::Drop; #[stable(feature = "rust1", since = "1.0.0")] pub use self::function::{Fn, FnMut, FnOnce}; - -#[unstable(feature = "async_fn_traits", issue = "none")] -pub use self::async_function::{AsyncFn, AsyncFnMut, AsyncFnOnce}; - #[stable(feature = "rust1", since = "1.0.0")] pub use self::index::{Index, IndexMut}; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::range::{Range, RangeFrom, RangeFull, RangeTo}; - pub(crate) use self::index_range::IndexRange; - -#[stable(feature = "inclusive_range", since = "1.26.0")] -pub use self::range::{Bound, RangeBounds, RangeInclusive, RangeToInclusive}; - #[unstable(feature = "one_sided_range", issue = "69780")] pub use self::range::OneSidedRange; - -#[unstable(feature = "try_trait_v2", issue = "84277")] -pub use self::try_trait::{FromResidual, Try}; - -#[unstable(feature = "try_trait_v2_yeet", issue = "96374")] -pub use self::try_trait::Yeet; - +#[stable(feature = "inclusive_range", since = "1.26.0")] +pub use self::range::{Bound, RangeBounds, RangeInclusive, RangeToInclusive}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::range::{Range, RangeFrom, RangeFull, RangeTo}; #[unstable(feature = "try_trait_v2_residual", issue = "91285")] pub use self::try_trait::Residual; - +#[unstable(feature = "try_trait_v2_yeet", issue = "96374")] +pub use self::try_trait::Yeet; pub(crate) use self::try_trait::{ChangeOutputType, NeverShortCircuit}; - -#[unstable(feature = "coroutine_trait", issue = "43122")] -pub use self::coroutine::{Coroutine, CoroutineState}; - +#[unstable(feature = "try_trait_v2", issue = "84277")] +pub use self::try_trait::{FromResidual, Try}; #[unstable(feature = "coerce_unsized", issue = "18598")] pub use self::unsize::CoerceUnsized; - #[unstable(feature = "dispatch_from_dyn", issue = "none")] pub use self::unsize::DispatchFromDyn; - -#[unstable(feature = "control_flow_enum", reason = "new API", issue = "75744")] -pub use self::control_flow::ControlFlow; diff --git a/library/core/src/option.rs b/library/core/src/option.rs index d93cb8d10e607..6c89c81018038 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -557,13 +557,10 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::iter::{self, FusedIterator, TrustedLen}; +use crate::ops::{self, ControlFlow, Deref, DerefMut}; use crate::panicking::{panic, panic_display}; use crate::pin::Pin; -use crate::{ - cmp, convert, hint, mem, - ops::{self, ControlFlow, Deref, DerefMut}, - slice, -}; +use crate::{cmp, convert, hint, mem, slice}; /// The `Option` type. See [the module level documentation](self) for more. #[derive(Copy, Eq, Debug, Hash)] diff --git a/library/core/src/panic.rs b/library/core/src/panic.rs index 37c338dd9b778..6c5236ed99ce8 100644 --- a/library/core/src/panic.rs +++ b/library/core/src/panic.rs @@ -6,16 +6,15 @@ mod location; mod panic_info; mod unwind_safe; -use crate::any::Any; - #[stable(feature = "panic_hooks", since = "1.10.0")] pub use self::location::Location; #[stable(feature = "panic_hooks", since = "1.10.0")] pub use self::panic_info::PanicInfo; -#[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "panic_info_message", since = "1.81.0")] pub use self::panic_info::PanicMessage; #[stable(feature = "catch_unwind", since = "1.9.0")] pub use self::unwind_safe::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe}; +use crate::any::Any; #[doc(hidden)] #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")] @@ -160,7 +159,7 @@ pub unsafe trait PanicPayload: crate::fmt::Display { /// Just borrow the contents. fn get(&mut self) -> &(dyn Any + Send); - /// Try to borrow the contents as `&str`, if possible without doing any allocations. + /// Tries to borrow the contents as `&str`, if possible without doing any allocations. fn as_str(&mut self) -> Option<&str> { None } diff --git a/library/core/src/panic/panic_info.rs b/library/core/src/panic/panic_info.rs index 6bbb9c3017110..e4d0c897b65ca 100644 --- a/library/core/src/panic/panic_info.rs +++ b/library/core/src/panic/panic_info.rs @@ -24,7 +24,7 @@ pub struct PanicInfo<'a> { /// that were given to the `panic!()` macro. /// /// See [`PanicInfo::message`]. -#[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "panic_info_message", since = "1.81.0")] pub struct PanicMessage<'a> { message: fmt::Arguments<'a>, } @@ -57,7 +57,7 @@ impl<'a> PanicInfo<'a> { /// } /// ``` #[must_use] - #[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "panic_info_message", since = "1.81.0")] pub fn message(&self) -> PanicMessage<'_> { PanicMessage { message: self.message } } @@ -152,7 +152,7 @@ impl Display for PanicInfo<'_> { } impl<'a> PanicMessage<'a> { - /// Get the formatted message, if it has no arguments to be formatted at runtime. + /// Gets the formatted message, if it has no arguments to be formatted at runtime. /// /// This can be used to avoid allocations in some cases. /// @@ -164,7 +164,7 @@ impl<'a> PanicMessage<'a> { /// For most cases with placeholders, this function will return `None`. /// /// See [`fmt::Arguments::as_str`] for details. - #[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "panic_info_message", since = "1.81.0")] #[rustc_const_unstable(feature = "const_arguments_as_str", issue = "103900")] #[must_use] #[inline] @@ -173,7 +173,7 @@ impl<'a> PanicMessage<'a> { } } -#[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "panic_info_message", since = "1.81.0")] impl Display for PanicMessage<'_> { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -181,7 +181,7 @@ impl Display for PanicMessage<'_> { } } -#[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "panic_info_message", since = "1.81.0")] impl fmt::Debug for PanicMessage<'_> { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/library/core/src/panicking.rs b/library/core/src/panicking.rs index 97fb1d6b7323f..7affe63825719 100644 --- a/library/core/src/panicking.rs +++ b/library/core/src/panicking.rs @@ -294,10 +294,11 @@ fn panic_misaligned_pointer_dereference(required: usize, found: usize) -> ! { ) } -/// Panic because we cannot unwind out of a function. +/// Panics because we cannot unwind out of a function. /// /// This is a separate function to avoid the codesize impact of each crate containing the string to /// pass to `panic_nounwind`. +/// /// This function is called directly by the codegen backend, and must not have /// any extra arguments (including those synthesized by track_caller). #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] @@ -309,10 +310,11 @@ fn panic_cannot_unwind() -> ! { panic_nounwind("panic in a function that cannot unwind") } -/// Panic because we are unwinding out of a destructor during cleanup. +/// Panics because we are unwinding out of a destructor during cleanup. /// /// This is a separate function to avoid the codesize impact of each crate containing the string to /// pass to `panic_nounwind`. +/// /// This function is called directly by the codegen backend, and must not have /// any extra arguments (including those synthesized by track_caller). #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] diff --git a/library/core/src/pin.rs b/library/core/src/pin.rs index 0d2aa3070a19f..d752151d10cc8 100644 --- a/library/core/src/pin.rs +++ b/library/core/src/pin.rs @@ -421,7 +421,7 @@ //! } //! //! impl Unmovable { -//! /// Create a new `Unmovable`. +//! /// Creates a new `Unmovable`. //! /// //! /// To ensure the data doesn't move we place it on the heap behind a pinning Box. //! /// Note that the data is pinned, but the `Pin>` which is pinning it can @@ -920,11 +920,8 @@ #![stable(feature = "pin", since = "1.33.0")] -use crate::cmp; -use crate::fmt; use crate::hash::{Hash, Hasher}; use crate::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver}; - #[allow(unused_imports)] use crate::{ cell::{RefCell, UnsafeCell}, @@ -932,6 +929,7 @@ use crate::{ marker::PhantomPinned, mem, ptr, }; +use crate::{cmp, fmt}; /// A pointer which pins its pointee in place. /// @@ -1168,7 +1166,7 @@ impl> Hash for Pin { } impl> Pin { - /// Construct a new `Pin` around a pointer to some data of a type that + /// Constructs a new `Pin` around a pointer to some data of a type that /// implements [`Unpin`]. /// /// Unlike `Pin::new_unchecked`, this method is safe because the pointer @@ -1223,7 +1221,7 @@ impl> Pin { } impl Pin { - /// Construct a new `Pin` around a reference to some data of a type that + /// Constructs a new `Pin` around a reference to some data of a type that /// may or may not implement [`Unpin`]. /// /// If `pointer` dereferences to an [`Unpin`] type, [`Pin::new`] should be used @@ -1569,7 +1567,7 @@ impl<'a, T: ?Sized> Pin<&'a mut T> { self.__pointer } - /// Construct a new pin by mapping the interior value. + /// Constructs a new pin by mapping the interior value. /// /// For example, if you wanted to get a `Pin` of a field of something, /// you could use this to get access to that field in one line of code. @@ -1602,7 +1600,7 @@ impl<'a, T: ?Sized> Pin<&'a mut T> { } impl Pin<&'static T> { - /// Get a pinning reference from a `&'static` reference. + /// Gets a pinning reference from a `&'static` reference. /// /// This is safe because `T` is borrowed immutably for the `'static` lifetime, which /// never ends. @@ -1639,8 +1637,8 @@ impl<'a, Ptr: DerefMut> Pin<&'a mut Pin> { // // We need to ensure that two things hold for that to be the case: // - // 1) Once we give out a `Pin<&mut Ptr::Target>`, an `&mut Ptr::Target` will not be given out. - // 2) By giving out a `Pin<&mut Ptr::Target>`, we do not risk of violating + // 1) Once we give out a `Pin<&mut Ptr::Target>`, a `&mut Ptr::Target` will not be given out. + // 2) By giving out a `Pin<&mut Ptr::Target>`, we do not risk violating // `Pin<&mut Pin>` // // The existence of `Pin` is sufficient to guarantee #1: since we already have a @@ -1656,7 +1654,7 @@ impl<'a, Ptr: DerefMut> Pin<&'a mut Pin> { } impl Pin<&'static mut T> { - /// Get a pinning mutable reference from a static mutable reference. + /// Gets a pinning mutable reference from a static mutable reference. /// /// This is safe because `T` is borrowed for the `'static` lifetime, which /// never ends. diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 3e7933e9eec86..93bbd92593f2c 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -61,7 +61,7 @@ impl *const T { self as _ } - /// Use the pointer value in a new pointer of another type. + /// Uses the pointer value in a new pointer of another type. /// /// In case `meta` is a (fat) pointer to an unsized type, this operation /// will ignore the pointer part, whereas for (thin) pointers to sized diff --git a/library/core/src/ptr/metadata.rs b/library/core/src/ptr/metadata.rs index 06f205c0f2670..ccc9f8754f00c 100644 --- a/library/core/src/ptr/metadata.rs +++ b/library/core/src/ptr/metadata.rs @@ -2,8 +2,7 @@ use crate::fmt; use crate::hash::{Hash, Hasher}; -use crate::intrinsics::aggregate_raw_ptr; -use crate::intrinsics::ptr_metadata; +use crate::intrinsics::{aggregate_raw_ptr, ptr_metadata}; use crate::marker::Freeze; use crate::ptr::NonNull; @@ -81,7 +80,7 @@ pub trait Pointee { // NOTE: don’t stabilize this before trait aliases are stable in the language? pub trait Thin = Pointee; -/// Extract the metadata component of a pointer. +/// Extracts the metadata component of a pointer. /// /// Values of type `*mut T`, `&T`, or `&mut T` can be passed directly to this function /// as they implicitly coerce to `*const T`. diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index f2247e83ec5c5..25d8f4a0adbd9 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -196,9 +196,9 @@ //! * The **provenance** it has, defining the memory it has permission to access. //! Provenance can be absent, in which case the pointer does not have permission to access any memory. //! -//! Under Strict Provenance, a usize *cannot* accurately represent a pointer, and converting from -//! a pointer to a usize is generally an operation which *only* extracts the address. It is -//! therefore *impossible* to construct a valid pointer from a usize because there is no way +//! Under Strict Provenance, a `usize` *cannot* accurately represent a pointer, and converting from +//! a pointer to a `usize` is generally an operation which *only* extracts the address. It is +//! therefore *impossible* to construct a valid pointer from a `usize` because there is no way //! to restore the address-space and provenance. In other words, pointer-integer-pointer //! roundtrips are not possible (in the sense that the resulting pointer is not dereferenceable). //! @@ -234,16 +234,16 @@ //! //! Most code needs no changes to conform to strict provenance, as the only really concerning //! operation that *wasn't* obviously already Undefined Behaviour is casts from usize to a -//! pointer. For code which *does* cast a usize to a pointer, the scope of the change depends +//! pointer. For code which *does* cast a `usize` to a pointer, the scope of the change depends //! on exactly what you're doing. //! -//! In general, you just need to make sure that if you want to convert a usize address to a +//! In general, you just need to make sure that if you want to convert a `usize` address to a //! pointer and then use that pointer to read/write memory, you need to keep around a pointer //! that has sufficient provenance to perform that read/write itself. In this way all of your //! casts from an address to a pointer are essentially just applying offsets/indexing. //! //! This is generally trivial to do for simple cases like tagged pointers *as long as you -//! represent the tagged pointer as an actual pointer and not a usize*. For instance: +//! represent the tagged pointer as an actual pointer and not a `usize`*. For instance: //! //! ``` //! #![feature(strict_provenance)] @@ -409,13 +409,9 @@ #![allow(clippy::not_unsafe_ptr_arg_deref)] use crate::cmp::Ordering; -use crate::fmt; -use crate::hash; -use crate::intrinsics; use crate::marker::FnPtr; -use crate::ub_checks; - use crate::mem::{self, MaybeUninit}; +use crate::{fmt, hash, intrinsics, ub_checks}; mod alignment; #[unstable(feature = "ptr_alignment_type", issue = "102070")] @@ -423,12 +419,10 @@ pub use alignment::Alignment; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] -pub use crate::intrinsics::copy_nonoverlapping; - +pub use crate::intrinsics::copy; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] -pub use crate::intrinsics::copy; - +pub use crate::intrinsics::copy_nonoverlapping; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] pub use crate::intrinsics::write_bytes; @@ -606,7 +600,7 @@ pub const fn null_mut() -> *mut T { /// Without provenance, this pointer is not associated with any actual allocation. Such a /// no-provenance pointer may be used for zero-sized memory accesses (if suitably aligned), but /// non-zero-sized memory accesses with a no-provenance pointer are UB. No-provenance pointers are -/// little more than a usize address in disguise. +/// little more than a `usize` address in disguise. /// /// This is different from `addr as *const T`, which creates a pointer that picks up a previously /// exposed provenance. See [`with_exposed_provenance`] for more details on that operation. @@ -650,7 +644,7 @@ pub const fn dangling() -> *const T { /// Without provenance, this pointer is not associated with any actual allocation. Such a /// no-provenance pointer may be used for zero-sized memory accesses (if suitably aligned), but /// non-zero-sized memory accesses with a no-provenance pointer are UB. No-provenance pointers are -/// little more than a usize address in disguise. +/// little more than a `usize` address in disguise. /// /// This is different from `addr as *mut T`, which creates a pointer that picks up a previously /// exposed provenance. See [`with_exposed_provenance_mut`] for more details on that operation. @@ -687,7 +681,7 @@ pub const fn dangling_mut() -> *mut T { without_provenance_mut(mem::align_of::()) } -/// Convert an address back to a pointer, picking up a previously 'exposed' provenance. +/// Converts an address back to a pointer, picking up a previously 'exposed' provenance. /// /// This is a more rigorously specified alternative to `addr as *const T`. The provenance of the /// returned pointer is that of *any* pointer that was previously exposed by passing it to @@ -735,7 +729,7 @@ where addr as *const T } -/// Convert an address back to a mutable pointer, picking up a previously 'exposed' provenance. +/// Converts an address back to a mutable pointer, picking up a previously 'exposed' provenance. /// /// This is a more rigorously specified alternative to `addr as *mut T`. The provenance of the /// returned pointer is that of *any* pointer that was previously passed to @@ -775,10 +769,53 @@ where addr as *mut T } -/// Convert a reference to a raw pointer. +/// Converts a reference to a raw pointer. /// -/// This is equivalent to `r as *const T`, but is a bit safer since it will never silently change -/// type or mutability, in particular if the code is refactored. +/// For `r: &T`, `from_ref(r)` is equivalent to `r as *const T` (except for the caveat noted below), +/// but is a bit safer since it will never silently change type or mutability, in particular if the +/// code is refactored. +/// +/// The caller must ensure that the pointee outlives the pointer this function returns, or else it +/// will end up dangling. +/// +/// The caller must also ensure that the memory the pointer (non-transitively) points to is never +/// written to (except inside an `UnsafeCell`) using this pointer or any pointer derived from it. If +/// you need to mutate the pointee, use [`from_mut`]. Specifically, to turn a mutable reference `m: +/// &mut T` into `*const T`, prefer `from_mut(m).cast_const()` to obtain a pointer that can later be +/// used for mutation. +/// +/// ## Interaction with lifetime extension +/// +/// Note that this has subtle interactions with the rules for lifetime extension of temporaries in +/// tail expressions. This code is valid, albeit in a non-obvious way: +/// ```rust +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// // The temporary holding the return value of `foo` has its lifetime extended, +/// // because the surrounding expression involves no function call. +/// let p = &foo() as *const T; +/// unsafe { p.read() }; +/// ``` +/// Naively replacing the cast with `from_ref` is not valid: +/// ```rust,no_run +/// # use std::ptr; +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// // The temporary holding the return value of `foo` does *not* have its lifetime extended, +/// // because the surrounding expression involves no function call. +/// let p = ptr::from_ref(&foo()); +/// unsafe { p.read() }; // UB! Reading from a dangling pointer ⚠️ +/// ``` +/// The recommended way to write this code is to avoid relying on lifetime extension +/// when raw pointers are involved: +/// ```rust +/// # use std::ptr; +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// let x = foo(); +/// let p = ptr::from_ref(&x); +/// unsafe { p.read() }; +/// ``` #[inline(always)] #[must_use] #[stable(feature = "ptr_from_ref", since = "1.76.0")] @@ -789,10 +826,47 @@ pub const fn from_ref(r: &T) -> *const T { r } -/// Convert a mutable reference to a raw pointer. +/// Converts a mutable reference to a raw pointer. +/// +/// For `r: &mut T`, `from_mut(r)` is equivalent to `r as *mut T` (except for the caveat noted +/// below), but is a bit safer since it will never silently change type or mutability, in particular +/// if the code is refactored. +/// +/// The caller must ensure that the pointee outlives the pointer this function returns, or else it +/// will end up dangling. +/// +/// ## Interaction with lifetime extension /// -/// This is equivalent to `r as *mut T`, but is a bit safer since it will never silently change -/// type or mutability, in particular if the code is refactored. +/// Note that this has subtle interactions with the rules for lifetime extension of temporaries in +/// tail expressions. This code is valid, albeit in a non-obvious way: +/// ```rust +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// // The temporary holding the return value of `foo` has its lifetime extended, +/// // because the surrounding expression involves no function call. +/// let p = &mut foo() as *mut T; +/// unsafe { p.write(T::default()) }; +/// ``` +/// Naively replacing the cast with `from_mut` is not valid: +/// ```rust,no_run +/// # use std::ptr; +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// // The temporary holding the return value of `foo` does *not* have its lifetime extended, +/// // because the surrounding expression involves no function call. +/// let p = ptr::from_mut(&mut foo()); +/// unsafe { p.write(T::default()) }; // UB! Writing to a dangling pointer ⚠️ +/// ``` +/// The recommended way to write this code is to avoid relying on lifetime extension +/// when raw pointers are involved: +/// ```rust +/// # use std::ptr; +/// # type T = i32; +/// # fn foo() -> T { 42 } +/// let mut x = foo(); +/// let p = ptr::from_mut(&mut x); +/// unsafe { p.write(T::default()) }; +/// ``` #[inline(always)] #[must_use] #[stable(feature = "ptr_from_ref", since = "1.76.0")] @@ -1388,7 +1462,7 @@ pub const unsafe fn read(src: *const T) -> T { /// /// # Examples /// -/// Read a usize value from a byte buffer: +/// Read a `usize` value from a byte buffer: /// /// ``` /// use std::mem; @@ -1599,7 +1673,7 @@ pub const unsafe fn write(dst: *mut T, src: T) { /// /// # Examples /// -/// Write a usize value to a byte buffer: +/// Write a `usize` value to a byte buffer: /// /// ``` /// use std::mem; @@ -1934,7 +2008,7 @@ pub(crate) const unsafe fn align_offset(p: *const T, a: usize) -> usiz let y = cttz_nonzero(a); if x < y { x } else { y } }; - // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a usize. + // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a `usize`. let gcd = unsafe { unchecked_shl(1usize, gcdpow) }; // SAFETY: gcd is always greater or equal to 1. if addr & unsafe { unchecked_sub(gcd, 1) } == 0 { @@ -2133,7 +2207,7 @@ impl fmt::Debug for F { } } -/// Create a `const` raw pointer to a place, without creating an intermediate reference. +/// Creates a `const` raw pointer to a place, without creating an intermediate reference. /// /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned /// and points to initialized data. For cases where those requirements do not hold, @@ -2207,7 +2281,7 @@ pub macro addr_of($place:expr) { &raw const $place } -/// Create a `mut` raw pointer to a place, without creating an intermediate reference. +/// Creates a `mut` raw pointer to a place, without creating an intermediate reference. /// /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned /// and points to initialized data. For cases where those requirements do not hold, diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index 904d6c62dcf1e..bcf9b889182c7 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -60,7 +60,7 @@ impl *mut T { self as _ } - /// Use the pointer value in a new pointer of another type. + /// Uses the pointer value in a new pointer of another type. /// /// In case `meta` is a (fat) pointer to an unsized type, this operation /// will ignore the pointer part, whereas for (thin) pointers to sized diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index 796c85d0cacc7..4a716a7503964 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -1,15 +1,12 @@ use crate::cmp::Ordering; -use crate::fmt; -use crate::hash; -use crate::intrinsics; use crate::marker::Unsize; use crate::mem::{MaybeUninit, SizedTypeProperties}; use crate::num::NonZero; use crate::ops::{CoerceUnsized, DispatchFromDyn}; -use crate::ptr; use crate::ptr::Unique; use crate::slice::{self, SliceIndex}; use crate::ub_checks::assert_unsafe_precondition; +use crate::{fmt, hash, intrinsics, ptr}; /// `*mut T` but non-zero and [covariant]. /// diff --git a/library/core/src/range.rs b/library/core/src/range.rs index bfbbf123b1ca5..408972c267f1a 100644 --- a/library/core/src/range.rs +++ b/library/core/src/range.rs @@ -25,15 +25,13 @@ mod iter; pub mod legacy; #[doc(inline)] -pub use crate::ops::{Bound, OneSidedRange, RangeBounds, RangeFull, RangeTo, RangeToInclusive}; - +pub use iter::{IterRange, IterRangeFrom, IterRangeInclusive}; use Bound::{Excluded, Included, Unbounded}; #[doc(inline)] pub use crate::iter::Step; - #[doc(inline)] -pub use iter::{IterRange, IterRangeFrom, IterRangeInclusive}; +pub use crate::ops::{Bound, OneSidedRange, RangeBounds, RangeFull, RangeTo, RangeToInclusive}; /// A (half-open) range bounded inclusively below and exclusively above /// (`start..end` in a future edition). @@ -72,7 +70,7 @@ impl fmt::Debug for Range { } impl Range { - /// Create an iterator over the elements within this range. + /// Creates an iterator over the elements within this range. /// /// Shorthand for `.clone().into_iter()` /// @@ -292,7 +290,7 @@ impl> RangeInclusive { } impl RangeInclusive { - /// Create an iterator over the elements within this range. + /// Creates an iterator over the elements within this range. /// /// Shorthand for `.clone().into_iter()` /// @@ -408,7 +406,7 @@ impl fmt::Debug for RangeFrom { } impl RangeFrom { - /// Create an iterator over the elements within this range. + /// Creates an iterator over the elements within this range. /// /// Shorthand for `.clone().into_iter()` /// diff --git a/library/core/src/range/iter.rs b/library/core/src/range/iter.rs index 2b7db475ffb2c..4935280df60bc 100644 --- a/library/core/src/range/iter.rs +++ b/library/core/src/range/iter.rs @@ -1,9 +1,8 @@ -use crate::num::NonZero; -use crate::range::{legacy, Range, RangeFrom, RangeInclusive}; - use crate::iter::{ FusedIterator, Step, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, TrustedStep, }; +use crate::num::NonZero; +use crate::range::{legacy, Range, RangeFrom, RangeInclusive}; /// By-value [`Range`] iterator. #[unstable(feature = "new_range_api", issue = "125687")] diff --git a/library/core/src/slice/ascii.rs b/library/core/src/slice/ascii.rs index bf444d2f68af8..d1ea52fab6b87 100644 --- a/library/core/src/slice/ascii.rs +++ b/library/core/src/slice/ascii.rs @@ -1,12 +1,10 @@ //! Operations on ASCII `[u8]`. -use crate::ascii; -use crate::fmt::{self, Write}; -use crate::iter; -use crate::mem; -use crate::ops; use core::ascii::EscapeDefault; +use crate::fmt::{self, Write}; +use crate::{ascii, iter, mem, ops}; + #[cfg(not(test))] impl [u8] { /// Checks if all bytes in this slice are within the ASCII range. diff --git a/library/core/src/slice/cmp.rs b/library/core/src/slice/cmp.rs index 5bee4d551352e..d19d0eae16671 100644 --- a/library/core/src/slice/cmp.rs +++ b/library/core/src/slice/cmp.rs @@ -1,12 +1,10 @@ //! Comparison traits for `[T]`. +use super::{from_raw_parts, memchr}; use crate::cmp::{self, BytewiseEq, Ordering}; use crate::intrinsics::compare_bytes; use crate::mem; -use super::from_raw_parts; -use super::memchr; - #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq<[U]> for [T] where diff --git a/library/core/src/slice/index.rs b/library/core/src/slice/index.rs index 2624a44bb4bcb..de1492e82ce7d 100644 --- a/library/core/src/slice/index.rs +++ b/library/core/src/slice/index.rs @@ -1,9 +1,8 @@ //! Indexing implementations for `[T]`. use crate::intrinsics::const_eval_select; -use crate::ops; -use crate::range; use crate::ub_checks::assert_unsafe_precondition; +use crate::{ops, range}; #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index for [T] @@ -214,6 +213,7 @@ pub unsafe trait SliceIndex: private_slice_index::Sealed { /// Returns a pointer to the output at this location, without /// performing any bounds checking. + /// /// Calling this method with an out-of-bounds index or a dangling `slice` pointer /// is *[undefined behavior]* even if the resulting pointer is not used. /// @@ -223,6 +223,7 @@ pub unsafe trait SliceIndex: private_slice_index::Sealed { /// Returns a mutable pointer to the output at this location, without /// performing any bounds checking. + /// /// Calling this method with an out-of-bounds index or a dangling `slice` pointer /// is *[undefined behavior]* even if the resulting pointer is not used. /// @@ -802,13 +803,13 @@ unsafe impl SliceIndex<[T]> for ops::RangeToInclusive { } } -/// Performs bounds-checking of a range. +/// Performs bounds checking of a range. /// /// This method is similar to [`Index::index`] for slices, but it returns a /// [`Range`] equivalent to `range`. You can use this method to turn any range /// into `start` and `end` values. /// -/// `bounds` is the range of the slice to use for bounds-checking. It should +/// `bounds` is the range of the slice to use for bounds checking. It should /// be a [`RangeTo`] range that ends at the length of the slice. /// /// The returned [`Range`] is safe to pass to [`slice::get_unchecked`] and @@ -898,7 +899,7 @@ where ops::Range { start, end } } -/// Performs bounds-checking of a range without panicking. +/// Performs bounds checking of a range without panicking. /// /// This is a version of [`range()`] that returns [`None`] instead of panicking. /// @@ -951,7 +952,8 @@ where if start > end || end > len { None } else { Some(ops::Range { start, end }) } } -/// Convert pair of `ops::Bound`s into `ops::Range` without performing any bounds checking and (in debug) overflow checking +/// Converts a pair of `ops::Bound`s into `ops::Range` without performing any +/// bounds checking or (in debug) overflow checking. pub(crate) fn into_range_unchecked( len: usize, (start, end): (ops::Bound, ops::Bound), @@ -970,7 +972,7 @@ pub(crate) fn into_range_unchecked( start..end } -/// Convert pair of `ops::Bound`s into `ops::Range`. +/// Converts pair of `ops::Bound`s into `ops::Range`. /// Returns `None` on overflowing indices. pub(crate) fn into_range( len: usize, @@ -995,7 +997,7 @@ pub(crate) fn into_range( Some(start..end) } -/// Convert pair of `ops::Bound`s into `ops::Range`. +/// Converts pair of `ops::Bound`s into `ops::Range`. /// Panics on overflowing indices. pub(crate) fn into_slice_range( len: usize, diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index 504676ce187a8..62b170a87d445 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -3,8 +3,7 @@ #[macro_use] // import iterator! and forward_iterator! mod macros; -use crate::cmp; -use crate::fmt; +use super::{from_raw_parts, from_raw_parts_mut}; use crate::hint::assert_unchecked; use crate::iter::{ FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, UncheckedIterator, @@ -13,8 +12,7 @@ use crate::marker::PhantomData; use crate::mem::{self, SizedTypeProperties}; use crate::num::NonZero; use crate::ptr::{self, without_provenance, without_provenance_mut, NonNull}; - -use super::{from_raw_parts, from_raw_parts_mut}; +use crate::{cmp, fmt}; #[stable(feature = "boxed_slice_into_iter", since = "1.80.0")] impl !Iterator for [T] {} diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 6d3e625bef428..b1440214d795a 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -7,16 +7,13 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::cmp::Ordering::{self, Equal, Greater, Less}; -use crate::fmt; -use crate::hint; -use crate::intrinsics::{exact_div, unchecked_sub}; +use crate::intrinsics::{exact_div, select_unpredictable, unchecked_sub}; use crate::mem::{self, SizedTypeProperties}; use crate::num::NonZero; use crate::ops::{Bound, OneSidedRange, Range, RangeBounds}; -use crate::ptr; use crate::simd::{self, Simd}; -use crate::slice; use crate::ub_checks::assert_unsafe_precondition; +use crate::{fmt, hint, ptr, slice}; #[unstable( feature = "slice_internals", @@ -44,52 +41,38 @@ mod specialize; #[unstable(feature = "str_internals", issue = "none")] #[doc(hidden)] pub use ascii::is_ascii_simple; - +#[stable(feature = "inherent_ascii_escape", since = "1.60.0")] +pub use ascii::EscapeAscii; +#[stable(feature = "slice_get_slice", since = "1.28.0")] +pub use index::SliceIndex; +#[unstable(feature = "slice_range", issue = "76393")] +pub use index::{range, try_range}; +#[unstable(feature = "array_windows", issue = "75027")] +pub use iter::ArrayWindows; +#[unstable(feature = "array_chunks", issue = "74985")] +pub use iter::{ArrayChunks, ArrayChunksMut}; +#[stable(feature = "slice_group_by", since = "1.77.0")] +pub use iter::{ChunkBy, ChunkByMut}; #[stable(feature = "rust1", since = "1.0.0")] pub use iter::{Chunks, ChunksMut, Windows}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use iter::{Iter, IterMut}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut}; - -#[stable(feature = "slice_rsplit", since = "1.27.0")] -pub use iter::{RSplit, RSplitMut}; - #[stable(feature = "chunks_exact", since = "1.31.0")] pub use iter::{ChunksExact, ChunksExactMut}; - +#[stable(feature = "rust1", since = "1.0.0")] +pub use iter::{Iter, IterMut}; #[stable(feature = "rchunks", since = "1.31.0")] pub use iter::{RChunks, RChunksExact, RChunksExactMut, RChunksMut}; - -#[unstable(feature = "array_chunks", issue = "74985")] -pub use iter::{ArrayChunks, ArrayChunksMut}; - -#[unstable(feature = "array_windows", issue = "75027")] -pub use iter::ArrayWindows; - -#[stable(feature = "slice_group_by", since = "1.77.0")] -pub use iter::{ChunkBy, ChunkByMut}; - +#[stable(feature = "slice_rsplit", since = "1.27.0")] +pub use iter::{RSplit, RSplitMut}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use iter::{RSplitN, RSplitNMut, Split, SplitMut, SplitN, SplitNMut}; #[stable(feature = "split_inclusive", since = "1.51.0")] pub use iter::{SplitInclusive, SplitInclusiveMut}; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use raw::{from_raw_parts, from_raw_parts_mut}; - #[stable(feature = "from_ref", since = "1.28.0")] pub use raw::{from_mut, from_ref}; - #[unstable(feature = "slice_from_ptr_range", issue = "89792")] pub use raw::{from_mut_ptr_range, from_ptr_range}; - -#[stable(feature = "slice_get_slice", since = "1.28.0")] -pub use index::SliceIndex; - -#[unstable(feature = "slice_range", issue = "76393")] -pub use index::{range, try_range}; - -#[stable(feature = "inherent_ascii_escape", since = "1.60.0")] -pub use ascii::EscapeAscii; +#[stable(feature = "rust1", since = "1.0.0")] +pub use raw::{from_raw_parts, from_raw_parts_mut}; /// Calculates the direction and split point of a one-sided range. /// @@ -321,7 +304,7 @@ impl [T] { if let [.., last] = self { Some(last) } else { None } } - /// Return an array reference to the first `N` items in the slice. + /// Returns an array reference to the first `N` items in the slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -350,7 +333,7 @@ impl [T] { } } - /// Return a mutable array reference to the first `N` items in the slice. + /// Returns a mutable array reference to the first `N` items in the slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -381,7 +364,7 @@ impl [T] { } } - /// Return an array reference to the first `N` items in the slice and the remaining slice. + /// Returns an array reference to the first `N` items in the slice and the remaining slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -413,7 +396,7 @@ impl [T] { } } - /// Return a mutable array reference to the first `N` items in the slice and the remaining + /// Returns a mutable array reference to the first `N` items in the slice and the remaining /// slice. /// /// If the slice is not at least `N` in length, this will return `None`. @@ -451,7 +434,7 @@ impl [T] { } } - /// Return an array reference to the last `N` items in the slice and the remaining slice. + /// Returns an array reference to the last `N` items in the slice and the remaining slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -483,7 +466,7 @@ impl [T] { } } - /// Return a mutable array reference to the last `N` items in the slice and the remaining + /// Returns a mutable array reference to the last `N` items in the slice and the remaining /// slice. /// /// If the slice is not at least `N` in length, this will return `None`. @@ -521,7 +504,7 @@ impl [T] { } } - /// Return an array reference to the last `N` items in the slice. + /// Returns an array reference to the last `N` items in the slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -539,7 +522,7 @@ impl [T] { /// ``` #[inline] #[stable(feature = "slice_first_last_chunk", since = "1.77.0")] - #[rustc_const_stable(feature = "slice_first_last_chunk", since = "1.77.0")] + #[rustc_const_stable(feature = "const_slice_last_chunk", since = "1.80.0")] pub const fn last_chunk(&self) -> Option<&[T; N]> { if self.len() < N { None @@ -554,7 +537,7 @@ impl [T] { } } - /// Return a mutable array reference to the last `N` items in the slice. + /// Returns a mutable array reference to the last `N` items in the slice. /// /// If the slice is not at least `N` in length, this will return `None`. /// @@ -726,7 +709,7 @@ impl [T] { /// Returns a raw pointer to the slice's buffer. /// /// The caller must ensure that the slice outlives the pointer this - /// function returns, or else it will end up pointing to garbage. + /// function returns, or else it will end up dangling. /// /// The caller must also ensure that the memory the pointer (non-transitively) points to /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer @@ -761,7 +744,7 @@ impl [T] { /// Returns an unsafe mutable pointer to the slice's buffer. /// /// The caller must ensure that the slice outlives the pointer this - /// function returns, or else it will end up pointing to garbage. + /// function returns, or else it will end up dangling. /// /// Modifying the container referenced by this slice may cause its buffer /// to be reallocated, which would also make any pointers to it invalid. @@ -828,7 +811,7 @@ impl [T] { // - Both pointers are part of the same object, as pointing directly // past the object also counts. // - // - The size of the slice is never larger than isize::MAX bytes, as + // - The size of the slice is never larger than `isize::MAX` bytes, as // noted here: // - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447 // - https://doc.rust-lang.org/reference/behavior-considered-undefined.html @@ -839,7 +822,7 @@ impl [T] { // - There is no wrapping around involved, as slices do not wrap past // the end of the address space. // - // See the documentation of pointer::add. + // See the documentation of [`pointer::add`]. let end = unsafe { start.add(self.len()) }; start..end } @@ -2787,41 +2770,54 @@ impl [T] { where F: FnMut(&'a T) -> Ordering, { - // INVARIANTS: - // - 0 <= left <= left + size = right <= self.len() - // - f returns Less for everything in self[..left] - // - f returns Greater for everything in self[right..] let mut size = self.len(); - let mut left = 0; - let mut right = size; - while left < right { - let mid = left + size / 2; - - // SAFETY: the while condition means `size` is strictly positive, so - // `size/2 < size`. Thus `left + size/2 < left + size`, which - // coupled with the `left + size <= self.len()` invariant means - // we have `left + size/2 < self.len()`, and this is in-bounds. + if size == 0 { + return Err(0); + } + let mut base = 0usize; + + // This loop intentionally doesn't have an early exit if the comparison + // returns Equal. We want the number of loop iterations to depend *only* + // on the size of the input slice so that the CPU can reliably predict + // the loop count. + while size > 1 { + let half = size / 2; + let mid = base + half; + + // SAFETY: the call is made safe by the following inconstants: + // - `mid >= 0`: by definition + // - `mid < size`: `mid = size / 2 + size / 4 + size / 8 ...` let cmp = f(unsafe { self.get_unchecked(mid) }); - // This control flow produces conditional moves, which results in - // fewer branches and instructions than if/else or matching on - // cmp::Ordering. - // This is x86 asm for u8: https://rust.godbolt.org/z/698eYffTx. - left = if cmp == Less { mid + 1 } else { left }; - right = if cmp == Greater { mid } else { right }; - if cmp == Equal { - // SAFETY: same as the `get_unchecked` above - unsafe { hint::assert_unchecked(mid < self.len()) }; - return Ok(mid); - } - - size = right - left; + // Binary search interacts poorly with branch prediction, so force + // the compiler to use conditional moves if supported by the target + // architecture. + base = select_unpredictable(cmp == Greater, base, mid); + + // This is imprecise in the case where `size` is odd and the + // comparison returns Greater: the mid element still gets included + // by `size` even though it's known to be larger than the element + // being searched for. + // + // This is fine though: we gain more performance by keeping the + // loop iteration count invariant (and thus predictable) than we + // lose from considering one additional element. + size -= half; } - // SAFETY: directly true from the overall invariant. - // Note that this is `<=`, unlike the assume in the `Ok` path. - unsafe { hint::assert_unchecked(left <= self.len()) }; - Err(left) + // SAFETY: base is always in [0, size) because base <= mid. + let cmp = f(unsafe { self.get_unchecked(base) }); + if cmp == Equal { + // SAFETY: same as the `get_unchecked` above. + unsafe { hint::assert_unchecked(base < self.len()) }; + Ok(base) + } else { + let result = base + (cmp == Less) as usize; + // SAFETY: same as the `get_unchecked` above. + // Note that this is `<=`, unlike the assume in the `Ok` path. + unsafe { hint::assert_unchecked(result <= self.len()) }; + Err(result) + } } /// Binary searches this slice with a key extraction function. @@ -3021,7 +3017,7 @@ impl [T] { sort::unstable::sort(self, &mut |a, b| f(a).lt(&f(b))); } - /// Reorder the slice such that the element at `index` after the reordering is at its final + /// Reorders the slice such that the element at `index` after the reordering is at its final /// sorted position. /// /// This reordering has the additional property that any value at position `i < index` will be @@ -3082,7 +3078,7 @@ impl [T] { sort::select::partition_at_index(self, index, T::lt) } - /// Reorder the slice with a comparator function such that the element at `index` after the + /// Reorders the slice with a comparator function such that the element at `index` after the /// reordering is at its final sorted position. /// /// This reordering has the additional property that any value at position `i < index` will be @@ -3147,7 +3143,7 @@ impl [T] { sort::select::partition_at_index(self, index, |a: &T, b: &T| compare(a, b) == Less) } - /// Reorder the slice with a key extraction function such that the element at `index` after the + /// Reorders the slice with a key extraction function such that the element at `index` after the /// reordering is at its final sorted position. /// /// This reordering has the additional property that any value at position `i < index` will be @@ -3405,8 +3401,10 @@ impl [T] { /// Rotates the slice in-place such that the first `mid` elements of the /// slice move to the end while the last `self.len() - mid` elements move to - /// the front. After calling `rotate_left`, the element previously at index - /// `mid` will become the first element in the slice. + /// the front. + /// + /// After calling `rotate_left`, the element previously at index `mid` will + /// become the first element in the slice. /// /// # Panics /// @@ -3448,8 +3446,10 @@ impl [T] { /// Rotates the slice in-place such that the first `self.len() - k` /// elements of the slice move to the end while the last `k` elements move - /// to the front. After calling `rotate_right`, the element previously at - /// index `self.len() - k` will become the first element in the slice. + /// to the front. + /// + /// After calling `rotate_right`, the element previously at index + /// `self.len() - k` will become the first element in the slice. /// /// # Panics /// @@ -3819,7 +3819,7 @@ impl [T] { (us_len, ts_len) } - /// Transmute the slice to a slice of another type, ensuring alignment of the types is + /// Transmutes the slice to a slice of another type, ensuring alignment of the types is /// maintained. /// /// This method splits the slice into three distinct slices: prefix, correctly aligned middle @@ -3884,7 +3884,7 @@ impl [T] { } } - /// Transmute the mutable slice to a mutable slice of another type, ensuring alignment of the + /// Transmutes the mutable slice to a mutable slice of another type, ensuring alignment of the /// types is maintained. /// /// This method splits the slice into three distinct slices: prefix, correctly aligned middle @@ -3957,7 +3957,7 @@ impl [T] { } } - /// Split a slice into a prefix, a middle of aligned SIMD types, and a suffix. + /// Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix. /// /// This is a safe wrapper around [`slice::align_to`], so inherits the same /// guarantees as that method. @@ -4021,7 +4021,7 @@ impl [T] { unsafe { self.align_to() } } - /// Split a mutable slice into a mutable prefix, a middle of aligned SIMD types, + /// Splits a mutable slice into a mutable prefix, a middle of aligned SIMD types, /// and a mutable suffix. /// /// This is a safe wrapper around [`slice::align_to_mut`], so inherits the same @@ -4069,7 +4069,6 @@ impl [T] { /// # Examples /// /// ``` - /// #![feature(is_sorted)] /// let empty: [i32; 0] = []; /// /// assert!([1, 2, 2, 9].is_sorted()); @@ -4079,7 +4078,7 @@ impl [T] { /// assert!(![0.0, 1.0, f32::NAN].is_sorted()); /// ``` #[inline] - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn is_sorted(&self) -> bool where @@ -4096,8 +4095,6 @@ impl [T] { /// # Examples /// /// ``` - /// #![feature(is_sorted)] - /// /// assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b)); /// assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b)); /// @@ -4108,7 +4105,7 @@ impl [T] { /// assert!(empty.is_sorted_by(|a, b| false)); /// assert!(empty.is_sorted_by(|a, b| true)); /// ``` - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn is_sorted_by<'a, F>(&'a self, mut compare: F) -> bool where @@ -4128,13 +4125,11 @@ impl [T] { /// # Examples /// /// ``` - /// #![feature(is_sorted)] - /// /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len())); /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs())); /// ``` #[inline] - #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] + #[stable(feature = "is_sorted", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool where diff --git a/library/core/src/slice/raw.rs b/library/core/src/slice/raw.rs index 280aead270e76..85507eb8a7381 100644 --- a/library/core/src/slice/raw.rs +++ b/library/core/src/slice/raw.rs @@ -1,9 +1,7 @@ //! Free functions to create `&[T]` and `&mut [T]`. -use crate::array; use crate::ops::Range; -use crate::ptr; -use crate::ub_checks; +use crate::{array, ptr, ub_checks}; /// Forms a slice from a pointer and a length. /// diff --git a/library/core/src/slice/rotate.rs b/library/core/src/slice/rotate.rs index 1d7b86339799b..1e4865a7caad9 100644 --- a/library/core/src/slice/rotate.rs +++ b/library/core/src/slice/rotate.rs @@ -1,6 +1,5 @@ -use crate::cmp; use crate::mem::{self, MaybeUninit, SizedTypeProperties}; -use crate::ptr; +use crate::{cmp, ptr}; /// Rotates the range `[mid-left, mid+right)` such that the element at `mid` becomes the first /// element. Equivalently, rotates the range `left` elements to the left or `right` elements to the diff --git a/library/core/src/slice/sort/select.rs b/library/core/src/slice/sort/select.rs index 6212def30416b..f6529f23bcb3f 100644 --- a/library/core/src/slice/sort/select.rs +++ b/library/core/src/slice/sort/select.rs @@ -7,12 +7,11 @@ //! better performance than one would get using heapsort as fallback. use crate::mem::{self, SizedTypeProperties}; - use crate::slice::sort::shared::pivot::choose_pivot; use crate::slice::sort::shared::smallsort::insertion_sort_shift_left; use crate::slice::sort::unstable::quicksort::partition; -/// Reorder the slice such that the element at `index` is at its final sorted position. +/// Reorders the slice such that the element at `index` is at its final sorted position. pub(crate) fn partition_at_index( v: &mut [T], index: usize, diff --git a/library/core/src/slice/sort/shared/smallsort.rs b/library/core/src/slice/sort/shared/smallsort.rs index 5111ed8756bf1..5064c5a0ae55a 100644 --- a/library/core/src/slice/sort/shared/smallsort.rs +++ b/library/core/src/slice/sort/shared/smallsort.rs @@ -1,11 +1,8 @@ //! This module contains a variety of sort implementations that are optimized for small lengths. -use crate::intrinsics; use crate::mem::{self, ManuallyDrop, MaybeUninit}; -use crate::ptr; -use crate::slice; - use crate::slice::sort::shared::FreezeMarker; +use crate::{intrinsics, ptr, slice}; // It's important to differentiate between SMALL_SORT_THRESHOLD performance for // small slices and small-sort performance sorting small sub-slices as part of diff --git a/library/core/src/slice/sort/stable/drift.rs b/library/core/src/slice/sort/stable/drift.rs index 2d9c4ac9fcf7c..644e75a4581e9 100644 --- a/library/core/src/slice/sort/stable/drift.rs +++ b/library/core/src/slice/sort/stable/drift.rs @@ -1,14 +1,12 @@ //! This module contains the hybrid top-level loop combining bottom-up Mergesort with top-down //! Quicksort. -use crate::cmp; -use crate::intrinsics; use crate::mem::MaybeUninit; - use crate::slice::sort::shared::find_existing_run; use crate::slice::sort::shared::smallsort::StableSmallSortTypeImpl; use crate::slice::sort::stable::merge::merge; use crate::slice::sort::stable::quicksort::quicksort; +use crate::{cmp, intrinsics}; /// Sorts `v` based on comparison function `is_less`. If `eager_sort` is true, /// it will only do small-sorts and physical merges, ensuring O(N * log(N)) @@ -273,7 +271,7 @@ fn stable_quicksort bool>( } /// Compactly stores the length of a run, and whether or not it is sorted. This -/// can always fit in a usize because the maximum slice length is isize::MAX. +/// can always fit in a `usize` because the maximum slice length is [`isize::MAX`]. #[derive(Copy, Clone)] struct DriftsortRun(usize); diff --git a/library/core/src/slice/sort/stable/merge.rs b/library/core/src/slice/sort/stable/merge.rs index 6739e114b130a..0cb21740795b7 100644 --- a/library/core/src/slice/sort/stable/merge.rs +++ b/library/core/src/slice/sort/stable/merge.rs @@ -1,8 +1,7 @@ //! This module contains logic for performing a merge of two sorted sub-slices. -use crate::cmp; use crate::mem::MaybeUninit; -use crate::ptr; +use crate::{cmp, ptr}; /// Merges non-decreasing runs `v[..mid]` and `v[mid..]` using `scratch` as /// temporary storage, and stores the result into `v[..]`. diff --git a/library/core/src/slice/sort/stable/mod.rs b/library/core/src/slice/sort/stable/mod.rs index 18f7b2ac54af5..a383b0f589ccf 100644 --- a/library/core/src/slice/sort/stable/mod.rs +++ b/library/core/src/slice/sort/stable/mod.rs @@ -1,12 +1,10 @@ //! This module contains the entry points for `slice::sort`. -use crate::cmp; -use crate::intrinsics; use crate::mem::{self, MaybeUninit, SizedTypeProperties}; - use crate::slice::sort::shared::smallsort::{ insertion_sort_shift_left, StableSmallSortTypeImpl, SMALL_SORT_GENERAL_SCRATCH_LEN, }; +use crate::{cmp, intrinsics}; pub(crate) mod drift; pub(crate) mod merge; diff --git a/library/core/src/slice/sort/stable/quicksort.rs b/library/core/src/slice/sort/stable/quicksort.rs index 181fe603d2325..3319d67ab52fa 100644 --- a/library/core/src/slice/sort/stable/quicksort.rs +++ b/library/core/src/slice/sort/stable/quicksort.rs @@ -1,12 +1,10 @@ //! This module contains a stable quicksort and partition implementation. -use crate::intrinsics; use crate::mem::{self, ManuallyDrop, MaybeUninit}; -use crate::ptr; - use crate::slice::sort::shared::pivot::choose_pivot; use crate::slice::sort::shared::smallsort::StableSmallSortTypeImpl; use crate::slice::sort::shared::FreezeMarker; +use crate::{intrinsics, ptr}; /// Sorts `v` recursively using quicksort. /// @@ -196,7 +194,8 @@ struct PartitionState { impl PartitionState { /// # Safety - /// scan and scratch must point to valid disjoint buffers of length len. The + /// + /// `scan` and `scratch` must point to valid disjoint buffers of length `len`. The /// scan buffer must be initialized. unsafe fn new(scan: *const T, scratch: *mut T, len: usize) -> Self { // SAFETY: See function safety comment. @@ -208,6 +207,7 @@ impl PartitionState { /// branchless core of the partition. /// /// # Safety + /// /// This function may be called at most `len` times. If it is called exactly /// `len` times the scratch buffer then contains a copy of each element from /// the scan buffer exactly once - a permutation, and num_left <= len. diff --git a/library/core/src/slice/sort/unstable/heapsort.rs b/library/core/src/slice/sort/unstable/heapsort.rs index 559605ef4b6b3..27e2ad588ea09 100644 --- a/library/core/src/slice/sort/unstable/heapsort.rs +++ b/library/core/src/slice/sort/unstable/heapsort.rs @@ -1,7 +1,6 @@ //! This module contains a branchless heapsort as fallback for unstable quicksort. -use crate::intrinsics; -use crate::ptr; +use crate::{intrinsics, ptr}; /// Sorts `v` using heapsort, which guarantees *O*(*n* \* log(*n*)) worst-case. /// diff --git a/library/core/src/slice/sort/unstable/mod.rs b/library/core/src/slice/sort/unstable/mod.rs index 692c2d8f7c7ba..ed735e1ebfbc0 100644 --- a/library/core/src/slice/sort/unstable/mod.rs +++ b/library/core/src/slice/sort/unstable/mod.rs @@ -2,7 +2,6 @@ use crate::intrinsics; use crate::mem::SizedTypeProperties; - use crate::slice::sort::shared::find_existing_run; use crate::slice::sort::shared::smallsort::insertion_sort_shift_left; diff --git a/library/core/src/slice/sort/unstable/quicksort.rs b/library/core/src/slice/sort/unstable/quicksort.rs index 533b5b0eec767..cd53656e9b4b8 100644 --- a/library/core/src/slice/sort/unstable/quicksort.rs +++ b/library/core/src/slice/sort/unstable/quicksort.rs @@ -1,11 +1,9 @@ //! This module contains an unstable quicksort and two partition implementations. -use crate::intrinsics; use crate::mem::{self, ManuallyDrop}; -use crate::ptr; - use crate::slice::sort::shared::pivot::choose_pivot; use crate::slice::sort::shared::smallsort::UnstableSmallSortTypeImpl; +use crate::{intrinsics, ptr}; /// Sorts `v` recursively. /// diff --git a/library/core/src/str/converts.rs b/library/core/src/str/converts.rs index 397759bd5cae7..1956a04829d1d 100644 --- a/library/core/src/str/converts.rs +++ b/library/core/src/str/converts.rs @@ -1,9 +1,8 @@ //! Ways to create a `str` from bytes slice. -use crate::{mem, ptr}; - use super::validations::run_utf8_validation; use super::Utf8Error; +use crate::{mem, ptr}; /// Converts a slice of bytes to a string slice. /// @@ -206,7 +205,7 @@ pub const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str { unsafe { &mut *(v as *mut [u8] as *mut str) } } -/// Creates an `&str` from a pointer and a length. +/// Creates a `&str` from a pointer and a length. /// /// The pointed-to bytes must be valid UTF-8. /// If this might not be the case, use `str::from_utf8(slice::from_raw_parts(ptr, len))`, @@ -225,7 +224,7 @@ pub const unsafe fn from_raw_parts<'a>(ptr: *const u8, len: usize) -> &'a str { unsafe { &*ptr::from_raw_parts(ptr, len) } } -/// Creates an `&mut str` from a pointer and a length. +/// Creates a `&mut str` from a pointer and a length. /// /// The pointed-to bytes must be valid UTF-8. /// If this might not be the case, use `str::from_utf8_mut(slice::from_raw_parts_mut(ptr, len))`, diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 5845e3b5481ad..06f796f9f3ad8 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -1,23 +1,20 @@ //! Iterators for `str` methods. -use crate::char as char_mod; +use super::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher}; +use super::validations::{next_code_point, next_code_point_reverse}; +use super::{ + from_utf8_unchecked, BytesIsNotEmpty, CharEscapeDebugContinue, CharEscapeDefault, + CharEscapeUnicode, IsAsciiWhitespace, IsNotEmpty, IsWhitespace, LinesMap, UnsafeBytesToStr, +}; use crate::fmt::{self, Write}; -use crate::iter::{Chain, FlatMap, Flatten}; -use crate::iter::{Copied, Filter, FusedIterator, Map, TrustedLen}; -use crate::iter::{TrustedRandomAccess, TrustedRandomAccessNoCoerce}; +use crate::iter::{ + Chain, Copied, Filter, FlatMap, Flatten, FusedIterator, Map, TrustedLen, TrustedRandomAccess, + TrustedRandomAccessNoCoerce, +}; use crate::num::NonZero; use crate::ops::Try; -use crate::option; use crate::slice::{self, Split as SliceSplit}; - -use super::from_utf8_unchecked; -use super::pattern::Pattern; -use super::pattern::{DoubleEndedSearcher, ReverseSearcher, Searcher}; -use super::validations::{next_code_point, next_code_point_reverse}; -use super::LinesMap; -use super::{BytesIsNotEmpty, UnsafeBytesToStr}; -use super::{CharEscapeDebugContinue, CharEscapeDefault, CharEscapeUnicode}; -use super::{IsAsciiWhitespace, IsNotEmpty, IsWhitespace}; +use crate::{char as char_mod, option}; /// An iterator over the [`char`]s of a string slice. /// diff --git a/library/core/src/str/lossy.rs b/library/core/src/str/lossy.rs index 51a0777c2d613..3f31107acf050 100644 --- a/library/core/src/str/lossy.rs +++ b/library/core/src/str/lossy.rs @@ -1,10 +1,8 @@ -use crate::fmt; -use crate::fmt::Formatter; -use crate::fmt::Write; -use crate::iter::FusedIterator; - use super::from_utf8_unchecked; use super::validations::utf8_char_width; +use crate::fmt; +use crate::fmt::{Formatter, Write}; +use crate::iter::FusedIterator; impl [u8] { /// Creates an iterator over the contiguous valid UTF-8 ranges of this diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index 6cd029f743639..56517348dc7d2 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -13,74 +13,52 @@ mod iter; mod traits; mod validations; -use self::pattern::Pattern; -use self::pattern::{DoubleEndedSearcher, ReverseSearcher, Searcher}; - -use crate::ascii; +use self::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher}; use crate::char::{self, EscapeDebugExtArgs}; -use crate::mem; use crate::ops::Range; use crate::slice::{self, SliceIndex}; +use crate::{ascii, mem}; pub mod pattern; mod lossy; -#[stable(feature = "utf8_chunks", since = "1.79.0")] -pub use lossy::{Utf8Chunk, Utf8Chunks}; - +#[unstable(feature = "str_from_raw_parts", issue = "119206")] +pub use converts::{from_raw_parts, from_raw_parts_mut}; #[stable(feature = "rust1", since = "1.0.0")] pub use converts::{from_utf8, from_utf8_unchecked}; - #[stable(feature = "str_mut_extras", since = "1.20.0")] pub use converts::{from_utf8_mut, from_utf8_unchecked_mut}; - -#[unstable(feature = "str_from_raw_parts", issue = "119206")] -pub use converts::{from_raw_parts, from_raw_parts_mut}; - #[stable(feature = "rust1", since = "1.0.0")] pub use error::{ParseBoolError, Utf8Error}; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use traits::FromStr; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use iter::{Bytes, CharIndices, Chars, Lines, SplitWhitespace}; - +#[stable(feature = "encode_utf16", since = "1.8.0")] +pub use iter::EncodeUtf16; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] pub use iter::LinesAny; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use iter::{RSplit, RSplitTerminator, Split, SplitTerminator}; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use iter::{RSplitN, SplitN}; - -#[stable(feature = "str_matches", since = "1.2.0")] -pub use iter::{Matches, RMatches}; - -#[stable(feature = "str_match_indices", since = "1.5.0")] -pub use iter::{MatchIndices, RMatchIndices}; - -#[stable(feature = "encode_utf16", since = "1.8.0")] -pub use iter::EncodeUtf16; - -#[stable(feature = "str_escape", since = "1.34.0")] -pub use iter::{EscapeDebug, EscapeDefault, EscapeUnicode}; - #[stable(feature = "split_ascii_whitespace", since = "1.34.0")] pub use iter::SplitAsciiWhitespace; - #[stable(feature = "split_inclusive", since = "1.51.0")] pub use iter::SplitInclusive; - +#[stable(feature = "rust1", since = "1.0.0")] +pub use iter::{Bytes, CharIndices, Chars, Lines, SplitWhitespace}; +#[stable(feature = "str_escape", since = "1.34.0")] +pub use iter::{EscapeDebug, EscapeDefault, EscapeUnicode}; +#[stable(feature = "str_match_indices", since = "1.5.0")] +pub use iter::{MatchIndices, RMatchIndices}; +use iter::{MatchIndicesInternal, MatchesInternal, SplitInternal, SplitNInternal}; +#[stable(feature = "str_matches", since = "1.2.0")] +pub use iter::{Matches, RMatches}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use iter::{RSplit, RSplitTerminator, Split, SplitTerminator}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use iter::{RSplitN, SplitN}; +#[stable(feature = "utf8_chunks", since = "1.79.0")] +pub use lossy::{Utf8Chunk, Utf8Chunks}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use traits::FromStr; #[unstable(feature = "str_internals", issue = "none")] pub use validations::{next_code_point, utf8_char_width}; -use iter::MatchIndicesInternal; -use iter::SplitInternal; -use iter::{MatchesInternal, SplitNInternal}; - #[inline(never)] #[cold] #[track_caller] @@ -592,6 +570,7 @@ impl str { /// Creates a string slice from another string slice, bypassing safety /// checks. + /// /// This is generally not recommended, use with caution! For a safe /// alternative see [`str`] and [`IndexMut`]. /// @@ -623,7 +602,7 @@ impl str { unsafe { &mut *(begin..end).get_unchecked_mut(self) } } - /// Divide one string slice into two at an index. + /// Divides one string slice into two at an index. /// /// The argument, `mid`, should be a byte offset from the start of the /// string. It must also be on the boundary of a UTF-8 code point. @@ -662,7 +641,7 @@ impl str { } } - /// Divide one mutable string slice into two at an index. + /// Divides one mutable string slice into two at an index. /// /// The argument, `mid`, should be a byte offset from the start of the /// string. It must also be on the boundary of a UTF-8 code point. @@ -705,7 +684,7 @@ impl str { } } - /// Divide one string slice into two at an index. + /// Divides one string slice into two at an index. /// /// The argument, `mid`, should be a valid byte offset from the start of the /// string. It must also be on the boundary of a UTF-8 code point. The @@ -744,7 +723,7 @@ impl str { } } - /// Divide one mutable string slice into two at an index. + /// Divides one mutable string slice into two at an index. /// /// The argument, `mid`, should be a valid byte offset from the start of the /// string. It must also be on the boundary of a UTF-8 code point. The @@ -784,7 +763,7 @@ impl str { } } - /// Divide one string slice into two at an index. + /// Divides one string slice into two at an index. /// /// # Safety /// @@ -912,7 +891,7 @@ impl str { CharIndices { front_offset: 0, iter: self.chars() } } - /// An iterator over the bytes of a string slice. + /// Returns an iterator over the bytes of a string slice. /// /// As a string slice consists of a sequence of bytes, we can iterate /// through a string slice by byte. This method returns such an iterator. @@ -1038,7 +1017,7 @@ impl str { SplitAsciiWhitespace { inner } } - /// An iterator over the lines of a string, as string slices. + /// Returns an iterator over the lines of a string, as string slices. /// /// Lines are split at line endings that are either newlines (`\n`) or /// sequences of a carriage return followed by a line feed (`\r\n`). @@ -1089,7 +1068,7 @@ impl str { Lines(self.split_inclusive('\n').map(LinesMap)) } - /// An iterator over the lines of a string. + /// Returns an iterator over the lines of a string. #[stable(feature = "rust1", since = "1.0.0")] #[deprecated(since = "1.4.0", note = "use lines() instead now", suggestion = "lines")] #[inline] @@ -1303,7 +1282,7 @@ impl str { pat.into_searcher(self).next_match_back().map(|(i, _)| i) } - /// An iterator over substrings of this string slice, separated by + /// Returns an iterator over substrings of this string slice, separated by /// characters matched by a pattern. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a @@ -1428,10 +1407,11 @@ impl str { }) } - /// An iterator over substrings of this string slice, separated by - /// characters matched by a pattern. Differs from the iterator produced by - /// `split` in that `split_inclusive` leaves the matched part as the - /// terminator of the substring. + /// Returns an iterator over substrings of this string slice, separated by + /// characters matched by a pattern. + /// + /// Differs from the iterator produced by `split` in that `split_inclusive` + /// leaves the matched part as the terminator of the substring. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a /// function or closure that determines if a character matches. @@ -1468,8 +1448,8 @@ impl str { }) } - /// An iterator over substrings of the given string slice, separated by - /// characters matched by a pattern and yielded in reverse order. + /// Returns an iterator over substrings of the given string slice, separated + /// by characters matched by a pattern and yielded in reverse order. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a /// function or closure that determines if a character matches. @@ -1520,8 +1500,8 @@ impl str { RSplit(self.split(pat).0) } - /// An iterator over substrings of the given string slice, separated by - /// characters matched by a pattern. + /// Returns an iterator over substrings of the given string slice, separated + /// by characters matched by a pattern. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a /// function or closure that determines if a character matches. @@ -1566,7 +1546,7 @@ impl str { SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 }) } - /// An iterator over substrings of `self`, separated by characters + /// Returns an iterator over substrings of `self`, separated by characters /// matched by a pattern and yielded in reverse order. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a @@ -1615,8 +1595,8 @@ impl str { RSplitTerminator(self.split_terminator(pat).0) } - /// An iterator over substrings of the given string slice, separated by a - /// pattern, restricted to returning at most `n` items. + /// Returns an iterator over substrings of the given string slice, separated + /// by a pattern, restricted to returning at most `n` items. /// /// If `n` substrings are returned, the last substring (the `n`th substring) /// will contain the remainder of the string. @@ -1667,9 +1647,9 @@ impl str { SplitN(SplitNInternal { iter: self.split(pat).0, count: n }) } - /// An iterator over substrings of this string slice, separated by a - /// pattern, starting from the end of the string, restricted to returning - /// at most `n` items. + /// Returns an iterator over substrings of this string slice, separated by a + /// pattern, starting from the end of the string, restricted to returning at + /// most `n` items. /// /// If `n` substrings are returned, the last substring (the `n`th substring) /// will contain the remainder of the string. @@ -1759,8 +1739,8 @@ impl str { unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) } } - /// An iterator over the disjoint matches of a pattern within the given string - /// slice. + /// Returns an iterator over the disjoint matches of a pattern within the + /// given string slice. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a /// function or closure that determines if a character matches. @@ -1794,8 +1774,8 @@ impl str { Matches(MatchesInternal(pat.into_searcher(self))) } - /// An iterator over the disjoint matches of a pattern within this string slice, - /// yielded in reverse order. + /// Returns an iterator over the disjoint matches of a pattern within this + /// string slice, yielded in reverse order. /// /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a /// function or closure that determines if a character matches. @@ -1831,7 +1811,7 @@ impl str { RMatches(self.matches(pat).0) } - /// An iterator over the disjoint matches of a pattern within this string + /// Returns an iterator over the disjoint matches of a pattern within this string /// slice as well as the index that the match starts at. /// /// For matches of `pat` within `self` that overlap, only the indices @@ -1872,7 +1852,7 @@ impl str { MatchIndices(MatchIndicesInternal(pat.into_searcher(self))) } - /// An iterator over the disjoint matches of a pattern within `self`, + /// Returns an iterator over the disjoint matches of a pattern within `self`, /// yielded in reverse order along with the index of the match. /// /// For matches of `pat` within `self` that overlap, only the indices @@ -2597,7 +2577,7 @@ impl str { unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii()) } } - /// Return an iterator that escapes each char in `self` with [`char::escape_debug`]. + /// Returns an iterator that escapes each char in `self` with [`char::escape_debug`]. /// /// Note: only extended grapheme codepoints that begin the string will be /// escaped. @@ -2646,7 +2626,7 @@ impl str { } } - /// Return an iterator that escapes each char in `self` with [`char::escape_default`]. + /// Returns an iterator that escapes each char in `self` with [`char::escape_default`]. /// /// # Examples /// @@ -2684,7 +2664,7 @@ impl str { EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) } } - /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`]. + /// Returns an iterator that escapes each char in `self` with [`char::escape_unicode`]. /// /// # Examples /// diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index 33a5d45e445d7..2f1096db8f00c 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -38,11 +38,10 @@ issue = "27721" )] -use crate::cmp; use crate::cmp::Ordering; use crate::convert::TryInto as _; -use crate::fmt; use crate::slice::memchr; +use crate::{cmp, fmt}; // Pattern @@ -1759,8 +1758,7 @@ fn simd_contains(needle: &str, haystack: &str) -> Option { use crate::ops::BitAnd; use crate::simd::cmp::SimdPartialEq; - use crate::simd::mask8x16 as Mask; - use crate::simd::u8x16 as Block; + use crate::simd::{mask8x16 as Mask, u8x16 as Block}; let first_probe = needle[0]; let last_byte_offset = needle.len() - 1; diff --git a/library/core/src/str/traits.rs b/library/core/src/str/traits.rs index 3de5546c4d4e3..b69c476ae5e53 100644 --- a/library/core/src/str/traits.rs +++ b/library/core/src/str/traits.rs @@ -1,14 +1,11 @@ //! Trait implementations for `str`. +use super::ParseBoolError; use crate::cmp::Ordering; use crate::intrinsics::unchecked_sub; -use crate::ops; -use crate::ptr; -use crate::range; use crate::slice::SliceIndex; use crate::ub_checks::assert_unsafe_precondition; - -use super::ParseBoolError; +use crate::{ops, ptr, range}; /// Implements ordering of strings. /// diff --git a/library/core/src/str/validations.rs b/library/core/src/str/validations.rs index a11d7fee8af0c..cca8ff74dda8b 100644 --- a/library/core/src/str/validations.rs +++ b/library/core/src/str/validations.rs @@ -1,8 +1,7 @@ //! Operations related to UTF-8 validation. -use crate::mem; - use super::Utf8Error; +use crate::mem; /// Returns the initial codepoint accumulator for the first byte. /// The first byte is special, only want bottom 5 bits for width 2, 4 bits diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index efc07f38f68e0..495d9191a9f85 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -223,12 +223,9 @@ #![allow(clippy::not_unsafe_ptr_arg_deref)] use self::Ordering::*; - use crate::cell::UnsafeCell; -use crate::fmt; -use crate::intrinsics; - use crate::hint::spin_loop; +use crate::{fmt, intrinsics}; // Some architectures don't have byte-sized atomics, which results in LLVM // emulating them using a LL/SC loop. However for AtomicBool we can take @@ -481,7 +478,7 @@ impl AtomicBool { unsafe { &mut *(self.v.get() as *mut bool) } } - /// Get atomic access to a `&mut bool`. + /// Gets atomic access to a `&mut bool`. /// /// # Examples /// @@ -503,7 +500,7 @@ impl AtomicBool { unsafe { &mut *(v as *mut bool as *mut Self) } } - /// Get non-atomic access to a `&mut [AtomicBool]` slice. + /// Gets non-atomic access to a `&mut [AtomicBool]` slice. /// /// This is safe because the mutable reference guarantees that no other threads are /// concurrently accessing the atomic data. @@ -537,7 +534,7 @@ impl AtomicBool { unsafe { &mut *(this as *mut [Self] as *mut [bool]) } } - /// Get atomic access to a `&mut [bool]` slice. + /// Gets atomic access to a `&mut [bool]` slice. /// /// # Examples /// @@ -1080,7 +1077,7 @@ impl AtomicBool { /// assert_eq!(foo.load(Ordering::SeqCst), true); /// ``` #[inline] - #[stable(feature = "atomic_bool_fetch_not", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "atomic_bool_fetch_not", since = "1.81.0")] #[cfg(target_has_atomic = "8")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces pub fn fetch_not(&self, order: Ordering) -> bool { @@ -1276,7 +1273,7 @@ impl AtomicPtr { self.p.get_mut() } - /// Get atomic access to a pointer. + /// Gets atomic access to a pointer. /// /// # Examples /// @@ -1303,7 +1300,7 @@ impl AtomicPtr { unsafe { &mut *(v as *mut *mut T as *mut Self) } } - /// Get non-atomic access to a `&mut [AtomicPtr]` slice. + /// Gets non-atomic access to a `&mut [AtomicPtr]` slice. /// /// This is safe because the mutable reference guarantees that no other threads are /// concurrently accessing the atomic data. @@ -1343,7 +1340,7 @@ impl AtomicPtr { unsafe { &mut *(this as *mut [Self] as *mut [*mut T]) } } - /// Get atomic access to a slice of pointers. + /// Gets atomic access to a slice of pointers. /// /// # Examples /// diff --git a/library/core/src/sync/exclusive.rs b/library/core/src/sync/exclusive.rs index e8170c13ed263..fbf8dafad1869 100644 --- a/library/core/src/sync/exclusive.rs +++ b/library/core/src/sync/exclusive.rs @@ -114,7 +114,7 @@ impl Exclusive { } impl Exclusive { - /// Get exclusive access to the underlying value. + /// Gets exclusive access to the underlying value. #[unstable(feature = "exclusive_wrapper", issue = "98407")] #[must_use] #[inline] @@ -122,7 +122,7 @@ impl Exclusive { &mut self.inner } - /// Get pinned exclusive access to the underlying value. + /// Gets pinned exclusive access to the underlying value. /// /// `Exclusive` is considered to _structurally pin_ the underlying /// value, which means _unpinned_ `Exclusive`s can produce _unpinned_ diff --git a/library/core/src/task/wake.rs b/library/core/src/task/wake.rs index 86a965f68e085..8ce3eb2ea3921 100644 --- a/library/core/src/task/wake.rs +++ b/library/core/src/task/wake.rs @@ -1,12 +1,10 @@ #![stable(feature = "futures_api", since = "1.36.0")] -use crate::mem::transmute; - use crate::any::Any; -use crate::fmt; use crate::marker::PhantomData; +use crate::mem::{transmute, ManuallyDrop}; use crate::panic::AssertUnwindSafe; -use crate::ptr; +use crate::{fmt, ptr}; /// A `RawWaker` allows the implementor of a task executor to create a [`Waker`] /// or a [`LocalWaker`] which provides customized wakeup behavior. @@ -62,7 +60,7 @@ impl RawWaker { RawWaker { data, vtable } } - /// Get the `data` pointer used to create this `RawWaker`. + /// Gets the `data` pointer used to create this `RawWaker`. #[inline] #[must_use] #[unstable(feature = "waker_getters", issue = "96992")] @@ -70,7 +68,7 @@ impl RawWaker { self.data } - /// Get the `vtable` pointer used to create this `RawWaker`. + /// Gets the `vtable` pointer used to create this `RawWaker`. #[inline] #[must_use] #[unstable(feature = "waker_getters", issue = "96992")] @@ -151,7 +149,7 @@ pub struct RawWakerVTable { /// pointer. wake_by_ref: unsafe fn(*const ()), - /// This function gets called when a [`Waker`] gets dropped. + /// This function will be called when a [`Waker`] gets dropped. /// /// The implementation of this function must make sure to release any /// resources that are associated with this instance of a [`RawWaker`] and @@ -204,7 +202,8 @@ impl RawWakerVTable { /// /// # `drop` /// - /// This function gets called when a [`Waker`]/[`LocalWaker`] gets dropped. + /// This function will be called when a [`Waker`]/[`LocalWaker`] gets + /// dropped. /// /// The implementation of this function must make sure to release any /// resources that are associated with this instance of a [`RawWaker`] and @@ -249,9 +248,9 @@ pub struct Context<'a> { } impl<'a> Context<'a> { - /// Create a new `Context` from a [`&Waker`](Waker). + /// Creates a new `Context` from a [`&Waker`](Waker). #[stable(feature = "futures_api", since = "1.36.0")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_stable(feature = "const_waker", since = "CURRENT_RUSTC_VERSION")] #[must_use] #[inline] pub const fn from_waker(waker: &'a Waker) -> Self { @@ -262,7 +261,7 @@ impl<'a> Context<'a> { #[inline] #[must_use] #[stable(feature = "futures_api", since = "1.36.0")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_stable(feature = "const_waker", since = "CURRENT_RUSTC_VERSION")] pub const fn waker(&self) -> &'a Waker { &self.waker } @@ -270,7 +269,7 @@ impl<'a> Context<'a> { /// Returns a reference to the [`LocalWaker`] for the current task. #[inline] #[unstable(feature = "local_waker", issue = "118959")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "local_waker", issue = "118959")] pub const fn local_waker(&self) -> &'a LocalWaker { &self.local_waker } @@ -278,7 +277,7 @@ impl<'a> Context<'a> { /// Returns a reference to the extension data for the current task. #[inline] #[unstable(feature = "context_ext", issue = "123392")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "context_ext", issue = "123392")] pub const fn ext(&mut self) -> &mut dyn Any { // FIXME: this field makes Context extra-weird about unwind safety // can we justify AssertUnwindSafe if we stabilize this? do we care? @@ -335,10 +334,10 @@ pub struct ContextBuilder<'a> { } impl<'a> ContextBuilder<'a> { - /// Create a ContextBuilder from a Waker. + /// Creates a ContextBuilder from a Waker. #[inline] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] #[unstable(feature = "local_waker", issue = "118959")] + #[rustc_const_stable(feature = "const_waker", since = "CURRENT_RUSTC_VERSION")] pub const fn from_waker(waker: &'a Waker) -> Self { // SAFETY: LocalWaker is just Waker without thread safety let local_waker = unsafe { transmute(waker) }; @@ -351,10 +350,10 @@ impl<'a> ContextBuilder<'a> { } } - /// Create a ContextBuilder from an existing Context. + /// Creates a ContextBuilder from an existing Context. #[inline] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] #[unstable(feature = "context_ext", issue = "123392")] + #[rustc_const_unstable(feature = "context_ext", issue = "123392")] pub const fn from(cx: &'a mut Context<'_>) -> Self { let ext = match &mut cx.ext.0 { ExtData::Some(ext) => ExtData::Some(*ext), @@ -369,26 +368,26 @@ impl<'a> ContextBuilder<'a> { } } - /// This method is used to set the value for the waker on `Context`. + /// Sets the value for the waker on `Context`. #[inline] #[unstable(feature = "context_ext", issue = "123392")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "context_ext", issue = "123392")] pub const fn waker(self, waker: &'a Waker) -> Self { Self { waker, ..self } } - /// This method is used to set the value for the local waker on `Context`. + /// Sets the value for the local waker on `Context`. #[inline] #[unstable(feature = "local_waker", issue = "118959")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "local_waker", issue = "118959")] pub const fn local_waker(self, local_waker: &'a LocalWaker) -> Self { Self { local_waker, ..self } } - /// This method is used to set the value for the extension data on `Context`. + /// Sets the value for the extension data on `Context`. #[inline] #[unstable(feature = "context_ext", issue = "123392")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "context_ext", issue = "123392")] pub const fn ext(self, data: &'a mut dyn Any) -> Self { Self { ext: ExtData::Some(data), ..self } } @@ -396,7 +395,7 @@ impl<'a> ContextBuilder<'a> { /// Builds the `Context`. #[inline] #[unstable(feature = "local_waker", issue = "118959")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_stable(feature = "const_waker", since = "CURRENT_RUSTC_VERSION")] pub const fn build(self) -> Context<'a> { let ContextBuilder { waker, local_waker, ext, _marker, _marker2 } = self; Context { waker, local_waker, ext: AssertUnwindSafe(ext), _marker, _marker2 } @@ -429,7 +428,7 @@ impl<'a> ContextBuilder<'a> { /// [`Future::poll()`]: core::future::Future::poll /// [`Poll::Pending`]: core::task::Poll::Pending /// [`Wake`]: ../../alloc/task/trait.Wake.html -#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/66401 +#[repr(transparent)] #[stable(feature = "futures_api", since = "1.36.0")] pub struct Waker { waker: RawWaker, @@ -443,7 +442,7 @@ unsafe impl Send for Waker {} unsafe impl Sync for Waker {} impl Waker { - /// Wake up the task associated with this `Waker`. + /// Wakes up the task associated with this `Waker`. /// /// As long as the executor keeps running and the task is not finished, it is /// guaranteed that each invocation of [`wake()`](Self::wake) (or @@ -465,19 +464,17 @@ impl Waker { pub fn wake(self) { // The actual wakeup call is delegated through a virtual function call // to the implementation which is defined by the executor. - let wake = self.waker.vtable.wake; - let data = self.waker.data; // Don't call `drop` -- the waker will be consumed by `wake`. - crate::mem::forget(self); + let this = ManuallyDrop::new(self); // SAFETY: This is safe because `Waker::from_raw` is the only way // to initialize `wake` and `data` requiring the user to acknowledge // that the contract of `RawWaker` is upheld. - unsafe { (wake)(data) }; + unsafe { (this.waker.vtable.wake)(this.waker.data) }; } - /// Wake up the task associated with this `Waker` without consuming the `Waker`. + /// Wakes up the task associated with this `Waker` without consuming the `Waker`. /// /// This is similar to [`wake()`](Self::wake), but may be slightly less efficient in /// the case where an owned `Waker` is available. This method should be preferred to @@ -524,7 +521,7 @@ impl Waker { #[inline] #[must_use] #[stable(feature = "futures_api", since = "1.36.0")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_stable(feature = "const_waker", since = "CURRENT_RUSTC_VERSION")] pub const unsafe fn from_raw(waker: RawWaker) -> Waker { Waker { waker } } @@ -558,7 +555,7 @@ impl Waker { WAKER } - /// Get a reference to the underlying [`RawWaker`]. + /// Gets a reference to the underlying [`RawWaker`]. #[inline] #[must_use] #[unstable(feature = "waker_getters", issue = "96992")] @@ -695,7 +692,7 @@ impl fmt::Debug for Waker { /// [`Poll::Pending`]: core::task::Poll::Pending /// [`local_waker`]: core::task::Context::local_waker #[unstable(feature = "local_waker", issue = "118959")] -#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/66401 +#[repr(transparent)] pub struct LocalWaker { waker: RawWaker, } @@ -704,7 +701,7 @@ pub struct LocalWaker { impl Unpin for LocalWaker {} impl LocalWaker { - /// Wake up the task associated with this `LocalWaker`. + /// Wakes up the task associated with this `LocalWaker`. /// /// As long as the executor keeps running and the task is not finished, it is /// guaranteed that each invocation of [`wake()`](Self::wake) (or @@ -726,19 +723,17 @@ impl LocalWaker { pub fn wake(self) { // The actual wakeup call is delegated through a virtual function call // to the implementation which is defined by the executor. - let wake = self.waker.vtable.wake; - let data = self.waker.data; // Don't call `drop` -- the waker will be consumed by `wake`. - crate::mem::forget(self); + let this = ManuallyDrop::new(self); // SAFETY: This is safe because `Waker::from_raw` is the only way // to initialize `wake` and `data` requiring the user to acknowledge // that the contract of `RawWaker` is upheld. - unsafe { (wake)(data) }; + unsafe { (this.waker.vtable.wake)(this.waker.data) }; } - /// Wake up the task associated with this `LocalWaker` without consuming the `LocalWaker`. + /// Wakes up the task associated with this `LocalWaker` without consuming the `LocalWaker`. /// /// This is similar to [`wake()`](Self::wake), but may be slightly less efficient in /// the case where an owned `Waker` is available. This method should be preferred to @@ -777,7 +772,7 @@ impl LocalWaker { #[inline] #[must_use] #[unstable(feature = "local_waker", issue = "118959")] - #[rustc_const_unstable(feature = "const_waker", issue = "102012")] + #[rustc_const_unstable(feature = "local_waker", issue = "118959")] pub const unsafe fn from_raw(waker: RawWaker) -> LocalWaker { Self { waker } } @@ -812,7 +807,7 @@ impl LocalWaker { WAKER } - /// Get a reference to the underlying [`RawWaker`]. + /// Gets a reference to the underlying [`RawWaker`]. #[inline] #[must_use] #[unstable(feature = "waker_getters", issue = "96992")] diff --git a/library/core/src/time.rs b/library/core/src/time.rs index d66f558078ea8..0390bb59a8984 100644 --- a/library/core/src/time.rs +++ b/library/core/src/time.rs @@ -617,16 +617,14 @@ impl Duration { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// use std::time::Duration; /// /// assert_eq!(Duration::new(100, 0).abs_diff(Duration::new(80, 0)), Duration::new(20, 0)); /// assert_eq!(Duration::new(100, 400_000_000).abs_diff(Duration::new(110, 0)), Duration::new(9, 600_000_000)); /// ``` - #[stable(feature = "duration_abs_diff", since = "CURRENT_RUSTC_VERSION")] - #[rustc_const_stable(feature = "duration_abs_diff", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "duration_abs_diff", since = "1.81.0")] + #[rustc_const_stable(feature = "duration_abs_diff", since = "1.81.0")] #[rustc_allow_const_fn_unstable(const_option)] #[must_use = "this returns the result of the operation, \ without modifying the original"] @@ -640,8 +638,6 @@ impl Duration { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// use std::time::Duration; /// @@ -700,8 +696,6 @@ impl Duration { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// use std::time::Duration; /// @@ -758,8 +752,6 @@ impl Duration { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// use std::time::Duration; /// @@ -814,8 +806,6 @@ impl Duration { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// use std::time::Duration; /// @@ -1037,7 +1027,7 @@ impl Duration { Duration::from_secs_f32(rhs * self.as_secs_f32()) } - /// Divide `Duration` by `f64`. + /// Divides `Duration` by `f64`. /// /// # Panics /// This method will panic if result is negative, overflows `Duration` or not finite. @@ -1058,7 +1048,7 @@ impl Duration { Duration::from_secs_f64(self.as_secs_f64() / rhs) } - /// Divide `Duration` by `f32`. + /// Divides `Duration` by `f32`. /// /// # Panics /// This method will panic if result is negative, overflows `Duration` or not finite. @@ -1081,7 +1071,7 @@ impl Duration { Duration::from_secs_f32(self.as_secs_f32() / rhs) } - /// Divide `Duration` by `Duration` and return `f64`. + /// Divides `Duration` by `Duration` and returns `f64`. /// /// # Examples /// ``` @@ -1102,7 +1092,7 @@ impl Duration { self_nanos / rhs_nanos } - /// Divide `Duration` by `Duration` and return `f32`. + /// Divides `Duration` by `Duration` and returns `f32`. /// /// # Examples /// ``` diff --git a/library/core/src/tuple.rs b/library/core/src/tuple.rs index bc376b13f64d9..65d4d5cf2ce41 100644 --- a/library/core/src/tuple.rs +++ b/library/core/src/tuple.rs @@ -1,9 +1,7 @@ // See core/src/primitive_docs.rs for documentation. use crate::cmp::Ordering::{self, *}; -use crate::marker::ConstParamTy_; -use crate::marker::StructuralPartialEq; -use crate::marker::UnsizedConstParamTy; +use crate::marker::{ConstParamTy_, StructuralPartialEq, UnsizedConstParamTy}; // Recursive macro for implementing n-ary tuple functions and operations // diff --git a/library/core/src/ub_checks.rs b/library/core/src/ub_checks.rs index 1aa6a288e7082..b65b48c162d9c 100644 --- a/library/core/src/ub_checks.rs +++ b/library/core/src/ub_checks.rs @@ -3,9 +3,11 @@ use crate::intrinsics::{self, const_eval_select}; -/// Check that the preconditions of an unsafe function are followed. The check is enabled at -/// runtime if debug assertions are enabled when the caller is monomorphized. In const-eval/Miri -/// checks implemented with this macro for language UB are always ignored. +/// Checks that the preconditions of an unsafe function are followed. +/// +/// The check is enabled at runtime if debug assertions are enabled when the +/// caller is monomorphized. In const-eval/Miri checks implemented with this +/// macro for language UB are always ignored. /// /// This macro should be called as /// `assert_unsafe_precondition!(check_{library,lang}_ub, "message", (ident: type = expr, ident: type = expr) => check_expr)` @@ -79,7 +81,6 @@ macro_rules! assert_unsafe_precondition { } #[unstable(feature = "ub_checks", issue = "none")] pub use assert_unsafe_precondition; - /// Checking library UB is always enabled when UB-checking is done /// (and we use a reexport so that there is no unnecessary wrapper function). #[unstable(feature = "ub_checks", issue = "none")] diff --git a/library/core/src/unicode/mod.rs b/library/core/src/unicode/mod.rs index 5ddd9f7476dd8..6066aa9921607 100644 --- a/library/core/src/unicode/mod.rs +++ b/library/core/src/unicode/mod.rs @@ -1,13 +1,15 @@ #![unstable(feature = "unicode_internals", issue = "none")] #![allow(missing_docs)] -// The `pub use` ones are for use in alloc, and are not re-exported in std. - -pub(crate) use unicode_data::alphabetic::lookup as Alphabetic; +// for use in alloc, not re-exported in std. +#[rustfmt::skip] pub use unicode_data::case_ignorable::lookup as Case_Ignorable; pub use unicode_data::cased::lookup as Cased; -pub(crate) use unicode_data::cc::lookup as Cc; pub use unicode_data::conversions; + +#[rustfmt::skip] +pub(crate) use unicode_data::alphabetic::lookup as Alphabetic; +pub(crate) use unicode_data::cc::lookup as Cc; pub(crate) use unicode_data::grapheme_extend::lookup as Grapheme_Extend; pub(crate) use unicode_data::lowercase::lookup as Lowercase; pub(crate) use unicode_data::n::lookup as N; diff --git a/library/core/tests/array.rs b/library/core/tests/array.rs index e7773d138c255..b6d18f1ec3822 100644 --- a/library/core/tests/array.rs +++ b/library/core/tests/array.rs @@ -259,7 +259,8 @@ fn iterator_drops() { #[test] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn array_default_impl_avoids_leaks_on_panic() { - use core::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + use core::sync::atomic::AtomicUsize; + use core::sync::atomic::Ordering::Relaxed; static COUNTER: AtomicUsize = AtomicUsize::new(0); #[derive(Debug)] struct Bomb(#[allow(dead_code)] usize); diff --git a/library/core/tests/clone.rs b/library/core/tests/clone.rs index 23efab2f1b598..b7130f16f8795 100644 --- a/library/core/tests/clone.rs +++ b/library/core/tests/clone.rs @@ -36,7 +36,8 @@ fn test_clone_to_uninit_slice_success() { #[test] #[cfg(panic = "unwind")] fn test_clone_to_uninit_slice_drops_on_panic() { - use core::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + use core::sync::atomic::AtomicUsize; + use core::sync::atomic::Ordering::Relaxed; /// A static counter is OK to use as long as _this one test_ isn't run several times in /// multiple threads. diff --git a/library/core/tests/cmp.rs b/library/core/tests/cmp.rs index 72fdd490da152..6c4e2146f9148 100644 --- a/library/core/tests/cmp.rs +++ b/library/core/tests/cmp.rs @@ -1,7 +1,5 @@ -use core::cmp::{ - self, - Ordering::{self, *}, -}; +use core::cmp::Ordering::{self, *}; +use core::cmp::{self}; #[test] fn test_int_totalord() { diff --git a/library/core/tests/ffi.rs b/library/core/tests/ffi.rs new file mode 100644 index 0000000000000..2b33fbd95f073 --- /dev/null +++ b/library/core/tests/ffi.rs @@ -0,0 +1 @@ +mod cstr; diff --git a/library/core/tests/ffi/cstr.rs b/library/core/tests/ffi/cstr.rs new file mode 100644 index 0000000000000..9bf4c21a9ab97 --- /dev/null +++ b/library/core/tests/ffi/cstr.rs @@ -0,0 +1,15 @@ +use core::ffi::CStr; + +#[test] +fn compares_as_u8s() { + let a: &CStr = c"Hello!"; // Starts with ascii + let a_bytes: &[u8] = a.to_bytes(); + assert!((..0b1000_0000).contains(&a_bytes[0])); + + let b: &CStr = c"こんにちは!"; // Starts with non ascii + let b_bytes: &[u8] = b.to_bytes(); + assert!((0b1000_0000..).contains(&b_bytes[0])); + + assert_eq!(Ord::cmp(a, b), Ord::cmp(a_bytes, b_bytes)); + assert_eq!(PartialOrd::partial_cmp(a, b), PartialOrd::partial_cmp(a_bytes, b_bytes)); +} diff --git a/library/core/tests/hash/sip.rs b/library/core/tests/hash/sip.rs index 0a67c485c98bb..f79954f916b77 100644 --- a/library/core/tests/hash/sip.rs +++ b/library/core/tests/hash/sip.rs @@ -1,7 +1,6 @@ #![allow(deprecated)] -use core::hash::{Hash, Hasher}; -use core::hash::{SipHasher, SipHasher13}; +use core::hash::{Hash, Hasher, SipHasher, SipHasher13}; use core::{mem, slice}; // Hash just the bytes of the slice, without length prefix diff --git a/library/core/tests/iter/adapters/chain.rs b/library/core/tests/iter/adapters/chain.rs index c93510df524cf..1b2c026ee1eb4 100644 --- a/library/core/tests/iter/adapters/chain.rs +++ b/library/core/tests/iter/adapters/chain.rs @@ -1,7 +1,8 @@ -use super::*; use core::iter::*; use core::num::NonZero; +use super::*; + #[test] fn test_chain() { let xs = [0, 1, 2, 3, 4, 5]; diff --git a/library/core/tests/iter/adapters/flatten.rs b/library/core/tests/iter/adapters/flatten.rs index 1f953f2aa0110..66b7b6cb563e9 100644 --- a/library/core/tests/iter/adapters/flatten.rs +++ b/library/core/tests/iter/adapters/flatten.rs @@ -1,8 +1,9 @@ -use super::*; use core::assert_eq; use core::iter::*; use core::num::NonZero; +use super::*; + #[test] fn test_iterator_flatten() { let xs = [0, 3, 6]; diff --git a/library/core/tests/iter/adapters/map_windows.rs b/library/core/tests/iter/adapters/map_windows.rs index 6744eff3fa26f..01cebc9b27fd8 100644 --- a/library/core/tests/iter/adapters/map_windows.rs +++ b/library/core/tests/iter/adapters/map_windows.rs @@ -1,10 +1,12 @@ -use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering::SeqCst; #[cfg(not(panic = "abort"))] mod drop_checks { //! These tests mainly make sure the elements are correctly dropped. - use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}; + use std::sync::atomic::Ordering::SeqCst; + use std::sync::atomic::{AtomicBool, AtomicUsize}; #[derive(Debug)] struct DropInfo { diff --git a/library/core/tests/iter/adapters/peekable.rs b/library/core/tests/iter/adapters/peekable.rs index c1a1c29b609b7..7f4341b8902c8 100644 --- a/library/core/tests/iter/adapters/peekable.rs +++ b/library/core/tests/iter/adapters/peekable.rs @@ -1,6 +1,7 @@ -use super::*; use core::iter::*; +use super::*; + #[test] fn test_iterator_peekable() { let xs = vec![0, 1, 2, 3, 4, 5]; diff --git a/library/core/tests/iter/adapters/zip.rs b/library/core/tests/iter/adapters/zip.rs index ba54de5822bf7..94b49bac45337 100644 --- a/library/core/tests/iter/adapters/zip.rs +++ b/library/core/tests/iter/adapters/zip.rs @@ -1,6 +1,7 @@ -use super::*; use core::iter::*; +use super::*; + #[test] fn test_zip_nth() { let xs = [0, 1, 2, 4, 5]; @@ -239,8 +240,7 @@ fn test_zip_trusted_random_access_composition() { #[test] #[cfg(panic = "unwind")] fn test_zip_trusted_random_access_next_back_drop() { - use std::panic::catch_unwind; - use std::panic::AssertUnwindSafe; + use std::panic::{catch_unwind, AssertUnwindSafe}; let mut counter = 0; diff --git a/library/core/tests/iter/range.rs b/library/core/tests/iter/range.rs index e31db0732e094..d5d2b8bf2b047 100644 --- a/library/core/tests/iter/range.rs +++ b/library/core/tests/iter/range.rs @@ -1,7 +1,8 @@ -use super::*; use core::ascii::Char as AsciiChar; use core::num::NonZero; +use super::*; + #[test] fn test_range() { assert_eq!((0..5).collect::>(), [0, 1, 2, 3, 4]); diff --git a/library/core/tests/iter/sources.rs b/library/core/tests/iter/sources.rs index a15f3a5148f0a..eb8c80dd08724 100644 --- a/library/core/tests/iter/sources.rs +++ b/library/core/tests/iter/sources.rs @@ -1,6 +1,7 @@ -use super::*; use core::iter::*; +use super::*; + #[test] fn test_repeat() { let mut it = repeat(42); diff --git a/library/core/tests/lazy.rs b/library/core/tests/lazy.rs index 7f7f1f0058801..a3b89f15b3f81 100644 --- a/library/core/tests/lazy.rs +++ b/library/core/tests/lazy.rs @@ -1,7 +1,6 @@ -use core::{ - cell::{Cell, LazyCell, OnceCell}, - sync::atomic::{AtomicUsize, Ordering::SeqCst}, -}; +use core::cell::{Cell, LazyCell, OnceCell}; +use core::sync::atomic::AtomicUsize; +use core::sync::atomic::Ordering::SeqCst; #[test] fn once_cell() { diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index 83a615fcd8be3..1e336bf96b8fa 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -1,6 +1,11 @@ +// tidy-alphabetical-start +#![cfg_attr(bootstrap, feature(offset_of_nested))] +#![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] +#![cfg_attr(test, feature(cfg_match))] #![feature(alloc_layout_extra)] #![feature(array_chunks)] #![feature(array_ptr_get)] +#![feature(array_try_from_fn)] #![feature(array_windows)] #![feature(ascii_char)] #![feature(ascii_char_variants)] @@ -9,114 +14,109 @@ #![feature(bigint_helper_methods)] #![feature(cell_update)] #![feature(clone_to_uninit)] -#![feature(const_align_offset)] #![feature(const_align_of_val_raw)] +#![feature(const_align_offset)] +#![feature(const_array_from_ref)] #![feature(const_black_box)] #![feature(const_cell_into_inner)] #![feature(const_hash)] #![feature(const_heap)] #![feature(const_intrinsic_copy)] -#![feature(const_int_from_str)] +#![feature(const_ip)] +#![feature(const_ipv4)] +#![feature(const_ipv6)] +#![feature(const_likely)] #![feature(const_maybe_uninit_as_mut_ptr)] +#![feature(const_mut_refs)] #![feature(const_nonnull_new)] +#![feature(const_option)] +#![feature(const_option_ext)] +#![feature(const_pin)] #![feature(const_pointer_is_aligned)] #![feature(const_ptr_as_ref)] #![feature(const_ptr_write)] +#![feature(const_result)] +#![feature(const_slice_from_ref)] #![feature(const_three_way_compare)] #![feature(const_trait_impl)] -#![feature(const_likely)] #![feature(core_intrinsics)] #![feature(core_io_borrowed_buf)] #![feature(core_private_bignum)] #![feature(core_private_diy_float)] #![feature(dec2flt)] -#![feature(duration_consts_float)] #![feature(duration_constants)] #![feature(duration_constructors)] +#![feature(duration_consts_float)] +#![feature(error_generic_member_access)] #![feature(exact_size_is_empty)] #![feature(extern_types)] -#![feature(freeze)] +#![feature(float_minimum_maximum)] #![feature(flt2dec)] #![feature(fmt_internals)] -#![feature(float_minimum_maximum)] +#![feature(freeze)] #![feature(future_join)] #![feature(generic_assert_internals)] -#![feature(array_try_from_fn)] +#![feature(get_many_mut)] #![feature(hasher_prefixfree_extras)] #![feature(hashmap_internals)] -#![feature(try_find)] -#![feature(is_sorted)] -#![feature(layout_for_ptr)] -#![feature(pattern)] -#![feature(slice_take)] -#![feature(slice_from_ptr_range)] -#![feature(slice_split_once)] -#![feature(split_as_slice)] -#![feature(maybe_uninit_fill)] -#![feature(maybe_uninit_write_slice)] -#![feature(maybe_uninit_uninit_array_transpose)] -#![feature(min_specialization)] -#![feature(noop_waker)] -#![feature(numfmt)] -#![feature(num_midpoint)] -#![feature(offset_of_nested)] -#![feature(isqrt)] -#![feature(step_trait)] -#![feature(str_internals)] -#![feature(std_internals)] -#![feature(test)] -#![feature(trusted_len)] -#![feature(try_blocks)] -#![feature(try_trait_v2)] -#![feature(slice_internals)] -#![feature(slice_partition_dedup)] +#![feature(int_roundings)] #![feature(ip)] +#![feature(is_ascii_octdigit)] +#![feature(isqrt)] #![feature(iter_advance_by)] #![feature(iter_array_chunks)] #![feature(iter_chain)] #![feature(iter_collect_into)] -#![feature(iter_partition_in_place)] #![feature(iter_intersperse)] #![feature(iter_is_partitioned)] +#![feature(iter_map_windows)] #![feature(iter_next_chunk)] #![feature(iter_order_by)] +#![feature(iter_partition_in_place)] #![feature(iter_repeat_n)] #![feature(iterator_try_collect)] #![feature(iterator_try_reduce)] -#![feature(const_ip)] -#![feature(const_ipv4)] -#![feature(const_ipv6)] -#![feature(const_mut_refs)] -#![feature(const_pin)] -#![feature(const_waker)] +#![feature(layout_for_ptr)] +#![feature(maybe_uninit_fill)] +#![feature(maybe_uninit_uninit_array_transpose)] +#![feature(maybe_uninit_write_slice)] +#![feature(min_specialization)] #![feature(never_type)] -#![feature(unwrap_infallible)] +#![feature(noop_waker)] +#![feature(num_midpoint)] +#![feature(numfmt)] +#![feature(pattern)] #![feature(pointer_is_aligned_to)] #![feature(portable_simd)] #![feature(ptr_metadata)] -#![feature(unsized_tuple_coercion)] -#![feature(const_option)] -#![feature(const_option_ext)] -#![feature(const_result)] -#![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] -#![cfg_attr(test, feature(cfg_match))] -#![feature(int_roundings)] +#![feature(slice_from_ptr_range)] +#![feature(slice_internals)] +#![feature(slice_partition_dedup)] +#![feature(slice_split_once)] +#![feature(slice_take)] #![feature(split_array)] +#![feature(split_as_slice)] +#![feature(std_internals)] +#![feature(step_trait)] +#![feature(str_internals)] #![feature(strict_provenance)] #![feature(strict_provenance_atomic_ptr)] +#![feature(test)] +#![feature(trait_upcasting)] +#![feature(trusted_len)] #![feature(trusted_random_access)] +#![feature(try_blocks)] +#![feature(try_find)] +#![feature(try_trait_v2)] +#![feature(unsigned_is_multiple_of)] #![feature(unsize)] -#![feature(const_array_from_ref)] -#![feature(const_slice_from_ref)] +#![feature(unsized_tuple_coercion)] +#![feature(unwrap_infallible)] #![feature(waker_getters)] -#![feature(error_generic_member_access)] -#![feature(trait_upcasting)] -#![feature(is_ascii_octdigit)] -#![feature(get_many_mut)] -#![feature(iter_map_windows)] +// tidy-alphabetical-end #![allow(internal_features)] -#![deny(unsafe_op_in_unsafe_fn)] #![deny(fuzzy_provenance_casts)] +#![deny(unsafe_op_in_unsafe_fn)] mod alloc; mod any; @@ -132,6 +132,7 @@ mod clone; mod cmp; mod const_ptr; mod convert; +mod ffi; mod fmt; mod future; mod hash; diff --git a/library/core/tests/mem.rs b/library/core/tests/mem.rs index cc73391630760..b7eee10ec3f9c 100644 --- a/library/core/tests/mem.rs +++ b/library/core/tests/mem.rs @@ -1,6 +1,5 @@ use core::mem::*; use core::ptr; - #[cfg(panic = "unwind")] use std::rc::Rc; diff --git a/library/core/tests/net/ip_addr.rs b/library/core/tests/net/ip_addr.rs index f9b351ef1980b..a10b51c550d5b 100644 --- a/library/core/tests/net/ip_addr.rs +++ b/library/core/tests/net/ip_addr.rs @@ -1,9 +1,10 @@ -use super::{sa4, sa6}; use core::net::{ IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope, SocketAddr, SocketAddrV4, SocketAddrV6, }; use core::str::FromStr; +use super::{sa4, sa6}; + #[test] fn test_from_str_ipv4() { assert_eq!(Ok(Ipv4Addr::new(127, 0, 0, 1)), "127.0.0.1".parse()); diff --git a/library/core/tests/num/flt2dec/mod.rs b/library/core/tests/num/flt2dec/mod.rs index 83e2707b57e8b..070a53edc2e0f 100644 --- a/library/core/tests/num/flt2dec/mod.rs +++ b/library/core/tests/num/flt2dec/mod.rs @@ -1,12 +1,10 @@ -use std::mem::MaybeUninit; -use std::{fmt, str}; - -use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded}; -use core::num::flt2dec::{round_up, Sign, MAX_SIG_DIGITS}; use core::num::flt2dec::{ - to_exact_exp_str, to_exact_fixed_str, to_shortest_exp_str, to_shortest_str, + decode, round_up, to_exact_exp_str, to_exact_fixed_str, to_shortest_exp_str, to_shortest_str, + DecodableFloat, Decoded, FullDecoded, Sign, MAX_SIG_DIGITS, }; use core::num::fmt::{Formatted, Part}; +use std::mem::MaybeUninit; +use std::{fmt, str}; mod estimator; mod strategy { diff --git a/library/core/tests/num/flt2dec/random.rs b/library/core/tests/num/flt2dec/random.rs index 0084c1c814e2d..4817a66638391 100644 --- a/library/core/tests/num/flt2dec/random.rs +++ b/library/core/tests/num/flt2dec/random.rs @@ -1,13 +1,10 @@ #![cfg(not(target_arch = "wasm32"))] +use core::num::flt2dec::strategy::grisu::{format_exact_opt, format_shortest_opt}; +use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded, MAX_SIG_DIGITS}; use std::mem::MaybeUninit; use std::str; -use core::num::flt2dec::strategy::grisu::format_exact_opt; -use core::num::flt2dec::strategy::grisu::format_shortest_opt; -use core::num::flt2dec::MAX_SIG_DIGITS; -use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded}; - use rand::distributions::{Distribution, Uniform}; pub fn decode_finite(v: T) -> Decoded { diff --git a/library/core/tests/num/flt2dec/strategy/dragon.rs b/library/core/tests/num/flt2dec/strategy/dragon.rs index fc2e724a20c7c..be25fee3f6c71 100644 --- a/library/core/tests/num/flt2dec/strategy/dragon.rs +++ b/library/core/tests/num/flt2dec/strategy/dragon.rs @@ -1,7 +1,8 @@ -use super::super::*; use core::num::bignum::Big32x40 as Big; use core::num::flt2dec::strategy::dragon::*; +use super::super::*; + #[test] fn test_mul_pow10() { let mut prevpow10 = Big::from_small(1); diff --git a/library/core/tests/num/flt2dec/strategy/grisu.rs b/library/core/tests/num/flt2dec/strategy/grisu.rs index b59a3b9b72d3b..9b2f0453de73e 100644 --- a/library/core/tests/num/flt2dec/strategy/grisu.rs +++ b/library/core/tests/num/flt2dec/strategy/grisu.rs @@ -1,6 +1,7 @@ -use super::super::*; use core::num::flt2dec::strategy::grisu::*; +use super::super::*; + #[test] #[cfg_attr(miri, ignore)] // Miri is too slow fn test_cached_power() { diff --git a/library/core/tests/num/uint_macros.rs b/library/core/tests/num/uint_macros.rs index 955440647eb98..d009ad89d5ce7 100644 --- a/library/core/tests/num/uint_macros.rs +++ b/library/core/tests/num/uint_macros.rs @@ -260,6 +260,14 @@ macro_rules! uint_module { assert_eq!(MAX.checked_next_multiple_of(2), None); } + #[test] + fn test_is_next_multiple_of() { + assert!((12 as $T).is_multiple_of(4)); + assert!(!(12 as $T).is_multiple_of(5)); + assert!((0 as $T).is_multiple_of(0)); + assert!(!(12 as $T).is_multiple_of(0)); + } + #[test] fn test_carrying_add() { assert_eq!($T::MAX.carrying_add(1, false), (0, true)); diff --git a/library/core/tests/ops.rs b/library/core/tests/ops.rs index 0c81cba35b3df..2ee0abd399bb6 100644 --- a/library/core/tests/ops.rs +++ b/library/core/tests/ops.rs @@ -1,7 +1,8 @@ mod control_flow; -use core::ops::{Bound, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive}; -use core::ops::{Deref, DerefMut}; +use core::ops::{ + Bound, Deref, DerefMut, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, +}; // Test the Range structs and syntax. diff --git a/library/core/tests/pin_macro.rs b/library/core/tests/pin_macro.rs index 57485ef3974cc..36c6972515a96 100644 --- a/library/core/tests/pin_macro.rs +++ b/library/core/tests/pin_macro.rs @@ -1,10 +1,8 @@ // edition:2021 -use core::{ - marker::PhantomPinned, - mem::{drop as stuff, transmute}, - pin::{pin, Pin}, -}; +use core::marker::PhantomPinned; +use core::mem::{drop as stuff, transmute}; +use core::pin::{pin, Pin}; #[test] fn basic() { diff --git a/library/core/tests/ptr.rs b/library/core/tests/ptr.rs index e3830165eda61..bc1940ebf32b5 100644 --- a/library/core/tests/ptr.rs +++ b/library/core/tests/ptr.rs @@ -1050,7 +1050,7 @@ fn nonnull_tagged_pointer_with_provenance() { /// A mask for the non-data-carrying bits of the address. pub const ADDRESS_MASK: usize = usize::MAX << Self::NUM_BITS; - /// Create a new tagged pointer from a possibly null pointer. + /// Creates a new tagged pointer from a possibly null pointer. pub fn new(pointer: *mut T) -> Option> { Some(TaggedPointer(NonNull::new(pointer)?)) } diff --git a/library/core/tests/result.rs b/library/core/tests/result.rs index 00a6fd75b4f46..90ec844bc5771 100644 --- a/library/core/tests/result.rs +++ b/library/core/tests/result.rs @@ -410,7 +410,8 @@ fn result_opt_conversions() { #[test] fn result_try_trait_v2_branch() { use core::num::NonZero; - use core::ops::{ControlFlow::*, Try}; + use core::ops::ControlFlow::*; + use core::ops::Try; assert_eq!(Ok::(4).branch(), Continue(4)); assert_eq!(Err::(4).branch(), Break(Err(4))); diff --git a/library/core/tests/slice.rs b/library/core/tests/slice.rs index 4cbbabb672ba0..cdefb5d3eb201 100644 --- a/library/core/tests/slice.rs +++ b/library/core/tests/slice.rs @@ -69,13 +69,13 @@ fn test_binary_search() { assert_eq!(b.binary_search(&8), Err(5)); let b = [(); usize::MAX]; - assert_eq!(b.binary_search(&()), Ok(usize::MAX / 2)); + assert_eq!(b.binary_search(&()), Ok(usize::MAX - 1)); } #[test] fn test_binary_search_by_overflow() { let b = [(); usize::MAX]; - assert_eq!(b.binary_search_by(|_| Ordering::Equal), Ok(usize::MAX / 2)); + assert_eq!(b.binary_search_by(|_| Ordering::Equal), Ok(usize::MAX - 1)); assert_eq!(b.binary_search_by(|_| Ordering::Greater), Err(0)); assert_eq!(b.binary_search_by(|_| Ordering::Less), Err(usize::MAX)); } @@ -87,13 +87,13 @@ fn test_binary_search_implementation_details() { let b = [1, 1, 2, 2, 3, 3, 3]; assert_eq!(b.binary_search(&1), Ok(1)); assert_eq!(b.binary_search(&2), Ok(3)); - assert_eq!(b.binary_search(&3), Ok(5)); + assert_eq!(b.binary_search(&3), Ok(6)); let b = [1, 1, 1, 1, 1, 3, 3, 3, 3]; assert_eq!(b.binary_search(&1), Ok(4)); - assert_eq!(b.binary_search(&3), Ok(7)); + assert_eq!(b.binary_search(&3), Ok(8)); let b = [1, 1, 1, 1, 3, 3, 3, 3, 3]; - assert_eq!(b.binary_search(&1), Ok(2)); - assert_eq!(b.binary_search(&3), Ok(4)); + assert_eq!(b.binary_search(&1), Ok(3)); + assert_eq!(b.binary_search(&3), Ok(8)); } #[test] @@ -1856,6 +1856,7 @@ fn sort_unstable() { #[cfg_attr(miri, ignore)] // Miri is too slow fn select_nth_unstable() { use core::cmp::Ordering::{Equal, Greater, Less}; + use rand::seq::SliceRandom; use rand::Rng; diff --git a/library/core/tests/waker.rs b/library/core/tests/waker.rs index 2c66e0d7ad3a4..361e900e69562 100644 --- a/library/core/tests/waker.rs +++ b/library/core/tests/waker.rs @@ -20,3 +20,33 @@ static WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new( |_| {}, |_| {}, ); + +// https://github.com/rust-lang/rust/issues/102012#issuecomment-1915282956 +mod nop_waker { + use core::future::{ready, Future}; + use core::pin::Pin; + use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; + + const NOP_RAWWAKER: RawWaker = { + fn nop(_: *const ()) {} + const VTAB: RawWakerVTable = RawWakerVTable::new(|_| NOP_RAWWAKER, nop, nop, nop); + RawWaker::new(&() as *const (), &VTAB) + }; + + const NOP_WAKER: &Waker = &unsafe { Waker::from_raw(NOP_RAWWAKER) }; + + const NOP_CONTEXT: Context<'static> = Context::from_waker(NOP_WAKER); + + fn poll_once(f: &mut F) -> Poll + where + F: Future + ?Sized + Unpin, + { + let mut cx = NOP_CONTEXT; + Pin::new(f).as_mut().poll(&mut cx) + } + + #[test] + fn test_const_waker() { + assert_eq!(poll_once(&mut ready(1)), Poll::Ready(1)); + } +} diff --git a/library/panic_abort/src/lib.rs b/library/panic_abort/src/lib.rs index 14ba4af2bb575..dc2b42bb90ae8 100644 --- a/library/panic_abort/src/lib.rs +++ b/library/panic_abort/src/lib.rs @@ -14,7 +14,6 @@ #![feature(std_internals)] #![feature(staged_api)] #![feature(rustc_attrs)] -#![cfg_attr(bootstrap, feature(c_unwind))] #![allow(internal_features)] #[cfg(target_os = "android")] diff --git a/library/panic_unwind/src/emcc.rs b/library/panic_unwind/src/emcc.rs index fed4c52e83c5f..86a43184fb529 100644 --- a/library/panic_unwind/src/emcc.rs +++ b/library/panic_unwind/src/emcc.rs @@ -8,10 +8,9 @@ use alloc::boxed::Box; use core::any::Any; -use core::intrinsics; -use core::mem; -use core::ptr; use core::sync::atomic::{AtomicBool, Ordering}; +use core::{intrinsics, mem, ptr}; + use unwind as uw; // This matches the layout of std::type_info in C++ diff --git a/library/panic_unwind/src/lib.rs b/library/panic_unwind/src/lib.rs index 77abb9125f651..2d174f4b1a4a2 100644 --- a/library/panic_unwind/src/lib.rs +++ b/library/panic_unwind/src/lib.rs @@ -24,7 +24,6 @@ #![feature(rustc_attrs)] #![panic_runtime] #![feature(panic_runtime)] -#![cfg_attr(bootstrap, feature(c_unwind))] // `real_imp` is unused with Miri, so silence warnings. #![cfg_attr(miri, allow(dead_code))] #![allow(internal_features)] diff --git a/library/portable-simd/crates/core_simd/src/masks.rs b/library/portable-simd/crates/core_simd/src/masks.rs index e6e27c76a5e99..04de3a968276d 100644 --- a/library/portable-simd/crates/core_simd/src/masks.rs +++ b/library/portable-simd/crates/core_simd/src/masks.rs @@ -137,7 +137,7 @@ where T: MaskElement, LaneCount: SupportedLaneCount, { - /// Construct a mask by setting all elements to the given value. + /// Constructs a mask by setting all elements to the given value. #[inline] pub fn splat(value: bool) -> Self { Self(mask_impl::Mask::splat(value)) @@ -288,7 +288,7 @@ where self.0.all() } - /// Create a bitmask from a mask. + /// Creates a bitmask from a mask. /// /// Each bit is set if the corresponding element in the mask is `true`. /// If the mask contains more than 64 elements, the bitmask is truncated to the first 64. @@ -298,7 +298,7 @@ where self.0.to_bitmask_integer() } - /// Create a mask from a bitmask. + /// Creates a mask from a bitmask. /// /// For each bit, if it is set, the corresponding element in the mask is set to `true`. /// If the mask contains more than 64 elements, the remainder are set to `false`. @@ -308,7 +308,7 @@ where Self(mask_impl::Mask::from_bitmask_integer(bitmask)) } - /// Create a bitmask vector from a mask. + /// Creates a bitmask vector from a mask. /// /// Each bit is set if the corresponding element in the mask is `true`. /// The remaining bits are unset. @@ -328,7 +328,7 @@ where self.0.to_bitmask_vector() } - /// Create a mask from a bitmask vector. + /// Creates a mask from a bitmask vector. /// /// For each bit, if it is set, the corresponding element in the mask is set to `true`. /// @@ -350,7 +350,7 @@ where Self(mask_impl::Mask::from_bitmask_vector(bitmask)) } - /// Find the index of the first set element. + /// Finds the index of the first set element. /// /// ``` /// # #![feature(portable_simd)] diff --git a/library/portable-simd/crates/core_simd/src/simd/ptr/const_ptr.rs b/library/portable-simd/crates/core_simd/src/simd/ptr/const_ptr.rs index cbffbc564cfed..be635ea640b86 100644 --- a/library/portable-simd/crates/core_simd/src/simd/ptr/const_ptr.rs +++ b/library/portable-simd/crates/core_simd/src/simd/ptr/const_ptr.rs @@ -54,7 +54,7 @@ pub trait SimdConstPtr: Copy + Sealed { /// [`Self::with_exposed_provenance`] and returns the "address" portion. fn expose_provenance(self) -> Self::Usize; - /// Convert an address back to a pointer, picking up a previously "exposed" provenance. + /// Converts an address back to a pointer, picking up a previously "exposed" provenance. /// /// Equivalent to calling [`core::ptr::with_exposed_provenance`] on each element. fn with_exposed_provenance(addr: Self::Usize) -> Self; diff --git a/library/portable-simd/crates/core_simd/src/simd/ptr/mut_ptr.rs b/library/portable-simd/crates/core_simd/src/simd/ptr/mut_ptr.rs index 6bc6ca3ac42dc..f6823a949e32a 100644 --- a/library/portable-simd/crates/core_simd/src/simd/ptr/mut_ptr.rs +++ b/library/portable-simd/crates/core_simd/src/simd/ptr/mut_ptr.rs @@ -51,7 +51,7 @@ pub trait SimdMutPtr: Copy + Sealed { /// [`Self::with_exposed_provenance`] and returns the "address" portion. fn expose_provenance(self) -> Self::Usize; - /// Convert an address back to a pointer, picking up a previously "exposed" provenance. + /// Converts an address back to a pointer, picking up a previously "exposed" provenance. /// /// Equivalent to calling [`core::ptr::with_exposed_provenance_mut`] on each element. fn with_exposed_provenance(addr: Self::Usize) -> Self; diff --git a/library/portable-simd/crates/core_simd/src/swizzle.rs b/library/portable-simd/crates/core_simd/src/swizzle.rs index 71110bb282018..2f4f777b20e29 100644 --- a/library/portable-simd/crates/core_simd/src/swizzle.rs +++ b/library/portable-simd/crates/core_simd/src/swizzle.rs @@ -69,12 +69,12 @@ pub macro simd_swizzle { } } -/// Create a vector from the elements of another vector. +/// Creates a vector from the elements of another vector. pub trait Swizzle { /// Map from the elements of the input vector to the output vector. const INDEX: [usize; N]; - /// Create a new vector from the elements of `vector`. + /// Creates a new vector from the elements of `vector`. /// /// Lane `i` of the output is `vector[Self::INDEX[i]]`. #[inline] @@ -109,7 +109,7 @@ pub trait Swizzle { } } - /// Create a new vector from the elements of `first` and `second`. + /// Creates a new vector from the elements of `first` and `second`. /// /// Lane `i` of the output is `concat[Self::INDEX[i]]`, where `concat` is the concatenation of /// `first` and `second`. @@ -145,7 +145,7 @@ pub trait Swizzle { } } - /// Create a new mask from the elements of `mask`. + /// Creates a new mask from the elements of `mask`. /// /// Element `i` of the output is `concat[Self::INDEX[i]]`, where `concat` is the concatenation of /// `first` and `second`. @@ -161,7 +161,7 @@ pub trait Swizzle { unsafe { Mask::from_int_unchecked(Self::swizzle(mask.to_int())) } } - /// Create a new mask from the elements of `first` and `second`. + /// Creates a new mask from the elements of `first` and `second`. /// /// Element `i` of the output is `concat[Self::INDEX[i]]`, where `concat` is the concatenation of /// `first` and `second`. diff --git a/library/portable-simd/crates/core_simd/src/to_bytes.rs b/library/portable-simd/crates/core_simd/src/to_bytes.rs index 222526c4ab30a..4833ea9e11362 100644 --- a/library/portable-simd/crates/core_simd/src/to_bytes.rs +++ b/library/portable-simd/crates/core_simd/src/to_bytes.rs @@ -10,7 +10,7 @@ mod sealed { } use sealed::Sealed; -/// Convert SIMD vectors to vectors of bytes +/// Converts SIMD vectors to vectors of bytes pub trait ToBytes: Sealed { /// This type, reinterpreted as bytes. type Bytes: Copy @@ -22,26 +22,26 @@ pub trait ToBytes: Sealed { + SimdUint + 'static; - /// Return the memory representation of this integer as a byte array in native byte + /// Returns the memory representation of this integer as a byte array in native byte /// order. fn to_ne_bytes(self) -> Self::Bytes; - /// Return the memory representation of this integer as a byte array in big-endian + /// Returns the memory representation of this integer as a byte array in big-endian /// (network) byte order. fn to_be_bytes(self) -> Self::Bytes; - /// Return the memory representation of this integer as a byte array in little-endian + /// Returns the memory representation of this integer as a byte array in little-endian /// byte order. fn to_le_bytes(self) -> Self::Bytes; - /// Create a native endian integer value from its memory representation as a byte array + /// Creates a native endian integer value from its memory representation as a byte array /// in native endianness. fn from_ne_bytes(bytes: Self::Bytes) -> Self; - /// Create an integer value from its representation as a byte array in big endian. + /// Creates an integer value from its representation as a byte array in big endian. fn from_be_bytes(bytes: Self::Bytes) -> Self; - /// Create an integer value from its representation as a byte array in little endian. + /// Creates an integer value from its representation as a byte array in little endian. fn from_le_bytes(bytes: Self::Bytes) -> Self; } diff --git a/library/portable-simd/crates/core_simd/src/vector.rs b/library/portable-simd/crates/core_simd/src/vector.rs index 8dbdfc0e1fe03..3e23916914963 100644 --- a/library/portable-simd/crates/core_simd/src/vector.rs +++ b/library/portable-simd/crates/core_simd/src/vector.rs @@ -187,7 +187,7 @@ where unsafe { &mut *(self as *mut Self as *mut [T; N]) } } - /// Load a vector from an array of `T`. + /// Loads a vector from an array of `T`. /// /// This function is necessary since `repr(simd)` has padding for non-power-of-2 vectors (at the time of writing). /// With padding, `read_unaligned` will read past the end of an array of N elements. @@ -567,7 +567,7 @@ where unsafe { Self::gather_select_ptr(ptrs, enable, or) } } - /// Read elementwise from pointers into a SIMD vector. + /// Reads elementwise from pointers into a SIMD vector. /// /// # Safety /// @@ -808,7 +808,7 @@ where } } - /// Write pointers elementwise into a SIMD vector. + /// Writes pointers elementwise into a SIMD vector. /// /// # Safety /// diff --git a/library/proc_macro/src/bridge/arena.rs b/library/proc_macro/src/bridge/arena.rs index f81f2152cd046..1d5986093c8a4 100644 --- a/library/proc_macro/src/bridge/arena.rs +++ b/library/proc_macro/src/bridge/arena.rs @@ -5,12 +5,9 @@ //! being built at the same time as `std`. use std::cell::{Cell, RefCell}; -use std::cmp; use std::mem::MaybeUninit; use std::ops::Range; -use std::ptr; -use std::slice; -use std::str; +use std::{cmp, ptr, slice, str}; // The arenas start with PAGE-sized chunks, and then each new chunk is twice as // big as its predecessor, up until we reach HUGE_PAGE-sized chunks, whereupon diff --git a/library/proc_macro/src/bridge/buffer.rs b/library/proc_macro/src/bridge/buffer.rs index 149767bf70521..78fcd1999b2f3 100644 --- a/library/proc_macro/src/bridge/buffer.rs +++ b/library/proc_macro/src/bridge/buffer.rs @@ -1,7 +1,7 @@ //! Buffer management for same-process client<->server communication. use std::io::{self, Write}; -use std::mem; +use std::mem::{self, ManuallyDrop}; use std::ops::{Deref, DerefMut}; use std::slice; @@ -129,17 +129,16 @@ impl Drop for Buffer { } impl From> for Buffer { - fn from(mut v: Vec) -> Self { + fn from(v: Vec) -> Self { + let mut v = ManuallyDrop::new(v); let (data, len, capacity) = (v.as_mut_ptr(), v.len(), v.capacity()); - mem::forget(v); // This utility function is nested in here because it can *only* // be safely called on `Buffer`s created by *this* `proc_macro`. fn to_vec(b: Buffer) -> Vec { unsafe { - let Buffer { data, len, capacity, .. } = b; - mem::forget(b); - Vec::from_raw_parts(data, len, capacity) + let b = ManuallyDrop::new(b); + Vec::from_raw_parts(b.data, b.len, b.capacity) } } diff --git a/library/proc_macro/src/bridge/client.rs b/library/proc_macro/src/bridge/client.rs index faca745e56f74..5a1086527a127 100644 --- a/library/proc_macro/src/bridge/client.rs +++ b/library/proc_macro/src/bridge/client.rs @@ -1,11 +1,11 @@ //! Client-side types. -use super::*; - use std::cell::RefCell; use std::marker::PhantomData; use std::sync::atomic::AtomicU32; +use super::*; + macro_rules! define_client_handles { ( 'owned: $($oty:ident,)* @@ -51,9 +51,7 @@ macro_rules! define_client_handles { impl Encode for $oty { fn encode(self, w: &mut Writer, s: &mut S) { - let handle = self.handle; - mem::forget(self); - handle.encode(w, s); + mem::ManuallyDrop::new(self).handle.encode(w, s); } } @@ -192,10 +190,11 @@ impl<'a> !Sync for Bridge<'a> {} #[allow(unsafe_code)] mod state { - use super::Bridge; use std::cell::{Cell, RefCell}; use std::ptr; + use super::Bridge; + thread_local! { static BRIDGE_STATE: Cell<*const ()> = const { Cell::new(ptr::null()) }; } diff --git a/library/proc_macro/src/bridge/fxhash.rs b/library/proc_macro/src/bridge/fxhash.rs index 9fb79eabd0556..74a41451825ff 100644 --- a/library/proc_macro/src/bridge/fxhash.rs +++ b/library/proc_macro/src/bridge/fxhash.rs @@ -5,8 +5,7 @@ //! on the `rustc_hash` crate. use std::collections::HashMap; -use std::hash::BuildHasherDefault; -use std::hash::Hasher; +use std::hash::{BuildHasherDefault, Hasher}; use std::ops::BitXor; /// Type alias for a hashmap using the `fx` hash algorithm. diff --git a/library/proc_macro/src/bridge/mod.rs b/library/proc_macro/src/bridge/mod.rs index 8553e8d5e4fd6..03c3e697cfe2b 100644 --- a/library/proc_macro/src/bridge/mod.rs +++ b/library/proc_macro/src/bridge/mod.rs @@ -8,16 +8,12 @@ #![deny(unsafe_code)] -use crate::{Delimiter, Level, Spacing}; -use std::fmt; use std::hash::Hash; -use std::marker; -use std::mem; -use std::ops::Bound; -use std::ops::Range; -use std::panic; +use std::ops::{Bound, Range}; use std::sync::Once; -use std::thread; +use std::{fmt, marker, mem, panic, thread}; + +use crate::{Delimiter, Level, Spacing}; /// Higher-order macro describing the server RPC API, allowing automatic /// generation of type-safe Rust APIs, both client-side and server-side. diff --git a/library/proc_macro/src/bridge/server.rs b/library/proc_macro/src/bridge/server.rs index 0dbd4bac85c9f..692b6038a3872 100644 --- a/library/proc_macro/src/bridge/server.rs +++ b/library/proc_macro/src/bridge/server.rs @@ -1,10 +1,10 @@ //! Server-side traits. -use super::*; - use std::cell::Cell; use std::marker::PhantomData; +use super::*; + macro_rules! define_server_handles { ( 'owned: $($oty:ident,)* @@ -350,7 +350,7 @@ where /// A message pipe used for communicating between server and client threads. pub trait MessagePipe: Sized { - /// Create a new pair of endpoints for the message pipe. + /// Creates a new pair of endpoints for the message pipe. fn new() -> (Self, Self); /// Send a message to the other endpoint of this pipe. diff --git a/library/proc_macro/src/bridge/symbol.rs b/library/proc_macro/src/bridge/symbol.rs index 86ce2cc189588..37aaee6b21553 100644 --- a/library/proc_macro/src/bridge/symbol.rs +++ b/library/proc_macro/src/bridge/symbol.rs @@ -28,7 +28,7 @@ impl Symbol { INTERNER.with_borrow_mut(|i| i.intern(string)) } - /// Create a new `Symbol` for an identifier. + /// Creates a new `Symbol` for an identifier. /// /// Validates and normalizes before converting it to a symbol. pub(crate) fn new_ident(string: &str, is_raw: bool) -> Self { @@ -63,7 +63,7 @@ impl Symbol { INTERNER.with_borrow_mut(|i| i.clear()); } - /// Check if the ident is a valid ASCII identifier. + /// Checks if the ident is a valid ASCII identifier. /// /// This is a short-circuit which is cheap to implement within the /// proc-macro client to avoid RPC when creating simple idents, but may @@ -177,7 +177,7 @@ impl Interner { name } - /// Read a symbol's value from the store while it is held. + /// Reads a symbol's value from the store while it is held. fn get(&self, symbol: Symbol) -> &str { // NOTE: Subtract out the offset which was added to make the symbol // nonzero and prevent symbol name re-use. diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index 57247359fbf29..c271ac1870624 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -37,6 +37,7 @@ #![recursion_limit = "256"] #![allow(internal_features)] #![deny(ffi_unwind_calls)] +#![warn(rustdoc::unescaped_backticks)] #[unstable(feature = "proc_macro_internals", issue = "27812")] #[doc(hidden)] @@ -45,16 +46,17 @@ pub mod bridge; mod diagnostic; mod escape; -#[unstable(feature = "proc_macro_diagnostic", issue = "54140")] -pub use diagnostic::{Diagnostic, Level, MultiSpan}; - -use crate::escape::{escape_bytes, EscapeOptions}; use std::ffi::CStr; use std::ops::{Range, RangeBounds}; use std::path::PathBuf; use std::str::FromStr; use std::{error, fmt}; +#[unstable(feature = "proc_macro_diagnostic", issue = "54140")] +pub use diagnostic::{Diagnostic, Level, MultiSpan}; + +use crate::escape::{escape_bytes, EscapeOptions}; + /// Determines whether proc_macro has been made accessible to the currently /// running program. /// diff --git a/library/rtstartup/rsbegin.rs b/library/rtstartup/rsbegin.rs index 14bce2bbeee2b..9a3d95bd8ddfb 100644 --- a/library/rtstartup/rsbegin.rs +++ b/library/rtstartup/rsbegin.rs @@ -29,6 +29,8 @@ trait Copy {} #[lang = "freeze"] auto trait Freeze {} +impl Copy for *mut T {} + #[lang = "drop_in_place"] #[inline] #[allow(unconditional_recursion)] diff --git a/library/rtstartup/rsend.rs b/library/rtstartup/rsend.rs index 714643c83866f..2514eb0034402 100644 --- a/library/rtstartup/rsend.rs +++ b/library/rtstartup/rsend.rs @@ -17,6 +17,8 @@ trait Copy {} #[lang = "freeze"] auto trait Freeze {} +impl Copy for *mut T {} + #[lang = "drop_in_place"] #[inline] #[allow(unconditional_recursion)] diff --git a/library/std/Cargo.toml b/library/std/Cargo.toml index 5929c94a864e8..fe601855cc1e7 100644 --- a/library/std/Cargo.toml +++ b/library/std/Cargo.toml @@ -17,7 +17,7 @@ cfg-if = { version = "1.0", features = ['rustc-dep-of-std'] } panic_unwind = { path = "../panic_unwind", optional = true } panic_abort = { path = "../panic_abort" } core = { path = "../core", public = true } -compiler_builtins = { version = "0.1.105" } +compiler_builtins = { version = "0.1.114" } profiler_builtins = { path = "../profiler_builtins", optional = true } unwind = { path = "../unwind" } hashbrown = { version = "0.14", default-features = false, features = [ @@ -95,8 +95,8 @@ profiler = ["profiler_builtins"] compiler-builtins-c = ["alloc/compiler-builtins-c"] compiler-builtins-mem = ["alloc/compiler-builtins-mem"] compiler-builtins-no-asm = ["alloc/compiler-builtins-no-asm"] +compiler-builtins-no-f16-f128 = ["alloc/compiler-builtins-no-f16-f128"] compiler-builtins-mangled-names = ["alloc/compiler-builtins-mangled-names"] -compiler-builtins-weak-intrinsics = ["alloc/compiler-builtins-weak-intrinsics"] llvm-libunwind = ["unwind/llvm-libunwind"] system-llvm-libunwind = ["unwind/system-llvm-libunwind"] diff --git a/library/std/benches/hash/map.rs b/library/std/benches/hash/map.rs index bf646cbae47db..d6023c8212b89 100644 --- a/library/std/benches/hash/map.rs +++ b/library/std/benches/hash/map.rs @@ -1,6 +1,7 @@ #![cfg(test)] use std::collections::HashMap; + use test::Bencher; #[bench] diff --git a/library/std/benches/hash/set_ops.rs b/library/std/benches/hash/set_ops.rs index 1a4c4a66ee9e0..b97e3b450850e 100644 --- a/library/std/benches/hash/set_ops.rs +++ b/library/std/benches/hash/set_ops.rs @@ -1,4 +1,5 @@ use std::collections::HashSet; + use test::Bencher; #[bench] diff --git a/library/std/build.rs b/library/std/build.rs index c542ba81eedc1..9b58dd53ba20a 100644 --- a/library/std/build.rs +++ b/library/std/build.rs @@ -94,7 +94,7 @@ fn main() { // Unsupported ("arm64ec", _) => false, // MinGW ABI bugs - ("x86", "windows") => false, + ("x86_64", "windows") => false, // x86 has ABI bugs that show up with optimizations. This should be partially fixed with // the compiler-builtins update. ("x86" | "x86_64", _) => false, @@ -122,6 +122,8 @@ fn main() { ("nvptx64", _) => false, // ABI unsupported ("sparc", _) => false, + // MinGW ABI bugs + ("x86_64", "windows") => false, // 64-bit Linux is about the only platform to have f128 symbols by default (_, "linux") if target_pointer_width == 64 => true, // Same as for f16, except MacOS is also missing f128 symbols. diff --git a/library/std/src/alloc.rs b/library/std/src/alloc.rs index dc4924cdf581d..5d51d6a0c78a8 100644 --- a/library/std/src/alloc.rs +++ b/library/std/src/alloc.rs @@ -56,10 +56,9 @@ #![deny(unsafe_op_in_unsafe_fn)] #![stable(feature = "alloc_module", since = "1.28.0")] -use core::hint; use core::ptr::NonNull; use core::sync::atomic::{AtomicPtr, Ordering}; -use core::{mem, ptr}; +use core::{hint, mem, ptr}; #[stable(feature = "alloc_module", since = "1.28.0")] #[doc(inline)] diff --git a/library/std/src/ascii.rs b/library/std/src/ascii.rs index b18ab50de123e..3a2880fd50904 100644 --- a/library/std/src/ascii.rs +++ b/library/std/src/ascii.rs @@ -13,11 +13,10 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::ascii::{escape_default, EscapeDefault}; - #[unstable(feature = "ascii_char", issue = "110998")] pub use core::ascii::Char; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::ascii::{escape_default, EscapeDefault}; /// Extension methods for ASCII-subset only operations. /// diff --git a/library/std/src/backtrace.rs b/library/std/src/backtrace.rs index 4d376753cb6d2..7df9a8a14b00c 100644 --- a/library/std/src/backtrace.rs +++ b/library/std/src/backtrace.rs @@ -89,13 +89,13 @@ mod tests; // a backtrace or actually symbolizing it. use crate::backtrace_rs::{self, BytesOrWideString}; -use crate::env; use crate::ffi::c_void; -use crate::fmt; use crate::panic::UnwindSafe; -use crate::sync::atomic::{AtomicU8, Ordering::Relaxed}; +use crate::sync::atomic::AtomicU8; +use crate::sync::atomic::Ordering::Relaxed; use crate::sync::LazyLock; use crate::sys::backtrace::{lock, output_filename, set_image_base}; +use crate::{env, fmt}; /// A captured OS thread stack backtrace. /// @@ -271,7 +271,7 @@ impl Backtrace { enabled } - /// Capture a stack backtrace of the current thread. + /// Captures a stack backtrace of the current thread. /// /// This function will capture a stack backtrace of the current OS thread of /// execution, returning a `Backtrace` type which can be later used to print diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index 1f6a3e904795a..822fa5791e300 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -1,13 +1,11 @@ #[cfg(test)] mod tests; -use self::Entry::*; - use hashbrown::hash_map as base; +use self::Entry::*; use crate::borrow::Borrow; -use crate::collections::TryReserveError; -use crate::collections::TryReserveErrorKind; +use crate::collections::{TryReserveError, TryReserveErrorKind}; use crate::error::Error; use crate::fmt::{self, Debug}; use crate::hash::{BuildHasher, Hash, RandomState}; diff --git a/library/std/src/collections/hash/map/tests.rs b/library/std/src/collections/hash/map/tests.rs index 8585376abc18b..6641197c3724a 100644 --- a/library/std/src/collections/hash/map/tests.rs +++ b/library/std/src/collections/hash/map/tests.rs @@ -1,11 +1,12 @@ +use rand::Rng; +use realstd::collections::TryReserveErrorKind::*; + use super::Entry::{Occupied, Vacant}; use super::HashMap; use crate::assert_matches::assert_matches; use crate::cell::RefCell; use crate::hash::RandomState; use crate::test_helpers::test_rng; -use rand::Rng; -use realstd::collections::TryReserveErrorKind::*; // https://github.com/rust-lang/rust/issues/62301 fn _assert_hashmap_is_unwind_safe() { @@ -946,7 +947,6 @@ fn test_raw_entry() { mod test_extract_if { use super::*; - use crate::panic::{catch_unwind, AssertUnwindSafe}; use crate::sync::atomic::{AtomicUsize, Ordering}; diff --git a/library/std/src/collections/hash/set.rs b/library/std/src/collections/hash/set.rs index f0a498fc7bbca..d611353b0d3f2 100644 --- a/library/std/src/collections/hash/set.rs +++ b/library/std/src/collections/hash/set.rs @@ -3,6 +3,7 @@ mod tests; use hashbrown::hash_set as base; +use super::map::map_try_reserve_error; use crate::borrow::Borrow; use crate::collections::TryReserveError; use crate::fmt; @@ -10,8 +11,6 @@ use crate::hash::{BuildHasher, Hash, RandomState}; use crate::iter::{Chain, FusedIterator}; use crate::ops::{BitAnd, BitOr, BitXor, Sub}; -use super::map::map_try_reserve_error; - /// A [hash set] implemented as a `HashMap` where the value is `()`. /// /// As with the [`HashMap`] type, a `HashSet` requires that the elements diff --git a/library/std/src/collections/hash/set/tests.rs b/library/std/src/collections/hash/set/tests.rs index a188409004305..4e6351652721f 100644 --- a/library/std/src/collections/hash/set/tests.rs +++ b/library/std/src/collections/hash/set/tests.rs @@ -1,5 +1,4 @@ use super::HashSet; - use crate::hash::RandomState; use crate::panic::{catch_unwind, AssertUnwindSafe}; use crate::sync::atomic::{AtomicU32, Ordering}; diff --git a/library/std/src/collections/mod.rs b/library/std/src/collections/mod.rs index 1389d24a8c519..3b04412e76630 100644 --- a/library/std/src/collections/mod.rs +++ b/library/std/src/collections/mod.rs @@ -401,12 +401,14 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[stable(feature = "rust1", since = "1.0.0")] -// FIXME(#82080) The deprecation here is only theoretical, and does not actually produce a warning. -#[deprecated(note = "moved to `std::ops::Bound`", since = "1.26.0")] -#[doc(hidden)] -pub use crate::ops::Bound; - +#[stable(feature = "try_reserve", since = "1.57.0")] +pub use alloc_crate::collections::TryReserveError; +#[unstable( + feature = "try_reserve_kind", + reason = "Uncertain how much info should be exposed", + issue = "48043" +)] +pub use alloc_crate::collections::TryReserveErrorKind; #[stable(feature = "rust1", since = "1.0.0")] pub use alloc_crate::collections::{binary_heap, btree_map, btree_set}; #[stable(feature = "rust1", since = "1.0.0")] @@ -422,15 +424,11 @@ pub use self::hash_map::HashMap; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] pub use self::hash_set::HashSet; - -#[stable(feature = "try_reserve", since = "1.57.0")] -pub use alloc_crate::collections::TryReserveError; -#[unstable( - feature = "try_reserve_kind", - reason = "Uncertain how much info should be exposed", - issue = "48043" -)] -pub use alloc_crate::collections::TryReserveErrorKind; +#[stable(feature = "rust1", since = "1.0.0")] +// FIXME(#82080) The deprecation here is only theoretical, and does not actually produce a warning. +#[deprecated(note = "moved to `std::ops::Bound`", since = "1.26.0")] +#[doc(hidden)] +pub use crate::ops::Bound; mod hash; @@ -439,7 +437,6 @@ pub mod hash_map { //! A hash map implemented with quadratic probing and SIMD lookup. #[stable(feature = "rust1", since = "1.0.0")] pub use super::hash::map::*; - #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] pub use crate::hash::random::DefaultHasher; #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] diff --git a/library/std/src/env.rs b/library/std/src/env.rs index fc9b8cfd46d65..50ae83090c7e1 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -15,11 +15,9 @@ mod tests; use crate::error::Error; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::path::{Path, PathBuf}; -use crate::sys; use crate::sys::os as os_imp; +use crate::{fmt, io, sys}; /// Returns the current working directory as a [`PathBuf`]. /// diff --git a/library/std/src/error.rs b/library/std/src/error.rs index 87aad8f764bd0..3e17431af45b0 100644 --- a/library/std/src/error.rs +++ b/library/std/src/error.rs @@ -4,14 +4,14 @@ #[cfg(test)] mod tests; -use crate::backtrace::Backtrace; -use crate::fmt::{self, Write}; - #[stable(feature = "rust1", since = "1.0.0")] pub use core::error::Error; #[unstable(feature = "error_generic_member_access", issue = "99301")] pub use core::error::{request_ref, request_value, Request}; +use crate::backtrace::Backtrace; +use crate::fmt::{self, Write}; + /// An error reporter that prints an error and its sources. /// /// Report also exposes configuration options for formatting the error sources, either entirely on a @@ -234,7 +234,7 @@ impl Report where Report: From, { - /// Create a new `Report` from an input error. + /// Creates a new `Report` from an input error. #[unstable(feature = "error_reporter", issue = "90172")] pub fn new(error: E) -> Report { Self::from(error) @@ -500,13 +500,8 @@ where } if self.show_backtrace { - let backtrace = self.backtrace(); - - if let Some(backtrace) = backtrace { - let backtrace = backtrace.to_string(); - - f.write_str("\n\nStack backtrace:\n")?; - f.write_str(backtrace.trim_end())?; + if let Some(backtrace) = self.backtrace() { + write!(f, "\n\nStack backtrace:\n{}", backtrace.to_string().trim_end())?; } } diff --git a/library/std/src/error/tests.rs b/library/std/src/error/tests.rs index ed070a26b0cf0..88a9f33c07908 100644 --- a/library/std/src/error/tests.rs +++ b/library/std/src/error/tests.rs @@ -1,6 +1,7 @@ +use core::error::Request; + use super::Error; use crate::fmt; -use core::error::Request; #[derive(Debug, PartialEq)] struct A; diff --git a/library/std/src/f128.rs b/library/std/src/f128.rs index 0591c6f517b44..a5b00d57cefdd 100644 --- a/library/std/src/f128.rs +++ b/library/std/src/f128.rs @@ -7,12 +7,12 @@ #[cfg(test)] mod tests; -#[cfg(not(test))] -use crate::intrinsics; - #[unstable(feature = "f128", issue = "116909")] pub use core::f128::consts; +#[cfg(not(test))] +use crate::intrinsics; + #[cfg(not(test))] impl f128 { /// Raises a number to an integer power. @@ -53,7 +53,6 @@ impl f128 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[rustc_allow_incoherent_impl] #[unstable(feature = "f128", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] diff --git a/library/std/src/f128/tests.rs b/library/std/src/f128/tests.rs index 0b3e485b0e735..162c8dbad81a1 100644 --- a/library/std/src/f128/tests.rs +++ b/library/std/src/f128/tests.rs @@ -1,10 +1,8 @@ -#![cfg(not(bootstrap))] // FIXME(f16_f128): only tested on platforms that have symbols and aren't buggy #![cfg(reliable_f128)] use crate::f128::consts; -use crate::num::FpCategory as Fp; -use crate::num::*; +use crate::num::{FpCategory as Fp, *}; /// Smallest number const TINY_BITS: u128 = 0x1; diff --git a/library/std/src/f16.rs b/library/std/src/f16.rs index d48518622999a..e3024defed734 100644 --- a/library/std/src/f16.rs +++ b/library/std/src/f16.rs @@ -7,12 +7,12 @@ #[cfg(test)] mod tests; -#[cfg(not(test))] -use crate::intrinsics; - #[unstable(feature = "f16", issue = "116909")] pub use core::f16::consts; +#[cfg(not(test))] +use crate::intrinsics; + #[cfg(not(test))] impl f16 { /// Raises a number to an integer power. @@ -53,7 +53,6 @@ impl f16 { /// # } /// ``` #[inline] - #[cfg(not(bootstrap))] #[rustc_allow_incoherent_impl] #[unstable(feature = "f16", issue = "116909")] #[must_use = "method returns a new number and does not mutate the original value"] diff --git a/library/std/src/f16/tests.rs b/library/std/src/f16/tests.rs index 26658a0be87bc..f73bdf68e8295 100644 --- a/library/std/src/f16/tests.rs +++ b/library/std/src/f16/tests.rs @@ -1,10 +1,8 @@ -#![cfg(not(bootstrap))] // FIXME(f16_f128): only tested on platforms that have symbols and aren't buggy #![cfg(reliable_f16)] use crate::f16::consts; -use crate::num::FpCategory as Fp; -use crate::num::*; +use crate::num::{FpCategory as Fp, *}; // We run out of precision pretty quickly with f16 // const F16_APPROX_L1: f16 = 0.001; diff --git a/library/std/src/f32.rs b/library/std/src/f32.rs index 4fc82fec0adbc..12433d25bfa45 100644 --- a/library/std/src/f32.rs +++ b/library/std/src/f32.rs @@ -15,11 +15,6 @@ #[cfg(test)] mod tests; -#[cfg(not(test))] -use crate::intrinsics; -#[cfg(not(test))] -use crate::sys::cmath; - #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::f32::{ @@ -27,6 +22,11 @@ pub use core::f32::{ MIN_EXP, MIN_POSITIVE, NAN, NEG_INFINITY, RADIX, }; +#[cfg(not(test))] +use crate::intrinsics; +#[cfg(not(test))] +use crate::sys::cmath; + #[cfg(not(test))] impl f32 { /// Returns the largest integer less than or equal to `self`. @@ -574,7 +574,7 @@ impl f32 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn log2(self) -> f32 { - crate::sys::log2f32(self) + unsafe { intrinsics::log2f32(self) } } /// Returns the base 10 logarithm of the number. diff --git a/library/std/src/f32/tests.rs b/library/std/src/f32/tests.rs index 63e65698374c8..3a4c1c120a495 100644 --- a/library/std/src/f32/tests.rs +++ b/library/std/src/f32/tests.rs @@ -1,6 +1,5 @@ use crate::f32::consts; -use crate::num::FpCategory as Fp; -use crate::num::*; +use crate::num::{FpCategory as Fp, *}; /// Smallest number #[allow(dead_code)] // unused on x86 diff --git a/library/std/src/f64.rs b/library/std/src/f64.rs index 1ca2b32e241c9..a343e19173e59 100644 --- a/library/std/src/f64.rs +++ b/library/std/src/f64.rs @@ -15,11 +15,6 @@ #[cfg(test)] mod tests; -#[cfg(not(test))] -use crate::intrinsics; -#[cfg(not(test))] -use crate::sys::cmath; - #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::f64::{ @@ -27,6 +22,11 @@ pub use core::f64::{ MIN_EXP, MIN_POSITIVE, NAN, NEG_INFINITY, RADIX, }; +#[cfg(not(test))] +use crate::intrinsics; +#[cfg(not(test))] +use crate::sys::cmath; + #[cfg(not(test))] impl f64 { /// Returns the largest integer less than or equal to `self`. @@ -574,7 +574,7 @@ impl f64 { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn log2(self) -> f64 { - crate::sys::log2f64(self) + unsafe { intrinsics::log2f64(self) } } /// Returns the base 10 logarithm of the number. diff --git a/library/std/src/f64/tests.rs b/library/std/src/f64/tests.rs index d9e17fd601d2d..bac8405f97361 100644 --- a/library/std/src/f64/tests.rs +++ b/library/std/src/f64/tests.rs @@ -1,6 +1,5 @@ use crate::f64::consts; -use crate::num::FpCategory as Fp; -use crate::num::*; +use crate::num::{FpCategory as Fp, *}; /// Smallest number #[allow(dead_code)] // unused on x86 diff --git a/library/std/src/ffi/c_str.rs b/library/std/src/ffi/c_str.rs index b59b0c5bba65a..cb0ca5d1376ea 100644 --- a/library/std/src/ffi/c_str.rs +++ b/library/std/src/ffi/c_str.rs @@ -1,19 +1,14 @@ //! [`CStr`], [`CString`], and related types. -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::ffi::c_str::CStr; - -#[stable(feature = "cstr_from_bytes", since = "1.10.0")] -pub use core::ffi::c_str::FromBytesWithNulError; - -#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")] -pub use core::ffi::c_str::FromBytesUntilNulError; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::ffi::c_str::{CString, NulError}; - #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")] pub use alloc::ffi::c_str::FromVecWithNulError; - #[stable(feature = "cstring_into", since = "1.7.0")] pub use alloc::ffi::c_str::IntoStringError; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc::ffi::c_str::{CString, NulError}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::ffi::c_str::CStr; +#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")] +pub use core::ffi::c_str::FromBytesUntilNulError; +#[stable(feature = "cstr_from_bytes", since = "1.10.0")] +pub use core::ffi::c_str::FromBytesWithNulError; diff --git a/library/std/src/ffi/mod.rs b/library/std/src/ffi/mod.rs index f45fd77e8b167..2b67750c2f0a9 100644 --- a/library/std/src/ffi/mod.rs +++ b/library/std/src/ffi/mod.rs @@ -164,50 +164,42 @@ #[unstable(feature = "c_str_module", issue = "112134")] pub mod c_str; -#[doc(inline)] -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::c_str::{CStr, CString}; - -#[doc(no_inline)] -#[stable(feature = "cstr_from_bytes", since = "1.10.0")] -pub use self::c_str::FromBytesWithNulError; +#[stable(feature = "core_c_void", since = "1.30.0")] +pub use core::ffi::c_void; +#[stable(feature = "core_ffi_c", since = "1.64.0")] +pub use core::ffi::{ + c_char, c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, + c_ulong, c_ulonglong, c_ushort, +}; +#[unstable( + feature = "c_variadic", + reason = "the `c_variadic` feature has not been properly tested on \ + all supported platforms", + issue = "44930" +)] +pub use core::ffi::{VaList, VaListImpl}; #[doc(no_inline)] #[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")] pub use self::c_str::FromBytesUntilNulError; - #[doc(no_inline)] -#[stable(feature = "rust1", since = "1.0.0")] -pub use self::c_str::NulError; - +#[stable(feature = "cstr_from_bytes", since = "1.10.0")] +pub use self::c_str::FromBytesWithNulError; #[doc(no_inline)] #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")] pub use self::c_str::FromVecWithNulError; - #[doc(no_inline)] #[stable(feature = "cstring_into", since = "1.7.0")] pub use self::c_str::IntoStringError; - +#[doc(no_inline)] +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::c_str::NulError; +#[doc(inline)] +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::c_str::{CStr, CString}; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] pub use self::os_str::{OsStr, OsString}; -#[stable(feature = "core_ffi_c", since = "1.64.0")] -pub use core::ffi::{ - c_char, c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, - c_ulong, c_ulonglong, c_ushort, -}; - -#[stable(feature = "core_c_void", since = "1.30.0")] -pub use core::ffi::c_void; - -#[unstable( - feature = "c_variadic", - reason = "the `c_variadic` feature has not been properly tested on \ - all supported platforms", - issue = "44930" -)] -pub use core::ffi::{VaList, VaListImpl}; - #[unstable(feature = "os_str_display", issue = "120048")] pub mod os_str; diff --git a/library/std/src/ffi/os_str.rs b/library/std/src/ffi/os_str.rs index f9dba08da4c3c..a501bcc98cf38 100644 --- a/library/std/src/ffi/os_str.rs +++ b/library/std/src/ffi/os_str.rs @@ -4,18 +4,15 @@ mod tests; use crate::borrow::{Borrow, Cow}; -use crate::cmp; use crate::collections::TryReserveError; -use crate::fmt; use crate::hash::{Hash, Hasher}; use crate::ops::{self, Range}; use crate::rc::Rc; -use crate::slice; use crate::str::FromStr; use crate::sync::Arc; - use crate::sys::os_str::{Buf, Slice}; use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::{cmp, fmt, slice}; /// A type that can represent owned, mutable platform-native strings, but is /// cheaply inter-convertible with Rust strings. @@ -115,10 +112,8 @@ impl crate::sealed::Sealed for OsString {} #[stable(feature = "rust1", since = "1.0.0")] // `OsStr::from_inner` current implementation relies // on `OsStr` being layout-compatible with `Slice`. -// However, `OsStr` layout is considered an implementation detail and must not be relied upon. We -// want `repr(transparent)` but we don't want it to show up in rustdoc, so we hide it under -// `cfg(doc)`. This is an ad-hoc implementation of attribute privacy. -#[cfg_attr(not(doc), repr(transparent))] +// However, `OsStr` layout is considered an implementation detail and must not be relied upon. +#[repr(transparent)] pub struct OsStr { inner: Slice, } diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index 6413b3515ecec..c5edb03bb08be 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -50,7 +50,7 @@ use crate::time::SystemTime; /// } /// ``` /// -/// Read the contents of a file into a [`String`] (you can also use [`read`]): +/// Reads the contents of a file into a [`String`] (you can also use [`read`]): /// /// ```no_run /// use std::fs::File; @@ -229,7 +229,7 @@ pub struct DirBuilder { recursive: bool, } -/// Read the entire contents of a file into a bytes vector. +/// Reads the entire contents of a file into a bytes vector. /// /// This is a convenience function for using [`File::open`] and [`read_to_end`] /// with fewer imports and without an intermediate variable. @@ -268,7 +268,7 @@ pub fn read>(path: P) -> io::Result> { inner(path.as_ref()) } -/// Read the entire contents of a file into a string. +/// Reads the entire contents of a file into a string. /// /// This is a convenience function for using [`File::open`] and [`read_to_string`] /// with fewer imports and without an intermediate variable. @@ -311,7 +311,7 @@ pub fn read_to_string>(path: P) -> io::Result { inner(path.as_ref()) } -/// Write a slice as the entire contents of a file. +/// Writes a slice as the entire contents of a file. /// /// This function will create a file if it does not exist, /// and will entirely replace its contents if it does. @@ -767,7 +767,7 @@ fn buffer_capacity_required(mut file: &File) -> Option { #[stable(feature = "rust1", since = "1.0.0")] impl Read for &File { - /// Read some bytes from the file. + /// Reads some bytes from the file. /// /// See [`Read::read`] docs for more info. /// @@ -835,7 +835,7 @@ impl Read for &File { } #[stable(feature = "rust1", since = "1.0.0")] impl Write for &File { - /// Write some bytes from the file. + /// Writes some bytes from the file. /// /// See [`Write::write`] docs for more info. /// @@ -1526,7 +1526,7 @@ impl FromInner for Metadata { } impl FileTimes { - /// Create a new `FileTimes` with no times set. + /// Creates a new `FileTimes` with no times set. /// /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps. #[stable(feature = "file_set_times", since = "1.75.0")] @@ -2005,7 +2005,7 @@ pub fn remove_file>(path: P) -> io::Result<()> { fs_imp::unlink(path.as_ref()) } -/// Given a path, query the file system to get information about a file, +/// Given a path, queries the file system to get information about a file, /// directory, etc. /// /// This function will traverse symbolic links to query information about the @@ -2044,7 +2044,7 @@ pub fn metadata>(path: P) -> io::Result { fs_imp::stat(path.as_ref()).map(Metadata) } -/// Query the metadata about a file without following symlinks. +/// Queries the metadata about a file without following symlinks. /// /// # Platform-specific behavior /// @@ -2079,7 +2079,7 @@ pub fn symlink_metadata>(path: P) -> io::Result { fs_imp::lstat(path.as_ref()).map(Metadata) } -/// Rename a file or directory to a new name, replacing the original file if +/// Renames a file or directory to a new name, replacing the original file if /// `to` already exists. /// /// This will not work if the new name is on a different mount point. @@ -2400,13 +2400,8 @@ pub fn create_dir>(path: P) -> io::Result<()> { /// /// # Errors /// -/// This function will return an error in the following situations, but is not -/// limited to just these cases: -/// -/// * If any directory in the path specified by `path` -/// does not already exist and it could not be created otherwise. The specific -/// error conditions for when a directory is being created (after it is -/// determined to not exist) are outlined by [`fs::create_dir`]. +/// The function will return an error if any directory specified in path does not exist and +/// could not be created. There may be other error conditions; see [`fs::create_dir`] for specifics. /// /// Notable exception is made for situations where any of the directories /// specified in the `path` could not be created as it was being created concurrently. @@ -2749,7 +2744,7 @@ impl AsInnerMut for DirBuilder { /// ``` /// /// [`Path::exists`]: crate::path::Path::exists -#[stable(feature = "fs_try_exists", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "fs_try_exists", since = "1.81.0")] #[inline] pub fn exists>(path: P) -> io::Result { fs_imp::exists(path.as_ref()) diff --git a/library/std/src/fs/tests.rs b/library/std/src/fs/tests.rs index c1fc2e5488d0c..13028c4c3b57e 100644 --- a/library/std/src/fs/tests.rs +++ b/library/std/src/fs/tests.rs @@ -1,20 +1,11 @@ -use crate::io::prelude::*; - -use crate::env; -use crate::fs::{self, File, FileTimes, OpenOptions}; -use crate::io::{BorrowedBuf, ErrorKind, SeekFrom}; -use crate::mem::MaybeUninit; -use crate::path::Path; -use crate::str; -use crate::sync::Arc; -use crate::sys_common::io::test::{tmpdir, TempDir}; -use crate::thread; -use crate::time::{Duration, Instant, SystemTime}; - use rand::RngCore; #[cfg(target_os = "macos")] use crate::ffi::{c_char, c_int}; +use crate::fs::{self, File, FileTimes, OpenOptions}; +use crate::io::prelude::*; +use crate::io::{BorrowedBuf, ErrorKind, SeekFrom}; +use crate::mem::MaybeUninit; #[cfg(unix)] use crate::os::unix::fs::symlink as symlink_dir; #[cfg(unix)] @@ -23,8 +14,13 @@ use crate::os::unix::fs::symlink as symlink_file; use crate::os::unix::fs::symlink as junction_point; #[cfg(windows)] use crate::os::windows::fs::{junction_point, symlink_dir, symlink_file, OpenOptionsExt}; +use crate::path::Path; +use crate::sync::Arc; #[cfg(target_os = "macos")] use crate::sys::weak::weak; +use crate::sys_common::io::test::{tmpdir, TempDir}; +use crate::time::{Duration, Instant, SystemTime}; +use crate::{env, str, thread}; macro_rules! check { ($e:expr) => { @@ -1514,7 +1510,9 @@ fn symlink_hard_link() { #[test] #[cfg(windows)] fn create_dir_long_paths() { - use crate::{ffi::OsStr, iter, os::windows::ffi::OsStrExt}; + use crate::ffi::OsStr; + use crate::iter; + use crate::os::windows::ffi::OsStrExt; const PATH_LEN: usize = 247; let tmpdir = tmpdir(); diff --git a/library/std/src/hash/random.rs b/library/std/src/hash/random.rs index 0adf91e14ac6e..8ef45172eac40 100644 --- a/library/std/src/hash/random.rs +++ b/library/std/src/hash/random.rs @@ -10,8 +10,7 @@ #[allow(deprecated)] use super::{BuildHasher, Hasher, SipHasher13}; use crate::cell::Cell; -use crate::fmt; -use crate::sys; +use crate::{fmt, sys}; /// `RandomState` is the default state for [`HashMap`] types. /// diff --git a/library/std/src/io/buffered/bufreader.rs b/library/std/src/io/buffered/bufreader.rs index 0cdc49c87d8fc..f11dd50c5e2b7 100644 --- a/library/std/src/io/buffered/bufreader.rs +++ b/library/std/src/io/buffered/bufreader.rs @@ -1,11 +1,12 @@ mod buffer; +use buffer::Buffer; + use crate::fmt; use crate::io::{ self, uninlined_slow_read_byte, BorrowedCursor, BufRead, IoSliceMut, Read, Seek, SeekFrom, SizeHint, SpecReadByte, DEFAULT_BUF_SIZE, }; -use buffer::Buffer; /// The `BufReader` struct adds buffering to any reader. /// diff --git a/library/std/src/io/buffered/bufwriter.rs b/library/std/src/io/buffered/bufwriter.rs index a8680e9b6ead1..21650d467446e 100644 --- a/library/std/src/io/buffered/bufwriter.rs +++ b/library/std/src/io/buffered/bufwriter.rs @@ -1,10 +1,8 @@ -use crate::error; -use crate::fmt; use crate::io::{ self, ErrorKind, IntoInnerError, IoSlice, Seek, SeekFrom, Write, DEFAULT_BUF_SIZE, }; use crate::mem::{self, ManuallyDrop}; -use crate::ptr; +use crate::{error, fmt, ptr}; /// Wraps a writer and buffers its output. /// diff --git a/library/std/src/io/buffered/linewriter.rs b/library/std/src/io/buffered/linewriter.rs index 3d4ae70419322..cc6921b86dd0b 100644 --- a/library/std/src/io/buffered/linewriter.rs +++ b/library/std/src/io/buffered/linewriter.rs @@ -1,5 +1,6 @@ use crate::fmt; -use crate::io::{self, buffered::LineWriterShim, BufWriter, IntoInnerError, IoSlice, Write}; +use crate::io::buffered::LineWriterShim; +use crate::io::{self, BufWriter, IntoInnerError, IoSlice, Write}; /// Wraps a writer and buffers output to it, flushing whenever a newline /// (`0x0a`, `'\n'`) is detected. diff --git a/library/std/src/io/buffered/linewritershim.rs b/library/std/src/io/buffered/linewritershim.rs index c3ac7855d4450..3d04ccd1c7d81 100644 --- a/library/std/src/io/buffered/linewritershim.rs +++ b/library/std/src/io/buffered/linewritershim.rs @@ -1,7 +1,9 @@ -use crate::io::{self, BufWriter, IoSlice, Write}; use core::slice::memchr; +use crate::io::{self, BufWriter, IoSlice, Write}; + /// Private helper struct for implementing the line-buffered writing logic. +/// /// This shim temporarily wraps a BufWriter, and uses its internals to /// implement a line-buffered writer (specifically by using the internal /// methods like write_to_buf and flush_buf). In this way, a more @@ -20,27 +22,27 @@ impl<'a, W: ?Sized + Write> LineWriterShim<'a, W> { Self { buffer } } - /// Get a reference to the inner writer (that is, the writer + /// Gets a reference to the inner writer (that is, the writer /// wrapped by the BufWriter). fn inner(&self) -> &W { self.buffer.get_ref() } - /// Get a mutable reference to the inner writer (that is, the writer + /// Gets a mutable reference to the inner writer (that is, the writer /// wrapped by the BufWriter). Be careful with this writer, as writes to /// it will bypass the buffer. fn inner_mut(&mut self) -> &mut W { self.buffer.get_mut() } - /// Get the content currently buffered in self.buffer + /// Gets the content currently buffered in self.buffer fn buffered(&self) -> &[u8] { self.buffer.buffer() } - /// Flush the buffer iff the last byte is a newline (indicating that an + /// Flushes the buffer iff the last byte is a newline (indicating that an /// earlier write only succeeded partially, and we want to retry flushing - /// the buffered line before continuing with a subsequent write) + /// the buffered line before continuing with a subsequent write). fn flush_if_completed_line(&mut self) -> io::Result<()> { match self.buffered().last().copied() { Some(b'\n') => self.buffer.flush_buf(), @@ -50,10 +52,11 @@ impl<'a, W: ?Sized + Write> LineWriterShim<'a, W> { } impl<'a, W: ?Sized + Write> Write for LineWriterShim<'a, W> { - /// Write some data into this BufReader with line buffering. This means - /// that, if any newlines are present in the data, the data up to the last - /// newline is sent directly to the underlying writer, and data after it - /// is buffered. Returns the number of bytes written. + /// Writes some data into this BufReader with line buffering. + /// + /// This means that, if any newlines are present in the data, the data up to + /// the last newline is sent directly to the underlying writer, and data + /// after it is buffered. Returns the number of bytes written. /// /// This function operates on a "best effort basis"; in keeping with the /// convention of `Write::write`, it makes at most one attempt to write @@ -136,11 +139,12 @@ impl<'a, W: ?Sized + Write> Write for LineWriterShim<'a, W> { self.buffer.flush() } - /// Write some vectored data into this BufReader with line buffering. This - /// means that, if any newlines are present in the data, the data up to - /// and including the buffer containing the last newline is sent directly - /// to the inner writer, and the data after it is buffered. Returns the - /// number of bytes written. + /// Writes some vectored data into this BufReader with line buffering. + /// + /// This means that, if any newlines are present in the data, the data up to + /// and including the buffer containing the last newline is sent directly to + /// the inner writer, and the data after it is buffered. Returns the number + /// of bytes written. /// /// This function operates on a "best effort basis"; in keeping with the /// convention of `Write::write`, it makes at most one attempt to write @@ -245,10 +249,11 @@ impl<'a, W: ?Sized + Write> Write for LineWriterShim<'a, W> { self.inner().is_write_vectored() } - /// Write some data into this BufReader with line buffering. This means - /// that, if any newlines are present in the data, the data up to the last - /// newline is sent directly to the underlying writer, and data after it - /// is buffered. + /// Writes some data into this BufReader with line buffering. + /// + /// This means that, if any newlines are present in the data, the data up to + /// the last newline is sent directly to the underlying writer, and data + /// after it is buffered. /// /// Because this function attempts to send completed lines to the underlying /// writer, it will also flush the existing buffer if it contains any diff --git a/library/std/src/io/buffered/mod.rs b/library/std/src/io/buffered/mod.rs index 100dab1e2493c..475d877528f7f 100644 --- a/library/std/src/io/buffered/mod.rs +++ b/library/std/src/io/buffered/mod.rs @@ -8,16 +8,14 @@ mod linewritershim; #[cfg(test)] mod tests; -use crate::error; -use crate::fmt; -use crate::io::Error; +#[stable(feature = "bufwriter_into_parts", since = "1.56.0")] +pub use bufwriter::WriterPanicked; +use linewritershim::LineWriterShim; #[stable(feature = "rust1", since = "1.0.0")] pub use self::{bufreader::BufReader, bufwriter::BufWriter, linewriter::LineWriter}; -use linewritershim::LineWriterShim; - -#[stable(feature = "bufwriter_into_parts", since = "1.56.0")] -pub use bufwriter::WriterPanicked; +use crate::io::Error; +use crate::{error, fmt}; /// An error returned by [`BufWriter::into_inner`] which combines an error that /// happened while writing out the buffer, and the buffered writer object @@ -48,7 +46,7 @@ pub use bufwriter::WriterPanicked; pub struct IntoInnerError(W, Error); impl IntoInnerError { - /// Construct a new IntoInnerError + /// Constructs a new IntoInnerError fn new(writer: W, error: Error) -> Self { Self(writer, error) } diff --git a/library/std/src/io/buffered/tests.rs b/library/std/src/io/buffered/tests.rs index ab66deaf31d22..d89ecd317d6ee 100644 --- a/library/std/src/io/buffered/tests.rs +++ b/library/std/src/io/buffered/tests.rs @@ -3,9 +3,8 @@ use crate::io::{ self, BorrowedBuf, BufReader, BufWriter, ErrorKind, IoSlice, LineWriter, SeekFrom, }; use crate::mem::MaybeUninit; -use crate::panic; use crate::sync::atomic::{AtomicUsize, Ordering}; -use crate::thread; +use crate::{panic, thread}; /// A dummy reader intended at testing short-reads propagation. pub struct ShortReader { diff --git a/library/std/src/io/copy/tests.rs b/library/std/src/io/copy/tests.rs index a1f909a3c5386..7e08826a7e1d8 100644 --- a/library/std/src/io/copy/tests.rs +++ b/library/std/src/io/copy/tests.rs @@ -119,13 +119,12 @@ fn copy_specializes_from_slice() { #[cfg(unix)] mod io_benches { - use crate::fs::File; - use crate::fs::OpenOptions; + use test::Bencher; + + use crate::fs::{File, OpenOptions}; use crate::io::prelude::*; use crate::io::BufReader; - use test::Bencher; - #[bench] fn bench_copy_buf_reader(b: &mut Bencher) { let mut file_in = File::open("/dev/zero").expect("opening /dev/zero failed"); diff --git a/library/std/src/io/cursor.rs b/library/std/src/io/cursor.rs index 2ed64a40495ef..9f913eae09544 100644 --- a/library/std/src/io/cursor.rs +++ b/library/std/src/io/cursor.rs @@ -1,10 +1,9 @@ #[cfg(test)] mod tests; -use crate::io::prelude::*; - use crate::alloc::Allocator; use crate::cmp; +use crate::io::prelude::*; use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut, SeekFrom}; /// A `Cursor` wraps an in-memory buffer and provides it with a @@ -210,55 +209,60 @@ impl Cursor where T: AsRef<[u8]>, { - /// Returns the remaining slice. + /// Splits the underlying slice at the cursor position and returns them. /// /// # Examples /// /// ``` - /// #![feature(cursor_remaining)] + /// #![feature(cursor_split)] /// use std::io::Cursor; /// /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); /// - /// assert_eq!(buff.remaining_slice(), &[1, 2, 3, 4, 5]); + /// assert_eq!(buff.split(), ([].as_slice(), [1, 2, 3, 4, 5].as_slice())); /// /// buff.set_position(2); - /// assert_eq!(buff.remaining_slice(), &[3, 4, 5]); - /// - /// buff.set_position(4); - /// assert_eq!(buff.remaining_slice(), &[5]); + /// assert_eq!(buff.split(), ([1, 2].as_slice(), [3, 4, 5].as_slice())); /// /// buff.set_position(6); - /// assert_eq!(buff.remaining_slice(), &[]); + /// assert_eq!(buff.split(), ([1, 2, 3, 4, 5].as_slice(), [].as_slice())); /// ``` - #[unstable(feature = "cursor_remaining", issue = "86369")] - pub fn remaining_slice(&self) -> &[u8] { - let len = self.pos.min(self.inner.as_ref().len() as u64); - &self.inner.as_ref()[(len as usize)..] + #[unstable(feature = "cursor_split", issue = "86369")] + pub fn split(&self) -> (&[u8], &[u8]) { + let slice = self.inner.as_ref(); + let pos = self.pos.min(slice.len() as u64); + slice.split_at(pos as usize) } +} - /// Returns `true` if the remaining slice is empty. +impl Cursor +where + T: AsMut<[u8]>, +{ + /// Splits the underlying slice at the cursor position and returns them + /// mutably. /// /// # Examples /// /// ``` - /// #![feature(cursor_remaining)] + /// #![feature(cursor_split)] /// use std::io::Cursor; /// /// let mut buff = Cursor::new(vec![1, 2, 3, 4, 5]); /// - /// buff.set_position(2); - /// assert!(!buff.is_empty()); + /// assert_eq!(buff.split_mut(), ([].as_mut_slice(), [1, 2, 3, 4, 5].as_mut_slice())); /// - /// buff.set_position(5); - /// assert!(buff.is_empty()); + /// buff.set_position(2); + /// assert_eq!(buff.split_mut(), ([1, 2].as_mut_slice(), [3, 4, 5].as_mut_slice())); /// - /// buff.set_position(10); - /// assert!(buff.is_empty()); + /// buff.set_position(6); + /// assert_eq!(buff.split_mut(), ([1, 2, 3, 4, 5].as_mut_slice(), [].as_mut_slice())); /// ``` - #[unstable(feature = "cursor_remaining", issue = "86369")] - pub fn is_empty(&self) -> bool { - self.pos >= self.inner.as_ref().len() as u64 + #[unstable(feature = "cursor_split", issue = "86369")] + pub fn split_mut(&mut self) -> (&mut [u8], &mut [u8]) { + let slice = self.inner.as_mut(); + let pos = self.pos.min(slice.len() as u64); + slice.split_at_mut(pos as usize) } } @@ -320,7 +324,7 @@ where T: AsRef<[u8]>, { fn read(&mut self, buf: &mut [u8]) -> io::Result { - let n = Read::read(&mut self.remaining_slice(), buf)?; + let n = Read::read(&mut Cursor::split(self).1, buf)?; self.pos += n as u64; Ok(n) } @@ -328,7 +332,7 @@ where fn read_buf(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> { let prev_written = cursor.written(); - Read::read_buf(&mut self.remaining_slice(), cursor.reborrow())?; + Read::read_buf(&mut Cursor::split(self).1, cursor.reborrow())?; self.pos += (cursor.written() - prev_written) as u64; @@ -352,7 +356,7 @@ where } fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { - let result = Read::read_exact(&mut self.remaining_slice(), buf); + let result = Read::read_exact(&mut Cursor::split(self).1, buf); match result { Ok(_) => self.pos += buf.len() as u64, @@ -366,14 +370,14 @@ where fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> { let prev_written = cursor.written(); - let result = Read::read_buf_exact(&mut self.remaining_slice(), cursor.reborrow()); + let result = Read::read_buf_exact(&mut Cursor::split(self).1, cursor.reborrow()); self.pos += (cursor.written() - prev_written) as u64; result } fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { - let content = self.remaining_slice(); + let content = Cursor::split(self).1; let len = content.len(); buf.try_reserve(len)?; buf.extend_from_slice(content); @@ -384,7 +388,7 @@ where fn read_to_string(&mut self, buf: &mut String) -> io::Result { let content = - crate::str::from_utf8(self.remaining_slice()).map_err(|_| io::Error::INVALID_UTF8)?; + crate::str::from_utf8(Cursor::split(self).1).map_err(|_| io::Error::INVALID_UTF8)?; let len = content.len(); buf.try_reserve(len)?; buf.push_str(content); @@ -400,7 +404,7 @@ where T: AsRef<[u8]>, { fn fill_buf(&mut self) -> io::Result<&[u8]> { - Ok(self.remaining_slice()) + Ok(Cursor::split(self).1) } fn consume(&mut self, amt: usize) { self.pos += amt as u64; diff --git a/library/std/src/io/error.rs b/library/std/src/io/error.rs index 8de27367a3f21..e8ae1d99fbf37 100644 --- a/library/std/src/io/error.rs +++ b/library/std/src/io/error.rs @@ -11,10 +11,7 @@ mod repr_unpacked; #[cfg(any(not(target_pointer_width = "64"), target_os = "uefi"))] use repr_unpacked::Repr; -use crate::error; -use crate::fmt; -use crate::result; -use crate::sys; +use crate::{error, fmt, result, sys}; /// A specialized [`Result`] type for I/O operations. /// @@ -167,7 +164,7 @@ impl SimpleMessage { } } -/// Create and return an `io::Error` for a given `ErrorKind` and constant +/// Creates and returns an `io::Error` for a given `ErrorKind` and constant /// message. This doesn't allocate. pub(crate) macro const_io_error($kind:expr, $message:expr $(,)?) { $crate::io::error::Error::from_static_message({ @@ -852,7 +849,7 @@ impl Error { } } - /// Attempt to downcast the custom boxed error to `E`. + /// Attempts to downcast the custom boxed error to `E`. /// /// If this [`Error`] contains a custom boxed error, /// then it would attempt downcasting on the boxed error, diff --git a/library/std/src/io/error/repr_bitpacked.rs b/library/std/src/io/error/repr_bitpacked.rs index fbb74967df3f1..9d3ade46bd929 100644 --- a/library/std/src/io/error/repr_bitpacked.rs +++ b/library/std/src/io/error/repr_bitpacked.rs @@ -102,10 +102,11 @@ //! to use a pointer type to store something that may hold an integer, some of //! the time. -use super::{Custom, ErrorData, ErrorKind, RawOsError, SimpleMessage}; use core::marker::PhantomData; use core::ptr::{self, NonNull}; +use super::{Custom, ErrorData, ErrorKind, RawOsError, SimpleMessage}; + // The 2 least-significant bits are used as tag. const TAG_MASK: usize = 0b11; const TAG_SIMPLE_MESSAGE: usize = 0b00; diff --git a/library/std/src/io/error/tests.rs b/library/std/src/io/error/tests.rs index fc6db2825e811..064e2e36b7a1d 100644 --- a/library/std/src/io/error/tests.rs +++ b/library/std/src/io/error/tests.rs @@ -1,10 +1,9 @@ use super::{const_io_error, Custom, Error, ErrorData, ErrorKind, Repr, SimpleMessage}; use crate::assert_matches::assert_matches; -use crate::error; -use crate::fmt; use crate::mem::size_of; use crate::sys::decode_error_kind; use crate::sys::os::error_string; +use crate::{error, fmt}; #[test] fn test_size() { @@ -95,7 +94,8 @@ fn test_errorkind_packing() { #[test] fn test_simple_message_packing() { - use super::{ErrorKind::*, SimpleMessage}; + use super::ErrorKind::*; + use super::SimpleMessage; macro_rules! check_simple_msg { ($err:expr, $kind:ident, $msg:literal) => {{ let e = &$err; diff --git a/library/std/src/io/impls.rs b/library/std/src/io/impls.rs index a8a2e9413e11c..85023540a816f 100644 --- a/library/std/src/io/impls.rs +++ b/library/std/src/io/impls.rs @@ -2,12 +2,9 @@ mod tests; use crate::alloc::Allocator; -use crate::cmp; use crate::collections::VecDeque; -use crate::fmt; use crate::io::{self, BorrowedCursor, BufRead, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write}; -use crate::mem; -use crate::str; +use crate::{cmp, fmt, mem, str}; // ============================================================================= // Forwarding implementations diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index 1345a30361e28..644b294db8da1 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -297,15 +297,12 @@ #[cfg(test)] mod tests; -use crate::cmp; -use crate::fmt; -use crate::mem::take; -use crate::ops::{Deref, DerefMut}; -use crate::slice; -use crate::str; -use crate::sys; +#[unstable(feature = "read_buf", issue = "78485")] +pub use core::io::{BorrowedBuf, BorrowedCursor}; use core::slice::memchr; +pub(crate) use error::const_io_error; + #[stable(feature = "bufwriter_into_parts", since = "1.56.0")] pub use self::buffered::WriterPanicked; #[unstable(feature = "raw_os_error_ty", issue = "107792")] @@ -328,10 +325,9 @@ pub use self::{ stdio::{stderr, stdin, stdout, Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock}, util::{empty, repeat, sink, Empty, Repeat, Sink}, }; - -#[unstable(feature = "read_buf", issue = "78485")] -pub use core::io::{BorrowedBuf, BorrowedCursor}; -pub(crate) use error::const_io_error; +use crate::mem::take; +use crate::ops::{Deref, DerefMut}; +use crate::{cmp, fmt, slice, str, sys}; mod buffered; pub(crate) mod copy; @@ -782,7 +778,7 @@ pub trait Read { false } - /// Read all bytes until EOF in this source, placing them into `buf`. + /// Reads all bytes until EOF in this source, placing them into `buf`. /// /// All bytes read from this source will be appended to the specified buffer /// `buf`. This function will continuously call [`read()`] to append more data to @@ -866,7 +862,7 @@ pub trait Read { default_read_to_end(self, buf, None) } - /// Read all bytes until EOF in this source, appending them to `buf`. + /// Reads all bytes until EOF in this source, appending them to `buf`. /// /// If successful, this function returns the number of bytes which were read /// and appended to `buf`. @@ -909,7 +905,7 @@ pub trait Read { default_read_to_string(self, buf, None) } - /// Read the exact number of bytes required to fill `buf`. + /// Reads the exact number of bytes required to fill `buf`. /// /// This function reads as many bytes as necessary to completely fill the /// specified buffer `buf`. @@ -973,7 +969,7 @@ pub trait Read { default_read_buf(|b| self.read(b), buf) } - /// Read the exact number of bytes required to fill `cursor`. + /// Reads the exact number of bytes required to fill `cursor`. /// /// This is similar to the [`read_exact`](Read::read_exact) method, except /// that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use @@ -1159,7 +1155,7 @@ pub trait Read { } } -/// Read all bytes from a [reader][Read] into a new [`String`]. +/// Reads all bytes from a [reader][Read] into a new [`String`]. /// /// This is a convenience function for [`Read::read_to_string`]. Using this /// function avoids having to create a variable first and provides more type @@ -1212,7 +1208,7 @@ pub fn read_to_string(mut reader: R) -> Result { /// A buffer type used with `Read::read_vectored`. /// -/// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be +/// It is semantically a wrapper around a `&mut [u8]`, but is guaranteed to be /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on /// Windows. #[stable(feature = "iovec", since = "1.36.0")] @@ -1266,7 +1262,7 @@ impl<'a> IoSliceMut<'a> { /// buf.advance(3); /// assert_eq!(buf.deref(), [1; 5].as_ref()); /// ``` - #[stable(feature = "io_slice_advance", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "io_slice_advance", since = "1.81.0")] #[inline] pub fn advance(&mut self, n: usize) { self.0.advance(n) @@ -1305,7 +1301,7 @@ impl<'a> IoSliceMut<'a> { /// assert_eq!(bufs[0].deref(), [2; 14].as_ref()); /// assert_eq!(bufs[1].deref(), [3; 8].as_ref()); /// ``` - #[stable(feature = "io_slice_advance", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "io_slice_advance", since = "1.81.0")] #[inline] pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) { // Number of buffers to remove. @@ -1406,7 +1402,7 @@ impl<'a> IoSlice<'a> { /// buf.advance(3); /// assert_eq!(buf.deref(), [1; 5].as_ref()); /// ``` - #[stable(feature = "io_slice_advance", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "io_slice_advance", since = "1.81.0")] #[inline] pub fn advance(&mut self, n: usize) { self.0.advance(n) @@ -1444,7 +1440,7 @@ impl<'a> IoSlice<'a> { /// IoSlice::advance_slices(&mut bufs, 10); /// assert_eq!(bufs[0].deref(), [2; 14].as_ref()); /// assert_eq!(bufs[1].deref(), [3; 8].as_ref()); - #[stable(feature = "io_slice_advance", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "io_slice_advance", since = "1.81.0")] #[inline] pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) { // Number of buffers to remove. @@ -1531,7 +1527,7 @@ impl<'a> Deref for IoSlice<'a> { #[doc(notable_trait)] #[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")] pub trait Write { - /// Write a buffer into this writer, returning how many bytes were written. + /// Writes a buffer into this writer, returning how many bytes were written. /// /// This function will attempt to write the entire contents of `buf`, but /// the entire write might not succeed, or the write may also generate an @@ -1630,7 +1626,7 @@ pub trait Write { false } - /// Flush this output stream, ensuring that all intermediately buffered + /// Flushes this output stream, ensuring that all intermediately buffered /// contents reach their destination. /// /// # Errors @@ -2247,7 +2243,7 @@ pub trait BufRead: Read { #[stable(feature = "rust1", since = "1.0.0")] fn consume(&mut self, amt: usize); - /// Check if the underlying `Read` has any data left to be read. + /// Checks if the underlying `Read` has any data left to be read. /// /// This function may fill the buffer to check for data, /// so this functions returns `Result`, not `bool`. @@ -2278,7 +2274,7 @@ pub trait BufRead: Read { self.fill_buf().map(|b| !b.is_empty()) } - /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached. + /// Reads all bytes into `buf` until the delimiter `byte` or EOF is reached. /// /// This function will read bytes from the underlying stream until the /// delimiter or EOF is found. Once found, all bytes up to, and including, @@ -2337,7 +2333,7 @@ pub trait BufRead: Read { read_until(self, byte, buf) } - /// Skip all bytes until the delimiter `byte` or EOF is reached. + /// Skips all bytes until the delimiter `byte` or EOF is reached. /// /// This function will read (and discard) bytes from the underlying stream until the /// delimiter or EOF is found. @@ -2399,7 +2395,7 @@ pub trait BufRead: Read { skip_until(self, byte) } - /// Read all bytes until a newline (the `0xA` byte) is reached, and append + /// Reads all bytes until a newline (the `0xA` byte) is reached, and append /// them to the provided `String` buffer. /// /// Previous content of the buffer will be preserved. To avoid appending to @@ -3038,7 +3034,7 @@ where } } -/// Read a single byte in a slow, generic way. This is used by the default +/// Reads a single byte in a slow, generic way. This is used by the default /// `spec_read_byte`. #[inline] fn inlined_slow_read_byte(reader: &mut R) -> Option> { diff --git a/library/std/src/io/stdio.rs b/library/std/src/io/stdio.rs index 9aee2bb5e1c5c..6de069a518e3d 100644 --- a/library/std/src/io/stdio.rs +++ b/library/std/src/io/stdio.rs @@ -3,11 +3,10 @@ #[cfg(test)] mod tests; -use crate::io::prelude::*; - use crate::cell::{Cell, RefCell}; use crate::fmt; use crate::fs::File; +use crate::io::prelude::*; use crate::io::{ self, BorrowedCursor, BufReader, IoSlice, IoSliceMut, LineWriter, Lines, SpecReadByte, }; @@ -1092,7 +1091,7 @@ pub fn try_set_output_capture( OUTPUT_CAPTURE.try_with(move |slot| slot.replace(sink)) } -/// Write `args` to the capture buffer if enabled and possible, or `global_s` +/// Writes `args` to the capture buffer if enabled and possible, or `global_s` /// otherwise. `label` identifies the stream in a panic message. /// /// This function is used to print error messages, so it takes extra diff --git a/library/std/src/io/tests.rs b/library/std/src/io/tests.rs index a2c1c430863ab..bb6a53bb290f9 100644 --- a/library/std/src/io/tests.rs +++ b/library/std/src/io/tests.rs @@ -1,7 +1,8 @@ use super::{repeat, BorrowedBuf, Cursor, SeekFrom}; use crate::cmp::{self, min}; -use crate::io::{self, IoSlice, IoSliceMut, DEFAULT_BUF_SIZE}; -use crate::io::{BufRead, BufReader, Read, Seek, Write}; +use crate::io::{ + self, BufRead, BufReader, IoSlice, IoSliceMut, Read, Seek, Write, DEFAULT_BUF_SIZE, +}; use crate::mem::MaybeUninit; use crate::ops::Deref; @@ -530,7 +531,7 @@ fn io_slice_advance_slices_beyond_total_length() { assert!(bufs.is_empty()); } -/// Create a new writer that reads from at most `n_bufs` and reads +/// Creates a new writer that reads from at most `n_bufs` and reads /// `per_call` bytes (in total) per call to write. fn test_writer(n_bufs: usize, per_call: usize) -> TestWriter { TestWriter { n_bufs, per_call, written: Vec::new() } @@ -675,13 +676,13 @@ fn cursor_read_exact_eof() { let mut r = slice.clone(); assert!(r.read_exact(&mut [0; 10]).is_err()); - assert!(r.is_empty()); + assert!(Cursor::split(&r).1.is_empty()); let mut r = slice; let buf = &mut [0; 10]; let mut buf = BorrowedBuf::from(buf.as_mut_slice()); assert!(r.read_buf_exact(buf.unfilled()).is_err()); - assert!(r.is_empty()); + assert!(Cursor::split(&r).1.is_empty()); assert_eq!(buf.filled(), b"123456"); } diff --git a/library/std/src/io/util/tests.rs b/library/std/src/io/util/tests.rs index 6de91e29c7707..1dff3f3832bd7 100644 --- a/library/std/src/io/util/tests.rs +++ b/library/std/src/io/util/tests.rs @@ -1,6 +1,5 @@ use crate::io::prelude::*; use crate::io::{empty, repeat, sink, BorrowedBuf, Empty, Repeat, SeekFrom, Sink}; - use crate::mem::MaybeUninit; #[test] diff --git a/library/std/src/keyword_docs.rs b/library/std/src/keyword_docs.rs index 8415f36eba251..c82228fca4bcf 100644 --- a/library/std/src/keyword_docs.rs +++ b/library/std/src/keyword_docs.rs @@ -1175,7 +1175,7 @@ mod ref_keyword {} #[doc(keyword = "return")] // -/// Return a value from a function. +/// Returns a value from a function. /// /// A `return` marks the end of an execution path in a function: /// @@ -2310,7 +2310,7 @@ mod where_keyword {} #[doc(alias = "promise")] #[doc(keyword = "async")] // -/// Return a [`Future`] instead of blocking the current thread. +/// Returns a [`Future`] instead of blocking the current thread. /// /// Use `async` in front of `fn`, `closure`, or a `block` to turn the marked code into a `Future`. /// As such the code will not be run immediately, but will only be evaluated when the returned diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 9fba657d116de..05e33d47bac39 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -254,6 +254,7 @@ #![deny(fuzzy_provenance_casts)] #![deny(unsafe_op_in_unsafe_fn)] #![allow(rustdoc::redundant_explicit_links)] +#![warn(rustdoc::unescaped_backticks)] // Ensure that std can be linked against panic_abort despite compiled with `-C panic=unwind` #![deny(ffi_unwind_calls)] // std may use features in a platform-specific way @@ -268,14 +269,9 @@ #![cfg_attr(any(windows, target_os = "uefi"), feature(round_char_boundary))] #![cfg_attr(target_family = "wasm", feature(stdarch_wasm_atomic_wait))] #![cfg_attr(target_arch = "wasm64", feature(simd_wasm64))] -#![cfg_attr( - all(any(target_arch = "x86_64", target_arch = "x86"), target_os = "uefi"), - feature(stdarch_x86_has_cpuid) -)] // // Language features: // tidy-alphabetical-start -#![cfg_attr(bootstrap, feature(c_unwind))] #![feature(alloc_error_handler)] #![feature(allocator_internals)] #![feature(allow_internal_unsafe)] @@ -302,6 +298,7 @@ #![feature(let_chains)] #![feature(link_cfg)] #![feature(linkage)] +#![feature(macro_metavar_expr_concat)] #![feature(min_exhaustive_patterns)] #![feature(min_specialization)] #![feature(must_not_suspend)] @@ -407,7 +404,6 @@ #![feature(const_ip)] #![feature(const_ipv4)] #![feature(const_ipv6)] -#![feature(const_waker)] #![feature(thread_local_internals)] // tidy-alphabetical-end // @@ -471,24 +467,6 @@ pub mod rt; // The Rust prelude pub mod prelude; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::borrow; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::boxed; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::fmt; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::format; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::rc; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::slice; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::str; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::string; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::vec; #[stable(feature = "rust1", since = "1.0.0")] pub use core::any; #[stable(feature = "core_array", since = "1.36.0")] @@ -566,6 +544,25 @@ pub use core::u8; #[allow(deprecated, deprecated_in_future)] pub use core::usize; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::borrow; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::boxed; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::fmt; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::format; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::rc; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::slice; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::str; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::string; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::vec; + #[unstable(feature = "f128", issue = "116909")] pub mod f128; #[unstable(feature = "f16", issue = "116909")] @@ -609,23 +606,23 @@ mod std_float; pub mod simd { #![doc = include_str!("../../portable-simd/crates/core_simd/src/core_simd_docs.md")] - #[doc(inline)] - pub use crate::std_float::StdFloat; #[doc(inline)] pub use core::simd::*; + + #[doc(inline)] + pub use crate::std_float::StdFloat; } #[stable(feature = "futures_api", since = "1.36.0")] pub mod task { //! Types and Traits for working with asynchronous tasks. - #[doc(inline)] - #[stable(feature = "futures_api", since = "1.36.0")] - pub use core::task::*; - #[doc(inline)] #[stable(feature = "wake_trait", since = "1.51.0")] pub use alloc::task::*; + #[doc(inline)] + #[stable(feature = "futures_api", since = "1.36.0")] + pub use core::task::*; } #[doc = include_str!("../../stdarch/crates/core_arch/src/core_arch_docs.md")] @@ -670,35 +667,31 @@ mod panicking; #[allow(dead_code, unused_attributes, fuzzy_provenance_casts, unsafe_op_in_unsafe_fn)] mod backtrace_rs; -// Re-export macros defined in core. -#[stable(feature = "rust1", since = "1.0.0")] -#[allow(deprecated, deprecated_in_future)] -pub use core::{ - assert_eq, assert_ne, debug_assert, debug_assert_eq, debug_assert_ne, matches, todo, r#try, - unimplemented, unreachable, write, writeln, -}; - -// Re-export built-in macros defined through core. -#[stable(feature = "builtin_macro_prelude", since = "1.38.0")] -#[allow(deprecated)] -pub use core::{ - assert, assert_matches, cfg, column, compile_error, concat, concat_idents, const_format_args, - env, file, format_args, format_args_nl, include, include_bytes, include_str, line, log_syntax, - module_path, option_env, stringify, trace_macros, -}; - +#[unstable(feature = "cfg_match", issue = "115585")] +pub use core::cfg_match; #[unstable( feature = "concat_bytes", issue = "87555", reason = "`concat_bytes` is not stable enough for use and is subject to change" )] pub use core::concat_bytes; - -#[unstable(feature = "cfg_match", issue = "115585")] -pub use core::cfg_match; - #[stable(feature = "core_primitive", since = "1.43.0")] pub use core::primitive; +// Re-export built-in macros defined through core. +#[stable(feature = "builtin_macro_prelude", since = "1.38.0")] +#[allow(deprecated)] +pub use core::{ + assert, assert_matches, cfg, column, compile_error, concat, concat_idents, const_format_args, + env, file, format_args, format_args_nl, include, include_bytes, include_str, line, log_syntax, + module_path, option_env, stringify, trace_macros, +}; +// Re-export macros defined in core. +#[stable(feature = "rust1", since = "1.0.0")] +#[allow(deprecated, deprecated_in_future)] +pub use core::{ + assert_eq, assert_ne, debug_assert, debug_assert_eq, debug_assert_ne, matches, todo, r#try, + unimplemented, unreachable, write, writeln, +}; // Include a number of private modules that exist solely to provide // the rustdoc documentation for primitive types. Using `include!` diff --git a/library/std/src/net/ip_addr.rs b/library/std/src/net/ip_addr.rs index e167fbd1b9cf8..8a9426b61f999 100644 --- a/library/std/src/net/ip_addr.rs +++ b/library/std/src/net/ip_addr.rs @@ -2,17 +2,15 @@ #[cfg(all(test, not(target_os = "emscripten")))] mod tests; -use crate::sys::net::netc as c; -use crate::sys_common::{FromInner, IntoInner}; - #[stable(feature = "ip_addr", since = "1.7.0")] pub use core::net::IpAddr; - +#[unstable(feature = "ip", issue = "27709")] +pub use core::net::Ipv6MulticastScope; #[stable(feature = "rust1", since = "1.0.0")] pub use core::net::{Ipv4Addr, Ipv6Addr}; -#[unstable(feature = "ip", issue = "27709")] -pub use core::net::Ipv6MulticastScope; +use crate::sys::net::netc as c; +use crate::sys_common::{FromInner, IntoInner}; impl IntoInner for Ipv4Addr { #[inline] diff --git a/library/std/src/net/mod.rs b/library/std/src/net/mod.rs index 858776f14466a..3b19c743b1e24 100644 --- a/library/std/src/net/mod.rs +++ b/library/std/src/net/mod.rs @@ -21,7 +21,8 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::io::{self, ErrorKind}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::net::AddrParseError; #[stable(feature = "rust1", since = "1.0.0")] pub use self::ip_addr::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope}; @@ -33,8 +34,7 @@ pub use self::tcp::IntoIncoming; pub use self::tcp::{Incoming, TcpListener, TcpStream}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::udp::UdpSocket; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::net::AddrParseError; +use crate::io::{self, ErrorKind}; mod ip_addr; mod socket_addr; diff --git a/library/std/src/net/socket_addr.rs b/library/std/src/net/socket_addr.rs index 421fed9077c5b..84922aabdb569 100644 --- a/library/std/src/net/socket_addr.rs +++ b/library/std/src/net/socket_addr.rs @@ -2,19 +2,14 @@ #[cfg(all(test, not(target_os = "emscripten")))] mod tests; -use crate::io; -use crate::iter; -use crate::mem; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::net::{SocketAddr, SocketAddrV4, SocketAddrV6}; + use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -use crate::option; -use crate::slice; use crate::sys::net::netc as c; use crate::sys_common::net::LookupHost; use crate::sys_common::{FromInner, IntoInner}; -use crate::vec; - -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::net::{SocketAddr, SocketAddrV4, SocketAddrV6}; +use crate::{io, iter, mem, option, slice, vec}; impl FromInner for SocketAddrV4 { fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 { diff --git a/library/std/src/net/tcp.rs b/library/std/src/net/tcp.rs index 6336354239b02..22d2dfe65a249 100644 --- a/library/std/src/net/tcp.rs +++ b/library/std/src/net/tcp.rs @@ -3,14 +3,12 @@ #[cfg(all(test, not(any(target_os = "emscripten", target_os = "xous"))))] mod tests; -use crate::io::prelude::*; - use crate::fmt; +use crate::io::prelude::*; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; use crate::iter::FusedIterator; use crate::net::{Shutdown, SocketAddr, ToSocketAddrs}; -use crate::sys_common::net as net_imp; -use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::sys_common::{net as net_imp, AsInner, FromInner, IntoInner}; use crate::time::Duration; /// A TCP stream between a local and a remote socket. diff --git a/library/std/src/net/tcp/tests.rs b/library/std/src/net/tcp/tests.rs index 3ad046733a634..d26517d74e492 100644 --- a/library/std/src/net/tcp/tests.rs +++ b/library/std/src/net/tcp/tests.rs @@ -1,12 +1,11 @@ -use crate::fmt; use crate::io::prelude::*; use crate::io::{BorrowedBuf, IoSlice, IoSliceMut}; use crate::mem::MaybeUninit; use crate::net::test::{next_test_ip4, next_test_ip6}; use crate::net::*; use crate::sync::mpsc::channel; -use crate::thread; use crate::time::{Duration, Instant}; +use crate::{fmt, thread}; fn each_ip(f: &mut dyn FnMut(SocketAddr)) { f(next_test_ip4()); diff --git a/library/std/src/net/udp.rs b/library/std/src/net/udp.rs index 60347a11da9c5..32e9086003d6b 100644 --- a/library/std/src/net/udp.rs +++ b/library/std/src/net/udp.rs @@ -4,8 +4,7 @@ mod tests; use crate::fmt; use crate::io::{self, ErrorKind}; use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; -use crate::sys_common::net as net_imp; -use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::sys_common::{net as net_imp, AsInner, FromInner, IntoInner}; use crate::time::Duration; /// A UDP socket. diff --git a/library/std/src/num.rs b/library/std/src/num.rs index 8910cdea7c0c9..c1e6e7e628c83 100644 --- a/library/std/src/num.rs +++ b/library/std/src/num.rs @@ -9,32 +9,27 @@ #[cfg(test)] mod tests; +#[stable(feature = "int_error_matching", since = "1.55.0")] +pub use core::num::IntErrorKind; +#[stable(feature = "generic_nonzero", since = "1.79.0")] +pub use core::num::NonZero; #[stable(feature = "saturating_int_impl", since = "1.74.0")] pub use core::num::Saturating; #[stable(feature = "rust1", since = "1.0.0")] pub use core::num::Wrapping; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::num::{FpCategory, ParseFloatError, ParseIntError, TryFromIntError}; - #[unstable( feature = "nonzero_internals", reason = "implementation detail which may disappear or be replaced at any time", issue = "none" )] pub use core::num::ZeroablePrimitive; - -#[stable(feature = "generic_nonzero", since = "1.79.0")] -pub use core::num::NonZero; - +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::num::{FpCategory, ParseFloatError, ParseIntError, TryFromIntError}; #[stable(feature = "signed_nonzero", since = "1.34.0")] pub use core::num::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize}; - #[stable(feature = "nonzero", since = "1.28.0")] pub use core::num::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize}; -#[stable(feature = "int_error_matching", since = "1.55.0")] -pub use core::num::IntErrorKind; - #[cfg(test)] use crate::fmt; #[cfg(test)] diff --git a/library/std/src/os/aix/raw.rs b/library/std/src/os/aix/raw.rs index b4c8dc72cfe5b..13f61fc97226b 100644 --- a/library/std/src/os/aix/raw.rs +++ b/library/std/src/os/aix/raw.rs @@ -4,6 +4,5 @@ #[stable(feature = "pthread_t", since = "1.8.0")] pub use libc::pthread_t; - #[stable(feature = "raw_ext", since = "1.1.0")] pub use libc::{blkcnt_t, blksize_t, dev_t, ino_t, mode_t, nlink_t, off_t, stat, time_t}; diff --git a/library/std/src/os/android/fs.rs b/library/std/src/os/android/fs.rs index 1beb3cf6e84b5..6b931e3816950 100644 --- a/library/std/src/os/android/fs.rs +++ b/library/std/src/os/android/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::android::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/android/net.rs b/library/std/src/os/android/net.rs index 349e73eaabdaf..960a304fd0c8d 100644 --- a/library/std/src/os/android/net.rs +++ b/library/std/src/os/android/net.rs @@ -4,9 +4,7 @@ #[stable(feature = "unix_socket_abstract", since = "1.70.0")] pub use crate::os::net::linux_ext::addr::SocketAddrExt; - #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub use crate::os::net::linux_ext::socket::UnixSocketExt; - #[unstable(feature = "tcp_quickack", issue = "96256")] pub use crate::os::net::linux_ext::tcp::TcpStreamExt; diff --git a/library/std/src/os/darwin/fs.rs b/library/std/src/os/darwin/fs.rs index 2032cca311a15..2d154b214b5f0 100644 --- a/library/std/src/os/darwin/fs.rs +++ b/library/std/src/os/darwin/fs.rs @@ -1,13 +1,12 @@ #![allow(dead_code)] +#[allow(deprecated)] +use super::raw; use crate::fs::{self, Metadata}; use crate::sealed::Sealed; use crate::sys_common::{AsInner, AsInnerMut, IntoInner}; use crate::time::SystemTime; -#[allow(deprecated)] -use super::raw; - /// OS-specific extensions to [`fs::Metadata`]. /// /// [`fs::Metadata`]: crate::fs::Metadata diff --git a/library/std/src/os/dragonfly/fs.rs b/library/std/src/os/dragonfly/fs.rs index 1424fc4c69880..0cd543b2ab97d 100644 --- a/library/std/src/os/dragonfly/fs.rs +++ b/library/std/src/os/dragonfly/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::dragonfly::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/emscripten/fs.rs b/library/std/src/os/emscripten/fs.rs index d5ec8e03c00d1..3282b79ac1c81 100644 --- a/library/std/src/os/emscripten/fs.rs +++ b/library/std/src/os/emscripten/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::emscripten::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/espidf/fs.rs b/library/std/src/os/espidf/fs.rs index 88701dafe20ce..ffff584cda02a 100644 --- a/library/std/src/os/espidf/fs.rs +++ b/library/std/src/os/espidf/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::espidf::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/fd/owned.rs b/library/std/src/os/fd/owned.rs index 5833c59725682..2d087c03b04b4 100644 --- a/library/std/src/os/fd/owned.rs +++ b/library/std/src/os/fd/owned.rs @@ -4,14 +4,12 @@ #![deny(unsafe_op_in_unsafe_fn)] use super::raw::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; -use crate::fmt; -use crate::fs; -use crate::io; use crate::marker::PhantomData; -use crate::mem::forget; +use crate::mem::ManuallyDrop; #[cfg(not(any(target_arch = "wasm32", target_env = "sgx", target_os = "hermit")))] use crate::sys::cvt; use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::{fmt, fs, io}; /// A borrowed file descriptor. /// @@ -70,7 +68,7 @@ pub struct OwnedFd { } impl BorrowedFd<'_> { - /// Return a `BorrowedFd` holding the given raw file descriptor. + /// Returns a `BorrowedFd` holding the given raw file descriptor. /// /// # Safety /// @@ -148,9 +146,7 @@ impl AsRawFd for OwnedFd { impl IntoRawFd for OwnedFd { #[inline] fn into_raw_fd(self) -> RawFd { - let fd = self.fd; - forget(self); - fd + ManuallyDrop::new(self).fd } } diff --git a/library/std/src/os/fd/raw.rs b/library/std/src/os/fd/raw.rs index ef896ea95c9c9..0d99d5492a268 100644 --- a/library/std/src/os/fd/raw.rs +++ b/library/std/src/os/fd/raw.rs @@ -2,8 +2,9 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::fs; -use crate::io; +#[cfg(target_os = "hermit")] +use hermit_abi as libc; + #[cfg(target_os = "hermit")] use crate::os::hermit::io::OwnedFd; #[cfg(not(target_os = "hermit"))] @@ -15,8 +16,7 @@ use crate::os::unix::io::OwnedFd; #[cfg(target_os = "wasi")] use crate::os::wasi::io::OwnedFd; use crate::sys_common::{AsInner, IntoInner}; -#[cfg(target_os = "hermit")] -use hermit_abi as libc; +use crate::{fs, io}; /// Raw file descriptors. #[rustc_allowed_through_unstable_modules] @@ -138,6 +138,7 @@ pub trait IntoRawFd { /// let raw_fd: RawFd = f.into_raw_fd(); /// # Ok::<(), io::Error>(()) /// ``` + #[must_use = "losing the raw file descriptor may leak resources"] #[stable(feature = "into_raw_os", since = "1.4.0")] fn into_raw_fd(self) -> RawFd; } diff --git a/library/std/src/os/fortanix_sgx/arch.rs b/library/std/src/os/fortanix_sgx/arch.rs index 8358cb9e81b65..4c8048e7152e2 100644 --- a/library/std/src/os/fortanix_sgx/arch.rs +++ b/library/std/src/os/fortanix_sgx/arch.rs @@ -4,9 +4,10 @@ //! Software Developer's Manual, Volume 3, Chapter 40. #![unstable(feature = "sgx_platform", issue = "56975")] -use crate::mem::MaybeUninit; use core::arch::asm; +use crate::mem::MaybeUninit; + /// Wrapper struct to force 16-byte alignment. #[repr(align(16))] #[unstable(feature = "sgx_platform", issue = "56975")] diff --git a/library/std/src/os/fortanix_sgx/mod.rs b/library/std/src/os/fortanix_sgx/mod.rs index b31dc06f8dfbd..64f4d97ca95e2 100644 --- a/library/std/src/os/fortanix_sgx/mod.rs +++ b/library/std/src/os/fortanix_sgx/mod.rs @@ -22,20 +22,12 @@ pub mod usercalls { /// Lowest-level interfaces to usercalls and usercall ABI type definitions. pub mod raw { pub use crate::sys::abi::usercalls::raw::{ - accept_stream, alloc, async_queues, bind_stream, close, connect_stream, exit, flush, - free, insecure_time, launch_thread, read, read_alloc, send, wait, write, - }; - pub use crate::sys::abi::usercalls::raw::{do_usercall, Usercalls as UsercallNrs}; - pub use crate::sys::abi::usercalls::raw::{Register, RegisterArgument, ReturnValue}; - - pub use crate::sys::abi::usercalls::raw::Error; - pub use crate::sys::abi::usercalls::raw::{ - ByteBuffer, Cancel, FifoDescriptor, Return, Usercall, - }; - pub use crate::sys::abi::usercalls::raw::{Fd, Result, Tcs}; - pub use crate::sys::abi::usercalls::raw::{ - EV_RETURNQ_NOT_EMPTY, EV_UNPARK, EV_USERCALLQ_NOT_FULL, FD_STDERR, FD_STDIN, FD_STDOUT, - RESULT_SUCCESS, USERCALL_USER_DEFINED, WAIT_INDEFINITE, WAIT_NO, + accept_stream, alloc, async_queues, bind_stream, close, connect_stream, do_usercall, + exit, flush, free, insecure_time, launch_thread, read, read_alloc, send, wait, write, + ByteBuffer, Cancel, Error, Fd, FifoDescriptor, Register, RegisterArgument, Result, + Return, ReturnValue, Tcs, Usercall, Usercalls as UsercallNrs, EV_RETURNQ_NOT_EMPTY, + EV_UNPARK, EV_USERCALLQ_NOT_FULL, FD_STDERR, FD_STDIN, FD_STDOUT, RESULT_SUCCESS, + USERCALL_USER_DEFINED, WAIT_INDEFINITE, WAIT_NO, }; } } diff --git a/library/std/src/os/freebsd/fs.rs b/library/std/src/os/freebsd/fs.rs index 5689a82e00a34..34384a4bcb505 100644 --- a/library/std/src/os/freebsd/fs.rs +++ b/library/std/src/os/freebsd/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::freebsd::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/freebsd/net.rs b/library/std/src/os/freebsd/net.rs index b7e0fdc0a9aab..fcfc5c1c83935 100644 --- a/library/std/src/os/freebsd/net.rs +++ b/library/std/src/os/freebsd/net.rs @@ -42,7 +42,7 @@ pub trait UnixSocketExt: Sealed { #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] fn set_local_creds_persistent(&self, local_creds_persistent: bool) -> io::Result<()>; - /// Get a filter name if one had been set previously on the socket. + /// Gets a filter name if one had been set previously on the socket. #[unstable(feature = "acceptfilter", issue = "121891")] fn acceptfilter(&self) -> io::Result<&CStr>; diff --git a/library/std/src/os/haiku/fs.rs b/library/std/src/os/haiku/fs.rs index a23a2af8f6e7b..23f6493180b76 100644 --- a/library/std/src/os/haiku/fs.rs +++ b/library/std/src/os/haiku/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::haiku::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/hermit/io/net.rs b/library/std/src/os/hermit/io/net.rs index 8f3802d7873dc..7a774345b231a 100644 --- a/library/std/src/os/hermit/io/net.rs +++ b/library/std/src/os/hermit/io/net.rs @@ -1,5 +1,4 @@ -use crate::os::hermit::io::OwnedFd; -use crate::os::hermit::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; +use crate::os::hermit::io::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; use crate::{net, sys}; diff --git a/library/std/src/os/hermit/mod.rs b/library/std/src/os/hermit/mod.rs index 02a4b2c3ab5e7..5812206a25759 100644 --- a/library/std/src/os/hermit/mod.rs +++ b/library/std/src/os/hermit/mod.rs @@ -1,4 +1,5 @@ #![stable(feature = "rust1", since = "1.0.0")] +#![deny(unsafe_op_in_unsafe_fn)] #[allow(unused_extern_crates)] #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/std/src/os/illumos/fs.rs b/library/std/src/os/illumos/fs.rs index 63be48b8131b2..75dbe167785db 100644 --- a/library/std/src/os/illumos/fs.rs +++ b/library/std/src/os/illumos/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::illumos::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/ios/mod.rs b/library/std/src/os/ios/mod.rs index 5e130d77b7bfd..52d592ed95afa 100644 --- a/library/std/src/os/ios/mod.rs +++ b/library/std/src/os/ios/mod.rs @@ -7,7 +7,6 @@ pub mod fs { #[doc(inline)] #[stable(feature = "file_set_times", since = "1.75.0")] pub use crate::os::darwin::fs::FileTimesExt; - #[doc(inline)] #[stable(feature = "metadata_ext", since = "1.1.0")] pub use crate::os::darwin::fs::MetadataExt; diff --git a/library/std/src/os/l4re/fs.rs b/library/std/src/os/l4re/fs.rs index 6d6a535b1e831..0511ddcf19af6 100644 --- a/library/std/src/os/l4re/fs.rs +++ b/library/std/src/os/l4re/fs.rs @@ -5,10 +5,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::l4re::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/linux/fs.rs b/library/std/src/os/linux/fs.rs index ab0b2a3eda3f5..20a7a161a2628 100644 --- a/library/std/src/os/linux/fs.rs +++ b/library/std/src/os/linux/fs.rs @@ -5,10 +5,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::linux::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/linux/net.rs b/library/std/src/os/linux/net.rs index f898e70548706..1de120c8fd366 100644 --- a/library/std/src/os/linux/net.rs +++ b/library/std/src/os/linux/net.rs @@ -4,9 +4,7 @@ #[stable(feature = "unix_socket_abstract", since = "1.70.0")] pub use crate::os::net::linux_ext::addr::SocketAddrExt; - #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub use crate::os::net::linux_ext::socket::UnixSocketExt; - #[unstable(feature = "tcp_quickack", issue = "96256")] pub use crate::os::net::linux_ext::tcp::TcpStreamExt; diff --git a/library/std/src/os/macos/mod.rs b/library/std/src/os/macos/mod.rs index 3638406b1807d..59fe90834c2b4 100644 --- a/library/std/src/os/macos/mod.rs +++ b/library/std/src/os/macos/mod.rs @@ -7,7 +7,6 @@ pub mod fs { #[doc(inline)] #[stable(feature = "file_set_times", since = "1.75.0")] pub use crate::os::darwin::fs::FileTimesExt; - #[doc(inline)] #[stable(feature = "metadata_ext", since = "1.1.0")] pub use crate::os::darwin::fs::MetadataExt; diff --git a/library/std/src/os/net/linux_ext/tcp.rs b/library/std/src/os/net/linux_ext/tcp.rs index ff29afe7ed311..c8d012962d45a 100644 --- a/library/std/src/os/net/linux_ext/tcp.rs +++ b/library/std/src/os/net/linux_ext/tcp.rs @@ -2,10 +2,9 @@ //! //! [`std::net`]: crate::net -use crate::io; -use crate::net; use crate::sealed::Sealed; use crate::sys_common::AsInner; +use crate::{io, net}; /// Os-specific extensions for [`TcpStream`] /// diff --git a/library/std/src/os/net/linux_ext/tests.rs b/library/std/src/os/net/linux_ext/tests.rs index f8dbbfc18e28e..12f35696abc5c 100644 --- a/library/std/src/os/net/linux_ext/tests.rs +++ b/library/std/src/os/net/linux_ext/tests.rs @@ -1,9 +1,8 @@ #[test] fn quickack() { - use crate::{ - net::{test::next_test_ip4, TcpListener, TcpStream}, - os::net::linux_ext::tcp::TcpStreamExt, - }; + use crate::net::test::next_test_ip4; + use crate::net::{TcpListener, TcpStream}; + use crate::os::net::linux_ext::tcp::TcpStreamExt; macro_rules! t { ($e:expr) => { @@ -30,10 +29,9 @@ fn quickack() { #[test] #[cfg(target_os = "linux")] fn deferaccept() { - use crate::{ - net::{test::next_test_ip4, TcpListener, TcpStream}, - os::net::linux_ext::tcp::TcpStreamExt, - }; + use crate::net::test::next_test_ip4; + use crate::net::{TcpListener, TcpStream}; + use crate::os::net::linux_ext::tcp::TcpStreamExt; macro_rules! t { ($e:expr) => { diff --git a/library/std/src/os/netbsd/fs.rs b/library/std/src/os/netbsd/fs.rs index fe0be069e5e3f..74fbbabb17a5d 100644 --- a/library/std/src/os/netbsd/fs.rs +++ b/library/std/src/os/netbsd/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::netbsd::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/netbsd/net.rs b/library/std/src/os/netbsd/net.rs index b9679c7b3af33..e1950d349bf7d 100644 --- a/library/std/src/os/netbsd/net.rs +++ b/library/std/src/os/netbsd/net.rs @@ -42,7 +42,7 @@ pub trait UnixSocketExt: Sealed { #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] fn set_local_creds(&self, local_creds: bool) -> io::Result<()>; - /// Get a filter name if one had been set previously on the socket. + /// Gets a filter name if one had been set previously on the socket. #[unstable(feature = "acceptfilter", issue = "121891")] fn acceptfilter(&self) -> io::Result<&CStr>; diff --git a/library/std/src/os/openbsd/fs.rs b/library/std/src/os/openbsd/fs.rs index b8d8d31c5b8cf..e584098476a7b 100644 --- a/library/std/src/os/openbsd/fs.rs +++ b/library/std/src/os/openbsd/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::openbsd::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/redox/fs.rs b/library/std/src/os/redox/fs.rs index 682ca6a2c0309..c6b813f0cc6ce 100644 --- a/library/std/src/os/redox/fs.rs +++ b/library/std/src/os/redox/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::redox::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/solaris/fs.rs b/library/std/src/os/solaris/fs.rs index 0931437370429..9b0527d713891 100644 --- a/library/std/src/os/solaris/fs.rs +++ b/library/std/src/os/solaris/fs.rs @@ -1,10 +1,9 @@ #![stable(feature = "metadata_ext", since = "1.1.0")] use crate::fs::Metadata; -use crate::sys_common::AsInner; - #[allow(deprecated)] use crate::os::solaris::raw; +use crate::sys_common::AsInner; /// OS-specific extensions to [`fs::Metadata`]. /// diff --git a/library/std/src/os/solid/io.rs b/library/std/src/os/solid/io.rs index e75bcf74e5cd3..2d18f33961506 100644 --- a/library/std/src/os/solid/io.rs +++ b/library/std/src/os/solid/io.rs @@ -46,12 +46,10 @@ #![unstable(feature = "solid_ext", issue = "none")] -use crate::fmt; use crate::marker::PhantomData; -use crate::mem::forget; -use crate::net; -use crate::sys; +use crate::mem::ManuallyDrop; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; +use crate::{fmt, net, sys}; /// Raw file descriptors. pub type RawFd = i32; @@ -98,7 +96,7 @@ pub struct OwnedFd { } impl BorrowedFd<'_> { - /// Return a `BorrowedFd` holding the given raw file descriptor. + /// Returns a `BorrowedFd` holding the given raw file descriptor. /// /// # Safety /// @@ -148,9 +146,7 @@ impl AsRawFd for OwnedFd { impl IntoRawFd for OwnedFd { #[inline] fn into_raw_fd(self) -> RawFd { - let fd = self.fd; - forget(self); - fd + ManuallyDrop::new(self).fd } } @@ -346,6 +342,7 @@ pub trait IntoRawFd { /// This function **transfers ownership** of the underlying file descriptor /// to the caller. Callers are then the unique owners of the file descriptor /// and must close the descriptor once it's no longer needed. + #[must_use = "losing the raw file descriptor may leak resources"] fn into_raw_fd(self) -> RawFd; } diff --git a/library/std/src/os/uefi/env.rs b/library/std/src/os/uefi/env.rs index 5d082e7c11388..cf8ae697e389d 100644 --- a/library/std/src/os/uefi/env.rs +++ b/library/std/src/os/uefi/env.rs @@ -2,8 +2,9 @@ #![unstable(feature = "uefi_std", issue = "100499")] +use crate::ffi::c_void; +use crate::ptr::NonNull; use crate::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; -use crate::{ffi::c_void, ptr::NonNull}; static SYSTEM_TABLE: AtomicPtr = AtomicPtr::new(crate::ptr::null_mut()); static IMAGE_HANDLE: AtomicPtr = AtomicPtr::new(crate::ptr::null_mut()); @@ -26,7 +27,7 @@ static BOOT_SERVICES_FLAG: AtomicBool = AtomicBool::new(false); /// standard library is loaded. /// /// # SAFETY -/// Calling this function more than once will panic +/// Calling this function more than once will panic. pub(crate) unsafe fn init_globals(handle: NonNull, system_table: NonNull) { IMAGE_HANDLE .compare_exchange( @@ -47,23 +48,25 @@ pub(crate) unsafe fn init_globals(handle: NonNull, system_table: NonNull BOOT_SERVICES_FLAG.store(true, Ordering::Release) } -/// Get the SystemTable Pointer. +/// Gets the SystemTable Pointer. +/// /// If you want to use `BootServices` then please use [`boot_services`] as it performs some /// additional checks. /// -/// Note: This function panics if the System Table or Image Handle is not initialized +/// Note: This function panics if the System Table or Image Handle is not initialized. pub fn system_table() -> NonNull { try_system_table().unwrap() } -/// Get the ImageHandle Pointer. +/// Gets the ImageHandle Pointer. /// -/// Note: This function panics if the System Table or Image Handle is not initialized +/// Note: This function panics if the System Table or Image Handle is not initialized. pub fn image_handle() -> NonNull { try_image_handle().unwrap() } -/// Get the BootServices Pointer. +/// Gets the BootServices Pointer. +/// /// This function also checks if `ExitBootServices` has already been called. pub fn boot_services() -> Option> { if BOOT_SERVICES_FLAG.load(Ordering::Acquire) { @@ -75,14 +78,16 @@ pub fn boot_services() -> Option> { } } -/// Get the SystemTable Pointer. -/// This function is mostly intended for places where panic is not an option +/// Gets the SystemTable Pointer. +/// +/// This function is mostly intended for places where panic is not an option. pub(crate) fn try_system_table() -> Option> { NonNull::new(SYSTEM_TABLE.load(Ordering::Acquire)) } -/// Get the SystemHandle Pointer. -/// This function is mostly intended for places where panicking is not an option +/// Gets the SystemHandle Pointer. +/// +/// This function is mostly intended for places where panicking is not an option. pub(crate) fn try_image_handle() -> Option> { NonNull::new(IMAGE_HANDLE.load(Ordering::Acquire)) } diff --git a/library/std/src/os/unix/fs.rs b/library/std/src/os/unix/fs.rs index 970023d8cf19e..caf6980afd91b 100644 --- a/library/std/src/os/unix/fs.rs +++ b/library/std/src/os/unix/fs.rs @@ -4,18 +4,18 @@ #![stable(feature = "rust1", since = "1.0.0")] +#[allow(unused_imports)] +use io::{Read, Write}; + use super::platform::fs::MetadataExt as _; +// Used for `File::read` on intra-doc links +use crate::ffi::OsStr; use crate::fs::{self, OpenOptions, Permissions}; -use crate::io; use crate::os::unix::io::{AsFd, AsRawFd}; use crate::path::Path; -use crate::sys; -use crate::sys_common::{AsInner, AsInnerMut, FromInner}; -// Used for `File::read` on intra-doc links -use crate::ffi::OsStr; use crate::sealed::Sealed; -#[allow(unused_imports)] -use io::{Read, Write}; +use crate::sys_common::{AsInner, AsInnerMut, FromInner}; +use crate::{io, sys}; // Tests for this module #[cfg(test)] @@ -1064,7 +1064,7 @@ pub fn lchown>(dir: P, uid: Option, gid: Option) -> io: /// } /// ``` #[stable(feature = "unix_chroot", since = "1.56.0")] -#[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))] +#[cfg(not(target_os = "fuchsia"))] pub fn chroot>(dir: P) -> io::Result<()> { sys::fs::chroot(dir.as_ref()) } diff --git a/library/std/src/os/unix/net/ancillary.rs b/library/std/src/os/unix/net/ancillary.rs index fe8e2be93724e..9b487a6298247 100644 --- a/library/std/src/os/unix/net/ancillary.rs +++ b/library/std/src/os/unix/net/ancillary.rs @@ -164,7 +164,7 @@ struct AncillaryDataIter<'a, T> { } impl<'a, T> AncillaryDataIter<'a, T> { - /// Create `AncillaryDataIter` struct to iterate through the data unit in the control message. + /// Creates `AncillaryDataIter` struct to iterate through the data unit in the control message. /// /// # Safety /// @@ -220,7 +220,7 @@ pub struct SocketCred(libc::sockcred2); #[doc(cfg(any(target_os = "android", target_os = "linux")))] #[cfg(any(target_os = "android", target_os = "linux"))] impl SocketCred { - /// Create a Unix credential struct. + /// Creates a Unix credential struct. /// /// PID, UID and GID is set to 0. #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] @@ -235,7 +235,7 @@ impl SocketCred { self.0.pid = pid; } - /// Get the current PID. + /// Gets the current PID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_pid(&self) -> libc::pid_t { @@ -248,7 +248,7 @@ impl SocketCred { self.0.uid = uid; } - /// Get the current UID. + /// Gets the current UID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_uid(&self) -> libc::uid_t { @@ -261,7 +261,7 @@ impl SocketCred { self.0.gid = gid; } - /// Get the current GID. + /// Gets the current GID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_gid(&self) -> libc::gid_t { @@ -271,7 +271,7 @@ impl SocketCred { #[cfg(target_os = "freebsd")] impl SocketCred { - /// Create a Unix credential struct. + /// Creates a Unix credential struct. /// /// PID, UID and GID is set to 0. #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] @@ -295,7 +295,7 @@ impl SocketCred { self.0.sc_pid = pid; } - /// Get the current PID. + /// Gets the current PID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_pid(&self) -> libc::pid_t { @@ -308,7 +308,7 @@ impl SocketCred { self.0.sc_euid = uid; } - /// Get the current UID. + /// Gets the current UID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_uid(&self) -> libc::uid_t { @@ -321,7 +321,7 @@ impl SocketCred { self.0.sc_egid = gid; } - /// Get the current GID. + /// Gets the current GID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_gid(&self) -> libc::gid_t { @@ -331,7 +331,7 @@ impl SocketCred { #[cfg(target_os = "netbsd")] impl SocketCred { - /// Create a Unix credential struct. + /// Creates a Unix credential struct. /// /// PID, UID and GID is set to 0. #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] @@ -353,7 +353,7 @@ impl SocketCred { self.0.sc_pid = pid; } - /// Get the current PID. + /// Gets the current PID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_pid(&self) -> libc::pid_t { @@ -366,7 +366,7 @@ impl SocketCred { self.0.sc_uid = uid; } - /// Get the current UID. + /// Gets the current UID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_uid(&self) -> libc::uid_t { @@ -379,7 +379,7 @@ impl SocketCred { self.0.sc_gid = gid; } - /// Get the current GID. + /// Gets the current GID. #[must_use] #[unstable(feature = "unix_socket_ancillary_data", issue = "76915")] pub fn get_gid(&self) -> libc::gid_t { @@ -466,7 +466,7 @@ pub enum AncillaryData<'a> { } impl<'a> AncillaryData<'a> { - /// Create an `AncillaryData::ScmRights` variant. + /// Creates an `AncillaryData::ScmRights` variant. /// /// # Safety /// @@ -478,7 +478,7 @@ impl<'a> AncillaryData<'a> { AncillaryData::ScmRights(scm_rights) } - /// Create an `AncillaryData::ScmCredentials` variant. + /// Creates an `AncillaryData::ScmCredentials` variant. /// /// # Safety /// @@ -605,7 +605,7 @@ pub struct SocketAncillary<'a> { } impl<'a> SocketAncillary<'a> { - /// Create an ancillary data with the given buffer. + /// Creates an ancillary data with the given buffer. /// /// # Example /// diff --git a/library/std/src/os/unix/net/datagram.rs b/library/std/src/os/unix/net/datagram.rs index b29f9099a1111..a605c3d4a2602 100644 --- a/library/std/src/os/unix/net/datagram.rs +++ b/library/std/src/os/unix/net/datagram.rs @@ -1,3 +1,17 @@ +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "openbsd", + target_os = "netbsd", + target_os = "solaris", + target_os = "illumos", + target_os = "haiku", + target_os = "nto", +))] +use libc::MSG_NOSIGNAL; + #[cfg(any(doc, target_os = "android", target_os = "linux"))] use super::{recv_vectored_with_ancillary_from, send_vectored_with_ancillary_to, SocketAncillary}; use super::{sockaddr_un, SocketAddr}; @@ -12,18 +26,6 @@ use crate::sys::net::Socket; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; use crate::{fmt, io}; - -#[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "openbsd", - target_os = "netbsd", - target_os = "haiku", - target_os = "nto", -))] -use libc::MSG_NOSIGNAL; #[cfg(not(any( target_os = "linux", target_os = "android", @@ -31,6 +33,8 @@ use libc::MSG_NOSIGNAL; target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", + target_os = "solaris", + target_os = "illumos", target_os = "haiku", target_os = "nto", )))] diff --git a/library/std/src/os/unix/net/tests.rs b/library/std/src/os/unix/net/tests.rs index e456e41b21c88..21e2176185d25 100644 --- a/library/std/src/os/unix/net/tests.rs +++ b/library/std/src/os/unix/net/tests.rs @@ -1,18 +1,16 @@ use super::*; use crate::io::prelude::*; use crate::io::{self, ErrorKind, IoSlice, IoSliceMut}; +#[cfg(target_os = "android")] +use crate::os::android::net::{SocketAddrExt, UnixSocketExt}; +#[cfg(target_os = "linux")] +use crate::os::linux::net::{SocketAddrExt, UnixSocketExt}; #[cfg(any(target_os = "android", target_os = "linux"))] use crate::os::unix::io::AsRawFd; use crate::sys_common::io::test::tmpdir; use crate::thread; use crate::time::Duration; -#[cfg(target_os = "android")] -use crate::os::android::net::{SocketAddrExt, UnixSocketExt}; - -#[cfg(target_os = "linux")] -use crate::os::linux::net::{SocketAddrExt, UnixSocketExt}; - macro_rules! or_panic { ($e:expr) => { match $e { diff --git a/library/std/src/os/unix/net/ucred.rs b/library/std/src/os/unix/net/ucred.rs index 1497e730bbf15..b96e373ad0ae3 100644 --- a/library/std/src/os/unix/net/ucred.rs +++ b/library/std/src/os/unix/net/ucred.rs @@ -23,9 +23,8 @@ pub struct UCred { pub pid: Option, } -#[cfg(any(target_os = "android", target_os = "linux"))] -pub(super) use self::impl_linux::peer_cred; - +#[cfg(target_vendor = "apple")] +pub(super) use self::impl_apple::peer_cred; #[cfg(any( target_os = "dragonfly", target_os = "freebsd", @@ -34,17 +33,17 @@ pub(super) use self::impl_linux::peer_cred; target_os = "nto" ))] pub(super) use self::impl_bsd::peer_cred; - -#[cfg(target_vendor = "apple")] -pub(super) use self::impl_apple::peer_cred; +#[cfg(any(target_os = "android", target_os = "linux"))] +pub(super) use self::impl_linux::peer_cred; #[cfg(any(target_os = "linux", target_os = "android"))] mod impl_linux { + use libc::{c_void, getsockopt, socklen_t, ucred, SOL_SOCKET, SO_PEERCRED}; + use super::UCred; use crate::os::unix::io::AsRawFd; use crate::os::unix::net::UnixStream; use crate::{io, mem}; - use libc::{c_void, getsockopt, socklen_t, ucred, SOL_SOCKET, SO_PEERCRED}; pub fn peer_cred(socket: &UnixStream) -> io::Result { let ucred_size = mem::size_of::(); @@ -99,11 +98,12 @@ mod impl_bsd { #[cfg(target_vendor = "apple")] mod impl_apple { + use libc::{c_void, getpeereid, getsockopt, pid_t, socklen_t, LOCAL_PEERPID, SOL_LOCAL}; + use super::UCred; use crate::os::unix::io::AsRawFd; use crate::os::unix::net::UnixStream; use crate::{io, mem}; - use libc::{c_void, getpeereid, getsockopt, pid_t, socklen_t, LOCAL_PEERPID, SOL_LOCAL}; pub fn peer_cred(socket: &UnixStream) -> io::Result { let mut cred = UCred { uid: 1, gid: 1, pid: None }; diff --git a/library/std/src/os/unix/net/ucred/tests.rs b/library/std/src/os/unix/net/ucred/tests.rs index a6cc81318fc08..59414f4dcae13 100644 --- a/library/std/src/os/unix/net/ucred/tests.rs +++ b/library/std/src/os/unix/net/ucred/tests.rs @@ -1,6 +1,7 @@ -use crate::os::unix::net::UnixStream; use libc::{getegid, geteuid, getpid}; +use crate::os::unix::net::UnixStream; + #[test] #[cfg(any( target_os = "android", diff --git a/library/std/src/os/unix/process.rs b/library/std/src/os/unix/process.rs index 72ea54bd77203..c53423675bd00 100644 --- a/library/std/src/os/unix/process.rs +++ b/library/std/src/os/unix/process.rs @@ -4,15 +4,13 @@ #![stable(feature = "rust1", since = "1.0.0")] +use cfg_if::cfg_if; + use crate::ffi::OsStr; -use crate::io; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; -use crate::process; use crate::sealed::Sealed; -use crate::sys; use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; - -use cfg_if::cfg_if; +use crate::{io, process, sys}; cfg_if! { if #[cfg(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon", target_os = "vita"))] { @@ -444,7 +442,7 @@ impl From for OwnedFd { } } -/// Create a `ChildStdin` from the provided `OwnedFd`. +/// Creates a `ChildStdin` from the provided `OwnedFd`. /// /// The provided file descriptor must point to a pipe /// with the `CLOEXEC` flag set. @@ -475,7 +473,7 @@ impl From for OwnedFd { } } -/// Create a `ChildStdout` from the provided `OwnedFd`. +/// Creates a `ChildStdout` from the provided `OwnedFd`. /// /// The provided file descriptor must point to a pipe /// with the `CLOEXEC` flag set. @@ -506,7 +504,7 @@ impl From for OwnedFd { } } -/// Create a `ChildStderr` from the provided `OwnedFd`. +/// Creates a `ChildStderr` from the provided `OwnedFd`. /// /// The provided file descriptor must point to a pipe /// with the `CLOEXEC` flag set. diff --git a/library/std/src/os/vita/mod.rs b/library/std/src/os/vita/mod.rs index da9edd12f7b03..92a2bf0a59ab5 100644 --- a/library/std/src/os/vita/mod.rs +++ b/library/std/src/os/vita/mod.rs @@ -1,5 +1,6 @@ //! Definitions for vita +#![forbid(unsafe_op_in_unsafe_fn)] #![stable(feature = "raw_ext", since = "1.1.0")] pub mod fs; diff --git a/library/std/src/os/vita/raw.rs b/library/std/src/os/vita/raw.rs index 74cae4d4135d1..e4b65ef1ed767 100644 --- a/library/std/src/os/vita/raw.rs +++ b/library/std/src/os/vita/raw.rs @@ -10,9 +10,6 @@ )] #![allow(deprecated)] -use crate::os::raw::c_long; -use crate::os::unix::raw::{gid_t, uid_t}; - #[stable(feature = "pthread_t", since = "1.8.0")] pub type pthread_t = libc::pthread_t; @@ -34,37 +31,3 @@ pub type off_t = libc::off_t; #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = libc::time_t; - -#[repr(C)] -#[derive(Clone)] -#[stable(feature = "raw_ext", since = "1.1.0")] -pub struct stat { - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_dev: dev_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_ino: ino_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_mode: mode_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_nlink: nlink_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_uid: uid_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_gid: gid_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_rdev: dev_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_size: off_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_atime: time_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_mtime: time_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_ctime: time_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_blksize: blksize_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_blocks: blkcnt_t, - #[stable(feature = "raw_ext", since = "1.1.0")] - pub st_spare4: [c_long; 2usize], -} diff --git a/library/std/src/os/wasi/fs.rs b/library/std/src/os/wasi/fs.rs index 46fc2a50de911..a58ca543d6777 100644 --- a/library/std/src/os/wasi/fs.rs +++ b/library/std/src/os/wasi/fs.rs @@ -5,14 +5,15 @@ #![deny(unsafe_op_in_unsafe_fn)] #![unstable(feature = "wasi_ext", issue = "71213")] +// Used for `File::read` on intra-doc links +#[allow(unused_imports)] +use io::{Read, Write}; + use crate::ffi::OsStr; use crate::fs::{self, File, Metadata, OpenOptions}; use crate::io::{self, IoSlice, IoSliceMut}; use crate::path::{Path, PathBuf}; use crate::sys_common::{AsInner, AsInnerMut, FromInner}; -// Used for `File::read` on intra-doc links -#[allow(unused_imports)] -use io::{Read, Write}; /// WASI-specific extensions to [`File`]. pub trait FileExt { @@ -169,55 +170,55 @@ pub trait FileExt { #[doc(alias = "fd_tell")] fn tell(&self) -> io::Result; - /// Adjust the flags associated with this file. + /// Adjusts the flags associated with this file. /// /// This corresponds to the `fd_fdstat_set_flags` syscall. #[doc(alias = "fd_fdstat_set_flags")] fn fdstat_set_flags(&self, flags: u16) -> io::Result<()>; - /// Adjust the rights associated with this file. + /// Adjusts the rights associated with this file. /// /// This corresponds to the `fd_fdstat_set_rights` syscall. #[doc(alias = "fd_fdstat_set_rights")] fn fdstat_set_rights(&self, rights: u64, inheriting: u64) -> io::Result<()>; - /// Provide file advisory information on a file descriptor. + /// Provides file advisory information on a file descriptor. /// /// This corresponds to the `fd_advise` syscall. #[doc(alias = "fd_advise")] fn advise(&self, offset: u64, len: u64, advice: u8) -> io::Result<()>; - /// Force the allocation of space in a file. + /// Forces the allocation of space in a file. /// /// This corresponds to the `fd_allocate` syscall. #[doc(alias = "fd_allocate")] fn allocate(&self, offset: u64, len: u64) -> io::Result<()>; - /// Create a directory. + /// Creates a directory. /// /// This corresponds to the `path_create_directory` syscall. #[doc(alias = "path_create_directory")] fn create_directory>(&self, dir: P) -> io::Result<()>; - /// Read the contents of a symbolic link. + /// Reads the contents of a symbolic link. /// /// This corresponds to the `path_readlink` syscall. #[doc(alias = "path_readlink")] fn read_link>(&self, path: P) -> io::Result; - /// Return the attributes of a file or directory. + /// Returns the attributes of a file or directory. /// /// This corresponds to the `path_filestat_get` syscall. #[doc(alias = "path_filestat_get")] fn metadata_at>(&self, lookup_flags: u32, path: P) -> io::Result; - /// Unlink a file. + /// Unlinks a file. /// /// This corresponds to the `path_unlink_file` syscall. #[doc(alias = "path_unlink_file")] fn remove_file>(&self, path: P) -> io::Result<()>; - /// Remove a directory. + /// Removes a directory. /// /// This corresponds to the `path_remove_directory` syscall. #[doc(alias = "path_remove_directory")] @@ -501,7 +502,7 @@ impl DirEntryExt for fs::DirEntry { } } -/// Create a hard link. +/// Creates a hard link. /// /// This corresponds to the `path_link` syscall. #[doc(alias = "path_link")] @@ -520,7 +521,7 @@ pub fn link, U: AsRef>( ) } -/// Rename a file or directory. +/// Renames a file or directory. /// /// This corresponds to the `path_rename` syscall. #[doc(alias = "path_rename")] @@ -537,7 +538,7 @@ pub fn rename, U: AsRef>( ) } -/// Create a symbolic link. +/// Creates a symbolic link. /// /// This corresponds to the `path_symlink` syscall. #[doc(alias = "path_symlink")] @@ -551,7 +552,7 @@ pub fn symlink, U: AsRef>( .symlink(osstr2str(old_path.as_ref().as_ref())?, osstr2str(new_path.as_ref().as_ref())?) } -/// Create a symbolic link. +/// Creates a symbolic link. /// /// This is a convenience API similar to `std::os::unix::fs::symlink` and /// `std::os::windows::fs::symlink_file` and `std::os::windows::fs::symlink_dir`. diff --git a/library/std/src/os/wasi/net/mod.rs b/library/std/src/os/wasi/net/mod.rs index 73c097d4a50ab..4704dd574517a 100644 --- a/library/std/src/os/wasi/net/mod.rs +++ b/library/std/src/os/wasi/net/mod.rs @@ -2,9 +2,8 @@ #![unstable(feature = "wasi_ext", issue = "71213")] -use crate::io; -use crate::net; use crate::sys_common::AsInner; +use crate::{io, net}; /// WASI-specific extensions to [`std::net::TcpListener`]. /// diff --git a/library/std/src/os/windows/ffi.rs b/library/std/src/os/windows/ffi.rs index 96bab59d3f8d7..496443dbbc3ac 100644 --- a/library/std/src/os/windows/ffi.rs +++ b/library/std/src/os/windows/ffi.rs @@ -56,11 +56,10 @@ use crate::ffi::{OsStr, OsString}; use crate::sealed::Sealed; use crate::sys::os_str::Buf; -use crate::sys_common::wtf8::Wtf8Buf; -use crate::sys_common::{AsInner, FromInner}; - #[stable(feature = "rust1", since = "1.0.0")] pub use crate::sys_common::wtf8::EncodeWide; +use crate::sys_common::wtf8::Wtf8Buf; +use crate::sys_common::{AsInner, FromInner}; /// Windows-specific extensions to [`OsString`]. /// diff --git a/library/std/src/os/windows/fs.rs b/library/std/src/os/windows/fs.rs index 7cac8c39ea89f..3dcde43cfec78 100644 --- a/library/std/src/os/windows/fs.rs +++ b/library/std/src/os/windows/fs.rs @@ -5,12 +5,11 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::fs::{self, Metadata, OpenOptions}; -use crate::io; use crate::path::Path; use crate::sealed::Sealed; -use crate::sys; use crate::sys_common::{AsInner, AsInnerMut, IntoInner}; use crate::time::SystemTime; +use crate::{io, sys}; /// Windows-specific extensions to [`fs::File`]. #[stable(feature = "file_offset", since = "1.15.0")] @@ -631,7 +630,7 @@ pub fn symlink_dir, Q: AsRef>(original: P, link: Q) -> io:: sys::fs::symlink_inner(original.as_ref(), link.as_ref(), true) } -/// Create a junction point. +/// Creates a junction point. /// /// The `link` path will be a directory junction pointing to the original path. /// If `link` is a relative path then it will be made absolute prior to creating the junction point. diff --git a/library/std/src/os/windows/io/handle.rs b/library/std/src/os/windows/io/handle.rs index a9d1983dce610..a4fa94e2b96a4 100644 --- a/library/std/src/os/windows/io/handle.rs +++ b/library/std/src/os/windows/io/handle.rs @@ -3,15 +3,11 @@ #![stable(feature = "io_safety", since = "1.63.0")] use super::raw::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle}; -use crate::fmt; -use crate::fs; -use crate::io; use crate::marker::PhantomData; -use crate::mem::{forget, ManuallyDrop}; -use crate::ptr; -use crate::sys; +use crate::mem::ManuallyDrop; use crate::sys::cvt; use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::{fmt, fs, io, ptr, sys}; /// A borrowed handle. /// @@ -135,7 +131,7 @@ unsafe impl Sync for HandleOrInvalid {} unsafe impl Sync for BorrowedHandle<'_> {} impl BorrowedHandle<'_> { - /// Return a `BorrowedHandle` holding the given raw handle. + /// Returns a `BorrowedHandle` holding the given raw handle. /// /// # Safety /// @@ -319,9 +315,7 @@ impl AsRawHandle for OwnedHandle { impl IntoRawHandle for OwnedHandle { #[inline] fn into_raw_handle(self) -> RawHandle { - let handle = self.handle; - forget(self); - handle + ManuallyDrop::new(self).handle } } diff --git a/library/std/src/os/windows/io/raw.rs b/library/std/src/os/windows/io/raw.rs index 343cc6e4a8a5a..6658248d574c9 100644 --- a/library/std/src/os/windows/io/raw.rs +++ b/library/std/src/os/windows/io/raw.rs @@ -2,16 +2,12 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::fs; -use crate::io; -use crate::net; #[cfg(doc)] use crate::os::windows::io::{AsHandle, AsSocket}; use crate::os::windows::io::{OwnedHandle, OwnedSocket}; use crate::os::windows::raw; -use crate::ptr; -use crate::sys; use crate::sys_common::{self, AsInner, FromInner, IntoInner}; +use crate::{fs, io, net, ptr, sys}; /// Raw HANDLEs. #[stable(feature = "rust1", since = "1.0.0")] @@ -44,7 +40,7 @@ pub trait AsRawHandle { fn as_raw_handle(&self) -> RawHandle; } -/// Construct I/O objects from raw handles. +/// Constructs I/O objects from raw handles. #[stable(feature = "from_raw_os", since = "1.1.0")] pub trait FromRawHandle { /// Constructs a new I/O object from the specified raw handle. @@ -89,6 +85,7 @@ pub trait IntoRawHandle { /// However, transferring ownership is not strictly required. Use a /// `Into::into` implementation for an API which strictly /// transfers ownership. + #[must_use = "losing the raw handle may leak resources"] #[stable(feature = "into_raw_os", since = "1.4.0")] fn into_raw_handle(self) -> RawHandle; } @@ -232,6 +229,7 @@ pub trait IntoRawSocket { /// However, transferring ownership is not strictly required. Use a /// `Into::into` implementation for an API which strictly /// transfers ownership. + #[must_use = "losing the raw socket may leak resources"] #[stable(feature = "into_raw_os", since = "1.4.0")] fn into_raw_socket(self) -> RawSocket; } diff --git a/library/std/src/os/windows/io/socket.rs b/library/std/src/os/windows/io/socket.rs index 4334d041439d9..1fcfb6e73ad03 100644 --- a/library/std/src/os/windows/io/socket.rs +++ b/library/std/src/os/windows/io/socket.rs @@ -3,14 +3,11 @@ #![stable(feature = "io_safety", since = "1.63.0")] use super::raw::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; -use crate::mem; -use crate::mem::forget; -use crate::sys; +use crate::mem::{self, ManuallyDrop}; #[cfg(not(target_vendor = "uwp"))] use crate::sys::cvt; +use crate::{fmt, io, sys}; /// A borrowed socket. /// @@ -64,7 +61,7 @@ pub struct OwnedSocket { } impl BorrowedSocket<'_> { - /// Return a `BorrowedSocket` holding the given raw socket. + /// Returns a `BorrowedSocket` holding the given raw socket. /// /// # Safety /// @@ -191,9 +188,7 @@ impl AsRawSocket for OwnedSocket { impl IntoRawSocket for OwnedSocket { #[inline] fn into_raw_socket(self) -> RawSocket { - let socket = self.socket; - forget(self); - socket + ManuallyDrop::new(self).socket } } diff --git a/library/std/src/os/windows/process.rs b/library/std/src/os/windows/process.rs index 3927b2ed9bb5c..c2830d2eb61d1 100644 --- a/library/std/src/os/windows/process.rs +++ b/library/std/src/os/windows/process.rs @@ -8,10 +8,9 @@ use crate::ffi::OsStr; use crate::os::windows::io::{ AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle, OwnedHandle, RawHandle, }; -use crate::process; use crate::sealed::Sealed; -use crate::sys; use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; +use crate::{process, sys}; #[stable(feature = "process_extensions", since = "1.2.0")] impl FromRawHandle for process::Stdio { @@ -109,7 +108,7 @@ impl IntoRawHandle for process::ChildStderr { } } -/// Create a `ChildStdin` from the provided `OwnedHandle`. +/// Creates a `ChildStdin` from the provided `OwnedHandle`. /// /// The provided handle must be asynchronous, as reading and /// writing from and to it is implemented using asynchronous APIs. @@ -122,7 +121,7 @@ impl From for process::ChildStdin { } } -/// Create a `ChildStdout` from the provided `OwnedHandle`. +/// Creates a `ChildStdout` from the provided `OwnedHandle`. /// /// The provided handle must be asynchronous, as reading and /// writing from and to it is implemented using asynchronous APIs. @@ -135,7 +134,7 @@ impl From for process::ChildStdout { } } -/// Create a `ChildStderr` from the provided `OwnedHandle`. +/// Creates a `ChildStderr` from the provided `OwnedHandle`. /// /// The provided handle must be asynchronous, as reading and /// writing from and to it is implemented using asynchronous APIs. diff --git a/library/std/src/os/xous/ffi.rs b/library/std/src/os/xous/ffi.rs index e9a9f53372026..1a4a940bf358a 100644 --- a/library/std/src/os/xous/ffi.rs +++ b/library/std/src/os/xous/ffi.rs @@ -274,7 +274,7 @@ fn connect_impl(address: ServerAddress, blocking: bool) -> Result Result { connect_impl(address, true) } -/// Attempt to connect to a Xous server represented by the specified `address`. +/// Attempts to connect to a Xous server represented by the specified `address`. /// /// If the server does not exist then None is returned. pub(crate) fn try_connect(address: ServerAddress) -> Result, Error> { @@ -293,7 +293,7 @@ pub(crate) fn try_connect(address: ServerAddress) -> Result, } } -/// Terminate the current process and return the specified code to the parent process. +/// Terminates the current process and returns the specified code to the parent process. pub(crate) fn exit(return_code: u32) -> ! { let a0 = Syscall::TerminateProcess as usize; let a1 = return_code as usize; @@ -320,7 +320,7 @@ pub(crate) fn exit(return_code: u32) -> ! { unreachable!(); } -/// Suspend the current thread and allow another thread to run. This thread may +/// Suspends the current thread and allow another thread to run. This thread may /// continue executing again immediately if there are no other threads available /// to run on the system. pub(crate) fn do_yield() { @@ -348,9 +348,11 @@ pub(crate) fn do_yield() { }; } -/// Allocate memory from the system. An optional physical and/or virtual address -/// may be specified in order to ensure memory is allocated at specific offsets, -/// otherwise the kernel will select an address. +/// Allocates memory from the system. +/// +/// An optional physical and/or virtual address may be specified in order to +/// ensure memory is allocated at specific offsets, otherwise the kernel will +/// select an address. /// /// # Safety /// @@ -400,7 +402,7 @@ pub(crate) unsafe fn map_memory( } } -/// Destroy the given memory, returning it to the compiler. +/// Destroys the given memory, returning it to the compiler. /// /// Safety: The memory pointed to by `range` should not be used after this /// function returns, even if this function returns Err(). @@ -439,9 +441,10 @@ pub(crate) unsafe fn unmap_memory(range: *mut [T]) -> Result<(), Error> { } } -/// Adjust the memory flags for the given range. This can be used to remove flags -/// from a given region in order to harden memory access. Note that flags may -/// only be removed and may never be added. +/// Adjusts the memory flags for the given range. +/// +/// This can be used to remove flags from a given region in order to harden +/// memory access. Note that flags may only be removed and may never be added. /// /// Safety: The memory pointed to by `range` may become inaccessible or have its /// mutability removed. It is up to the caller to ensure that the flags specified @@ -484,7 +487,7 @@ pub(crate) unsafe fn update_memory_flags( } } -/// Create a thread with a given stack and up to four arguments +/// Creates a thread with a given stack and up to four arguments. pub(crate) fn create_thread( start: *mut usize, stack: *mut [u8], @@ -527,7 +530,7 @@ pub(crate) fn create_thread( } } -/// Wait for the given thread to terminate and return the exit code from that thread. +/// Waits for the given thread to terminate and returns the exit code from that thread. pub(crate) fn join_thread(thread_id: ThreadId) -> Result { let mut a0 = Syscall::JoinThread as usize; let mut a1 = thread_id.into(); @@ -567,7 +570,7 @@ pub(crate) fn join_thread(thread_id: ThreadId) -> Result { } } -/// Get the current thread's ID +/// Gets the current thread's ID. pub(crate) fn thread_id() -> Result { let mut a0 = Syscall::GetThreadId as usize; let mut a1 = 0; @@ -603,7 +606,7 @@ pub(crate) fn thread_id() -> Result { } } -/// Adjust the given `knob` limit to match the new value `new`. The current value must +/// Adjusts the given `knob` limit to match the new value `new`. The current value must /// match the `current` in order for this to take effect. /// /// The new value is returned as a result of this call. If the call fails, then the old diff --git a/library/std/src/os/xous/services.rs b/library/std/src/os/xous/services.rs index a75be1b857003..ddf0236f5ad74 100644 --- a/library/std/src/os/xous/services.rs +++ b/library/std/src/os/xous/services.rs @@ -1,6 +1,7 @@ -use crate::os::xous::ffi::Connection; use core::sync::atomic::{AtomicU32, Ordering}; +use crate::os::xous::ffi::Connection; + mod dns; pub(crate) use dns::*; @@ -83,7 +84,7 @@ mod ns { } } -/// Attempt to connect to a server by name. If the server does not exist, this will +/// Attempts to connect to a server by name. If the server does not exist, this will /// block until the server is created. /// /// Note that this is different from connecting to a server by address. Server @@ -94,7 +95,7 @@ pub fn connect(name: &str) -> Option { ns::connect_with_name(name) } -/// Attempt to connect to a server by name. If the server does not exist, this will +/// Attempts to connect to a server by name. If the server does not exist, this will /// immediately return `None`. /// /// Note that this is different from connecting to a server by address. Server @@ -107,7 +108,7 @@ pub fn try_connect(name: &str) -> Option { static NAME_SERVER_CONNECTION: AtomicU32 = AtomicU32::new(0); -/// Return a `Connection` to the name server. If the name server has not been started, +/// Returns a `Connection` to the name server. If the name server has not been started, /// then this call will block until the name server has been started. The `Connection` /// will be shared among all connections in a process, so it is safe to call this /// multiple times. diff --git a/library/std/src/os/xous/services/dns.rs b/library/std/src/os/xous/services/dns.rs index a7d88f4892cda..0288164839360 100644 --- a/library/std/src/os/xous/services/dns.rs +++ b/library/std/src/os/xous/services/dns.rs @@ -1,6 +1,7 @@ +use core::sync::atomic::{AtomicU32, Ordering}; + use crate::os::xous::ffi::Connection; use crate::os::xous::services::connect; -use core::sync::atomic::{AtomicU32, Ordering}; #[repr(usize)] pub(crate) enum DnsLendMut { @@ -13,7 +14,7 @@ impl Into for DnsLendMut { } } -/// Return a `Connection` to the DNS lookup server. This server is used for +/// Returns a `Connection` to the DNS lookup server. This server is used for /// querying domain name values. pub(crate) fn dns_server() -> Connection { static DNS_CONNECTION: AtomicU32 = AtomicU32::new(0); diff --git a/library/std/src/os/xous/services/log.rs b/library/std/src/os/xous/services/log.rs index 55a501dc7d00e..1661011ca64b1 100644 --- a/library/std/src/os/xous/services/log.rs +++ b/library/std/src/os/xous/services/log.rs @@ -1,10 +1,11 @@ -use crate::os::xous::ffi::Connection; use core::sync::atomic::{AtomicU32, Ordering}; -/// Group `usize` bytes into a `usize` and return it, beginning -/// from `offset` * sizeof(usize) bytes from the start. For example, -/// `group_or_null([1,2,3,4,5,6,7,8], 1)` on a 32-bit system will -/// return a usize with 5678 packed into it. +use crate::os::xous::ffi::Connection; + +/// Group a `usize` worth of bytes into a `usize` and return it, beginning from +/// `offset` * sizeof(usize) bytes from the start. For example, +/// `group_or_null([1,2,3,4,5,6,7,8], 1)` on a 32-bit system will return a +/// `usize` with 5678 packed into it. fn group_or_null(data: &[u8], offset: usize) -> usize { let start = offset * core::mem::size_of::(); let mut out_array = [0u8; core::mem::size_of::()]; @@ -56,10 +57,12 @@ impl Into for LogLend { } } -/// Return a `Connection` to the log server, which is used for printing messages to -/// the console and reporting panics. If the log server has not yet started, this -/// will block until the server is running. It is safe to call this multiple times, -/// because the address is shared among all threads in a process. +/// Returns a `Connection` to the log server, which is used for printing messages to +/// the console and reporting panics. +/// +/// If the log server has not yet started, this will block until the server is +/// running. It is safe to call this multiple times, because the address is +/// shared among all threads in a process. pub(crate) fn log_server() -> Connection { static LOG_SERVER_CONNECTION: AtomicU32 = AtomicU32::new(0); diff --git a/library/std/src/os/xous/services/net.rs b/library/std/src/os/xous/services/net.rs index 26d337dcef168..83acc7961b377 100644 --- a/library/std/src/os/xous/services/net.rs +++ b/library/std/src/os/xous/services/net.rs @@ -1,6 +1,7 @@ +use core::sync::atomic::{AtomicU32, Ordering}; + use crate::os::xous::ffi::Connection; use crate::os::xous::services::connect; -use core::sync::atomic::{AtomicU32, Ordering}; pub(crate) enum NetBlockingScalar { StdGetTtlUdp(u16 /* fd */), /* 36 */ @@ -80,7 +81,7 @@ impl<'a> Into<[usize; 5]> for NetBlockingScalar { } } -/// Return a `Connection` to the Network server. This server provides all +/// Returns a `Connection` to the Network server. This server provides all /// OS-level networking functions. pub(crate) fn net_server() -> Connection { static NET_CONNECTION: AtomicU32 = AtomicU32::new(0); diff --git a/library/std/src/os/xous/services/systime.rs b/library/std/src/os/xous/services/systime.rs index bbb875c69426e..079ede7aa86c7 100644 --- a/library/std/src/os/xous/services/systime.rs +++ b/library/std/src/os/xous/services/systime.rs @@ -1,6 +1,7 @@ -use crate::os::xous::ffi::{connect, Connection}; use core::sync::atomic::{AtomicU32, Ordering}; +use crate::os::xous::ffi::{connect, Connection}; + pub(crate) enum SystimeScalar { GetUtcTimeMs, } @@ -13,7 +14,7 @@ impl Into<[usize; 5]> for SystimeScalar { } } -/// Return a `Connection` to the systime server. This server is used for reporting the +/// Returns a `Connection` to the systime server. This server is used for reporting the /// realtime clock. pub(crate) fn systime_server() -> Connection { static SYSTIME_SERVER_CONNECTION: AtomicU32 = AtomicU32::new(0); diff --git a/library/std/src/os/xous/services/ticktimer.rs b/library/std/src/os/xous/services/ticktimer.rs index 7759303fdbe23..66ade6da65cd3 100644 --- a/library/std/src/os/xous/services/ticktimer.rs +++ b/library/std/src/os/xous/services/ticktimer.rs @@ -1,6 +1,7 @@ -use crate::os::xous::ffi::Connection; use core::sync::atomic::{AtomicU32, Ordering}; +use crate::os::xous::ffi::Connection; + pub(crate) enum TicktimerScalar { ElapsedMs, SleepMs(usize), @@ -27,7 +28,7 @@ impl Into<[usize; 5]> for TicktimerScalar { } } -/// Return a `Connection` to the ticktimer server. This server is used for synchronization +/// Returns a `Connection` to the ticktimer server. This server is used for synchronization /// primitives such as sleep, Mutex, and Condvar. pub(crate) fn ticktimer_server() -> Connection { static TICKTIMER_SERVER_CONNECTION: AtomicU32 = AtomicU32::new(0); diff --git a/library/std/src/panic.rs b/library/std/src/panic.rs index c5d1a893ee809..4c496ade81cda 100644 --- a/library/std/src/panic.rs +++ b/library/std/src/panic.rs @@ -3,12 +3,10 @@ #![stable(feature = "std_panic", since = "1.9.0")] use crate::any::Any; -use crate::collections; -use crate::fmt; -use crate::panicking; use crate::sync::atomic::{AtomicU8, Ordering}; use crate::sync::{Condvar, Mutex, RwLock}; use crate::thread::Result; +use crate::{collections, fmt, panicking}; #[stable(feature = "panic_hooks", since = "1.10.0")] #[deprecated( @@ -39,7 +37,7 @@ pub type PanicInfo<'a> = PanicHookInfo<'a>; /// ``` /// /// [`set_hook`]: ../../std/panic/fn.set_hook.html -#[stable(feature = "panic_hook_info", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "panic_hook_info", since = "1.81.0")] #[derive(Debug)] pub struct PanicHookInfo<'a> { payload: &'a (dyn Any + Send), @@ -236,20 +234,17 @@ pub macro panic_2015 { #[doc(hidden)] #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")] pub use core::panic::panic_2021; - #[stable(feature = "panic_hooks", since = "1.10.0")] -pub use crate::panicking::{set_hook, take_hook}; +pub use core::panic::Location; +#[stable(feature = "catch_unwind", since = "1.9.0")] +pub use core::panic::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe}; #[unstable(feature = "panic_update_hook", issue = "92649")] pub use crate::panicking::update_hook; - #[stable(feature = "panic_hooks", since = "1.10.0")] -pub use core::panic::Location; - -#[stable(feature = "catch_unwind", since = "1.9.0")] -pub use core::panic::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe}; +pub use crate::panicking::{set_hook, take_hook}; -/// Panic the current thread with the given message as the panic payload. +/// Panics the current thread with the given message as the panic payload. /// /// The message can be of any (`Any + Send`) type, not just strings. /// @@ -380,7 +375,7 @@ pub fn resume_unwind(payload: Box) -> ! { panicking::rust_panic_without_hook(payload) } -/// Make all future panics abort directly without running the panic hook or unwinding. +/// Makes all future panics abort directly without running the panic hook or unwinding. /// /// There is no way to undo this; the effect lasts until the process exits or /// execs (or the equivalent). @@ -461,18 +456,17 @@ impl BacktraceStyle { // Internally stores equivalent of an Option. static SHOULD_CAPTURE: AtomicU8 = AtomicU8::new(0); -/// Configure whether the default panic hook will capture and display a +/// Configures whether the default panic hook will capture and display a /// backtrace. /// /// The default value for this setting may be set by the `RUST_BACKTRACE` /// environment variable; see the details in [`get_backtrace_style`]. #[unstable(feature = "panic_backtrace_config", issue = "93346")] pub fn set_backtrace_style(style: BacktraceStyle) { - if !cfg!(feature = "backtrace") { - // If the `backtrace` feature of this crate isn't enabled, skip setting. - return; + if cfg!(feature = "backtrace") { + // If the `backtrace` feature of this crate is enabled, set the backtrace style. + SHOULD_CAPTURE.store(style.as_u8(), Ordering::Release); } - SHOULD_CAPTURE.store(style.as_u8(), Ordering::Release); } /// Checks whether the standard library's panic hook will capture and print a @@ -508,21 +502,13 @@ pub fn get_backtrace_style() -> Option { return Some(style); } - let format = crate::env::var_os("RUST_BACKTRACE") - .map(|x| { - if &x == "0" { - BacktraceStyle::Off - } else if &x == "full" { - BacktraceStyle::Full - } else { - BacktraceStyle::Short - } - }) - .unwrap_or(if crate::sys::FULL_BACKTRACE_DEFAULT { - BacktraceStyle::Full - } else { - BacktraceStyle::Off - }); + let format = match crate::env::var_os("RUST_BACKTRACE") { + Some(x) if &x == "0" => BacktraceStyle::Off, + Some(x) if &x == "full" => BacktraceStyle::Full, + Some(_) => BacktraceStyle::Short, + None if crate::sys::FULL_BACKTRACE_DEFAULT => BacktraceStyle::Full, + None => BacktraceStyle::Off, + }; set_backtrace_style(format); Some(format) } diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index 418a855fb728e..e818b448270dd 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -9,26 +9,23 @@ #![deny(unsafe_op_in_unsafe_fn)] -use crate::panic::{BacktraceStyle, PanicHookInfo}; use core::panic::{Location, PanicPayload}; +// make sure to use the stderr output configured +// by libtest in the real copy of std +#[cfg(test)] +use realstd::io::try_set_output_capture; + use crate::any::Any; -use crate::fmt; -use crate::intrinsics; +#[cfg(not(test))] +use crate::io::try_set_output_capture; use crate::mem::{self, ManuallyDrop}; -use crate::process; +use crate::panic::{BacktraceStyle, PanicHookInfo}; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sync::{PoisonError, RwLock}; use crate::sys::backtrace; use crate::sys::stdio::panic_output; -use crate::thread; - -#[cfg(not(test))] -use crate::io::try_set_output_capture; -// make sure to use the stderr output configured -// by libtest in the real copy of std -#[cfg(test)] -use realstd::io::try_set_output_capture; +use crate::{fmt, intrinsics, process, thread}; // Binary interface to the panic runtime that the standard library depends on. // diff --git a/library/std/src/path.rs b/library/std/src/path.rs index d5121a554bf6c..80163667636ae 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -71,22 +71,17 @@ mod tests; use crate::borrow::{Borrow, Cow}; -use crate::cmp; use crate::collections::TryReserveError; use crate::error::Error; -use crate::fmt; -use crate::fs; +use crate::ffi::{os_str, OsStr, OsString}; use crate::hash::{Hash, Hasher}; -use crate::io; use crate::iter::FusedIterator; use crate::ops::{self, Deref}; use crate::rc::Rc; use crate::str::FromStr; use crate::sync::Arc; - -use crate::ffi::{os_str, OsStr, OsString}; -use crate::sys; use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR}; +use crate::{cmp, fmt, fs, io, sys}; //////////////////////////////////////////////////////////////////////////////// // GENERAL NOTES @@ -1797,7 +1792,7 @@ impl> From<&T> for PathBuf { #[stable(feature = "rust1", since = "1.0.0")] impl From for PathBuf { - /// Converts an [`OsString`] into a [`PathBuf`] + /// Converts an [`OsString`] into a [`PathBuf`]. /// /// This conversion does not allocate or copy memory. #[inline] @@ -2079,10 +2074,8 @@ impl AsRef for PathBuf { #[stable(feature = "rust1", since = "1.0.0")] // `Path::new` current implementation relies // on `Path` being layout-compatible with `OsStr`. -// However, `Path` layout is considered an implementation detail and must not be relied upon. We -// want `repr(transparent)` but we don't want it to show up in rustdoc, so we hide it under -// `cfg(doc)`. This is an ad-hoc implementation of attribute privacy. -#[cfg_attr(not(doc), repr(transparent))] +// However, `Path` layout is considered an implementation detail and must not be relied upon. +#[repr(transparent)] pub struct Path { inner: OsStr, } diff --git a/library/std/src/path/tests.rs b/library/std/src/path/tests.rs index 3ade4fb892f5e..a12e42cba0c5c 100644 --- a/library/std/src/path/tests.rs +++ b/library/std/src/path/tests.rs @@ -1,8 +1,8 @@ -use super::*; +use core::hint::black_box; +use super::*; use crate::collections::{BTreeSet, HashSet}; use crate::hash::DefaultHasher; -use core::hint::black_box; #[allow(unknown_lints, unused_macro_rules)] macro_rules! t ( diff --git a/library/std/src/pipe.rs b/library/std/src/pipe.rs index f251b57a7cca6..aa4c7014fe918 100644 --- a/library/std/src/pipe.rs +++ b/library/std/src/pipe.rs @@ -11,10 +11,8 @@ //! # } //! ``` -use crate::{ - io, - sys::anonymous_pipe::{pipe as pipe_inner, AnonPipe}, -}; +use crate::io; +use crate::sys::anonymous_pipe::{pipe as pipe_inner, AnonPipe}; /// Create anonymous pipe that is close-on-exec and blocking. #[unstable(feature = "anonymous_pipe", issue = "127154")] diff --git a/library/std/src/sys/anonymous_pipe/tests.rs b/library/std/src/pipe/tests.rs similarity index 78% rename from library/std/src/sys/anonymous_pipe/tests.rs rename to library/std/src/pipe/tests.rs index f5ea583eefe0d..9c38e10678752 100644 --- a/library/std/src/sys/anonymous_pipe/tests.rs +++ b/library/std/src/pipe/tests.rs @@ -1,9 +1,8 @@ -use crate::{ - io::{Read, Write}, - pipe::pipe, -}; +use crate::io::{Read, Write}; +use crate::pipe::pipe; #[test] +#[cfg(all(windows, unix, not(miri)))] fn pipe_creation_clone_and_rw() { let (rx, tx) = pipe().unwrap(); diff --git a/library/std/src/process.rs b/library/std/src/process.rs index fc86578a5ff2f..9ffdebe1b6ffe 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -151,21 +151,18 @@ #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx", target_os = "xous"))))] mod tests; -use crate::io::prelude::*; - use crate::convert::Infallible; use crate::ffi::OsStr; -use crate::fmt; -use crate::fs; +use crate::io::prelude::*; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; use crate::num::NonZero; use crate::path::Path; -use crate::str; use crate::sys::pipe::{read2, AnonPipe}; use crate::sys::process as imp; #[stable(feature = "command_access", since = "1.57.0")] pub use crate::sys_common::process::CommandEnvs; use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; +use crate::{fmt, fs, str}; /// Representation of a running or exited child process. /// @@ -2056,7 +2053,7 @@ impl ExitCode { // representation of an ExitCode // // More info: https://internals.rust-lang.org/t/mini-pre-rfc-redesigning-process-exitstatus/5426 - /// Convert an `ExitCode` into an i32 + /// Converts an `ExitCode` into an i32 #[unstable( feature = "process_exitcode_internals", reason = "exposed only for libstd", @@ -2079,7 +2076,7 @@ impl Default for ExitCode { #[stable(feature = "process_exitcode", since = "1.61.0")] impl From for ExitCode { - /// Construct an `ExitCode` from an arbitrary u8 value. + /// Constructs an `ExitCode` from an arbitrary u8 value. fn from(code: u8) -> Self { ExitCode(imp::ExitCode::from(code)) } diff --git a/library/std/src/process/tests.rs b/library/std/src/process/tests.rs index 055601d030799..f8e8e0dea553b 100644 --- a/library/std/src/process/tests.rs +++ b/library/std/src/process/tests.rs @@ -1,6 +1,5 @@ -use crate::io::prelude::*; - use super::{Command, Output, Stdio}; +use crate::io::prelude::*; use crate::io::{BorrowedBuf, ErrorKind}; use crate::mem::MaybeUninit; use crate::str; diff --git a/library/std/src/rt.rs b/library/std/src/rt.rs index deb4a8fa7eed0..307a543c9d215 100644 --- a/library/std/src/rt.rs +++ b/library/std/src/rt.rs @@ -16,9 +16,11 @@ #![deny(unsafe_op_in_unsafe_fn)] #![allow(unused_macros)] +#[rustfmt::skip] pub use crate::panicking::{begin_panic, panic_count}; pub use core::panicking::{panic_display, panic_fmt}; +#[rustfmt::skip] use crate::sync::Once; use crate::sys; use crate::thread::{self, Thread}; diff --git a/library/std/src/sync/lazy_lock.rs b/library/std/src/sync/lazy_lock.rs index 18906aceffa30..953aef40e7b76 100644 --- a/library/std/src/sync/lazy_lock.rs +++ b/library/std/src/sync/lazy_lock.rs @@ -1,3 +1,4 @@ +use super::once::ExclusiveState; use crate::cell::UnsafeCell; use crate::mem::ManuallyDrop; use crate::ops::Deref; @@ -5,8 +6,6 @@ use crate::panic::{RefUnwindSafe, UnwindSafe}; use crate::sync::Once; use crate::{fmt, ptr}; -use super::once::ExclusiveState; - // We use the state of a Once as discriminant value. Upon creation, the state is // "incomplete" and `f` contains the initialization closure. In the first call to // `call_once`, `f` is taken and run. If it succeeds, `value` is set and the state @@ -175,7 +174,7 @@ impl T> LazyLock { } impl LazyLock { - /// Get the inner value if it has already been initialized. + /// Gets the inner value if it has already been initialized. fn get(&self) -> Option<&T> { if self.once.is_completed() { // SAFETY: diff --git a/library/std/src/sync/lazy_lock/tests.rs b/library/std/src/sync/lazy_lock/tests.rs index a5d4e25c5962a..8a6ab4ac4fd99 100644 --- a/library/std/src/sync/lazy_lock/tests.rs +++ b/library/std/src/sync/lazy_lock/tests.rs @@ -1,13 +1,8 @@ -use crate::{ - cell::LazyCell, - panic, - sync::{ - atomic::{AtomicUsize, Ordering::SeqCst}, - Mutex, - }, - sync::{LazyLock, OnceLock}, - thread, -}; +use crate::cell::LazyCell; +use crate::sync::atomic::AtomicUsize; +use crate::sync::atomic::Ordering::SeqCst; +use crate::sync::{LazyLock, Mutex, OnceLock}; +use crate::{panic, thread}; fn spawn_and_wait(f: impl FnOnce() -> R + Send + 'static) -> R { thread::spawn(f).join().unwrap() diff --git a/library/std/src/sync/mod.rs b/library/std/src/sync/mod.rs index 9a38c42f43a02..d0ba8cc3b47df 100644 --- a/library/std/src/sync/mod.rs +++ b/library/std/src/sync/mod.rs @@ -158,17 +158,20 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::sync::{Arc, Weak}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::sync::atomic; #[unstable(feature = "exclusive_wrapper", issue = "98407")] pub use core::sync::Exclusive; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::sync::{Arc, Weak}; + #[stable(feature = "rust1", since = "1.0.0")] pub use self::barrier::{Barrier, BarrierWaitResult}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::condvar::{Condvar, WaitTimeoutResult}; +#[stable(feature = "lazy_cell", since = "1.80.0")] +pub use self::lazy_lock::LazyLock; #[unstable(feature = "mapped_lock_guards", issue = "117108")] pub use self::mutex::MappedMutexGuard; #[stable(feature = "rust1", since = "1.0.0")] @@ -176,21 +179,17 @@ pub use self::mutex::{Mutex, MutexGuard}; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] pub use self::once::{Once, OnceState, ONCE_INIT}; +#[stable(feature = "once_cell", since = "1.70.0")] +pub use self::once_lock::OnceLock; #[stable(feature = "rust1", since = "1.0.0")] pub use self::poison::{LockResult, PoisonError, TryLockError, TryLockResult}; +#[unstable(feature = "reentrant_lock", issue = "121440")] +pub use self::reentrant_lock::{ReentrantLock, ReentrantLockGuard}; #[unstable(feature = "mapped_lock_guards", issue = "117108")] pub use self::rwlock::{MappedRwLockReadGuard, MappedRwLockWriteGuard}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard}; -#[stable(feature = "lazy_cell", since = "1.80.0")] -pub use self::lazy_lock::LazyLock; -#[stable(feature = "once_cell", since = "1.70.0")] -pub use self::once_lock::OnceLock; - -#[unstable(feature = "reentrant_lock", issue = "121440")] -pub use self::reentrant_lock::{ReentrantLock, ReentrantLockGuard}; - pub mod mpsc; mod barrier; diff --git a/library/std/src/sync/mpmc/array.rs b/library/std/src/sync/mpmc/array.rs index 185319add745f..34acd9c9a943b 100644 --- a/library/std/src/sync/mpmc/array.rs +++ b/library/std/src/sync/mpmc/array.rs @@ -13,7 +13,6 @@ use super::error::*; use super::select::{Operation, Selected, Token}; use super::utils::{Backoff, CachePadded}; use super::waker::SyncWaker; - use crate::cell::UnsafeCell; use crate::mem::MaybeUninit; use crate::ptr; diff --git a/library/std/src/sync/mpmc/context.rs b/library/std/src/sync/mpmc/context.rs index bbfc6ce00ffc2..8db3c9896eb77 100644 --- a/library/std/src/sync/mpmc/context.rs +++ b/library/std/src/sync/mpmc/context.rs @@ -2,7 +2,6 @@ use super::select::Selected; use super::waker::current_thread_id; - use crate::cell::Cell; use crate::ptr; use crate::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; diff --git a/library/std/src/sync/mpmc/counter.rs b/library/std/src/sync/mpmc/counter.rs index 3478cf41dc9d2..d1bfe612f536f 100644 --- a/library/std/src/sync/mpmc/counter.rs +++ b/library/std/src/sync/mpmc/counter.rs @@ -1,6 +1,5 @@ -use crate::ops; -use crate::process; use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use crate::{ops, process}; /// Reference counter internals. struct Counter { diff --git a/library/std/src/sync/mpmc/error.rs b/library/std/src/sync/mpmc/error.rs index 33b2bff853498..e3aec7e76232f 100644 --- a/library/std/src/sync/mpmc/error.rs +++ b/library/std/src/sync/mpmc/error.rs @@ -1,7 +1,5 @@ -use crate::error; -use crate::fmt; - pub use crate::sync::mpsc::{RecvError, RecvTimeoutError, SendError, TryRecvError, TrySendError}; +use crate::{error, fmt}; /// An error returned from the [`send_timeout`] method. /// diff --git a/library/std/src/sync/mpmc/list.rs b/library/std/src/sync/mpmc/list.rs index edac7a0cb1835..bbe205cad04e6 100644 --- a/library/std/src/sync/mpmc/list.rs +++ b/library/std/src/sync/mpmc/list.rs @@ -5,7 +5,6 @@ use super::error::*; use super::select::{Operation, Selected, Token}; use super::utils::{Backoff, CachePadded}; use super::waker::SyncWaker; - use crate::cell::UnsafeCell; use crate::marker::PhantomData; use crate::mem::MaybeUninit; diff --git a/library/std/src/sync/mpmc/mod.rs b/library/std/src/sync/mpmc/mod.rs index 2068dda393a2b..c640e07348ea0 100644 --- a/library/std/src/sync/mpmc/mod.rs +++ b/library/std/src/sync/mpmc/mod.rs @@ -40,10 +40,11 @@ mod utils; mod waker; mod zero; +pub use error::*; + use crate::fmt; use crate::panic::{RefUnwindSafe, UnwindSafe}; use crate::time::{Duration, Instant}; -pub use error::*; /// Creates a channel of unbounded capacity. /// diff --git a/library/std/src/sync/mpmc/waker.rs b/library/std/src/sync/mpmc/waker.rs index 9aab1b9417edb..fb877887f9c9d 100644 --- a/library/std/src/sync/mpmc/waker.rs +++ b/library/std/src/sync/mpmc/waker.rs @@ -2,7 +2,6 @@ use super::context::Context; use super::select::{Operation, Selected}; - use crate::ptr; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sync::Mutex; diff --git a/library/std/src/sync/mpmc/zero.rs b/library/std/src/sync/mpmc/zero.rs index 6d1c9d64e7a7a..2b82eeda3d5fb 100644 --- a/library/std/src/sync/mpmc/zero.rs +++ b/library/std/src/sync/mpmc/zero.rs @@ -7,7 +7,6 @@ use super::error::*; use super::select::{Operation, Selected, Token}; use super::utils::Backoff; use super::waker::Waker; - use crate::cell::UnsafeCell; use crate::marker::PhantomData; use crate::sync::atomic::{AtomicBool, Ordering}; diff --git a/library/std/src/sync/mpsc/mod.rs b/library/std/src/sync/mpsc/mod.rs index feee6948db4fd..26d5b9515a244 100644 --- a/library/std/src/sync/mpsc/mod.rs +++ b/library/std/src/sync/mpsc/mod.rs @@ -148,10 +148,9 @@ mod sync_tests; // not exposed publicly, but if you are curious about the implementation, // that's where everything is. -use crate::error; -use crate::fmt; use crate::sync::mpmc; use crate::time::{Duration, Instant}; +use crate::{error, fmt}; /// The receiving half of Rust's [`channel`] (or [`sync_channel`]) type. /// This half can only be owned by one thread. diff --git a/library/std/src/sync/mpsc/sync_tests.rs b/library/std/src/sync/mpsc/sync_tests.rs index 945de280f40d8..49b65c8efe692 100644 --- a/library/std/src/sync/mpsc/sync_tests.rs +++ b/library/std/src/sync/mpsc/sync_tests.rs @@ -1,8 +1,7 @@ use super::*; -use crate::env; use crate::rc::Rc; use crate::sync::mpmc::SendTimeoutError; -use crate::thread; +use crate::{env, thread}; pub fn stress_factor() -> usize { match env::var("RUST_TEST_STRESS") { diff --git a/library/std/src/sync/mpsc/tests.rs b/library/std/src/sync/mpsc/tests.rs index ac1a804cf9c84..13892fa0d18e4 100644 --- a/library/std/src/sync/mpsc/tests.rs +++ b/library/std/src/sync/mpsc/tests.rs @@ -1,6 +1,5 @@ use super::*; -use crate::env; -use crate::thread; +use crate::{env, thread}; pub fn stress_factor() -> usize { match env::var("RUST_TEST_STRESS") { diff --git a/library/std/src/sync/once.rs b/library/std/src/sync/once.rs index 9d969af8c6d84..bf595fdea2d25 100644 --- a/library/std/src/sync/once.rs +++ b/library/std/src/sync/once.rs @@ -70,7 +70,7 @@ pub(crate) enum ExclusiveState { #[stable(feature = "rust1", since = "1.0.0")] #[deprecated( since = "1.38.0", - note = "the `new` function is now preferred", + note = "the `Once::new()` function is now preferred", suggestion = "Once::new()" )] pub const ONCE_INIT: Once = Once::new(); @@ -264,6 +264,47 @@ impl Once { self.inner.is_completed() } + /// Blocks the current thread until initialization has completed. + /// + /// # Example + /// + /// ```rust + /// #![feature(once_wait)] + /// + /// use std::sync::Once; + /// use std::thread; + /// + /// static READY: Once = Once::new(); + /// + /// let thread = thread::spawn(|| { + /// READY.wait(); + /// println!("everything is ready"); + /// }); + /// + /// READY.call_once(|| println!("performing setup")); + /// ``` + /// + /// # Panics + /// + /// If this [`Once`] has been poisoned because an initialization closure has + /// panicked, this method will also panic. Use [`wait_force`](Self::wait_force) + /// if this behaviour is not desired. + #[unstable(feature = "once_wait", issue = "127527")] + pub fn wait(&self) { + if !self.inner.is_completed() { + self.inner.wait(false); + } + } + + /// Blocks the current thread until initialization has completed, ignoring + /// poisoning. + #[unstable(feature = "once_wait", issue = "127527")] + pub fn wait_force(&self) { + if !self.inner.is_completed() { + self.inner.wait(true); + } + } + /// Returns the current state of the `Once` instance. /// /// Since this takes a mutable reference, no initialization can currently diff --git a/library/std/src/sync/once/tests.rs b/library/std/src/sync/once/tests.rs index 0c35597e11c51..ce96468aeb6e1 100644 --- a/library/std/src/sync/once/tests.rs +++ b/library/std/src/sync/once/tests.rs @@ -1,7 +1,9 @@ use super::Once; -use crate::panic; +use crate::sync::atomic::AtomicBool; +use crate::sync::atomic::Ordering::Relaxed; use crate::sync::mpsc::channel; -use crate::thread; +use crate::time::Duration; +use crate::{panic, thread}; #[test] fn smoke_once() { @@ -114,3 +116,47 @@ fn wait_for_force_to_finish() { assert!(t1.join().is_ok()); assert!(t2.join().is_ok()); } + +#[test] +fn wait() { + for _ in 0..50 { + let val = AtomicBool::new(false); + let once = Once::new(); + + thread::scope(|s| { + for _ in 0..4 { + s.spawn(|| { + once.wait(); + assert!(val.load(Relaxed)); + }); + } + + once.call_once(|| val.store(true, Relaxed)); + }); + } +} + +#[test] +fn wait_on_poisoned() { + let once = Once::new(); + + panic::catch_unwind(|| once.call_once(|| panic!())).unwrap_err(); + panic::catch_unwind(|| once.wait()).unwrap_err(); +} + +#[test] +fn wait_force_on_poisoned() { + let once = Once::new(); + + thread::scope(|s| { + panic::catch_unwind(|| once.call_once(|| panic!())).unwrap_err(); + + s.spawn(|| { + thread::sleep(Duration::from_millis(100)); + + once.call_once_force(|_| {}); + }); + + once.wait_force(); + }) +} diff --git a/library/std/src/sync/once_lock.rs b/library/std/src/sync/once_lock.rs index 94955beaf37b7..56cf877ddc6d5 100644 --- a/library/std/src/sync/once_lock.rs +++ b/library/std/src/sync/once_lock.rs @@ -167,6 +167,34 @@ impl OnceLock { } } + /// Blocks the current thread until the cell is initialized. + /// + /// # Example + /// + /// Waiting for a computation on another thread to finish: + /// ```rust + /// #![feature(once_wait)] + /// + /// use std::thread; + /// use std::sync::OnceLock; + /// + /// let value = OnceLock::new(); + /// + /// thread::scope(|s| { + /// s.spawn(|| value.set(1 + 1)); + /// + /// let result = value.wait(); + /// assert_eq!(result, &2); + /// }) + /// ``` + #[inline] + #[unstable(feature = "once_wait", issue = "127527")] + pub fn wait(&self) -> &T { + self.once.wait_force(); + + unsafe { self.get_unchecked() } + } + /// Sets the contents of this cell to `value`. /// /// May block if another thread is currently attempting to initialize the cell. The cell is @@ -281,9 +309,7 @@ impl OnceLock { /// Gets the mutable reference of the contents of the cell, initializing /// it with `f` if the cell was empty. /// - /// Many threads may call `get_mut_or_init` concurrently with different - /// initializing functions, but it is guaranteed that only one function - /// will be executed. + /// This method never blocks. /// /// # Panics /// @@ -373,6 +399,8 @@ impl OnceLock { /// it with `f` if the cell was empty. If the cell was empty and `f` failed, /// an error is returned. /// + /// This method never blocks. + /// /// # Panics /// /// If `f` panics, the panic is propagated to the caller, and @@ -578,7 +606,7 @@ impl Clone for OnceLock { #[stable(feature = "once_cell", since = "1.70.0")] impl From for OnceLock { - /// Create a new cell with its contents set to `value`. + /// Creates a new cell with its contents set to `value`. /// /// # Example /// diff --git a/library/std/src/sync/once_lock/tests.rs b/library/std/src/sync/once_lock/tests.rs index d5d32e73d8880..176830c6748b2 100644 --- a/library/std/src/sync/once_lock/tests.rs +++ b/library/std/src/sync/once_lock/tests.rs @@ -1,12 +1,8 @@ -use crate::{ - panic, - sync::OnceLock, - sync::{ - atomic::{AtomicUsize, Ordering::SeqCst}, - mpsc::channel, - }, - thread, -}; +use crate::sync::atomic::AtomicUsize; +use crate::sync::atomic::Ordering::SeqCst; +use crate::sync::mpsc::channel; +use crate::sync::OnceLock; +use crate::{panic, thread}; fn spawn_and_wait(f: impl FnOnce() -> R + Send + 'static) -> R { thread::spawn(f).join().unwrap() diff --git a/library/std/src/sync/poison.rs b/library/std/src/sync/poison.rs index f4975088b372d..da66a088e51b1 100644 --- a/library/std/src/sync/poison.rs +++ b/library/std/src/sync/poison.rs @@ -1,6 +1,5 @@ use crate::error::Error; use crate::fmt; - #[cfg(panic = "unwind")] use crate::sync::atomic::{AtomicBool, Ordering}; #[cfg(panic = "unwind")] @@ -31,13 +30,13 @@ impl Flag { } } - /// Check the flag for an unguarded borrow, where we only care about existing poison. + /// Checks the flag for an unguarded borrow, where we only care about existing poison. #[inline] pub fn borrow(&self) -> LockResult<()> { if self.get() { Err(PoisonError::new(())) } else { Ok(()) } } - /// Check the flag for a guarded borrow, where we may also set poison when `done`. + /// Checks the flag for a guarded borrow, where we may also set poison when `done`. #[inline] pub fn guard(&self) -> LockResult { let ret = Guard { diff --git a/library/std/src/sync/rwlock.rs b/library/std/src/sync/rwlock.rs index a4ec52a4abe63..d995a16e056d6 100644 --- a/library/std/src/sync/rwlock.rs +++ b/library/std/src/sync/rwlock.rs @@ -573,7 +573,7 @@ impl From for RwLock { } impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> { - /// Create a new instance of `RwLockReadGuard` from a `RwLock`. + /// Creates a new instance of `RwLockReadGuard` from a `RwLock`. // SAFETY: if and only if `lock.inner.read()` (or `lock.inner.try_read()`) has been // successfully called from the same thread before instantiating this object. unsafe fn new(lock: &'rwlock RwLock) -> LockResult> { @@ -585,7 +585,7 @@ impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> { } impl<'rwlock, T: ?Sized> RwLockWriteGuard<'rwlock, T> { - /// Create a new instance of `RwLockWriteGuard` from a `RwLock`. + /// Creates a new instance of `RwLockWriteGuard` from a `RwLock`. // SAFETY: if and only if `lock.inner.write()` (or `lock.inner.try_write()`) has been // successfully called from the same thread before instantiating this object. unsafe fn new(lock: &'rwlock RwLock) -> LockResult> { diff --git a/library/std/src/sync/rwlock/tests.rs b/library/std/src/sync/rwlock/tests.rs index 9cc5e7a3a60f1..12bb0fbf0503b 100644 --- a/library/std/src/sync/rwlock/tests.rs +++ b/library/std/src/sync/rwlock/tests.rs @@ -1,3 +1,5 @@ +use rand::Rng; + use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sync::mpsc::channel; use crate::sync::{ @@ -5,7 +7,6 @@ use crate::sync::{ TryLockError, }; use crate::thread; -use rand::Rng; #[derive(Eq, PartialEq, Debug)] struct NonCopy(i32); diff --git a/library/std/src/sys/anonymous_pipe/mod.rs b/library/std/src/sys/anonymous_pipe/mod.rs index 74875677cf3e7..aa14c8b650d34 100644 --- a/library/std/src/sys/anonymous_pipe/mod.rs +++ b/library/std/src/sys/anonymous_pipe/mod.rs @@ -1,18 +1,14 @@ +#![forbid(unsafe_op_in_unsafe_fn)] + cfg_if::cfg_if! { if #[cfg(unix)] { mod unix; - pub(crate) use unix::{AnonPipe, pipe}; - - #[cfg(all(test, not(miri)))] - mod tests; + pub use unix::{AnonPipe, pipe}; } else if #[cfg(windows)] { mod windows; - pub(crate) use windows::{AnonPipe, pipe}; - - #[cfg(all(test, not(miri)))] - mod tests; + pub use windows::{AnonPipe, pipe}; } else { mod unsupported; - pub(crate) use unsupported::{AnonPipe, pipe}; + pub use unsupported::{AnonPipe, pipe}; } } diff --git a/library/std/src/sys/anonymous_pipe/unix.rs b/library/std/src/sys/anonymous_pipe/unix.rs index ddbf1d7334fe0..9168024730e67 100644 --- a/library/std/src/sys/anonymous_pipe/unix.rs +++ b/library/std/src/sys/anonymous_pipe/unix.rs @@ -1,16 +1,15 @@ -use crate::{ - io, - os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}, - pipe::{PipeReader, PipeWriter}, - process::Stdio, - sys::{fd::FileDesc, pipe::anon_pipe}, - sys_common::{FromInner, IntoInner}, -}; +use crate::io; +use crate::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; +use crate::pipe::{PipeReader, PipeWriter}; +use crate::process::Stdio; +use crate::sys::fd::FileDesc; +use crate::sys::pipe::anon_pipe; +use crate::sys_common::{FromInner, IntoInner}; -pub(crate) type AnonPipe = FileDesc; +pub type AnonPipe = FileDesc; #[inline] -pub(crate) fn pipe() -> io::Result<(AnonPipe, AnonPipe)> { +pub fn pipe() -> io::Result<(AnonPipe, AnonPipe)> { anon_pipe().map(|(rx, wx)| (rx.into_inner(), wx.into_inner())) } @@ -35,7 +34,7 @@ impl From for OwnedFd { #[unstable(feature = "anonymous_pipe", issue = "127154")] impl FromRawFd for PipeReader { unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { - Self(FileDesc::from_raw_fd(raw_fd)) + unsafe { Self(FileDesc::from_raw_fd(raw_fd)) } } } #[unstable(feature = "anonymous_pipe", issue = "127154")] @@ -72,7 +71,7 @@ impl From for OwnedFd { #[unstable(feature = "anonymous_pipe", issue = "127154")] impl FromRawFd for PipeWriter { unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { - Self(FileDesc::from_raw_fd(raw_fd)) + unsafe { Self(FileDesc::from_raw_fd(raw_fd)) } } } #[unstable(feature = "anonymous_pipe", issue = "127154")] diff --git a/library/std/src/sys/anonymous_pipe/unsupported.rs b/library/std/src/sys/anonymous_pipe/unsupported.rs index 5962b69203ee2..dd51e70315e96 100644 --- a/library/std/src/sys/anonymous_pipe/unsupported.rs +++ b/library/std/src/sys/anonymous_pipe/unsupported.rs @@ -1,13 +1,10 @@ -use crate::{ - io, - pipe::{PipeReader, PipeWriter}, - process::Stdio, -}; - -pub(crate) use crate::sys::pipe::AnonPipe; +use crate::io; +use crate::pipe::{PipeReader, PipeWriter}; +use crate::process::Stdio; +pub use crate::sys::pipe::AnonPipe; #[inline] -pub(crate) fn pipe() -> io::Result<(AnonPipe, AnonPipe)> { +pub fn pipe() -> io::Result<(AnonPipe, AnonPipe)> { Err(io::Error::UNSUPPORTED_PLATFORM) } diff --git a/library/std/src/sys/anonymous_pipe/windows.rs b/library/std/src/sys/anonymous_pipe/windows.rs index 81f95aa286a9c..a48198f8a812b 100644 --- a/library/std/src/sys/anonymous_pipe/windows.rs +++ b/library/std/src/sys/anonymous_pipe/windows.rs @@ -1,19 +1,26 @@ -use crate::{ - io, - os::windows::io::{ - AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle, OwnedHandle, RawHandle, - }, - pipe::{PipeReader, PipeWriter}, - process::Stdio, - sys::{handle::Handle, pipe::unnamed_anon_pipe}, - sys_common::{FromInner, IntoInner}, +use crate::os::windows::io::{ + AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle, OwnedHandle, RawHandle, }; +use crate::pipe::{PipeReader, PipeWriter}; +use crate::process::Stdio; +use crate::sys::c; +use crate::sys::handle::Handle; +use crate::sys_common::{FromInner, IntoInner}; +use crate::{io, ptr}; -pub(crate) type AnonPipe = Handle; +pub type AnonPipe = Handle; -#[inline] -pub(crate) fn pipe() -> io::Result<(AnonPipe, AnonPipe)> { - unnamed_anon_pipe().map(|(rx, wx)| (rx.into_inner(), wx.into_inner())) +pub fn pipe() -> io::Result<(AnonPipe, AnonPipe)> { + let mut read_pipe = c::INVALID_HANDLE_VALUE; + let mut write_pipe = c::INVALID_HANDLE_VALUE; + + let ret = unsafe { c::CreatePipe(&mut read_pipe, &mut write_pipe, ptr::null_mut(), 0) }; + + if ret == 0 { + Err(io::Error::last_os_error()) + } else { + unsafe { Ok((Handle::from_raw_handle(read_pipe), Handle::from_raw_handle(write_pipe))) } + } } #[unstable(feature = "anonymous_pipe", issue = "127154")] @@ -32,7 +39,7 @@ impl AsRawHandle for PipeReader { #[unstable(feature = "anonymous_pipe", issue = "127154")] impl FromRawHandle for PipeReader { unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self { - Self(Handle::from_raw_handle(raw_handle)) + unsafe { Self(Handle::from_raw_handle(raw_handle)) } } } #[unstable(feature = "anonymous_pipe", issue = "127154")] @@ -71,7 +78,7 @@ impl AsRawHandle for PipeWriter { #[unstable(feature = "anonymous_pipe", issue = "127154")] impl FromRawHandle for PipeWriter { unsafe fn from_raw_handle(raw_handle: RawHandle) -> Self { - Self(Handle::from_raw_handle(raw_handle)) + unsafe { Self(Handle::from_raw_handle(raw_handle)) } } } #[unstable(feature = "anonymous_pipe", issue = "127154")] diff --git a/library/std/src/sys/backtrace.rs b/library/std/src/sys/backtrace.rs index 133ea520e30c7..4d939e175cf2e 100644 --- a/library/std/src/sys/backtrace.rs +++ b/library/std/src/sys/backtrace.rs @@ -3,12 +3,10 @@ use crate::backtrace_rs::{self, BacktraceFmt, BytesOrWideString, PrintFmt}; use crate::borrow::Cow; -use crate::env; -use crate::fmt; -use crate::io; use crate::io::prelude::*; use crate::path::{self, Path, PathBuf}; use crate::sync::{Mutex, MutexGuard, PoisonError}; +use crate::{env, fmt, io}; /// Max number of frames to print. const MAX_NB_FRAMES: usize = 100; diff --git a/library/std/src/sys/mod.rs b/library/std/src/sys/mod.rs index 202997b749513..a86b3628f249a 100644 --- a/library/std/src/sys/mod.rs +++ b/library/std/src/sys/mod.rs @@ -7,7 +7,6 @@ mod pal; mod personality; -#[unstable(feature = "anonymous_pipe", issue = "127154")] pub mod anonymous_pipe; pub mod backtrace; pub mod cmath; diff --git a/library/std/src/sys/os_str/bytes.rs b/library/std/src/sys/os_str/bytes.rs index 2a7477e3afc20..0f8bd6453528e 100644 --- a/library/std/src/sys/os_str/bytes.rs +++ b/library/std/src/sys/os_str/bytes.rs @@ -3,13 +3,11 @@ use crate::borrow::Cow; use crate::collections::TryReserveError; -use crate::fmt; use crate::fmt::Write; -use crate::mem; use crate::rc::Rc; -use crate::str; use crate::sync::Arc; use crate::sys_common::{AsInner, IntoInner}; +use crate::{fmt, mem, str}; #[cfg(test)] mod tests; diff --git a/library/std/src/sys/os_str/wtf8.rs b/library/std/src/sys/os_str/wtf8.rs index 806bf033dbc94..ed975ba58b5e2 100644 --- a/library/std/src/sys/os_str/wtf8.rs +++ b/library/std/src/sys/os_str/wtf8.rs @@ -2,12 +2,11 @@ //! wrapper around the "WTF-8" encoding; see the `wtf8` module for more. use crate::borrow::Cow; use crate::collections::TryReserveError; -use crate::fmt; -use crate::mem; use crate::rc::Rc; use crate::sync::Arc; use crate::sys_common::wtf8::{check_utf8_boundary, Wtf8, Wtf8Buf}; use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::{fmt, mem}; #[derive(Clone, Hash)] pub struct Buf { diff --git a/library/std/src/sys/pal/common/alloc.rs b/library/std/src/sys/pal/common/alloc.rs index 54506c3229675..1b465f95d1bc3 100644 --- a/library/std/src/sys/pal/common/alloc.rs +++ b/library/std/src/sys/pal/common/alloc.rs @@ -1,7 +1,6 @@ #![forbid(unsafe_op_in_unsafe_fn)] use crate::alloc::{GlobalAlloc, Layout, System}; -use crate::cmp; -use crate::ptr; +use crate::{cmp, ptr}; // The minimum alignment guaranteed by the architecture. This value is used to // add fast paths for low alignment values. diff --git a/library/std/src/sys/pal/common/small_c_string.rs b/library/std/src/sys/pal/common/small_c_string.rs index 37812fc0659a2..3c96714b5c58c 100644 --- a/library/std/src/sys/pal/common/small_c_string.rs +++ b/library/std/src/sys/pal/common/small_c_string.rs @@ -1,8 +1,7 @@ use crate::ffi::{CStr, CString}; use crate::mem::MaybeUninit; use crate::path::Path; -use crate::slice; -use crate::{io, ptr}; +use crate::{io, ptr, slice}; // Make sure to stay under 4096 so the compiler doesn't insert a probe frame: // https://docs.rs/compiler_builtins/latest/compiler_builtins/probestack/index.html diff --git a/library/std/src/sys/pal/common/tests.rs b/library/std/src/sys/pal/common/tests.rs index e72d02203da10..b7698907070c7 100644 --- a/library/std/src/sys/pal/common/tests.rs +++ b/library/std/src/sys/pal/common/tests.rs @@ -1,8 +1,9 @@ +use core::iter::repeat; + use crate::ffi::CString; use crate::hint::black_box; use crate::path::Path; use crate::sys::common::small_c_string::run_path_with_cstr; -use core::iter::repeat; #[test] fn stack_allocation_works() { diff --git a/library/std/src/sys/pal/hermit/alloc.rs b/library/std/src/sys/pal/hermit/alloc.rs index 2cd0db909403b..f10d5f9227e63 100644 --- a/library/std/src/sys/pal/hermit/alloc.rs +++ b/library/std/src/sys/pal/hermit/alloc.rs @@ -1,31 +1,28 @@ use super::hermit_abi; use crate::alloc::{GlobalAlloc, Layout, System}; -use crate::ptr; #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - hermit_abi::malloc(layout.size(), layout.align()) - } - - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - let addr = hermit_abi::malloc(layout.size(), layout.align()); - - if !addr.is_null() { - ptr::write_bytes(addr, 0x00, layout.size()); - } - - addr + let size = layout.size(); + let align = layout.align(); + unsafe { hermit_abi::malloc(size, align) } } #[inline] unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - hermit_abi::free(ptr, layout.size(), layout.align()) + let size = layout.size(); + let align = layout.align(); + unsafe { + hermit_abi::free(ptr, size, align); + } } #[inline] unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { - hermit_abi::realloc(ptr, layout.size(), layout.align(), new_size) + let size = layout.size(); + let align = layout.align(); + unsafe { hermit_abi::realloc(ptr, size, align, new_size) } } } diff --git a/library/std/src/sys/pal/hermit/args.rs b/library/std/src/sys/pal/hermit/args.rs index 220a76e4b1237..51afe3434aedc 100644 --- a/library/std/src/sys/pal/hermit/args.rs +++ b/library/std/src/sys/pal/hermit/args.rs @@ -1,12 +1,8 @@ use crate::ffi::{c_char, CStr, OsString}; -use crate::fmt; use crate::os::hermit::ffi::OsStringExt; -use crate::ptr; -use crate::sync::atomic::{ - AtomicIsize, AtomicPtr, - Ordering::{Acquire, Relaxed, Release}, -}; -use crate::vec; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use crate::sync::atomic::{AtomicIsize, AtomicPtr}; +use crate::{fmt, ptr, vec}; static ARGC: AtomicIsize = AtomicIsize::new(0); static ARGV: AtomicPtr<*const u8> = AtomicPtr::new(ptr::null_mut()); diff --git a/library/std/src/sys/pal/hermit/fd.rs b/library/std/src/sys/pal/hermit/fd.rs index 3c52b85de23a2..79fc13bd4a87f 100644 --- a/library/std/src/sys/pal/hermit/fd.rs +++ b/library/std/src/sys/pal/hermit/fd.rs @@ -3,13 +3,10 @@ use super::hermit_abi; use crate::cmp; use crate::io::{self, IoSlice, IoSliceMut, Read}; -use crate::os::hermit::io::{FromRawFd, OwnedFd, RawFd}; -use crate::sys::cvt; -use crate::sys::unsupported; +use crate::os::hermit::io::{FromRawFd, OwnedFd, RawFd, *}; +use crate::sys::{cvt, unsupported}; use crate::sys_common::{AsInner, FromInner, IntoInner}; -use crate::os::hermit::io::*; - const fn max_iov() -> usize { hermit_abi::IOV_MAX } @@ -114,7 +111,8 @@ impl FromInner for FileDesc { impl FromRawFd for FileDesc { unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { - Self { fd: FromRawFd::from_raw_fd(raw_fd) } + let fd = unsafe { OwnedFd::from_raw_fd(raw_fd) }; + Self { fd } } } diff --git a/library/std/src/sys/pal/hermit/fs.rs b/library/std/src/sys/pal/hermit/fs.rs index e4e9eee044efa..aaf1a044d0613 100644 --- a/library/std/src/sys/pal/hermit/fs.rs +++ b/library/std/src/sys/pal/hermit/fs.rs @@ -4,21 +4,17 @@ use super::hermit_abi::{ O_DIRECTORY, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, S_IFDIR, S_IFLNK, S_IFMT, S_IFREG, }; use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; -use crate::io::{self, Error, ErrorKind}; -use crate::io::{BorrowedCursor, IoSlice, IoSliceMut, SeekFrom}; -use crate::mem; +use crate::io::{self, BorrowedCursor, Error, ErrorKind, IoSlice, IoSliceMut, SeekFrom}; use crate::os::hermit::ffi::OsStringExt; use crate::os::hermit::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::path::{Path, PathBuf}; use crate::sync::Arc; use crate::sys::common::small_c_string::run_path_with_cstr; -use crate::sys::cvt; use crate::sys::time::SystemTime; -use crate::sys::unsupported; -use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; - +use crate::sys::{cvt, unsupported}; pub use crate::sys_common::fs::{copy, exists}; +use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; +use crate::{fmt, mem}; #[derive(Debug)] pub struct File(FileDesc); @@ -488,7 +484,8 @@ impl IntoRawFd for File { impl FromRawFd for File { unsafe fn from_raw_fd(raw_fd: RawFd) -> Self { - Self(FromRawFd::from_raw_fd(raw_fd)) + let file_desc = unsafe { FileDesc::from_raw_fd(raw_fd) }; + Self(file_desc) } } diff --git a/library/std/src/sys/pal/hermit/io.rs b/library/std/src/sys/pal/hermit/io.rs index 9de7b53e53c03..aad1eef71e9b0 100644 --- a/library/std/src/sys/pal/hermit/io.rs +++ b/library/std/src/sys/pal/hermit/io.rs @@ -1,9 +1,9 @@ +use hermit_abi::{c_void, iovec}; + use crate::marker::PhantomData; use crate::os::hermit::io::{AsFd, AsRawFd}; use crate::slice; -use hermit_abi::{c_void, iovec}; - #[derive(Copy, Clone)] #[repr(transparent)] pub struct IoSlice<'a> { diff --git a/library/std/src/sys/pal/hermit/mod.rs b/library/std/src/sys/pal/hermit/mod.rs index 55583b89d6714..ef406b9ec7f0d 100644 --- a/library/std/src/sys/pal/hermit/mod.rs +++ b/library/std/src/sys/pal/hermit/mod.rs @@ -13,7 +13,8 @@ //! compiling for wasm. That way it's a compile time error for something that's //! guaranteed to be a runtime error! -#![allow(missing_docs, nonstandard_style, unsafe_op_in_unsafe_fn)] +#![deny(unsafe_op_in_unsafe_fn)] +#![allow(missing_docs, nonstandard_style)] use crate::os::raw::c_char; @@ -49,9 +50,7 @@ pub fn unsupported_err() -> crate::io::Error { } pub fn abort_internal() -> ! { - unsafe { - hermit_abi::abort(); - } + unsafe { hermit_abi::abort() } } pub fn hashmap_random_keys() -> (u64, u64) { @@ -80,7 +79,9 @@ pub extern "C" fn __rust_abort() { // SAFETY: must be called only once during runtime initialization. // NOTE: this is not guaranteed to run, for example when Rust code is called externally. pub unsafe fn init(argc: isize, argv: *const *const u8, _sigpipe: u8) { - args::init(argc, argv); + unsafe { + args::init(argc, argv); + } } // SAFETY: must be called only once during runtime cleanup. @@ -101,10 +102,12 @@ pub unsafe extern "C" fn runtime_entry( // initialize environment os::init_environment(env as *const *const i8); - let result = main(argc as isize, argv); + let result = unsafe { main(argc as isize, argv) }; - crate::sys::thread_local::destructors::run(); - hermit_abi::exit(result); + unsafe { + crate::sys::thread_local::destructors::run(); + } + unsafe { hermit_abi::exit(result) } } #[inline] diff --git a/library/std/src/sys/pal/hermit/net.rs b/library/std/src/sys/pal/hermit/net.rs index 6016d50eba085..416469c003738 100644 --- a/library/std/src/sys/pal/hermit/net.rs +++ b/library/std/src/sys/pal/hermit/net.rs @@ -1,17 +1,16 @@ #![allow(dead_code)] +use core::ffi::c_int; + use super::fd::FileDesc; -use crate::cmp; use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut}; -use crate::mem; use crate::net::{Shutdown, SocketAddr}; use crate::os::hermit::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, RawFd}; use crate::sys::time::Instant; use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr}; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; - -use core::ffi::c_int; +use crate::{cmp, mem}; #[allow(unused_extern_crates)] pub extern crate hermit_abi as netc; diff --git a/library/std/src/sys/pal/hermit/os.rs b/library/std/src/sys/pal/hermit/os.rs index a7a73c756f216..f8ea80afa43f1 100644 --- a/library/std/src/sys/pal/hermit/os.rs +++ b/library/std/src/sys/pal/hermit/os.rs @@ -1,17 +1,15 @@ +use core::slice::memchr; + use super::hermit_abi; use crate::collections::HashMap; use crate::error::Error as StdError; use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::os::hermit::ffi::OsStringExt; use crate::path::{self, PathBuf}; -use crate::str; use crate::sync::Mutex; use crate::sys::unsupported; -use crate::vec; -use core::slice::memchr; +use crate::{fmt, io, str, vec}; pub fn errno() -> i32 { unsafe { hermit_abi::get_errno() } @@ -70,21 +68,21 @@ pub fn current_exe() -> io::Result { unsupported() } -static mut ENV: Option>> = None; +static ENV: Mutex>> = Mutex::new(None); pub fn init_environment(env: *const *const i8) { - unsafe { - ENV = Some(Mutex::new(HashMap::new())); + let mut guard = ENV.lock().unwrap(); + let map = guard.insert(HashMap::new()); - if env.is_null() { - return; - } + if env.is_null() { + return; + } - let mut guard = ENV.as_ref().unwrap().lock().unwrap(); + unsafe { let mut environ = env; while !(*environ).is_null() { if let Some((key, value)) = parse(CStr::from_ptr(*environ).to_bytes()) { - guard.insert(key, value); + map.insert(key, value); } environ = environ.add(1); } @@ -156,30 +154,26 @@ impl Iterator for Env { /// Returns a vector of (variable, value) byte-vector pairs for all the /// environment variables of the current process. pub fn env() -> Env { - unsafe { - let guard = ENV.as_ref().unwrap().lock().unwrap(); - let mut result = Vec::new(); + let guard = ENV.lock().unwrap(); + let env = guard.as_ref().unwrap(); - for (key, value) in guard.iter() { - result.push((key.clone(), value.clone())); - } + let result = env.iter().map(|(key, value)| (key.clone(), value.clone())).collect::>(); - return Env { iter: result.into_iter() }; - } + Env { iter: result.into_iter() } } pub fn getenv(k: &OsStr) -> Option { - unsafe { ENV.as_ref().unwrap().lock().unwrap().get_mut(k).cloned() } + ENV.lock().unwrap().as_ref().unwrap().get(k).cloned() } pub unsafe fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let (k, v) = (k.to_owned(), v.to_owned()); - ENV.as_ref().unwrap().lock().unwrap().insert(k, v); + ENV.lock().unwrap().as_mut().unwrap().insert(k, v); Ok(()) } pub unsafe fn unsetenv(k: &OsStr) -> io::Result<()> { - ENV.as_ref().unwrap().lock().unwrap().remove(k); + ENV.lock().unwrap().as_mut().unwrap().remove(k); Ok(()) } @@ -192,9 +186,7 @@ pub fn home_dir() -> Option { } pub fn exit(code: i32) -> ! { - unsafe { - hermit_abi::exit(code); - } + unsafe { hermit_abi::exit(code) } } pub fn getpid() -> u32 { diff --git a/library/std/src/sys/pal/hermit/thread.rs b/library/std/src/sys/pal/hermit/thread.rs index a244b953d2a49..6321f92e3d9d0 100644 --- a/library/std/src/sys/pal/hermit/thread.rs +++ b/library/std/src/sys/pal/hermit/thread.rs @@ -2,11 +2,10 @@ use super::hermit_abi; use crate::ffi::CStr; -use crate::io; -use crate::mem; +use crate::mem::ManuallyDrop; use crate::num::NonZero; -use crate::ptr; use crate::time::Duration; +use crate::{io, ptr}; pub type Tid = hermit_abi::Tid; @@ -26,18 +25,22 @@ impl Thread { core_id: isize, ) -> io::Result { let p = Box::into_raw(Box::new(p)); - let tid = hermit_abi::spawn2( - thread_start, - p.expose_provenance(), - hermit_abi::Priority::into(hermit_abi::NORMAL_PRIO), - stack, - core_id, - ); + let tid = unsafe { + hermit_abi::spawn2( + thread_start, + p.expose_provenance(), + hermit_abi::Priority::into(hermit_abi::NORMAL_PRIO), + stack, + core_id, + ) + }; return if tid == 0 { // The thread failed to start and as a result p was not consumed. Therefore, it is // safe to reconstruct the box so that it gets deallocated. - drop(Box::from_raw(p)); + unsafe { + drop(Box::from_raw(p)); + } Err(io::const_io_error!(io::ErrorKind::Uncategorized, "Unable to create thread!")) } else { Ok(Thread { tid: tid }) @@ -55,7 +58,9 @@ impl Thread { } pub unsafe fn new(stack: usize, p: Box) -> io::Result { - Thread::new_with_coreid(stack, p, -1 /* = no specific core */) + unsafe { + Thread::new_with_coreid(stack, p, -1 /* = no specific core */) + } } #[inline] @@ -90,9 +95,7 @@ impl Thread { #[inline] pub fn into_id(self) -> Tid { - let id = self.tid; - mem::forget(self); - id + ManuallyDrop::new(self).tid } } diff --git a/library/std/src/sys/pal/hermit/time.rs b/library/std/src/sys/pal/hermit/time.rs index e0cb7c2aa98a5..2c87c4860a27a 100644 --- a/library/std/src/sys/pal/hermit/time.rs +++ b/library/std/src/sys/pal/hermit/time.rs @@ -1,10 +1,11 @@ #![allow(dead_code)] +use core::hash::{Hash, Hasher}; + use super::hermit_abi::{self, timespec, CLOCK_MONOTONIC, CLOCK_REALTIME}; use crate::cmp::Ordering; use crate::ops::{Add, AddAssign, Sub, SubAssign}; use crate::time::Duration; -use core::hash::{Hash, Hasher}; const NSEC_PER_SEC: i32 = 1_000_000_000; diff --git a/library/std/src/sys/pal/itron/error.rs b/library/std/src/sys/pal/itron/error.rs index fbc822d4eb6e1..8ff3017c61471 100644 --- a/library/std/src/sys/pal/itron/error.rs +++ b/library/std/src/sys/pal/itron/error.rs @@ -1,6 +1,6 @@ -use crate::{fmt, io::ErrorKind}; - use super::abi; +use crate::fmt; +use crate::io::ErrorKind; /// Wraps a μITRON error code. #[derive(Debug, Copy, Clone)] @@ -9,7 +9,7 @@ pub struct ItronError { } impl ItronError { - /// Construct `ItronError` from the specified error code. Returns `None` if the + /// Constructs `ItronError` from the specified error code. Returns `None` if the /// error code does not represent a failure or warning. #[inline] pub fn new(er: abi::ER) -> Option { @@ -22,7 +22,7 @@ impl ItronError { if let Some(error) = Self::new(er) { Err(error) } else { Ok(er) } } - /// Get the raw error code. + /// Gets the raw error code. #[inline] pub fn as_raw(&self) -> abi::ER { self.er diff --git a/library/std/src/sys/pal/itron/spin.rs b/library/std/src/sys/pal/itron/spin.rs index 44d409444bca4..6a9a7c72deb7d 100644 --- a/library/std/src/sys/pal/itron/spin.rs +++ b/library/std/src/sys/pal/itron/spin.rs @@ -1,9 +1,7 @@ use super::abi; -use crate::{ - cell::UnsafeCell, - mem::MaybeUninit, - sync::atomic::{AtomicBool, AtomicUsize, Ordering}, -}; +use crate::cell::UnsafeCell; +use crate::mem::MaybeUninit; +use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; /// A mutex implemented by `dis_dsp` (for intra-core synchronization) and a /// spinlock (for inter-core synchronization). diff --git a/library/std/src/sys/pal/itron/task.rs b/library/std/src/sys/pal/itron/task.rs index 94beb50a2541b..5da0c5917885f 100644 --- a/library/std/src/sys/pal/itron/task.rs +++ b/library/std/src/sys/pal/itron/task.rs @@ -1,23 +1,20 @@ -use super::{ - abi, - error::{fail, fail_aborting, ItronError}, -}; - +use super::abi; +use super::error::{fail, fail_aborting, ItronError}; use crate::mem::MaybeUninit; -/// Get the ID of the task in Running state. Panics on failure. +/// Gets the ID of the task in Running state. Panics on failure. #[inline] pub fn current_task_id() -> abi::ID { try_current_task_id().unwrap_or_else(|e| fail(e, &"get_tid")) } -/// Get the ID of the task in Running state. Aborts on failure. +/// Gets the ID of the task in Running state. Aborts on failure. #[inline] pub fn current_task_id_aborting() -> abi::ID { try_current_task_id().unwrap_or_else(|e| fail_aborting(e, &"get_tid")) } -/// Get the ID of the task in Running state. +/// Gets the ID of the task in Running state. #[inline] pub fn try_current_task_id() -> Result { unsafe { @@ -27,13 +24,13 @@ pub fn try_current_task_id() -> Result { } } -/// Get the specified task's priority. Panics on failure. +/// Gets the specified task's priority. Panics on failure. #[inline] pub fn task_priority(task: abi::ID) -> abi::PRI { try_task_priority(task).unwrap_or_else(|e| fail(e, &"get_pri")) } -/// Get the specified task's priority. +/// Gets the specified task's priority. #[inline] pub fn try_task_priority(task: abi::ID) -> Result { unsafe { diff --git a/library/std/src/sys/pal/itron/thread.rs b/library/std/src/sys/pal/itron/thread.rs index fd7b5558f7566..01e69afa99e13 100644 --- a/library/std/src/sys/pal/itron/thread.rs +++ b/library/std/src/sys/pal/itron/thread.rs @@ -1,22 +1,17 @@ //! Thread implementation backed by μITRON tasks. Assumes `acre_tsk` and //! `exd_tsk` are available. -use super::{ - abi, - error::{expect_success, expect_success_aborting, ItronError}, - task, - time::dur2reltims, -}; -use crate::{ - cell::UnsafeCell, - ffi::CStr, - hint, io, - mem::ManuallyDrop, - num::NonZero, - ptr::NonNull, - sync::atomic::{AtomicUsize, Ordering}, - time::Duration, -}; +use super::error::{expect_success, expect_success_aborting, ItronError}; +use super::time::dur2reltims; +use super::{abi, task}; +use crate::cell::UnsafeCell; +use crate::ffi::CStr; +use crate::mem::ManuallyDrop; +use crate::num::NonZero; +use crate::ptr::NonNull; +use crate::sync::atomic::{AtomicUsize, Ordering}; +use crate::time::Duration; +use crate::{hint, io}; pub struct Thread { p_inner: NonNull, @@ -308,7 +303,7 @@ impl Drop for Thread { } } -/// Terminate and delete the specified task. +/// Terminates and deletes the specified task. /// /// This function will abort if `deleted_task` refers to the calling task. /// @@ -337,7 +332,7 @@ unsafe fn terminate_and_delete_task(deleted_task: abi::ID) { expect_success_aborting(unsafe { abi::del_tsk(deleted_task) }, &"del_tsk"); } -/// Terminate and delete the calling task. +/// Terminates and deletes the calling task. /// /// Atomicity is not required - i.e., it can be assumed that other threads won't /// `ter_tsk` the calling task while this function is still in progress. (This diff --git a/library/std/src/sys/pal/itron/time.rs b/library/std/src/sys/pal/itron/time.rs index 427ea0d80e107..7976c27f4952b 100644 --- a/library/std/src/sys/pal/itron/time.rs +++ b/library/std/src/sys/pal/itron/time.rs @@ -1,5 +1,7 @@ -use super::{abi, error::expect_success}; -use crate::{mem::MaybeUninit, time::Duration}; +use super::abi; +use super::error::expect_success; +use crate::mem::MaybeUninit; +use crate::time::Duration; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub struct Instant(abi::SYSTIM); diff --git a/library/std/src/sys/pal/mod.rs b/library/std/src/sys/pal/mod.rs index df0176244489a..9be018c8a5312 100644 --- a/library/std/src/sys/pal/mod.rs +++ b/library/std/src/sys/pal/mod.rs @@ -76,23 +76,5 @@ cfg_if::cfg_if! { } } -#[cfg(not(test))] -cfg_if::cfg_if! { - if #[cfg(target_os = "android")] { - pub use self::android::log2f32; - pub use self::android::log2f64; - } else { - #[inline] - pub fn log2f32(n: f32) -> f32 { - unsafe { crate::intrinsics::log2f32(n) } - } - - #[inline] - pub fn log2f64(n: f64) -> f64 { - unsafe { crate::intrinsics::log2f64(n) } - } - } -} - #[cfg(not(target_os = "uefi"))] pub type RawOsError = i32; diff --git a/library/std/src/sys/pal/sgx/abi/mod.rs b/library/std/src/sys/pal/sgx/abi/mod.rs index 9508c38741551..d8836452e7555 100644 --- a/library/std/src/sys/pal/sgx/abi/mod.rs +++ b/library/std/src/sys/pal/sgx/abi/mod.rs @@ -1,9 +1,10 @@ #![cfg_attr(test, allow(unused))] // RT initialization logic is not compiled for test -use crate::io::Write; use core::arch::global_asm; use core::sync::atomic::{AtomicUsize, Ordering}; +use crate::io::Write; + // runtime features pub(super) mod panic; mod reloc; diff --git a/library/std/src/sys/pal/sgx/abi/panic.rs b/library/std/src/sys/pal/sgx/abi/panic.rs index 229b3b3291f63..c06b97ee3674a 100644 --- a/library/std/src/sys/pal/sgx/abi/panic.rs +++ b/library/std/src/sys/pal/sgx/abi/panic.rs @@ -1,7 +1,6 @@ use super::usercalls::alloc::UserRef; -use crate::cmp; use crate::io::{self, Write}; -use crate::mem; +use crate::{cmp, mem}; extern "C" { fn take_debug_panic_buf_ptr() -> *mut u8; diff --git a/library/std/src/sys/pal/sgx/abi/tls/mod.rs b/library/std/src/sys/pal/sgx/abi/tls/mod.rs index 8a9ea4ac00df0..34fc2f20d2214 100644 --- a/library/std/src/sys/pal/sgx/abi/tls/mod.rs +++ b/library/std/src/sys/pal/sgx/abi/tls/mod.rs @@ -2,10 +2,9 @@ mod sync_bitset; use self::sync_bitset::*; use crate::cell::Cell; -use crate::mem; use crate::num::NonZero; -use crate::ptr; use crate::sync::atomic::{AtomicUsize, Ordering}; +use crate::{mem, ptr}; #[cfg(target_pointer_width = "64")] const USIZE_BITS: usize = 64; @@ -95,8 +94,8 @@ impl Tls { #[allow(unused)] pub unsafe fn activate_persistent(self: Box) { // FIXME: Needs safety information. See entry.S for `set_tls_ptr` definition. - unsafe { set_tls_ptr(core::ptr::addr_of!(*self) as _) }; - mem::forget(self); + let ptr = Box::into_raw(self).cast_const().cast::(); + unsafe { set_tls_ptr(ptr) }; } unsafe fn current<'a>() -> &'a Tls { diff --git a/library/std/src/sys/pal/sgx/abi/usercalls/alloc.rs b/library/std/src/sys/pal/sgx/abi/usercalls/alloc.rs index f99cea360f1f4..298095257396a 100644 --- a/library/std/src/sys/pal/sgx/abi/usercalls/alloc.rs +++ b/library/std/src/sys/pal/sgx/abi/usercalls/alloc.rs @@ -1,18 +1,16 @@ #![allow(unused)] +use fortanix_sgx_abi::*; + +use super::super::mem::{is_enclave_range, is_user_range}; use crate::arch::asm; use crate::cell::UnsafeCell; -use crate::cmp; use crate::convert::TryInto; -use crate::intrinsics; -use crate::mem; +use crate::mem::{self, ManuallyDrop}; use crate::ops::{CoerceUnsized, Deref, DerefMut, Index, IndexMut}; use crate::ptr::{self, NonNull}; -use crate::slice; use crate::slice::SliceIndex; - -use super::super::mem::{is_enclave_range, is_user_range}; -use fortanix_sgx_abi::*; +use crate::{cmp, intrinsics, slice}; /// A type that can be safely read from or written to userspace. /// @@ -67,7 +65,7 @@ pub unsafe trait UserSafe { /// Equivalent to `mem::align_of::`. fn align_of() -> usize; - /// Construct a pointer to `Self` given a memory range in user space. + /// Constructs a pointer to `Self` given a memory range in user space. /// /// N.B., this takes a size, not a length! /// @@ -77,7 +75,7 @@ pub unsafe trait UserSafe { /// correct size and is correctly aligned and points to the right type. unsafe fn from_raw_sized_unchecked(ptr: *mut u8, size: usize) -> *mut Self; - /// Construct a pointer to `Self` given a memory range. + /// Constructs a pointer to `Self` given a memory range. /// /// N.B., this takes a size, not a length! /// @@ -176,6 +174,7 @@ unsafe impl UserSafe for [T] { /// are used solely to indicate intent: a mutable reference is for writing to /// user memory, an immutable reference for reading from user memory. #[unstable(feature = "sgx_platform", issue = "56975")] +#[repr(transparent)] pub struct UserRef(UnsafeCell); /// An owned type in userspace memory. `User` is equivalent to `Box` in /// enclave memory. Access to the memory is only allowed by copying to avoid @@ -266,9 +265,7 @@ where /// Converts this value into a raw pointer. The value will no longer be /// automatically freed. pub fn into_raw(self) -> *mut T { - let ret = self.0; - mem::forget(self); - ret.as_ptr() as _ + ManuallyDrop::new(self).0.as_ptr() as _ } } @@ -277,7 +274,7 @@ impl User where T: UserSafe, { - /// Allocate space for `T` in user memory. + /// Allocates space for `T` in user memory. pub fn uninitialized() -> Self { Self::new_uninit_bytes(mem::size_of::()) } @@ -288,7 +285,7 @@ impl User<[T]> where [T]: UserSafe, { - /// Allocate space for a `[T]` of `n` elements in user memory. + /// Allocates space for a `[T]` of `n` elements in user memory. pub fn uninitialized(n: usize) -> Self { Self::new_uninit_bytes(n * mem::size_of::()) } diff --git a/library/std/src/sys/pal/sgx/abi/usercalls/mod.rs b/library/std/src/sys/pal/sgx/abi/usercalls/mod.rs index e19e843267a90..def1ccdf81ac0 100644 --- a/library/std/src/sys/pal/sgx/abi/usercalls/mod.rs +++ b/library/std/src/sys/pal/sgx/abi/usercalls/mod.rs @@ -171,10 +171,12 @@ pub fn wait(event_mask: u64, mut timeout: u64) -> IoResult { unsafe { raw::wait(event_mask, timeout).from_sgx_result() } } -/// This function makes an effort to wait for a non-spurious event at least as -/// long as `duration`. Note that in general there is no guarantee about accuracy -/// of time and timeouts in SGX model. The enclave runner serving usercalls may -/// lie about current time and/or ignore timeout values. +/// Makes an effort to wait for a non-spurious event at least as long as +/// `duration`. +/// +/// Note that in general there is no guarantee about accuracy of time and +/// timeouts in SGX model. The enclave runner serving usercalls may lie about +/// current time and/or ignore timeout values. /// /// Once the event is observed, `should_wake_up` will be used to determine /// whether or not the event was spurious. diff --git a/library/std/src/sys/pal/sgx/abi/usercalls/tests.rs b/library/std/src/sys/pal/sgx/abi/usercalls/tests.rs index 58b8eb215d73c..ef824d35f4a16 100644 --- a/library/std/src/sys/pal/sgx/abi/usercalls/tests.rs +++ b/library/std/src/sys/pal/sgx/abi/usercalls/tests.rs @@ -1,5 +1,4 @@ -use super::alloc::User; -use super::alloc::{copy_from_userspace, copy_to_userspace}; +use super::alloc::{copy_from_userspace, copy_to_userspace, User}; #[test] fn test_copy_to_userspace_function() { diff --git a/library/std/src/sys/pal/sgx/alloc.rs b/library/std/src/sys/pal/sgx/alloc.rs index 0c7bf9a9201f2..f68ede9fcf012 100644 --- a/library/std/src/sys/pal/sgx/alloc.rs +++ b/library/std/src/sys/pal/sgx/alloc.rs @@ -1,9 +1,9 @@ -use crate::alloc::{GlobalAlloc, Layout, System}; -use crate::ptr; use core::sync::atomic::{AtomicBool, Ordering}; use super::abi::mem as sgx_mem; use super::waitqueue::SpinMutex; +use crate::alloc::{GlobalAlloc, Layout, System}; +use crate::ptr; // Using a SpinMutex because we never want to exit the enclave waiting for the // allocator. diff --git a/library/std/src/sys/pal/sgx/args.rs b/library/std/src/sys/pal/sgx/args.rs index ef4176c4ac0f0..a72a041da6cc9 100644 --- a/library/std/src/sys/pal/sgx/args.rs +++ b/library/std/src/sys/pal/sgx/args.rs @@ -1,10 +1,10 @@ -use super::abi::usercalls::{alloc, raw::ByteBuffer}; +use super::abi::usercalls::alloc; +use super::abi::usercalls::raw::ByteBuffer; use crate::ffi::OsString; -use crate::fmt; -use crate::slice; use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sys::os_str::Buf; use crate::sys_common::FromInner; +use crate::{fmt, slice}; #[cfg_attr(test, linkage = "available_externally")] #[export_name = "_ZN16__rust_internals3std3sys3sgx4args4ARGSE"] diff --git a/library/std/src/sys/pal/sgx/fd.rs b/library/std/src/sys/pal/sgx/fd.rs index b3686d0e28328..c41b527cff798 100644 --- a/library/std/src/sys/pal/sgx/fd.rs +++ b/library/std/src/sys/pal/sgx/fd.rs @@ -2,7 +2,7 @@ use fortanix_sgx_abi::Fd; use super::abi::usercalls; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; -use crate::mem; +use crate::mem::ManuallyDrop; use crate::sys::{AsInner, FromInner, IntoInner}; #[derive(Debug)] @@ -21,9 +21,7 @@ impl FileDesc { /// Extracts the actual file descriptor without closing it. pub fn into_raw(self) -> Fd { - let fd = self.fd; - mem::forget(self); - fd + ManuallyDrop::new(self).fd } pub fn read(&self, buf: &mut [u8]) -> io::Result { @@ -70,9 +68,7 @@ impl AsInner for FileDesc { impl IntoInner for FileDesc { fn into_inner(self) -> Fd { - let fd = self.fd; - mem::forget(self); - fd + ManuallyDrop::new(self).fd } } diff --git a/library/std/src/sys/pal/sgx/net.rs b/library/std/src/sys/pal/sgx/net.rs index 68a2d5eded2da..f2e751c51194d 100644 --- a/library/std/src/sys/pal/sgx/net.rs +++ b/library/std/src/sys/pal/sgx/net.rs @@ -1,13 +1,11 @@ -use crate::error; -use crate::fmt; +use super::abi::usercalls; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, ToSocketAddrs}; use crate::sync::Arc; use crate::sys::fd::FileDesc; use crate::sys::{sgx_ineffective, unsupported, AsInner, FromInner, IntoInner, TryIntoInner}; use crate::time::Duration; - -use super::abi::usercalls; +use crate::{error, fmt}; const DEFAULT_FAKE_TTL: u32 = 64; diff --git a/library/std/src/sys/pal/sgx/os.rs b/library/std/src/sys/pal/sgx/os.rs index c021300d4ae33..46af710aa396c 100644 --- a/library/std/src/sys/pal/sgx/os.rs +++ b/library/std/src/sys/pal/sgx/os.rs @@ -3,16 +3,12 @@ use fortanix_sgx_abi::{Error, RESULT_SUCCESS}; use crate::collections::HashMap; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::path::{self, PathBuf}; -use crate::str; use crate::sync::atomic::{AtomicUsize, Ordering}; -use crate::sync::Mutex; -use crate::sync::Once; +use crate::sync::{Mutex, Once}; use crate::sys::{decode_error_kind, sgx_ineffective, unsupported}; -use crate::vec; +use crate::{fmt, io, str, vec}; pub fn errno() -> i32 { RESULT_SUCCESS diff --git a/library/std/src/sys/pal/sgx/thread.rs b/library/std/src/sys/pal/sgx/thread.rs index 446cdd18b7e42..cecd53c352c5a 100644 --- a/library/std/src/sys/pal/sgx/thread.rs +++ b/library/std/src/sys/pal/sgx/thread.rs @@ -1,12 +1,12 @@ #![cfg_attr(test, allow(dead_code))] // why is this necessary? + +use super::abi::usercalls; use super::unsupported; use crate::ffi::CStr; use crate::io; use crate::num::NonZero; use crate::time::Duration; -use super::abi::usercalls; - pub struct Thread(task_queue::JoinHandle); pub const DEFAULT_MIN_STACK_SIZE: usize = 4096; diff --git a/library/std/src/sys/pal/sgx/thread_parking.rs b/library/std/src/sys/pal/sgx/thread_parking.rs index 0006cd4f1be25..660624ea9c3b8 100644 --- a/library/std/src/sys/pal/sgx/thread_parking.rs +++ b/library/std/src/sys/pal/sgx/thread_parking.rs @@ -1,7 +1,8 @@ +use fortanix_sgx_abi::{EV_UNPARK, WAIT_INDEFINITE}; + use super::abi::usercalls; use crate::io::ErrorKind; use crate::time::Duration; -use fortanix_sgx_abi::{EV_UNPARK, WAIT_INDEFINITE}; pub type ThreadId = fortanix_sgx_abi::Tcs; diff --git a/library/std/src/sys/pal/sgx/waitqueue/mod.rs b/library/std/src/sys/pal/sgx/waitqueue/mod.rs index f5668a9493fb5..bd114523fe80b 100644 --- a/library/std/src/sys/pal/sgx/waitqueue/mod.rs +++ b/library/std/src/sys/pal/sgx/waitqueue/mod.rs @@ -16,17 +16,15 @@ mod tests; mod spin_mutex; mod unsafe_list; -use crate::num::NonZero; -use crate::ops::{Deref, DerefMut}; -use crate::panic::{self, AssertUnwindSafe}; -use crate::time::Duration; - -use super::abi::thread; -use super::abi::usercalls; use fortanix_sgx_abi::{Tcs, EV_UNPARK, WAIT_INDEFINITE}; pub use self::spin_mutex::{try_lock_or_false, SpinMutex, SpinMutexGuard}; use self::unsafe_list::{UnsafeList, UnsafeListEntry}; +use super::abi::{thread, usercalls}; +use crate::num::NonZero; +use crate::ops::{Deref, DerefMut}; +use crate::panic::{self, AssertUnwindSafe}; +use crate::time::Duration; /// An queue entry in a `WaitQueue`. struct WaitEntry { diff --git a/library/std/src/sys/pal/solid/abi/fs.rs b/library/std/src/sys/pal/solid/abi/fs.rs index 75efaaac2a948..394be15b0064b 100644 --- a/library/std/src/sys/pal/solid/abi/fs.rs +++ b/library/std/src/sys/pal/solid/abi/fs.rs @@ -1,11 +1,12 @@ //! `solid_fs.h` -use crate::os::raw::{c_char, c_int, c_uchar}; pub use libc::{ ino_t, off_t, stat, time_t, O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, SEEK_CUR, SEEK_END, SEEK_SET, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFMT, S_IFREG, S_IWRITE, }; +use crate::os::raw::{c_char, c_int, c_uchar}; + pub const O_ACCMODE: c_int = 0x3; pub const SOLID_MAX_PATH: usize = 256; diff --git a/library/std/src/sys/pal/solid/abi/mod.rs b/library/std/src/sys/pal/solid/abi/mod.rs index 8440d572cfbd3..62cd86236bbd3 100644 --- a/library/std/src/sys/pal/solid/abi/mod.rs +++ b/library/std/src/sys/pal/solid/abi/mod.rs @@ -3,7 +3,6 @@ use crate::os::raw::c_int; mod fs; pub mod sockets; pub use self::fs::*; - // `solid_types.h` pub use super::itron::abi::{ER, ER_ID, E_TMOUT, ID}; diff --git a/library/std/src/sys/pal/solid/abi/sockets.rs b/library/std/src/sys/pal/solid/abi/sockets.rs index 11c430360ce88..3c9e3f9ffb95d 100644 --- a/library/std/src/sys/pal/solid/abi/sockets.rs +++ b/library/std/src/sys/pal/solid/abi/sockets.rs @@ -1,6 +1,7 @@ -use crate::os::raw::{c_char, c_uint, c_void}; pub use libc::{c_int, c_long, size_t, ssize_t, timeval}; +use crate::os::raw::{c_char, c_uint, c_void}; + pub const SOLID_NET_ERR_BASE: c_int = -2000; pub const EINPROGRESS: c_int = SOLID_NET_ERR_BASE - libc::EINPROGRESS; diff --git a/library/std/src/sys/pal/solid/alloc.rs b/library/std/src/sys/pal/solid/alloc.rs index d013bd8761003..4cf60ac9b2e23 100644 --- a/library/std/src/sys/pal/solid/alloc.rs +++ b/library/std/src/sys/pal/solid/alloc.rs @@ -1,7 +1,5 @@ -use crate::{ - alloc::{GlobalAlloc, Layout, System}, - sys::common::alloc::{realloc_fallback, MIN_ALIGN}, -}; +use crate::alloc::{GlobalAlloc, Layout, System}; +use crate::sys::common::alloc::{realloc_fallback, MIN_ALIGN}; #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { diff --git a/library/std/src/sys/pal/solid/error.rs b/library/std/src/sys/pal/solid/error.rs index 547b4f3a9840e..66c4d8a0ea27a 100644 --- a/library/std/src/sys/pal/solid/error.rs +++ b/library/std/src/sys/pal/solid/error.rs @@ -1,8 +1,7 @@ +pub use self::itron::error::{expect_success, ItronError as SolidError}; use super::{abi, itron, net}; use crate::io::ErrorKind; -pub use self::itron::error::{expect_success, ItronError as SolidError}; - /// Describe the specified SOLID error code. Returns `None` if it's an /// undefined error code. /// diff --git a/library/std/src/sys/pal/solid/fs.rs b/library/std/src/sys/pal/solid/fs.rs index dc83e4f4b4999..8179ec8821a38 100644 --- a/library/std/src/sys/pal/solid/fs.rs +++ b/library/std/src/sys/pal/solid/fs.rs @@ -1,17 +1,14 @@ use super::{abi, error}; -use crate::{ - ffi::{CStr, CString, OsStr, OsString}, - fmt, - io::{self, BorrowedCursor, IoSlice, IoSliceMut, SeekFrom}, - mem::MaybeUninit, - os::raw::{c_int, c_short}, - os::solid::ffi::OsStrExt, - path::{Path, PathBuf}, - sync::Arc, - sys::time::SystemTime, - sys::unsupported, -}; - +use crate::ffi::{CStr, CString, OsStr, OsString}; +use crate::fmt; +use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, SeekFrom}; +use crate::mem::MaybeUninit; +use crate::os::raw::{c_int, c_short}; +use crate::os::solid::ffi::OsStrExt; +use crate::path::{Path, PathBuf}; +use crate::sync::Arc; +use crate::sys::time::SystemTime; +use crate::sys::unsupported; pub use crate::sys_common::fs::exists; /// A file descriptor. diff --git a/library/std/src/sys/pal/solid/io.rs b/library/std/src/sys/pal/solid/io.rs index a862bb7870264..4b1f788a492c5 100644 --- a/library/std/src/sys/pal/solid/io.rs +++ b/library/std/src/sys/pal/solid/io.rs @@ -1,8 +1,8 @@ -use crate::marker::PhantomData; -use crate::slice; +use libc::c_void; use super::abi::sockets::iovec; -use libc::c_void; +use crate::marker::PhantomData; +use crate::slice; #[derive(Copy, Clone)] #[repr(transparent)] diff --git a/library/std/src/sys/pal/solid/mod.rs b/library/std/src/sys/pal/solid/mod.rs index 0b158fb63df70..cbf34286878fe 100644 --- a/library/std/src/sys/pal/solid/mod.rs +++ b/library/std/src/sys/pal/solid/mod.rs @@ -32,8 +32,7 @@ pub mod pipe; #[path = "../unsupported/process.rs"] pub mod process; pub mod stdio; -pub use self::itron::thread; -pub use self::itron::thread_parking; +pub use self::itron::{thread, thread_parking}; pub mod time; // SAFETY: must be called only once during runtime initialization. diff --git a/library/std/src/sys/pal/solid/net.rs b/library/std/src/sys/pal/solid/net.rs index 5bd339849e9dc..b6a31395095d9 100644 --- a/library/std/src/sys/pal/solid/net.rs +++ b/library/std/src/sys/pal/solid/net.rs @@ -1,19 +1,15 @@ -use super::abi; -use crate::{ - cmp, - ffi::CStr, - io::{self, BorrowedBuf, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}, - mem, - net::{Shutdown, SocketAddr}, - os::solid::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}, - ptr, str, - sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr}, - sys_common::{FromInner, IntoInner}, - time::Duration, -}; +use libc::{c_int, c_void, size_t}; use self::netc::{sockaddr, socklen_t, MSG_PEEK}; -use libc::{c_int, c_void, size_t}; +use super::abi; +use crate::ffi::CStr; +use crate::io::{self, BorrowedBuf, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}; +use crate::net::{Shutdown, SocketAddr}; +use crate::os::solid::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}; +use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr}; +use crate::sys_common::{FromInner, IntoInner}; +use crate::time::Duration; +use crate::{cmp, mem, ptr, str}; pub mod netc { pub use super::super::abi::sockets::*; diff --git a/library/std/src/sys/pal/solid/os.rs b/library/std/src/sys/pal/solid/os.rs index ac90aae4ebe46..d8afcb91f67f2 100644 --- a/library/std/src/sys/pal/solid/os.rs +++ b/library/std/src/sys/pal/solid/os.rs @@ -1,20 +1,14 @@ -use super::unsupported; +use core::slice::memchr; + +use super::{error, itron, unsupported}; use crate::error::Error as StdError; use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; -use crate::io; -use crate::os::{ - raw::{c_char, c_int}, - solid::ffi::{OsStrExt, OsStringExt}, -}; +use crate::os::raw::{c_char, c_int}; +use crate::os::solid::ffi::{OsStrExt, OsStringExt}; use crate::path::{self, PathBuf}; use crate::sync::{PoisonError, RwLock}; use crate::sys::common::small_c_string::run_with_cstr; -use crate::vec; - -use super::{error, itron}; - -use core::slice::memchr; +use crate::{fmt, io, vec}; // `solid` directly maps `errno`s to μITRON error codes. impl itron::error::ItronError { diff --git a/library/std/src/sys/pal/solid/time.rs b/library/std/src/sys/pal/solid/time.rs index f83f1644fe854..3f9bbb0b63cdb 100644 --- a/library/std/src/sys/pal/solid/time.rs +++ b/library/std/src/sys/pal/solid/time.rs @@ -1,7 +1,8 @@ -use super::{abi, error::expect_success}; -use crate::{mem::MaybeUninit, time::Duration}; - +use super::abi; +use super::error::expect_success; pub use super::itron::time::Instant; +use crate::mem::MaybeUninit; +use crate::time::Duration; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub struct SystemTime(abi::time_t); diff --git a/library/std/src/sys/pal/teeos/os.rs b/library/std/src/sys/pal/teeos/os.rs index 3be0846a6dd4d..82cade771b513 100644 --- a/library/std/src/sys/pal/teeos/os.rs +++ b/library/std/src/sys/pal/teeos/os.rs @@ -2,14 +2,11 @@ use core::marker::PhantomData; +use super::unsupported; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; -use crate::path; use crate::path::PathBuf; - -use super::unsupported; +use crate::{fmt, io, path}; pub fn errno() -> i32 { unsafe { (*libc::__errno_location()) as i32 } diff --git a/library/std/src/sys/pal/teeos/stdio.rs b/library/std/src/sys/pal/teeos/stdio.rs index 9ca04f2927323..67e251812da7f 100644 --- a/library/std/src/sys/pal/teeos/stdio.rs +++ b/library/std/src/sys/pal/teeos/stdio.rs @@ -1,8 +1,9 @@ #![deny(unsafe_op_in_unsafe_fn)] -use crate::io; use core::arch::asm; +use crate::io; + pub struct Stdin; pub struct Stdout; pub struct Stderr; diff --git a/library/std/src/sys/pal/teeos/thread.rs b/library/std/src/sys/pal/teeos/thread.rs index 7a27d749f1c9c..15c65240ddd2a 100644 --- a/library/std/src/sys/pal/teeos/thread.rs +++ b/library/std/src/sys/pal/teeos/thread.rs @@ -1,13 +1,9 @@ -use core::convert::TryInto; - -use crate::cmp; use crate::ffi::CStr; -use crate::io; -use crate::mem; +use crate::mem::{self, ManuallyDrop}; use crate::num::NonZero; -use crate::ptr; use crate::sys::os; use crate::time::Duration; +use crate::{cmp, io, ptr}; pub const DEFAULT_MIN_STACK_SIZE: usize = 8 * 1024; @@ -115,11 +111,9 @@ impl Thread { /// must join, because no pthread_detach supported pub fn join(self) { - unsafe { - let ret = libc::pthread_join(self.id, ptr::null_mut()); - mem::forget(self); - assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret)); - } + let id = self.into_id(); + let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) }; + assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret)); } pub fn id(&self) -> libc::pthread_t { @@ -127,9 +121,7 @@ impl Thread { } pub fn into_id(self) -> libc::pthread_t { - let id = self.id; - mem::forget(self); - id + ManuallyDrop::new(self).id } } diff --git a/library/std/src/sys/pal/uefi/args.rs b/library/std/src/sys/pal/uefi/args.rs index 18a69afa7d91b..bdf6f5a0c1c34 100644 --- a/library/std/src/sys/pal/uefi/args.rs +++ b/library/std/src/sys/pal/uefi/args.rs @@ -3,10 +3,9 @@ use r_efi::protocols::loaded_image; use super::helpers; use crate::env::current_exe; use crate::ffi::OsString; -use crate::fmt; use crate::iter::Iterator; use crate::mem::size_of; -use crate::vec; +use crate::{fmt, vec}; pub struct Args { parsed_args_list: vec::IntoIter, @@ -76,7 +75,7 @@ impl DoubleEndedIterator for Args { /// This implementation is based on what is defined in Section 3.4 of /// [UEFI Shell Specification](https://uefi.org/sites/default/files/resources/UEFI_Shell_Spec_2_0.pdf) /// -/// Return None in the following cases: +/// Returns None in the following cases: /// - Invalid UTF-16 (unpaired surrogate) /// - Empty/improper arguments fn parse_lp_cmd_line(code_units: &[u16]) -> Option> { diff --git a/library/std/src/sys/pal/uefi/helpers.rs b/library/std/src/sys/pal/uefi/helpers.rs index 29984a915b894..4031d33ba8066 100644 --- a/library/std/src/sys/pal/uefi/helpers.rs +++ b/library/std/src/sys/pal/uefi/helpers.rs @@ -15,7 +15,9 @@ use r_efi::protocols::{device_path, device_path_to_text}; use crate::ffi::{OsStr, OsString}; use crate::io::{self, const_io_error}; use crate::mem::{size_of, MaybeUninit}; -use crate::os::uefi::{self, env::boot_services, ffi::OsStrExt, ffi::OsStringExt}; +use crate::os::uefi::env::boot_services; +use crate::os::uefi::ffi::{OsStrExt, OsStringExt}; +use crate::os::uefi::{self}; use crate::ptr::NonNull; use crate::slice; use crate::sync::atomic::{AtomicPtr, Ordering}; @@ -30,8 +32,9 @@ type BootUninstallMultipleProtocolInterfaces = const BOOT_SERVICES_UNAVAILABLE: io::Error = const_io_error!(io::ErrorKind::Other, "Boot Services are no longer available"); -/// Locate Handles with a particular Protocol GUID -/// Implemented using `EFI_BOOT_SERVICES.LocateHandles()` +/// Locates Handles with a particular Protocol GUID. +/// +/// Implemented using `EFI_BOOT_SERVICES.LocateHandles()`. /// /// Returns an array of [Handles](r_efi::efi::Handle) that support a specified protocol. pub(crate) fn locate_handles(mut guid: Guid) -> io::Result>> { @@ -148,8 +151,9 @@ pub(crate) unsafe fn close_event(evt: NonNull) -> io::Result if r.is_error() { Err(crate::io::Error::from_raw_os_error(r.as_usize())) } else { Ok(()) } } -/// Get the Protocol for current system handle. -/// Note: Some protocols need to be manually freed. It is the callers responsibility to do so. +/// Gets the Protocol for current system handle. +/// +/// Note: Some protocols need to be manually freed. It is the caller's responsibility to do so. pub(crate) fn image_handle_protocol(protocol_guid: Guid) -> io::Result> { let system_handle = uefi::env::try_image_handle().ok_or(io::const_io_error!( io::ErrorKind::NotFound, @@ -220,7 +224,7 @@ pub(crate) fn device_path_to_text(path: NonNull) -> io::R Err(io::const_io_error!(io::ErrorKind::NotFound, "No device path to text protocol found")) } -/// Get RuntimeServices +/// Gets RuntimeServices. pub(crate) fn runtime_services() -> Option> { let system_table: NonNull = crate::os::uefi::env::try_system_table()?.cast(); diff --git a/library/std/src/sys/pal/uefi/mod.rs b/library/std/src/sys/pal/uefi/mod.rs index c54e9477bfc1f..851bcea4c1e43 100644 --- a/library/std/src/sys/pal/uefi/mod.rs +++ b/library/std/src/sys/pal/uefi/mod.rs @@ -101,9 +101,10 @@ pub const fn unsupported_err() -> std_io::Error { } pub fn decode_error_kind(code: RawOsError) -> crate::io::ErrorKind { - use crate::io::ErrorKind; use r_efi::efi::Status; + use crate::io::ErrorKind; + match r_efi::efi::Status::from_usize(code) { Status::ALREADY_STARTED | Status::COMPROMISED_DATA diff --git a/library/std/src/sys/pal/uefi/os.rs b/library/std/src/sys/pal/uefi/os.rs index 0b27977df2fde..4d2d7264704b2 100644 --- a/library/std/src/sys/pal/uefi/os.rs +++ b/library/std/src/sys/pal/uefi/os.rs @@ -1,14 +1,14 @@ +use r_efi::efi::protocols::{device_path, loaded_image_device_path}; +use r_efi::efi::Status; + use super::{helpers, unsupported, RawOsError}; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::os::uefi; use crate::path::{self, PathBuf}; use crate::ptr::NonNull; -use r_efi::efi::protocols::{device_path, loaded_image_device_path}; -use r_efi::efi::Status; +use crate::{fmt, io}; pub fn errno() -> RawOsError { 0 diff --git a/library/std/src/sys/pal/uefi/process.rs b/library/std/src/sys/pal/uefi/process.rs index 5c7c8415ee295..fdc5f5d7e4fea 100644 --- a/library/std/src/sys/pal/uefi/process.rs +++ b/library/std/src/sys/pal/uefi/process.rs @@ -1,20 +1,15 @@ use r_efi::protocols::simple_text_output; -use crate::ffi::OsStr; -use crate::ffi::OsString; -use crate::fmt; -use crate::io; -use crate::num::NonZero; -use crate::num::NonZeroI32; +use super::helpers; +pub use crate::ffi::OsString as EnvKey; +use crate::ffi::{OsStr, OsString}; +use crate::num::{NonZero, NonZeroI32}; use crate::path::Path; use crate::sys::fs::File; use crate::sys::pipe::AnonPipe; use crate::sys::unsupported; use crate::sys_common::process::{CommandEnv, CommandEnvs}; - -pub use crate::ffi::OsString as EnvKey; - -use super::helpers; +use crate::{fmt, io}; //////////////////////////////////////////////////////////////////////////////// // Command diff --git a/library/std/src/sys/pal/uefi/time.rs b/library/std/src/sys/pal/uefi/time.rs index 76562cf9f51c0..495ff2dc930ed 100644 --- a/library/std/src/sys/pal/uefi/time.rs +++ b/library/std/src/sys/pal/uefi/time.rs @@ -59,11 +59,12 @@ impl SystemTime { } pub(crate) mod system_time_internal { + use r_efi::efi::{RuntimeServices, Time}; + use super::super::helpers; use super::*; use crate::mem::MaybeUninit; use crate::ptr::NonNull; - use r_efi::efi::{RuntimeServices, Time}; pub fn now() -> Option { let runtime_services: NonNull = helpers::runtime_services()?; @@ -114,13 +115,14 @@ pub(crate) mod system_time_internal { } pub(crate) mod instant_internal { + use r_efi::protocols::timestamp; + use super::super::helpers; use super::*; use crate::mem::MaybeUninit; use crate::ptr::NonNull; use crate::sync::atomic::{AtomicPtr, Ordering}; use crate::sys_common::mul_div_u64; - use r_efi::protocols::timestamp; const NS_PER_SEC: u64 = 1_000_000_000; @@ -173,10 +175,6 @@ pub(crate) mod instant_internal { #[cfg(target_arch = "x86_64")] fn timestamp_rdtsc() -> Option { - if !crate::arch::x86_64::has_cpuid() { - return None; - } - static FREQUENCY: crate::sync::OnceLock = crate::sync::OnceLock::new(); // Get Frequency in Mhz @@ -198,10 +196,6 @@ pub(crate) mod instant_internal { #[cfg(target_arch = "x86")] fn timestamp_rdtsc() -> Option { - if !crate::arch::x86::has_cpuid() { - return None; - } - static FREQUENCY: crate::sync::OnceLock = crate::sync::OnceLock::new(); let freq = FREQUENCY diff --git a/library/std/src/sys/pal/unix/android.rs b/library/std/src/sys/pal/unix/android.rs deleted file mode 100644 index 0f704994f550a..0000000000000 --- a/library/std/src/sys/pal/unix/android.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! Android ABI-compatibility module -//! -//! The ABI of Android has changed quite a bit over time, and std attempts to be -//! both forwards and backwards compatible as much as possible. We want to -//! always work with the most recent version of Android, but we also want to -//! work with older versions of Android for whenever projects need to. -//! -//! Our current minimum supported Android version is `android-9`, e.g., Android -//! with API level 9. We then in theory want to work on that and all future -//! versions of Android! -//! -//! Some of the detection here is done at runtime via `dlopen` and -//! introspection. Other times no detection is performed at all and we just -//! provide a fallback implementation as some versions of Android we support -//! don't have the function. -//! -//! You'll find more details below about why each compatibility shim is needed. - -#![cfg(target_os = "android")] - -use libc::{c_int, sighandler_t}; - -use super::weak::weak; - -// The `log2` and `log2f` functions apparently appeared in android-18, or at -// least you can see they're not present in the android-17 header [1] and they -// are present in android-18 [2]. -// -// [1]: https://chromium.googlesource.com/android_tools/+/20ee6d20/ndk/platforms -// /android-17/arch-arm/usr/include/math.h -// [2]: https://chromium.googlesource.com/android_tools/+/20ee6d20/ndk/platforms -// /android-18/arch-arm/usr/include/math.h -// -// Note that these shims are likely less precise than directly calling `log2`, -// but hopefully that should be enough for now... -// -// Note that mathematically, for any arbitrary `y`: -// -// log_2(x) = log_y(x) / log_y(2) -// = log_y(x) / (1 / log_2(y)) -// = log_y(x) * log_2(y) -// -// Hence because `ln` (log_e) is available on all Android we just choose `y = e` -// and get: -// -// log_2(x) = ln(x) * log_2(e) - -#[cfg(not(test))] -pub fn log2f32(f: f32) -> f32 { - f.ln() * crate::f32::consts::LOG2_E -} - -#[cfg(not(test))] -pub fn log2f64(f: f64) -> f64 { - f.ln() * crate::f64::consts::LOG2_E -} - -// Back in the day [1] the `signal` function was just an inline wrapper -// around `bsd_signal`, but starting in API level android-20 the `signal` -// symbols was introduced [2]. Finally, in android-21 the API `bsd_signal` was -// removed [3]. -// -// Basically this means that if we want to be binary compatible with multiple -// Android releases (oldest being 9 and newest being 21) then we need to check -// for both symbols and not actually link against either. -// -// [1]: https://chromium.googlesource.com/android_tools/+/20ee6d20/ndk/platforms -// /android-18/arch-arm/usr/include/signal.h -// [2]: https://chromium.googlesource.com/android_tools/+/fbd420/ndk_experimental -// /platforms/android-20/arch-arm -// /usr/include/signal.h -// [3]: https://chromium.googlesource.com/android_tools/+/20ee6d/ndk/platforms -// /android-21/arch-arm/usr/include/signal.h -pub unsafe fn signal(signum: c_int, handler: sighandler_t) -> sighandler_t { - weak!(fn signal(c_int, sighandler_t) -> sighandler_t); - weak!(fn bsd_signal(c_int, sighandler_t) -> sighandler_t); - - let f = signal.get().or_else(|| bsd_signal.get()); - let f = f.expect("neither `signal` nor `bsd_signal` symbols found"); - f(signum, handler) -} diff --git a/library/std/src/sys/pal/unix/args.rs b/library/std/src/sys/pal/unix/args.rs index e2ec838b740cb..9a37e1a0346d7 100644 --- a/library/std/src/sys/pal/unix/args.rs +++ b/library/std/src/sys/pal/unix/args.rs @@ -6,9 +6,8 @@ #![allow(dead_code)] // runtime init functions not used during testing use crate::ffi::{CStr, OsString}; -use crate::fmt; use crate::os::unix::ffi::OsStringExt; -use crate::vec; +use crate::{fmt, vec}; /// One-time global initialization. pub unsafe fn init(argc: isize, argv: *const *const u8) { diff --git a/library/std/src/sys/pal/unix/fd.rs b/library/std/src/sys/pal/unix/fd.rs index 10ae3c3ab570d..d8e239ee23ed5 100644 --- a/library/std/src/sys/pal/unix/fd.rs +++ b/library/std/src/sys/pal/unix/fd.rs @@ -3,12 +3,6 @@ #[cfg(test)] mod tests; -use crate::cmp; -use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read}; -use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; -use crate::sys::cvt; -use crate::sys_common::{AsInner, FromInner, IntoInner}; - #[cfg(any( target_os = "android", target_os = "linux", @@ -26,6 +20,12 @@ use libc::off64_t; )))] use libc::off_t as off64_t; +use crate::cmp; +use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read}; +use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; +use crate::sys::cvt; +use crate::sys_common::{AsInner, FromInner, IntoInner}; + #[derive(Debug)] pub struct FileDesc(OwnedFd); @@ -125,6 +125,7 @@ impl FileDesc { (&mut me).read_to_end(buf) } + #[cfg_attr(target_os = "vxworks", allow(unused_unsafe))] pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result { #[cfg(not(any( all(target_os = "linux", not(target_env = "musl")), @@ -318,6 +319,7 @@ impl FileDesc { cfg!(not(any(target_os = "espidf", target_os = "horizon", target_os = "vita"))) } + #[cfg_attr(target_os = "vxworks", allow(unused_unsafe))] pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result { #[cfg(not(any( all(target_os = "linux", not(target_env = "musl")), diff --git a/library/std/src/sys/pal/unix/fd/tests.rs b/library/std/src/sys/pal/unix/fd/tests.rs index 5d17e46786c79..c5301ce655787 100644 --- a/library/std/src/sys/pal/unix/fd/tests.rs +++ b/library/std/src/sys/pal/unix/fd/tests.rs @@ -1,6 +1,7 @@ +use core::mem::ManuallyDrop; + use super::{FileDesc, IoSlice}; use crate::os::unix::io::FromRawFd; -use core::mem::ManuallyDrop; #[test] fn limit_vector_count() { diff --git a/library/std/src/sys/pal/unix/fs.rs b/library/std/src/sys/pal/unix/fs.rs index b323da8d859d5..bdb83f0785784 100644 --- a/library/std/src/sys/pal/unix/fs.rs +++ b/library/std/src/sys/pal/unix/fs.rs @@ -4,29 +4,6 @@ #[cfg(test)] mod tests; -use crate::os::unix::prelude::*; - -use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt::{self, Write as _}; -use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom}; -use crate::mem; -use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd}; -use crate::path::{Path, PathBuf}; -use crate::ptr; -use crate::sync::Arc; -use crate::sys::common::small_c_string::run_path_with_cstr; -use crate::sys::fd::FileDesc; -use crate::sys::time::SystemTime; -use crate::sys::{cvt, cvt_r}; -use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; - -#[cfg(all(target_os = "linux", target_env = "gnu"))] -use crate::sys::weak::syscall; -#[cfg(target_os = "android")] -use crate::sys::weak::weak; - -use libc::{c_int, mode_t}; - #[cfg(all(target_os = "linux", target_env = "gnu"))] use libc::c_char; #[cfg(any( @@ -73,6 +50,7 @@ use libc::readdir64_r; target_os = "hurd", )))] use libc::readdir_r as readdir64_r; +use libc::{c_int, mode_t}; #[cfg(target_os = "android")] use libc::{ dirent as dirent64, fstat as fstat64, fstatat as fstatat64, ftruncate64, lseek64, @@ -97,7 +75,24 @@ use libc::{ ))] use libc::{dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, stat64}; +use crate::ffi::{CStr, OsStr, OsString}; +use crate::fmt::{self, Write as _}; +use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom}; +use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd}; +use crate::os::unix::prelude::*; +use crate::path::{Path, PathBuf}; +use crate::sync::Arc; +use crate::sys::common::small_c_string::run_path_with_cstr; +use crate::sys::fd::FileDesc; +use crate::sys::time::SystemTime; +#[cfg(all(target_os = "linux", target_env = "gnu"))] +use crate::sys::weak::syscall; +#[cfg(target_os = "android")] +use crate::sys::weak::weak; +use crate::sys::{cvt, cvt_r}; pub use crate::sys_common::fs::exists; +use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner}; +use crate::{mem, ptr}; pub struct File(FileDesc); @@ -857,6 +852,7 @@ impl Drop for Dir { target_os = "espidf", target_os = "fuchsia", target_os = "horizon", + target_os = "vxworks", )))] { let fd = unsafe { libc::dirfd(self.0) }; @@ -1313,7 +1309,12 @@ impl File { } pub fn set_times(&self, times: FileTimes) -> io::Result<()> { - #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon")))] + #[cfg(not(any( + target_os = "redox", + target_os = "espidf", + target_os = "horizon", + target_os = "vxworks" + )))] let to_timespec = |time: Option| match time { Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts), Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_io_error!( @@ -1327,10 +1328,11 @@ impl File { None => Ok(libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT as _ }), }; cfg_if::cfg_if! { - if #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon"))] { + if #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon", target_os = "vxworks"))] { // Redox doesn't appear to support `UTIME_OMIT`. // ESP-IDF and HorizonOS do not support `futimens` at all and the behavior for those OS is therefore // the same as for Redox. + // `futimens` and `UTIME_OMIT` are a work in progress for vxworks. let _ = times; Err(io::const_io_error!( io::ErrorKind::Unsupported, @@ -1962,6 +1964,7 @@ pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> { Ok(()) } +#[cfg(not(target_os = "vxworks"))] pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> { run_path_with_cstr(path, &|path| { cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) }) @@ -1969,11 +1972,23 @@ pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> { }) } +#[cfg(target_os = "vxworks")] +pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> { + let (_, _, _) = (path, uid, gid); + Err(io::const_io_error!(io::ErrorKind::Unsupported, "lchown not supported by vxworks")) +} + #[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))] pub fn chroot(dir: &Path) -> io::Result<()> { run_path_with_cstr(dir, &|dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ())) } +#[cfg(target_os = "vxworks")] +pub fn chroot(dir: &Path) -> io::Result<()> { + let _ = dir; + Err(io::const_io_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks")) +} + pub use remove_dir_impl::remove_dir_all; // Fallback for REDOX, ESP-ID, Horizon, Vita, Vxworks and Miri @@ -2001,6 +2016,11 @@ mod remove_dir_impl { miri )))] mod remove_dir_impl { + #[cfg(not(all(target_os = "linux", target_env = "gnu")))] + use libc::{fdopendir, openat, unlinkat}; + #[cfg(all(target_os = "linux", target_env = "gnu"))] + use libc::{fdopendir, openat64 as openat, unlinkat}; + use super::{lstat, Dir, DirEntry, InnerReadDir, ReadDir}; use crate::ffi::CStr; use crate::io; @@ -2010,11 +2030,6 @@ mod remove_dir_impl { use crate::sys::common::small_c_string::run_path_with_cstr; use crate::sys::{cvt, cvt_r}; - #[cfg(not(all(target_os = "linux", target_env = "gnu")))] - use libc::{fdopendir, openat, unlinkat}; - #[cfg(all(target_os = "linux", target_env = "gnu"))] - use libc::{fdopendir, openat64 as openat, unlinkat}; - pub fn openat_nofollow_dironly(parent_fd: Option, p: &CStr) -> io::Result { let fd = cvt_r(|| unsafe { openat( diff --git a/library/std/src/sys/pal/unix/futex.rs b/library/std/src/sys/pal/unix/futex.rs index b8900da4cddb5..cc725045c4810 100644 --- a/library/std/src/sys/pal/unix/futex.rs +++ b/library/std/src/sys/pal/unix/futex.rs @@ -16,7 +16,7 @@ pub type SmallAtomic = AtomicU32; /// Must be the underlying type of SmallAtomic pub type SmallPrimitive = u32; -/// Wait for a futex_wake operation to wake us. +/// Waits for a `futex_wake` operation to wake us. /// /// Returns directly if the futex doesn't hold the expected value. /// @@ -87,7 +87,7 @@ pub fn futex_wait(futex: &AtomicU32, expected: u32, timeout: Option) - } } -/// Wake up one thread that's blocked on futex_wait on this futex. +/// Wakes up one thread that's blocked on `futex_wait` on this futex. /// /// Returns true if this actually woke up such a thread, /// or false if no thread was waiting on this futex. @@ -100,7 +100,7 @@ pub fn futex_wake(futex: &AtomicU32) -> bool { unsafe { libc::syscall(libc::SYS_futex, ptr, op, 1) > 0 } } -/// Wake up all threads that are waiting on futex_wait on this futex. +/// Wakes up all threads that are waiting on `futex_wait` on this futex. #[cfg(any(target_os = "linux", target_os = "android"))] pub fn futex_wake_all(futex: &AtomicU32) { let ptr = futex as *const AtomicU32; diff --git a/library/std/src/sys/pal/unix/io.rs b/library/std/src/sys/pal/unix/io.rs index 29c340dd34942..181c35a971eca 100644 --- a/library/std/src/sys/pal/unix/io.rs +++ b/library/std/src/sys/pal/unix/io.rs @@ -1,9 +1,9 @@ +use libc::{c_void, iovec}; + use crate::marker::PhantomData; use crate::os::fd::{AsFd, AsRawFd}; use crate::slice; -use libc::{c_void, iovec}; - #[derive(Copy, Clone)] #[repr(transparent)] pub struct IoSlice<'a> { diff --git a/library/std/src/sys/pal/unix/kernel_copy.rs b/library/std/src/sys/pal/unix/kernel_copy.rs index cd38b7c07e2b1..a671383cb7957 100644 --- a/library/std/src/sys/pal/unix/kernel_copy.rs +++ b/library/std/src/sys/pal/unix/kernel_copy.rs @@ -42,6 +42,12 @@ //! progress, they can hit a performance cliff. //! * complexity +#[cfg(not(any(all(target_os = "linux", target_env = "gnu"), target_os = "hurd")))] +use libc::sendfile as sendfile64; +#[cfg(any(all(target_os = "linux", target_env = "gnu"), target_os = "hurd"))] +use libc::sendfile64; +use libc::{EBADF, EINVAL, ENOSYS, EOPNOTSUPP, EOVERFLOW, EPERM, EXDEV}; + use crate::cmp::min; use crate::fs::{File, Metadata}; use crate::io::copy::generic_copy; @@ -54,16 +60,12 @@ use crate::net::TcpStream; use crate::os::unix::fs::FileTypeExt; use crate::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use crate::os::unix::net::UnixStream; +use crate::pipe::{PipeReader, PipeWriter}; use crate::process::{ChildStderr, ChildStdin, ChildStdout}; use crate::ptr; use crate::sync::atomic::{AtomicBool, AtomicU8, Ordering}; use crate::sys::cvt; use crate::sys::weak::syscall; -#[cfg(not(any(all(target_os = "linux", target_env = "gnu"), target_os = "hurd")))] -use libc::sendfile as sendfile64; -#[cfg(any(all(target_os = "linux", target_env = "gnu"), target_os = "hurd"))] -use libc::sendfile64; -use libc::{EBADF, EINVAL, ENOSYS, EOPNOTSUPP, EOVERFLOW, EPERM, EXDEV}; #[cfg(test)] mod tests; @@ -404,6 +406,30 @@ impl CopyWrite for &UnixStream { } } +impl CopyRead for PipeReader { + fn properties(&self) -> CopyParams { + CopyParams(FdMeta::Pipe, Some(self.as_raw_fd())) + } +} + +impl CopyRead for &PipeReader { + fn properties(&self) -> CopyParams { + CopyParams(FdMeta::Pipe, Some(self.as_raw_fd())) + } +} + +impl CopyWrite for PipeWriter { + fn properties(&self) -> CopyParams { + CopyParams(FdMeta::Pipe, Some(self.as_raw_fd())) + } +} + +impl CopyWrite for &PipeWriter { + fn properties(&self) -> CopyParams { + CopyParams(FdMeta::Pipe, Some(self.as_raw_fd())) + } +} + impl CopyWrite for ChildStdin { fn properties(&self) -> CopyParams { CopyParams(FdMeta::Pipe, Some(self.as_raw_fd())) diff --git a/library/std/src/sys/pal/unix/kernel_copy/tests.rs b/library/std/src/sys/pal/unix/kernel_copy/tests.rs index a524270e3fb85..1350d743ff6f3 100644 --- a/library/std/src/sys/pal/unix/kernel_copy/tests.rs +++ b/library/std/src/sys/pal/unix/kernel_copy/tests.rs @@ -1,8 +1,6 @@ use crate::fs::OpenOptions; use crate::io; -use crate::io::Result; -use crate::io::SeekFrom; -use crate::io::{BufRead, Read, Seek, Write}; +use crate::io::{BufRead, Read, Result, Seek, SeekFrom, Write}; use crate::os::unix::io::AsRawFd; use crate::sys_common::io::test::tmpdir; diff --git a/library/std/src/sys/pal/unix/mod.rs b/library/std/src/sys/pal/unix/mod.rs index 262f9c704a882..b62129f4cdd26 100644 --- a/library/std/src/sys/pal/unix/mod.rs +++ b/library/std/src/sys/pal/unix/mod.rs @@ -1,15 +1,13 @@ #![allow(missing_docs, nonstandard_style)] -use crate::io::ErrorKind; - pub use self::rand::hashmap_random_keys; +use crate::io::ErrorKind; #[cfg(not(target_os = "espidf"))] #[macro_use] pub mod weak; pub mod alloc; -pub mod android; pub mod args; pub mod env; pub mod fd; @@ -86,11 +84,12 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { target_vendor = "apple", )))] 'poll: { - use crate::sys::os::errno; #[cfg(not(all(target_os = "linux", target_env = "gnu")))] use libc::open as open64; #[cfg(all(target_os = "linux", target_env = "gnu"))] use libc::open64; + + use crate::sys::os::errno; let pfds: &mut [_] = &mut [ libc::pollfd { fd: 0, events: 0, revents: 0 }, libc::pollfd { fd: 1, events: 0, revents: 0 }, @@ -140,11 +139,12 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { target_os = "vita", )))] { - use crate::sys::os::errno; #[cfg(not(all(target_os = "linux", target_env = "gnu")))] use libc::open as open64; #[cfg(all(target_os = "linux", target_env = "gnu"))] use libc::open64; + + use crate::sys::os::errno; for fd in 0..3 { if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF { if open64(c"/dev/null".as_ptr().cast(), libc::O_RDWR, 0) == -1 { @@ -164,6 +164,8 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { target_os = "emscripten", target_os = "fuchsia", target_os = "horizon", + target_os = "vxworks", + target_os = "vita", // Unikraft's `signal` implementation is currently broken: // https://github.com/unikraft/lib-musl/issues/57 target_vendor = "unikraft", @@ -209,6 +211,8 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { target_os = "emscripten", target_os = "fuchsia", target_os = "horizon", + target_os = "vxworks", + target_os = "vita", )))] static ON_BROKEN_PIPE_FLAG_USED: crate::sync::atomic::AtomicBool = crate::sync::atomic::AtomicBool::new(false); @@ -218,6 +222,8 @@ static ON_BROKEN_PIPE_FLAG_USED: crate::sync::atomic::AtomicBool = target_os = "emscripten", target_os = "fuchsia", target_os = "horizon", + target_os = "vxworks", + target_os = "vita", )))] pub(crate) fn on_broken_pipe_flag_used() -> bool { ON_BROKEN_PIPE_FLAG_USED.load(crate::sync::atomic::Ordering::Relaxed) @@ -229,10 +235,7 @@ pub unsafe fn cleanup() { stack_overflow::cleanup(); } -#[cfg(target_os = "android")] -pub use crate::sys::android::signal; #[allow(unused_imports)] -#[cfg(not(target_os = "android"))] pub use libc::signal; #[inline] @@ -305,7 +308,7 @@ macro_rules! impl_is_minus_one { impl_is_minus_one! { i8 i16 i32 i64 isize } -/// Convert native return values to Result using the *-1 means error is in `errno`* convention. +/// Converts native return values to Result using the *-1 means error is in `errno`* convention. /// Non-error values are `Ok`-wrapped. pub fn cvt(t: T) -> crate::io::Result { if t.is_minus_one() { Err(crate::io::Error::last_os_error()) } else { Ok(t) } diff --git a/library/std/src/sys/pal/unix/net.rs b/library/std/src/sys/pal/unix/net.rs index bedb06043a7b4..bc0e3f4eeeac8 100644 --- a/library/std/src/sys/pal/unix/net.rs +++ b/library/std/src/sys/pal/unix/net.rs @@ -1,7 +1,7 @@ -use crate::cmp; +use libc::{c_int, c_void, size_t, sockaddr, socklen_t, MSG_PEEK}; + use crate::ffi::CStr; use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut}; -use crate::mem; use crate::net::{Shutdown, SocketAddr}; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::sys::fd::FileDesc; @@ -9,8 +9,7 @@ use crate::sys::pal::unix::IsMinusOne; use crate::sys_common::net::{getsockopt, setsockopt, sockaddr_to_addr}; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::{Duration, Instant}; - -use libc::{c_int, c_void, size_t, sockaddr, socklen_t, MSG_PEEK}; +use crate::{cmp, mem}; cfg_if::cfg_if! { if #[cfg(target_vendor = "apple")] { @@ -214,16 +213,25 @@ impl Socket { } 0 => {} _ => { - // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look - // for POLLHUP rather than read readiness - if pollfd.revents & libc::POLLHUP != 0 { - let e = self.take_error()?.unwrap_or_else(|| { - io::const_io_error!( - io::ErrorKind::Uncategorized, - "no error set after POLLHUP", - ) - }); - return Err(e); + if cfg!(target_os = "vxworks") { + // VxWorks poll does not return POLLHUP or POLLERR in revents. Check if the + // connnection actually succeeded and return ok only when the socket is + // ready and no errors were found. + if let Some(e) = self.take_error()? { + return Err(e); + } + } else { + // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look + // for POLLHUP or POLLERR rather than read readiness + if pollfd.revents & (libc::POLLHUP | libc::POLLERR) != 0 { + let e = self.take_error()?.unwrap_or_else(|| { + io::const_io_error!( + io::ErrorKind::Uncategorized, + "no error set after POLLHUP", + ) + }); + return Err(e); + } } return Ok(()); diff --git a/library/std/src/sys/pal/unix/os.rs b/library/std/src/sys/pal/unix/os.rs index 9adc2b94e599e..a785b97ac8dc5 100644 --- a/library/std/src/sys/pal/unix/os.rs +++ b/library/std/src/sys/pal/unix/os.rs @@ -5,29 +5,20 @@ #[cfg(test)] mod tests; -use crate::os::unix::prelude::*; +use core::slice::memchr; + +use libc::{c_char, c_int, c_void}; use crate::error::Error as StdError; use crate::ffi::{CStr, CString, OsStr, OsString}; -use crate::fmt; -use crate::io; -use crate::iter; -use crate::mem; +use crate::os::unix::prelude::*; use crate::path::{self, PathBuf}; -use crate::ptr; -use crate::slice; -use crate::str; use crate::sync::{PoisonError, RwLock}; use crate::sys::common::small_c_string::{run_path_with_cstr, run_with_cstr}; -use crate::sys::cvt; -use crate::sys::fd; -use crate::vec; -use core::slice::memchr; - #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))] use crate::sys::weak::weak; - -use libc::{c_char, c_int, c_void}; +use crate::sys::{cvt, fd}; +use crate::{fmt, io, iter, mem, ptr, slice, str, vec}; const TMPBUF_SZ: usize = 128; @@ -248,13 +239,12 @@ impl StdError for JoinPathsError { #[cfg(target_os = "aix")] pub fn current_exe() -> io::Result { - use crate::io::ErrorKind; - #[cfg(test)] use realstd::env; #[cfg(not(test))] use crate::env; + use crate::io::ErrorKind; let exe_path = env::args().next().ok_or(io::const_io_error!( ErrorKind::NotFound, @@ -513,13 +503,12 @@ pub fn current_exe() -> io::Result { #[cfg(target_os = "fuchsia")] pub fn current_exe() -> io::Result { - use crate::io::ErrorKind; - #[cfg(test)] use realstd::env; #[cfg(not(test))] use crate::env; + use crate::io::ErrorKind; let exe_path = env::args().next().ok_or(io::const_io_error!( ErrorKind::Uncategorized, diff --git a/library/std/src/sys/pal/unix/pipe.rs b/library/std/src/sys/pal/unix/pipe.rs index 8762af614f17e..f0ebc767badad 100644 --- a/library/std/src/sys/pal/unix/pipe.rs +++ b/library/std/src/sys/pal/unix/pipe.rs @@ -47,6 +47,8 @@ pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { } impl AnonPipe { + #[allow(dead_code)] + // FIXME: This function seems legitimately unused. pub fn try_clone(&self) -> io::Result { self.0.duplicate().map(Self) } @@ -85,6 +87,8 @@ impl AnonPipe { self.0.is_write_vectored() } + #[allow(dead_code)] + // FIXME: This function seems legitimately unused. pub fn as_file_desc(&self) -> &FileDesc { &self.0 } diff --git a/library/std/src/sys/pal/unix/process/process_common.rs b/library/std/src/sys/pal/unix/process/process_common.rs index f615e8086dccf..fec825054195a 100644 --- a/library/std/src/sys/pal/unix/process/process_common.rs +++ b/library/std/src/sys/pal/unix/process/process_common.rs @@ -1,24 +1,20 @@ #[cfg(all(test, not(target_os = "emscripten")))] mod tests; -use crate::os::unix::prelude::*; +use libc::{c_char, c_int, gid_t, pid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS}; use crate::collections::BTreeMap; use crate::ffi::{CStr, CString, OsStr, OsString}; -use crate::fmt; -use crate::io; +use crate::os::unix::prelude::*; use crate::path::Path; -use crate::ptr; use crate::sys::fd::FileDesc; use crate::sys::fs::File; +#[cfg(not(target_os = "fuchsia"))] +use crate::sys::fs::OpenOptions; use crate::sys::pipe::{self, AnonPipe}; use crate::sys_common::process::{CommandEnv, CommandEnvs}; use crate::sys_common::{FromInner, IntoInner}; - -#[cfg(not(target_os = "fuchsia"))] -use crate::sys::fs::OpenOptions; - -use libc::{c_char, c_int, gid_t, pid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS}; +use crate::{fmt, io, ptr}; cfg_if::cfg_if! { if #[cfg(target_os = "fuchsia")] { @@ -128,6 +124,7 @@ pub struct StdioPipes { // passed to do_exec() with configuration of what the child stdio should look // like +#[cfg_attr(target_os = "vita", allow(dead_code))] pub struct ChildPipes { pub stdin: ChildStdio, pub stdout: ChildStdio, diff --git a/library/std/src/sys/pal/unix/process/process_common/tests.rs b/library/std/src/sys/pal/unix/process/process_common/tests.rs index 823b4a5633629..e5c8dd6e341e1 100644 --- a/library/std/src/sys/pal/unix/process/process_common/tests.rs +++ b/library/std/src/sys/pal/unix/process/process_common/tests.rs @@ -1,9 +1,7 @@ use super::*; - use crate::ffi::OsStr; -use crate::mem; -use crate::ptr; use crate::sys::{cvt, cvt_nz}; +use crate::{mem, ptr}; macro_rules! t { ($e:expr) => { diff --git a/library/std/src/sys/pal/unix/process/process_fuchsia.rs b/library/std/src/sys/pal/unix/process/process_fuchsia.rs index 23c2be6adf9ee..f3d5fdec4c291 100644 --- a/library/std/src/sys/pal/unix/process/process_fuchsia.rs +++ b/library/std/src/sys/pal/unix/process/process_fuchsia.rs @@ -1,13 +1,9 @@ -use crate::fmt; -use crate::io; -use crate::mem; -use crate::num::NonZero; -use crate::ptr; +use libc::{c_int, size_t}; +use crate::num::NonZero; use crate::sys::process::process_common::*; use crate::sys::process::zircon::{zx_handle_t, Handle}; - -use libc::{c_int, size_t}; +use crate::{fmt, io, mem, ptr}; //////////////////////////////////////////////////////////////////////////////// // Command diff --git a/library/std/src/sys/pal/unix/process/process_unix.rs b/library/std/src/sys/pal/unix/process/process_unix.rs index abd4a334783e4..5552e9ac97753 100644 --- a/library/std/src/sys/pal/unix/process/process_unix.rs +++ b/library/std/src/sys/pal/unix/process/process_unix.rs @@ -1,20 +1,7 @@ -use crate::fmt; -use crate::io::{self, Error, ErrorKind}; -use crate::mem; -use crate::num::NonZero; -use crate::sys; -use crate::sys::cvt; -use crate::sys::process::process_common::*; - -#[cfg(target_os = "linux")] -use crate::sys::pal::unix::linux::pidfd::PidFd; - #[cfg(target_os = "vxworks")] use libc::RTP_ID as pid_t; - #[cfg(not(target_os = "vxworks"))] use libc::{c_int, pid_t}; - #[cfg(not(any( target_os = "vxworks", target_os = "l4re", @@ -23,6 +10,14 @@ use libc::{c_int, pid_t}; )))] use libc::{gid_t, uid_t}; +use crate::io::{self, Error, ErrorKind}; +use crate::num::NonZero; +use crate::sys::cvt; +#[cfg(target_os = "linux")] +use crate::sys::pal::unix::linux::pidfd::PidFd; +use crate::sys::process::process_common::*; +use crate::{fmt, mem, sys}; + cfg_if::cfg_if! { if #[cfg(all(target_os = "nto", target_env = "nto71"))] { use crate::thread; @@ -446,11 +441,12 @@ impl Command { stdio: &ChildPipes, envp: Option<&CStringArray>, ) -> io::Result> { + #[cfg(target_os = "linux")] + use core::sync::atomic::{AtomicU8, Ordering}; + use crate::mem::MaybeUninit; use crate::sys::weak::weak; use crate::sys::{self, cvt_nz, on_broken_pipe_flag_used}; - #[cfg(target_os = "linux")] - use core::sync::atomic::{AtomicU8, Ordering}; if self.get_gid().is_some() || self.get_uid().is_some() @@ -762,10 +758,11 @@ impl Command { #[cfg(target_os = "linux")] fn send_pidfd(&self, sock: &crate::sys::net::Socket) { + use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET}; + use crate::io::IoSlice; use crate::os::fd::RawFd; use crate::sys::cvt_r; - use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET}; unsafe { let child_pid = libc::getpid(); @@ -819,11 +816,11 @@ impl Command { #[cfg(target_os = "linux")] fn recv_pidfd(&self, sock: &crate::sys::net::Socket) -> pid_t { + use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET}; + use crate::io::IoSliceMut; use crate::sys::cvt_r; - use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET}; - unsafe { const SCM_MSG_LEN: usize = mem::size_of::<[c_int; 1]>(); @@ -1047,7 +1044,7 @@ impl From for ExitStatus { } } -/// Convert a signal number to a readable, searchable name. +/// Converts a signal number to a readable, searchable name. /// /// This string should be displayed right after the signal number. /// If a signal is unrecognized, it returns the empty string, so that @@ -1189,12 +1186,11 @@ impl ExitStatusError { #[cfg(target_os = "linux")] mod linux_child_ext { - use crate::io; - use crate::mem; use crate::os::linux::process as os; use crate::sys::pal::unix::linux::pidfd as imp; use crate::sys::pal::unix::ErrorKind; use crate::sys_common::FromInner; + use crate::{io, mem}; #[unstable(feature = "linux_pidfd", issue = "82971")] impl crate::os::linux::process::ChildExt for crate::process::Child { diff --git a/library/std/src/sys/pal/unix/process/process_unsupported.rs b/library/std/src/sys/pal/unix/process/process_unsupported.rs index 90d53464c83f1..c58548835ff3d 100644 --- a/library/std/src/sys/pal/unix/process/process_unsupported.rs +++ b/library/std/src/sys/pal/unix/process/process_unsupported.rs @@ -1,10 +1,10 @@ +use libc::{c_int, pid_t}; + use crate::io; use crate::num::NonZero; use crate::sys::pal::unix::unsupported::*; use crate::sys::process::process_common::*; -use libc::{c_int, pid_t}; - //////////////////////////////////////////////////////////////////////////////// // Command //////////////////////////////////////////////////////////////////////////////// diff --git a/library/std/src/sys/pal/unix/process/process_unsupported/wait_status.rs b/library/std/src/sys/pal/unix/process/process_unsupported/wait_status.rs index 973188b1f2b27..f04036bde4922 100644 --- a/library/std/src/sys/pal/unix/process/process_unsupported/wait_status.rs +++ b/library/std/src/sys/pal/unix/process/process_unsupported/wait_status.rs @@ -2,12 +2,11 @@ //! //! Separate module to facilitate testing against a real Unix implementation. +use super::ExitStatusError; use crate::ffi::c_int; use crate::fmt; use crate::num::NonZero; -use super::ExitStatusError; - /// Emulated wait status for use by `process_unsupported.rs` /// /// Uses the "traditional unix" encoding. For use on platfors which are `#[cfg(unix)]` diff --git a/library/std/src/sys/pal/unix/process/process_vxworks.rs b/library/std/src/sys/pal/unix/process/process_vxworks.rs index 5007dbd34b4ab..6a9d8fab1d412 100644 --- a/library/std/src/sys/pal/unix/process/process_vxworks.rs +++ b/library/std/src/sys/pal/unix/process/process_vxworks.rs @@ -1,12 +1,11 @@ -use crate::fmt; +use libc::{self, c_char, c_int, RTP_ID}; + use crate::io::{self, ErrorKind}; use crate::num::NonZero; -use crate::sys; use crate::sys::cvt; +use crate::sys::pal::unix::thread; use crate::sys::process::process_common::*; -use crate::sys_common::thread; -use libc::RTP_ID; -use libc::{self, c_char, c_int}; +use crate::{fmt, sys}; //////////////////////////////////////////////////////////////////////////////// // Command @@ -68,7 +67,12 @@ impl Command { .as_ref() .map(|c| c.as_ptr()) .unwrap_or_else(|| *sys::os::environ() as *const _); - let stack_size = thread::min_stack(); + let stack_size = crate::cmp::max( + crate::env::var_os("RUST_MIN_STACK") + .and_then(|s| s.to_str().and_then(|s| s.parse().ok())) + .unwrap_or(thread::DEFAULT_MIN_STACK_SIZE), + libc::PTHREAD_STACK_MIN, + ); // ensure that access to the environment is synchronized let _lock = sys::os::env_read_lock(); diff --git a/library/std/src/sys/pal/unix/process/zircon.rs b/library/std/src/sys/pal/unix/process/zircon.rs index 2e596486f9c86..4035e2370a3c6 100644 --- a/library/std/src/sys/pal/unix/process/zircon.rs +++ b/library/std/src/sys/pal/unix/process/zircon.rs @@ -1,11 +1,11 @@ #![allow(non_camel_case_types, unused)] +use libc::{c_int, c_void, size_t}; + use crate::io; use crate::mem::MaybeUninit; use crate::os::raw::c_char; -use libc::{c_int, c_void, size_t}; - pub type zx_handle_t = u32; pub type zx_vaddr_t = usize; pub type zx_rights_t = u32; diff --git a/library/std/src/sys/pal/unix/rand.rs b/library/std/src/sys/pal/unix/rand.rs index e6df109a6b8f2..8a78ea8e7ccc7 100644 --- a/library/std/src/sys/pal/unix/rand.rs +++ b/library/std/src/sys/pal/unix/rand.rs @@ -24,7 +24,6 @@ pub fn hashmap_random_keys() -> (u64, u64) { mod imp { use crate::fs::File; use crate::io::Read; - #[cfg(any(target_os = "linux", target_os = "android"))] use crate::sys::weak::syscall; @@ -178,9 +177,10 @@ mod imp { #[cfg(target_vendor = "apple")] mod imp { - use crate::io; use libc::{c_int, c_void, size_t}; + use crate::io; + #[inline(always)] fn random_failure() -> ! { panic!("unexpected random generation error: {}", io::Error::last_os_error()); @@ -311,8 +311,10 @@ mod imp { #[cfg(target_os = "vxworks")] mod imp { + use core::sync::atomic::AtomicBool; + use core::sync::atomic::Ordering::Relaxed; + use crate::io; - use core::sync::atomic::{AtomicBool, Ordering::Relaxed}; pub fn fill_bytes(v: &mut [u8]) { static RNG_INIT: AtomicBool = AtomicBool::new(false); diff --git a/library/std/src/sys/pal/unix/stack_overflow.rs b/library/std/src/sys/pal/unix/stack_overflow.rs index 6eeec48bf5eaf..9ff44b54c41a1 100644 --- a/library/std/src/sys/pal/unix/stack_overflow.rs +++ b/library/std/src/sys/pal/unix/stack_overflow.rs @@ -1,10 +1,8 @@ #![cfg_attr(test, allow(dead_code))] +pub use self::imp::{cleanup, init}; use self::imp::{drop_handler, make_handler}; -pub use self::imp::cleanup; -pub use self::imp::init; - pub struct Handler { data: *mut libc::c_void, } @@ -37,24 +35,23 @@ impl Drop for Handler { target_os = "solaris" ))] mod imp { + #[cfg(not(all(target_os = "linux", target_env = "gnu")))] + use libc::{mmap as mmap64, mprotect, munmap}; + #[cfg(all(target_os = "linux", target_env = "gnu"))] + use libc::{mmap64, mprotect, munmap}; + use libc::{ + sigaction, sigaltstack, sighandler_t, MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, + PROT_NONE, PROT_READ, PROT_WRITE, SA_ONSTACK, SA_SIGINFO, SIGBUS, SIGSEGV, SIG_DFL, + SS_DISABLE, + }; + use super::Handler; use crate::cell::Cell; - use crate::io; - use crate::mem; use crate::ops::Range; - use crate::ptr; use crate::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; use crate::sync::OnceLock; use crate::sys::pal::unix::os; - use crate::thread; - - #[cfg(not(all(target_os = "linux", target_env = "gnu")))] - use libc::{mmap as mmap64, mprotect, munmap}; - #[cfg(all(target_os = "linux", target_env = "gnu"))] - use libc::{mmap64, mprotect, munmap}; - use libc::{sigaction, sighandler_t, SA_ONSTACK, SA_SIGINFO, SIGBUS, SIGSEGV, SIG_DFL}; - use libc::{sigaltstack, SS_DISABLE}; - use libc::{MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE}; + use crate::{io, mem, ptr, thread}; // We use a TLS variable to store the address of the guard page. While TLS // variables are not guaranteed to be signal-safe, this works out in practice diff --git a/library/std/src/sys/pal/unix/thread.rs b/library/std/src/sys/pal/unix/thread.rs index 619f4e4121e73..44cb7b7b7ce5b 100644 --- a/library/std/src/sys/pal/unix/thread.rs +++ b/library/std/src/sys/pal/unix/thread.rs @@ -1,16 +1,13 @@ -use crate::cmp; use crate::ffi::CStr; -use crate::io; -use crate::mem; +use crate::mem::{self, ManuallyDrop}; use crate::num::NonZero; -use crate::ptr; -use crate::sys::{os, stack_overflow}; -use crate::time::Duration; - #[cfg(all(target_os = "linux", target_env = "gnu"))] use crate::sys::weak::dlsym; #[cfg(any(target_os = "solaris", target_os = "illumos", target_os = "nto"))] use crate::sys::weak::weak; +use crate::sys::{os, stack_overflow}; +use crate::time::Duration; +use crate::{cmp, io, ptr}; #[cfg(not(any(target_os = "l4re", target_os = "vxworks", target_os = "espidf")))] pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024; #[cfg(target_os = "l4re")] @@ -268,11 +265,9 @@ impl Thread { } pub fn join(self) { - unsafe { - let ret = libc::pthread_join(self.id, ptr::null_mut()); - mem::forget(self); - assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret)); - } + let id = self.into_id(); + let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) }; + assert!(ret == 0, "failed to join thread: {}", io::Error::from_raw_os_error(ret)); } pub fn id(&self) -> libc::pthread_t { @@ -280,9 +275,7 @@ impl Thread { } pub fn into_id(self) -> libc::pthread_t { - let id = self.id; - mem::forget(self); - id + ManuallyDrop::new(self).id } } @@ -462,8 +455,18 @@ pub fn available_parallelism() -> io::Result> { Ok(NonZero::new_unchecked(sinfo.cpu_count as usize)) } + } else if #[cfg(target_os = "vxworks")] { + // Note: there is also `vxCpuConfiguredGet`, closer to _SC_NPROCESSORS_CONF + // expectations than the actual cores availability. + extern "C" { + fn vxCpuEnabledGet() -> libc::cpuset_t; + } + + // always fetches a valid bitmask + let set = unsafe { vxCpuEnabledGet() }; + Ok(NonZero::new_unchecked(set.count_ones() as usize)) } else { - // FIXME: implement on vxWorks, Redox, l4re + // FIXME: implement on Redox, l4re Err(io::const_io_error!(io::ErrorKind::Unsupported, "Getting the number of hardware threads is not supported on the target platform")) } } @@ -479,11 +482,9 @@ mod cgroups { use crate::borrow::Cow; use crate::ffi::OsString; use crate::fs::{exists, File}; - use crate::io::Read; - use crate::io::{BufRead, BufReader}; + use crate::io::{BufRead, BufReader, Read}; use crate::os::unix::ffi::OsStringExt; - use crate::path::Path; - use crate::path::PathBuf; + use crate::path::{Path, PathBuf}; use crate::str::from_utf8; #[derive(PartialEq)] diff --git a/library/std/src/sys/pal/unix/thread_parking.rs b/library/std/src/sys/pal/unix/thread_parking.rs index 1366410b71edc..1da5fce3cd30f 100644 --- a/library/std/src/sys/pal/unix/thread_parking.rs +++ b/library/std/src/sys/pal/unix/thread_parking.rs @@ -2,10 +2,11 @@ // separate modules for each platform. #![cfg(target_os = "netbsd")] +use libc::{_lwp_self, c_long, clockid_t, lwpid_t, time_t, timespec, CLOCK_MONOTONIC}; + use crate::ffi::{c_int, c_void}; use crate::ptr; use crate::time::Duration; -use libc::{_lwp_self, c_long, clockid_t, lwpid_t, time_t, timespec, CLOCK_MONOTONIC}; extern "C" { fn ___lwp_park60( diff --git a/library/std/src/sys/pal/unix/weak.rs b/library/std/src/sys/pal/unix/weak.rs index 4765a286e6b9e..35762f5a53b5b 100644 --- a/library/std/src/sys/pal/unix/weak.rs +++ b/library/std/src/sys/pal/unix/weak.rs @@ -23,9 +23,8 @@ use crate::ffi::CStr; use crate::marker::PhantomData; -use crate::mem; -use crate::ptr; use crate::sync::atomic::{self, AtomicPtr, Ordering}; +use crate::{mem, ptr}; // We can use true weak linkage on ELF targets. #[cfg(all(unix, not(target_vendor = "apple")))] @@ -169,14 +168,7 @@ pub(crate) macro syscall { if let Some(fun) = $name.get() { fun($($arg_name),*) } else { - // This looks like a hack, but concat_idents only accepts idents - // (not paths). - use libc::*; - - syscall( - concat_idents!(SYS_, $name), - $($arg_name),* - ) as $ret + libc::syscall(libc::${concat(SYS_, $name)}, $($arg_name),*) as $ret } } ) @@ -186,14 +178,7 @@ pub(crate) macro syscall { pub(crate) macro raw_syscall { (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => ( unsafe fn $name($($arg_name:$t),*) -> $ret { - // This looks like a hack, but concat_idents only accepts idents - // (not paths). - use libc::*; - - syscall( - concat_idents!(SYS_, $name), - $($arg_name),* - ) as $ret + libc::syscall(libc::${concat(SYS_, $name)}, $($arg_name),*) as $ret } ) } diff --git a/library/std/src/sys/pal/unsupported/os.rs b/library/std/src/sys/pal/unsupported/os.rs index 3be98898bbeb9..481fd62c04fe8 100644 --- a/library/std/src/sys/pal/unsupported/os.rs +++ b/library/std/src/sys/pal/unsupported/os.rs @@ -1,10 +1,9 @@ use super::unsupported; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::path::{self, PathBuf}; +use crate::{fmt, io}; pub fn errno() -> i32 { 0 diff --git a/library/std/src/sys/pal/unsupported/pipe.rs b/library/std/src/sys/pal/unsupported/pipe.rs index 781eafe2f1a6b..6799d21a1ff75 100644 --- a/library/std/src/sys/pal/unsupported/pipe.rs +++ b/library/std/src/sys/pal/unsupported/pipe.rs @@ -1,7 +1,5 @@ -use crate::{ - fmt, - io::{self, BorrowedCursor, IoSlice, IoSliceMut}, -}; +use crate::fmt; +use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; pub struct AnonPipe(!); diff --git a/library/std/src/sys/pal/unsupported/process.rs b/library/std/src/sys/pal/unsupported/process.rs index 2445d9073dbb9..40231bfc90b1e 100644 --- a/library/std/src/sys/pal/unsupported/process.rs +++ b/library/std/src/sys/pal/unsupported/process.rs @@ -1,14 +1,12 @@ +pub use crate::ffi::OsString as EnvKey; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::num::NonZero; use crate::path::Path; use crate::sys::fs::File; use crate::sys::pipe::AnonPipe; use crate::sys::unsupported; use crate::sys_common::process::{CommandEnv, CommandEnvs}; - -pub use crate::ffi::OsString as EnvKey; +use crate::{fmt, io}; //////////////////////////////////////////////////////////////////////////////// // Command diff --git a/library/std/src/sys/pal/wasi/args.rs b/library/std/src/sys/pal/wasi/args.rs index c42c310e3a254..6b6d1b8ff4e2e 100644 --- a/library/std/src/sys/pal/wasi/args.rs +++ b/library/std/src/sys/pal/wasi/args.rs @@ -1,9 +1,8 @@ #![deny(unsafe_op_in_unsafe_fn)] use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; use crate::os::wasi::ffi::OsStrExt; -use crate::vec; +use crate::{fmt, vec}; pub struct Args { iter: vec::IntoIter, diff --git a/library/std/src/sys/pal/wasi/fs.rs b/library/std/src/sys/pal/wasi/fs.rs index c58e6a08b374e..11900886f0b5c 100644 --- a/library/std/src/sys/pal/wasi/fs.rs +++ b/library/std/src/sys/pal/wasi/fs.rs @@ -2,22 +2,19 @@ use super::fd::WasiFd; use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, SeekFrom}; -use crate::iter; use crate::mem::{self, ManuallyDrop}; use crate::os::raw::c_int; use crate::os::wasi::ffi::{OsStrExt, OsStringExt}; use crate::os::wasi::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd}; use crate::path::{Path, PathBuf}; -use crate::ptr; use crate::sync::Arc; use crate::sys::common::small_c_string::run_path_with_cstr; use crate::sys::time::SystemTime; use crate::sys::unsupported; -use crate::sys_common::{AsInner, FromInner, IntoInner}; - pub use crate::sys_common::fs::exists; +use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::{fmt, iter, ptr}; pub struct File { fd: WasiFd, diff --git a/library/std/src/sys/pal/wasi/helpers.rs b/library/std/src/sys/pal/wasi/helpers.rs index 82149cef8fad1..4b770ee23bc5d 100644 --- a/library/std/src/sys/pal/wasi/helpers.rs +++ b/library/std/src/sys/pal/wasi/helpers.rs @@ -1,5 +1,4 @@ -use crate::io as std_io; -use crate::mem; +use crate::{io as std_io, mem}; #[inline] pub fn is_interrupted(errno: i32) -> bool { diff --git a/library/std/src/sys/pal/wasi/mod.rs b/library/std/src/sys/pal/wasi/mod.rs index d8fe06d1973c9..f4dc3ebd4140b 100644 --- a/library/std/src/sys/pal/wasi/mod.rs +++ b/library/std/src/sys/pal/wasi/mod.rs @@ -48,8 +48,5 @@ mod helpers; // import conflict rules. If we glob export `helpers` and `common` together, // then the compiler complains about conflicts. -pub use helpers::abort_internal; -pub use helpers::decode_error_kind; use helpers::err2io; -pub use helpers::hashmap_random_keys; -pub use helpers::is_interrupted; +pub use helpers::{abort_internal, decode_error_kind, hashmap_random_keys, is_interrupted}; diff --git a/library/std/src/sys/pal/wasi/os.rs b/library/std/src/sys/pal/wasi/os.rs index e96296997e6a9..f5b17d9df94b4 100644 --- a/library/std/src/sys/pal/wasi/os.rs +++ b/library/std/src/sys/pal/wasi/os.rs @@ -1,18 +1,16 @@ #![deny(unsafe_op_in_unsafe_fn)] +use core::slice::memchr; + use crate::error::Error as StdError; use crate::ffi::{CStr, OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::ops::Drop; use crate::os::wasi::prelude::*; use crate::path::{self, PathBuf}; -use crate::str; use crate::sys::common::small_c_string::{run_path_with_cstr, run_with_cstr}; use crate::sys::unsupported; -use crate::vec; -use core::slice::memchr; +use crate::{fmt, io, str, vec}; // Add a few symbols not in upstream `libc` just yet. mod libc { diff --git a/library/std/src/sys/pal/wasi/thread.rs b/library/std/src/sys/pal/wasi/thread.rs index 975eef2451f4c..c37acd8dfeeb7 100644 --- a/library/std/src/sys/pal/wasi/thread.rs +++ b/library/std/src/sys/pal/wasi/thread.rs @@ -1,9 +1,8 @@ use crate::ffi::CStr; -use crate::io; -use crate::mem; use crate::num::NonZero; use crate::sys::unsupported; use crate::time::Duration; +use crate::{io, mem}; cfg_if::cfg_if! { if #[cfg(target_feature = "atomics")] { @@ -172,12 +171,10 @@ impl Thread { pub fn join(self) { cfg_if::cfg_if! { if #[cfg(target_feature = "atomics")] { - unsafe { - let ret = libc::pthread_join(self.id, ptr::null_mut()); - mem::forget(self); - if ret != 0 { - rtabort!("failed to join thread: {}", io::Error::from_raw_os_error(ret)); - } + let id = mem::ManuallyDrop::new(self).id; + let ret = unsafe { libc::pthread_join(id, ptr::null_mut()) }; + if ret != 0 { + rtabort!("failed to join thread: {}", io::Error::from_raw_os_error(ret)); } } else { self.0 diff --git a/library/std/src/sys/pal/wasip2/mod.rs b/library/std/src/sys/pal/wasip2/mod.rs index 0930d2e22fa8d..f20630e10cff9 100644 --- a/library/std/src/sys/pal/wasip2/mod.rs +++ b/library/std/src/sys/pal/wasip2/mod.rs @@ -51,10 +51,7 @@ mod helpers; // import conflict rules. If we glob export `helpers` and `common` together, // then the compiler complains about conflicts. -pub use helpers::abort_internal; -pub use helpers::decode_error_kind; use helpers::err2io; -pub use helpers::hashmap_random_keys; -pub use helpers::is_interrupted; +pub use helpers::{abort_internal, decode_error_kind, hashmap_random_keys, is_interrupted}; mod cabi_realloc; diff --git a/library/std/src/sys/pal/wasm/alloc.rs b/library/std/src/sys/pal/wasm/alloc.rs index b74ce0d47425a..ef9d753d7f86c 100644 --- a/library/std/src/sys/pal/wasm/alloc.rs +++ b/library/std/src/sys/pal/wasm/alloc.rs @@ -57,10 +57,8 @@ unsafe impl GlobalAlloc for System { #[cfg(target_feature = "atomics")] mod lock { - use crate::sync::atomic::{ - AtomicI32, - Ordering::{Acquire, Release}, - }; + use crate::sync::atomic::AtomicI32; + use crate::sync::atomic::Ordering::{Acquire, Release}; static LOCKED: AtomicI32 = AtomicI32::new(0); diff --git a/library/std/src/sys/pal/wasm/atomics/futex.rs b/library/std/src/sys/pal/wasm/atomics/futex.rs index 3584138ca0447..42913a99ee9d6 100644 --- a/library/std/src/sys/pal/wasm/atomics/futex.rs +++ b/library/std/src/sys/pal/wasm/atomics/futex.rs @@ -24,7 +24,7 @@ pub fn futex_wait(futex: &AtomicU32, expected: u32, timeout: Option) - } } -/// Wake up one thread that's blocked on futex_wait on this futex. +/// Wakes up one thread that's blocked on `futex_wait` on this futex. /// /// Returns true if this actually woke up such a thread, /// or false if no thread was waiting on this futex. @@ -32,7 +32,7 @@ pub fn futex_wake(futex: &AtomicU32) -> bool { unsafe { wasm::memory_atomic_notify(futex as *const AtomicU32 as *mut i32, 1) > 0 } } -/// Wake up all threads that are waiting on futex_wait on this futex. +/// Wakes up all threads that are waiting on `futex_wait` on this futex. pub fn futex_wake_all(futex: &AtomicU32) { unsafe { wasm::memory_atomic_notify(futex as *const AtomicU32 as *mut i32, i32::MAX as u32); diff --git a/library/std/src/sys/pal/windows/alloc.rs b/library/std/src/sys/pal/windows/alloc.rs index 987be6b69eec9..92b68b26032c6 100644 --- a/library/std/src/sys/pal/windows/alloc.rs +++ b/library/std/src/sys/pal/windows/alloc.rs @@ -1,10 +1,11 @@ +use core::mem::MaybeUninit; + use crate::alloc::{GlobalAlloc, Layout, System}; use crate::ffi::c_void; use crate::ptr; use crate::sync::atomic::{AtomicPtr, Ordering}; use crate::sys::c::{self, windows_targets}; use crate::sys::common::alloc::{realloc_fallback, MIN_ALIGN}; -use core::mem::MaybeUninit; #[cfg(test)] mod tests; @@ -37,7 +38,7 @@ windows_targets::link!("kernel32.dll" "system" fn GetProcessHeap() -> c::HANDLE) // Note that `dwBytes` is allowed to be zero, contrary to some other allocators. // // See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-heapalloc -windows_targets::link!("kernel32.dll" "system" fn HeapAlloc(hheap: c::HANDLE, dwflags: u32, dwbytes: usize) -> *mut core::ffi::c_void); +windows_targets::link!("kernel32.dll" "system" fn HeapAlloc(hheap: c::HANDLE, dwflags: u32, dwbytes: usize) -> *mut c_void); // Reallocate a block of memory behind a given pointer `lpMem` from a given heap `hHeap`, // to a block of at least `dwBytes` bytes, either shrinking the block in place, @@ -61,9 +62,9 @@ windows_targets::link!("kernel32.dll" "system" fn HeapAlloc(hheap: c::HANDLE, dw windows_targets::link!("kernel32.dll" "system" fn HeapReAlloc( hheap: c::HANDLE, dwflags : u32, - lpmem: *const core::ffi::c_void, + lpmem: *const c_void, dwbytes: usize -) -> *mut core::ffi::c_void); +) -> *mut c_void); // Free a block of memory behind a given pointer `lpMem` from a given heap `hHeap`. // Returns a nonzero value if the operation is successful, and zero if the operation fails. @@ -79,7 +80,7 @@ windows_targets::link!("kernel32.dll" "system" fn HeapReAlloc( // Note that `lpMem` is allowed to be null, which will not cause the operation to fail. // // See https://docs.microsoft.com/windows/win32/api/heapapi/nf-heapapi-heapfree -windows_targets::link!("kernel32.dll" "system" fn HeapFree(hheap: c::HANDLE, dwflags: u32, lpmem: *const core::ffi::c_void) -> c::BOOL); +windows_targets::link!("kernel32.dll" "system" fn HeapFree(hheap: c::HANDLE, dwflags: u32, lpmem: *const c_void) -> c::BOOL); // Cached handle to the default heap of the current process. // Either a non-null handle returned by `GetProcessHeap`, or null when not yet initialized or `GetProcessHeap` failed. diff --git a/library/std/src/sys/pal/windows/args.rs b/library/std/src/sys/pal/windows/args.rs index 5098c05196e25..66e75a8357149 100644 --- a/library/std/src/sys/pal/windows/args.rs +++ b/library/std/src/sys/pal/windows/args.rs @@ -8,8 +8,6 @@ mod tests; use super::os::current_exe; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::num::NonZero; use crate::os::windows::prelude::*; use crate::path::{Path, PathBuf}; @@ -18,9 +16,7 @@ use crate::sys::process::ensure_no_nuls; use crate::sys::{c, to_u16s}; use crate::sys_common::wstr::WStrUnits; use crate::sys_common::AsInner; -use crate::vec; - -use crate::iter; +use crate::{fmt, io, iter, vec}; /// This is the const equivalent to `NonZero::new(n).unwrap()` /// diff --git a/library/std/src/sys/pal/windows/c.rs b/library/std/src/sys/pal/windows/c.rs index f8d8398b8250e..08b75186aef90 100644 --- a/library/std/src/sys/pal/windows/c.rs +++ b/library/std/src/sys/pal/windows/c.rs @@ -4,12 +4,9 @@ #![cfg_attr(test, allow(dead_code))] #![unstable(issue = "none", feature = "windows_c")] #![allow(clippy::style)] -#![allow(unsafe_op_in_unsafe_fn)] -use crate::ffi::CStr; -use crate::mem; -use crate::os::raw::{c_uint, c_ulong, c_ushort, c_void}; -use crate::ptr; +use core::ffi::{c_uint, c_ulong, c_ushort, c_void, CStr}; +use core::{mem, ptr}; pub(super) mod windows_targets; @@ -136,26 +133,26 @@ compat_fn_with_fallback! { // >= Win10 1607 // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreaddescription pub fn SetThreadDescription(hthread: HANDLE, lpthreaddescription: PCWSTR) -> HRESULT { - SetLastError(ERROR_CALL_NOT_IMPLEMENTED as u32); E_NOTIMPL + unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as u32); E_NOTIMPL } } // >= Win10 1607 // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreaddescription pub fn GetThreadDescription(hthread: HANDLE, lpthreaddescription: *mut PWSTR) -> HRESULT { - SetLastError(ERROR_CALL_NOT_IMPLEMENTED as u32); E_NOTIMPL + unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as u32); E_NOTIMPL } } // >= Win8 / Server 2012 // https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime #[cfg(target_vendor = "win7")] pub fn GetSystemTimePreciseAsFileTime(lpsystemtimeasfiletime: *mut FILETIME) -> () { - GetSystemTimeAsFileTime(lpsystemtimeasfiletime) + unsafe { GetSystemTimeAsFileTime(lpsystemtimeasfiletime) } } // >= Win11 / Server 2022 // https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppath2a pub fn GetTempPath2W(bufferlength: u32, buffer: PWSTR) -> u32 { - GetTempPathW(bufferlength, buffer) + unsafe { GetTempPathW(bufferlength, buffer) } } } @@ -188,12 +185,12 @@ extern "system" { compat_fn_optional! { crate::sys::compat::load_synch_functions(); pub fn WaitOnAddress( - address: *const ::core::ffi::c_void, - compareaddress: *const ::core::ffi::c_void, + address: *const c_void, + compareaddress: *const c_void, addresssize: usize, dwmilliseconds: u32 ) -> BOOL; - pub fn WakeByAddressSingle(address: *const ::core::ffi::c_void); + pub fn WakeByAddressSingle(address: *const c_void); } #[cfg(any(target_vendor = "win7", target_vendor = "uwp"))] @@ -240,7 +237,7 @@ compat_fn_with_fallback! { shareaccess: FILE_SHARE_MODE, createdisposition: NTCREATEFILE_CREATE_DISPOSITION, createoptions: NTCREATEFILE_CREATE_OPTIONS, - eabuffer: *const ::core::ffi::c_void, + eabuffer: *const c_void, ealength: u32 ) -> NTSTATUS { STATUS_NOT_IMPLEMENTED @@ -250,9 +247,9 @@ compat_fn_with_fallback! { filehandle: HANDLE, event: HANDLE, apcroutine: PIO_APC_ROUTINE, - apccontext: *const core::ffi::c_void, + apccontext: *const c_void, iostatusblock: *mut IO_STATUS_BLOCK, - buffer: *mut core::ffi::c_void, + buffer: *mut c_void, length: u32, byteoffset: *const i64, key: *const u32 @@ -264,9 +261,9 @@ compat_fn_with_fallback! { filehandle: HANDLE, event: HANDLE, apcroutine: PIO_APC_ROUTINE, - apccontext: *const core::ffi::c_void, + apccontext: *const c_void, iostatusblock: *mut IO_STATUS_BLOCK, - buffer: *const core::ffi::c_void, + buffer: *const c_void, length: u32, byteoffset: *const i64, key: *const u32 @@ -278,44 +275,3 @@ compat_fn_with_fallback! { Status as u32 } } - -// # Arm32 shim -// -// AddVectoredExceptionHandler and WSAStartup use platform-specific types. -// However, Microsoft no longer supports thumbv7a so definitions for those targets -// are not included in the win32 metadata. We work around that by defining them here. -// -// Where possible, these definitions should be kept in sync with https://docs.rs/windows-sys -cfg_if::cfg_if! { -if #[cfg(not(target_vendor = "uwp"))] { - #[link(name = "kernel32")] - extern "system" { - pub fn AddVectoredExceptionHandler( - first: u32, - handler: PVECTORED_EXCEPTION_HANDLER, - ) -> *mut c_void; - } - pub type PVECTORED_EXCEPTION_HANDLER = Option< - unsafe extern "system" fn(exceptioninfo: *mut EXCEPTION_POINTERS) -> i32, - >; - #[repr(C)] - pub struct EXCEPTION_POINTERS { - pub ExceptionRecord: *mut EXCEPTION_RECORD, - pub ContextRecord: *mut CONTEXT, - } - #[cfg(target_arch = "arm")] - pub enum CONTEXT {} -}} -// WSAStartup is only redefined here so that we can override WSADATA for Arm32 -windows_targets::link!("ws2_32.dll" "system" fn WSAStartup(wversionrequested: u16, lpwsadata: *mut WSADATA) -> i32); -#[cfg(target_arch = "arm")] -#[repr(C)] -pub struct WSADATA { - pub wVersion: u16, - pub wHighVersion: u16, - pub szDescription: [u8; 257], - pub szSystemStatus: [u8; 129], - pub iMaxSockets: u16, - pub iMaxUdpDg: u16, - pub lpVendorInfo: PSTR, -} diff --git a/library/std/src/sys/pal/windows/c/bindings.txt b/library/std/src/sys/pal/windows/c/bindings.txt index de4f1050e927a..afacc370c3420 100644 --- a/library/std/src/sys/pal/windows/c/bindings.txt +++ b/library/std/src/sys/pal/windows/c/bindings.txt @@ -2176,6 +2176,7 @@ Windows.Win32.Networking.WinSock.WSARecv Windows.Win32.Networking.WinSock.WSASend Windows.Win32.Networking.WinSock.WSASERVICE_NOT_FOUND Windows.Win32.Networking.WinSock.WSASocketW +Windows.Win32.Networking.WinSock.WSAStartup Windows.Win32.Networking.WinSock.WSASYSCALLFAILURE Windows.Win32.Networking.WinSock.WSASYSNOTREADY Windows.Win32.Networking.WinSock.WSATRY_AGAIN @@ -2420,6 +2421,7 @@ Windows.Win32.System.Console.STD_HANDLE Windows.Win32.System.Console.STD_INPUT_HANDLE Windows.Win32.System.Console.STD_OUTPUT_HANDLE Windows.Win32.System.Console.WriteConsoleW +Windows.Win32.System.Diagnostics.Debug.AddVectoredExceptionHandler Windows.Win32.System.Diagnostics.Debug.ARM64_NT_NEON128 Windows.Win32.System.Diagnostics.Debug.CONTEXT Windows.Win32.System.Diagnostics.Debug.EXCEPTION_RECORD diff --git a/library/std/src/sys/pal/windows/c/windows_sys.rs b/library/std/src/sys/pal/windows/c/windows_sys.rs index 29110bde3b4c4..9f22f54819509 100644 --- a/library/std/src/sys/pal/windows/c/windows_sys.rs +++ b/library/std/src/sys/pal/windows/c/windows_sys.rs @@ -5,6 +5,7 @@ windows_targets::link!("advapi32.dll" "system" fn OpenProcessToken(processhandle windows_targets::link!("advapi32.dll" "system" "SystemFunction036" fn RtlGenRandom(randombuffer : *mut core::ffi::c_void, randombufferlength : u32) -> BOOLEAN); windows_targets::link!("kernel32.dll" "system" fn AcquireSRWLockExclusive(srwlock : *mut SRWLOCK)); windows_targets::link!("kernel32.dll" "system" fn AcquireSRWLockShared(srwlock : *mut SRWLOCK)); +windows_targets::link!("kernel32.dll" "system" fn AddVectoredExceptionHandler(first : u32, handler : PVECTORED_EXCEPTION_HANDLER) -> *mut core::ffi::c_void); windows_targets::link!("kernel32.dll" "system" fn CancelIo(hfile : HANDLE) -> BOOL); windows_targets::link!("kernel32.dll" "system" fn CloseHandle(hobject : HANDLE) -> BOOL); windows_targets::link!("kernel32.dll" "system" fn CompareStringOrdinal(lpstring1 : PCWSTR, cchcount1 : i32, lpstring2 : PCWSTR, cchcount2 : i32, bignorecase : BOOL) -> COMPARESTRING_RESULT); @@ -114,6 +115,7 @@ windows_targets::link!("ws2_32.dll" "system" fn WSAGetLastError() -> WSA_ERROR); windows_targets::link!("ws2_32.dll" "system" fn WSARecv(s : SOCKET, lpbuffers : *const WSABUF, dwbuffercount : u32, lpnumberofbytesrecvd : *mut u32, lpflags : *mut u32, lpoverlapped : *mut OVERLAPPED, lpcompletionroutine : LPWSAOVERLAPPED_COMPLETION_ROUTINE) -> i32); windows_targets::link!("ws2_32.dll" "system" fn WSASend(s : SOCKET, lpbuffers : *const WSABUF, dwbuffercount : u32, lpnumberofbytessent : *mut u32, dwflags : u32, lpoverlapped : *mut OVERLAPPED, lpcompletionroutine : LPWSAOVERLAPPED_COMPLETION_ROUTINE) -> i32); windows_targets::link!("ws2_32.dll" "system" fn WSASocketW(af : i32, r#type : i32, protocol : i32, lpprotocolinfo : *const WSAPROTOCOL_INFOW, g : u32, dwflags : u32) -> SOCKET); +windows_targets::link!("ws2_32.dll" "system" fn WSAStartup(wversionrequested : u16, lpwsadata : *mut WSADATA) -> i32); windows_targets::link!("ws2_32.dll" "system" fn accept(s : SOCKET, addr : *mut SOCKADDR, addrlen : *mut i32) -> SOCKET); windows_targets::link!("ws2_32.dll" "system" fn bind(s : SOCKET, name : *const SOCKADDR, namelen : i32) -> i32); windows_targets::link!("ws2_32.dll" "system" fn closesocket(s : SOCKET) -> i32); @@ -2284,6 +2286,12 @@ pub type EXCEPTION_DISPOSITION = i32; pub const EXCEPTION_MAXIMUM_PARAMETERS: u32 = 15u32; #[repr(C)] #[derive(Clone, Copy)] +pub struct EXCEPTION_POINTERS { + pub ExceptionRecord: *mut EXCEPTION_RECORD, + pub ContextRecord: *mut CONTEXT, +} +#[repr(C)] +#[derive(Clone, Copy)] pub struct EXCEPTION_RECORD { pub ExceptionCode: NTSTATUS, pub ExceptionFlags: u32, @@ -2860,6 +2868,8 @@ pub type PTIMERAPCROUTINE = Option< dwtimerhighvalue: u32, ), >; +pub type PVECTORED_EXCEPTION_HANDLER = + Option i32>; pub type PWSTR = *mut u16; pub const READ_CONTROL: FILE_ACCESS_RIGHTS = 131072u32; pub const REALTIME_PRIORITY_CLASS: PROCESS_CREATION_FLAGS = 256u32; @@ -3292,5 +3302,19 @@ pub struct XSAVE_FORMAT { pub XmmRegisters: [M128A; 8], pub Reserved4: [u8; 224], } + +#[cfg(target_arch = "arm")] +#[repr(C)] +pub struct WSADATA { + pub wVersion: u16, + pub wHighVersion: u16, + pub szDescription: [u8; 257], + pub szSystemStatus: [u8; 129], + pub iMaxSockets: u16, + pub iMaxUdpDg: u16, + pub lpVendorInfo: PSTR, +} +#[cfg(target_arch = "arm")] +pub enum CONTEXT {} // ignore-tidy-filelength use super::windows_targets; diff --git a/library/std/src/sys/pal/windows/compat.rs b/library/std/src/sys/pal/windows/compat.rs index 49fa1603f3e1e..75232dfc0b0f1 100644 --- a/library/std/src/sys/pal/windows/compat.rs +++ b/library/std/src/sys/pal/windows/compat.rs @@ -158,8 +158,10 @@ macro_rules! compat_fn_with_fallback { static PTR: AtomicPtr = AtomicPtr::new(load as *mut _); unsafe extern "system" fn load($($argname: $argtype),*) -> $rettype { - let func = load_from_module(Module::new($module)); - func($($argname),*) + unsafe { + let func = load_from_module(Module::new($module)); + func($($argname),*) + } } fn load_from_module(module: Option) -> F { @@ -182,8 +184,10 @@ macro_rules! compat_fn_with_fallback { #[inline(always)] pub unsafe fn call($($argname: $argtype),*) -> $rettype { - let func: F = mem::transmute(PTR.load(Ordering::Relaxed)); - func($($argname),*) + unsafe { + let func: F = mem::transmute(PTR.load(Ordering::Relaxed)); + func($($argname),*) + } } } #[allow(unused)] @@ -225,7 +229,7 @@ macro_rules! compat_fn_optional { } #[inline] pub unsafe extern "system" fn $symbol($($argname: $argtype),*) $(-> $rettype)? { - $symbol::option().unwrap()($($argname),*) + unsafe { $symbol::option().unwrap()($($argname),*) } } )+ ) diff --git a/library/std/src/sys/pal/windows/fs.rs b/library/std/src/sys/pal/windows/fs.rs index 15d446786addc..d99d4931de40f 100644 --- a/library/std/src/sys/pal/windows/fs.rs +++ b/library/std/src/sys/pal/windows/fs.rs @@ -1,26 +1,21 @@ use core::ptr::addr_of; -use crate::os::windows::prelude::*; - +use super::api::{self, WinError}; +use super::{to_u16s, IoResult}; use crate::borrow::Cow; use crate::ffi::{c_void, OsStr, OsString}; -use crate::fmt; use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom}; use crate::mem::{self, MaybeUninit}; use crate::os::windows::io::{AsHandle, BorrowedHandle}; +use crate::os::windows::prelude::*; use crate::path::{Path, PathBuf}; -use crate::ptr; -use crate::slice; use crate::sync::Arc; use crate::sys::handle::Handle; +use crate::sys::path::maybe_verbatim; use crate::sys::time::SystemTime; use crate::sys::{c, cvt, Align8}; use crate::sys_common::{AsInner, FromInner, IntoInner}; -use crate::thread; - -use super::api::{self, WinError}; -use super::{to_u16s, IoResult}; -use crate::sys::path::maybe_verbatim; +use crate::{fmt, ptr, slice, thread}; pub struct File { handle: Handle, @@ -416,8 +411,8 @@ impl File { dwHighDateTime: (info.LastWriteTime >> 32) as u32, }, change_time: Some(c::FILETIME { - dhLowDateTime: info.ChangeTime as c::DWORD, - dhHighDateTime: (info.ChangeTime >> 32) as c::DWORD, + dwLowDateTime: info.ChangeTime as u32, + dwHighDateTime: (info.ChangeTime >> 32) as u32, }), file_size: 0, reparse_tag: 0, @@ -637,7 +632,7 @@ impl File { Ok(()) } - /// Get only basic file information such as attributes and file times. + /// Gets only basic file information such as attributes and file times. fn basic_info(&self) -> io::Result { unsafe { let mut info: c::FILE_BASIC_INFO = mem::zeroed(); diff --git a/library/std/src/sys/pal/windows/futex.rs b/library/std/src/sys/pal/windows/futex.rs index c54810e06cdd6..8c5081a607aa3 100644 --- a/library/std/src/sys/pal/windows/futex.rs +++ b/library/std/src/sys/pal/windows/futex.rs @@ -1,14 +1,13 @@ -use super::api::{self, WinError}; -use crate::sys::c; -use crate::sys::dur2timeout; use core::ffi::c_void; -use core::mem; -use core::ptr; use core::sync::atomic::{ AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicPtr, AtomicU16, AtomicU32, AtomicU64, AtomicU8, AtomicUsize, }; use core::time::Duration; +use core::{mem, ptr}; + +use super::api::{self, WinError}; +use crate::sys::{c, dur2timeout}; /// An atomic for use as a futex that is at least 8-bits but may be larger. pub type SmallAtomic = AtomicU8; diff --git a/library/std/src/sys/pal/windows/handle.rs b/library/std/src/sys/pal/windows/handle.rs index 94408f69e2503..82a880faf5fa7 100644 --- a/library/std/src/sys/pal/windows/handle.rs +++ b/library/std/src/sys/pal/windows/handle.rs @@ -3,15 +3,14 @@ #[cfg(test)] mod tests; -use crate::cmp; +use core::ffi::c_void; +use core::{cmp, mem, ptr}; + use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut, Read}; -use crate::mem; use crate::os::windows::io::{ AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle, OwnedHandle, RawHandle, }; -use crate::ptr; -use crate::sys::c; -use crate::sys::cvt; +use crate::sys::{c, cvt}; use crate::sys_common::{AsInner, FromInner, IntoInner}; /// An owned container for `HANDLE` object, closing them on Drop. @@ -255,7 +254,7 @@ impl Handle { None, ptr::null_mut(), &mut io_status, - buf.cast::(), + buf.cast::(), len, offset.as_ref().map(|n| ptr::from_ref(n).cast::()).unwrap_or(ptr::null()), ptr::null(), @@ -305,7 +304,7 @@ impl Handle { None, ptr::null_mut(), &mut io_status, - buf.as_ptr().cast::(), + buf.as_ptr().cast::(), len, offset.as_ref().map(|n| ptr::from_ref(n).cast::()).unwrap_or(ptr::null()), ptr::null(), diff --git a/library/std/src/sys/pal/windows/io.rs b/library/std/src/sys/pal/windows/io.rs index bf3dfdfdd3e7d..785a3f6768b70 100644 --- a/library/std/src/sys/pal/windows/io.rs +++ b/library/std/src/sys/pal/windows/io.rs @@ -1,9 +1,10 @@ +use core::ffi::c_void; + use crate::marker::PhantomData; use crate::mem::size_of; use crate::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle}; use crate::slice; use crate::sys::c; -use core::ffi::c_void; #[derive(Copy, Clone)] #[repr(transparent)] diff --git a/library/std/src/sys/pal/windows/mod.rs b/library/std/src/sys/pal/windows/mod.rs index b85a8318bcbbd..6ed77fbc3d445 100644 --- a/library/std/src/sys/pal/windows/mod.rs +++ b/library/std/src/sys/pal/windows/mod.rs @@ -1,6 +1,7 @@ #![allow(missing_docs, nonstandard_style)] -#![deny(unsafe_op_in_unsafe_fn)] +#![forbid(unsafe_op_in_unsafe_fn)] +pub use self::rand::hashmap_random_keys; use crate::ffi::{OsStr, OsString}; use crate::io::ErrorKind; use crate::mem::MaybeUninit; @@ -9,8 +10,6 @@ use crate::path::PathBuf; use crate::sys::pal::windows::api::wide_str; use crate::time::Duration; -pub use self::rand::hashmap_random_keys; - #[macro_use] pub mod compat; diff --git a/library/std/src/sys/pal/windows/net.rs b/library/std/src/sys/pal/windows/net.rs index b7ecff032e4af..ce995f5ed5af7 100644 --- a/library/std/src/sys/pal/windows/net.rs +++ b/library/std/src/sys/pal/windows/net.rs @@ -1,21 +1,17 @@ #![unstable(issue = "none", feature = "windows_net")] -use crate::cmp; +use core::ffi::{c_int, c_long, c_ulong, c_ushort}; + use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut, Read}; -use crate::mem; use crate::net::{Shutdown, SocketAddr}; use crate::os::windows::io::{ AsRawSocket, AsSocket, BorrowedSocket, FromRawSocket, IntoRawSocket, OwnedSocket, RawSocket, }; -use crate::ptr; use crate::sync::OnceLock; -use crate::sys; use crate::sys::c; -use crate::sys_common::net; -use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::sys_common::{net, AsInner, FromInner, IntoInner}; use crate::time::Duration; - -use core::ffi::{c_int, c_long, c_ulong, c_ushort}; +use crate::{cmp, mem, ptr, sys}; #[allow(non_camel_case_types)] pub type wrlen_t = i32; @@ -25,9 +21,10 @@ pub mod netc { //! //! Some Windows API types are not quite what's expected by our cross-platform //! net code. E.g. naming differences or different pointer types. - use crate::sys::c::{self, ADDRESS_FAMILY, ADDRINFOA, SOCKADDR, SOCKET}; + use core::ffi::{c_char, c_int, c_uint, c_ulong, c_ushort, c_void}; + use crate::sys::c::{self, ADDRESS_FAMILY, ADDRINFOA, SOCKADDR, SOCKET}; // re-exports from Windows API bindings. pub use crate::sys::c::{ bind, connect, freeaddrinfo, getpeername, getsockname, getsockopt, listen, setsockopt, diff --git a/library/std/src/sys/pal/windows/os.rs b/library/std/src/sys/pal/windows/os.rs index f1f4d3a5d26ef..5242bc9da31fe 100644 --- a/library/std/src/sys/pal/windows/os.rs +++ b/library/std/src/sys/pal/windows/os.rs @@ -5,20 +5,15 @@ #[cfg(test)] mod tests; -use crate::os::windows::prelude::*; - +use super::api::{self, WinError}; +use super::to_u16s; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::os::windows::ffi::EncodeWide; +use crate::os::windows::prelude::*; use crate::path::{self, PathBuf}; -use crate::ptr; -use crate::slice; use crate::sys::{c, cvt}; - -use super::api::{self, WinError}; -use super::to_u16s; +use crate::{fmt, io, ptr, slice}; pub fn errno() -> i32 { api::get_last_error().code as i32 diff --git a/library/std/src/sys/pal/windows/pipe.rs b/library/std/src/sys/pal/windows/pipe.rs index 01433d68b695b..7d1b5aca1d5fe 100644 --- a/library/std/src/sys/pal/windows/pipe.rs +++ b/library/std/src/sys/pal/windows/pipe.rs @@ -1,18 +1,15 @@ -use crate::os::windows::prelude::*; - use crate::ffi::OsStr; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; -use crate::mem; +use crate::os::windows::prelude::*; use crate::path::Path; -use crate::ptr; use crate::sync::atomic::AtomicUsize; use crate::sync::atomic::Ordering::Relaxed; -use crate::sys::c; use crate::sys::fs::{File, OpenOptions}; use crate::sys::handle::Handle; -use crate::sys::hashmap_random_keys; use crate::sys::pal::windows::api::{self, WinError}; +use crate::sys::{c, hashmap_random_keys}; use crate::sys_common::{FromInner, IntoInner}; +use crate::{mem, ptr}; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes @@ -39,23 +36,6 @@ pub struct Pipes { pub theirs: AnonPipe, } -/// Create true unnamed anonymous pipe. -pub fn unnamed_anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { - let mut read_pipe = c::INVALID_HANDLE_VALUE; - let mut write_pipe = c::INVALID_HANDLE_VALUE; - - let ret = unsafe { c::CreatePipe(&mut read_pipe, &mut write_pipe, ptr::null_mut(), 0) }; - - if ret == 0 { - Err(io::Error::last_os_error()) - } else { - Ok(( - AnonPipe::from_inner(unsafe { Handle::from_raw_handle(read_pipe) }), - AnonPipe::from_inner(unsafe { Handle::from_raw_handle(write_pipe) }), - )) - } -} - /// Although this looks similar to `anon_pipe` in the Unix module it's actually /// subtly different. Here we'll return two pipes in the `Pipes` return value, /// but one is intended for "us" where as the other is intended for "someone diff --git a/library/std/src/sys/pal/windows/process.rs b/library/std/src/sys/pal/windows/process.rs index 76d2cb77d474c..06eae5a07b068 100644 --- a/library/std/src/sys/pal/windows/process.rs +++ b/library/std/src/sys/pal/windows/process.rs @@ -3,35 +3,28 @@ #[cfg(test)] mod tests; -use crate::cmp; +use core::ffi::c_void; + +use super::api::{self, WinError}; use crate::collections::BTreeMap; -use crate::env; use crate::env::consts::{EXE_EXTENSION, EXE_SUFFIX}; use crate::ffi::{OsStr, OsString}; -use crate::fmt; use crate::io::{self, Error, ErrorKind}; -use crate::mem; use crate::mem::MaybeUninit; use crate::num::NonZero; use crate::os::windows::ffi::{OsStrExt, OsStringExt}; use crate::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle}; use crate::path::{Path, PathBuf}; -use crate::ptr; use crate::sync::Mutex; use crate::sys::args::{self, Arg}; use crate::sys::c::{self, EXIT_FAILURE, EXIT_SUCCESS}; -use crate::sys::cvt; use crate::sys::fs::{File, OpenOptions}; use crate::sys::handle::Handle; -use crate::sys::path; use crate::sys::pipe::{self, AnonPipe}; -use crate::sys::stdio; +use crate::sys::{cvt, path, stdio}; use crate::sys_common::process::{CommandEnv, CommandEnvs}; use crate::sys_common::IntoInner; - -use core::ffi::c_void; - -use super::api::{self, WinError}; +use crate::{cmp, env, fmt, mem, ptr}; //////////////////////////////////////////////////////////////////////////////// // Command @@ -549,7 +542,7 @@ where None } -/// Check if a file exists without following symlinks. +/// Checks if a file exists without following symlinks. fn program_exists(path: &Path) -> Option> { unsafe { let path = args::to_user_path(path).ok()?; @@ -571,7 +564,7 @@ impl Stdio { Ok(io) => unsafe { let io = Handle::from_raw_handle(io); let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS); - io.into_raw_handle(); + let _ = io.into_raw_handle(); // Don't close the handle ret }, // If no stdio handle is available, then propagate the null value. diff --git a/library/std/src/sys/pal/windows/process/tests.rs b/library/std/src/sys/pal/windows/process/tests.rs index 3fc0c75240c33..65325fa64a077 100644 --- a/library/std/src/sys/pal/windows/process/tests.rs +++ b/library/std/src/sys/pal/windows/process/tests.rs @@ -1,5 +1,4 @@ -use super::make_command_line; -use super::Arg; +use super::{make_command_line, Arg}; use crate::env; use crate::ffi::{OsStr, OsString}; use crate::process::Command; diff --git a/library/std/src/sys/pal/windows/stdio.rs b/library/std/src/sys/pal/windows/stdio.rs index c6a21665157d7..575f2250eb91c 100644 --- a/library/std/src/sys/pal/windows/stdio.rs +++ b/library/std/src/sys/pal/windows/stdio.rs @@ -1,16 +1,13 @@ #![unstable(issue = "none", feature = "windows_stdio")] +use core::str::utf8_char_width; + use super::api::{self, WinError}; -use crate::cmp; -use crate::io; use crate::mem::MaybeUninit; use crate::os::windows::io::{FromRawHandle, IntoRawHandle}; -use crate::ptr; -use crate::str; -use crate::sys::c; -use crate::sys::cvt; use crate::sys::handle::Handle; -use core::str::utf8_char_width; +use crate::sys::{c, cvt}; +use crate::{cmp, io, ptr, str}; #[cfg(test)] mod tests; @@ -97,7 +94,7 @@ fn write(handle_id: u32, data: &[u8], incomplete_utf8: &mut IncompleteUtf8) -> i unsafe { let handle = Handle::from_raw_handle(handle); let ret = handle.write(data); - handle.into_raw_handle(); // Don't close the handle + let _ = handle.into_raw_handle(); // Don't close the handle return ret; } } @@ -246,7 +243,7 @@ impl io::Read for Stdin { unsafe { let handle = Handle::from_raw_handle(handle); let ret = handle.read(buf); - handle.into_raw_handle(); // Don't close the handle + let _ = handle.into_raw_handle(); // Don't close the handle return ret; } } diff --git a/library/std/src/sys/pal/windows/thread.rs b/library/std/src/sys/pal/windows/thread.rs index 668a3c05e20be..28bce529cd991 100644 --- a/library/std/src/sys/pal/windows/thread.rs +++ b/library/std/src/sys/pal/windows/thread.rs @@ -1,18 +1,15 @@ +use core::ffi::c_void; + +use super::time::WaitableTimer; +use super::to_u16s; use crate::ffi::CStr; -use crate::io; use crate::num::NonZero; -use crate::os::windows::io::AsRawHandle; -use crate::os::windows::io::HandleOrNull; -use crate::ptr; -use crate::sys::c; +use crate::os::windows::io::{AsRawHandle, HandleOrNull}; use crate::sys::handle::Handle; -use crate::sys::stack_overflow; +use crate::sys::{c, stack_overflow}; use crate::sys_common::FromInner; use crate::time::Duration; -use core::ffi::c_void; - -use super::time::WaitableTimer; -use super::to_u16s; +use crate::{io, ptr}; pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024; diff --git a/library/std/src/sys/pal/windows/time.rs b/library/std/src/sys/pal/windows/time.rs index b853daeffebd7..d9010e3996109 100644 --- a/library/std/src/sys/pal/windows/time.rs +++ b/library/std/src/sys/pal/windows/time.rs @@ -1,13 +1,12 @@ +use core::hash::{Hash, Hasher}; +use core::ops::Neg; + use crate::cmp::Ordering; -use crate::fmt; -use crate::mem; use crate::ptr::null; use crate::sys::c; use crate::sys_common::IntoInner; use crate::time::Duration; - -use core::hash::{Hash, Hasher}; -use core::ops::Neg; +use crate::{fmt, mem}; const NANOS_PER_SEC: u64 = 1_000_000_000; const INTERVALS_PER_SEC: u64 = NANOS_PER_SEC / 100; @@ -166,8 +165,7 @@ fn intervals2dur(intervals: u64) -> Duration { mod perf_counter { use super::NANOS_PER_SEC; use crate::sync::atomic::{AtomicU64, Ordering}; - use crate::sys::c; - use crate::sys::cvt; + use crate::sys::{c, cvt}; use crate::sys_common::mul_div_u64; use crate::time::Duration; @@ -230,7 +228,7 @@ pub(super) struct WaitableTimer { handle: c::HANDLE, } impl WaitableTimer { - /// Create a high-resolution timer. Will fail before Windows 10, version 1803. + /// Creates a high-resolution timer. Will fail before Windows 10, version 1803. pub fn high_resolution() -> Result { let handle = unsafe { c::CreateWaitableTimerExW( diff --git a/library/std/src/sys/pal/xous/alloc.rs b/library/std/src/sys/pal/xous/alloc.rs index 601411173aacb..9ea43445d0206 100644 --- a/library/std/src/sys/pal/xous/alloc.rs +++ b/library/std/src/sys/pal/xous/alloc.rs @@ -46,10 +46,8 @@ unsafe impl GlobalAlloc for System { } mod lock { - use crate::sync::atomic::{ - AtomicI32, - Ordering::{Acquire, Release}, - }; + use crate::sync::atomic::AtomicI32; + use crate::sync::atomic::Ordering::{Acquire, Release}; static LOCKED: AtomicI32 = AtomicI32::new(0); diff --git a/library/std/src/sys/pal/xous/net/dns.rs b/library/std/src/sys/pal/xous/net/dns.rs index 63056324bfbd9..50efe978c4a83 100644 --- a/library/std/src/sys/pal/xous/net/dns.rs +++ b/library/std/src/sys/pal/xous/net/dns.rs @@ -1,8 +1,9 @@ +use core::convert::{TryFrom, TryInto}; + use crate::io; use crate::net::{Ipv4Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; use crate::os::xous::ffi::lend_mut; use crate::os::xous::services::{dns_server, DnsLendMut}; -use core::convert::{TryFrom, TryInto}; pub struct DnsError { pub code: u8, diff --git a/library/std/src/sys/pal/xous/net/tcplistener.rs b/library/std/src/sys/pal/xous/net/tcplistener.rs index 47305013083c8..ddfb289162b69 100644 --- a/library/std/src/sys/pal/xous/net/tcplistener.rs +++ b/library/std/src/sys/pal/xous/net/tcplistener.rs @@ -1,11 +1,11 @@ +use core::convert::TryInto; +use core::sync::atomic::{AtomicBool, AtomicU16, AtomicUsize, Ordering}; + use super::*; -use crate::fmt; -use crate::io; use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use crate::os::xous::services; use crate::sync::Arc; -use core::convert::TryInto; -use core::sync::atomic::{AtomicBool, AtomicU16, AtomicUsize, Ordering}; +use crate::{fmt, io}; macro_rules! unimpl { () => { diff --git a/library/std/src/sys/pal/xous/net/tcpstream.rs b/library/std/src/sys/pal/xous/net/tcpstream.rs index 0ad8811071111..03442cf2fcdfd 100644 --- a/library/std/src/sys/pal/xous/net/tcpstream.rs +++ b/library/std/src/sys/pal/xous/net/tcpstream.rs @@ -1,3 +1,5 @@ +use core::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}; + use super::*; use crate::fmt; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; @@ -5,7 +7,6 @@ use crate::net::{IpAddr, Ipv4Addr, Shutdown, SocketAddr, SocketAddrV4, SocketAdd use crate::os::xous::services; use crate::sync::Arc; use crate::time::Duration; -use core::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}; macro_rules! unimpl { () => { diff --git a/library/std/src/sys/pal/xous/net/udp.rs b/library/std/src/sys/pal/xous/net/udp.rs index 3d0522b25f3fb..de5133280ba9d 100644 --- a/library/std/src/sys/pal/xous/net/udp.rs +++ b/library/std/src/sys/pal/xous/net/udp.rs @@ -1,13 +1,13 @@ +use core::convert::TryInto; +use core::sync::atomic::{AtomicUsize, Ordering}; + use super::*; use crate::cell::Cell; -use crate::fmt; -use crate::io; use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use crate::os::xous::services; use crate::sync::Arc; use crate::time::Duration; -use core::convert::TryInto; -use core::sync::atomic::{AtomicUsize, Ordering}; +use crate::{fmt, io}; macro_rules! unimpl { () => { diff --git a/library/std/src/sys/pal/xous/os.rs b/library/std/src/sys/pal/xous/os.rs index 9be09eed62989..8f8f35428c487 100644 --- a/library/std/src/sys/pal/xous/os.rs +++ b/library/std/src/sys/pal/xous/os.rs @@ -1,11 +1,10 @@ use super::unsupported; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::os::xous::ffi::Error as XousError; use crate::path::{self, PathBuf}; +use crate::{fmt, io}; #[cfg(not(test))] #[cfg(feature = "panic_unwind")] diff --git a/library/std/src/sys/pal/xous/thread.rs b/library/std/src/sys/pal/xous/thread.rs index 279f24f9ee8e4..a95b0aa14d255 100644 --- a/library/std/src/sys/pal/xous/thread.rs +++ b/library/std/src/sys/pal/xous/thread.rs @@ -1,3 +1,5 @@ +use core::arch::asm; + use crate::ffi::CStr; use crate::io; use crate::num::NonZero; @@ -7,7 +9,6 @@ use crate::os::xous::ffi::{ }; use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; use crate::time::Duration; -use core::arch::asm; pub struct Thread { tid: ThreadId, diff --git a/library/std/src/sys/pal/xous/time.rs b/library/std/src/sys/pal/xous/time.rs index 4e4ae67efffa2..ae8be81c0b7c5 100644 --- a/library/std/src/sys/pal/xous/time.rs +++ b/library/std/src/sys/pal/xous/time.rs @@ -1,7 +1,7 @@ use crate::os::xous::ffi::blocking_scalar; -use crate::os::xous::services::{ - systime_server, ticktimer_server, SystimeScalar::GetUtcTimeMs, TicktimerScalar::ElapsedMs, -}; +use crate::os::xous::services::SystimeScalar::GetUtcTimeMs; +use crate::os::xous::services::TicktimerScalar::ElapsedMs; +use crate::os::xous::services::{systime_server, ticktimer_server}; use crate::time::Duration; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] diff --git a/library/std/src/sys/pal/zkvm/os.rs b/library/std/src/sys/pal/zkvm/os.rs index e7d6cd52a258e..68d91a123acd4 100644 --- a/library/std/src/sys/pal/zkvm/os.rs +++ b/library/std/src/sys/pal/zkvm/os.rs @@ -1,12 +1,11 @@ use super::{abi, unsupported, WORD_SIZE}; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::path::{self, PathBuf}; use crate::sys::os_str; use crate::sys_common::FromInner; +use crate::{fmt, io}; pub fn errno() -> i32 { 0 diff --git a/library/std/src/sys/pal/zkvm/stdio.rs b/library/std/src/sys/pal/zkvm/stdio.rs index e771ed0de28db..dd218c8894ca5 100644 --- a/library/std/src/sys/pal/zkvm/stdio.rs +++ b/library/std/src/sys/pal/zkvm/stdio.rs @@ -1,4 +1,5 @@ -use super::{abi, abi::fileno}; +use super::abi; +use super::abi::fileno; use crate::io; pub struct Stdin; diff --git a/library/std/src/sys/path/unix.rs b/library/std/src/sys/path/unix.rs index 837f68d3eaff7..2a7c025c3c46a 100644 --- a/library/std/src/sys/path/unix.rs +++ b/library/std/src/sys/path/unix.rs @@ -1,7 +1,6 @@ -use crate::env; use crate::ffi::OsStr; -use crate::io; use crate::path::{Path, PathBuf, Prefix}; +use crate::{env, io}; #[inline] pub fn is_sep_byte(b: u8) -> bool { diff --git a/library/std/src/sys/path/windows.rs b/library/std/src/sys/path/windows.rs index cebc791023115..21841eb18cc0e 100644 --- a/library/std/src/sys/path/windows.rs +++ b/library/std/src/sys/path/windows.rs @@ -1,8 +1,7 @@ use crate::ffi::{OsStr, OsString}; -use crate::io; use crate::path::{Path, PathBuf, Prefix}; -use crate::ptr; use crate::sys::pal::{c, fill_utf16_buf, os2path, to_u16s}; +use crate::{io, ptr}; #[cfg(test)] mod tests; @@ -218,7 +217,7 @@ pub(crate) fn maybe_verbatim(path: &Path) -> io::Result> { get_long_path(path, true) } -/// Get a normalized absolute path that can bypass path length limits. +/// Gets a normalized absolute path that can bypass path length limits. /// /// Setting prefer_verbatim to true suggests a stronger preference for verbatim /// paths even when not strictly necessary. This allows the Windows API to avoid diff --git a/library/std/src/sys/personality/dwarf/eh.rs b/library/std/src/sys/personality/dwarf/eh.rs index ff88ef4e0e1d0..c37c3e442aea6 100644 --- a/library/std/src/sys/personality/dwarf/eh.rs +++ b/library/std/src/sys/personality/dwarf/eh.rs @@ -12,9 +12,9 @@ #![allow(non_upper_case_globals)] #![allow(unused)] +use core::{mem, ptr}; + use super::DwarfReader; -use core::mem; -use core::ptr; pub const DW_EH_PE_omit: u8 = 0xFF; pub const DW_EH_PE_absptr: u8 = 0x00; @@ -70,45 +70,51 @@ pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>) -> Result let func_start = context.func_start; let mut reader = DwarfReader::new(lsda); - - let start_encoding = reader.read::(); - // base address for landing pad offsets - let lpad_base = if start_encoding != DW_EH_PE_omit { - read_encoded_pointer(&mut reader, context, start_encoding)? - } else { - func_start + let lpad_base = unsafe { + let start_encoding = reader.read::(); + // base address for landing pad offsets + if start_encoding != DW_EH_PE_omit { + read_encoded_pointer(&mut reader, context, start_encoding)? + } else { + func_start + } }; + let call_site_encoding = unsafe { + let ttype_encoding = reader.read::(); + if ttype_encoding != DW_EH_PE_omit { + // Rust doesn't analyze exception types, so we don't care about the type table + reader.read_uleb128(); + } - let ttype_encoding = reader.read::(); - if ttype_encoding != DW_EH_PE_omit { - // Rust doesn't analyze exception types, so we don't care about the type table - reader.read_uleb128(); - } - - let call_site_encoding = reader.read::(); - let call_site_table_length = reader.read_uleb128(); - let action_table = reader.ptr.add(call_site_table_length as usize); + reader.read::() + }; + let action_table = unsafe { + let call_site_table_length = reader.read_uleb128(); + reader.ptr.add(call_site_table_length as usize) + }; let ip = context.ip; if !USING_SJLJ_EXCEPTIONS { // read the callsite table while reader.ptr < action_table { - // these are offsets rather than pointers; - let cs_start = read_encoded_offset(&mut reader, call_site_encoding)?; - let cs_len = read_encoded_offset(&mut reader, call_site_encoding)?; - let cs_lpad = read_encoded_offset(&mut reader, call_site_encoding)?; - let cs_action_entry = reader.read_uleb128(); - // Callsite table is sorted by cs_start, so if we've passed the ip, we - // may stop searching. - if ip < func_start.wrapping_add(cs_start) { - break; - } - if ip < func_start.wrapping_add(cs_start + cs_len) { - if cs_lpad == 0 { - return Ok(EHAction::None); - } else { - let lpad = lpad_base.wrapping_add(cs_lpad); - return Ok(interpret_cs_action(action_table, cs_action_entry, lpad)); + unsafe { + // these are offsets rather than pointers; + let cs_start = read_encoded_offset(&mut reader, call_site_encoding)?; + let cs_len = read_encoded_offset(&mut reader, call_site_encoding)?; + let cs_lpad = read_encoded_offset(&mut reader, call_site_encoding)?; + let cs_action_entry = reader.read_uleb128(); + // Callsite table is sorted by cs_start, so if we've passed the ip, we + // may stop searching. + if ip < func_start.wrapping_add(cs_start) { + break; + } + if ip < func_start.wrapping_add(cs_start + cs_len) { + if cs_lpad == 0 { + return Ok(EHAction::None); + } else { + let lpad = lpad_base.wrapping_add(cs_lpad); + return Ok(interpret_cs_action(action_table, cs_action_entry, lpad)); + } } } } @@ -125,15 +131,15 @@ pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>) -> Result } let mut idx = ip.addr(); loop { - let cs_lpad = reader.read_uleb128(); - let cs_action_entry = reader.read_uleb128(); + let cs_lpad = unsafe { reader.read_uleb128() }; + let cs_action_entry = unsafe { reader.read_uleb128() }; idx -= 1; if idx == 0 { // Can never have null landing pad for sjlj -- that would have // been indicated by a -1 call site index. // FIXME(strict provenance) let lpad = ptr::with_exposed_provenance((cs_lpad + 1) as usize); - return Ok(interpret_cs_action(action_table, cs_action_entry, lpad)); + return Ok(unsafe { interpret_cs_action(action_table, cs_action_entry, lpad) }); } } } @@ -151,9 +157,9 @@ unsafe fn interpret_cs_action( } else { // If lpad != 0 and cs_action_entry != 0, we have to check ttype_index. // If ttype_index == 0 under the condition, we take cleanup action. - let action_record = action_table.offset(cs_action_entry as isize - 1); + let action_record = unsafe { action_table.offset(cs_action_entry as isize - 1) }; let mut action_reader = DwarfReader::new(action_record); - let ttype_index = action_reader.read_sleb128(); + let ttype_index = unsafe { action_reader.read_sleb128() }; if ttype_index == 0 { EHAction::Cleanup(lpad) } else if ttype_index > 0 { @@ -170,7 +176,7 @@ fn round_up(unrounded: usize, align: usize) -> Result { if align.is_power_of_two() { Ok((unrounded + align - 1) & !(align - 1)) } else { Err(()) } } -/// Read a offset (`usize`) from `reader` whose encoding is described by `encoding`. +/// Reads an offset (`usize`) from `reader` whose encoding is described by `encoding`. /// /// `encoding` must be a [DWARF Exception Header Encoding as described by the LSB spec][LSB-dwarf-ext]. /// In addition the upper ("application") part must be zero. @@ -186,23 +192,25 @@ unsafe fn read_encoded_offset(reader: &mut DwarfReader, encoding: u8) -> Result< if encoding == DW_EH_PE_omit || encoding & 0xF0 != 0 { return Err(()); } - let result = match encoding & 0x0F { - // despite the name, LLVM also uses absptr for offsets instead of pointers - DW_EH_PE_absptr => reader.read::(), - DW_EH_PE_uleb128 => reader.read_uleb128() as usize, - DW_EH_PE_udata2 => reader.read::() as usize, - DW_EH_PE_udata4 => reader.read::() as usize, - DW_EH_PE_udata8 => reader.read::() as usize, - DW_EH_PE_sleb128 => reader.read_sleb128() as usize, - DW_EH_PE_sdata2 => reader.read::() as usize, - DW_EH_PE_sdata4 => reader.read::() as usize, - DW_EH_PE_sdata8 => reader.read::() as usize, - _ => return Err(()), + let result = unsafe { + match encoding & 0x0F { + // despite the name, LLVM also uses absptr for offsets instead of pointers + DW_EH_PE_absptr => reader.read::(), + DW_EH_PE_uleb128 => reader.read_uleb128() as usize, + DW_EH_PE_udata2 => reader.read::() as usize, + DW_EH_PE_udata4 => reader.read::() as usize, + DW_EH_PE_udata8 => reader.read::() as usize, + DW_EH_PE_sleb128 => reader.read_sleb128() as usize, + DW_EH_PE_sdata2 => reader.read::() as usize, + DW_EH_PE_sdata4 => reader.read::() as usize, + DW_EH_PE_sdata8 => reader.read::() as usize, + _ => return Err(()), + } }; Ok(result) } -/// Read a pointer from `reader` whose encoding is described by `encoding`. +/// Reads a pointer from `reader` whose encoding is described by `encoding`. /// /// `encoding` must be a [DWARF Exception Header Encoding as described by the LSB spec][LSB-dwarf-ext]. /// @@ -250,14 +258,14 @@ unsafe fn read_encoded_pointer( if encoding & 0x0F != DW_EH_PE_absptr { return Err(()); } - reader.read::<*const u8>() + unsafe { reader.read::<*const u8>() } } else { - let offset = read_encoded_offset(reader, encoding & 0x0F)?; + let offset = unsafe { read_encoded_offset(reader, encoding & 0x0F)? }; base_ptr.wrapping_add(offset) }; if encoding & DW_EH_PE_indirect != 0 { - ptr = *(ptr.cast::<*const u8>()); + ptr = unsafe { *(ptr.cast::<*const u8>()) }; } Ok(ptr) diff --git a/library/std/src/sys/personality/dwarf/mod.rs b/library/std/src/sys/personality/dwarf/mod.rs index 89f7f133e21b4..5c52d96c4cad4 100644 --- a/library/std/src/sys/personality/dwarf/mod.rs +++ b/library/std/src/sys/personality/dwarf/mod.rs @@ -5,6 +5,7 @@ // This module is used only by x86_64-pc-windows-gnu for now, but we // are compiling it everywhere to avoid regressions. #![allow(unused)] +#![forbid(unsafe_op_in_unsafe_fn)] #[cfg(test)] mod tests; @@ -17,7 +18,6 @@ pub struct DwarfReader { pub ptr: *const u8, } -#[forbid(unsafe_op_in_unsafe_fn)] impl DwarfReader { pub fn new(ptr: *const u8) -> DwarfReader { DwarfReader { ptr } diff --git a/library/std/src/sys/personality/emcc.rs b/library/std/src/sys/personality/emcc.rs index cb52ae89b1911..d374e3ad4c8f6 100644 --- a/library/std/src/sys/personality/emcc.rs +++ b/library/std/src/sys/personality/emcc.rs @@ -1,9 +1,10 @@ //! On Emscripten Rust panics are wrapped in C++ exceptions, so we just forward //! to `__gxx_personality_v0` which is provided by Emscripten. -use crate::ffi::c_int; use unwind as uw; +use crate::ffi::c_int; + // This is required by the compiler to exist (e.g., it's a lang item), but it's // never actually called by the compiler. Emscripten EH doesn't use a // personality function at all, it instead uses __cxa_find_matching_catch. diff --git a/library/std/src/sys/personality/gcc.rs b/library/std/src/sys/personality/gcc.rs index 0dc53550ca943..f6b1844e153fd 100644 --- a/library/std/src/sys/personality/gcc.rs +++ b/library/std/src/sys/personality/gcc.rs @@ -35,10 +35,12 @@ //! //! Once stack has been unwound down to the handler frame level, unwinding stops //! and the last personality routine transfers control to the catch block. +#![forbid(unsafe_op_in_unsafe_fn)] + +use unwind as uw; use super::dwarf::eh::{self, EHAction, EHContext}; use crate::ffi::c_int; -use unwind as uw; // Register ids were lifted from LLVM's TargetLowering::getExceptionPointerRegister() // and TargetLowering::getExceptionSelectorRegister() for each architecture, @@ -92,107 +94,116 @@ const UNWIND_DATA_REG: (i32, i32) = (4, 5); // a0, a1 // https://github.com/gcc-mirror/gcc/blob/trunk/libgcc/unwind-c.c cfg_if::cfg_if! { - if #[cfg(all(not(all(target_vendor = "apple", not(target_os = "watchos"))), target_arch = "arm", not(target_os = "netbsd")))] { - // ARM EHABI personality routine. - // https://web.archive.org/web/20190728160938/https://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf - // - // Apple 32-bit ARM (but not watchOS) uses the default routine instead - // since it uses SjLj unwinding. + if #[cfg(all( + target_arch = "arm", + not(all(target_vendor = "apple", not(target_os = "watchos"))), + not(target_os = "netbsd"), + ))] { + /// personality fn called by [ARM EHABI][armeabi-eh] + /// + /// Apple 32-bit ARM (but not watchOS) uses the default routine instead + /// since it uses "setjmp-longjmp" unwinding. + /// + /// [armeabi-eh]: https://web.archive.org/web/20190728160938/https://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf #[lang = "eh_personality"] unsafe extern "C" fn rust_eh_personality( state: uw::_Unwind_State, exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, ) -> uw::_Unwind_Reason_Code { - let state = state as c_int; - let action = state & uw::_US_ACTION_MASK as c_int; - let search_phase = if action == uw::_US_VIRTUAL_UNWIND_FRAME as c_int { - // Backtraces on ARM will call the personality routine with - // state == _US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND. In those cases - // we want to continue unwinding the stack, otherwise all our backtraces - // would end at __rust_try - if state & uw::_US_FORCE_UNWIND as c_int != 0 { + unsafe { + let state = state as c_int; + let action = state & uw::_US_ACTION_MASK as c_int; + let search_phase = if action == uw::_US_VIRTUAL_UNWIND_FRAME as c_int { + // Backtraces on ARM will call the personality routine with + // state == _US_VIRTUAL_UNWIND_FRAME | _US_FORCE_UNWIND. In those cases + // we want to continue unwinding the stack, otherwise all our backtraces + // would end at __rust_try + if state & uw::_US_FORCE_UNWIND as c_int != 0 { + return continue_unwind(exception_object, context); + } + true + } else if action == uw::_US_UNWIND_FRAME_STARTING as c_int { + false + } else if action == uw::_US_UNWIND_FRAME_RESUME as c_int { return continue_unwind(exception_object, context); - } - true - } else if action == uw::_US_UNWIND_FRAME_STARTING as c_int { - false - } else if action == uw::_US_UNWIND_FRAME_RESUME as c_int { - return continue_unwind(exception_object, context); - } else { - return uw::_URC_FAILURE; - }; + } else { + return uw::_URC_FAILURE; + }; - // The DWARF unwinder assumes that _Unwind_Context holds things like the function - // and LSDA pointers, however ARM EHABI places them into the exception object. - // To preserve signatures of functions like _Unwind_GetLanguageSpecificData(), which - // take only the context pointer, GCC personality routines stash a pointer to - // exception_object in the context, using location reserved for ARM's - // "scratch register" (r12). - uw::_Unwind_SetGR(context, uw::UNWIND_POINTER_REG, exception_object as uw::_Unwind_Ptr); - // ...A more principled approach would be to provide the full definition of ARM's - // _Unwind_Context in our libunwind bindings and fetch the required data from there - // directly, bypassing DWARF compatibility functions. + // The DWARF unwinder assumes that _Unwind_Context holds things like the function + // and LSDA pointers, however ARM EHABI places them into the exception object. + // To preserve signatures of functions like _Unwind_GetLanguageSpecificData(), which + // take only the context pointer, GCC personality routines stash a pointer to + // exception_object in the context, using location reserved for ARM's + // "scratch register" (r12). + uw::_Unwind_SetGR(context, uw::UNWIND_POINTER_REG, exception_object as uw::_Unwind_Ptr); + // ...A more principled approach would be to provide the full definition of ARM's + // _Unwind_Context in our libunwind bindings and fetch the required data from there + // directly, bypassing DWARF compatibility functions. - let eh_action = match find_eh_action(context) { - Ok(action) => action, - Err(_) => return uw::_URC_FAILURE, - }; - if search_phase { - match eh_action { - EHAction::None | EHAction::Cleanup(_) => { - return continue_unwind(exception_object, context); - } - EHAction::Catch(_) | EHAction::Filter(_) => { - // EHABI requires the personality routine to update the - // SP value in the barrier cache of the exception object. - (*exception_object).private[5] = - uw::_Unwind_GetGR(context, uw::UNWIND_SP_REG); - return uw::_URC_HANDLER_FOUND; + let eh_action = match find_eh_action(context) { + Ok(action) => action, + Err(_) => return uw::_URC_FAILURE, + }; + if search_phase { + match eh_action { + EHAction::None | EHAction::Cleanup(_) => { + return continue_unwind(exception_object, context); + } + EHAction::Catch(_) | EHAction::Filter(_) => { + // EHABI requires the personality routine to update the + // SP value in the barrier cache of the exception object. + (*exception_object).private[5] = + uw::_Unwind_GetGR(context, uw::UNWIND_SP_REG); + return uw::_URC_HANDLER_FOUND; + } + EHAction::Terminate => return uw::_URC_FAILURE, } - EHAction::Terminate => return uw::_URC_FAILURE, - } - } else { - match eh_action { - EHAction::None => return continue_unwind(exception_object, context), - EHAction::Filter(_) if state & uw::_US_FORCE_UNWIND as c_int != 0 => return continue_unwind(exception_object, context), - EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { - uw::_Unwind_SetGR( - context, - UNWIND_DATA_REG.0, - exception_object as uw::_Unwind_Ptr, - ); - uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); - uw::_Unwind_SetIP(context, lpad); - return uw::_URC_INSTALL_CONTEXT; + } else { + match eh_action { + EHAction::None => return continue_unwind(exception_object, context), + EHAction::Filter(_) if state & uw::_US_FORCE_UNWIND as c_int != 0 => return continue_unwind(exception_object, context), + EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { + uw::_Unwind_SetGR( + context, + UNWIND_DATA_REG.0, + exception_object as uw::_Unwind_Ptr, + ); + uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); + uw::_Unwind_SetIP(context, lpad); + return uw::_URC_INSTALL_CONTEXT; + } + EHAction::Terminate => return uw::_URC_FAILURE, } - EHAction::Terminate => return uw::_URC_FAILURE, } - } - // On ARM EHABI the personality routine is responsible for actually - // unwinding a single stack frame before returning (ARM EHABI Sec. 6.1). - unsafe fn continue_unwind( - exception_object: *mut uw::_Unwind_Exception, - context: *mut uw::_Unwind_Context, - ) -> uw::_Unwind_Reason_Code { - if __gnu_unwind_frame(exception_object, context) == uw::_URC_NO_REASON { - uw::_URC_CONTINUE_UNWIND - } else { - uw::_URC_FAILURE - } - } - // defined in libgcc - extern "C" { - fn __gnu_unwind_frame( + // On ARM EHABI the personality routine is responsible for actually + // unwinding a single stack frame before returning (ARM EHABI Sec. 6.1). + unsafe fn continue_unwind( exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, - ) -> uw::_Unwind_Reason_Code; + ) -> uw::_Unwind_Reason_Code { + unsafe { + if __gnu_unwind_frame(exception_object, context) == uw::_URC_NO_REASON { + uw::_URC_CONTINUE_UNWIND + } else { + uw::_URC_FAILURE + } + } + } + // defined in libgcc + extern "C" { + fn __gnu_unwind_frame( + exception_object: *mut uw::_Unwind_Exception, + context: *mut uw::_Unwind_Context, + ) -> uw::_Unwind_Reason_Code; + } } } } else { - // Default personality routine, which is used directly on most targets - // and indirectly on Windows x86_64 via SEH. + /// Default personality routine, which is used directly on most targets + /// and indirectly on Windows x86_64 and AArch64 via SEH. unsafe extern "C" fn rust_eh_personality_impl( version: c_int, actions: uw::_Unwind_Action, @@ -200,43 +211,49 @@ cfg_if::cfg_if! { exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, ) -> uw::_Unwind_Reason_Code { - if version != 1 { - return uw::_URC_FATAL_PHASE1_ERROR; - } - let eh_action = match find_eh_action(context) { - Ok(action) => action, - Err(_) => return uw::_URC_FATAL_PHASE1_ERROR, - }; - if actions as i32 & uw::_UA_SEARCH_PHASE as i32 != 0 { - match eh_action { - EHAction::None | EHAction::Cleanup(_) => uw::_URC_CONTINUE_UNWIND, - EHAction::Catch(_) | EHAction::Filter(_) => uw::_URC_HANDLER_FOUND, - EHAction::Terminate => uw::_URC_FATAL_PHASE1_ERROR, + unsafe { + if version != 1 { + return uw::_URC_FATAL_PHASE1_ERROR; } - } else { - match eh_action { - EHAction::None => uw::_URC_CONTINUE_UNWIND, - // Forced unwinding hits a terminate action. - EHAction::Filter(_) if actions as i32 & uw::_UA_FORCE_UNWIND as i32 != 0 => uw::_URC_CONTINUE_UNWIND, - EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { - uw::_Unwind_SetGR( - context, - UNWIND_DATA_REG.0, - exception_object.cast(), - ); - uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); - uw::_Unwind_SetIP(context, lpad); - uw::_URC_INSTALL_CONTEXT + let eh_action = match find_eh_action(context) { + Ok(action) => action, + Err(_) => return uw::_URC_FATAL_PHASE1_ERROR, + }; + if actions as i32 & uw::_UA_SEARCH_PHASE as i32 != 0 { + match eh_action { + EHAction::None | EHAction::Cleanup(_) => uw::_URC_CONTINUE_UNWIND, + EHAction::Catch(_) | EHAction::Filter(_) => uw::_URC_HANDLER_FOUND, + EHAction::Terminate => uw::_URC_FATAL_PHASE1_ERROR, + } + } else { + match eh_action { + EHAction::None => uw::_URC_CONTINUE_UNWIND, + // Forced unwinding hits a terminate action. + EHAction::Filter(_) if actions as i32 & uw::_UA_FORCE_UNWIND as i32 != 0 => uw::_URC_CONTINUE_UNWIND, + EHAction::Cleanup(lpad) | EHAction::Catch(lpad) | EHAction::Filter(lpad) => { + uw::_Unwind_SetGR( + context, + UNWIND_DATA_REG.0, + exception_object.cast(), + ); + uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, core::ptr::null()); + uw::_Unwind_SetIP(context, lpad); + uw::_URC_INSTALL_CONTEXT + } + EHAction::Terminate => uw::_URC_FATAL_PHASE2_ERROR, } - EHAction::Terminate => uw::_URC_FATAL_PHASE2_ERROR, } } } cfg_if::cfg_if! { if #[cfg(all(windows, any(target_arch = "aarch64", target_arch = "x86_64"), target_env = "gnu"))] { - // On x86_64 MinGW targets, the unwinding mechanism is SEH however the unwind - // handler data (aka LSDA) uses GCC-compatible encoding. + /// personality fn called by [Windows Structured Exception Handling][windows-eh] + /// + /// On x86_64 and AArch64 MinGW targets, the unwinding mechanism is SEH, + /// however the unwind handler data (aka LSDA) uses GCC-compatible encoding + /// + /// [windows-eh]: https://learn.microsoft.com/en-us/cpp/cpp/structured-exception-handling-c-cpp?view=msvc-170 #[lang = "eh_personality"] #[allow(nonstandard_style)] unsafe extern "C" fn rust_eh_personality( @@ -245,16 +262,33 @@ cfg_if::cfg_if! { contextRecord: *mut uw::CONTEXT, dispatcherContext: *mut uw::DISPATCHER_CONTEXT, ) -> uw::EXCEPTION_DISPOSITION { - uw::_GCC_specific_handler( - exceptionRecord, - establisherFrame, - contextRecord, - dispatcherContext, - rust_eh_personality_impl, - ) + // SAFETY: the cfg is still target_os = "windows" and target_env = "gnu", + // which means that this is the correct function to call, passing our impl fn + // as the callback which gets actually used + unsafe { + uw::_GCC_specific_handler( + exceptionRecord, + establisherFrame, + contextRecord, + dispatcherContext, + rust_eh_personality_impl, + ) + } } } else { - // The personality routine for most of our targets. + /// personality fn called by [Itanium C++ ABI Exception Handling][itanium-eh] + /// + /// The personality routine for most non-Windows targets. This will be called by + /// the unwinding library: + /// - "In the search phase, the framework repeatedly calls the personality routine, + /// with the _UA_SEARCH_PHASE flag as described below, first for the current PC + /// and register state, and then unwinding a frame to a new PC at each step..." + /// - "If the search phase reports success, the framework restarts in the cleanup + /// phase. Again, it repeatedly calls the personality routine, with the + /// _UA_CLEANUP_PHASE flag as described below, first for the current PC and + /// register state, and then unwinding a frame to a new PC at each step..."i + /// + /// [itanium-eh]: https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html #[lang = "eh_personality"] unsafe extern "C" fn rust_eh_personality( version: c_int, @@ -263,13 +297,17 @@ cfg_if::cfg_if! { exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, ) -> uw::_Unwind_Reason_Code { - rust_eh_personality_impl( - version, - actions, - exception_class, - exception_object, - context, - ) + // SAFETY: the platform support must modify the cfg for the inner fn + // if it needs something different than what is currently invoked. + unsafe { + rust_eh_personality_impl( + version, + actions, + exception_class, + exception_object, + context, + ) + } } } } @@ -277,18 +315,20 @@ cfg_if::cfg_if! { } unsafe fn find_eh_action(context: *mut uw::_Unwind_Context) -> Result { - let lsda = uw::_Unwind_GetLanguageSpecificData(context) as *const u8; - let mut ip_before_instr: c_int = 0; - let ip = uw::_Unwind_GetIPInfo(context, &mut ip_before_instr); - let eh_context = EHContext { - // The return address points 1 byte past the call instruction, - // which could be in the next IP range in LSDA range table. - // - // `ip = -1` has special meaning, so use wrapping sub to allow for that - ip: if ip_before_instr != 0 { ip } else { ip.wrapping_sub(1) }, - func_start: uw::_Unwind_GetRegionStart(context), - get_text_start: &|| uw::_Unwind_GetTextRelBase(context), - get_data_start: &|| uw::_Unwind_GetDataRelBase(context), - }; - eh::find_eh_action(lsda, &eh_context) + unsafe { + let lsda = uw::_Unwind_GetLanguageSpecificData(context) as *const u8; + let mut ip_before_instr: c_int = 0; + let ip = uw::_Unwind_GetIPInfo(context, &mut ip_before_instr); + let eh_context = EHContext { + // The return address points 1 byte past the call instruction, + // which could be in the next IP range in LSDA range table. + // + // `ip = -1` has special meaning, so use wrapping sub to allow for that + ip: if ip_before_instr != 0 { ip } else { ip.wrapping_sub(1) }, + func_start: uw::_Unwind_GetRegionStart(context), + get_text_start: &|| uw::_Unwind_GetTextRelBase(context), + get_data_start: &|| uw::_Unwind_GetDataRelBase(context), + }; + eh::find_eh_action(lsda, &eh_context) + } } diff --git a/library/std/src/sys/sync/condvar/futex.rs b/library/std/src/sys/sync/condvar/futex.rs index 4586d0fd941a7..39cd97c01ea32 100644 --- a/library/std/src/sys/sync/condvar/futex.rs +++ b/library/std/src/sys/sync/condvar/futex.rs @@ -1,4 +1,5 @@ -use crate::sync::atomic::{AtomicU32, Ordering::Relaxed}; +use crate::sync::atomic::AtomicU32; +use crate::sync::atomic::Ordering::Relaxed; use crate::sys::futex::{futex_wait, futex_wake, futex_wake_all}; use crate::sys::sync::Mutex; use crate::time::Duration; diff --git a/library/std/src/sys/sync/condvar/itron.rs b/library/std/src/sys/sync/condvar/itron.rs index 3a3039889e98b..f6f2b698e4945 100644 --- a/library/std/src/sys/sync/condvar/itron.rs +++ b/library/std/src/sys/sync/condvar/itron.rs @@ -1,9 +1,13 @@ //! POSIX conditional variable implementation based on user-space wait queues. -use crate::sys::pal::itron::{ - abi, error::expect_success_aborting, spin::SpinMutex, task, time::with_tmos_strong, -}; -use crate::{mem::replace, ptr::NonNull, sys::sync::Mutex, time::Duration}; +use crate::mem::replace; +use crate::ptr::NonNull; +use crate::sys::pal::itron::error::expect_success_aborting; +use crate::sys::pal::itron::spin::SpinMutex; +use crate::sys::pal::itron::time::with_tmos_strong; +use crate::sys::pal::itron::{abi, task}; +use crate::sys::sync::Mutex; +use crate::time::Duration; // The implementation is inspired by the queue-based implementation shown in // Andrew D. Birrell's paper "Implementing Condition Variables with Semaphores" diff --git a/library/std/src/sys/sync/condvar/pthread.rs b/library/std/src/sys/sync/condvar/pthread.rs index a2a96410d932c..2b4bdfe415c80 100644 --- a/library/std/src/sys/sync/condvar/pthread.rs +++ b/library/std/src/sys/sync/condvar/pthread.rs @@ -1,6 +1,7 @@ use crate::cell::UnsafeCell; use crate::ptr; -use crate::sync::atomic::{AtomicPtr, Ordering::Relaxed}; +use crate::sync::atomic::AtomicPtr; +use crate::sync::atomic::Ordering::Relaxed; use crate::sys::sync::{mutex, Mutex}; #[cfg(not(target_os = "nto"))] use crate::sys::time::TIMESPEC_MAX; diff --git a/library/std/src/sys/sync/condvar/teeos.rs b/library/std/src/sys/sync/condvar/teeos.rs index 6457da91c2a5d..943867cd76169 100644 --- a/library/std/src/sys/sync/condvar/teeos.rs +++ b/library/std/src/sys/sync/condvar/teeos.rs @@ -1,6 +1,7 @@ use crate::cell::UnsafeCell; use crate::ptr; -use crate::sync::atomic::{AtomicPtr, Ordering::Relaxed}; +use crate::sync::atomic::AtomicPtr; +use crate::sync::atomic::Ordering::Relaxed; use crate::sys::sync::mutex::{self, Mutex}; use crate::sys::time::TIMESPEC_MAX; use crate::sys_common::lazy_box::{LazyBox, LazyInit}; diff --git a/library/std/src/sys/sync/condvar/windows7.rs b/library/std/src/sys/sync/condvar/windows7.rs index 07fa5fdd698ee..56eeeda551ebb 100644 --- a/library/std/src/sys/sync/condvar/windows7.rs +++ b/library/std/src/sys/sync/condvar/windows7.rs @@ -1,7 +1,6 @@ use crate::cell::UnsafeCell; -use crate::sys::c; -use crate::sys::os; use crate::sys::sync::{mutex, Mutex}; +use crate::sys::{c, os}; use crate::time::Duration; pub struct Condvar { diff --git a/library/std/src/sys/sync/condvar/xous.rs b/library/std/src/sys/sync/condvar/xous.rs index 7b218818ef8ef..007383479a100 100644 --- a/library/std/src/sys/sync/condvar/xous.rs +++ b/library/std/src/sys/sync/condvar/xous.rs @@ -1,8 +1,9 @@ +use core::sync::atomic::{AtomicUsize, Ordering}; + use crate::os::xous::ffi::{blocking_scalar, scalar}; use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; use crate::sys::sync::Mutex; use crate::time::Duration; -use core::sync::atomic::{AtomicUsize, Ordering}; // The implementation is inspired by Andrew D. Birrell's paper // "Implementing Condition Variables with Semaphores" diff --git a/library/std/src/sys/sync/mutex/fuchsia.rs b/library/std/src/sys/sync/mutex/fuchsia.rs index 5d89e5a13fd36..81a6361a83a49 100644 --- a/library/std/src/sys/sync/mutex/fuchsia.rs +++ b/library/std/src/sys/sync/mutex/fuchsia.rs @@ -37,10 +37,8 @@ //! //! [mutex in Fuchsia's libsync]: https://cs.opensource.google/fuchsia/fuchsia/+/main:zircon/system/ulib/sync/mutex.c -use crate::sync::atomic::{ - AtomicU32, - Ordering::{Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::AtomicU32; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use crate::sys::futex::zircon::{ zx_futex_wait, zx_futex_wake_single_owner, zx_handle_t, zx_thread_self, ZX_ERR_BAD_HANDLE, ZX_ERR_BAD_STATE, ZX_ERR_INVALID_ARGS, ZX_ERR_TIMED_OUT, ZX_ERR_WRONG_TYPE, ZX_OK, diff --git a/library/std/src/sys/sync/mutex/itron.rs b/library/std/src/sys/sync/mutex/itron.rs index b29c7e1d03444..8440ffdd33772 100644 --- a/library/std/src/sys/sync/mutex/itron.rs +++ b/library/std/src/sys/sync/mutex/itron.rs @@ -2,18 +2,16 @@ //! `TA_INHERIT` are available. #![forbid(unsafe_op_in_unsafe_fn)] -use crate::sys::pal::itron::{ - abi, - error::{expect_success, expect_success_aborting, fail, ItronError}, - spin::SpinIdOnceCell, -}; +use crate::sys::pal::itron::abi; +use crate::sys::pal::itron::error::{expect_success, expect_success_aborting, fail, ItronError}; +use crate::sys::pal::itron::spin::SpinIdOnceCell; pub struct Mutex { /// The ID of the underlying mutex object mtx: SpinIdOnceCell<()>, } -/// Create a mutex object. This function never panics. +/// Creates a mutex object. This function never panics. fn new_mtx() -> Result { ItronError::err_if_negative(unsafe { abi::acre_mtx(&abi::T_CMTX { @@ -31,7 +29,7 @@ impl Mutex { Mutex { mtx: SpinIdOnceCell::new() } } - /// Get the inner mutex's ID, which is lazily created. + /// Gets the inner mutex's ID, which is lazily created. fn raw(&self) -> abi::ID { match self.mtx.get_or_try_init(|| new_mtx().map(|id| (id, ()))) { Ok((id, ())) => id, diff --git a/library/std/src/sys/sync/mutex/xous.rs b/library/std/src/sys/sync/mutex/xous.rs index 1426e48f8b7af..63efa5a0210ab 100644 --- a/library/std/src/sys/sync/mutex/xous.rs +++ b/library/std/src/sys/sync/mutex/xous.rs @@ -1,9 +1,7 @@ use crate::os::xous::ffi::{blocking_scalar, do_yield}; use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; -use crate::sync::atomic::{ - AtomicBool, AtomicUsize, - Ordering::{Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use crate::sync::atomic::{AtomicBool, AtomicUsize}; pub struct Mutex { /// The "locked" value indicates how many threads are waiting on this diff --git a/library/std/src/sys/sync/once/futex.rs b/library/std/src/sys/sync/once/futex.rs index 8a231e65ad134..2c8a054282b01 100644 --- a/library/std/src/sys/sync/once/futex.rs +++ b/library/std/src/sys/sync/once/futex.rs @@ -1,14 +1,12 @@ use crate::cell::Cell; use crate::sync as public; -use crate::sync::atomic::{ - AtomicU32, - Ordering::{Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::AtomicU32; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use crate::sync::once::ExclusiveState; use crate::sys::futex::{futex_wait, futex_wake_all}; // On some platforms, the OS is very nice and handles the waiter queue for us. -// This means we only need one atomic value with 5 states: +// This means we only need one atomic value with 4 states: /// No initialization has run yet, and no thread is currently using the Once. const INCOMPLETE: u32 = 0; @@ -19,16 +17,20 @@ const POISONED: u32 = 1; /// Some thread is currently attempting to run initialization. It may succeed, /// so all future threads need to wait for it to finish. const RUNNING: u32 = 2; -/// Some thread is currently attempting to run initialization and there are threads -/// waiting for it to finish. -const QUEUED: u32 = 3; /// Initialization has completed and all future calls should finish immediately. -const COMPLETE: u32 = 4; +const COMPLETE: u32 = 3; -// Threads wait by setting the state to QUEUED and calling `futex_wait` on the state +// An additional bit indicates whether there are waiting threads: + +/// May only be set if the state is not COMPLETE. +const QUEUED: u32 = 4; + +// Threads wait by setting the QUEUED bit and calling `futex_wait` on the state // variable. When the running thread finishes, it will wake all waiting threads using // `futex_wake_all`. +const STATE_MASK: u32 = 0b11; + pub struct OnceState { poisoned: bool, set_state_to: Cell, @@ -47,7 +49,7 @@ impl OnceState { } struct CompletionGuard<'a> { - state: &'a AtomicU32, + state_and_queued: &'a AtomicU32, set_state_on_drop_to: u32, } @@ -56,32 +58,32 @@ impl<'a> Drop for CompletionGuard<'a> { // Use release ordering to propagate changes to all threads checking // up on the Once. `futex_wake_all` does its own synchronization, hence // we do not need `AcqRel`. - if self.state.swap(self.set_state_on_drop_to, Release) == QUEUED { - futex_wake_all(self.state); + if self.state_and_queued.swap(self.set_state_on_drop_to, Release) & QUEUED != 0 { + futex_wake_all(self.state_and_queued); } } } pub struct Once { - state: AtomicU32, + state_and_queued: AtomicU32, } impl Once { #[inline] pub const fn new() -> Once { - Once { state: AtomicU32::new(INCOMPLETE) } + Once { state_and_queued: AtomicU32::new(INCOMPLETE) } } #[inline] pub fn is_completed(&self) -> bool { // Use acquire ordering to make all initialization changes visible to the // current thread. - self.state.load(Acquire) == COMPLETE + self.state_and_queued.load(Acquire) == COMPLETE } #[inline] pub(crate) fn state(&mut self) -> ExclusiveState { - match *self.state.get_mut() { + match *self.state_and_queued.get_mut() { INCOMPLETE => ExclusiveState::Incomplete, POISONED => ExclusiveState::Poisoned, COMPLETE => ExclusiveState::Complete, @@ -89,31 +91,73 @@ impl Once { } } - // This uses FnMut to match the API of the generic implementation. As this - // implementation is quite light-weight, it is generic over the closure and - // so avoids the cost of dynamic dispatch. #[cold] #[track_caller] - pub fn call(&self, ignore_poisoning: bool, f: &mut impl FnMut(&public::OnceState)) { - let mut state = self.state.load(Acquire); + pub fn wait(&self, ignore_poisoning: bool) { + let mut state_and_queued = self.state_and_queued.load(Acquire); loop { + let state = state_and_queued & STATE_MASK; + let queued = state_and_queued & QUEUED != 0; match state { + COMPLETE => return, + POISONED if !ignore_poisoning => { + // Panic to propagate the poison. + panic!("Once instance has previously been poisoned"); + } + _ => { + // Set the QUEUED bit if it has not already been set. + if !queued { + state_and_queued += QUEUED; + if let Err(new) = self.state_and_queued.compare_exchange_weak( + state, + state_and_queued, + Relaxed, + Acquire, + ) { + state_and_queued = new; + continue; + } + } + + futex_wait(&self.state_and_queued, state_and_queued, None); + state_and_queued = self.state_and_queued.load(Acquire); + } + } + } + } + + #[cold] + #[track_caller] + pub fn call(&self, ignore_poisoning: bool, f: &mut dyn FnMut(&public::OnceState)) { + let mut state_and_queued = self.state_and_queued.load(Acquire); + loop { + let state = state_and_queued & STATE_MASK; + let queued = state_and_queued & QUEUED != 0; + match state { + COMPLETE => return, POISONED if !ignore_poisoning => { // Panic to propagate the poison. panic!("Once instance has previously been poisoned"); } INCOMPLETE | POISONED => { // Try to register the current thread as the one running. - if let Err(new) = - self.state.compare_exchange_weak(state, RUNNING, Acquire, Acquire) - { - state = new; + let next = RUNNING + if queued { QUEUED } else { 0 }; + if let Err(new) = self.state_and_queued.compare_exchange_weak( + state_and_queued, + next, + Acquire, + Acquire, + ) { + state_and_queued = new; continue; } + // `waiter_queue` will manage other waiting threads, and // wake them up on drop. - let mut waiter_queue = - CompletionGuard { state: &self.state, set_state_on_drop_to: POISONED }; + let mut waiter_queue = CompletionGuard { + state_and_queued: &self.state_and_queued, + set_state_on_drop_to: POISONED, + }; // Run the function, letting it know if we're poisoned or not. let f_state = public::OnceState { inner: OnceState { @@ -125,21 +169,27 @@ impl Once { waiter_queue.set_state_on_drop_to = f_state.inner.set_state_to.get(); return; } - RUNNING | QUEUED => { - // Set the state to QUEUED if it is not already. - if state == RUNNING - && let Err(new) = - self.state.compare_exchange_weak(RUNNING, QUEUED, Relaxed, Acquire) - { - state = new; - continue; + _ => { + // All other values must be RUNNING. + assert!(state == RUNNING); + + // Set the QUEUED bit if it is not already set. + if !queued { + state_and_queued += QUEUED; + if let Err(new) = self.state_and_queued.compare_exchange_weak( + state, + state_and_queued, + Relaxed, + Acquire, + ) { + state_and_queued = new; + continue; + } } - futex_wait(&self.state, QUEUED, None); - state = self.state.load(Acquire); + futex_wait(&self.state_and_queued, state_and_queued, None); + state_and_queued = self.state_and_queued.load(Acquire); } - COMPLETE => return, - _ => unreachable!("state is never set to invalid values"), } } } diff --git a/library/std/src/sys/sync/once/no_threads.rs b/library/std/src/sys/sync/once/no_threads.rs index 11fde1888ba7c..12c1d9f5a6c98 100644 --- a/library/std/src/sys/sync/once/no_threads.rs +++ b/library/std/src/sys/sync/once/no_threads.rs @@ -55,6 +55,12 @@ impl Once { } } + #[cold] + #[track_caller] + pub fn wait(&self, _ignore_poisoning: bool) { + panic!("not implementable on this target"); + } + #[cold] #[track_caller] pub fn call(&self, ignore_poisoning: bool, f: &mut impl FnMut(&public::OnceState)) { diff --git a/library/std/src/sys/sync/once/queue.rs b/library/std/src/sys/sync/once/queue.rs index 730cdb768bd27..86f72c82008bc 100644 --- a/library/std/src/sys/sync/once/queue.rs +++ b/library/std/src/sys/sync/once/queue.rs @@ -56,22 +56,21 @@ // allowed, so no need for `SeqCst`. use crate::cell::Cell; -use crate::fmt; -use crate::ptr; -use crate::sync as public; -use crate::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; +use crate::sync::atomic::Ordering::{AcqRel, Acquire, Release}; +use crate::sync::atomic::{AtomicBool, AtomicPtr}; use crate::sync::once::ExclusiveState; use crate::thread::{self, Thread}; +use crate::{fmt, ptr, sync as public}; -type Masked = (); +type StateAndQueue = *mut (); pub struct Once { - state_and_queue: AtomicPtr, + state_and_queue: AtomicPtr<()>, } pub struct OnceState { poisoned: bool, - set_state_on_drop_to: Cell<*mut Masked>, + set_state_on_drop_to: Cell, } // Four states that a Once can be in, encoded into the lower bits of @@ -83,7 +82,8 @@ const COMPLETE: usize = 0x3; // Mask to learn about the state. All other bits are the queue of waiters if // this is in the RUNNING state. -const STATE_MASK: usize = 0x3; +const STATE_MASK: usize = 0b11; +const QUEUE_MASK: usize = !STATE_MASK; // Representation of a node in the linked list of waiters, used while in the // RUNNING state. @@ -95,15 +95,23 @@ const STATE_MASK: usize = 0x3; struct Waiter { thread: Cell>, signaled: AtomicBool, - next: *const Waiter, + next: Cell<*const Waiter>, } // Head of a linked list of waiters. // Every node is a struct on the stack of a waiting thread. // Will wake up the waiters when it gets dropped, i.e. also on panic. struct WaiterQueue<'a> { - state_and_queue: &'a AtomicPtr, - set_state_on_drop_to: *mut Masked, + state_and_queue: &'a AtomicPtr<()>, + set_state_on_drop_to: StateAndQueue, +} + +fn to_queue(current: StateAndQueue) -> *const Waiter { + current.mask(QUEUE_MASK).cast() +} + +fn to_state(current: StateAndQueue) -> usize { + current.addr() & STATE_MASK } impl Once { @@ -119,7 +127,7 @@ impl Once { // operations visible to us, and, this being a fast path, weaker // ordering helps with performance. This `Acquire` synchronizes with // `Release` operations on the slow path. - self.state_and_queue.load(Ordering::Acquire).addr() == COMPLETE + self.state_and_queue.load(Acquire).addr() == COMPLETE } #[inline] @@ -132,6 +140,25 @@ impl Once { } } + #[cold] + #[track_caller] + pub fn wait(&self, ignore_poisoning: bool) { + let mut current = self.state_and_queue.load(Acquire); + loop { + let state = to_state(current); + match state { + COMPLETE => return, + POISONED if !ignore_poisoning => { + // Panic to propagate the poison. + panic!("Once instance has previously been poisoned"); + } + _ => { + current = wait(&self.state_and_queue, current, !ignore_poisoning); + } + } + } + } + // This is a non-generic function to reduce the monomorphization cost of // using `call_once` (this isn't exactly a trivial or small implementation). // @@ -146,9 +173,10 @@ impl Once { #[cold] #[track_caller] pub fn call(&self, ignore_poisoning: bool, init: &mut dyn FnMut(&public::OnceState)) { - let mut state_and_queue = self.state_and_queue.load(Ordering::Acquire); + let mut current = self.state_and_queue.load(Acquire); loop { - match state_and_queue.addr() { + let state = to_state(current); + match state { COMPLETE => break, POISONED if !ignore_poisoning => { // Panic to propagate the poison. @@ -156,16 +184,16 @@ impl Once { } POISONED | INCOMPLETE => { // Try to register this thread as the one RUNNING. - let exchange_result = self.state_and_queue.compare_exchange( - state_and_queue, - ptr::without_provenance_mut(RUNNING), - Ordering::Acquire, - Ordering::Acquire, - ); - if let Err(old) = exchange_result { - state_and_queue = old; + if let Err(new) = self.state_and_queue.compare_exchange_weak( + current, + current.mask(QUEUE_MASK).wrapping_byte_add(RUNNING), + Acquire, + Acquire, + ) { + current = new; continue; } + // `waiter_queue` will manage other waiting threads, and // wake them up on drop. let mut waiter_queue = WaiterQueue { @@ -176,54 +204,57 @@ impl Once { // poisoned or not. let init_state = public::OnceState { inner: OnceState { - poisoned: state_and_queue.addr() == POISONED, + poisoned: state == POISONED, set_state_on_drop_to: Cell::new(ptr::without_provenance_mut(COMPLETE)), }, }; init(&init_state); waiter_queue.set_state_on_drop_to = init_state.inner.set_state_on_drop_to.get(); - break; + return; } _ => { // All other values must be RUNNING with possibly a // pointer to the waiter queue in the more significant bits. - assert!(state_and_queue.addr() & STATE_MASK == RUNNING); - wait(&self.state_and_queue, state_and_queue); - state_and_queue = self.state_and_queue.load(Ordering::Acquire); + assert!(state == RUNNING); + current = wait(&self.state_and_queue, current, true); } } } } } -fn wait(state_and_queue: &AtomicPtr, mut current_state: *mut Masked) { - // Note: the following code was carefully written to avoid creating a - // mutable reference to `node` that gets aliased. +fn wait( + state_and_queue: &AtomicPtr<()>, + mut current: StateAndQueue, + return_on_poisoned: bool, +) -> StateAndQueue { + let node = &Waiter { + thread: Cell::new(Some(thread::current())), + signaled: AtomicBool::new(false), + next: Cell::new(ptr::null()), + }; + loop { - // Don't queue this thread if the status is no longer running, - // otherwise we will not be woken up. - if current_state.addr() & STATE_MASK != RUNNING { - return; + let state = to_state(current); + let queue = to_queue(current); + + // If initialization has finished, return. + if state == COMPLETE || (return_on_poisoned && state == POISONED) { + return current; } - // Create the node for our current thread. - let node = Waiter { - thread: Cell::new(Some(thread::current())), - signaled: AtomicBool::new(false), - next: current_state.with_addr(current_state.addr() & !STATE_MASK) as *const Waiter, - }; - let me = core::ptr::addr_of!(node) as *const Masked as *mut Masked; + // Update the node for our current thread. + node.next.set(queue); // Try to slide in the node at the head of the linked list, making sure // that another thread didn't just replace the head of the linked list. - let exchange_result = state_and_queue.compare_exchange( - current_state, - me.with_addr(me.addr() | RUNNING), - Ordering::Release, - Ordering::Relaxed, - ); - if let Err(old) = exchange_result { - current_state = old; + if let Err(new) = state_and_queue.compare_exchange_weak( + current, + ptr::from_ref(node).wrapping_byte_add(state) as StateAndQueue, + Release, + Acquire, + ) { + current = new; continue; } @@ -232,14 +263,15 @@ fn wait(state_and_queue: &AtomicPtr, mut current_state: *mut Masked) { // would drop our `Waiter` node and leave a hole in the linked list // (and a dangling reference). Guard against spurious wakeups by // reparking ourselves until we are signaled. - while !node.signaled.load(Ordering::Acquire) { + while !node.signaled.load(Acquire) { // If the managing thread happens to signal and unpark us before we // can park ourselves, the result could be this thread never gets // unparked. Luckily `park` comes with the guarantee that if it got // an `unpark` just before on an unparked thread it does not park. thread::park(); } - break; + + return state_and_queue.load(Acquire); } } @@ -253,11 +285,10 @@ impl fmt::Debug for Once { impl Drop for WaiterQueue<'_> { fn drop(&mut self) { // Swap out our state with however we finished. - let state_and_queue = - self.state_and_queue.swap(self.set_state_on_drop_to, Ordering::AcqRel); + let current = self.state_and_queue.swap(self.set_state_on_drop_to, AcqRel); // We should only ever see an old state which was RUNNING. - assert_eq!(state_and_queue.addr() & STATE_MASK, RUNNING); + assert_eq!(current.addr() & STATE_MASK, RUNNING); // Walk the entire linked list of waiters and wake them up (in lifo // order, last to register is first to wake up). @@ -266,16 +297,13 @@ impl Drop for WaiterQueue<'_> { // free `node` if there happens to be has a spurious wakeup. // So we have to take out the `thread` field and copy the pointer to // `next` first. - let mut queue = - state_and_queue.with_addr(state_and_queue.addr() & !STATE_MASK) as *const Waiter; + let mut queue = to_queue(current); while !queue.is_null() { - let next = (*queue).next; + let next = (*queue).next.get(); let thread = (*queue).thread.take().unwrap(); - (*queue).signaled.store(true, Ordering::Release); - // ^- FIXME (maybe): This is another case of issue #55005 - // `store()` has a potentially dangling ref to `signaled`. - queue = next; + (*queue).signaled.store(true, Release); thread.unpark(); + queue = next; } } } diff --git a/library/std/src/sys/sync/rwlock/futex.rs b/library/std/src/sys/sync/rwlock/futex.rs index aa0de900238f5..75ecc2ab5c52f 100644 --- a/library/std/src/sys/sync/rwlock/futex.rs +++ b/library/std/src/sys/sync/rwlock/futex.rs @@ -1,7 +1,5 @@ -use crate::sync::atomic::{ - AtomicU32, - Ordering::{Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::AtomicU32; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use crate::sys::futex::{futex_wait, futex_wake, futex_wake_all}; pub struct RwLock { @@ -222,7 +220,7 @@ impl RwLock { } } - /// Wake up waiting threads after unlocking. + /// Wakes up waiting threads after unlocking. /// /// If both are waiting, this will wake up only one writer, but will fall /// back to waking up readers if there was no writer to wake up. diff --git a/library/std/src/sys/sync/rwlock/queue.rs b/library/std/src/sys/sync/rwlock/queue.rs index 337cc6c2ca094..458c16516bbe1 100644 --- a/library/std/src/sys/sync/rwlock/queue.rs +++ b/library/std/src/sys/sync/rwlock/queue.rs @@ -111,10 +111,8 @@ use crate::cell::OnceCell; use crate::hint::spin_loop; use crate::mem; use crate::ptr::{self, null_mut, without_provenance_mut, NonNull}; -use crate::sync::atomic::{ - AtomicBool, AtomicPtr, - Ordering::{AcqRel, Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; +use crate::sync::atomic::{AtomicBool, AtomicPtr}; use crate::thread::{self, Thread}; // Locking uses exponential backoff. `SPIN_COUNT` indicates how many times the @@ -186,7 +184,7 @@ struct Node { } impl Node { - /// Create a new queue node. + /// Creates a new queue node. fn new(write: bool) -> Node { Node { next: AtomicLink::new(None), diff --git a/library/std/src/sys/sync/rwlock/solid.rs b/library/std/src/sys/sync/rwlock/solid.rs index a8fef685ceb27..0537140202091 100644 --- a/library/std/src/sys/sync/rwlock/solid.rs +++ b/library/std/src/sys/sync/rwlock/solid.rs @@ -1,13 +1,9 @@ //! A readers-writer lock implementation backed by the SOLID kernel extension. #![forbid(unsafe_op_in_unsafe_fn)] -use crate::sys::pal::{ - abi, - itron::{ - error::{expect_success, expect_success_aborting, fail, ItronError}, - spin::SpinIdOnceCell, - }, -}; +use crate::sys::pal::abi; +use crate::sys::pal::itron::error::{expect_success, expect_success_aborting, fail, ItronError}; +use crate::sys::pal::itron::spin::SpinIdOnceCell; pub struct RwLock { /// The ID of the underlying mutex object @@ -28,7 +24,7 @@ impl RwLock { RwLock { rwl: SpinIdOnceCell::new() } } - /// Get the inner mutex's ID, which is lazily created. + /// Gets the inner mutex's ID, which is lazily created. fn raw(&self) -> abi::ID { match self.rwl.get_or_try_init(|| new_rwl().map(|id| (id, ()))) { Ok((id, ())) => id, diff --git a/library/std/src/sys/sync/thread_parking/darwin.rs b/library/std/src/sys/sync/thread_parking/darwin.rs index 973c08f03171e..96e3d23c332c4 100644 --- a/library/std/src/sys/sync/thread_parking/darwin.rs +++ b/library/std/src/sys/sync/thread_parking/darwin.rs @@ -13,10 +13,8 @@ #![allow(non_camel_case_types)] use crate::pin::Pin; -use crate::sync::atomic::{ - AtomicI8, - Ordering::{Acquire, Release}, -}; +use crate::sync::atomic::AtomicI8; +use crate::sync::atomic::Ordering::{Acquire, Release}; use crate::time::Duration; type dispatch_semaphore_t = *mut crate::ffi::c_void; diff --git a/library/std/src/sys/sync/thread_parking/futex.rs b/library/std/src/sys/sync/thread_parking/futex.rs index 034eececb2a28..ce852eaadc4d9 100644 --- a/library/std/src/sys/sync/thread_parking/futex.rs +++ b/library/std/src/sys/sync/thread_parking/futex.rs @@ -36,7 +36,7 @@ pub struct Parker { // Ordering::Release when writing NOTIFIED (the 'token') in unpark(), and using // Ordering::Acquire when checking for this state in park(). impl Parker { - /// Construct the futex parker. The UNIX parker implementation + /// Constructs the futex parker. The UNIX parker implementation /// requires this to happen in-place. pub unsafe fn new_in_place(parker: *mut Parker) { unsafe { parker.write(Self { state: Atomic::new(EMPTY) }) }; diff --git a/library/std/src/sys/sync/thread_parking/id.rs b/library/std/src/sys/sync/thread_parking/id.rs index 0466743966034..a7b07b509dfd8 100644 --- a/library/std/src/sys/sync/thread_parking/id.rs +++ b/library/std/src/sys/sync/thread_parking/id.rs @@ -9,10 +9,8 @@ use crate::cell::UnsafeCell; use crate::pin::Pin; -use crate::sync::atomic::{ - fence, AtomicI8, - Ordering::{Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use crate::sync::atomic::{fence, AtomicI8}; use crate::sys::thread_parking::{current, park, park_timeout, unpark, ThreadId}; use crate::time::Duration; @@ -30,7 +28,7 @@ impl Parker { Parker { state: AtomicI8::new(EMPTY), tid: UnsafeCell::new(None) } } - /// Create a new thread parker. UNIX requires this to happen in-place. + /// Creates a new thread parker. UNIX requires this to happen in-place. pub unsafe fn new_in_place(parker: *mut Parker) { parker.write(Parker::new()) } diff --git a/library/std/src/sys/sync/thread_parking/pthread.rs b/library/std/src/sys/sync/thread_parking/pthread.rs index fdac1096dbfc1..c64600e9e29c3 100644 --- a/library/std/src/sys/sync/thread_parking/pthread.rs +++ b/library/std/src/sys/sync/thread_parking/pthread.rs @@ -92,7 +92,7 @@ pub struct Parker { } impl Parker { - /// Construct the UNIX parker in-place. + /// Constructs the UNIX parker in-place. /// /// # Safety /// The constructed parker must never be moved. diff --git a/library/std/src/sys/sync/thread_parking/windows7.rs b/library/std/src/sys/sync/thread_parking/windows7.rs index 3a8d40dc5cfac..1000b63b6d01a 100644 --- a/library/std/src/sys/sync/thread_parking/windows7.rs +++ b/library/std/src/sys/sync/thread_parking/windows7.rs @@ -57,14 +57,13 @@ // [3]: https://docs.microsoft.com/en-us/archive/msdn-magazine/2012/november/windows-with-c-the-evolution-of-synchronization-in-windows-and-c // [4]: Windows Internals, Part 1, ISBN 9780735671300 +use core::ffi::c_void; + use crate::pin::Pin; -use crate::sync::atomic::{ - AtomicI8, - Ordering::{Acquire, Release}, -}; +use crate::sync::atomic::AtomicI8; +use crate::sync::atomic::Ordering::{Acquire, Release}; use crate::sys::{c, dur2timeout}; use crate::time::Duration; -use core::ffi::c_void; pub struct Parker { state: AtomicI8, @@ -95,7 +94,7 @@ const NOTIFIED: i8 = 1; // Ordering::Release when writing NOTIFIED (the 'token') in unpark(), and using // Ordering::Acquire when reading this state in park() after waking up. impl Parker { - /// Construct the Windows parker. The UNIX parker implementation + /// Constructs the Windows parker. The UNIX parker implementation /// requires this to happen in-place. pub unsafe fn new_in_place(parker: *mut Parker) { parker.write(Self { state: AtomicI8::new(EMPTY) }); @@ -185,16 +184,15 @@ impl Parker { #[cfg(target_vendor = "win7")] mod keyed_events { - use super::{Parker, EMPTY, NOTIFIED}; - use crate::sys::c; use core::pin::Pin; use core::ptr; - use core::sync::atomic::{ - AtomicPtr, - Ordering::{Acquire, Relaxed}, - }; + use core::sync::atomic::AtomicPtr; + use core::sync::atomic::Ordering::{Acquire, Relaxed}; use core::time::Duration; + use super::{Parker, EMPTY, NOTIFIED}; + use crate::sys::c; + pub unsafe fn park(parker: Pin<&Parker>) { // Wait for unpark() to produce this event. c::NtWaitForKeyedEvent(keyed_event_handle(), parker.ptr(), 0, ptr::null_mut()); diff --git a/library/std/src/sys/sync/thread_parking/xous.rs b/library/std/src/sys/sync/thread_parking/xous.rs index 0bd0462d77d35..64b6f731f2377 100644 --- a/library/std/src/sys/sync/thread_parking/xous.rs +++ b/library/std/src/sys/sync/thread_parking/xous.rs @@ -2,10 +2,8 @@ use crate::os::xous::ffi::{blocking_scalar, scalar}; use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; use crate::pin::Pin; use crate::ptr; -use crate::sync::atomic::{ - AtomicI8, - Ordering::{Acquire, Release}, -}; +use crate::sync::atomic::AtomicI8; +use crate::sync::atomic::Ordering::{Acquire, Release}; use crate::time::Duration; const NOTIFIED: i8 = 1; diff --git a/library/std/src/sys/thread_local/guard/solid.rs b/library/std/src/sys/thread_local/guard/solid.rs index b65d00c5b5fb7..054b2d561c8b4 100644 --- a/library/std/src/sys/thread_local/guard/solid.rs +++ b/library/std/src/sys/thread_local/guard/solid.rs @@ -3,7 +3,8 @@ //! destructors for terminated tasks, we still keep our own list. use crate::cell::Cell; -use crate::sys::pal::{abi, itron::task}; +use crate::sys::pal::abi; +use crate::sys::pal::itron::task; use crate::sys::thread_local::destructors; pub fn enable() { diff --git a/library/std/src/sys/thread_local/guard/windows.rs b/library/std/src/sys/thread_local/guard/windows.rs index e08ac44e1af88..bf94f7d6e3d13 100644 --- a/library/std/src/sys/thread_local/guard/windows.rs +++ b/library/std/src/sys/thread_local/guard/windows.rs @@ -63,9 +63,10 @@ //! [1]: https://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way //! [2]: https://github.com/ChromiumWebApps/chromium/blob/master/base/threading/thread_local_storage_win.cc#L42 +use core::ffi::c_void; + use crate::ptr; use crate::sys::c; -use core::ffi::c_void; pub fn enable() { // When destructors are used, we don't want LLVM eliminating CALLBACK for any diff --git a/library/std/src/sys/thread_local/key/windows.rs b/library/std/src/sys/thread_local/key/windows.rs index 8b43e558d5d98..f4e0f25a476ee 100644 --- a/library/std/src/sys/thread_local/key/windows.rs +++ b/library/std/src/sys/thread_local/key/windows.rs @@ -26,10 +26,8 @@ use crate::cell::UnsafeCell; use crate::ptr; -use crate::sync::atomic::{ - AtomicPtr, AtomicU32, - Ordering::{AcqRel, Acquire, Relaxed, Release}, -}; +use crate::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; +use crate::sync::atomic::{AtomicPtr, AtomicU32}; use crate::sys::c; use crate::sys::thread_local::guard; diff --git a/library/std/src/sys/thread_local/key/xous.rs b/library/std/src/sys/thread_local/key/xous.rs index 5a837a33e190e..4fb2fdcc61925 100644 --- a/library/std/src/sys/thread_local/key/xous.rs +++ b/library/std/src/sys/thread_local/key/xous.rs @@ -36,14 +36,13 @@ // FIXME(joboet): implement support for native TLS instead. -use crate::mem::ManuallyDrop; -use crate::ptr; -use crate::sync::atomic::AtomicPtr; -use crate::sync::atomic::AtomicUsize; -use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use core::arch::asm; +use crate::mem::ManuallyDrop; use crate::os::xous::ffi::{map_memory, unmap_memory, MemoryFlags}; +use crate::ptr; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use crate::sync::atomic::{AtomicPtr, AtomicUsize}; pub type Key = usize; pub type Dtor = unsafe extern "C" fn(*mut u8); @@ -79,7 +78,7 @@ fn tls_ptr_addr() -> *mut *mut u8 { core::ptr::with_exposed_provenance_mut::<*mut u8>(tp) } -/// Create an area of memory that's unique per thread. This area will +/// Creates an area of memory that's unique per thread. This area will /// contain all thread local pointers. fn tls_table() -> &'static mut [*mut u8] { let tp = tls_ptr_addr(); diff --git a/library/std/src/sys/thread_local/native/eager.rs b/library/std/src/sys/thread_local/native/eager.rs index 99e5ae7fb9687..fd48c4f720216 100644 --- a/library/std/src/sys/thread_local/native/eager.rs +++ b/library/std/src/sys/thread_local/native/eager.rs @@ -1,7 +1,6 @@ use crate::cell::{Cell, UnsafeCell}; use crate::ptr::{self, drop_in_place}; -use crate::sys::thread_local::abort_on_dtor_unwind; -use crate::sys::thread_local::destructors; +use crate::sys::thread_local::{abort_on_dtor_unwind, destructors}; #[derive(Clone, Copy)] enum State { @@ -21,7 +20,7 @@ impl Storage { Storage { state: Cell::new(State::Initial), val: UnsafeCell::new(val) } } - /// Get a pointer to the TLS value. If the TLS variable has been destroyed, + /// Gets a pointer to the TLS value. If the TLS variable has been destroyed, /// a null pointer is returned. /// /// The resulting pointer may not be used after thread destruction has diff --git a/library/std/src/sys/thread_local/native/lazy.rs b/library/std/src/sys/thread_local/native/lazy.rs index 9d47e8ef68975..51294285ba013 100644 --- a/library/std/src/sys/thread_local/native/lazy.rs +++ b/library/std/src/sys/thread_local/native/lazy.rs @@ -1,8 +1,7 @@ use crate::cell::UnsafeCell; use crate::hint::unreachable_unchecked; use crate::ptr; -use crate::sys::thread_local::abort_on_dtor_unwind; -use crate::sys::thread_local::destructors; +use crate::sys::thread_local::{abort_on_dtor_unwind, destructors}; pub unsafe trait DestroyedState: Sized { fn register_dtor(s: &Storage); @@ -39,7 +38,7 @@ where Storage { state: UnsafeCell::new(State::Initial) } } - /// Get a pointer to the TLS value, potentially initializing it with the + /// Gets a pointer to the TLS value, potentially initializing it with the /// provided parameters. If the TLS variable has been destroyed, a null /// pointer is returned. /// diff --git a/library/std/src/sys/thread_local/os.rs b/library/std/src/sys/thread_local/os.rs index e06185f00690b..e27b47c3f4536 100644 --- a/library/std/src/sys/thread_local/os.rs +++ b/library/std/src/sys/thread_local/os.rs @@ -60,7 +60,7 @@ impl Storage { Storage { key: LazyKey::new(Some(destroy_value::)), marker: PhantomData } } - /// Get a pointer to the TLS value, potentially initializing it with the + /// Gets a pointer to the TLS value, potentially initializing it with the /// provided parameters. If the TLS variable has been destroyed, a null /// pointer is returned. /// diff --git a/library/std/src/sys/thread_local/statik.rs b/library/std/src/sys/thread_local/statik.rs index 0f08cab1ae4ff..a3451ab74e04f 100644 --- a/library/std/src/sys/thread_local/statik.rs +++ b/library/std/src/sys/thread_local/statik.rs @@ -63,7 +63,7 @@ impl LazyStorage { LazyStorage { value: UnsafeCell::new(None) } } - /// Get a pointer to the TLS value, potentially initializing it with the + /// Gets a pointer to the TLS value, potentially initializing it with the /// provided parameters. /// /// The resulting pointer may not be used after reentrant inialialization diff --git a/library/std/src/sys_common/io.rs b/library/std/src/sys_common/io.rs index 4a42ff3c618ce..e386c955f3767 100644 --- a/library/std/src/sys_common/io.rs +++ b/library/std/src/sys_common/io.rs @@ -5,12 +5,11 @@ pub const DEFAULT_BUF_SIZE: usize = if cfg!(target_os = "espidf") { 512 } else { #[cfg(test)] #[allow(dead_code)] // not used on emscripten pub mod test { - use crate::env; - use crate::fs; - use crate::path::{Path, PathBuf}; - use crate::thread; use rand::RngCore; + use crate::path::{Path, PathBuf}; + use crate::{env, fs, thread}; + pub struct TempDir(PathBuf); impl TempDir { diff --git a/library/std/src/sys_common/lazy_box.rs b/library/std/src/sys_common/lazy_box.rs index 63c3316bdeb28..b45b05f63baaa 100644 --- a/library/std/src/sys_common/lazy_box.rs +++ b/library/std/src/sys_common/lazy_box.rs @@ -5,10 +5,8 @@ use crate::marker::PhantomData; use crate::ops::{Deref, DerefMut}; use crate::ptr::null_mut; -use crate::sync::atomic::{ - AtomicPtr, - Ordering::{AcqRel, Acquire}, -}; +use crate::sync::atomic::AtomicPtr; +use crate::sync::atomic::Ordering::{AcqRel, Acquire}; pub(crate) struct LazyBox { ptr: AtomicPtr, diff --git a/library/std/src/sys_common/net.rs b/library/std/src/sys_common/net.rs index 95ca67fc2e0b6..25ebeb3502d20 100644 --- a/library/std/src/sys_common/net.rs +++ b/library/std/src/sys_common/net.rs @@ -1,19 +1,14 @@ #[cfg(test)] mod tests; -use crate::cmp; -use crate::fmt; +use crate::ffi::{c_int, c_void}; use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}; -use crate::mem; use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; -use crate::ptr; use crate::sys::common::small_c_string::run_with_cstr; -use crate::sys::net::netc as c; -use crate::sys::net::{cvt, cvt_gai, cvt_r, init, wrlen_t, Socket}; +use crate::sys::net::{cvt, cvt_gai, cvt_r, init, netc as c, wrlen_t, Socket}; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; - -use crate::ffi::{c_int, c_void}; +use crate::{cmp, fmt, mem, ptr}; cfg_if::cfg_if! { if #[cfg(any( @@ -42,6 +37,7 @@ cfg_if::cfg_if! { target_os = "hurd", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", + target_os = "solaris", target_os = "illumos", target_os = "haiku", target_os = "nto"))] { use libc::MSG_NOSIGNAL; } else { diff --git a/library/std/src/sys_common/process.rs b/library/std/src/sys_common/process.rs index 4d295cf0f09d5..5333ee146f7d6 100644 --- a/library/std/src/sys_common/process.rs +++ b/library/std/src/sys_common/process.rs @@ -2,12 +2,10 @@ #![unstable(feature = "process_internals", issue = "none")] use crate::collections::BTreeMap; -use crate::env; use crate::ffi::{OsStr, OsString}; -use crate::fmt; -use crate::io; use crate::sys::pipe::read2; use crate::sys::process::{EnvKey, ExitStatus, Process, StdioPipes}; +use crate::{env, fmt, io}; // Stores a set of changes to an environment #[derive(Clone)] diff --git a/library/std/src/sys_common/wstr.rs b/library/std/src/sys_common/wstr.rs index 8eae160648502..f9a171fb7d8f5 100644 --- a/library/std/src/sys_common/wstr.rs +++ b/library/std/src/sys_common/wstr.rs @@ -15,7 +15,7 @@ pub struct WStrUnits<'a> { } impl WStrUnits<'_> { - /// Create the iterator. Returns `None` if `lpwstr` is null. + /// Creates the iterator. Returns `None` if `lpwstr` is null. /// /// SAFETY: `lpwstr` must point to a null-terminated wide string that lives /// at least as long as the lifetime of this struct. diff --git a/library/std/src/sys_common/wtf8.rs b/library/std/src/sys_common/wtf8.rs index 6aeeb6259285d..277c9506febbb 100644 --- a/library/std/src/sys_common/wtf8.rs +++ b/library/std/src/sys_common/wtf8.rs @@ -23,16 +23,12 @@ use core::str::next_code_point; use crate::borrow::Cow; use crate::collections::TryReserveError; -use crate::fmt; use crate::hash::{Hash, Hasher}; use crate::iter::FusedIterator; -use crate::mem; -use crate::ops; use crate::rc::Rc; -use crate::slice; -use crate::str; use crate::sync::Arc; use crate::sys_common::AsInner; +use crate::{fmt, mem, ops, slice, str}; const UTF8_REPLACEMENT_CHARACTER: &str = "\u{FFFD}"; diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs index e9731bc85d61c..59720f77465e1 100644 --- a/library/std/src/thread/mod.rs +++ b/library/std/src/thread/mod.rs @@ -160,24 +160,19 @@ mod tests; use crate::any::Any; use crate::cell::{Cell, OnceCell, UnsafeCell}; -use crate::env; use crate::ffi::CStr; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; -use crate::mem::{self, forget}; +use crate::mem::{self, forget, ManuallyDrop}; use crate::num::NonZero; -use crate::panic; -use crate::panicking; use crate::pin::Pin; use crate::ptr::addr_of_mut; -use crate::str; use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sync::Arc; use crate::sys::sync::Parker; use crate::sys::thread as imp; use crate::sys_common::{AsInner, IntoInner}; use crate::time::{Duration, Instant}; +use crate::{env, fmt, io, panic, panicking, str}; #[stable(feature = "scoped_threads", since = "1.63.0")] mod scoped; @@ -192,22 +187,14 @@ pub use scoped::{scope, Scope, ScopedJoinHandle}; #[macro_use] mod local; -cfg_if::cfg_if! { - if #[cfg(test)] { - // Avoid duplicating the global state associated with thread-locals between this crate and - // realstd. Miri relies on this. - pub use realstd::thread::{local_impl, AccessError, LocalKey}; - } else { - #[stable(feature = "rust1", since = "1.0.0")] - pub use self::local::{AccessError, LocalKey}; - - // Implementation details used by the thread_local!{} macro. - #[doc(hidden)] - #[unstable(feature = "thread_local_internals", issue = "none")] - pub mod local_impl { - pub use crate::sys::thread_local::*; - } - } +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::local::{AccessError, LocalKey}; + +// Implementation details used by the thread_local!{} macro. +#[doc(hidden)] +#[unstable(feature = "thread_local_internals", issue = "none")] +pub mod local_impl { + pub use crate::sys::thread_local::*; } //////////////////////////////////////////////////////////////////////////////// @@ -510,11 +497,10 @@ impl Builder { MaybeDangling(mem::MaybeUninit::new(x)) } fn into_inner(self) -> T { - // SAFETY: we are always initialized. - let ret = unsafe { self.0.assume_init_read() }; // Make sure we don't drop. - mem::forget(self); - ret + let this = ManuallyDrop::new(self); + // SAFETY: we are always initialized. + unsafe { this.0.assume_init_read() } } } impl Drop for MaybeDangling { @@ -858,7 +844,7 @@ pub fn panicking() -> bool { panicking::panicking() } -/// Use [`sleep`]. +/// Uses [`sleep`]. /// /// Puts the current thread to sleep for at least the specified amount of time. /// @@ -1129,7 +1115,7 @@ pub fn park() { forget(guard); } -/// Use [`park_timeout`]. +/// Uses [`park_timeout`]. /// /// Blocks unless or until the current thread's token is made available or /// the specified duration has been reached (may wake spuriously). @@ -1301,9 +1287,10 @@ enum ThreadName { // This module ensures private fields are kept private, which is necessary to enforce the safety requirements. mod thread_name_string { + use core::str; + use super::ThreadName; use crate::ffi::{CStr, CString}; - use core::str; /// Like a `String` it's guaranteed UTF-8 and like a `CString` it's null terminated. pub(crate) struct ThreadNameString { diff --git a/library/std/src/thread/scoped.rs b/library/std/src/thread/scoped.rs index e2e22e5194f4a..ba27c9220aea5 100644 --- a/library/std/src/thread/scoped.rs +++ b/library/std/src/thread/scoped.rs @@ -1,10 +1,9 @@ use super::{current, park, Builder, JoinInner, Result, Thread}; -use crate::fmt; -use crate::io; use crate::marker::PhantomData; use crate::panic::{catch_unwind, resume_unwind, AssertUnwindSafe}; use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use crate::sync::Arc; +use crate::{fmt, io}; /// A scope to spawn scoped threads in. /// @@ -67,7 +66,7 @@ impl ScopeData { } } -/// Create a scope for spawning scoped threads. +/// Creates a scope for spawning scoped threads. /// /// The function passed to `scope` will be provided a [`Scope`] object, /// through which scoped threads can be [spawned][`Scope::spawn`]. diff --git a/library/std/src/thread/tests.rs b/library/std/src/thread/tests.rs index 1fb1333be0e45..aa464d56f95b2 100644 --- a/library/std/src/thread/tests.rs +++ b/library/std/src/thread/tests.rs @@ -1,16 +1,12 @@ use super::Builder; use crate::any::Any; -use crate::mem; use crate::panic::panic_any; -use crate::result; -use crate::sync::{ - atomic::{AtomicBool, Ordering}, - mpsc::{channel, Sender}, - Arc, Barrier, -}; +use crate::sync::atomic::{AtomicBool, Ordering}; +use crate::sync::mpsc::{channel, Sender}; +use crate::sync::{Arc, Barrier}; use crate::thread::{self, Scope, ThreadId}; -use crate::time::Duration; -use crate::time::Instant; +use crate::time::{Duration, Instant}; +use crate::{mem, result}; // !!! These tests are dangerous. If something is buggy, they will hang, !!! // !!! instead of exiting cleanly. This might wedge the buildbots. !!! diff --git a/library/std/src/time.rs b/library/std/src/time.rs index 6f1a354d28a85..ae46670c25e61 100644 --- a/library/std/src/time.rs +++ b/library/std/src/time.rs @@ -34,18 +34,17 @@ #[cfg(test)] mod tests; +#[stable(feature = "time", since = "1.3.0")] +pub use core::time::Duration; +#[stable(feature = "duration_checked_float", since = "1.66.0")] +pub use core::time::TryFromFloatSecsError; + use crate::error::Error; use crate::fmt; use crate::ops::{Add, AddAssign, Sub, SubAssign}; use crate::sys::time; use crate::sys_common::{FromInner, IntoInner}; -#[stable(feature = "time", since = "1.3.0")] -pub use core::time::Duration; - -#[stable(feature = "duration_checked_float", since = "1.66.0")] -pub use core::time::TryFromFloatSecsError; - /// A measurement of a monotonically nondecreasing clock. /// Opaque and useful only with [`Duration`]. /// diff --git a/library/std/src/time/tests.rs b/library/std/src/time/tests.rs index 6ed84806e6d37..de36dc4c9fd16 100644 --- a/library/std/src/time/tests.rs +++ b/library/std/src/time/tests.rs @@ -1,8 +1,10 @@ -use super::{Duration, Instant, SystemTime, UNIX_EPOCH}; use core::fmt::Debug; + #[cfg(not(target_arch = "wasm32"))] use test::{black_box, Bencher}; +use super::{Duration, Instant, SystemTime, UNIX_EPOCH}; + macro_rules! assert_almost_eq { ($a:expr, $b:expr) => {{ let (a, b) = ($a, $b); diff --git a/library/std/tests/common/mod.rs b/library/std/tests/common/mod.rs index 1aad6549e76c3..7cf70c725e411 100644 --- a/library/std/tests/common/mod.rs +++ b/library/std/tests/common/mod.rs @@ -1,10 +1,9 @@ #![allow(unused)] -use rand::RngCore; -use std::env; -use std::fs; use std::path::{Path, PathBuf}; -use std::thread; +use std::{env, fs, thread}; + +use rand::RngCore; /// Copied from `std::test_helpers::test_rng`, since these tests rely on the /// seed not being the same for every RNG invocation too. diff --git a/library/std/tests/create_dir_all_bare.rs b/library/std/tests/create_dir_all_bare.rs index 79c3c8f528efa..8becf713205ee 100644 --- a/library/std/tests/create_dir_all_bare.rs +++ b/library/std/tests/create_dir_all_bare.rs @@ -3,9 +3,8 @@ //! Note that this test changes the current directory so //! should not be in the same process as other tests. -use std::env; -use std::fs; use std::path::{Path, PathBuf}; +use std::{env, fs}; mod common; diff --git a/library/std/tests/env.rs b/library/std/tests/env.rs index a1ca85c2145f5..4e472b4ce9953 100644 --- a/library/std/tests/env.rs +++ b/library/std/tests/env.rs @@ -4,9 +4,10 @@ use std::ffi::{OsStr, OsString}; use rand::distributions::{Alphanumeric, DistString}; mod common; -use common::test_rng; use std::thread; +use common::test_rng; + #[track_caller] fn make_rand_name() -> OsString { let n = format!("TEST{}", Alphanumeric.sample_string(&mut test_rng(), 10)); diff --git a/library/std/tests/pipe_subprocess.rs b/library/std/tests/pipe_subprocess.rs index c2278098b9b3f..1535742a83a21 100644 --- a/library/std/tests/pipe_subprocess.rs +++ b/library/std/tests/pipe_subprocess.rs @@ -3,7 +3,9 @@ fn main() { #[cfg(all(not(miri), any(unix, windows)))] { - use std::{env, io::Read, pipe::pipe, process}; + use std::io::Read; + use std::pipe::pipe; + use std::{env, process}; if env::var("I_AM_THE_CHILD").is_ok() { child(); diff --git a/library/std/tests/process_spawning.rs b/library/std/tests/process_spawning.rs index c56c111c37ded..d249eb7d50aa5 100644 --- a/library/std/tests/process_spawning.rs +++ b/library/std/tests/process_spawning.rs @@ -1,9 +1,6 @@ #![cfg(not(target_env = "sgx"))] -use std::env; -use std::fs; -use std::process; -use std::str; +use std::{env, fs, process, str}; mod common; diff --git a/library/std/tests/switch-stdout.rs b/library/std/tests/switch-stdout.rs index 0afe18088fa5f..42011a9b3da62 100644 --- a/library/std/tests/switch-stdout.rs +++ b/library/std/tests/switch-stdout.rs @@ -5,11 +5,10 @@ use std::io::{Read, Write}; mod common; -#[cfg(windows)] -use std::os::windows::io::OwnedHandle; - #[cfg(unix)] use std::os::fd::OwnedFd; +#[cfg(windows)] +use std::os::windows::io::OwnedHandle; #[cfg(unix)] fn switch_stdout_to(file: OwnedFd) -> OwnedFd { diff --git a/library/std/tests/windows.rs b/library/std/tests/windows.rs index 9f7596f1bc2c0..dab3182b81872 100644 --- a/library/std/tests/windows.rs +++ b/library/std/tests/windows.rs @@ -1,7 +1,9 @@ #![cfg(windows)] //! An external tests -use std::{ffi::OsString, os::windows::ffi::OsStringExt, path::PathBuf}; +use std::ffi::OsString; +use std::os::windows::ffi::OsStringExt; +use std::path::PathBuf; #[test] #[should_panic] diff --git a/library/stdarch b/library/stdarch index df3618d9f3516..47b929ddc521a 160000 --- a/library/stdarch +++ b/library/stdarch @@ -1 +1 @@ -Subproject commit df3618d9f35165f4bc548114e511c49c29e1fd9b +Subproject commit 47b929ddc521a78b0f699ba8d5c274d28593448a diff --git a/library/sysroot/Cargo.toml b/library/sysroot/Cargo.toml index 169eeeca8c2e8..7165c3e48af42 100644 --- a/library/sysroot/Cargo.toml +++ b/library/sysroot/Cargo.toml @@ -16,8 +16,8 @@ backtrace = ["std/backtrace"] compiler-builtins-c = ["std/compiler-builtins-c"] compiler-builtins-mem = ["std/compiler-builtins-mem"] compiler-builtins-no-asm = ["std/compiler-builtins-no-asm"] +compiler-builtins-no-f16-f128 = ["std/compiler-builtins-no-f16-f128"] compiler-builtins-mangled-names = ["std/compiler-builtins-mangled-names"] -compiler-builtins-weak-intrinsics = ["std/compiler-builtins-weak-intrinsics"] llvm-libunwind = ["std/llvm-libunwind"] system-llvm-libunwind = ["std/system-llvm-libunwind"] panic-unwind = ["std/panic_unwind"] diff --git a/library/test/src/bench.rs b/library/test/src/bench.rs index 9f34f54c3d60a..b71def3b03223 100644 --- a/library/test/src/bench.rs +++ b/library/test/src/bench.rs @@ -1,19 +1,16 @@ //! Benchmarking module. -use super::{ - event::CompletedTest, - options::BenchMode, - test_result::TestResult, - types::{TestDesc, TestId}, - Sender, -}; - -use crate::stats; -use std::cmp; -use std::io; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; +use std::{cmp, io}; + +use super::event::CompletedTest; +use super::options::BenchMode; +use super::test_result::TestResult; +use super::types::{TestDesc, TestId}; +use super::Sender; +use crate::stats; /// An identity function that *__hints__* to the compiler to be maximally pessimistic about what /// `black_box` could do. diff --git a/library/test/src/cli.rs b/library/test/src/cli.rs index b7d24405b775e..4ccd825bf8dd3 100644 --- a/library/test/src/cli.rs +++ b/library/test/src/cli.rs @@ -1,11 +1,11 @@ //! Module converting command-line arguments into test configuration. use std::env; +use std::io::{self, IsTerminal}; use std::path::PathBuf; use super::options::{ColorConfig, Options, OutputFormat, RunIgnored}; use super::time::TestTimeOptions; -use std::io::{self, IsTerminal}; #[derive(Debug)] pub struct TestOpts { diff --git a/library/test/src/console.rs b/library/test/src/console.rs index 7e224d60d9dc5..4d4cdcf4d7b6c 100644 --- a/library/test/src/console.rs +++ b/library/test/src/console.rs @@ -5,19 +5,19 @@ use std::io; use std::io::prelude::Write; use std::time::Instant; -use super::{ - bench::fmt_bench_samples, - cli::TestOpts, - event::{CompletedTest, TestEvent}, - filter_tests, - formatters::{JsonFormatter, JunitFormatter, OutputFormatter, PrettyFormatter, TerseFormatter}, - helpers::{concurrency::get_concurrency, metrics::MetricMap}, - options::{Options, OutputFormat}, - run_tests, term, - test_result::TestResult, - time::{TestExecTime, TestSuiteExecTime}, - types::{NamePadding, TestDesc, TestDescAndFn}, +use super::bench::fmt_bench_samples; +use super::cli::TestOpts; +use super::event::{CompletedTest, TestEvent}; +use super::formatters::{ + JsonFormatter, JunitFormatter, OutputFormatter, PrettyFormatter, TerseFormatter, }; +use super::helpers::concurrency::get_concurrency; +use super::helpers::metrics::MetricMap; +use super::options::{Options, OutputFormat}; +use super::test_result::TestResult; +use super::time::{TestExecTime, TestSuiteExecTime}; +use super::types::{NamePadding, TestDesc, TestDescAndFn}; +use super::{filter_tests, run_tests, term}; /// Generic wrapper over stdout. pub enum OutputLocation { diff --git a/library/test/src/formatters/json.rs b/library/test/src/formatters/json.rs index 6245aae17c4d7..aa1c50641cb54 100644 --- a/library/test/src/formatters/json.rs +++ b/library/test/src/formatters/json.rs @@ -1,12 +1,12 @@ -use std::{borrow::Cow, io, io::prelude::Write}; +use std::borrow::Cow; +use std::io; +use std::io::prelude::Write; use super::OutputFormatter; -use crate::{ - console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}, - test_result::TestResult, - time, - types::TestDesc, -}; +use crate::console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}; +use crate::test_result::TestResult; +use crate::time; +use crate::types::TestDesc; pub(crate) struct JsonFormatter { out: OutputLocation, diff --git a/library/test/src/formatters/junit.rs b/library/test/src/formatters/junit.rs index a211ebf1ded16..96b432008404b 100644 --- a/library/test/src/formatters/junit.rs +++ b/library/test/src/formatters/junit.rs @@ -1,13 +1,12 @@ -use std::io::{self, prelude::Write}; +use std::io::prelude::Write; +use std::io::{self}; use std::time::Duration; use super::OutputFormatter; -use crate::{ - console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}, - test_result::TestResult, - time, - types::{TestDesc, TestType}, -}; +use crate::console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}; +use crate::test_result::TestResult; +use crate::time; +use crate::types::{TestDesc, TestType}; pub struct JunitFormatter { out: OutputLocation, diff --git a/library/test/src/formatters/mod.rs b/library/test/src/formatters/mod.rs index bc6ffebc1d3b2..f1225fecfef1a 100644 --- a/library/test/src/formatters/mod.rs +++ b/library/test/src/formatters/mod.rs @@ -1,11 +1,10 @@ -use std::{io, io::prelude::Write}; +use std::io; +use std::io::prelude::Write; -use crate::{ - console::{ConsoleTestDiscoveryState, ConsoleTestState}, - test_result::TestResult, - time, - types::{TestDesc, TestName}, -}; +use crate::console::{ConsoleTestDiscoveryState, ConsoleTestState}; +use crate::test_result::TestResult; +use crate::time; +use crate::types::{TestDesc, TestName}; mod json; mod junit; diff --git a/library/test/src/formatters/pretty.rs b/library/test/src/formatters/pretty.rs index 22654a3400b44..7089eae4330a0 100644 --- a/library/test/src/formatters/pretty.rs +++ b/library/test/src/formatters/pretty.rs @@ -1,14 +1,12 @@ -use std::{io, io::prelude::Write}; +use std::io; +use std::io::prelude::Write; use super::OutputFormatter; -use crate::{ - bench::fmt_bench_samples, - console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}, - term, - test_result::TestResult, - time, - types::TestDesc, -}; +use crate::bench::fmt_bench_samples; +use crate::console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}; +use crate::test_result::TestResult; +use crate::types::TestDesc; +use crate::{term, time}; pub(crate) struct PrettyFormatter { out: OutputLocation, diff --git a/library/test/src/formatters/terse.rs b/library/test/src/formatters/terse.rs index 875c66e5fa32c..534aa2f33110c 100644 --- a/library/test/src/formatters/terse.rs +++ b/library/test/src/formatters/terse.rs @@ -1,15 +1,12 @@ -use std::{io, io::prelude::Write}; +use std::io; +use std::io::prelude::Write; use super::OutputFormatter; -use crate::{ - bench::fmt_bench_samples, - console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}, - term, - test_result::TestResult, - time, - types::NamePadding, - types::TestDesc, -}; +use crate::bench::fmt_bench_samples; +use crate::console::{ConsoleTestDiscoveryState, ConsoleTestState, OutputLocation}; +use crate::test_result::TestResult; +use crate::types::{NamePadding, TestDesc}; +use crate::{term, time}; // We insert a '\n' when the output hits 100 columns in quiet mode. 88 test // result chars leaves 12 chars for a progress count like " 11704/12853". diff --git a/library/test/src/helpers/concurrency.rs b/library/test/src/helpers/concurrency.rs index 1854c6a76524d..b1545cbec438a 100644 --- a/library/test/src/helpers/concurrency.rs +++ b/library/test/src/helpers/concurrency.rs @@ -1,7 +1,8 @@ //! Helper module which helps to determine amount of threads to be used //! during tests execution. -use std::{env, num::NonZero, thread}; +use std::num::NonZero; +use std::{env, thread}; pub fn get_concurrency() -> usize { if let Ok(value) = env::var("RUST_TEST_THREADS") { diff --git a/library/test/src/helpers/shuffle.rs b/library/test/src/helpers/shuffle.rs index 2ac3bfbd4d6f2..14389eb0e37af 100644 --- a/library/test/src/helpers/shuffle.rs +++ b/library/test/src/helpers/shuffle.rs @@ -1,8 +1,9 @@ -use crate::cli::TestOpts; -use crate::types::{TestDescAndFn, TestId, TestName}; use std::hash::{DefaultHasher, Hasher}; use std::time::{SystemTime, UNIX_EPOCH}; +use crate::cli::TestOpts; +use crate::types::{TestDescAndFn, TestId, TestName}; + pub fn get_shuffle_seed(opts: &TestOpts) -> Option { opts.shuffle_seed.or_else(|| { if opts.shuffle { diff --git a/library/test/src/lib.rs b/library/test/src/lib.rs index 71cb796b93705..632f8d161affa 100644 --- a/library/test/src/lib.rs +++ b/library/test/src/lib.rs @@ -24,6 +24,9 @@ #![feature(panic_can_unwind)] #![feature(test)] #![allow(internal_features)] +#![warn(rustdoc::unescaped_backticks)] + +pub use cli::TestOpts; pub use self::bench::{black_box, Bencher}; pub use self::console::run_tests_console; @@ -31,39 +34,31 @@ pub use self::options::{ColorConfig, Options, OutputFormat, RunIgnored, ShouldPa pub use self::types::TestName::*; pub use self::types::*; pub use self::ColorConfig::*; -pub use cli::TestOpts; // Module to be used by rustc to compile tests in libtest pub mod test { - pub use crate::{ - assert_test_result, - bench::Bencher, - cli::{parse_opts, TestOpts}, - filter_tests, - helpers::metrics::{Metric, MetricMap}, - options::{Options, RunIgnored, RunStrategy, ShouldPanic}, - run_test, test_main, test_main_static, - test_result::{TestResult, TrFailed, TrFailedMsg, TrIgnored, TrOk}, - time::{TestExecTime, TestTimeOptions}, - types::{ - DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, TestDesc, - TestDescAndFn, TestId, TestName, TestType, - }, + pub use crate::bench::Bencher; + pub use crate::cli::{parse_opts, TestOpts}; + pub use crate::helpers::metrics::{Metric, MetricMap}; + pub use crate::options::{Options, RunIgnored, RunStrategy, ShouldPanic}; + pub use crate::test_result::{TestResult, TrFailed, TrFailedMsg, TrIgnored, TrOk}; + pub use crate::time::{TestExecTime, TestTimeOptions}; + pub use crate::types::{ + DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, TestDesc, + TestDescAndFn, TestId, TestName, TestType, }; + pub use crate::{assert_test_result, filter_tests, run_test, test_main, test_main_static}; } -use std::{ - collections::VecDeque, - env, io, - io::prelude::Write, - mem::ManuallyDrop, - panic::{self, catch_unwind, AssertUnwindSafe, PanicHookInfo}, - process::{self, Command, Termination}, - sync::mpsc::{channel, Sender}, - sync::{Arc, Mutex}, - thread, - time::{Duration, Instant}, -}; +use std::collections::VecDeque; +use std::io::prelude::Write; +use std::mem::ManuallyDrop; +use std::panic::{self, catch_unwind, AssertUnwindSafe, PanicHookInfo}; +use std::process::{self, Command, Termination}; +use std::sync::mpsc::{channel, Sender}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use std::{env, io, thread}; pub mod bench; mod cli; @@ -82,6 +77,7 @@ mod types; mod tests; use core::any::Any; + use event::{CompletedTest, TestEvent}; use helpers::concurrency::get_concurrency; use helpers::shuffle::{get_shuffle_seed, shuffle_tests}; diff --git a/library/test/src/stats.rs b/library/test/src/stats.rs index b33b080126131..71c944afde8d6 100644 --- a/library/test/src/stats.rs +++ b/library/test/src/stats.rs @@ -116,7 +116,7 @@ pub struct Summary { } impl Summary { - /// Construct a new summary of a sample set. + /// Constructs a new summary of a sample set. pub fn new(samples: &[f64]) -> Summary { Summary { sum: samples.sum(), diff --git a/library/test/src/stats/tests.rs b/library/test/src/stats/tests.rs index 3a6e8401bf1ab..4b209dcf214da 100644 --- a/library/test/src/stats/tests.rs +++ b/library/test/src/stats/tests.rs @@ -1,10 +1,11 @@ use super::*; extern crate test; -use self::test::test::Bencher; use std::io; use std::io::prelude::*; +use self::test::test::Bencher; + // Test vectors generated from R, using the script src/etc/stat-test-vectors.r. macro_rules! assert_approx_eq { diff --git a/library/test/src/term.rs b/library/test/src/term.rs index a14b0d4f5a962..e736e85d46966 100644 --- a/library/test/src/term.rs +++ b/library/test/src/term.rs @@ -12,7 +12,8 @@ #![deny(missing_docs)] -use std::io::{self, prelude::*}; +use std::io::prelude::*; +use std::io::{self}; pub(crate) use terminfo::TerminfoTerminal; #[cfg(windows)] diff --git a/library/test/src/term/terminfo/mod.rs b/library/test/src/term/terminfo/mod.rs index 67ba89410cd99..67eec3ca50f48 100644 --- a/library/test/src/term/terminfo/mod.rs +++ b/library/test/src/term/terminfo/mod.rs @@ -1,20 +1,18 @@ //! Terminfo database interface. use std::collections::HashMap; -use std::env; -use std::error; -use std::fmt; use std::fs::File; -use std::io::{self, prelude::*, BufReader}; +use std::io::prelude::*; +use std::io::{self, BufReader}; use std::path::Path; - -use super::color; -use super::Terminal; +use std::{env, error, fmt}; use parm::{expand, Param, Variables}; use parser::compiled::{msys_terminfo, parse}; use searcher::get_dbpath_for_term; +use super::{color, Terminal}; + /// A parsed terminfo database entry. #[allow(unused)] #[derive(Debug)] diff --git a/library/test/src/term/terminfo/parm.rs b/library/test/src/term/terminfo/parm.rs index c5b4ef01893c2..529ec0c36e4a5 100644 --- a/library/test/src/term/terminfo/parm.rs +++ b/library/test/src/term/terminfo/parm.rs @@ -1,10 +1,10 @@ //! Parameterized string expansion +use std::iter::repeat; + use self::Param::*; use self::States::*; -use std::iter::repeat; - #[cfg(test)] mod tests; diff --git a/library/test/src/term/terminfo/parser/compiled.rs b/library/test/src/term/terminfo/parser/compiled.rs index 5d40b7988b52d..e687b3be41fbf 100644 --- a/library/test/src/term/terminfo/parser/compiled.rs +++ b/library/test/src/term/terminfo/parser/compiled.rs @@ -2,11 +2,12 @@ //! ncurses-compatible compiled terminfo format parsing (term(5)) -use super::super::TermInfo; use std::collections::HashMap; use std::io; use std::io::prelude::*; +use super::super::TermInfo; + #[cfg(test)] mod tests; diff --git a/library/test/src/term/terminfo/searcher.rs b/library/test/src/term/terminfo/searcher.rs index 3e8ccc91ab051..1b29598cf804e 100644 --- a/library/test/src/term/terminfo/searcher.rs +++ b/library/test/src/term/terminfo/searcher.rs @@ -2,14 +2,13 @@ //! //! Does not support hashed database, only filesystem! -use std::env; -use std::fs; use std::path::PathBuf; +use std::{env, fs}; #[cfg(test)] mod tests; -/// Return path to database entry for `term` +/// Returns path to database entry for `term` #[allow(deprecated)] pub(crate) fn get_dbpath_for_term(term: &str) -> Option { let mut dirs_to_search = Vec::new(); diff --git a/library/test/src/term/win.rs b/library/test/src/term/win.rs index 65764c0ffc1b9..ce9cad37f306b 100644 --- a/library/test/src/term/win.rs +++ b/library/test/src/term/win.rs @@ -5,8 +5,7 @@ use std::io; use std::io::prelude::*; -use super::color; -use super::Terminal; +use super::{color, Terminal}; /// A Terminal implementation that uses the Win32 Console API. pub(crate) struct WinConsole { diff --git a/library/test/src/test_result.rs b/library/test/src/test_result.rs index 98c54f038da6c..c5f4b03bfc96c 100644 --- a/library/test/src/test_result.rs +++ b/library/test/src/test_result.rs @@ -1,16 +1,14 @@ use std::any::Any; -use std::process::ExitStatus; - #[cfg(unix)] use std::os::unix::process::ExitStatusExt; +use std::process::ExitStatus; +pub use self::TestResult::*; use super::bench::BenchSamples; use super::options::ShouldPanic; use super::time; use super::types::TestDesc; -pub use self::TestResult::*; - // Return code for secondary process. // Start somewhere other than 0 so we know the return code means what we think // it means. diff --git a/library/test/src/tests.rs b/library/test/src/tests.rs index 43a906ad298d1..ba2f35362c54f 100644 --- a/library/test/src/tests.rs +++ b/library/test/src/tests.rs @@ -1,5 +1,4 @@ use super::*; - use crate::{ console::OutputLocation, formatters::PrettyFormatter, @@ -237,8 +236,9 @@ fn test_should_panic_bad_message() { #[cfg(not(target_os = "emscripten"))] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn test_should_panic_non_string_message_type() { - use crate::tests::TrFailedMsg; use std::any::TypeId; + + use crate::tests::TrFailedMsg; fn f() -> Result<(), String> { std::panic::panic_any(1i32); } diff --git a/library/test/src/time.rs b/library/test/src/time.rs index 7fd69d7f7e73c..02ae050db55bd 100644 --- a/library/test/src/time.rs +++ b/library/test/src/time.rs @@ -5,10 +5,9 @@ //! - Provide helpers for `report-time` and `measure-time` options. //! - Provide newtypes for executions times. -use std::env; -use std::fmt; use std::str::FromStr; use std::time::{Duration, Instant}; +use std::{env, fmt}; use super::types::{TestDesc, TestType}; @@ -24,9 +23,10 @@ pub const TEST_WARN_TIMEOUT_S: u64 = 60; /// Example of the expected format is `RUST_TEST_TIME_xxx=100,200`, where 100 means /// warn time, and 200 means critical time. pub mod time_constants { - use super::TEST_WARN_TIMEOUT_S; use std::time::Duration; + use super::TEST_WARN_TIMEOUT_S; + /// Environment variable for overriding default threshold for unit-tests. pub const UNIT_ENV_NAME: &str = "RUST_TEST_TIME_UNIT"; diff --git a/library/test/src/types.rs b/library/test/src/types.rs index 6a7035a8e2918..c3be3466cb928 100644 --- a/library/test/src/types.rs +++ b/library/test/src/types.rs @@ -4,15 +4,14 @@ use std::borrow::Cow; use std::fmt; use std::sync::mpsc::Sender; -use super::__rust_begin_short_backtrace; -use super::bench::Bencher; -use super::event::CompletedTest; -use super::options; - pub use NamePadding::*; pub use TestFn::*; pub use TestName::*; +use super::bench::Bencher; +use super::event::CompletedTest; +use super::{__rust_begin_short_backtrace, options}; + /// Type of the test according to the [Rust book](https://doc.rust-lang.org/cargo/guide/tests.html) /// conventions. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] diff --git a/library/unwind/src/lib.rs b/library/unwind/src/lib.rs index 45a1c334a44dd..b3de71f29f394 100644 --- a/library/unwind/src/lib.rs +++ b/library/unwind/src/lib.rs @@ -2,7 +2,6 @@ #![unstable(feature = "panic_unwind", issue = "32837")] #![feature(link_cfg)] #![feature(staged_api)] -#![cfg_attr(bootstrap, feature(c_unwind))] #![feature(strict_provenance)] #![cfg_attr(target_arch = "wasm64", feature(simd_wasm64))] #![cfg_attr(not(target_env = "msvc"), feature(libc))] diff --git a/library/unwind/src/unwinding.rs b/library/unwind/src/unwinding.rs index 083acaeb56af2..b3460791ce5ca 100644 --- a/library/unwind/src/unwinding.rs +++ b/library/unwind/src/unwinding.rs @@ -28,9 +28,7 @@ pub enum _Unwind_Reason_Code { _URC_FAILURE = 9, // used only by ARM EHABI } pub use _Unwind_Reason_Code::*; - -pub use unwinding::abi::UnwindContext; -pub use unwinding::abi::UnwindException; +pub use unwinding::abi::{UnwindContext, UnwindException}; pub enum _Unwind_Context {} pub use unwinding::custom_eh_frame_finder::{ diff --git a/rustfmt.toml b/rustfmt.toml index 8c1d3b94f195b..60cd03484007d 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -2,6 +2,8 @@ version = "Two" use_small_heuristics = "Max" merge_derives = false +group_imports = "StdExternalCrate" +imports_granularity = "Module" # Files to ignore. Each entry uses gitignore syntax, but `!` prefixes aren't allowed. ignore = [ @@ -22,8 +24,6 @@ ignore = [ "/tests/rustdoc-ui/", # Some have syntax errors, some are whitespace-sensitive. "/tests/ui/", # Some have syntax errors, some are whitespace-sensitive. "/tests/ui-fulldeps/", # Some are whitespace-sensitive (e.g. `// ~ERROR` comments). - # #[cfg(bootstrap)] so that t-release sees this when they search for it - "/tests/rustdoc-json/impl-trait-precise-capturing.rs", # Do not format submodules. # FIXME: sync submodule list with tidy/bootstrap/etc diff --git a/src/bootstrap/Cargo.lock b/src/bootstrap/Cargo.lock index de0924c0f4236..60453764d82d3 100644 --- a/src/bootstrap/Cargo.lock +++ b/src/bootstrap/Cargo.lock @@ -65,7 +65,7 @@ dependencies = [ "termcolor", "toml", "walkdir", - "windows", + "windows 0.52.0", "xz2", ] @@ -378,12 +378,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "once_cell" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" - [[package]] name = "opener" version = "0.5.2" @@ -549,16 +543,15 @@ dependencies = [ [[package]] name = "sysinfo" -version = "0.30.5" +version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fb4f3438c8f6389c864e61221cbc97e9bca98b4daf39a5beb7bea660f528bb2" +checksum = "d4115055da5f572fff541dd0c4e61b0262977f453cc9fe04be83aba25a89bdab" dependencies = [ - "cfg-if", "core-foundation-sys", "libc", + "memchr", "ntapi", - "once_cell", - "windows", + "windows 0.57.0", ] [[package]] @@ -655,7 +648,17 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" dependencies = [ - "windows-core", + "windows-core 0.52.0", + "windows-targets", +] + +[[package]] +name = "windows" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143" +dependencies = [ + "windows-core 0.57.0", "windows-targets", ] @@ -668,6 +671,49 @@ dependencies = [ "windows-targets", ] +[[package]] +name = "windows-core" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-result", + "windows-targets", +] + +[[package]] +name = "windows-implement" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-result" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.52.0" @@ -679,13 +725,14 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" +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", @@ -694,45 +741,51 @@ dependencies = [ [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" +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.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "xattr" diff --git a/src/bootstrap/Cargo.toml b/src/bootstrap/Cargo.toml index f723407c3ce31..84262c115b120 100644 --- a/src/bootstrap/Cargo.toml +++ b/src/bootstrap/Cargo.toml @@ -63,7 +63,7 @@ walkdir = "2.4" xz2 = "0.1" # Dependencies needed by the build-metrics feature -sysinfo = { version = "0.30", default-features = false, optional = true } +sysinfo = { version = "0.31.2", default-features = false, optional = true, features = ["system"] } [target.'cfg(windows)'.dependencies.junction] version = "1.0.0" diff --git a/src/bootstrap/src/bin/main.rs b/src/bootstrap/src/bin/main.rs index a7d21ba6ae127..dc8b5487a61e8 100644 --- a/src/bootstrap/src/bin/main.rs +++ b/src/bootstrap/src/bin/main.rs @@ -5,14 +5,10 @@ //! parent directory, and otherwise documentation can be found throughout the `build` //! directory in each respective module. -use std::io::Write; -use std::process; +use std::fs::{self, OpenOptions}; +use std::io::{self, BufRead, BufReader, IsTerminal, Write}; use std::str::FromStr; -use std::{ - env, - fs::{self, OpenOptions}, - io::{self, BufRead, BufReader, IsTerminal}, -}; +use std::{env, process}; use bootstrap::{ find_recent_config_change_ids, human_readable_changes, t, Build, Config, Subcommand, @@ -30,10 +26,7 @@ fn main() { // Display PID of process holding the lock // PID will be stored in a lock file let lock_path = config.out.join("lock"); - let pid = match fs::read_to_string(&lock_path) { - Ok(contents) => contents, - Err(_) => String::new(), - }; + let pid = fs::read_to_string(&lock_path).unwrap_or_default(); build_lock = fd_lock::RwLock::new(t!(fs::OpenOptions::new() .write(true) diff --git a/src/bootstrap/src/bin/rustc.rs b/src/bootstrap/src/bin/rustc.rs index 46e845f77ae1b..011c289d932db 100644 --- a/src/bootstrap/src/bin/rustc.rs +++ b/src/bootstrap/src/bin/rustc.rs @@ -315,12 +315,10 @@ fn format_rusage_data(_child: Child) -> Option { fn format_rusage_data(child: Child) -> Option { use std::os::windows::io::AsRawHandle; - use windows::{ - Win32::Foundation::HANDLE, - Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}, - Win32::System::Threading::GetProcessTimes, - Win32::System::Time::FileTimeToSystemTime, - }; + use windows::Win32::Foundation::HANDLE; + use windows::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows::Win32::System::Threading::GetProcessTimes; + use windows::Win32::System::Time::FileTimeToSystemTime; let handle = HANDLE(child.as_raw_handle() as isize); diff --git a/src/bootstrap/src/core/build_steps/check.rs b/src/bootstrap/src/core/build_steps/check.rs index ed5b9edc86d64..7f7faf077d047 100644 --- a/src/bootstrap/src/core/build_steps/check.rs +++ b/src/bootstrap/src/core/build_steps/check.rs @@ -1,7 +1,9 @@ //! Implementation of compiling the compiler and standard library, in "check"-based modes. +use std::path::PathBuf; + use crate::core::build_steps::compile::{ - add_to_sysroot, run_cargo, rustc_cargo, rustc_cargo_env, std_cargo, + add_to_sysroot, run_cargo, rustc_cargo, rustc_cargo_env, std_cargo, std_crates_for_run_make, }; use crate::core::build_steps::tool::{prepare_tool_cargo, SourceType}; use crate::core::builder::{ @@ -9,17 +11,6 @@ use crate::core::builder::{ }; use crate::core::config::TargetSelection; use crate::{Compiler, Mode, Subcommand}; -use std::path::{Path, PathBuf}; - -pub fn cargo_subcommand(kind: Kind) -> &'static str { - match kind { - Kind::Check - // We ensure check steps for both std and rustc from build_steps/clippy, so handle `Kind::Clippy` as well. - | Kind::Clippy => "check", - Kind::Fix => "fix", - _ => unreachable!(), - } -} #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Std { @@ -30,11 +21,18 @@ pub struct Std { /// /// [`compile::Rustc`]: crate::core::build_steps::compile::Rustc crates: Vec, + /// Override `Builder::kind` on cargo invocations. + /// + /// By default, `Builder::kind` is propagated as the subcommand to the cargo invocations. + /// However, there are cases when this is not desirable. For example, when running `x clippy $tool_name`, + /// passing `Builder::kind` to cargo invocations would run clippy on the entire compiler and library, + /// which is not useful if we only want to lint a few crates with specific rules. + override_build_kind: Option, } impl Std { - pub fn new(target: TargetSelection) -> Self { - Self { target, crates: vec![] } + pub fn new_with_build_kind(target: TargetSelection, kind: Option) -> Self { + Self { target, crates: vec![], override_build_kind: kind } } } @@ -47,12 +45,12 @@ impl Step for Std { } fn make_run(run: RunConfig<'_>) { - let crates = run.make_run_crates(Alias::Library); - run.builder.ensure(Std { target: run.target, crates }); + let crates = std_crates_for_run_make(&run); + run.builder.ensure(Std { target: run.target, crates, override_build_kind: None }); } fn run(self, builder: &Builder<'_>) { - builder.update_submodule(&Path::new("library").join("stdarch")); + builder.require_submodule("library/stdarch", None); let target = self.target; let compiler = builder.compiler(builder.top_stage, builder.config.build); @@ -63,7 +61,7 @@ impl Step for Std { Mode::Std, SourceType::InTree, target, - cargo_subcommand(builder.kind), + self.override_build_kind.unwrap_or(builder.kind), ); std_cargo(builder, target, compiler.stage, &mut cargo); @@ -117,7 +115,7 @@ impl Step for Std { Mode::Std, SourceType::InTree, target, - cargo_subcommand(builder.kind), + self.override_build_kind.unwrap_or(builder.kind), ); // If we're not in stage 0, tests and examples will fail to compile @@ -158,16 +156,31 @@ pub struct Rustc { /// /// [`compile::Rustc`]: crate::core::build_steps::compile::Rustc crates: Vec, + /// Override `Builder::kind` on cargo invocations. + /// + /// By default, `Builder::kind` is propagated as the subcommand to the cargo invocations. + /// However, there are cases when this is not desirable. For example, when running `x clippy $tool_name`, + /// passing `Builder::kind` to cargo invocations would run clippy on the entire compiler and library, + /// which is not useful if we only want to lint a few crates with specific rules. + override_build_kind: Option, } impl Rustc { pub fn new(target: TargetSelection, builder: &Builder<'_>) -> Self { + Self::new_with_build_kind(target, builder, None) + } + + pub fn new_with_build_kind( + target: TargetSelection, + builder: &Builder<'_>, + kind: Option, + ) -> Self { let crates = builder .in_tree_crates("rustc-main", Some(target)) .into_iter() .map(|krate| krate.name.to_string()) .collect(); - Self { target, crates } + Self { target, crates, override_build_kind: kind } } } @@ -182,7 +195,7 @@ impl Step for Rustc { fn make_run(run: RunConfig<'_>) { let crates = run.make_run_crates(Alias::Compiler); - run.builder.ensure(Rustc { target: run.target, crates }); + run.builder.ensure(Rustc { target: run.target, crates, override_build_kind: None }); } /// Builds the compiler. @@ -203,7 +216,7 @@ impl Step for Rustc { builder.ensure(crate::core::build_steps::compile::Std::new(compiler, compiler.host)); builder.ensure(crate::core::build_steps::compile::Std::new(compiler, target)); } else { - builder.ensure(Std::new(target)); + builder.ensure(Std::new_with_build_kind(target, self.override_build_kind)); } let mut cargo = builder::Cargo::new( @@ -212,7 +225,7 @@ impl Step for Rustc { Mode::Rustc, SourceType::InTree, target, - cargo_subcommand(builder.kind), + self.override_build_kind.unwrap_or(builder.kind), ); rustc_cargo(builder, &mut cargo, target, &compiler); @@ -290,7 +303,7 @@ impl Step for CodegenBackend { Mode::Codegen, SourceType::InTree, target, - cargo_subcommand(builder.kind), + builder.kind, ); cargo @@ -348,7 +361,7 @@ impl Step for RustAnalyzer { compiler, Mode::ToolRustc, target, - cargo_subcommand(builder.kind), + builder.kind, "src/tools/rust-analyzer", SourceType::InTree, &["in-rust-tree".to_owned()], @@ -416,7 +429,7 @@ macro_rules! tool_check_step { compiler, Mode::ToolRustc, target, - cargo_subcommand(builder.kind), + builder.kind, $path, $source_type, &[], diff --git a/src/bootstrap/src/core/build_steps/clean.rs b/src/bootstrap/src/core/build_steps/clean.rs index a4be6bc56c50d..4931036718227 100644 --- a/src/bootstrap/src/core/build_steps/clean.rs +++ b/src/bootstrap/src/core/build_steps/clean.rs @@ -11,7 +11,7 @@ use std::path::Path; use crate::core::builder::{crate_description, Builder, RunConfig, ShouldRun, Step}; use crate::utils::helpers::t; -use crate::{Build, Compiler, Mode, Subcommand}; +use crate::{Build, Compiler, Kind, Mode, Subcommand}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct CleanAll {} @@ -66,7 +66,7 @@ macro_rules! clean_crate_tree { fn run(self, builder: &Builder<'_>) -> Self::Output { let compiler = self.compiler; let target = compiler.host; - let mut cargo = builder.bare_cargo(compiler, $mode, target, "clean"); + let mut cargo = builder.bare_cargo(compiler, $mode, target, Kind::Clean); // Since https://github.com/rust-lang/rust/pull/111076 enables // unstable cargo feature (`public-dependency`), we need to ensure diff --git a/src/bootstrap/src/core/build_steps/clippy.rs b/src/bootstrap/src/core/build_steps/clippy.rs index ee7fb368a8c27..4ee9fbc314263 100644 --- a/src/bootstrap/src/core/build_steps/clippy.rs +++ b/src/bootstrap/src/core/build_steps/clippy.rs @@ -1,28 +1,13 @@ //! Implementation of running clippy on the compiler, standard library and various tools. -use std::path::Path; - -use crate::builder::Builder; -use crate::builder::ShouldRun; +use super::compile::{librustc_stamp, libstd_stamp, run_cargo, rustc_cargo, std_cargo}; +use super::tool::{prepare_tool_cargo, SourceType}; +use super::{check, compile}; +use crate::builder::{Builder, ShouldRun}; +use crate::core::build_steps::compile::std_crates_for_run_make; use crate::core::builder; -use crate::core::builder::crate_description; -use crate::core::builder::Alias; -use crate::core::builder::Kind; -use crate::core::builder::RunConfig; -use crate::core::builder::Step; -use crate::Mode; -use crate::Subcommand; -use crate::TargetSelection; - -use super::check; -use super::compile; -use super::compile::librustc_stamp; -use super::compile::libstd_stamp; -use super::compile::run_cargo; -use super::compile::rustc_cargo; -use super::compile::std_cargo; -use super::tool::prepare_tool_cargo; -use super::tool::SourceType; +use crate::core::builder::{crate_description, Alias, Kind, RunConfig, Step}; +use crate::{Mode, Subcommand, TargetSelection}; /// Disable the most spammy clippy lints const IGNORED_RULES_FOR_STD_AND_RUSTC: &[&str] = &[ @@ -122,18 +107,24 @@ impl Step for Std { } fn make_run(run: RunConfig<'_>) { - let crates = run.make_run_crates(Alias::Library); + let crates = std_crates_for_run_make(&run); run.builder.ensure(Std { target: run.target, crates }); } fn run(self, builder: &Builder<'_>) { - builder.update_submodule(&Path::new("library").join("stdarch")); + builder.require_submodule("library/stdarch", None); let target = self.target; let compiler = builder.compiler(builder.top_stage, builder.config.build); - let mut cargo = - builder::Cargo::new(builder, compiler, Mode::Std, SourceType::InTree, target, "clippy"); + let mut cargo = builder::Cargo::new( + builder, + compiler, + Mode::Std, + SourceType::InTree, + target, + Kind::Clippy, + ); std_cargo(builder, target, compiler.stage, &mut cargo); @@ -194,7 +185,7 @@ impl Step for Rustc { builder.ensure(compile::Std::new(compiler, compiler.host)); builder.ensure(compile::Std::new(compiler, target)); } else { - builder.ensure(check::Std::new(target)); + builder.ensure(check::Std::new_with_build_kind(target, Some(Kind::Check))); } let mut cargo = builder::Cargo::new( @@ -203,7 +194,7 @@ impl Step for Rustc { Mode::Rustc, SourceType::InTree, target, - "clippy", + Kind::Clippy, ); rustc_cargo(builder, &mut cargo, target, &compiler); @@ -261,14 +252,14 @@ macro_rules! lint_any { let compiler = builder.compiler(builder.top_stage, builder.config.build); let target = self.target; - builder.ensure(check::Rustc::new(target, builder)); + builder.ensure(check::Rustc::new_with_build_kind(target, builder, Some(Kind::Check))); let cargo = prepare_tool_cargo( builder, compiler, Mode::ToolRustc, target, - "clippy", + Kind::Clippy, $path, SourceType::InTree, &[], diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 9bbebf9b87037..c09180e542ff6 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -8,31 +8,28 @@ use std::borrow::Cow; use std::collections::HashSet; -use std::env; use std::ffi::OsStr; -use std::fs; use std::io::prelude::*; use std::io::BufReader; use std::path::{Path, PathBuf}; use std::process::Stdio; -use std::str; +use std::{env, fs, str}; use serde_derive::Deserialize; -use crate::core::build_steps::dist; -use crate::core::build_steps::llvm; use crate::core::build_steps::tool::SourceType; +use crate::core::build_steps::{dist, llvm}; use crate::core::builder; -use crate::core::builder::crate_description; -use crate::core::builder::Cargo; -use crate::core::builder::{Builder, Kind, PathSet, RunConfig, ShouldRun, Step, TaskPath}; +use crate::core::builder::{ + crate_description, Builder, Cargo, Kind, PathSet, RunConfig, ShouldRun, Step, TaskPath, +}; use crate::core::config::{DebuginfoLevel, LlvmLibunwind, RustcLto, TargetSelection}; use crate::utils::exec::command; use crate::utils::helpers::{ - exe, get_clang_cl_resource_dir, is_debug_info, is_dylib, symlink_dir, t, up_to_date, + self, exe, get_clang_cl_resource_dir, get_closest_merge_base_commit, is_debug_info, is_dylib, + symlink_dir, t, up_to_date, }; -use crate::LLVM_TOOLS; -use crate::{CLang, Compiler, DependencyType, GitRepo, Mode}; +use crate::{CLang, Compiler, DependencyType, GitRepo, Mode, LLVM_TOOLS}; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Std { @@ -118,25 +115,43 @@ impl Step for Std { const DEFAULT: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - // When downloading stage1, the standard library has already been copied to the sysroot, so - // there's no need to rebuild it. - let builder = run.builder; - run.crate_or_deps("sysroot") - .path("library") - .lazy_default_condition(Box::new(|| !builder.download_rustc())) + run.crate_or_deps("sysroot").path("library") } fn make_run(run: RunConfig<'_>) { - // If the paths include "library", build the entire standard library. - let has_alias = - run.paths.iter().any(|set| set.assert_single_path().path.ends_with("library")); - let crates = if has_alias { Default::default() } else { run.cargo_crates_in_set() }; + let crates = std_crates_for_run_make(&run); + let builder = run.builder; + + // Force compilation of the standard library from source if the `library` is modified. This allows + // library team to compile the standard library without needing to compile the compiler with + // the `rust.download-rustc=true` option. + let force_recompile = + if builder.rust_info().is_managed_git_subrepository() && builder.download_rustc() { + let closest_merge_commit = get_closest_merge_base_commit( + Some(&builder.src), + &builder.config.git_config(), + &builder.config.stage0_metadata.config.git_merge_commit_email, + &[], + ) + .unwrap(); + + // Check if `library` has changes (returns false otherwise) + !t!(helpers::git(Some(&builder.src)) + .args(["diff-index", "--quiet", &closest_merge_commit]) + .arg("--") + .arg(builder.src.join("library")) + .as_command_mut() + .status()) + .success() + } else { + false + }; run.builder.ensure(Std { compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()), target: run.target, crates, - force_recompile: false, + force_recompile, extra_rust_args: &[], is_for_mir_opt_tests: false, }); @@ -182,11 +197,16 @@ impl Step for Std { return; } - builder.update_submodule(&Path::new("library").join("stdarch")); + builder.require_submodule("library/stdarch", None); // Profiler information requires LLVM's compiler-rt if builder.config.profiler { - builder.update_submodule(Path::new("src/llvm-project")); + builder.require_submodule( + "src/llvm-project", + Some( + "The `build.profiler` config option requires `compiler-rt` sources from LLVM.", + ), + ); } let mut target_deps = builder.ensure(StartupObjects { compiler, target }); @@ -246,7 +266,7 @@ impl Step for Std { Mode::Std, SourceType::InTree, target, - "check", + Kind::Check, ); cargo.rustflag("-Zalways-encode-mir"); cargo.arg("--manifest-path").arg(builder.src.join("library/sysroot/Cargo.toml")); @@ -258,7 +278,7 @@ impl Step for Std { Mode::Std, SourceType::InTree, target, - "build", + Kind::Build, ); std_cargo(builder, target, compiler.stage, &mut cargo); for krate in &*self.crates { @@ -424,6 +444,28 @@ fn copy_self_contained_objects( target_deps } +/// Resolves standard library crates for `Std::run_make` for any build kind (like check, build, clippy, etc.). +pub fn std_crates_for_run_make(run: &RunConfig<'_>) -> Vec { + // FIXME: Extend builder tests to cover the `crates` field of `Std` instances. + if cfg!(feature = "bootstrap-self-test") { + return vec![]; + } + + let has_alias = run.paths.iter().any(|set| set.assert_single_path().path.ends_with("library")); + let target_is_no_std = run.builder.no_std(run.target).unwrap_or(false); + + // For no_std targets, do not add any additional crates to the compilation other than what `compile::std_cargo` already adds for no_std targets. + if target_is_no_std { + vec![] + } + // If the paths include "library", build the entire standard library. + else if has_alias { + run.make_run_crates(builder::Alias::Library) + } else { + run.cargo_crates_in_set() + } +} + /// Configure cargo to compile the standard library, adding appropriate env vars /// and such. pub fn std_cargo(builder: &Builder<'_>, target: TargetSelection, stage: u32, cargo: &mut Cargo) { @@ -456,13 +498,15 @@ pub fn std_cargo(builder: &Builder<'_>, target: TargetSelection, stage: u32, car // That's probably ok? At least, the difference wasn't enforced before. There's a comment in // the compiler_builtins build script that makes me nervous, though: // https://github.com/rust-lang/compiler-builtins/blob/31ee4544dbe47903ce771270d6e3bea8654e9e50/build.rs#L575-L579 - builder.update_submodule(&Path::new("src").join("llvm-project")); + builder.require_submodule( + "src/llvm-project", + Some( + "The `build.optimized-compiler-builtins` config option \ + requires `compiler-rt` sources from LLVM.", + ), + ); let compiler_builtins_root = builder.src.join("src/llvm-project/compiler-rt"); - if !compiler_builtins_root.exists() { - panic!( - "need LLVM sources available to build `compiler-rt`, but they weren't present; consider enabling `build.submodules = true` or disabling `optimized-compiler-builtins`" - ); - } + assert!(compiler_builtins_root.exists()); // Note that `libprofiler_builtins/build.rs` also computes this so if // you're changing something here please also change that. cargo.env("RUST_COMPILER_RT_ROOT", &compiler_builtins_root); @@ -916,7 +960,7 @@ impl Step for Rustc { Mode::Rustc, SourceType::InTree, target, - "build", + Kind::Build, ); rustc_cargo(builder, &mut cargo, target, &compiler); @@ -1356,7 +1400,7 @@ impl Step for CodegenBackend { Mode::Codegen, SourceType::InTree, target, - "build", + Kind::Build, ); cargo .arg("--manifest-path") @@ -1481,7 +1525,7 @@ pub fn compiler_file( let mut cmd = command(compiler); cmd.args(builder.cflags(target, GitRepo::Rustc, c)); cmd.arg(format!("-print-file-name={file}")); - let out = cmd.capture_stdout().run(builder).stdout(); + let out = cmd.run_capture_stdout(builder).stdout(); PathBuf::from(out.trim()) } @@ -1845,7 +1889,7 @@ impl Step for Assemble { builder.ensure(llvm::Llvm { target: target_compiler.host }); if !builder.config.dry_run() && builder.config.llvm_tools_enabled { let llvm_bin_dir = - command(llvm_config).capture_stdout().arg("--bindir").run(builder).stdout(); + command(llvm_config).arg("--bindir").run_capture_stdout(builder).stdout(); let llvm_bin_dir = Path::new(llvm_bin_dir.trim()); // Since we've already built the LLVM tools, install them to the sysroot. @@ -2171,7 +2215,7 @@ pub fn strip_debug(builder: &Builder<'_>, target: TargetSelection, path: &Path) } let previous_mtime = t!(t!(path.metadata()).modified()); - command("strip").capture().arg("--strip-debug").arg(path).run(builder); + command("strip").arg("--strip-debug").arg(path).run_capture(builder); let file = t!(fs::File::open(path)); diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index 649bcdd873353..c14709ffb6324 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -9,19 +9,17 @@ //! pieces of `rustup.rs`! use std::collections::HashSet; -use std::env; use std::ffi::OsStr; -use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; +use std::{env, fs}; use object::read::archive::ArchiveFile; use object::BinaryFormat; -use crate::core::build_steps::compile; use crate::core::build_steps::doc::DocumentationFormat; -use crate::core::build_steps::llvm; use crate::core::build_steps::tool::{self, Tool}; +use crate::core::build_steps::{compile, llvm}; use crate::core::builder::{Builder, Kind, RunConfig, ShouldRun, Step}; use crate::core::config::TargetSelection; use crate::utils::channel::{self, Info}; @@ -108,7 +106,6 @@ impl Step for JsonDocs { builder.ensure(crate::core::build_steps::doc::Std::new( builder.top_stage, host, - builder, DocumentationFormat::Json, )); @@ -182,7 +179,7 @@ fn make_win_dist( //Ask gcc where it keeps its stuff let mut cmd = command(builder.cc(target)); cmd.arg("-print-search-dirs"); - let gcc_out = cmd.capture_stdout().run(builder).stdout(); + let gcc_out = cmd.run_capture_stdout(builder).stdout(); let mut bin_path: Vec<_> = env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect(); let mut lib_path = Vec::new(); @@ -907,7 +904,7 @@ impl Step for Src { /// Creates the `rust-src` installer component fn run(self, builder: &Builder<'_>) -> GeneratedTarball { if !builder.config.dry_run() { - builder.update_submodule(Path::new("src/llvm-project")); + builder.require_submodule("src/llvm-project", None); } let tarball = Tarball::new_targetless(builder, "rust-src"); @@ -1022,10 +1019,7 @@ impl Step for PlainSourceTarball { // FIXME: This code looks _very_ similar to what we have in `src/core/build_steps/vendor.rs` // perhaps it should be removed in favor of making `dist` perform the `vendor` step? - // Ensure we have all submodules from src and other directories checked out. - for submodule in build_helper::util::parse_gitmodules(&builder.src) { - builder.update_submodule(Path::new(submodule)); - } + builder.require_and_update_all_submodules(); // Vendor all Cargo dependencies let mut cmd = command(&builder.initial_cargo); @@ -1040,6 +1034,8 @@ impl Step for PlainSourceTarball { .arg("--sync") .arg(builder.src.join("./compiler/rustc_codegen_gcc/Cargo.toml")) .arg("--sync") + .arg(builder.src.join("./library/Cargo.toml")) + .arg("--sync") .arg(builder.src.join("./src/bootstrap/Cargo.toml")) .arg("--sync") .arg(builder.src.join("./src/tools/opt-dist/Cargo.toml")) @@ -1067,7 +1063,7 @@ impl Step for PlainSourceTarball { cmd.arg("--sync").arg(manifest_path); } - let config = cmd.capture().run(builder).stdout(); + let config = cmd.run_capture(builder).stdout(); let cargo_config_dir = plain_dst_src.join(".cargo"); builder.create_dir(&cargo_config_dir); @@ -2075,7 +2071,7 @@ fn maybe_install_llvm( let mut cmd = command(llvm_config); cmd.arg("--libfiles"); builder.verbose(|| println!("running {cmd:?}")); - let files = cmd.capture_stdout().run(builder).stdout(); + let files = cmd.run_capture_stdout(builder).stdout(); let build_llvm_out = &builder.llvm_out(builder.config.build); let target_llvm_out = &builder.llvm_out(target); for file in files.trim_end().split(' ') { @@ -2128,8 +2124,13 @@ impl Step for LlvmTools { fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { let default = should_build_extended_tool(run.builder, "llvm-tools"); - // FIXME: allow using the names of the tools themselves? - run.alias("llvm-tools").default_condition(default) + + let mut run = run.alias("llvm-tools"); + for tool in LLVM_TOOLS { + run = run.alias(tool); + } + + run.default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -2137,6 +2138,32 @@ impl Step for LlvmTools { } fn run(self, builder: &Builder<'_>) -> Option { + fn tools_to_install(paths: &[PathBuf]) -> Vec<&'static str> { + let mut tools = vec![]; + + for path in paths { + let path = path.to_str().unwrap(); + + // Include all tools if path is 'llvm-tools'. + if path == "llvm-tools" { + return LLVM_TOOLS.to_owned(); + } + + for tool in LLVM_TOOLS { + if path == *tool { + tools.push(*tool); + } + } + } + + // If no specific tool is requested, include all tools. + if tools.is_empty() { + tools = LLVM_TOOLS.to_owned(); + } + + tools + } + let target = self.target; /* run only if llvm-config isn't used */ @@ -2157,7 +2184,7 @@ impl Step for LlvmTools { // Prepare the image directory let src_bindir = builder.llvm_out(target).join("bin"); let dst_bindir = format!("lib/rustlib/{}/bin", target.triple); - for tool in LLVM_TOOLS { + for tool in tools_to_install(&builder.paths) { let exe = src_bindir.join(exe(tool, target)); tarball.add_file(&exe, &dst_bindir, 0o755); } diff --git a/src/bootstrap/src/core/build_steps/doc.rs b/src/bootstrap/src/core/build_steps/doc.rs index d8204ea00f7b2..2cd5db706c26a 100644 --- a/src/bootstrap/src/core/build_steps/doc.rs +++ b/src/bootstrap/src/core/build_steps/doc.rs @@ -9,14 +9,15 @@ use std::io::{self, Write}; use std::path::{Path, PathBuf}; -use std::{fs, mem}; +use std::{env, fs, mem}; use crate::core::build_steps::compile; use crate::core::build_steps::tool::{self, prepare_tool_cargo, SourceType, Tool}; -use crate::core::builder::{self, crate_description}; -use crate::core::builder::{Alias, Builder, Compiler, Kind, RunConfig, ShouldRun, Step}; +use crate::core::builder::{ + self, crate_description, Alias, Builder, Compiler, Kind, RunConfig, ShouldRun, Step, +}; use crate::core::config::{Config, TargetSelection}; -use crate::utils::helpers::{dir_is_empty, symlink_dir, t, up_to_date}; +use crate::utils::helpers::{symlink_dir, t, up_to_date}; use crate::Mode; macro_rules! submodule_helper { @@ -53,8 +54,8 @@ macro_rules! book { fn run(self, builder: &Builder<'_>) { $( - let path = Path::new(submodule_helper!( $path, submodule $( = $submodule )? )); - builder.update_submodule(&path); + let path = submodule_helper!( $path, submodule $( = $submodule )? ); + builder.require_submodule(path, None); )? builder.ensure(RustbookSrc { target: self.target, @@ -62,6 +63,7 @@ macro_rules! book { src: builder.src.join($path), parent: Some(self), languages: $lang.into(), + rustdoc: None, }) } } @@ -80,7 +82,6 @@ book!( EditionGuide, "src/doc/edition-guide", "edition-guide", &[], submodule; EmbeddedBook, "src/doc/embedded-book", "embedded-book", &[], submodule; Nomicon, "src/doc/nomicon", "nomicon", &[], submodule; - Reference, "src/doc/reference", "reference", &[], submodule; RustByExample, "src/doc/rust-by-example", "rust-by-example", &["ja"], submodule; RustdocBook, "src/doc/rustdoc", "rustdoc", &[]; StyleGuide, "src/doc/style-guide", "style-guide", &[]; @@ -112,6 +113,7 @@ impl Step for UnstableBook { src: builder.md_doc_out(self.target).join("unstable-book"), parent: Some(self), languages: vec![], + rustdoc: None, }) } } @@ -123,6 +125,7 @@ struct RustbookSrc { src: PathBuf, parent: Option

, languages: Vec<&'static str>, + rustdoc: Option, } impl Step for RustbookSrc

{ @@ -153,13 +156,18 @@ impl Step for RustbookSrc

{ builder.info(&format!("Rustbook ({target}) - {name}")); let _ = fs::remove_dir_all(&out); - builder - .tool_cmd(Tool::Rustbook) - .arg("build") - .arg(&src) - .arg("-d") - .arg(&out) - .run(builder); + let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook); + if let Some(mut rustdoc) = self.rustdoc { + rustdoc.pop(); + let old_path = env::var_os("PATH").unwrap_or_default(); + let new_path = + env::join_paths(std::iter::once(rustdoc).chain(env::split_paths(&old_path))) + .expect("could not add rustdoc to PATH"); + + rustbook_cmd.env("PATH", new_path); + } + + rustbook_cmd.arg("build").arg(&src).arg("-d").arg(&out).run(builder); for lang in &self.languages { let out = out.join(lang); @@ -217,22 +225,14 @@ impl Step for TheBook { /// * Index page /// * Redirect pages fn run(self, builder: &Builder<'_>) { - let relative_path = Path::new("src").join("doc").join("book"); - builder.update_submodule(&relative_path); + builder.require_submodule("src/doc/book", None); let compiler = self.compiler; let target = self.target; - let absolute_path = builder.src.join(&relative_path); + let absolute_path = builder.src.join("src/doc/book"); let redirect_path = absolute_path.join("redirects"); - if !absolute_path.exists() - || !redirect_path.exists() - || dir_is_empty(&absolute_path) - || dir_is_empty(&redirect_path) - { - eprintln!("Please checkout submodule: {}", relative_path.display()); - crate::exit!(1); - } + // build book builder.ensure(RustbookSrc { target, @@ -240,6 +240,7 @@ impl Step for TheBook { src: absolute_path.clone(), parent: Some(self), languages: vec![], + rustdoc: None, }); // building older edition redirects @@ -252,6 +253,7 @@ impl Step for TheBook { // treat the other editions as not having a parent. parent: Option::::None, languages: vec![], + rustdoc: None, }); } @@ -562,18 +564,8 @@ pub struct Std { } impl Std { - pub(crate) fn new( - stage: u32, - target: TargetSelection, - builder: &Builder<'_>, - format: DocumentationFormat, - ) -> Self { - let crates = builder - .in_tree_crates("sysroot", Some(target)) - .into_iter() - .map(|krate| krate.name.to_string()) - .collect(); - Std { stage, target, format, crates } + pub(crate) fn new(stage: u32, target: TargetSelection, format: DocumentationFormat) -> Self { + Std { stage, target, format, crates: vec![] } } } @@ -587,6 +579,7 @@ impl Step for Std { } fn make_run(run: RunConfig<'_>) { + let crates = compile::std_crates_for_run_make(&run); run.builder.ensure(Std { stage: run.builder.top_stage, target: run.target, @@ -595,7 +588,7 @@ impl Step for Std { } else { DocumentationFormat::Html }, - crates: run.make_run_crates(Alias::Library), + crates, }); } @@ -606,6 +599,16 @@ impl Step for Std { fn run(self, builder: &Builder<'_>) { let stage = self.stage; let target = self.target; + let crates = if self.crates.is_empty() { + builder + .in_tree_crates("sysroot", Some(target)) + .iter() + .map(|c| c.name.to_string()) + .collect() + } else { + self.crates + }; + let out = match self.format { DocumentationFormat::Html => builder.doc_out(target), DocumentationFormat::Json => builder.json_doc_out(target), @@ -634,7 +637,7 @@ impl Step for Std { extra_args.push("--disable-minification"); } - doc_std(builder, self.format, stage, target, &out, &extra_args, &self.crates); + doc_std(builder, self.format, stage, target, &out, &extra_args, &crates); // Don't open if the format is json if let DocumentationFormat::Json = self.format { @@ -646,7 +649,7 @@ impl Step for Std { let index = out.join("std").join("index.html"); builder.open_in_browser(index); } else { - for requested_crate in &*self.crates { + for requested_crate in crates { if STD_PUBLIC_CRATES.iter().any(|&k| k == requested_crate) { let index = out.join(requested_crate).join("index.html"); builder.open_in_browser(index); @@ -693,13 +696,6 @@ fn doc_std( extra_args: &[&str], requested_crates: &[String], ) { - if builder.no_std(target) == Some(true) { - panic!( - "building std documentation for no_std target {target} is not supported\n\ - Set `docs = false` in the config to disable documentation, or pass `--skip library`." - ); - } - let compiler = builder.compiler(stage, builder.config.build); let target_doc_dir_name = if format == DocumentationFormat::Json { "json-doc" } else { "doc" }; @@ -712,7 +708,7 @@ fn doc_std( let out_dir = target_dir.join(target.triple).join("doc"); let mut cargo = - builder::Cargo::new(builder, compiler, Mode::Std, SourceType::InTree, target, "doc"); + builder::Cargo::new(builder, compiler, Mode::Std, SourceType::InTree, target, Kind::Doc); compile::std_cargo(builder, target, compiler.stage, &mut cargo); cargo @@ -814,8 +810,14 @@ impl Step for Rustc { ); // Build cargo command. - let mut cargo = - builder::Cargo::new(builder, compiler, Mode::Rustc, SourceType::InTree, target, "doc"); + let mut cargo = builder::Cargo::new( + builder, + compiler, + Mode::Rustc, + SourceType::InTree, + target, + Kind::Doc, + ); cargo.rustdocflag("--document-private-items"); // Since we always pass --document-private-items, there's no need to warn about linking to private items. @@ -932,8 +934,8 @@ macro_rules! tool_doc { let _ = source_type; // silence the "unused variable" warning let source_type = SourceType::Submodule; - let path = Path::new(submodule_helper!( $path, submodule $( = $submodule )? )); - builder.update_submodule(&path); + let path = submodule_helper!( $path, submodule $( = $submodule )? ); + builder.require_submodule(path, None); )? let stage = builder.top_stage; @@ -962,7 +964,7 @@ macro_rules! tool_doc { compiler, Mode::ToolRustc, target, - "doc", + Kind::Doc, $path, source_type, &[], @@ -1172,12 +1174,6 @@ impl Step for RustcBook { /// in the "md-doc" directory in the build output directory. Then /// "rustbook" is used to convert it to HTML. fn run(self, builder: &Builder<'_>) { - // These submodules are required to be checked out to build rustbook - // because they have Cargo dependencies that are needed. - #[allow(clippy::single_element_loop)] // This will change soon. - for path in ["src/doc/book"] { - builder.update_submodule(Path::new(path)); - } let out_base = builder.md_doc_out(self.target).join("rustc"); t!(fs::create_dir_all(&out_base)); let out_listing = out_base.join("src/lints"); @@ -1228,6 +1224,50 @@ impl Step for RustcBook { src: out_base, parent: Some(self), languages: vec![], + rustdoc: None, + }); + } +} + +#[derive(Ord, PartialOrd, Debug, Clone, Hash, PartialEq, Eq)] +pub struct Reference { + pub compiler: Compiler, + pub target: TargetSelection, +} + +impl Step for Reference { + type Output = (); + const DEFAULT: bool = true; + + fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { + let builder = run.builder; + run.path("src/doc/reference").default_condition(builder.config.docs) + } + + fn make_run(run: RunConfig<'_>) { + run.builder.ensure(Reference { + compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build), + target: run.target, + }); + } + + /// Builds the reference book. + fn run(self, builder: &Builder<'_>) { + builder.require_submodule("src/doc/reference", None); + + // This is needed for generating links to the standard library using + // the mdbook-spec plugin. + builder.ensure(compile::Std::new(self.compiler, builder.config.build)); + let rustdoc = builder.rustdoc(self.compiler); + + // Run rustbook/mdbook to generate the HTML pages. + builder.ensure(RustbookSrc { + target: self.target, + name: "reference".to_owned(), + src: builder.src.join("src/doc/reference"), + parent: Some(self), + languages: vec![], + rustdoc: Some(rustdoc), }); } } diff --git a/src/bootstrap/src/core/build_steps/format.rs b/src/bootstrap/src/core/build_steps/format.rs index d3ac2bae1e875..8c52df78ab685 100644 --- a/src/bootstrap/src/core/build_steps/format.rs +++ b/src/bootstrap/src/core/build_steps/format.rs @@ -1,17 +1,19 @@ //! Runs rustfmt on the repository. -use crate::core::builder::Builder; -use crate::utils::exec::command; -use crate::utils::helpers::{self, program_out_of_date, t}; -use build_helper::ci::CiEnv; -use build_helper::git::get_git_modified_files; -use ignore::WalkBuilder; use std::collections::VecDeque; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::mpsc::SyncSender; use std::sync::Mutex; +use build_helper::ci::CiEnv; +use build_helper::git::get_git_modified_files; +use ignore::WalkBuilder; + +use crate::core::builder::Builder; +use crate::utils::exec::command; +use crate::utils::helpers::{self, program_out_of_date, t}; + fn rustfmt(src: &Path, rustfmt: &Path, paths: &[PathBuf], check: bool) -> impl FnMut(bool) -> bool { let mut cmd = Command::new(rustfmt); // Avoid the submodule config paths from coming into play. We only allow a single global config @@ -60,7 +62,7 @@ fn get_rustfmt_version(build: &Builder<'_>) -> Option<(String, PathBuf)> { }); cmd.arg("--version"); - let output = cmd.capture().allow_failure().run(build); + let output = cmd.allow_failure().run_capture(build); if output.is_failure() { return None; } @@ -160,25 +162,23 @@ pub fn format(build: &Builder<'_>, check: bool, all: bool, paths: &[PathBuf]) { } } let git_available = - helpers::git(None).capture().allow_failure().arg("--version").run(build).is_success(); + helpers::git(None).allow_failure().arg("--version").run_capture(build).is_success(); let mut adjective = None; if git_available { let in_working_tree = helpers::git(Some(&build.src)) - .capture() .allow_failure() .arg("rev-parse") .arg("--is-inside-work-tree") - .run(build) + .run_capture(build) .is_success(); if in_working_tree { let untracked_paths_output = helpers::git(Some(&build.src)) - .capture_stdout() .arg("status") .arg("--porcelain") .arg("-z") .arg("--untracked-files=normal") - .run(build) + .run_capture_stdout(build) .stdout(); let untracked_paths: Vec<_> = untracked_paths_output .split_terminator('\0') diff --git a/src/bootstrap/src/core/build_steps/install.rs b/src/bootstrap/src/core/build_steps/install.rs index d3e9d6d787564..0ce86eadbce67 100644 --- a/src/bootstrap/src/core/build_steps/install.rs +++ b/src/bootstrap/src/core/build_steps/install.rs @@ -3,9 +3,8 @@ //! This module is responsible for installing the standard library, //! compiler, and documentation. -use std::env; -use std::fs; use std::path::{Component, Path, PathBuf}; +use std::{env, fs}; use crate::core::build_steps::dist; use crate::core::builder::{Builder, RunConfig, ShouldRun, Step}; diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index f234b08f5e2ca..81e591be6997c 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -8,25 +8,24 @@ //! LLVM and compiler-rt are essentially just wired up to everything else to //! ensure that they're always in place if needed. -use std::env; use std::env::consts::EXE_EXTENSION; use std::ffi::{OsStr, OsString}; use std::fs::{self, File}; -use std::io; use std::path::{Path, PathBuf}; use std::sync::OnceLock; +use std::{env, io}; + +use build_helper::ci::CiEnv; use crate::core::builder::{Builder, RunConfig, ShouldRun, Step}; use crate::core::config::{Config, TargetSelection}; use crate::utils::channel; +use crate::utils::exec::command; use crate::utils::helpers::{ self, exe, get_clang_cl_resource_dir, output, t, unhashed_basename, up_to_date, }; use crate::{generate_smart_stamp_hash, CLang, GitRepo, Kind}; -use crate::utils::exec::command; -use build_helper::ci::CiEnv; - #[derive(Clone)] pub struct LlvmResult { /// Path to llvm-config binary. @@ -89,7 +88,7 @@ impl LdFlags { /// if not). pub fn prebuilt_llvm_config(builder: &Builder<'_>, target: TargetSelection) -> LlvmBuildStatus { // If we have llvm submodule initialized already, sync it. - builder.update_existing_submodule(&Path::new("src").join("llvm-project")); + builder.update_existing_submodule("src/llvm-project"); builder.config.maybe_download_ci_llvm(); @@ -110,7 +109,8 @@ pub fn prebuilt_llvm_config(builder: &Builder<'_>, target: TargetSelection) -> L } // Initialize the llvm submodule if not initialized already. - builder.update_submodule(&Path::new("src").join("llvm-project")); + // If submodules are disabled, this does nothing. + builder.update_submodule("src/llvm-project"); let root = "src/llvm-project/llvm"; let out_dir = builder.llvm_out(target); @@ -471,7 +471,7 @@ impl Step for Llvm { builder.ensure(Llvm { target: builder.config.build }); if !builder.config.dry_run() { let llvm_bindir = - command(&llvm_config).capture_stdout().arg("--bindir").run(builder).stdout(); + command(&llvm_config).arg("--bindir").run_capture_stdout(builder).stdout(); let host_bin = Path::new(llvm_bindir.trim()); cfg.define( "LLVM_TABLEGEN", @@ -522,7 +522,7 @@ impl Step for Llvm { // Helper to find the name of LLVM's shared library on darwin and linux. let find_llvm_lib_name = |extension| { let version = - command(&res.llvm_config).capture_stdout().arg("--version").run(builder).stdout(); + command(&res.llvm_config).arg("--version").run_capture_stdout(builder).stdout(); let major = version.split('.').next().unwrap(); match &llvm_version_suffix { @@ -578,7 +578,7 @@ fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) { return; } - let version = command(llvm_config).capture_stdout().arg("--version").run(builder).stdout(); + let version = command(llvm_config).arg("--version").run_capture_stdout(builder).stdout(); let mut parts = version.split('.').take(2).filter_map(|s| s.parse::().ok()); if let (Some(major), Some(_minor)) = (parts.next(), parts.next()) { if major >= 17 { @@ -1197,7 +1197,10 @@ impl Step for CrtBeginEnd { /// Build crtbegin.o/crtend.o for musl target. fn run(self, builder: &Builder<'_>) -> Self::Output { - builder.update_submodule(Path::new("src/llvm-project")); + builder.require_submodule( + "src/llvm-project", + Some("The LLVM sources are required for the CRT from `compiler-rt`."), + ); let out_dir = builder.native_dir(self.target).join("crt"); @@ -1270,7 +1273,10 @@ impl Step for Libunwind { /// Build libunwind.a fn run(self, builder: &Builder<'_>) -> Self::Output { - builder.update_submodule(Path::new("src/llvm-project")); + builder.require_submodule( + "src/llvm-project", + Some("The LLVM sources are required for libunwind."), + ); if builder.config.dry_run() { return PathBuf::new(); diff --git a/src/bootstrap/src/core/build_steps/run.rs b/src/bootstrap/src/core/build_steps/run.rs index 3a2d3f675228d..fde1693646a8b 100644 --- a/src/bootstrap/src/core/build_steps/run.rs +++ b/src/bootstrap/src/core/build_steps/run.rs @@ -8,7 +8,7 @@ use std::path::PathBuf; use crate::core::build_steps::dist::distdir; use crate::core::build_steps::test; use crate::core::build_steps::tool::{self, SourceType, Tool}; -use crate::core::builder::{Builder, RunConfig, ShouldRun, Step}; +use crate::core::builder::{Builder, Kind, RunConfig, ShouldRun, Step}; use crate::core::config::flags::get_completion; use crate::core::config::TargetSelection; use crate::utils::exec::command; @@ -40,7 +40,7 @@ impl Step for BuildManifest { panic!("\n\nfailed to specify `dist.upload-addr` in `config.toml`\n\n") }); - let today = command("date").capture_stdout().arg("+%Y-%m-%d").run(builder).stdout(); + let today = command("date").arg("+%Y-%m-%d").run_capture_stdout(builder).stdout(); cmd.arg(sign); cmd.arg(distdir(builder)); @@ -142,7 +142,7 @@ impl Step for Miri { host_compiler, Mode::ToolRustc, host, - "run", + Kind::Run, "src/tools/miri", SourceType::InTree, &[], diff --git a/src/bootstrap/src/core/build_steps/setup.rs b/src/bootstrap/src/core/build_steps/setup.rs index 226b3729c10ce..8cd9ba5fd146f 100644 --- a/src/bootstrap/src/core/build_steps/setup.rs +++ b/src/bootstrap/src/core/build_steps/setup.rs @@ -5,13 +5,6 @@ //! allows setting up things that cannot be simply captured inside the config.toml, in addition to //! leading people away from manually editing most of the config.toml values. -use crate::core::builder::{Builder, RunConfig, ShouldRun, Step}; -use crate::t; -use crate::utils::change_tracker::CONFIG_CHANGE_HISTORY; -use crate::utils::exec::command; -use crate::utils::helpers::{self, hex_encode}; -use crate::Config; -use sha2::Digest; use std::env::consts::EXE_SUFFIX; use std::fmt::Write as _; use std::fs::File; @@ -20,6 +13,14 @@ use std::path::{Path, PathBuf, MAIN_SEPARATOR_STR}; use std::str::FromStr; use std::{fmt, fs, io}; +use sha2::Digest; + +use crate::core::builder::{Builder, RunConfig, ShouldRun, Step}; +use crate::utils::change_tracker::CONFIG_CHANGE_HISTORY; +use crate::utils::exec::command; +use crate::utils::helpers::{self, hex_encode}; +use crate::{t, Config}; + #[cfg(test)] mod tests; @@ -275,7 +276,7 @@ impl Step for Link { } fn rustup_installed(builder: &Builder<'_>) -> bool { - command("rustup").capture_stdout().arg("--version").run(builder).is_success() + command("rustup").arg("--version").run_capture_stdout(builder).is_success() } fn stage_dir_exists(stage_path: &str) -> bool { @@ -313,10 +314,9 @@ fn attempt_toolchain_link(builder: &Builder<'_>, stage_path: &str) { fn toolchain_is_linked(builder: &Builder<'_>) -> bool { match command("rustup") - .capture_stdout() .allow_failure() .args(["toolchain", "list"]) - .run(builder) + .run_capture_stdout(builder) .stdout_if_ok() { Some(toolchain_list) => { @@ -341,9 +341,8 @@ fn toolchain_is_linked(builder: &Builder<'_>) -> bool { fn try_link_toolchain(builder: &Builder<'_>, stage_path: &str) -> bool { command("rustup") - .capture_stdout() .args(["toolchain", "link", "stage1", stage_path]) - .run(builder) + .run_capture_stdout(builder) .is_success() } @@ -481,9 +480,8 @@ impl Step for Hook { // install a git hook to automatically run tidy, if they want fn install_git_hook_maybe(builder: &Builder<'_>, config: &Config) -> io::Result<()> { let git = helpers::git(Some(&config.src)) - .capture() .args(["rev-parse", "--git-common-dir"]) - .run(builder) + .run_capture(builder) .stdout(); let git = PathBuf::from(git.trim()); let hooks_dir = git.join("hooks"); diff --git a/src/bootstrap/src/core/build_steps/setup/tests.rs b/src/bootstrap/src/core/build_steps/setup/tests.rs index 3e4d66c74546f..3552224f33b56 100644 --- a/src/bootstrap/src/core/build_steps/setup/tests.rs +++ b/src/bootstrap/src/core/build_steps/setup/tests.rs @@ -1,6 +1,7 @@ +use sha2::Digest; + use super::{RUST_ANALYZER_SETTINGS, SETTINGS_HASHES}; use crate::utils::helpers::hex_encode; -use sha2::Digest; #[test] fn check_matching_settings_hash() { diff --git a/src/bootstrap/src/core/build_steps/suggest.rs b/src/bootstrap/src/core/build_steps/suggest.rs index 2d4409d27c65f..8aaffab514d88 100644 --- a/src/bootstrap/src/core/build_steps/suggest.rs +++ b/src/bootstrap/src/core/build_steps/suggest.rs @@ -2,10 +2,11 @@ #![cfg_attr(feature = "build-metrics", allow(unused))] -use clap::Parser; use std::path::PathBuf; use std::str::FromStr; +use clap::Parser; + use crate::core::build_steps::tool::Tool; use crate::core::builder::Builder; @@ -14,10 +15,9 @@ pub fn suggest(builder: &Builder<'_>, run: bool) { let git_config = builder.config.git_config(); let suggestions = builder .tool_cmd(Tool::SuggestTests) - .capture_stdout() .env("SUGGEST_TESTS_GIT_REPOSITORY", git_config.git_repository) .env("SUGGEST_TESTS_NIGHTLY_BRANCH", git_config.nightly_branch) - .run(builder) + .run_capture_stdout(builder) .stdout(); let suggestions = suggestions diff --git a/src/bootstrap/src/core/build_steps/synthetic_targets.rs b/src/bootstrap/src/core/build_steps/synthetic_targets.rs index 021680302cde6..04297c01d10aa 100644 --- a/src/bootstrap/src/core/build_steps/synthetic_targets.rs +++ b/src/bootstrap/src/core/build_steps/synthetic_targets.rs @@ -64,7 +64,7 @@ fn create_synthetic_target( // we cannot use nightly features. So `RUSTC_BOOTSTRAP` is needed here. cmd.env("RUSTC_BOOTSTRAP", "1"); - let output = cmd.capture().run(builder).stdout(); + let output = cmd.run_capture(builder).stdout(); let mut spec: serde_json::Value = serde_json::from_slice(output.as_bytes()).unwrap(); let spec_map = spec.as_object_mut().unwrap(); diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index cc5931c68db1f..c40aa718e7c68 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -3,27 +3,22 @@ //! `./x.py test` (aka [`Kind::Test`]) is currently allowed to reach build steps in other modules. //! However, this contains ~all test parts we expect people to be able to build and run locally. -use std::env; -use std::ffi::OsStr; -use std::ffi::OsString; -use std::fs; -use std::iter; +use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; +use std::{env, fs, iter}; use clap_complete::shells; -use crate::core::build_steps::compile; -use crate::core::build_steps::dist; use crate::core::build_steps::doc::DocumentationFormat; -use crate::core::build_steps::llvm; use crate::core::build_steps::synthetic_targets::MirOptPanicAbortSyntheticTarget; use crate::core::build_steps::tool::{self, SourceType, Tool}; use crate::core::build_steps::toolstate::ToolState; +use crate::core::build_steps::{compile, dist, llvm}; use crate::core::builder; -use crate::core::builder::crate_description; -use crate::core::builder::{Builder, Compiler, Kind, RunConfig, ShouldRun, Step}; -use crate::core::config::flags::get_completion; -use crate::core::config::flags::Subcommand; +use crate::core::builder::{ + crate_description, Builder, Compiler, Kind, RunConfig, ShouldRun, Step, +}; +use crate::core::config::flags::{get_completion, Subcommand}; use crate::core::config::TargetSelection; use crate::utils::exec::{command, BootstrapCommand}; use crate::utils::helpers::{ @@ -73,7 +68,7 @@ impl Step for CrateBootstrap { compiler, Mode::ToolBootstrap, bootstrap_host, - "test", + Kind::Test, path, SourceType::InTree, &[], @@ -124,7 +119,7 @@ You can skip linkcheck with --skip src/tools/linkchecker" compiler, Mode::ToolBootstrap, bootstrap_host, - "test", + Kind::Test, "src/tools/linkchecker", SourceType::InTree, &[], @@ -169,7 +164,7 @@ You can skip linkcheck with --skip src/tools/linkchecker" } fn check_if_tidy_is_installed(builder: &Builder<'_>) -> bool { - command("tidy").capture_stdout().allow_failure().arg("--version").run(builder).is_success() + command("tidy").allow_failure().arg("--version").run_capture_stdout(builder).is_success() } #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -289,7 +284,7 @@ impl Step for Cargo { compiler, Mode::ToolRustc, self.host, - "test", + Kind::Test, "src/tools/cargo", SourceType::Submodule, &[], @@ -360,7 +355,7 @@ impl Step for RustAnalyzer { compiler, Mode::ToolRustc, host, - "test", + Kind::Test, crate_path, SourceType::InTree, &["in-rust-tree".to_owned()], @@ -412,7 +407,7 @@ impl Step for Rustfmt { compiler, Mode::ToolRustc, host, - "test", + Kind::Test, "src/tools/rustfmt", SourceType::InTree, &[], @@ -447,7 +442,7 @@ impl Miri { Mode::Std, SourceType::Submodule, target, - "miri-setup", + Kind::MiriSetup, ); // Tell `cargo miri setup` where to find the sources. @@ -468,7 +463,7 @@ impl Miri { cargo.arg("--print-sysroot"); builder.verbose(|| println!("running: {cargo:?}")); - let stdout = cargo.capture_stdout().run(builder).stdout(); + let stdout = cargo.run_capture_stdout(builder).stdout(); // Output is "\n". let sysroot = stdout.trim_end(); builder.verbose(|| println!("`cargo miri setup --print-sysroot` said: {sysroot:?}")); @@ -532,7 +527,7 @@ impl Step for Miri { host_compiler, Mode::ToolRustc, host, - "test", + Kind::Test, "src/tools/miri", SourceType::InTree, &[], @@ -622,7 +617,7 @@ impl Step for CargoMiri { compiler, Mode::ToolStd, // it's unclear what to use here, we're not building anything just doing a smoke test! target, - "miri-test", + Kind::MiriTest, "src/tools/miri/test-cargo-miri", SourceType::Submodule, &[], @@ -682,7 +677,7 @@ impl Step for CompiletestTest { // when std sources change. Mode::ToolStd, host, - "test", + Kind::Test, "src/tools/compiletest", SourceType::InTree, &[], @@ -732,7 +727,7 @@ impl Step for Clippy { compiler, Mode::ToolRustc, host, - "test", + Kind::Test, "src/tools/clippy", SourceType::InTree, &[], @@ -749,7 +744,7 @@ impl Step for Clippy { let _guard = builder.msg_sysroot_tool(Kind::Test, compiler.stage, "clippy", host, host); // Clippy reports errors if it blessed the outputs - if cargo.allow_failure().run(builder).is_success() { + if cargo.allow_failure().run(builder) { // The tests succeeded; nothing to do. return; } @@ -852,7 +847,6 @@ impl Step for RustdocJSStd { builder.ensure(crate::core::build_steps::doc::Std::new( builder.top_stage, self.target, - builder, DocumentationFormat::Html, )); let _guard = builder.msg( @@ -904,12 +898,12 @@ fn get_browser_ui_test_version_inner( npm: &Path, global: bool, ) -> Option { - let mut command = command(npm).capture(); + let mut command = command(npm); command.arg("list").arg("--parseable").arg("--long").arg("--depth=0"); if global { command.arg("--global"); } - let lines = command.allow_failure().run(builder).stdout(); + let lines = command.allow_failure().run_capture(builder).stdout(); lines .lines() .find_map(|l| l.split(':').nth(1)?.strip_prefix("browser-ui-test@")) @@ -1282,7 +1276,7 @@ impl Step for RunMakeSupport { self.compiler, Mode::ToolStd, self.target, - "build", + Kind::Build, "src/tools/run-make-support", SourceType::InTree, &[], @@ -1326,7 +1320,7 @@ impl Step for CrateRunMakeSupport { compiler, Mode::ToolBootstrap, host, - "test", + Kind::Test, "src/tools/run-make-support", SourceType::InTree, &[], @@ -1372,7 +1366,7 @@ impl Step for CrateBuildHelper { compiler, Mode::ToolBootstrap, host, - "test", + Kind::Test, "src/tools/build_helper", SourceType::InTree, &[], @@ -1846,19 +1840,17 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the let lldb_exe = builder.config.lldb.clone().unwrap_or_else(|| PathBuf::from("lldb")); let lldb_version = command(&lldb_exe) - .capture() .allow_failure() .arg("--version") - .run(builder) + .run_capture(builder) .stdout_if_ok() .and_then(|v| if v.trim().is_empty() { None } else { Some(v) }); if let Some(ref vers) = lldb_version { cmd.arg("--lldb-version").arg(vers); let lldb_python_dir = command(&lldb_exe) .allow_failure() - .capture_stdout() .arg("-P") - .run(builder) + .run_capture_stdout(builder) .stdout_if_ok() .map(|p| p.lines().next().expect("lldb Python dir not found").to_string()); if let Some(ref dir) = lldb_python_dir { @@ -1917,10 +1909,9 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the builder.ensure(llvm::Llvm { target: builder.config.build }); if !builder.config.dry_run() { let llvm_version = - builder.run(command(&llvm_config).capture_stdout().arg("--version")).stdout(); - let llvm_components = builder - .run(command(&llvm_config).capture_stdout().arg("--components")) - .stdout(); + command(&llvm_config).arg("--version").run_capture_stdout(builder).stdout(); + let llvm_components = + command(&llvm_config).arg("--components").run_capture_stdout(builder).stdout(); // Remove trailing newline from llvm-config output. cmd.arg("--llvm-version") .arg(llvm_version.trim()) @@ -1940,7 +1931,7 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the // platform-specific environment variable as a workaround. if !builder.config.dry_run() && suite.ends_with("fulldeps") { let llvm_libdir = - builder.run(command(&llvm_config).capture_stdout().arg("--libdir")).stdout(); + command(&llvm_config).arg("--libdir").run_capture_stdout(builder).stdout(); add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cmd); } @@ -2095,7 +2086,7 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the let git_config = builder.config.git_config(); cmd.arg("--git-repository").arg(git_config.git_repository); cmd.arg("--nightly-branch").arg(git_config.nightly_branch); - cmd.force_coloring_in_ci(builder.ci_env); + cmd.force_coloring_in_ci(); #[cfg(feature = "build-metrics")] builder.metrics.begin_test_suite( @@ -2212,7 +2203,7 @@ impl BookTest { compiler.host, ); let _time = helpers::timeit(builder); - let toolstate = if rustbook_cmd.delay_failure().run(builder).is_success() { + let toolstate = if rustbook_cmd.delay_failure().run(builder) { ToolState::TestPass } else { ToolState::TestFail @@ -2257,7 +2248,12 @@ impl BookTest { } macro_rules! test_book { - ($($name:ident, $path:expr, $book_name:expr, default=$default:expr;)+) => { + ($( + $name:ident, $path:expr, $book_name:expr, + default=$default:expr + $(,submodules = $submodules:expr)? + ; + )+) => { $( #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct $name { @@ -2280,6 +2276,11 @@ macro_rules! test_book { } fn run(self, builder: &Builder<'_>) { + $( + for submodule in $submodules { + builder.require_submodule(submodule, None); + } + )* builder.ensure(BookTest { compiler: self.compiler, path: PathBuf::from($path), @@ -2293,15 +2294,15 @@ macro_rules! test_book { } test_book!( - Nomicon, "src/doc/nomicon", "nomicon", default=false; - Reference, "src/doc/reference", "reference", default=false; + Nomicon, "src/doc/nomicon", "nomicon", default=false, submodules=["src/doc/nomicon"]; + Reference, "src/doc/reference", "reference", default=false, submodules=["src/doc/reference"]; RustdocBook, "src/doc/rustdoc", "rustdoc", default=true; RustcBook, "src/doc/rustc", "rustc", default=true; - RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false; - EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false; - TheBook, "src/doc/book", "book", default=false; + RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false, submodules=["src/doc/rust-by-example"]; + EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false, submodules=["src/doc/embedded-book"]; + TheBook, "src/doc/book", "book", default=false, submodules=["src/doc/book"]; UnstableBook, "src/doc/unstable-book", "unstable-book", default=true; - EditionGuide, "src/doc/edition-guide", "edition-guide", default=false; + EditionGuide, "src/doc/edition-guide", "edition-guide", default=false, submodules=["src/doc/edition-guide"]; ); #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -2345,7 +2346,7 @@ impl Step for ErrorIndex { let guard = builder.msg(Kind::Test, compiler.stage, "error-index", compiler.host, compiler.host); let _time = helpers::timeit(builder); - tool.capture().run(builder); + tool.run_capture(builder); drop(guard); // The tests themselves need to link to std, so make sure it is // available. @@ -2376,9 +2377,10 @@ fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> cmd = cmd.delay_failure(); if !builder.config.verbose_tests { - cmd = cmd.capture(); + cmd.run_capture(builder).is_success() + } else { + cmd.run(builder) } - cmd.run(builder).is_success() } #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -2398,17 +2400,14 @@ impl Step for RustcGuide { } fn run(self, builder: &Builder<'_>) { - let relative_path = Path::new("src").join("doc").join("rustc-dev-guide"); - builder.update_submodule(&relative_path); + let relative_path = "src/doc/rustc-dev-guide"; + builder.require_submodule(relative_path, None); let src = builder.src.join(relative_path); let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook).delay_failure(); rustbook_cmd.arg("linkcheck").arg(&src); - let toolstate = if rustbook_cmd.run(builder).is_success() { - ToolState::TestPass - } else { - ToolState::TestFail - }; + let toolstate = + if rustbook_cmd.run(builder) { ToolState::TestPass } else { ToolState::TestFail }; builder.save_toolstate("rustc-dev-guide", toolstate); } } @@ -2631,7 +2630,7 @@ impl Step for Crate { mode, SourceType::InTree, target, - "miri-test", + Kind::MiriTest, ); // This hack helps bootstrap run standard library tests in Miri. The issue is as // follows: when running `cargo miri test` on libcore, cargo builds a local copy of core @@ -2654,14 +2653,7 @@ impl Step for Crate { } // Build `cargo test` command - builder::Cargo::new( - builder, - compiler, - mode, - SourceType::InTree, - target, - builder.kind.as_str(), - ) + builder::Cargo::new(builder, compiler, mode, SourceType::InTree, target, builder.kind) }; match mode { @@ -2753,7 +2745,7 @@ impl Step for CrateRustdoc { compiler, Mode::ToolRustc, target, - builder.kind.as_str(), + builder.kind, "src/tools/rustdoc", SourceType::InTree, &[], @@ -2845,7 +2837,7 @@ impl Step for CrateRustdocJsonTypes { compiler, Mode::ToolRustc, target, - builder.kind.as_str(), + builder.kind, "src/rustdoc-json-types", SourceType::InTree, &[], @@ -2920,7 +2912,7 @@ impl Step for RemoteCopyLibs { let f = t!(f); let name = f.file_name().into_string().unwrap(); if helpers::is_dylib(&name) { - builder.run(command(&tool).arg("push").arg(f.path())); + command(&tool).arg("push").arg(f.path()).run(builder); } } } @@ -2951,21 +2943,21 @@ impl Step for Distcheck { builder.ensure(dist::PlainSourceTarball); builder.ensure(dist::Src); - let mut cmd = command("tar"); - cmd.arg("-xf") + command("tar") + .arg("-xf") .arg(builder.ensure(dist::PlainSourceTarball).tarball()) .arg("--strip-components=1") - .current_dir(&dir); - cmd.run(builder); - builder.run( - command("./configure") - .args(&builder.config.configure_args) - .arg("--enable-vendor") - .current_dir(&dir), - ); - builder.run( - command(helpers::make(&builder.config.build.triple)).arg("check").current_dir(&dir), - ); + .current_dir(&dir) + .run(builder); + command("./configure") + .args(&builder.config.configure_args) + .arg("--enable-vendor") + .current_dir(&dir) + .run(builder); + command(helpers::make(&builder.config.build.triple)) + .arg("check") + .current_dir(&dir) + .run(builder); // Now make sure that rust-src has all of libstd's dependencies builder.info("Distcheck rust-src"); @@ -2973,24 +2965,23 @@ impl Step for Distcheck { let _ = fs::remove_dir_all(&dir); t!(fs::create_dir_all(&dir)); - let mut cmd = command("tar"); - cmd.arg("-xf") + command("tar") + .arg("-xf") .arg(builder.ensure(dist::Src).tarball()) .arg("--strip-components=1") - .current_dir(&dir); - cmd.run(builder); + .current_dir(&dir) + .run(builder); let toml = dir.join("rust-src/lib/rustlib/src/rust/library/std/Cargo.toml"); - builder.run( - command(&builder.initial_cargo) - // Will read the libstd Cargo.toml - // which uses the unstable `public-dependency` feature. - .env("RUSTC_BOOTSTRAP", "1") - .arg("generate-lockfile") - .arg("--manifest-path") - .arg(&toml) - .current_dir(&dir), - ); + command(&builder.initial_cargo) + // Will read the libstd Cargo.toml + // which uses the unstable `public-dependency` feature. + .env("RUSTC_BOOTSTRAP", "1") + .arg("generate-lockfile") + .arg("--manifest-path") + .arg(&toml) + .current_dir(&dir) + .run(builder); } } @@ -3009,7 +3000,7 @@ impl Step for Bootstrap { let _guard = builder.msg(Kind::Test, 0, "bootstrap", host, host); // Some tests require cargo submodule to be present. - builder.build.update_submodule(Path::new("src/tools/cargo")); + builder.build.require_submodule("src/tools/cargo", None); let mut check_bootstrap = command(builder.python()); check_bootstrap @@ -3080,7 +3071,7 @@ impl Step for TierCheck { self.compiler, Mode::ToolStd, self.compiler.host, - "run", + Kind::Run, "src/tools/tier-check", SourceType::InTree, &[], @@ -3152,7 +3143,7 @@ impl Step for RustInstaller { compiler, Mode::ToolBootstrap, bootstrap_host, - "test", + Kind::Test, "src/tools/rust-installer", SourceType::InTree, &[], @@ -3322,7 +3313,7 @@ impl Step for CodegenCranelift { Mode::Codegen, // Must be codegen to ensure dlopen on compiled dylibs works SourceType::InTree, target, - "run", + Kind::Run, ); cargo.current_dir(&builder.src.join("compiler/rustc_codegen_cranelift")); @@ -3454,7 +3445,7 @@ impl Step for CodegenGCC { Mode::Codegen, // Must be codegen to ensure dlopen on compiled dylibs works SourceType::InTree, target, - "run", + Kind::Run, ); cargo.current_dir(&builder.src.join("compiler/rustc_codegen_gcc")); @@ -3542,7 +3533,7 @@ impl Step for TestFloatParse { compiler, Mode::ToolStd, bootstrap_host, - "test", + Kind::Test, path, SourceType::InTree, &[], @@ -3565,7 +3556,7 @@ impl Step for TestFloatParse { compiler, Mode::ToolStd, bootstrap_host, - "run", + Kind::Run, path, SourceType::InTree, &[], diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 087df2f8a88e2..4d573b107b587 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -1,6 +1,5 @@ -use std::env; -use std::fs; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; +use std::{env, fs}; use crate::core::build_steps::compile; use crate::core::build_steps::toolstate::ToolState; @@ -10,9 +9,7 @@ use crate::core::config::TargetSelection; use crate::utils::channel::GitInfo; use crate::utils::exec::{command, BootstrapCommand}; use crate::utils::helpers::{add_dylib_path, exe, get_closest_merge_base_commit, git, t}; -use crate::Compiler; -use crate::Mode; -use crate::{gha, Kind}; +use crate::{gha, Compiler, Kind, Mode}; #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub enum SourceType { @@ -93,7 +90,7 @@ impl Step for ToolBuild { compiler, self.mode, target, - "build", + Kind::Build, path, self.source_type, &self.extra_features, @@ -139,12 +136,12 @@ pub fn prepare_tool_cargo( compiler: Compiler, mode: Mode, target: TargetSelection, - command: &'static str, + cmd_kind: Kind, path: &str, source_type: SourceType, extra_features: &[String], ) -> CargoCommand { - let mut cargo = builder::Cargo::new(builder, compiler, mode, source_type, target, command); + let mut cargo = builder::Cargo::new(builder, compiler, mode, source_type, target, cmd_kind); let dir = builder.src.join(path); cargo.arg("--manifest-path").arg(dir.join("Cargo.toml")); @@ -241,6 +238,7 @@ macro_rules! bootstrap_tool { $(,is_external_tool = $external:expr)* $(,is_unstable_tool = $unstable:expr)* $(,allow_features = $allow_features:expr)? + $(,submodules = $submodules:expr)? ; )+) => { #[derive(PartialEq, Eq, Clone)] @@ -287,6 +285,11 @@ macro_rules! bootstrap_tool { } fn run(self, builder: &Builder<'_>) -> PathBuf { + $( + for submodule in $submodules { + builder.require_submodule(submodule, None); + } + )* builder.ensure(ToolBuild { compiler: self.compiler, target: self.target, @@ -314,7 +317,7 @@ macro_rules! bootstrap_tool { } bootstrap_tool!( - Rustbook, "src/tools/rustbook", "rustbook"; + Rustbook, "src/tools/rustbook", "rustbook", submodules = SUBMODULES_FOR_RUSTBOOK; UnstableBookGen, "src/tools/unstable-book-gen", "unstable-book-gen"; Tidy, "src/tools/tidy", "tidy"; Linkchecker, "src/tools/linkchecker", "linkchecker"; @@ -340,6 +343,10 @@ bootstrap_tool!( WasmComponentLd, "src/tools/wasm-component-ld", "wasm-component-ld", is_unstable_tool = true, allow_features = "min_specialization"; ); +/// These are the submodules that are required for rustbook to work due to +/// depending on mdbook plugins. +pub static SUBMODULES_FOR_RUSTBOOK: &[&str] = &["src/doc/book", "src/doc/reference"]; + #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct OptimizedDist { pub compiler: Compiler, @@ -363,7 +370,7 @@ impl Step for OptimizedDist { fn run(self, builder: &Builder<'_>) -> PathBuf { // We need to ensure the rustc-perf submodule is initialized when building opt-dist since // the tool requires it to be in place to run. - builder.update_submodule(Path::new("src/tools/rustc-perf")); + builder.require_submodule("src/tools/rustc-perf", None); builder.ensure(ToolBuild { compiler: self.compiler, @@ -404,7 +411,7 @@ impl Step for RustcPerf { fn run(self, builder: &Builder<'_>) -> PathBuf { // We need to ensure the rustc-perf submodule is initialized. - builder.update_submodule(Path::new("src/tools/rustc-perf")); + builder.require_submodule("src/tools/rustc-perf", None); let tool = ToolBuild { compiler: self.compiler, @@ -589,8 +596,7 @@ impl Step for Rustdoc { .arg("--") .arg(librustdoc_src) .arg(rustdoc_src) - .run(builder) - .is_success(); + .run(builder); if !has_changes { let precompiled_rustdoc = builder @@ -640,7 +646,7 @@ impl Step for Rustdoc { build_compiler, Mode::ToolRustc, target, - "build", + Kind::Build, "src/tools/rustdoc", SourceType::InTree, features.as_slice(), @@ -705,7 +711,7 @@ impl Step for Cargo { } fn run(self, builder: &Builder<'_>) -> PathBuf { - builder.build.update_submodule(Path::new("src/tools/cargo")); + builder.build.require_submodule("src/tools/cargo", None); builder.ensure(ToolBuild { compiler: self.compiler, @@ -899,7 +905,7 @@ impl Step for LlvmBitcodeLinker { self.compiler, Mode::ToolRustc, self.target, - "build", + Kind::Build, "src/tools/llvm-bitcode-linker", SourceType::InTree, &self.extra_features, @@ -982,7 +988,7 @@ impl Step for LibcxxVersionTool { } } - let version_output = command(executable).capture_stdout().run(builder).stdout(); + let version_output = command(executable).run_capture_stdout(builder).stdout(); let version_str = version_output.split_once("version:").unwrap().1; let version = version_str.trim().parse::().unwrap(); @@ -1087,8 +1093,6 @@ macro_rules! tool_extended { // NOTE: tools need to be also added to `Builder::get_step_descriptions` in `builder.rs` // to make `./x.py build ` work. -// NOTE: Most submodule updates for tools are handled by bootstrap.py, since they're needed just to -// invoke Cargo to build bootstrap. See the comment there for more details. tool_extended!((self, builder), Cargofmt, "src/tools/rustfmt", "cargo-fmt", stable=true; CargoClippy, "src/tools/clippy", "cargo-clippy", stable=true; diff --git a/src/bootstrap/src/core/build_steps/toolstate.rs b/src/bootstrap/src/core/build_steps/toolstate.rs index 2ab0ce7454b17..b73961062f684 100644 --- a/src/bootstrap/src/core/build_steps/toolstate.rs +++ b/src/bootstrap/src/core/build_steps/toolstate.rs @@ -4,16 +4,15 @@ //! //! [Toolstate]: https://forge.rust-lang.org/infra/toolstate.html -use crate::core::builder::{Builder, RunConfig, ShouldRun, Step}; -use crate::utils::helpers::{self, t}; -use serde_derive::{Deserialize, Serialize}; use std::collections::HashMap; -use std::env; -use std::fmt; -use std::fs; use std::io::{Seek, SeekFrom}; use std::path::{Path, PathBuf}; -use std::time; +use std::{env, fmt, fs, time}; + +use serde_derive::{Deserialize, Serialize}; + +use crate::core::builder::{Builder, RunConfig, ShouldRun, Step}; +use crate::utils::helpers::{self, t}; // Each cycle is 42 days long (6 weeks); the last week is 35..=42 then. const BETA_WEEK_START: u64 = 35; @@ -102,12 +101,11 @@ fn print_error(tool: &str, submodule: &str) { fn check_changed_files(builder: &Builder<'_>, toolstates: &HashMap, ToolState>) { // Changed files let output = helpers::git(None) - .capture() .arg("diff") .arg("--name-status") .arg("HEAD") .arg("HEAD^") - .run(builder) + .run_capture(builder) .stdout(); for (tool, submodule) in STABLE_TOOLS.iter().chain(NIGHTLY_TOOLS.iter()) { @@ -391,7 +389,7 @@ fn commit_toolstate_change(builder: &Builder<'_>, current_toolstate: &ToolstateD .arg("-m") .arg(&message) .run(builder); - if !status.is_success() { + if !status { success = true; break; } @@ -403,7 +401,7 @@ fn commit_toolstate_change(builder: &Builder<'_>, current_toolstate: &ToolstateD .arg("master") .run(builder); // If we successfully push, exit. - if status.is_success() { + if status { success = true; break; } @@ -432,7 +430,7 @@ fn commit_toolstate_change(builder: &Builder<'_>, current_toolstate: &ToolstateD /// `publish_toolstate.py` script if the PR passes all tests and is merged to /// master. fn publish_test_results(builder: &Builder<'_>, current_toolstate: &ToolstateData) { - let commit = helpers::git(None).capture().arg("rev-parse").arg("HEAD").run(builder).stdout(); + let commit = helpers::git(None).arg("rev-parse").arg("HEAD").run_capture(builder).stdout(); let toolstate_serialized = t!(serde_json::to_string(¤t_toolstate)); diff --git a/src/bootstrap/src/core/build_steps/vendor.rs b/src/bootstrap/src/core/build_steps/vendor.rs index e6b3cb320cf16..33768465225fe 100644 --- a/src/bootstrap/src/core/build_steps/vendor.rs +++ b/src/bootstrap/src/core/build_steps/vendor.rs @@ -1,6 +1,8 @@ +use std::path::PathBuf; + +use crate::core::build_steps::tool::SUBMODULES_FOR_RUSTBOOK; use crate::core::builder::{Builder, RunConfig, ShouldRun, Step}; use crate::utils::exec::command; -use std::path::{Path, PathBuf}; #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub(crate) struct Vendor { @@ -35,8 +37,8 @@ impl Step for Vendor { } // These submodules must be present for `x vendor` to work. - for path in ["src/tools/cargo", "src/doc/book"] { - builder.build.update_submodule(Path::new(path)); + for submodule in SUBMODULES_FOR_RUSTBOOK.iter().chain(["src/tools/cargo"].iter()) { + builder.build.require_submodule(submodule, None); } // Sync these paths by default. @@ -45,6 +47,7 @@ impl Step for Vendor { "src/tools/rust-analyzer/Cargo.toml", "compiler/rustc_codegen_cranelift/Cargo.toml", "compiler/rustc_codegen_gcc/Cargo.toml", + "library/Cargo.toml", "src/bootstrap/Cargo.toml", "src/tools/rustbook/Cargo.toml", ] { diff --git a/src/bootstrap/src/core/builder.rs b/src/bootstrap/src/core/builder.rs index 78fbea2e8107c..84c23c059e97e 100644 --- a/src/bootstrap/src/core/builder.rs +++ b/src/bootstrap/src/core/builder.rs @@ -1,15 +1,16 @@ use std::any::{type_name, Any}; use std::cell::{Cell, RefCell}; use std::collections::BTreeSet; -use std::env; use std::ffi::{OsStr, OsString}; use std::fmt::{Debug, Write}; -use std::fs; use std::hash::Hash; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::sync::LazyLock; use std::time::{Duration, Instant}; +use std::{env, fs}; + +use clap::ValueEnum; use crate::core::build_steps::tool::{self, SourceType}; use crate::core::build_steps::{ @@ -17,17 +18,16 @@ use crate::core::build_steps::{ }; use crate::core::config::flags::{Color, Subcommand}; use crate::core::config::{DryRun, SplitDebuginfo, TargetSelection}; -use crate::prepare_behaviour_dump_dir; use crate::utils::cache::Cache; -use crate::utils::helpers::{self, add_dylib_path, add_link_lib_path, exe, linker_args}; -use crate::utils::helpers::{check_cfg_arg, libdir, linker_flags, t, LldThreads}; -use crate::EXTRA_CHECK_CFGS; -use crate::{Build, CLang, Crate, DocTests, GitRepo, Mode}; - use crate::utils::exec::{command, BootstrapCommand}; +use crate::utils::helpers::{ + self, add_dylib_path, add_link_lib_path, check_cfg_arg, exe, libdir, linker_args, linker_flags, + t, LldThreads, +}; pub use crate::Compiler; - -use clap::ValueEnum; +use crate::{ + prepare_behaviour_dump_dir, Build, CLang, Crate, DocTests, GitRepo, Mode, EXTRA_CHECK_CFGS, +}; #[cfg(test)] mod tests; @@ -689,7 +689,7 @@ impl<'a> ShouldRun<'a> { } } -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] +#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, ValueEnum)] pub enum Kind { #[value(alias = "b")] Build, @@ -701,6 +701,8 @@ pub enum Kind { #[value(alias = "t")] Test, Miri, + MiriSetup, + MiriTest, Bench, #[value(alias = "d")] Doc, @@ -725,6 +727,8 @@ impl Kind { Kind::Format => "fmt", Kind::Test => "test", Kind::Miri => "miri", + Kind::MiriSetup => panic!("`as_str` is not supported for `Kind::MiriSetup`."), + Kind::MiriTest => panic!("`as_str` is not supported for `Kind::MiriTest`."), Kind::Bench => "bench", Kind::Doc => "doc", Kind::Clean => "clean", @@ -1000,6 +1004,7 @@ impl<'a> Builder<'a> { Kind::Vendor => describe!(vendor::Vendor), // special-cased in Build::build() Kind::Format | Kind::Suggest | Kind::Perf => vec![], + Kind::MiriTest | Kind::MiriSetup => unreachable!(), } } @@ -1386,23 +1391,30 @@ impl<'a> Builder<'a> { compiler: Compiler, mode: Mode, target: TargetSelection, - cmd: &str, // FIXME make this properly typed + cmd_kind: Kind, ) -> BootstrapCommand { - let mut cargo; - if cmd == "clippy" { - cargo = self.cargo_clippy_cmd(compiler); - cargo.arg(cmd); - } else if let Some(subcmd) = cmd.strip_prefix("miri") { - // Command must be "miri-X". - let subcmd = subcmd - .strip_prefix('-') - .unwrap_or_else(|| panic!("expected `miri-$subcommand`, but got {}", cmd)); - cargo = self.cargo_miri_cmd(compiler); - cargo.arg("miri").arg(subcmd); - } else { - cargo = command(&self.initial_cargo); - cargo.arg(cmd); - } + let mut cargo = match cmd_kind { + Kind::Clippy => { + let mut cargo = self.cargo_clippy_cmd(compiler); + cargo.arg(cmd_kind.as_str()); + cargo + } + Kind::MiriSetup => { + let mut cargo = self.cargo_miri_cmd(compiler); + cargo.arg("miri").arg("setup"); + cargo + } + Kind::MiriTest => { + let mut cargo = self.cargo_miri_cmd(compiler); + cargo.arg("miri").arg("test"); + cargo + } + _ => { + let mut cargo = command(&self.initial_cargo); + cargo.arg(cmd_kind.as_str()); + cargo + } + }; // Run cargo from the source root so it can find .cargo/config. // This matters when using vendoring and the working directory is outside the repository. @@ -1431,7 +1443,7 @@ impl<'a> Builder<'a> { Color::Auto => {} // nothing to do } - if cmd != "install" { + if cmd_kind != Kind::Install { cargo.arg("--target").arg(target.rustc_target_arg()); } else { assert_eq!(target, compiler.host); @@ -1440,8 +1452,11 @@ impl<'a> Builder<'a> { if self.config.rust_optimize.is_release() { // FIXME: cargo bench/install do not accept `--release` // and miri doesn't want it - if cmd != "bench" && cmd != "install" && !cmd.starts_with("miri-") { - cargo.arg("--release"); + match cmd_kind { + Kind::Bench | Kind::Install | Kind::Miri | Kind::MiriSetup | Kind::MiriTest => {} + _ => { + cargo.arg("--release"); + } } } @@ -1464,9 +1479,9 @@ impl<'a> Builder<'a> { mode: Mode, source_type: SourceType, target: TargetSelection, - cmd: &str, // FIXME make this properly typed + cmd_kind: Kind, ) -> Cargo { - let mut cargo = self.bare_cargo(compiler, mode, target, cmd); + let mut cargo = self.bare_cargo(compiler, mode, target, cmd_kind); let out_dir = self.stage_out(compiler, mode); let mut hostflags = HostFlags::default(); @@ -1477,7 +1492,7 @@ impl<'a> Builder<'a> { self.clear_if_dirty(&out_dir, &backend); } - if cmd == "doc" || cmd == "rustdoc" { + if cmd_kind == Kind::Doc { let my_out = match mode { // This is the intended out directory for compiler documentation. Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target), @@ -1508,7 +1523,7 @@ impl<'a> Builder<'a> { // Set a flag for `check`/`clippy`/`fix`, so that certain build // scripts can do less work (i.e. not building/requiring LLVM). - if cmd == "check" || cmd == "clippy" || cmd == "fix" { + if matches!(cmd_kind, Kind::Check | Kind::Clippy | Kind::Fix) { // If we've not yet built LLVM, or it's stale, then bust // the rustc_llvm cache. That will always work, even though it // may mean that on the next non-check build we'll need to rebuild @@ -1558,7 +1573,7 @@ impl<'a> Builder<'a> { rustflags.arg("--cfg=bootstrap"); } - if cmd == "clippy" { + if cmd_kind == Kind::Clippy { // clippy overwrites sysroot if we pass it to cargo. // Pass it directly to clippy instead. // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`, @@ -1654,7 +1669,7 @@ impl<'a> Builder<'a> { Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {} Mode::Rustc | Mode::Codegen | Mode::ToolRustc => { // Build proc macros both for the host and the target - if target != compiler.host && cmd != "check" { + if target != compiler.host && cmd_kind != Kind::Check { cargo.arg("-Zdual-proc-macros"); rustflags.arg("-Zdual-proc-macros"); } @@ -1739,7 +1754,7 @@ impl<'a> Builder<'a> { } cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata); - if cmd == "clippy" { + if cmd_kind == Kind::Clippy { rustflags.arg("-Zforce-unstable-if-unmarked"); } @@ -1755,10 +1770,15 @@ impl<'a> Builder<'a> { // // Only clear out the directory if we're compiling std; otherwise, we // should let Cargo take care of things for us (via depdep info) - if !self.config.dry_run() && mode == Mode::Std && cmd == "build" { + if !self.config.dry_run() && mode == Mode::Std && cmd_kind == Kind::Build { self.clear_if_dirty(&out_dir, &self.rustc(compiler)); } + let rustdoc_path = match cmd_kind { + Kind::Doc | Kind::Test | Kind::MiriTest => self.rustdoc(compiler), + _ => PathBuf::from("/path/to/nowhere/rustdoc/not/required"), + }; + // Customize the compiler we're running. Specify the compiler to cargo // as our shim and then pass it some various options used to configure // how the actual compiler itself is called. @@ -1772,15 +1792,7 @@ impl<'a> Builder<'a> { .env("RUSTC_SYSROOT", sysroot) .env("RUSTC_LIBDIR", libdir) .env("RUSTDOC", self.bootstrap_out.join("rustdoc")) - .env( - "RUSTDOC_REAL", - // Make sure to handle both `test` and `miri-test` commands. - if cmd == "doc" || cmd == "rustdoc" || (cmd.ends_with("test") && want_rustdoc) { - self.rustdoc(compiler) - } else { - PathBuf::from("/path/to/nowhere/rustdoc/not/required") - }, - ) + .env("RUSTDOC_REAL", rustdoc_path) .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir()) .env("RUSTC_BREAK_ON_ICE", "1"); @@ -1799,7 +1811,7 @@ impl<'a> Builder<'a> { } // If this is for `miri-test`, prepare the sysroots. - if cmd == "miri-test" { + if cmd_kind == Kind::MiriTest { self.ensure(compile::Std::new(compiler, compiler.host)); let host_sysroot = self.sysroot(compiler); let miri_sysroot = test::Miri::build_miri_sysroot(self, compiler, target); @@ -1813,7 +1825,8 @@ impl<'a> Builder<'a> { rustflags.arg(&format!("-Zstack-protector={stack_protector}")); } - if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc { + if !matches!(cmd_kind, Kind::Build | Kind::Check | Kind::Clippy | Kind::Fix) && want_rustdoc + { cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler)); } @@ -1954,7 +1967,7 @@ impl<'a> Builder<'a> { if mode == Mode::ToolRustc || mode == Mode::Codegen { if let Some(llvm_config) = self.llvm_config(target) { let llvm_libdir = - command(llvm_config).capture_stdout().arg("--libdir").run(self).stdout(); + command(llvm_config).arg("--libdir").run_capture_stdout(self).stdout(); add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo); } } @@ -2144,7 +2157,7 @@ impl<'a> Builder<'a> { // Try to use a sysroot-relative bindir, in case it was configured absolutely. cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative()); - cargo.force_coloring_in_ci(self.ci_env); + cargo.force_coloring_in_ci(); // When we build Rust dylibs they're all intended for intermediate // usage, so make sure we pass the -Cprefer-dynamic flag instead of @@ -2430,9 +2443,9 @@ impl Cargo { mode: Mode, source_type: SourceType, target: TargetSelection, - cmd: &str, // FIXME make this properly typed + cmd_kind: Kind, ) -> Cargo { - let mut cargo = builder.cargo(compiler, mode, source_type, target, cmd); + let mut cargo = builder.cargo(compiler, mode, source_type, target, cmd_kind); cargo.configure_linker(builder); cargo } @@ -2448,9 +2461,9 @@ impl Cargo { mode: Mode, source_type: SourceType, target: TargetSelection, - cmd: &str, // FIXME make this properly typed + cmd_kind: Kind, ) -> Cargo { - builder.cargo(compiler, mode, source_type, target, cmd) + builder.cargo(compiler, mode, source_type, target, cmd_kind) } pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo { diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 97c9ece0036ea..f19a4dd6d490f 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1,7 +1,8 @@ +use std::thread; + use super::*; use crate::core::build_steps::doc::DocumentationFormat; use crate::core::config::Config; -use std::thread; fn configure(cmd: &str, host: &[&str], target: &[&str]) -> Config { configure_with_args(&[cmd.to_owned()], host, target) @@ -13,15 +14,18 @@ fn configure_with_args(cmd: &[String], host: &[&str], target: &[&str]) -> Config config.save_toolstates = None; config.dry_run = DryRun::SelfCheck; - // Ignore most submodules, since we don't need them for a dry run. - // But make sure to check out the `doc` and `rust-analyzer` submodules, since some steps need them - // just to know which commands to run. + // Ignore most submodules, since we don't need them for a dry run, and the + // tests run much faster without them. + // + // The src/doc/book submodule is needed because TheBook step tries to + // access files even during a dry-run (may want to consider just skipping + // that in a dry run). let submodule_build = Build::new(Config { // don't include LLVM, so CI doesn't require ninja/cmake to be installed rust_codegen_backends: vec![], ..Config::parse(&["check".to_owned()]) }); - submodule_build.update_submodule(Path::new("src/doc/book")); + submodule_build.require_submodule("src/doc/book", None); config.submodules = Some(false); config.ninja_in_file = false; @@ -75,13 +79,9 @@ macro_rules! std { macro_rules! doc_std { ($host:ident => $target:ident, stage = $stage:literal) => {{ - let config = configure("doc", &["A-A"], &["A-A"]); - let build = Build::new(config); - let builder = Builder::new(&build); doc::Std::new( $stage, TargetSelection::from_user(concat!(stringify!($target), "-", stringify!($target))), - &builder, DocumentationFormat::Html, ) }}; @@ -212,10 +212,11 @@ fn alias_and_path_for_library() { } mod defaults { + use pretty_assertions::assert_eq; + use super::{configure, first, run_build}; use crate::core::builder::*; use crate::Config; - use pretty_assertions::assert_eq; #[test] fn build_default() { @@ -323,9 +324,10 @@ mod defaults { } mod dist { + use pretty_assertions::assert_eq; + use super::{first, run_build, Config}; use crate::core::builder::*; - use pretty_assertions::assert_eq; fn configure(host: &[&str], target: &[&str]) -> Config { Config { stage: 2, ..super::configure("dist", host, target) } diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index e32288e2caf67..14beef20bad6e 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -4,29 +4,27 @@ //! how the build runs. use std::cell::{Cell, RefCell}; -use std::cmp; use std::collections::{HashMap, HashSet}; -use std::env; use std::fmt::{self, Display}; -use std::fs; use std::io::IsTerminal; use std::path::{absolute, Path, PathBuf}; use std::process::Command; use std::str::FromStr; use std::sync::OnceLock; +use std::{cmp, env, fs}; + +use build_helper::exit; +use build_helper::git::GitConfig; +use serde::{Deserialize, Deserializer}; +use serde_derive::Deserialize; use crate::core::build_steps::compile::CODEGEN_BACKEND_PREFIX; use crate::core::build_steps::llvm; +pub use crate::core::config::flags::Subcommand; use crate::core::config::flags::{Color, Flags, Warnings}; use crate::utils::cache::{Interned, INTERNER}; use crate::utils::channel::{self, GitInfo}; use crate::utils::helpers::{self, exe, get_closest_merge_base_commit, output, t}; -use build_helper::exit; -use serde::{Deserialize, Deserializer}; -use serde_derive::Deserialize; - -pub use crate::core::config::flags::Subcommand; -use build_helper::git::GitConfig; macro_rules! check_ci_llvm { ($name:expr) => { @@ -514,6 +512,11 @@ impl TargetSelection { pub fn is_windows(&self) -> bool { self.contains("windows") } + + /// Path to the file defining the custom target, if any. + pub fn filepath(&self) -> Option<&Path> { + self.file.as_ref().map(Path::new) + } } impl fmt::Display for TargetSelection { @@ -1842,6 +1845,23 @@ impl Config { config.llvm_from_ci = config.parse_download_ci_llvm(download_ci_llvm, asserts); if config.llvm_from_ci { + let warn = |option: &str| { + println!( + "WARNING: `{option}` will only be used on `compiler/rustc_llvm` build, not for the LLVM build." + ); + println!( + "HELP: To use `{option}` for LLVM builds, set `download-ci-llvm` option to false." + ); + }; + + if static_libstdcpp.is_some() { + warn("static-libstdcpp"); + } + + if link_shared.is_some() { + warn("link-shared"); + } + // None of the LLVM options, except assertions, are supported // when using downloaded LLVM. We could just ignore these but // that's potentially confusing, so force them to not be @@ -1851,9 +1871,6 @@ impl Config { check_ci_llvm!(optimize_toml); check_ci_llvm!(thin_lto); check_ci_llvm!(release_debuginfo); - // CI-built LLVM can be either dynamic or static. We won't know until we download it. - check_ci_llvm!(link_shared); - check_ci_llvm!(static_libstdcpp); check_ci_llvm!(targets); check_ci_llvm!(experimental_targets); check_ci_llvm!(clang_cl); @@ -2094,7 +2111,7 @@ impl Config { // CI should always run stage 2 builds, unless it specifically states otherwise #[cfg(not(test))] - if flags.stage.is_none() && crate::CiEnv::current() != crate::CiEnv::None { + if flags.stage.is_none() && build_helper::ci::CiEnv::is_ci() { match config.cmd { Subcommand::Test { .. } | Subcommand::Miri { .. } @@ -2404,8 +2421,11 @@ impl Config { .unwrap_or_else(|| SplitDebuginfo::default_for_platform(target)) } - pub fn submodules(&self, rust_info: &GitInfo) -> bool { - self.submodules.unwrap_or(rust_info.is_managed_git_subrepository()) + /// Returns whether or not submodules should be managed by bootstrap. + pub fn submodules(&self) -> bool { + // If not specified in config, the default is to only manage + // submodules if we're currently inside a git repository. + self.submodules.unwrap_or(self.rust_info.is_managed_git_subrepository()) } pub fn codegen_backends(&self, target: TargetSelection) -> &[String] { diff --git a/src/bootstrap/src/core/config/tests.rs b/src/bootstrap/src/core/config/tests.rs index bfb2c02860d21..6e695d269cf2c 100644 --- a/src/bootstrap/src/core/config/tests.rs +++ b/src/bootstrap/src/core/config/tests.rs @@ -1,17 +1,15 @@ -use super::{flags::Flags, ChangeIdWrapper, Config}; -use crate::core::build_steps::clippy::get_clippy_rules_in_order; -use crate::core::config::Target; -use crate::core::config::TargetSelection; -use crate::core::config::{LldMode, TomlConfig}; +use std::env; +use std::fs::{remove_file, File}; +use std::io::Write; +use std::path::Path; use clap::CommandFactory; use serde::Deserialize; -use std::{ - env, - fs::{remove_file, File}, - io::Write, - path::Path, -}; + +use super::flags::Flags; +use super::{ChangeIdWrapper, Config}; +use crate::core::build_steps::clippy::get_clippy_rules_in_order; +use crate::core::config::{LldMode, Target, TargetSelection, TomlConfig}; fn parse(config: &str) -> Config { Config::parse_inner(&["check".to_string(), "--config=/does/not/exist".to_string()], |&_| { diff --git a/src/bootstrap/src/core/download.rs b/src/bootstrap/src/core/download.rs index 56a8528d0a133..4d1aea3cd956a 100644 --- a/src/bootstrap/src/core/download.rs +++ b/src/bootstrap/src/core/download.rs @@ -1,19 +1,16 @@ -use std::{ - env, - ffi::OsString, - fs::{self, File}, - io::{BufRead, BufReader, BufWriter, ErrorKind, Write}, - path::{Path, PathBuf}, - process::{Command, Stdio}, - sync::OnceLock, -}; +use std::env; +use std::ffi::OsString; +use std::fs::{self, File}; +use std::io::{BufRead, BufReader, BufWriter, ErrorKind, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::OnceLock; use build_helper::ci::CiEnv; use xz2::bufread::XzDecoder; use crate::utils::exec::{command, BootstrapCommand}; -use crate::utils::helpers::hex_encode; -use crate::utils::helpers::{check_run, exe, move_file, program_out_of_date}; +use crate::utils::helpers::{check_run, exe, hex_encode, move_file, program_out_of_date}; use crate::{t, Config}; static SHOULD_FIX_BINS_AND_DYLIBS: OnceLock = OnceLock::new(); diff --git a/src/bootstrap/src/core/metadata.rs b/src/bootstrap/src/core/metadata.rs index b18da844014be..1016607fc8318 100644 --- a/src/bootstrap/src/core/metadata.rs +++ b/src/bootstrap/src/core/metadata.rs @@ -81,11 +81,14 @@ fn workspace_members(build: &Build) -> Vec { .arg("--no-deps") .arg("--manifest-path") .arg(build.src.join(manifest_path)); - let metadata_output = cargo.capture_stdout().run_always().run(build).stdout(); + let metadata_output = cargo.run_always().run_capture_stdout(build).stdout(); let Output { packages, .. } = t!(serde_json::from_str(&metadata_output)); packages }; - // Collects `metadata.packages` from all workspaces. - collect_metadata("Cargo.toml") + // Collects `metadata.packages` from the root and library workspaces. + let mut packages = vec![]; + packages.extend(collect_metadata("Cargo.toml")); + packages.extend(collect_metadata("library/Cargo.toml")); + packages } diff --git a/src/bootstrap/src/core/sanity.rs b/src/bootstrap/src/core/sanity.rs index 2be819d52ea1a..c42d4c56c3816 100644 --- a/src/bootstrap/src/core/sanity.rs +++ b/src/bootstrap/src/core/sanity.rs @@ -9,19 +9,17 @@ //! practice that's likely not true! use std::collections::HashMap; -use std::env; +#[cfg(not(feature = "bootstrap-self-test"))] +use std::collections::HashSet; use std::ffi::{OsStr, OsString}; -use std::fs; use std::path::PathBuf; +use std::{env, fs}; #[cfg(not(feature = "bootstrap-self-test"))] use crate::builder::Builder; +use crate::builder::Kind; #[cfg(not(feature = "bootstrap-self-test"))] use crate::core::build_steps::tool; -#[cfg(not(feature = "bootstrap-self-test"))] -use std::collections::HashSet; - -use crate::builder::Kind; use crate::core::config::Target; use crate::utils::exec::command; use crate::Build; @@ -262,7 +260,9 @@ than building it. if !has_target { // This might also be a custom target, so check the target file that could have been specified by the user. - if let Some(custom_target_path) = env::var_os("RUST_TARGET_PATH") { + if target.filepath().is_some_and(|p| p.exists()) { + has_target = true; + } else if let Some(custom_target_path) = env::var_os("RUST_TARGET_PATH") { let mut target_filename = OsString::from(&target_str); // Target filename ends with `.json`. target_filename.push(".json"); @@ -277,8 +277,12 @@ than building it. if !has_target { panic!( - "No such target exists in the target list, - specify a correct location of the JSON specification file for custom targets!" + "No such target exists in the target list,\n\ + make sure to correctly specify the location \ + of the JSON specification file \ + for custom targets!\n\ + Use BOOTSTRAP_SKIP_TARGET_SANITY=1 to \ + bypass this check." ); } } @@ -352,7 +356,7 @@ than building it. // There are three builds of cmake on windows: MSVC, MinGW, and // Cygwin. The Cygwin build does not have generators for Visual // Studio, so detect that here and error. - let out = command("cmake").capture_stdout().arg("--help").run(build).stdout(); + let out = command("cmake").arg("--help").run_capture_stdout(build).stdout(); if !out.contains("Visual Studio") { panic!( " diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index 79bea50c626b2..453fb39327d63 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -18,17 +18,15 @@ use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; -use std::env; use std::fmt::Display; use std::fs::{self, File}; -use std::io; use std::path::{Path, PathBuf}; use std::process::Command; -use std::str; use std::sync::OnceLock; use std::time::SystemTime; +use std::{env, io, str}; -use build_helper::ci::{gha, CiEnv}; +use build_helper::ci::gha; use build_helper::exit; use sha2::digest::Digest; use termcolor::{ColorChoice, StandardStream, WriteColor}; @@ -37,10 +35,8 @@ use utils::helpers::hex_encode; use crate::core::builder; use crate::core::builder::{Builder, Kind}; -use crate::core::config::{flags, LldMode}; -use crate::core::config::{DryRun, Target}; -use crate::core::config::{LlvmLibunwind, TargetSelection}; -use crate::utils::exec::{command, BehaviorOnFailure, BootstrapCommand, CommandOutput}; +use crate::core::config::{flags, DryRun, LldMode, LlvmLibunwind, Target, TargetSelection}; +use crate::utils::exec::{command, BehaviorOnFailure, BootstrapCommand, CommandOutput, OutputMode}; use crate::utils::helpers::{self, dir_is_empty, exe, libdir, mtime, output, symlink_dir}; mod core; @@ -49,6 +45,7 @@ mod utils; pub use core::builder::PathSet; pub use core::config::flags::Subcommand; pub use core::config::Config; + pub use utils::change_tracker::{ find_recent_config_change_ids, human_readable_changes, CONFIG_CHANGE_HISTORY, }; @@ -171,7 +168,6 @@ pub struct Build { crates: HashMap, crate_paths: HashMap, is_sudo: bool, - ci_env: CiEnv, delayed_failures: RefCell>, prerelease_version: Cell>, @@ -403,7 +399,6 @@ impl Build { crates: HashMap::new(), crate_paths: HashMap::new(), is_sudo, - ci_env: CiEnv::current(), delayed_failures: RefCell::new(Vec::new()), prerelease_version: Cell::new(None), @@ -441,7 +436,13 @@ impl Build { // Cargo.toml files. let rust_submodules = ["library/backtrace", "library/stdarch"]; for s in rust_submodules { - build.update_submodule(Path::new(s)); + build.require_submodule( + s, + Some( + "The submodule is required for the standard library \ + and the main Cargo workspace.", + ), + ); } // Now, update all existing submodules. build.update_existing_submodules(); @@ -470,12 +471,17 @@ impl Build { build } - // modified from `check_submodule` and `update_submodule` in bootstrap.py /// Given a path to the directory of a submodule, update it. /// /// `relative_path` should be relative to the root of the git repository, not an absolute path. - pub(crate) fn update_submodule(&self, relative_path: &Path) { - if !self.config.submodules(self.rust_info()) { + /// + /// This *does not* update the submodule if `config.toml` explicitly says + /// not to, or if we're not in a git repository (like a plain source + /// tarball). Typically [`Build::require_submodule`] should be + /// used instead to provide a nice error to the user if the submodule is + /// missing. + fn update_submodule(&self, relative_path: &str) { + if !self.config.submodules() { return; } @@ -496,21 +502,21 @@ impl Build { // Therefore, all commands below are marked with `run_always()`, so that they also run in // dry run mode. let submodule_git = || { - let mut cmd = helpers::git(Some(&absolute_path)).capture_stdout(); + let mut cmd = helpers::git(Some(&absolute_path)); cmd.run_always(); cmd }; // Determine commit checked out in submodule. - let checked_out_hash = submodule_git().args(["rev-parse", "HEAD"]).run(self).stdout(); + let checked_out_hash = + submodule_git().args(["rev-parse", "HEAD"]).run_capture_stdout(self).stdout(); let checked_out_hash = checked_out_hash.trim_end(); // Determine commit that the submodule *should* have. let recorded = helpers::git(Some(&self.src)) - .capture_stdout() .run_always() .args(["ls-tree", "HEAD"]) .arg(relative_path) - .run(self) + .run_capture_stdout(self) .stdout(); let actual_hash = recorded .split_whitespace() @@ -522,7 +528,7 @@ impl Build { return; } - println!("Updating submodule {}", relative_path.display()); + println!("Updating submodule {relative_path}"); helpers::git(Some(&self.src)) .run_always() .args(["submodule", "-q", "sync"]) @@ -534,11 +540,10 @@ impl Build { // Git is buggy and will try to fetch submodules from the tracking branch for *this* repository, // even though that has no relation to the upstream for the submodule. let current_branch = helpers::git(Some(&self.src)) - .capture_stdout() .allow_failure() .run_always() .args(["symbolic-ref", "--short", "HEAD"]) - .run(self) + .run_capture_stdout(self) .stdout_if_ok() .map(|s| s.trim().to_owned()); @@ -557,17 +562,14 @@ impl Build { git.arg(relative_path); git }; - if !update(true).run(self).is_success() { + if !update(true).run(self) { update(false).run(self); } // Save any local changes, but avoid running `git stash pop` if there are none (since it will exit with an error). // diff-index reports the modifications through the exit status - let has_local_modifications = submodule_git() - .allow_failure() - .args(["diff-index", "--quiet", "HEAD"]) - .run(self) - .is_failure(); + let has_local_modifications = + !submodule_git().allow_failure().args(["diff-index", "--quiet", "HEAD"]).run(self); if has_local_modifications { submodule_git().args(["stash", "push"]).run(self); } @@ -580,39 +582,81 @@ impl Build { } } + /// Updates a submodule, and exits with a failure if submodule management + /// is disabled and the submodule does not exist. + /// + /// The given submodule name should be its path relative to the root of + /// the main repository. + /// + /// The given `err_hint` will be shown to the user if the submodule is not + /// checked out and submodule management is disabled. + pub fn require_submodule(&self, submodule: &str, err_hint: Option<&str>) { + // When testing bootstrap itself, it is much faster to ignore + // submodules. Almost all Steps work fine without their submodules. + if cfg!(test) && !self.config.submodules() { + return; + } + self.update_submodule(submodule); + let absolute_path = self.config.src.join(submodule); + if dir_is_empty(&absolute_path) { + let maybe_enable = if !self.config.submodules() + && self.config.rust_info.is_managed_git_subrepository() + { + "\nConsider setting `build.submodules = true` or manually initializing the submodules." + } else { + "" + }; + let err_hint = err_hint.map_or_else(String::new, |e| format!("\n{e}")); + eprintln!( + "submodule {submodule} does not appear to be checked out, \ + but it is required for this step{maybe_enable}{err_hint}" + ); + exit!(1); + } + } + + /// Updates all submodules, and exits with an error if submodule + /// management is disabled and the submodule does not exist. + pub fn require_and_update_all_submodules(&self) { + for submodule in build_helper::util::parse_gitmodules(&self.src) { + self.require_submodule(submodule, None); + } + } + /// If any submodule has been initialized already, sync it unconditionally. /// This avoids contributors checking in a submodule change by accident. - pub fn update_existing_submodules(&self) { - // Avoid running git when there isn't a git checkout. - if !self.config.submodules(self.rust_info()) { + fn update_existing_submodules(&self) { + // Avoid running git when there isn't a git checkout, or the user has + // explicitly disabled submodules in `config.toml`. + if !self.config.submodules() { return; } let output = helpers::git(Some(&self.src)) - .capture() .args(["config", "--file"]) .arg(self.config.src.join(".gitmodules")) .args(["--get-regexp", "path"]) - .run(self) + .run_capture(self) .stdout(); for line in output.lines() { // Look for `submodule.$name.path = $path` // Sample output: `submodule.src/rust-installer.path src/tools/rust-installer` - let submodule = Path::new(line.split_once(' ').unwrap().1); + let submodule = line.split_once(' ').unwrap().1; + let path = Path::new(submodule); // Don't update the submodule unless it's already been cloned. - if GitInfo::new(false, submodule).is_managed_git_subrepository() { + if GitInfo::new(false, path).is_managed_git_subrepository() { self.update_submodule(submodule); } } } /// Updates the given submodule only if it's initialized already; nothing happens otherwise. - pub fn update_existing_submodule(&self, submodule: &Path) { + pub fn update_existing_submodule(&self, submodule: &str) { // Avoid running git when there isn't a git checkout. - if !self.config.submodules(self.rust_info()) { + if !self.config.submodules() { return; } - if GitInfo::new(false, submodule).is_managed_git_subrepository() { + if GitInfo::new(false, Path::new(submodule)).is_managed_git_subrepository() { self.update_submodule(submodule); } } @@ -870,14 +914,14 @@ impl Build { if let Some(s) = target_config.and_then(|c| c.llvm_filecheck.as_ref()) { s.to_path_buf() } else if let Some(s) = target_config.and_then(|c| c.llvm_config.as_ref()) { - let llvm_bindir = command(s).capture_stdout().arg("--bindir").run(self).stdout(); + let llvm_bindir = command(s).arg("--bindir").run_capture_stdout(self).stdout(); let filecheck = Path::new(llvm_bindir.trim()).join(exe("FileCheck", target)); if filecheck.exists() { filecheck } else { // On Fedora the system LLVM installs FileCheck in the // llvm subdirectory of the libdir. - let llvm_libdir = command(s).capture_stdout().arg("--libdir").run(self).stdout(); + let llvm_libdir = command(s).arg("--libdir").run_capture_stdout(self).stdout(); let lib_filecheck = Path::new(llvm_libdir.trim()).join("llvm").join(exe("FileCheck", target)); if lib_filecheck.exists() { @@ -944,7 +988,12 @@ impl Build { /// Execute a command and return its output. /// This method should be used for all command executions in bootstrap. #[track_caller] - fn run(&self, command: &mut BootstrapCommand) -> CommandOutput { + fn run( + &self, + command: &mut BootstrapCommand, + stdout: OutputMode, + stderr: OutputMode, + ) -> CommandOutput { command.mark_as_executed(); if self.config.dry_run() && !command.run_always { return CommandOutput::default(); @@ -957,19 +1006,20 @@ impl Build { println!("running: {command:?} (created at {created_at}, executed at {executed_at})") }); - let stdout = command.stdout.stdio(); - command.as_command_mut().stdout(stdout); - let stderr = command.stderr.stdio(); - command.as_command_mut().stderr(stderr); + let cmd = command.as_command_mut(); + cmd.stdout(stdout.stdio()); + cmd.stderr(stderr.stdio()); - let output = command.as_command_mut().output(); + let output = cmd.output(); use std::fmt::Write; let mut message = String::new(); let output: CommandOutput = match output { // Command has succeeded - Ok(output) if output.status.success() => output.into(), + Ok(output) if output.status.success() => { + CommandOutput::from_output(output, stdout, stderr) + } // Command has started, but then it failed Ok(output) => { writeln!( @@ -983,15 +1033,15 @@ Executed at: {executed_at}"#, ) .unwrap(); - let output: CommandOutput = output.into(); + let output: CommandOutput = CommandOutput::from_output(output, stdout, stderr); // If the output mode is OutputMode::Capture, we can now print the output. // If it is OutputMode::Print, then the output has already been printed to // stdout/stderr, and we thus don't have anything captured to print anyway. - if command.stdout.captures() { + if stdout.captures() { writeln!(message, "\nSTDOUT ----\n{}", output.stdout().trim()).unwrap(); } - if command.stderr.captures() { + if stderr.captures() { writeln!(message, "\nSTDERR ----\n{}", output.stderr().trim()).unwrap(); } output @@ -1004,7 +1054,7 @@ Executed at: {executed_at}"#, \nIt was not possible to execute the command: {e:?}" ) .unwrap(); - CommandOutput::did_not_start() + CommandOutput::did_not_start(stdout, stderr) } }; if !output.is_success() { @@ -1529,7 +1579,6 @@ Executed at: {executed_at}"#, // That's our beta number! // (Note that we use a `..` range, not the `...` symmetric difference.) helpers::git(Some(&self.src)) - .capture() .arg("rev-list") .arg("--count") .arg("--merges") @@ -1537,7 +1586,7 @@ Executed at: {executed_at}"#, "refs/remotes/origin/{}..HEAD", self.config.stage0_metadata.config.nightly_branch )) - .run(self) + .run_capture(self) .stdout() }); let n = count.trim().parse().unwrap(); @@ -1972,21 +2021,19 @@ pub fn generate_smart_stamp_hash( additional_input: &str, ) -> String { let diff = helpers::git(Some(dir)) - .capture_stdout() .allow_failure() .arg("diff") - .run(builder) + .run_capture_stdout(builder) .stdout_if_ok() .unwrap_or_default(); let status = helpers::git(Some(dir)) - .capture_stdout() .allow_failure() .arg("status") .arg("--porcelain") .arg("-z") .arg("--untracked-files=normal") - .run(builder) + .run_capture_stdout(builder) .stdout_if_ok() .unwrap_or_default(); diff --git a/src/bootstrap/src/utils/cache.rs b/src/bootstrap/src/utils/cache.rs index d60b54dc703f2..3f78b04d44aa3 100644 --- a/src/bootstrap/src/utils/cache.rs +++ b/src/bootstrap/src/utils/cache.rs @@ -3,13 +3,12 @@ use std::borrow::Borrow; use std::cell::RefCell; use std::cmp::Ordering; use std::collections::HashMap; -use std::fmt; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; -use std::mem; use std::ops::Deref; use std::path::PathBuf; use std::sync::{LazyLock, Mutex}; +use std::{fmt, mem}; use crate::core::builder::Step; diff --git a/src/bootstrap/src/utils/cc_detect.rs b/src/bootstrap/src/utils/cc_detect.rs index 20d79e490ec48..29e6b74aaceb8 100644 --- a/src/bootstrap/src/utils/cc_detect.rs +++ b/src/bootstrap/src/utils/cc_detect.rs @@ -182,15 +182,15 @@ fn default_compiler( return None; } - let cmd = BootstrapCommand::from(c.to_command()); - let output = cmd.capture_stdout().arg("--version").run(build).stdout(); + let mut cmd = BootstrapCommand::from(c.to_command()); + let output = cmd.arg("--version").run_capture_stdout(build).stdout(); let i = output.find(" 4.")?; match output[i + 3..].chars().next().unwrap() { '0'..='6' => {} _ => return None, } let alternative = format!("e{gnu_compiler}"); - if command(&alternative).capture().run(build).is_success() { + if command(&alternative).run_capture(build).is_success() { Some(PathBuf::from(alternative)) } else { None @@ -247,10 +247,8 @@ pub(crate) fn ndk_compiler(compiler: Language, triple: &str, ndk: &Path) -> Path triple.to_string() }; - // API 19 is the earliest API level supported by NDK r25b but AArch64 and x86_64 support - // begins at API level 21. - let api_level = - if triple.contains("aarch64") || triple.contains("x86_64") { "21" } else { "19" }; + // The earliest API supported by NDK r26d is 21. + let api_level = "21"; let compiler = format!("{}{}-{}", triple_translated, api_level, compiler.clang()); let host_tag = if cfg!(target_os = "macos") { // The NDK uses universal binaries, so this is correct even on ARM. @@ -258,7 +256,7 @@ pub(crate) fn ndk_compiler(compiler: Language, triple: &str, ndk: &Path) -> Path } else if cfg!(target_os = "windows") { "windows-x86_64" } else { - // NDK r25b only has official releases for macOS, Windows and Linux. + // NDK r26d only has official releases for macOS, Windows and Linux. // Try the Linux directory everywhere else, on the assumption that the OS has an // emulation layer that can cope (e.g. BSDs). "linux-x86_64" diff --git a/src/bootstrap/src/utils/change_tracker.rs b/src/bootstrap/src/utils/change_tracker.rs index 083418ed066b3..b8f70fdf6a805 100644 --- a/src/bootstrap/src/utils/change_tracker.rs +++ b/src/bootstrap/src/utils/change_tracker.rs @@ -210,4 +210,14 @@ pub const CONFIG_CHANGE_HISTORY: &[ChangeInfo] = &[ severity: ChangeSeverity::Info, summary: "the `wasm-component-ld` tool is now built as part of `build.extended` and can be a member of `build.tools`", }, + ChangeInfo { + change_id: 120593, + severity: ChangeSeverity::Info, + summary: "Removed android-ndk r25b support in favor of android-ndk r26d.", + }, + ChangeInfo { + change_id: 125181, + severity: ChangeSeverity::Warning, + summary: "For tarball sources, default value for `rust.channel` will be taken from `src/ci/channel` file.", + }, ]; diff --git a/src/bootstrap/src/utils/channel.rs b/src/bootstrap/src/utils/channel.rs index f8bcb584991a1..3ae512ef7f1c2 100644 --- a/src/bootstrap/src/utils/channel.rs +++ b/src/bootstrap/src/utils/channel.rs @@ -8,11 +8,10 @@ use std::fs; use std::path::Path; +use super::helpers; use crate::utils::helpers::{output, t}; use crate::Build; -use super::helpers; - #[derive(Clone, Default)] pub enum GitInfo { /// This is not a git repository. diff --git a/src/bootstrap/src/utils/exec.rs b/src/bootstrap/src/utils/exec.rs index a60c0084f3d7f..9f0d0b7e9691f 100644 --- a/src/bootstrap/src/utils/exec.rs +++ b/src/bootstrap/src/utils/exec.rs @@ -1,11 +1,13 @@ -use crate::Build; -use build_helper::ci::CiEnv; -use build_helper::drop_bomb::DropBomb; use std::ffi::OsStr; use std::fmt::{Debug, Formatter}; use std::path::Path; use std::process::{Command, CommandArgs, CommandEnvs, ExitStatus, Output, Stdio}; +use build_helper::ci::CiEnv; +use build_helper::drop_bomb::DropBomb; + +use crate::Build; + /// What should be done when the command fails. #[derive(Debug, Copy, Clone)] pub enum BehaviorOnFailure { @@ -50,7 +52,7 @@ impl OutputMode { /// If you want to delay failures until the end of bootstrap, use [delay_failure]. /// /// By default, the command will print its stdout/stderr to stdout/stderr of bootstrap ([OutputMode::Print]). -/// If you want to handle the output programmatically, use [BootstrapCommand::capture]. +/// If you want to handle the output programmatically, use [BootstrapCommand::run_capture]. /// /// Bootstrap will print a debug log to stdout if the command fails and failure is not allowed. /// @@ -59,8 +61,6 @@ impl OutputMode { pub struct BootstrapCommand { command: Command, pub failure_behavior: BehaviorOnFailure, - pub stdout: OutputMode, - pub stderr: OutputMode, // Run the command even during dry run pub run_always: bool, // This field makes sure that each command is executed (or disarmed) before it is dropped, @@ -135,22 +135,23 @@ impl BootstrapCommand { self } - /// Capture all output of the command, do not print it. - #[must_use] - pub fn capture(self) -> Self { - Self { stdout: OutputMode::Capture, stderr: OutputMode::Capture, ..self } + /// Run the command, while printing stdout and stderr. + /// Returns true if the command has succeeded. + #[track_caller] + pub fn run(&mut self, builder: &Build) -> bool { + builder.run(self, OutputMode::Print, OutputMode::Print).is_success() } - /// Capture stdout of the command, do not print it. - #[must_use] - pub fn capture_stdout(self) -> Self { - Self { stdout: OutputMode::Capture, ..self } + /// Run the command, while capturing and returning all its output. + #[track_caller] + pub fn run_capture(&mut self, builder: &Build) -> CommandOutput { + builder.run(self, OutputMode::Capture, OutputMode::Capture) } - /// Run the command, returning its output. + /// Run the command, while capturing and returning stdout, and printing stderr. #[track_caller] - pub fn run(&mut self, builder: &Build) -> CommandOutput { - builder.run(self) + pub fn run_capture_stdout(&mut self, builder: &Build) -> CommandOutput { + builder.run(self, OutputMode::Capture, OutputMode::Print) } /// Provides access to the stdlib Command inside. @@ -174,8 +175,8 @@ impl BootstrapCommand { } /// If in a CI environment, forces the command to run with colors. - pub fn force_coloring_in_ci(&mut self, ci_env: CiEnv) { - if ci_env != CiEnv::None { + pub fn force_coloring_in_ci(&mut self) { + if CiEnv::is_ci() { // Due to use of stamp/docker, the output stream of bootstrap is not // a TTY in CI, so coloring is by-default turned off. // The explicit `TERM=xterm` environment is needed for @@ -189,11 +190,7 @@ impl BootstrapCommand { impl Debug for BootstrapCommand { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self.command)?; - write!( - f, - " (failure_mode={:?}, stdout_mode={:?}, stderr_mode={:?})", - self.failure_behavior, self.stdout, self.stderr - ) + write!(f, " (failure_mode={:?})", self.failure_behavior) } } @@ -205,8 +202,6 @@ impl From for BootstrapCommand { Self { command, failure_behavior: BehaviorOnFailure::Exit, - stdout: OutputMode::Print, - stderr: OutputMode::Print, run_always: false, drop_bomb: DropBomb::arm(program), } @@ -230,17 +225,41 @@ pub fn command>(program: S) -> BootstrapCommand { } /// Represents the output of an executed process. -#[allow(unused)] pub struct CommandOutput { status: CommandStatus, - stdout: Vec, - stderr: Vec, + stdout: Option>, + stderr: Option>, } impl CommandOutput { #[must_use] - pub fn did_not_start() -> Self { - Self { status: CommandStatus::DidNotStart, stdout: vec![], stderr: vec![] } + pub fn did_not_start(stdout: OutputMode, stderr: OutputMode) -> Self { + Self { + status: CommandStatus::DidNotStart, + stdout: match stdout { + OutputMode::Print => None, + OutputMode::Capture => Some(vec![]), + }, + stderr: match stderr { + OutputMode::Print => None, + OutputMode::Capture => Some(vec![]), + }, + } + } + + #[must_use] + pub fn from_output(output: Output, stdout: OutputMode, stderr: OutputMode) -> Self { + Self { + status: CommandStatus::Finished(output.status), + stdout: match stdout { + OutputMode::Print => None, + OutputMode::Capture => Some(output.stdout), + }, + stderr: match stderr { + OutputMode::Print => None, + OutputMode::Capture => Some(output.stderr), + }, + } } #[must_use] @@ -266,7 +285,10 @@ impl CommandOutput { #[must_use] pub fn stdout(&self) -> String { - String::from_utf8(self.stdout.clone()).expect("Cannot parse process stdout as UTF-8") + String::from_utf8( + self.stdout.clone().expect("Accessing stdout of a command that did not capture stdout"), + ) + .expect("Cannot parse process stdout as UTF-8") } #[must_use] @@ -276,7 +298,10 @@ impl CommandOutput { #[must_use] pub fn stderr(&self) -> String { - String::from_utf8(self.stderr.clone()).expect("Cannot parse process stderr as UTF-8") + String::from_utf8( + self.stderr.clone().expect("Accessing stderr of a command that did not capture stderr"), + ) + .expect("Cannot parse process stderr as UTF-8") } } @@ -284,18 +309,8 @@ impl Default for CommandOutput { fn default() -> Self { Self { status: CommandStatus::Finished(ExitStatus::default()), - stdout: vec![], - stderr: vec![], - } - } -} - -impl From for CommandOutput { - fn from(output: Output) -> Self { - Self { - status: CommandStatus::Finished(output.status), - stdout: output.stdout, - stderr: output.stderr, + stdout: Some(vec![]), + stderr: Some(vec![]), } } } diff --git a/src/bootstrap/src/utils/helpers.rs b/src/bootstrap/src/utils/helpers.rs index 690d7318f9420..65e75f114bbeb 100644 --- a/src/bootstrap/src/utils/helpers.rs +++ b/src/bootstrap/src/utils/helpers.rs @@ -3,23 +3,20 @@ //! Simple things like testing the various filesystem operations here and there, //! not a lot of interesting happenings here unfortunately. -use build_helper::git::{get_git_merge_base, output_result, GitConfig}; -use build_helper::util::fail; -use std::env; use std::ffi::OsStr; -use std::fs; -use std::io; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -use std::str; use std::sync::OnceLock; use std::time::{Instant, SystemTime, UNIX_EPOCH}; +use std::{env, fs, io, str}; + +use build_helper::git::{get_git_merge_base, output_result, GitConfig}; +use build_helper::util::fail; use crate::core::builder::Builder; use crate::core::config::{Config, TargetSelection}; -use crate::LldMode; - pub use crate::utils::shared_helpers::{dylib_path, dylib_path_var}; +use crate::LldMode; #[cfg(test)] mod tests; @@ -48,9 +45,10 @@ macro_rules! t { } }; } -use crate::utils::exec::{command, BootstrapCommand}; pub use t; +use crate::utils::exec::{command, BootstrapCommand}; + pub fn exe(name: &str, target: TargetSelection) -> String { crate::utils::shared_helpers::exe(name, &target.triple) } @@ -347,7 +345,7 @@ pub fn get_clang_cl_resource_dir(builder: &Builder<'_>, clang_cl_path: &str) -> let mut builtins_locator = command(clang_cl_path); builtins_locator.args(["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]); - let clang_rt_builtins = builtins_locator.capture_stdout().run(builder).stdout(); + let clang_rt_builtins = builtins_locator.run_capture_stdout(builder).stdout(); let clang_rt_builtins = Path::new(clang_rt_builtins.trim()); assert!( clang_rt_builtins.exists(), @@ -372,9 +370,9 @@ fn lld_flag_no_threads(builder: &Builder<'_>, lld_mode: LldMode, is_windows: boo let (windows_flag, other_flag) = LLD_NO_THREADS.get_or_init(|| { let newer_version = match lld_mode { LldMode::External => { - let mut cmd = command("lld").capture_stdout(); + let mut cmd = command("lld"); cmd.arg("-flavor").arg("ld").arg("--version"); - let out = cmd.run(builder).stdout(); + let out = cmd.run_capture_stdout(builder).stdout(); match (out.find(char::is_numeric), out.find('.')) { (Some(b), Some(e)) => out.as_str()[b..e].parse::().ok().unwrap_or(14) > 10, _ => true, @@ -534,12 +532,11 @@ pub fn get_closest_merge_base_commit( author: &str, target_paths: &[PathBuf], ) -> Result { - let mut git = git(source_dir).capture_stdout(); + let mut git = git(source_dir); let merge_base = get_git_merge_base(config, source_dir).unwrap_or_else(|_| "HEAD".into()); - git.arg(Path::new("rev-list")); - git.args([&format!("--author={author}"), "-n1", "--first-parent", &merge_base]); + git.args(["rev-list", &format!("--author={author}"), "-n1", "--first-parent", &merge_base]); if !target_paths.is_empty() { git.arg("--").args(target_paths); diff --git a/src/bootstrap/src/utils/helpers/tests.rs b/src/bootstrap/src/utils/helpers/tests.rs index 2ab3952ae5a1d..f0cb324674fc6 100644 --- a/src/bootstrap/src/utils/helpers/tests.rs +++ b/src/bootstrap/src/utils/helpers/tests.rs @@ -1,14 +1,11 @@ -use crate::{ - utils::helpers::{ - check_cfg_arg, extract_beta_rev, hex_encode, make, program_out_of_date, symlink_dir, - }, - Config, -}; -use std::{ - fs::{self, remove_file, File}, - io::Write, - path::PathBuf, +use std::fs::{self, remove_file, File}; +use std::io::Write; +use std::path::PathBuf; + +use crate::utils::helpers::{ + check_cfg_arg, extract_beta_rev, hex_encode, make, program_out_of_date, symlink_dir, }; +use crate::Config; #[test] fn test_make() { diff --git a/src/bootstrap/src/utils/job.rs b/src/bootstrap/src/utils/job.rs index d7d20e57bd131..4012f5167ff73 100644 --- a/src/bootstrap/src/utils/job.rs +++ b/src/bootstrap/src/utils/job.rs @@ -40,28 +40,25 @@ pub unsafe fn setup(build: &mut crate::Build) { /// Note that this is a Windows specific module as none of this logic is required on Unix. #[cfg(windows)] mod for_windows { - use crate::Build; - use std::env; use std::ffi::c_void; - use std::io; - use std::mem; + use std::{env, io, mem}; - use windows::{ - core::PCWSTR, - Win32::Foundation::{CloseHandle, DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE}, - Win32::System::Diagnostics::Debug::{ - SetErrorMode, SEM_NOGPFAULTERRORBOX, THREAD_ERROR_MODE, - }, - Win32::System::JobObjects::{ - AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, - SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, - JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOB_OBJECT_LIMIT_PRIORITY_CLASS, - }, - Win32::System::Threading::{ - GetCurrentProcess, OpenProcess, BELOW_NORMAL_PRIORITY_CLASS, PROCESS_DUP_HANDLE, - }, + use windows::core::PCWSTR; + use windows::Win32::Foundation::{CloseHandle, DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE}; + use windows::Win32::System::Diagnostics::Debug::{ + SetErrorMode, SEM_NOGPFAULTERRORBOX, THREAD_ERROR_MODE, + }; + use windows::Win32::System::JobObjects::{ + AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, + SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOB_OBJECT_LIMIT_PRIORITY_CLASS, + }; + use windows::Win32::System::Threading::{ + GetCurrentProcess, OpenProcess, BELOW_NORMAL_PRIORITY_CLASS, PROCESS_DUP_HANDLE, }; + use crate::Build; + pub unsafe fn setup(build: &mut Build) { // Enable the Windows Error Reporting dialog which msys disables, // so we can JIT debug rustc diff --git a/src/bootstrap/src/utils/metrics.rs b/src/bootstrap/src/utils/metrics.rs index 697dd2f3505f6..e9acb93363e76 100644 --- a/src/bootstrap/src/utils/metrics.rs +++ b/src/bootstrap/src/utils/metrics.rs @@ -4,18 +4,20 @@ //! As this module requires additional dependencies not present during local builds, it's cfg'd //! away whenever the `build.metrics` config option is not set to `true`. -use crate::core::builder::{Builder, Step}; -use crate::utils::helpers::t; -use crate::Build; -use build_helper::metrics::{ - JsonInvocation, JsonInvocationSystemStats, JsonNode, JsonRoot, JsonStepSystemStats, Test, - TestOutcome, TestSuite, TestSuiteMetadata, -}; use std::cell::RefCell; use std::fs::File; use std::io::BufWriter; use std::time::{Duration, Instant, SystemTime}; -use sysinfo::System; + +use build_helper::metrics::{ + JsonInvocation, JsonInvocationSystemStats, JsonNode, JsonRoot, JsonStepSystemStats, Test, + TestOutcome, TestSuite, TestSuiteMetadata, +}; +use sysinfo::{CpuRefreshKind, RefreshKind, System}; + +use crate::core::builder::{Builder, Step}; +use crate::utils::helpers::t; +use crate::Build; // Update this number whenever a breaking change is made to the build metrics. // @@ -53,7 +55,9 @@ impl BuildMetrics { finished_steps: Vec::new(), running_steps: Vec::new(), - system_info: System::new(), + system_info: System::new_with_specifics( + RefreshKind::new().with_cpu(CpuRefreshKind::everything()), + ), timer_start: None, invocation_timer_start: Instant::now(), invocation_start: SystemTime::now(), @@ -75,7 +79,7 @@ impl BuildMetrics { self.collect_stats(&mut *state); } - state.system_info.refresh_cpu(); + state.system_info.refresh_cpu_usage(); state.timer_start = Some(Instant::now()); state.running_steps.push(StepMetrics { @@ -108,7 +112,7 @@ impl BuildMetrics { state.running_steps.last_mut().unwrap().children.push(step); // Start collecting again for the parent step. - state.system_info.refresh_cpu(); + state.system_info.refresh_cpu_usage(); state.timer_start = Some(Instant::now()); } } @@ -146,7 +150,7 @@ impl BuildMetrics { let elapsed = state.timer_start.unwrap().elapsed(); step.duration_excluding_children_sec += elapsed; - state.system_info.refresh_cpu(); + state.system_info.refresh_cpu_usage(); let cpu = state.system_info.cpus().iter().map(|p| p.cpu_usage()).sum::(); step.cpu_usage_time_sec += cpu as f64 / 100.0 * elapsed.as_secs_f64(); } @@ -157,8 +161,9 @@ impl BuildMetrics { let dest = build.out.join("metrics.json"); - let mut system = System::new(); - system.refresh_cpu(); + let mut system = + System::new_with_specifics(RefreshKind::new().with_cpu(CpuRefreshKind::everything())); + system.refresh_cpu_usage(); system.refresh_memory(); let system_stats = JsonInvocationSystemStats { diff --git a/src/bootstrap/src/utils/render_tests.rs b/src/bootstrap/src/utils/render_tests.rs index a3d0d36e7547d..b8aebc2854906 100644 --- a/src/bootstrap/src/utils/render_tests.rs +++ b/src/bootstrap/src/utils/render_tests.rs @@ -6,13 +6,15 @@ //! and rustc) libtest doesn't include the rendered human-readable output as a JSON field. We had //! to reimplement all the rendering logic in this module because of that. -use crate::core::builder::Builder; -use crate::utils::exec::BootstrapCommand; use std::io::{BufRead, BufReader, Read, Write}; use std::process::{ChildStdout, Stdio}; use std::time::Duration; + use termcolor::{Color, ColorSpec, WriteColor}; +use crate::core::builder::Builder; +use crate::utils::exec::BootstrapCommand; + const TERSE_TESTS_PER_LINE: usize = 88; pub(crate) fn add_flags_and_try_run_tests( diff --git a/src/bootstrap/src/utils/tarball.rs b/src/bootstrap/src/utils/tarball.rs index 28a295e3e2a5a..bfe2f084552e6 100644 --- a/src/bootstrap/src/utils/tarball.rs +++ b/src/bootstrap/src/utils/tarball.rs @@ -7,8 +7,8 @@ use std::path::{Path, PathBuf}; -use crate::core::builder::Builder; -use crate::core::{build_steps::dist::distdir, builder::Kind}; +use crate::core::build_steps::dist::distdir; +use crate::core::builder::{Builder, Kind}; use crate::utils::exec::BootstrapCommand; use crate::utils::helpers::{move_file, t}; use crate::utils::{channel, helpers}; @@ -370,11 +370,10 @@ impl<'a> Tarball<'a> { if self.builder.rust_info().is_managed_git_subrepository() { // %ct means committer date let timestamp = helpers::git(Some(&self.builder.src)) - .capture_stdout() .arg("log") .arg("-1") .arg("--format=%ct") - .run(self.builder) + .run_capture_stdout(self.builder) .stdout(); cmd.args(["--override-file-mtime", timestamp.trim()]); } diff --git a/src/ci/docker/host-x86_64/arm-android/Dockerfile b/src/ci/docker/host-x86_64/arm-android/Dockerfile index abca06fb9fb4c..222fa8a7355c8 100644 --- a/src/ci/docker/host-x86_64/arm-android/Dockerfile +++ b/src/ci/docker/host-x86_64/arm-android/Dockerfile @@ -6,7 +6,7 @@ RUN sh /scripts/android-base-apt-get.sh COPY scripts/android-ndk.sh /scripts/ RUN . /scripts/android-ndk.sh && \ - download_ndk android-ndk-r25b-linux.zip + download_ndk android-ndk-r26d-linux.zip RUN dpkg --add-architecture i386 && \ apt-get update && \ diff --git a/src/ci/docker/host-x86_64/arm-android/android-sdk.lock b/src/ci/docker/host-x86_64/arm-android/android-sdk.lock index a1be8a4346b6d..33b0c66ae095a 100644 --- a/src/ci/docker/host-x86_64/arm-android/android-sdk.lock +++ b/src/ci/docker/host-x86_64/arm-android/android-sdk.lock @@ -1,6 +1,6 @@ emulator emulator-linux-5264690.zip 48c1cda2bdf3095d9d9d5c010fbfb3d6d673e3ea patcher;v4 3534162-studio.sdk-patcher.zip 046699c5e2716ae11d77e0bad814f7f33fab261e -platform-tools platform-tools_r28.0.2-linux.zip 46a4c02a9b8e4e2121eddf6025da3c979bf02e28 -platforms;android-18 android-18_r03.zip e6b09b3505754cbbeb4a5622008b907262ee91cb -system-images;android-18;default;armeabi-v7a sys-img/android/armeabi-v7a-18_r05.zip 580b583720f7de671040d5917c8c9db0c7aa03fd +platform-tools platform-tools_r34.0.5-linux.zip 96097475cf7b279fdd8f218f5d043ffe94104ec3 +platforms;android-21 android-21_r02.zip 53536556059bb29ae82f414fd2e14bc335a4eb4c +system-images;android-21;default;armeabi-v7a sys-img/android/armeabi-v7a-21_r04.zip 8c606f81306564b65e41303d2603e4c42ded0d10 tools sdk-tools-linux-4333796.zip 8c7c28554a32318461802c1291d76fccfafde054 diff --git a/src/ci/docker/host-x86_64/dist-android/Dockerfile b/src/ci/docker/host-x86_64/dist-android/Dockerfile index 20b72b377cad2..54649e0d22b92 100644 --- a/src/ci/docker/host-x86_64/dist-android/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-android/Dockerfile @@ -6,7 +6,7 @@ RUN sh /scripts/android-base-apt-get.sh # ndk COPY scripts/android-ndk.sh /scripts/ RUN . /scripts/android-ndk.sh && \ - download_ndk android-ndk-r25b-linux.zip + download_ndk android-ndk-r26d-linux.zip # env ENV TARGETS=arm-linux-androideabi diff --git a/src/ci/docker/host-x86_64/dist-various-2/Dockerfile b/src/ci/docker/host-x86_64/dist-various-2/Dockerfile index 2621e9a603185..1b98d54169338 100644 --- a/src/ci/docker/host-x86_64/dist-various-2/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-various-2/Dockerfile @@ -24,7 +24,8 @@ RUN apt-get update && apt-get build-dep -y clang llvm && apt-get install -y --no # Needed for apt-key to work: dirmngr \ gpg-agent \ - g++-9-arm-linux-gnueabi + g++-9-arm-linux-gnueabi \ + g++-11-riscv64-linux-gnu RUN apt-key adv --batch --yes --keyserver keyserver.ubuntu.com --recv-keys 74DA7924C5513486 RUN add-apt-repository -y 'deb https://apt.dilos.org/dilos dilos2 main' @@ -73,6 +74,10 @@ RUN env \ CC=arm-linux-gnueabi-gcc-9 CFLAGS="-march=armv7-a" \ CXX=arm-linux-gnueabi-g++-9 CXXFLAGS="-march=armv7-a" \ bash musl.sh armv7 && \ + env \ + CC=riscv64-linux-gnu-gcc-11 \ + CXX=riscv64-linux-gnu-g++-11 \ + bash musl.sh riscv64gc && \ rm -rf /build/* WORKDIR /tmp @@ -125,6 +130,7 @@ ENV TARGETS=$TARGETS,x86_64-unknown-none ENV TARGETS=$TARGETS,aarch64-unknown-uefi ENV TARGETS=$TARGETS,i686-unknown-uefi ENV TARGETS=$TARGETS,x86_64-unknown-uefi +ENV TARGETS=$TARGETS,riscv64gc-unknown-linux-musl # As per https://bugs.launchpad.net/ubuntu/+source/gcc-defaults/+bug/1300211 # we need asm in the search path for gcc-9 (for gnux32) but not in the search path of the @@ -132,7 +138,11 @@ ENV TARGETS=$TARGETS,x86_64-unknown-uefi # Luckily one of the folders is /usr/local/include so symlink /usr/include/x86_64-linux-gnu/asm there RUN ln -s /usr/include/x86_64-linux-gnu/asm /usr/local/include/asm +# musl-gcc can't find libgcc_s.so.1 since it doesn't use the standard search paths. +RUN ln -s /usr/riscv64-linux-gnu/lib/libgcc_s.so.1 /usr/lib/gcc-cross/riscv64-linux-gnu/11/ + ENV RUST_CONFIGURE_ARGS --enable-extended --enable-lld --enable-llvm-bitcode-linker --disable-docs \ - --musl-root-armv7=/musl-armv7 + --musl-root-armv7=/musl-armv7 \ + --musl-root-riscv64gc=/musl-riscv64gc ENV SCRIPT python3 ../x.py dist --host='' --target $TARGETS diff --git a/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/src/main.rs b/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/src/main.rs index 2ec554c140b59..d75ee147799a7 100644 --- a/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/src/main.rs +++ b/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/src/main.rs @@ -5,6 +5,7 @@ #![no_std] use core::{panic, ptr}; + use r_efi::efi::{Char16, Handle, Status, SystemTable, RESET_SHUTDOWN}; #[panic_handler] diff --git a/src/ci/docker/scripts/android-start-emulator.sh b/src/ci/docker/scripts/android-start-emulator.sh index 09f0d13759c79..5ffb72eddb118 100755 --- a/src/ci/docker/scripts/android-start-emulator.sh +++ b/src/ci/docker/scripts/android-start-emulator.sh @@ -10,7 +10,7 @@ export SHELL=/bin/bash # the emulator date is set to unix epoch (in armeabi-v7a-18 image). Using # classic engine the emulator starts with the current date and the tests run # fine. If another image is used, this need to be evaluated again. -nohup nohup emulator @armeabi-v7a-18 \ +nohup nohup emulator @armeabi-v7a-21 \ -engine classic -no-window -partition-size 2047 0<&- &>/dev/null & exec "$@" diff --git a/src/ci/docker/scripts/rfl-build.sh b/src/ci/docker/scripts/rfl-build.sh index da7b029ca7329..d690aac27fae6 100755 --- a/src/ci/docker/scripts/rfl-build.sh +++ b/src/ci/docker/scripts/rfl-build.sh @@ -2,7 +2,7 @@ set -euo pipefail -LINUX_VERSION=c13320499ba0efd93174ef6462ae8a7a2933f6e7 +LINUX_VERSION=v6.11-rc1 # Build rustc, rustdoc and cargo ../x.py build --stage 1 library rustdoc @@ -65,4 +65,8 @@ make -C linux LLVM=1 -j$(($(nproc) + 1)) \ make -C linux LLVM=1 -j$(($(nproc) + 1)) \ samples/rust/rust_minimal.o \ samples/rust/rust_print.o \ - drivers/net/phy/ax88796b_rust.o + drivers/net/phy/ax88796b_rust.o \ + rust/doctests_kernel_generated.o + +make -C linux LLVM=1 -j$(($(nproc) + 1)) \ + rustdoc diff --git a/src/ci/github-actions/calculate-job-matrix.py b/src/ci/github-actions/calculate-job-matrix.py index d03bbda100807..7de6d5fcd5f75 100755 --- a/src/ci/github-actions/calculate-job-matrix.py +++ b/src/ci/github-actions/calculate-job-matrix.py @@ -97,9 +97,15 @@ def find_run_type(ctx: GitHubCtx) -> Optional[WorkflowRunType]: "refs/heads/automation/bors/try" ) + # Unrolled branch from a rollup for testing perf + # This should **not** allow custom try jobs + is_unrolled_perf_build = ctx.ref == "refs/heads/try-perf" + if try_build: - jobs = get_custom_jobs(ctx) - return TryRunType(custom_jobs=jobs) + custom_jobs = [] + if not is_unrolled_perf_build: + custom_jobs = get_custom_jobs(ctx) + return TryRunType(custom_jobs=custom_jobs) if ctx.ref == "refs/heads/auto": return AutoRunType() diff --git a/src/doc/reference b/src/doc/reference index e2f0bdc403186..2e191814f163e 160000 --- a/src/doc/reference +++ b/src/doc/reference @@ -1 +1 @@ -Subproject commit e2f0bdc4031866734661dcdb548184bde1450baf +Subproject commit 2e191814f163ee1e77e2d6094eee4dd78a289c5b diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index 292b6032f8493..467fd6f43e48f 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -65,6 +65,8 @@ - [riscv32im-risc0-zkvm-elf](platform-support/riscv32im-risc0-zkvm-elf.md) - [riscv32imac-unknown-xous-elf](platform-support/riscv32imac-unknown-xous-elf.md) - [riscv32*-unknown-none-elf](platform-support/riscv32-unknown-none-elf.md) + - [riscv64gc-unknown-linux-gnu](platform-support/riscv64gc-unknown-linux-gnu.md) + - [riscv64gc-unknown-linux-musl](platform-support/riscv64gc-unknown-linux-musl.md) - [sparc-unknown-none-elf](./platform-support/sparc-unknown-none-elf.md) - [*-pc-windows-gnullvm](platform-support/pc-windows-gnullvm.md) - [\*-nto-qnx-\*](platform-support/nto-qnx.md) @@ -74,6 +76,7 @@ - [*-unknown-openbsd](platform-support/openbsd.md) - [*-unknown-redox](platform-support/redox.md) - [\*-unknown-uefi](platform-support/unknown-uefi.md) + - [\*-wrs-vxworks](platform-support/vxworks.md) - [wasm32-wasip1](platform-support/wasm32-wasip1.md) - [wasm32-wasip1-threads](platform-support/wasm32-wasip1-threads.md) - [wasm32-wasip2](platform-support/wasm32-wasip2.md) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index 0c7f4e7bf1b43..7fd1808a1f026 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -97,7 +97,8 @@ target | notes `powerpc-unknown-linux-gnu` | PowerPC Linux (kernel 3.2, glibc 2.17) `powerpc64-unknown-linux-gnu` | PPC64 Linux (kernel 3.2, glibc 2.17) `powerpc64le-unknown-linux-gnu` | PPC64LE Linux (kernel 3.10, glibc 2.17) -`riscv64gc-unknown-linux-gnu` | RISC-V Linux (kernel 4.20, glibc 2.29) +[`riscv64gc-unknown-linux-gnu`](platform-support/riscv64gc-unknown-linux-gnu.md) | RISC-V Linux (kernel 4.20, glibc 2.29) +[`riscv64gc-unknown-linux-musl`](platform-support/riscv64gc-unknown-linux-musl.md) | RISC-V Linux (kernel 4.20, musl 1.2.3) `s390x-unknown-linux-gnu` | S390x Linux (kernel 3.2, glibc 2.17) `x86_64-unknown-freebsd` | 64-bit FreeBSD `x86_64-unknown-illumos` | illumos @@ -263,7 +264,7 @@ target | std | host | notes [`aarch64-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | ARM64 OpenBSD [`aarch64-unknown-redox`](platform-support/redox.md) | ✓ | | ARM64 Redox OS `aarch64-uwp-windows-msvc` | ✓ | | -`aarch64-wrs-vxworks` | ? | | +[`aarch64-wrs-vxworks`](platform-support/vxworks.md) | ✓ | | ARM64 VxWorks OS `aarch64_be-unknown-linux-gnu_ilp32` | ✓ | ✓ | ARM64 Linux (big-endian, ILP32 ABI) `aarch64_be-unknown-linux-gnu` | ✓ | ✓ | ARM64 Linux (big-endian) [`aarch64_be-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | ARM64 NetBSD (big-endian) @@ -281,7 +282,7 @@ target | std | host | notes [`armv7-unknown-linux-uclibceabihf`](platform-support/armv7-unknown-linux-uclibceabihf.md) | ✓ | ? | Armv7-A Linux with uClibc, hardfloat `armv7-unknown-freebsd` | ✓ | ✓ | Armv7-A FreeBSD [`armv7-unknown-netbsd-eabihf`](platform-support/netbsd.md) | ✓ | ✓ | Armv7-A NetBSD w/hard-float -`armv7-wrs-vxworks-eabihf` | ? | | Armv7-A for VxWorks +[`armv7-wrs-vxworks-eabihf`](platform-support/vxworks.md) | ? | | Armv7-A for VxWorks [`armv7a-kmc-solid_asp3-eabi`](platform-support/kmc-solid.md) | ✓ | | ARM SOLID with TOPPERS/ASP3 [`armv7a-kmc-solid_asp3-eabihf`](platform-support/kmc-solid.md) | ✓ | | ARM SOLID with TOPPERS/ASP3, hardfloat [`armv7a-none-eabihf`](platform-support/arm-none-eabi.md) | * | | Bare Armv7-A, hardfloat @@ -307,7 +308,7 @@ target | std | host | notes `i686-uwp-windows-gnu` | ✓ | | [^x86_32-floats-return-ABI] `i686-uwp-windows-msvc` | ✓ | | [^x86_32-floats-return-ABI] [`i686-win7-windows-msvc`](platform-support/win7-windows-msvc.md) | ✓ | | 32-bit Windows 7 support [^x86_32-floats-return-ABI] -`i686-wrs-vxworks` | ? | | [^x86_32-floats-return-ABI] +[`i686-wrs-vxworks`](platform-support/vxworks.md) | ? | | [^x86_32-floats-return-ABI] [`m68k-unknown-linux-gnu`](platform-support/m68k-unknown-linux-gnu.md) | ? | | Motorola 680x0 Linux `mips-unknown-linux-gnu` | ✓ | ✓ | MIPS Linux (kernel 4.4, glibc 2.23) `mips-unknown-linux-musl` | ✓ | | MIPS Linux with musl 1.2.3 @@ -333,8 +334,8 @@ target | std | host | notes `powerpc-unknown-linux-musl` | ? | | PowerPC Linux with musl 1.2.3 [`powerpc-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | NetBSD 32-bit powerpc systems [`powerpc-unknown-openbsd`](platform-support/powerpc-unknown-openbsd.md) | * | | -`powerpc-wrs-vxworks-spe` | ? | | -`powerpc-wrs-vxworks` | ? | | +[`powerpc-wrs-vxworks-spe`](platform-support/vxworks.md) | ? | | +[`powerpc-wrs-vxworks`](platform-support/vxworks.md) | ? | | `powerpc64-unknown-freebsd` | ✓ | ✓ | PPC64 FreeBSD (ELFv1 and ELFv2) `powerpc64le-unknown-freebsd` | | | PPC64LE FreeBSD `powerpc-unknown-freebsd` | | | PowerPC FreeBSD @@ -354,7 +355,6 @@ target | std | host | notes [`riscv64gc-unknown-hermit`](platform-support/hermit.md) | ✓ | | RISC-V Hermit `riscv64gc-unknown-freebsd` | | | RISC-V FreeBSD `riscv64gc-unknown-fuchsia` | | | RISC-V Fuchsia -`riscv64gc-unknown-linux-musl` | | | RISC-V Linux (kernel 4.20, musl 1.2.3) [`riscv64gc-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | RISC-V NetBSD [`riscv64gc-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | OpenBSD/riscv64 [`riscv64-linux-android`](platform-support/android.md) | | | RISC-V 64-bit Android @@ -383,7 +383,7 @@ target | std | host | notes `x86_64-uwp-windows-gnu` | ✓ | | `x86_64-uwp-windows-msvc` | ✓ | | [`x86_64-win7-windows-msvc`](platform-support/win7-windows-msvc.md) | ✓ | | 64-bit Windows 7 support -`x86_64-wrs-vxworks` | ? | | +[`x86_64-wrs-vxworks`](platform-support/vxworks.md) | ? | | [`x86_64h-apple-darwin`](platform-support/x86_64h-apple-darwin.md) | ✓ | ✓ | macOS with late-gen Intel (at least Haswell) [`x86_64-unknown-linux-none`](platform-support/x86_64-unknown-linux-none.md) | * | | 64-bit Linux with no libc [`xtensa-esp32-none-elf`](platform-support/xtensa.md) | * | | Xtensa ESP32 diff --git a/src/doc/rustc/src/platform-support/riscv64gc-unknown-linux-gnu.md b/src/doc/rustc/src/platform-support/riscv64gc-unknown-linux-gnu.md new file mode 100644 index 0000000000000..1acc0584be91b --- /dev/null +++ b/src/doc/rustc/src/platform-support/riscv64gc-unknown-linux-gnu.md @@ -0,0 +1,129 @@ +# `riscv64gc-unknown-linux-gnu` + +**Tier: 2 (with Host Tools)** + +RISC-V targets using the *RV64I* base instruction set with the *G* collection of extensions, as well as the *C* extension. + + +## Target maintainers + +- Kito Cheng, , [@kito-cheng](https://github.com/kito-cheng) +- Michael Maitland, , [@michaelmaitland](https://github.com/michaelmaitland) +- Robin Randhawa, , [@robin-randhawa-sifive](https://github.com/robin-randhawa-sifive) +- Craig Topper, , [@topperc](https://github.com/topperc) + +## Requirements + +This target requires: + +* Linux Kernel version 4.20 or later +* glibc 2.17 or later + + +## Building the target + +These targets are distributed through `rustup`, and otherwise require no +special configuration. + +If you need to build your own Rust for some reason though, the targets can be +enabled in `config.toml`. For example: + +```toml +[build] +target = ["riscv64gc-unknown-linux-gnu"] +``` + + +## Building Rust programs + + +On a RISC-V host, the `riscv64gc-unknown-linux-gnu` target should be automatically +installed and used by default. + +On a non-RISC-V host, add the target: + +```bash +rustup target add riscv64gc-unknown-linux-gnu +``` + +Then cross compile crates with: + +```bash +cargo build --target riscv64gc-unknown-linux-gnu +``` + + +## Testing + +There are no special requirements for testing and running the targets. +For testing cross builds on the host, please refer to the "Cross-compilation +toolchains and C code" +section below. + + +## Cross-compilation toolchains and C code + +A RISC-V toolchain can be obtained for Windows/Mac/Linux from the +[`riscv-gnu-toolchain`](https://github.com/riscv-collab/riscv-gnu-toolchain) +repostory. Binaries are available via +[embecosm](https://www.embecosm.com/resources/tool-chain-downloads/#riscv-linux), +and may also be available from your OS's package manager. + +On Ubuntu, a RISC-V toolchain can be installed with: + +```bash +apt install gcc-riscv64-linux-gnu g++-riscv64-linux-gnu libc6-dev-riscv64-cross +``` + +Depending on your system, you may need to configure the target to use the GNU +GCC linker. To use it, add the following to your `.cargo/config.toml`: + +```toml +[target.riscv64gc-unknown-linux-gnu] +linker = "riscv64-linux-gnu-gcc" +``` + +If your `riscv64-linux-gnu-*` toolchain is not in your `PATH` you may need to +configure additional settings: + +```toml +[target.riscv64gc-unknown-linux-gnu] +# Adjust the paths to point at your toolchain +cc = "/TOOLCHAIN_PATH/bin/riscv64-linux-gnu-gcc" +cxx = "/TOOLCHAIN_PATH/bin/riscv64-linux-gnu-g++" +ar = "/TOOLCHAIN_PATH/bin/riscv64-linux-gnu-ar" +ranlib = "/TOOLCHAIN_PATH/bin/riscv64-linux-gnu-ranlib" +linker = "/TOOLCHAIN_PATH/bin/riscv64-linux-gnu-gcc" +``` + +To test cross compiled binaries on a non-RISCV-V host, you can use +[`qemu`](https://www.qemu.org/docs/master/system/target-riscv.html). +On Ubuntu, a RISC-V emulator can be obtained with: + +```bash +apt install qemu-system-riscv64 +``` + +Then, in `.cargo/config.toml` set the `runner`: + +```toml +[target.riscv64gc-unknown-linux-gnu] +runner = "qemu-riscv64-static -L /usr/riscv64-linux-gnu -cpu rv64" +``` + +On Mac and Linux, it's also possible to use +[`lima`](https://github.com/lima-vm/lima) to emulate RISC-V in a similar way to +how WSL2 works on Windows: + +```bash +limactl start template://riscv +limactl shell riscv +``` + +Using [Docker (with BuildKit)](https://docs.docker.com/build/buildkit/) the +[`riscv64/ubuntu`](https://hub.docker.com/r/riscv64/ubuntu) image can be used +to buiild or run `riscv64gc-unknown-linux-gnu` binaries. + +```bash +docker run --platform linux/riscv64 -ti --rm --mount "type=bind,src=$(pwd),dst=/checkout" riscv64/ubuntu bash +``` diff --git a/src/doc/rustc/src/platform-support/riscv64gc-unknown-linux-musl.md b/src/doc/rustc/src/platform-support/riscv64gc-unknown-linux-musl.md new file mode 100644 index 0000000000000..5b3dc68303803 --- /dev/null +++ b/src/doc/rustc/src/platform-support/riscv64gc-unknown-linux-musl.md @@ -0,0 +1,47 @@ +# riscv64gc-unknown-linux-musl + +**Tier: 2** + +Target for RISC-V Linux programs using musl libc. + +## Target maintainers + +- [@Amanieu](https://github.com/Amanieu) +- [@kraj](https://github.com/kraj) + +## Requirements + +Building the target itself requires a RISC-V compiler that is supported by `cc-rs`. + +## Building the target + +The target can be built by enabling it for a `rustc` build. + +```toml +[build] +target = ["riscv64gc-unknown-linux-musl"] +``` + +Make sure your C compiler is included in `$PATH`, then add it to the `config.toml`: + +```toml +[target.riscv64gc-unknown-linux-musl] +cc = "riscv64-linux-gnu-gcc" +cxx = "riscv64-linux-gnu-g++" +ar = "riscv64-linux-gnu-ar" +linker = "riscv64-linux-gnu-gcc" +``` + +## Building Rust programs + +This target are distributed through `rustup`, and otherwise require no +special configuration. + +## Cross-compilation + +This target can be cross-compiled from any host. + +## Testing + +This target can be tested as normal with `x.py` on a RISC-V host or via QEMU +emulation. diff --git a/src/doc/rustc/src/platform-support/vxworks.md b/src/doc/rustc/src/platform-support/vxworks.md new file mode 100644 index 0000000000000..c0a818558e0bf --- /dev/null +++ b/src/doc/rustc/src/platform-support/vxworks.md @@ -0,0 +1,51 @@ +# `*-wrs-vxworks` + +**Tier: 3** + +Targets for the VxWorks operating +system. + +Target triplets available: + +- `x86_64-wrs-vxworks` +- `aarch64-wrs-vxworks` +- `i686-wrs-vxworks` +- `armv7-wrs-vxworks-eabihf` +- `powerpc-wrs-vxworks` +- `powerpc-wrs-vxworks-spe` + +## Target maintainers + +- B I Mohammed Abbas ([@biabbas](https://github.com/biabbas)) + +## Requirements + +Rust for each target can be cross-compiled with its specific target vsb configuration. Std support is added but not yet fully tested. + +## Building the target + +You can build Rust with support for the targets by adding it to the `target` list in `config.toml`. In addition the workbench and wr-cc have to configured and activated. + +```toml +[build] +build-stage = 1 +target = [ + "", + "x86_64-wrs-vxworks", + "aarch64-wrs-vxworks", + "i686-wrs-vxworks", + "armv7-wrs-vxworks-eabihf", + "powerpc-wrs-vxworks", + "powerpc-wrs-vxworks-spe", +] +``` + +## Building Rust programs + +Rust does not yet ship pre-compiled artifacts for VxWorks. + +The easiest way to build and test programs for VxWorks is to use the shipped rustc and cargo in VxWorks workbench, following the official windriver guidelines. + +## Cross-compilation toolchains and C code + +The target supports C code. Pre-compiled C toolchains can be found in provided VxWorks workbench. diff --git a/src/doc/rustc/src/targets/custom.md b/src/doc/rustc/src/targets/custom.md index a67cb10fc75a8..a332d24c9f1fb 100644 --- a/src/doc/rustc/src/targets/custom.md +++ b/src/doc/rustc/src/targets/custom.md @@ -15,3 +15,16 @@ rustc +nightly -Z unstable-options --target=wasm32-unknown-unknown --print targe ``` To use a custom target, see the (unstable) [`build-std` feature](../../cargo/reference/unstable.html#build-std) of `cargo`. + +## Custom Target Lookup Path + +When `rustc` is given an option `--target=TARGET` (where `TARGET` is any string), it uses the following logic: +1. if `TARGET` is the name of a built-in target, use that +2. if `TARGET` is a path to a file, read that file as a json target +3. otherwise, search the colon-seperated list of directories found + in the `RUST_TARGET_PATH` environment variable from left to right + for a file named `TARGET.json`. + +These steps are tried in order, so if there are multple potentially valid +interpretations for a target, whichever is found first will take priority. +If none of these methods find a target, an error is thrown. diff --git a/src/doc/unstable-book/src/library-features/is-sorted.md b/src/doc/unstable-book/src/library-features/is-sorted.md deleted file mode 100644 index e3b7dc3b28eb2..0000000000000 --- a/src/doc/unstable-book/src/library-features/is-sorted.md +++ /dev/null @@ -1,11 +0,0 @@ -# `is_sorted` - -The tracking issue for this feature is: [#53485] - -[#53485]: https://github.com/rust-lang/rust/issues/53485 - ------------------------- - -Add the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to `[T]`; -add the methods `is_sorted`, `is_sorted_by` and `is_sorted_by_key` to -`Iterator`. diff --git a/src/librustdoc/Cargo.toml b/src/librustdoc/Cargo.toml index fe531f0ff5985..b3fccbf6456e0 100644 --- a/src/librustdoc/Cargo.toml +++ b/src/librustdoc/Cargo.toml @@ -8,7 +8,7 @@ path = "lib.rs" [dependencies] arrayvec = { version = "0.7", default-features = false } -rinja = { version = "0.2", default-features = false, features = ["config"] } +rinja = { version = "0.3", default-features = false, features = ["config"] } base64 = "0.21.7" itertools = "0.12" indexmap = "2" @@ -23,6 +23,7 @@ tempfile = "3" tracing = "0.1" tracing-tree = "0.3.0" threadpool = "1.8.1" +unicode-segmentation = "1.9" [dependencies.tracing-subscriber] version = "0.3.3" diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index ac927e9a19426..2d41d2605c587 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -6,13 +6,11 @@ use rustc_middle::ty::{self, Region, Ty}; use rustc_span::def_id::DefId; use rustc_span::symbol::{kw, Symbol}; use rustc_trait_selection::traits::auto_trait::{self, RegionTarget}; - use thin_vec::ThinVec; -use crate::clean::{self, simplify, Lifetime}; use crate::clean::{ - clean_generic_param_def, clean_middle_ty, clean_predicate, clean_trait_ref_with_constraints, - clean_ty_generics, + self, clean_generic_param_def, clean_middle_ty, clean_trait_ref_with_constraints, + clean_ty_generics, Lifetime, }; use crate::core::DocContext; @@ -169,7 +167,7 @@ fn clean_param_env<'tcx>( // FIXME(#111101): Incorporate the explicit predicates of the item here... let item_predicates: FxIndexSet<_> = tcx.param_env(item_def_id).caller_bounds().iter().collect(); - let where_predicates = param_env + let predicates = param_env .caller_bounds() .iter() // FIXME: ...which hopefully allows us to simplify this: @@ -194,14 +192,15 @@ fn clean_param_env<'tcx>( } }) }) - .flat_map(|pred| clean_predicate(pred, cx)) - .chain(clean_region_outlives_constraints(®ion_data, generics)) + .map(|pred| (pred, rustc_span::DUMMY_SP)) .collect(); - let mut generics = clean::Generics { params, where_predicates }; - simplify::sized_bounds(cx, &mut generics); - generics.where_predicates = simplify::where_clauses(cx, generics.where_predicates); - generics + let mut where_predicates = + super::modern::clean_predicates(cx, predicates, &mut super::modern::WhereClause::default()); + // FIXME: these no longer get "simplif[ied]::where_clauses" + where_predicates.extend(clean_region_outlives_constraints(®ion_data, generics)); + + clean::Generics { params, where_predicates } } /// Clean region outlives constraints to where-predicates. diff --git a/src/librustdoc/clean/blanket_impl.rs b/src/librustdoc/clean/blanket_impl.rs index 4c7a2ecdb53f5..48c3fb65203cc 100644 --- a/src/librustdoc/clean/blanket_impl.rs +++ b/src/librustdoc/clean/blanket_impl.rs @@ -5,7 +5,6 @@ use rustc_middle::ty::{self, Upcast}; use rustc_span::def_id::DefId; use rustc_span::DUMMY_SP; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; - use thin_vec::ThinVec; use crate::clean; diff --git a/src/librustdoc/clean/cfg.rs b/src/librustdoc/clean/cfg.rs index 2814e83dcd757..fb9754c7ffcb0 100644 --- a/src/librustdoc/clean/cfg.rs +++ b/src/librustdoc/clean/cfg.rs @@ -4,15 +4,13 @@ // switch to use those structures instead. use std::fmt::{self, Write}; -use std::mem; -use std::ops; +use std::{mem, ops}; use rustc_ast::{LitKind, MetaItem, MetaItemKind, NestedMetaItem}; use rustc_data_structures::fx::FxHashSet; use rustc_feature::Features; use rustc_session::parse::ParseSess; use rustc_span::symbol::{sym, Symbol}; - use rustc_span::Span; use crate::html::escape::Escape; diff --git a/src/librustdoc/clean/cfg/tests.rs b/src/librustdoc/clean/cfg/tests.rs index 2857f74c744f5..a9b3abadb2044 100644 --- a/src/librustdoc/clean/cfg/tests.rs +++ b/src/librustdoc/clean/cfg/tests.rs @@ -1,11 +1,10 @@ -use super::*; - use rustc_ast::{MetaItemLit, Path, Safety, StrStyle}; -use rustc_span::create_default_session_globals_then; use rustc_span::symbol::{kw, Ident}; -use rustc_span::DUMMY_SP; +use rustc_span::{create_default_session_globals_then, DUMMY_SP}; use thin_vec::thin_vec; +use super::*; + fn word_cfg(s: &str) -> Cfg { Cfg::Cfg(Symbol::intern(s), None) } diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 0024e246ef007..f8953f0ebcfb5 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -3,11 +3,7 @@ use std::iter::once; use std::sync::Arc; -use thin_vec::{thin_vec, ThinVec}; - -use rustc_ast as ast; use rustc_data_structures::fx::FxHashSet; -use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, DefIdSet, LocalModDefId}; use rustc_hir::Mutability; @@ -16,8 +12,11 @@ use rustc_middle::ty::fast_reject::SimplifiedType; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::hygiene::MacroKind; -use rustc_span::symbol::{kw, sym, Symbol}; +use rustc_span::symbol::{sym, Symbol}; +use thin_vec::{thin_vec, ThinVec}; +use {rustc_ast as ast, rustc_hir as hir}; +use super::Item; use crate::clean::{ self, clean_bound_vars, clean_generics, clean_impl_item, clean_middle_assoc_item, clean_middle_field, clean_middle_ty, clean_poly_fn_sig, clean_trait_ref_with_constraints, @@ -27,8 +26,6 @@ use crate::clean::{ use crate::core::DocContext; use crate::formats::item_type::ItemType; -use super::Item; - /// Attempt to inline a definition into this AST. /// /// This function will fetch the definition specified, and if it is @@ -131,8 +128,8 @@ pub(crate) fn try_inline( Res::Def(DefKind::Const, did) => { record_extern_fqn(cx, did, ItemType::Constant); cx.with_param_env(did, |cx| { - let (generics, ty, ct) = build_const_item(cx, did); - clean::ConstantItem(generics, Box::new(ty), ct) + let ct = build_const_item(cx, did); + clean::ConstantItem(Box::new(ct)) }) } Res::Def(DefKind::Macro(kind), did) => { @@ -720,10 +717,7 @@ pub(crate) fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String { } } -fn build_const_item( - cx: &mut DocContext<'_>, - def_id: DefId, -) -> (clean::Generics, clean::Type, clean::Constant) { +fn build_const_item(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant { let mut generics = clean_ty_generics(cx, cx.tcx.generics_of(def_id), cx.tcx.explicit_predicates_of(def_id)); clean::simplify::move_bounds_to_generic_parameters(&mut generics); @@ -733,17 +727,17 @@ fn build_const_item( None, None, ); - (generics, ty, clean::Constant { kind: clean::ConstantKind::Extern { def_id } }) + clean::Constant { generics, type_: ty, kind: clean::ConstantKind::Extern { def_id } } } fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static { clean::Static { - type_: clean_middle_ty( + type_: Box::new(clean_middle_ty( ty::Binder::dummy(cx.tcx.type_of(did).instantiate_identity()), cx, Some(did), None, - ), + )), mutability: if mutable { Mutability::Mut } else { Mutability::Not }, expr: None, } @@ -798,11 +792,7 @@ fn build_macro( fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics { for pred in &mut g.where_predicates { match *pred { - clean::WherePredicate::BoundPredicate { - ty: clean::Generic(ref s), - ref mut bounds, - .. - } if *s == kw::SelfUpper => { + clean::WherePredicate::BoundPredicate { ty: clean::SelfTy, ref mut bounds, .. } => { bounds.retain(|bound| match bound { clean::GenericBound::TraitBound(clean::PolyTrait { trait_, .. }, _) => { trait_.def_id() != trait_did @@ -818,13 +808,13 @@ fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean: clean::WherePredicate::BoundPredicate { ty: clean::QPath(box clean::QPathData { - self_type: clean::Generic(ref s), + self_type: clean::Generic(_), trait_: Some(trait_), .. }), bounds, .. - } => !(bounds.is_empty() || *s == kw::SelfUpper && trait_.def_id() == trait_did), + } => !bounds.is_empty() && trait_.def_id() != trait_did, _ => true, }); g @@ -838,9 +828,7 @@ fn separate_supertrait_bounds( ) -> (clean::Generics, Vec) { let mut ty_bounds = Vec::new(); g.where_predicates.retain(|pred| match *pred { - clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds, .. } - if *s == kw::SelfUpper => - { + clean::WherePredicate::BoundPredicate { ty: clean::SelfTy, ref bounds, .. } => { ty_bounds.extend(bounds.iter().cloned()); false } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 2cd9b6fcd387e..2f5550066d0ca 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -25,46 +25,43 @@ mod auto_trait; mod blanket_impl; pub(crate) mod cfg; pub(crate) mod inline; +// FIXME: temporary module +mod modern; mod render_macro_matchers; mod simplify; pub(crate) mod types; pub(crate) mod utils; -use rustc_ast as ast; +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::mem; + use rustc_ast::token::{Token, TokenKind}; use rustc_ast::tokenstream::{TokenStream, TokenTree}; -use rustc_attr as attr; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, IndexEntry}; -use rustc_errors::{codes::*, struct_span_code_err, FatalError}; -use rustc_hir as hir; +use rustc_errors::codes::*; +use rustc_errors::{struct_span_code_err, FatalError}; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId, LOCAL_CRATE}; use rustc_hir::PredicateOrigin; use rustc_hir_analysis::lower_ty; use rustc_middle::metadata::Reexport; use rustc_middle::middle::resolve_bound_vars as rbv; -use rustc_middle::ty::GenericArgsRef; -use rustc_middle::ty::TypeVisitableExt; -use rustc_middle::ty::{self, AdtKind, Ty, TyCtxt}; +use rustc_middle::ty::{self, AdtKind, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; use rustc_span::hygiene::{AstPass, MacroKind}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::ExpnKind; use rustc_trait_selection::traits::wf::object_region_bounds; - -use std::borrow::Cow; -use std::collections::BTreeMap; -use std::mem; use thin_vec::ThinVec; - -use crate::core::DocContext; -use crate::formats::item_type::ItemType; -use crate::visit_ast::Module as DocModule; - use utils::*; +use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; pub(crate) use self::types::*; pub(crate) use self::utils::{krate, register_res, synthesize_auto_trait_and_blanket_impls}; +use crate::core::DocContext; +use crate::formats::item_type::ItemType; +use crate::visit_ast::Module as DocModule; pub(crate) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext<'tcx>) -> Item { let mut items: Vec = vec![]; @@ -287,23 +284,21 @@ fn clean_lifetime<'tcx>(lifetime: &hir::Lifetime, cx: &mut DocContext<'tcx>) -> pub(crate) fn clean_const<'tcx>( constant: &hir::ConstArg<'tcx>, _cx: &mut DocContext<'tcx>, -) -> Constant { +) -> ConstantKind { match &constant.kind { hir::ConstArgKind::Path(qpath) => { - Constant { kind: ConstantKind::Path { path: qpath_to_string(&qpath).into() } } - } - hir::ConstArgKind::Anon(anon) => { - Constant { kind: ConstantKind::Anonymous { body: anon.body } } + ConstantKind::Path { path: qpath_to_string(&qpath).into() } } + hir::ConstArgKind::Anon(anon) => ConstantKind::Anonymous { body: anon.body }, } } pub(crate) fn clean_middle_const<'tcx>( constant: ty::Binder<'tcx, ty::Const<'tcx>>, _cx: &mut DocContext<'tcx>, -) -> Constant { +) -> ConstantKind { // FIXME: instead of storing the stringified expression, store `self` directly instead. - Constant { kind: ConstantKind::TyConst { expr: constant.skip_binder().to_string().into() } } + ConstantKind::TyConst { expr: constant.skip_binder().to_string().into() } } pub(crate) fn clean_middle_region<'tcx>(region: ty::Region<'tcx>) -> Option { @@ -357,73 +352,6 @@ fn clean_where_predicate<'tcx>( }) } -pub(crate) fn clean_predicate<'tcx>( - predicate: ty::Clause<'tcx>, - cx: &mut DocContext<'tcx>, -) -> Option { - let bound_predicate = predicate.kind(); - match bound_predicate.skip_binder() { - ty::ClauseKind::Trait(pred) => clean_poly_trait_predicate(bound_predicate.rebind(pred), cx), - ty::ClauseKind::RegionOutlives(pred) => clean_region_outlives_predicate(pred), - ty::ClauseKind::TypeOutlives(pred) => { - clean_type_outlives_predicate(bound_predicate.rebind(pred), cx) - } - ty::ClauseKind::Projection(pred) => { - Some(clean_projection_predicate(bound_predicate.rebind(pred), cx)) - } - // FIXME(generic_const_exprs): should this do something? - ty::ClauseKind::ConstEvaluatable(..) - | ty::ClauseKind::WellFormed(..) - | ty::ClauseKind::ConstArgHasType(..) => None, - } -} - -fn clean_poly_trait_predicate<'tcx>( - pred: ty::PolyTraitPredicate<'tcx>, - cx: &mut DocContext<'tcx>, -) -> Option { - // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op. - // FIXME(effects) check constness - if Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait() { - return None; - } - - let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref); - Some(WherePredicate::BoundPredicate { - ty: clean_middle_ty(poly_trait_ref.self_ty(), cx, None, None), - bounds: vec![clean_poly_trait_ref_with_constraints(cx, poly_trait_ref, ThinVec::new())], - bound_params: Vec::new(), - }) -} - -fn clean_region_outlives_predicate<'tcx>( - pred: ty::RegionOutlivesPredicate<'tcx>, -) -> Option { - let ty::OutlivesPredicate(a, b) = pred; - - Some(WherePredicate::RegionPredicate { - lifetime: clean_middle_region(a).expect("failed to clean lifetime"), - bounds: vec![GenericBound::Outlives( - clean_middle_region(b).expect("failed to clean bounds"), - )], - }) -} - -fn clean_type_outlives_predicate<'tcx>( - pred: ty::Binder<'tcx, ty::TypeOutlivesPredicate<'tcx>>, - cx: &mut DocContext<'tcx>, -) -> Option { - let ty::OutlivesPredicate(ty, lt) = pred.skip_binder(); - - Some(WherePredicate::BoundPredicate { - ty: clean_middle_ty(pred.rebind(ty), cx, None, None), - bounds: vec![GenericBound::Outlives( - clean_middle_region(lt).expect("failed to clean lifetimes"), - )], - bound_params: Vec::new(), - }) -} - fn clean_middle_term<'tcx>( term: ty::Binder<'tcx, ty::Term<'tcx>>, cx: &mut DocContext<'tcx>, @@ -444,24 +372,6 @@ fn clean_hir_term<'tcx>(term: &hir::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Te } } -fn clean_projection_predicate<'tcx>( - pred: ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>, - cx: &mut DocContext<'tcx>, -) -> WherePredicate { - WherePredicate::EqPredicate { - lhs: clean_projection( - pred.map_bound(|p| { - // FIXME: This needs to be made resilient for `AliasTerm`s that - // are associated consts. - p.projection_term.expect_ty(cx.tcx) - }), - cx, - None, - ), - rhs: clean_middle_term(pred.map_bound(|p| p.term), cx), - } -} - fn clean_projection<'tcx>( ty: ty::Binder<'tcx, ty::AliasTy<'tcx>>, cx: &mut DocContext<'tcx>, @@ -498,6 +408,7 @@ fn compute_should_show_cast(self_def_id: Option, trait_: &Path, self_type .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_) } +// FIXME: Generalize to `clean_middle_projection_term` fn projection_to_path_segment<'tcx>( ty: ty::Binder<'tcx, ty::AliasTy<'tcx>>, cx: &mut DocContext<'tcx>, @@ -787,19 +698,19 @@ pub(crate) fn clean_generics<'tcx>( } } +// FIXME(fmease): Explain why we need to take `predicates`, too! fn clean_ty_generics<'tcx>( cx: &mut DocContext<'tcx>, - gens: &ty::Generics, - preds: ty::GenericPredicates<'tcx>, + generics: &'tcx ty::Generics, + predicates: ty::GenericPredicates<'tcx>, ) -> Generics { - // Don't populate `cx.impl_trait_bounds` before cleaning where clauses, - // since `clean_predicate` would consume them. - let mut impl_trait = BTreeMap::>::default(); + let mut apits = BTreeMap::new(); - let params: ThinVec<_> = gens + let params = generics .own_params .iter() .filter(|param| match param.kind { + // FIXME(fmease): Explain why we can get anonymous lifetimes. ty::GenericParamDefKind::Lifetime => !param.is_anonymous_lifetime(), ty::GenericParamDefKind::Type { synthetic, .. } => { if param.name == kw::SelfUpper { @@ -807,7 +718,7 @@ fn clean_ty_generics<'tcx>( return false; } if synthetic { - impl_trait.insert(param.index, vec![]); + apits.insert(param.index, Vec::new()); return false; } true @@ -817,115 +728,84 @@ fn clean_ty_generics<'tcx>( .map(|param| clean_generic_param_def(param, ParamDefaults::Yes, cx)) .collect(); - // param index -> [(trait DefId, associated type name & generics, term)] - let mut impl_trait_proj = - FxHashMap::>)>>::default(); + struct ApitFinder<'a, 'tcx> { + apits: &'a BTreeMap, rustc_span::Span)>>, + } - let where_predicates = preds - .predicates - .iter() - .flat_map(|(pred, _)| { - let mut projection = None; - let param_idx = (|| { - let bound_p = pred.kind(); - match bound_p.skip_binder() { - ty::ClauseKind::Trait(pred) => { - if let ty::Param(param) = pred.self_ty().kind() { - return Some(param.index); - } - } - ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => { - if let ty::Param(param) = ty.kind() { - return Some(param.index); - } - } - ty::ClauseKind::Projection(p) => { - if let ty::Param(param) = p.projection_term.self_ty().kind() { - projection = Some(bound_p.rebind(p)); - return Some(param.index); - } + impl<'tcx> ty::TypeVisitor> for ApitFinder<'_, 'tcx> { + type Result = ControlFlow; + + fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result { + match ty.kind() { + ty::Param(param_ty) => { + if self.apits.contains_key(¶m_ty.index) { + // FIXME: rephrase (there's no pred in scope) + // A predicate may at most contain a single APIT. + return ControlFlow::Break(param_ty.index); } - _ => (), } + _ if ty.has_param() => return ty.super_visit_with(self), + _ => {} + } + ControlFlow::Continue(()) + } + } - None - })(); - - if let Some(param_idx) = param_idx - && let Some(bounds) = impl_trait.get_mut(¶m_idx) + // FIXME: explainer + let predicates = predicates + .predicates + .iter() + .copied() + .filter(|&(predicate, span)| { + if let ControlFlow::Break(index) = + predicate.visit_with(&mut ApitFinder { apits: &apits }) { - let pred = clean_predicate(*pred, cx)?; - - bounds.extend(pred.get_bounds().into_iter().flatten().cloned()); - - if let Some(proj) = projection - && let lhs = clean_projection( - proj.map_bound(|p| { - // FIXME: This needs to be made resilient for `AliasTerm`s that - // are associated consts. - p.projection_term.expect_ty(cx.tcx) - }), - cx, - None, - ) - && let Some((_, trait_did, name)) = lhs.projection() - { - impl_trait_proj.entry(param_idx).or_default().push(( - trait_did, - name, - proj.map_bound(|p| p.term), - )); - } - - return None; + apits.get_mut(&index).unwrap().push((predicate, span)); + return false; } - - Some(pred) + true }) - .collect::>(); - - for (idx, mut bounds) in impl_trait { - let mut has_sized = false; - bounds.retain(|b| { - if b.is_sized_bound(cx) { - has_sized = true; - false - } else { - true - } - }); - if !has_sized { - bounds.push(GenericBound::maybe_sized(cx)); - } + .collect(); - // Move trait bounds to the front. - bounds.sort_by_key(|b| !b.is_trait_bound()); + // FIXME: does this handle Sized/?Sized properly? + for (index, predicates) in apits { + // FIXME: fix up API of clean_pred instead + let mut where_predicates = + modern::clean_predicates(cx, predicates, &mut modern::Apit::default()); + let mut bounds = match where_predicates.pop() { + Some(WherePredicate::BoundPredicate { bounds, .. }) => bounds, + Some(_) => unreachable!(), + None => Vec::new(), + }; // Add back a `Sized` bound if there are no *trait* bounds remaining (incl. `?Sized`). - // Since all potential trait bounds are at the front we can just check the first bound. - if bounds.first().map_or(true, |b| !b.is_trait_bound()) { + if bounds.iter().all(|bound| !bound.is_trait_bound()) { bounds.insert(0, GenericBound::sized(cx)); } + cx.impl_trait_bounds.insert(index.into(), bounds); + } - if let Some(proj) = impl_trait_proj.remove(&idx) { - for (trait_did, name, rhs) in proj { - let rhs = clean_middle_term(rhs, cx); - simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs); - } - } + let mut cleaner = modern::WhereClause::default(); + let mut where_predicates = modern::clean_predicates(cx, predicates, &mut cleaner); - cx.impl_trait_bounds.insert(idx.into(), bounds); + // FIXME: This adds extra clauses, instead of modifying existing bounds + // Smh. make clean_preds add those bounds onto existing ones if available + // NOTE: Maybe we should just cave in an add an `Option` param to clean_preds + // FIXME: This is so stupid + for param in &generics.own_params { + if let ty::GenericParamDefKind::Type { synthetic: false, .. } = param.kind + && !cleaner.sized.contains(¶m.index) + { + // FIXME: is this correct if we have parent generics? + where_predicates.push(WherePredicate::BoundPredicate { + ty: Type::Generic(param.name), + bounds: vec![GenericBound::maybe_sized(cx)], + bound_params: Vec::new(), + }) + } } - // Now that `cx.impl_trait_bounds` is populated, we can process - // remaining predicates which could contain `impl Trait`. - let where_predicates = - where_predicates.into_iter().flat_map(|p| clean_predicate(*p, cx)).collect(); - - let mut generics = Generics { params, where_predicates }; - simplify::sized_bounds(cx, &mut generics); - generics.where_predicates = simplify::where_clauses(cx, generics.where_predicates); - generics + Generics { params, where_predicates } } fn clean_ty_alias_inner_type<'tcx>( @@ -1230,14 +1110,11 @@ fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext let local_did = trait_item.owner_id.to_def_id(); cx.with_param_env(local_did, |cx| { let inner = match trait_item.kind { - hir::TraitItemKind::Const(ty, Some(default)) => { - let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)); - AssocConstItem( - generics, - Box::new(clean_ty(ty, cx)), - ConstantKind::Local { def_id: local_did, body: default }, - ) - } + hir::TraitItemKind::Const(ty, Some(default)) => AssocConstItem(Box::new(Constant { + generics: enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)), + kind: ConstantKind::Local { def_id: local_did, body: default }, + type_: clean_ty(ty, cx), + })), hir::TraitItemKind::Const(ty, None) => { let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)); TyAssocConstItem(generics, Box::new(clean_ty(ty, cx))) @@ -1282,11 +1159,11 @@ pub(crate) fn clean_impl_item<'tcx>( let local_did = impl_.owner_id.to_def_id(); cx.with_param_env(local_did, |cx| { let inner = match impl_.kind { - hir::ImplItemKind::Const(ty, expr) => { - let generics = clean_generics(impl_.generics, cx); - let default = ConstantKind::Local { def_id: local_did, body: expr }; - AssocConstItem(generics, Box::new(clean_ty(ty, cx)), default) - } + hir::ImplItemKind::Const(ty, expr) => AssocConstItem(Box::new(Constant { + generics: clean_generics(impl_.generics, cx), + kind: ConstantKind::Local { def_id: local_did, body: expr }, + type_: clean_ty(ty, cx), + })), hir::ImplItemKind::Fn(ref sig, body) => { let m = clean_function(cx, sig, impl_.generics, FunctionArgs::Body(body)); let defaultness = cx.tcx.defaultness(impl_.owner_id); @@ -1320,12 +1197,12 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( let tcx = cx.tcx; let kind = match assoc_item.kind { ty::AssocKind::Const => { - let ty = Box::new(clean_middle_ty( + let ty = clean_middle_ty( ty::Binder::dummy(tcx.type_of(assoc_item.def_id).instantiate_identity()), cx, Some(assoc_item.def_id), None, - )); + ); let mut generics = clean_ty_generics( cx, @@ -1339,9 +1216,13 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( ty::TraitContainer => tcx.defaultness(assoc_item.def_id).has_value(), }; if provided { - AssocConstItem(generics, ty, ConstantKind::Extern { def_id: assoc_item.def_id }) + AssocConstItem(Box::new(Constant { + generics, + kind: ConstantKind::Extern { def_id: assoc_item.def_id }, + type_: ty, + })) } else { - TyAssocConstItem(generics, ty) + TyAssocConstItem(generics, Box::new(ty)) } } ty::AssocKind::Fn => { @@ -1357,11 +1238,11 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( let self_arg_ty = tcx.fn_sig(assoc_item.def_id).instantiate_identity().input(0).skip_binder(); if self_arg_ty == self_ty { - item.decl.inputs.values[0].type_ = Generic(kw::SelfUpper); + item.decl.inputs.values[0].type_ = SelfTy; } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() { if ty == self_ty { match item.decl.inputs.values[0].type_ { - BorrowedRef { ref mut type_, .. } => **type_ = Generic(kw::SelfUpper), + BorrowedRef { ref mut type_, .. } => **type_ = SelfTy, _ => unreachable!(), } } @@ -1382,6 +1263,7 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( TyMethodItem(item) } } + // FIXME: Rewrite this!!! ty::AssocKind::Type => { let my_name = assoc_item.name; @@ -1397,7 +1279,7 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( { true } - (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &c.kind { + (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &**c { ConstantKind::TyConst { expr } => **expr == *param.name.as_str(), _ => false, }, @@ -1445,9 +1327,8 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( if trait_.def_id() != assoc_item.container_id(tcx) { return true; } - match *self_type { - Generic(ref s) if *s == kw::SelfUpper => {} - _ => return true, + if *self_type != SelfTy { + return true; } match &assoc.args { GenericArgs::AngleBracketed { args, constraints } => { @@ -1858,7 +1739,7 @@ pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> T } TyKind::Path(_) => clean_qpath(ty, cx), TyKind::TraitObject(bounds, ref lifetime, _) => { - let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect(); + let bounds = bounds.iter().map(|(bound, _)| clean_poly_trait_ref(bound, cx)).collect(); let lifetime = if !lifetime.is_elided() { Some(clean_lifetime(*lifetime, cx)) } else { None }; DynTrait(bounds, lifetime) @@ -2139,7 +2020,8 @@ pub(crate) fn clean_middle_ty<'tcx>( }) .collect::>(); - let bindings = obj + // FIXME: yooo + let constraints = obj .projection_bounds() .map(|pb| AssocItemConstraint { assoc: projection_to_path_segment( @@ -2175,7 +2057,7 @@ pub(crate) fn clean_middle_ty<'tcx>( .collect(); let late_bound_regions = late_bound_regions.into_iter().collect(); - let path = clean_middle_path(cx, did, false, bindings, args); + let path = clean_middle_path(cx, did, false, constraints, args); bounds.insert(0, PolyTrait { trait_: path, generic_params: late_bound_regions }); DynTrait(bounds, lifetime) @@ -2234,6 +2116,8 @@ pub(crate) fn clean_middle_ty<'tcx>( ty::Param(ref p) => { if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) { ImplTrait(bounds) + } else if p.name == kw::SelfUpper { + SelfTy } else { Generic(p.name) } @@ -2280,78 +2164,40 @@ fn clean_middle_opaque_bounds<'tcx>( impl_trait_def_id: DefId, args: ty::GenericArgsRef<'tcx>, ) -> Type { - let mut has_sized = false; - - let bounds: Vec<_> = cx + let predicates: Vec<_> = cx .tcx .explicit_item_bounds(impl_trait_def_id) .iter_instantiated_copied(cx.tcx, args) .collect(); - let mut bounds = bounds - .iter() - .filter_map(|(bound, _)| { - let bound_predicate = bound.kind(); - let trait_ref = match bound_predicate.skip_binder() { - ty::ClauseKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref), - ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => { - return clean_middle_region(reg).map(GenericBound::Outlives); - } - _ => return None, - }; - - if let Some(sized) = cx.tcx.lang_items().sized_trait() - && trait_ref.def_id() == sized - { - has_sized = true; - return None; - } - - let bindings: ThinVec<_> = bounds - .iter() - .filter_map(|(bound, _)| { - if let ty::ClauseKind::Projection(proj) = bound.kind().skip_binder() { - if proj.projection_term.trait_ref(cx.tcx) == trait_ref.skip_binder() { - Some(AssocItemConstraint { - assoc: projection_to_path_segment( - // FIXME: This needs to be made resilient for `AliasTerm`s that - // are associated consts. - bound.kind().rebind(proj.projection_term.expect_ty(cx.tcx)), - cx, - ), - kind: AssocItemConstraintKind::Equality { - term: clean_middle_term(bound.kind().rebind(proj.term), cx), - }, - }) - } else { - None - } - } else { - None - } - }) - .collect(); - - Some(clean_poly_trait_ref_with_constraints(cx, trait_ref, bindings)) - }) - .collect::>(); + // FIXME: fix up API of clean_pred instead + // FIXME: we currentyl elide `Sized` bc it looks for bounded_ty=`ty::Param` but we don't + // care about that here bc we want to look for bounded_ty=Alias(Opaque) (which we can + // actually assume / don't need to check) + // FIXME: Make it so clean_pred inserts `Sized` before any outlives bounds + let mut where_predicates = + modern::clean_predicates(cx, predicates, &mut modern::OpaqueTy::default()); + let mut bounds = match where_predicates.pop() { + Some(WherePredicate::BoundPredicate { bounds, .. }) => bounds, + Some(_) => unreachable!(), + None => Vec::new(), + }; - if !has_sized { - bounds.push(GenericBound::maybe_sized(cx)); - } + // FIXME: rewrite this, too + // - // Move trait bounds to the front. - bounds.sort_by_key(|b| !b.is_trait_bound()); + // // Move trait bounds to the front. + // bounds.sort_by_key(|b| !b.is_trait_bound()); // Add back a `Sized` bound if there are no *trait* bounds remaining (incl. `?Sized`). - // Since all potential trait bounds are at the front we can just check the first bound. - if bounds.first().map_or(true, |b| !b.is_trait_bound()) { + if bounds.iter().all(|bound| !bound.is_trait_bound()) { bounds.insert(0, GenericBound::sized(cx)); } if let Some(args) = cx.tcx.rendered_precise_capturing_args(impl_trait_def_id) { bounds.push(GenericBound::Use(args.to_vec())); } + // ImplTrait(bounds) } @@ -2744,18 +2590,19 @@ fn clean_maybe_renamed_item<'tcx>( let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id())); cx.with_param_env(def_id, |cx| { let kind = match item.kind { - ItemKind::Static(ty, mutability, body_id) => { - StaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: Some(body_id) }) - } - ItemKind::Const(ty, generics, body_id) => ConstantItem( - clean_generics(generics, cx), - Box::new(clean_ty(ty, cx)), - Constant { kind: ConstantKind::Local { body: body_id, def_id } }, - ), - ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy { - bounds: ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(), - generics: clean_generics(ty.generics, cx), + ItemKind::Static(ty, mutability, body_id) => StaticItem(Static { + type_: Box::new(clean_ty(ty, cx)), + mutability, + expr: Some(body_id), }), + ItemKind::Const(ty, generics, body_id) => ConstantItem(Box::new(Constant { + generics: clean_generics(generics, cx), + type_: clean_ty(ty, cx), + kind: ConstantKind::Local { body: body_id, def_id }, + })), + // clean_ty changes types which reference an OpaqueTy item to instead be + // an ImplTrait, so it's ok to return nothing here. + ItemKind::OpaqueTy(_) => return vec![], ItemKind::TyAlias(hir_ty, generics) => { *cx.current_type_aliases.entry(def_id).or_insert(0) += 1; let rustdoc_ty = clean_ty(hir_ty, cx); @@ -2838,7 +2685,7 @@ fn clean_maybe_renamed_item<'tcx>( ItemKind::Use(path, kind) => { return clean_use_statement(item, name, path, kind, cx, &mut FxHashSet::default()); } - _ => unreachable!("not yet converted"), + _ => span_bug!(item.span, "not yet converted"), }; vec![generate_item_with_correct_attrs( @@ -3109,7 +2956,7 @@ fn clean_maybe_renamed_foreign_item<'tcx>( ForeignFunctionItem(Box::new(Function { decl, generics }), safety) } hir::ForeignItemKind::Static(ty, mutability, safety) => ForeignStaticItem( - Static { type_: clean_ty(ty, cx), mutability, expr: None }, + Static { type_: Box::new(clean_ty(ty, cx)), mutability, expr: None }, safety, ), hir::ForeignItemKind::Type => ForeignTypeItem, diff --git a/src/librustdoc/clean/modern.rs b/src/librustdoc/clean/modern.rs new file mode 100644 index 0000000000000..12b7cbae8ddaf --- /dev/null +++ b/src/librustdoc/clean/modern.rs @@ -0,0 +1,392 @@ +#![allow(dead_code)] // FIXME + +use rustc_data_structures::unord::UnordSet; +use rustc_middle::ty::{self, ToPolyTraitRef, Ty, TyCtxt}; +use rustc_span::symbol::kw; +use rustc_span::Span; +use thin_vec::ThinVec; + +use super::{ + clean_middle_region, clean_middle_term, clean_middle_ty, clean_poly_trait_ref_with_constraints, + projection_to_path_segment, AssocItemConstraint, AssocItemConstraintKind, GenericBound, + WherePredicate, +}; +use crate::core::DocContext; + +// FIXME(return_type_notation, #123996): Support RTN. +// FIXME(async_closure): De-lower `AsyncFn*` bounds to `async Fn*` ones. + +// FIXME: experiment +pub(super) trait CleanPredicate<'tcx> { + fn elide_sized_bound_on(&mut self, ty: ty::Binder<'tcx, Ty<'tcx>>) -> bool; +} + +////////////// FIXME: temporary location + +#[derive(Default)] +pub(super) struct WhereClause { + pub(super) sized: UnordSet, +} + +impl<'tcx> CleanPredicate<'tcx> for WhereClause { + fn elide_sized_bound_on(&mut self, ty: ty::Binder<'tcx, Ty<'tcx>>) -> bool { + if let ty::Param(param_ty) = *ty.skip_binder().kind() + && param_ty.name != kw::SelfUpper + { + self.sized.insert(param_ty.index); + return true; + } + false + } +} + +#[derive(Default)] +pub(super) struct Apit { + sized: bool, +} + +impl<'tcx> CleanPredicate<'tcx> for Apit { + fn elide_sized_bound_on(&mut self, ty: ty::Binder<'tcx, Ty<'tcx>>) -> bool { + if let ty::Param(_) = ty.skip_binder().kind() { + self.sized = true; + return true; + } + false + } +} + +#[derive(Default)] +pub(super) struct OpaqueTy { + sized: bool, +} + +impl<'tcx> CleanPredicate<'tcx> for OpaqueTy { + fn elide_sized_bound_on(&mut self, ty: ty::Binder<'tcx, Ty<'tcx>>) -> bool { + // FIXME: is this correct? + if let ty::Alias(ty::Opaque, _) = ty.skip_binder().kind() { + eprintln!("HIT!"); + self.sized = true; + return true; + } + false + } +} + +////////////// + +// FIXME: we overflow the stack on RPITITs :( + +// FIXME: We 'need' to support arbitrarily nested ATBs +// like `A>` + +pub(super) fn clean_predicates<'tcx, C: CleanPredicate<'tcx>>( + cx: &mut DocContext<'tcx>, + mut predicates: Vec<(ty::Clause<'tcx>, Span)>, + cleaner: &mut C, +) -> ThinVec { + // FIXME: Ideally we'd only sort here if the item is an impl block (NB: def_kind() isn't reliable here + // bc the "item_def_id" doesn't refer to an impl block if this impl was synth'ed by auto_trait). + // FIXME: Also explain why we're doing this (at least for impls): namely `gather_explicit_predicates_of` + // reorders preds via `cgp::setup_constraining_predicates` if it's an impl + predicates.sort_by_key(|&(_, span)| span); + + let mut clauses = Default::default(); + + for (predicate, span) in predicates { + group_predicate(cx.tcx, predicate, span, &mut clauses, cleaner); + } + + // FIXME: Explain that reason why we need to go over stuff twice is because + // we first need to gather all projection predicates to be able to call + // clean_poly_trait_with_constraints which requires a full set of constraints + // NOTE: However, we might just get away with calling clean_poly_trait_ref + // and pushing the constraints later (similar to `simplify::merge_bounds`). + // FIXME: however, it makes things nicer actually to operate on ty:: things, not clean:: ones + // (interned equality, etc) + + clauses + .into_iter() + .filter_map(|clause| match clause { + Clause::BoundedTy { ty, bounds, .. } => clean_ty_clause(cx, ty, bounds, cleaner), + Clause::BoundedRe { re, bounds } => Some(clean_re_clause(re, bounds)), + }) + .collect() +} + +// FIXME: horrendous name +fn group_predicate<'tcx, C: CleanPredicate<'tcx>>( + tcx: TyCtxt<'tcx>, + predicate: ty::Clause<'tcx>, + span: Span, + clauses: &mut Vec>, // FIXME: ugly out param + cleaner: &mut C, +) { + let kind = predicate.kind(); + match kind.skip_binder() { + // FIXME(fmease): Acknowledge that we intentionally ignore polarity! + ty::ClauseKind::Trait(pred) => { + let pred = kind.rebind(pred); + let bounded_ty = pred.self_ty(); + + // FIXME: properly implement this + if tcx.is_lang_item(pred.def_id(), rustc_hir::LangItem::Sized) + && cleaner.elide_sized_bound_on(bounded_ty) + { + // FIXME: Instead of unconditionally dropping `Sized` bounds, we could make it so + // we only drop synthetic ones (by checking if the Span coincides with the span of + // the type parameter if the bounded ty is a type parameter). + // FIXME: Add back explainer about implicit Sized from mod simplify + return; + } + + // FIXME: I don't think this can handle `Trait>` (namely `Inner == ()`) + // FIXME: does this scale to assoc tys? we might want to allow the caller to specify + // the "base bounded ty" (Param for Normal&APIT, Alias(Opaque) for RPIT(IT?), Alias(Projection) for assoc ty item bounds) + if let ty::Alias(ty::Projection, alias_ty) = *bounded_ty.skip_binder().kind() + && let Some(Clause::BoundedTy { bounds, span: clause_span, .. }) = clauses.last_mut() + && clause_span.contains(span) // FIXME: explainer + && let Some(Bound::Trait(trait_ref, constraints)) = bounds.last_mut() + // FIXME: explain why skip_binder is okay here (relates to comment above) + && is_instance_of(tcx, trait_ref.skip_binder(), alias_ty.trait_ref(tcx)) + { + // FIXME: support constraints on this bound + let bound = Bound::Trait(pred.to_poly_trait_ref(), Vec::new()); + let bounded_alias_ty = pred.rebind(alias_ty); + + if let Some(Constraint::Bounds(alias_ty, alias_bounds)) = constraints.last_mut() + // FIXME: Audit (do we need to use is_instance of) + && *alias_ty == bounded_alias_ty //FIXME bad naming left<->right (both are bounded) + { + alias_bounds.push(bound); + } else { + constraints.push(Constraint::Bounds(bounded_alias_ty, vec![bound])); + } + return; + } + + // FIXME: Skip `Destruct` here + // // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op. + // // FIXME(effects) check constness + // if tcx.is_lang_item(pred.def_id(), hir::LangItem::Destruct) { + // return None; + // } + + let bound = Bound::Trait(pred.to_poly_trait_ref(), Vec::new()); + + if let Some(Clause::BoundedTy { ty, bounds, .. }) = clauses.last_mut() + && *ty == bounded_ty // FIXME: explain why `==` is okay here + { + bounds.push(bound); + } else { + clauses.push(Clause::BoundedTy { ty: bounded_ty, bounds: vec![bound], span }); + } + } + ty::ClauseKind::Projection(pred) => { + // FIXME: explain why it's fine to ignore polarity + if let Some(Clause::BoundedTy { bounds, .. }) = clauses.last_mut() + && let Some(Bound::Trait(trait_ref, constraints)) = bounds.last_mut() + // FIXME: Explain why this seems to be necessary + // FIXME: is skip_binder ok?? feels fishy + && is_instance_of(tcx, trait_ref.skip_binder(), pred.projection_term.trait_ref(tcx)) + { + // FIXME: explain why skip_binder is okay here (relates to comment above) + // FIXME: explain why this holds + // FIXME: this no longer holds + // debug_assert!(is_instance_of(tcx, trait_ref.skip_binder(), pred.projection_term.trait_ref(tcx))); + + constraints.push(Constraint::Equality(kind.rebind(pred))); + } else { + // FIXME: Explainer (synthetic `-> ()` has same span as trait ref, therefore they don't get placed after it). + // FIXME: make this more robust by also checking that the trait ref is a fn-family trait ref (incl. async ones) + // debug_assert_eq!(pred.term.as_type(), Some(tcx.types.unit)); + + // FIXME: Explainer why it's fine to drop things + // FIXME: however, make sure that `auto_trait.rs` actually conforms to the scheme + } + } + ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(bounded_re, bound)) => { + if let Some(Clause::BoundedRe { re, bounds }) = clauses.last_mut() + && *re == bounded_re + { + bounds.push(bound); + } else { + clauses.push(Clause::BoundedRe { re: bounded_re, bounds: vec![bound] }); + } + } + // FIXME: We also need to look for Alias(Projection): 'a to be able to resugar + // associated type bounds of the form `Trait` + ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(bounded_ty, bound)) => { + let bounded_ty = kind.rebind(bounded_ty); + + if let ty::Alias(ty::Projection, alias_ty) = *bounded_ty.skip_binder().kind() + && let Some(Clause::BoundedTy { bounds, span: clause_span, .. }) = clauses.last_mut() + && clause_span.contains(span) // FIXME: explainer + && let Some(Bound::Trait(trait_ref, constraints)) = bounds.last_mut() + // FIXME: explain why skip_binder is okay here (relates to comment above) + && is_instance_of(tcx, trait_ref.skip_binder(), alias_ty.trait_ref(tcx)) + { + let bound = Bound::Outlives(bound); + let bounded_alias_ty = bounded_ty.rebind(alias_ty); + + if let Some(Constraint::Bounds(alias_ty, alias_bounds)) = constraints.last_mut() + // FIXME: Audit (do we need to use is_instance of) + && *alias_ty == bounded_alias_ty //FIXME bad naming left<->right (both are bounded) + { + alias_bounds.push(bound); + } else { + constraints.push(Constraint::Bounds(bounded_alias_ty, vec![bound])); + } + return; + } + + if let Some(Clause::BoundedTy { ty, bounds, .. }) = clauses.last_mut() + && *ty == bounded_ty // FIXME: explain why `==` is okay here + { + bounds.push(Bound::Outlives(bound)); + } else { + clauses.push(Clause::BoundedTy { ty: bounded_ty, bounds: vec![Bound::Outlives(bound)], span }); + } + } + ty::ClauseKind::ConstArgHasType(_, _) + | ty::ClauseKind::WellFormed(_) + // FIXME(fmease): Check if we need to reify this for GCEs + | ty::ClauseKind::ConstEvaluatable(_) => {} + } +} + +fn clean_ty_clause<'tcx, C: CleanPredicate<'tcx>>( + cx: &mut DocContext<'tcx>, + bounded_ty: ty::Binder<'tcx, Ty<'tcx>>, + bounds: Vec>, + _cleaner: &mut C, // FIXME +) -> Option { + let bounds: Vec<_> = bounds.into_iter().map(|bound| clean_bound(cx, bound)).collect(); + + // FIXME: doing this in here isn't great... bc this leads to duplicate efforts + // if we don't have any preds (e.g., `X`) where we need to go through all + // "generics" "anyway" (NB: this module doesn't have a notion of "generics"!!!) + // if let ty::Param(param_ty) = bounded_ty.skip_binder().kind() + // && param_ty.name != kw::SelfUpper + // // FIXME: HACK + // && sized.insert(param_ty.index) + // { + // bounds.push(GenericBound::maybe_sized(cx)); + // } + + if bounds.is_empty() { + // FIXME: We might want to keep `where T:` (user-written) (Wf). + // However, we do need to skip here due to Sized/?Sized logic + return None; + } + + Some(WherePredicate::BoundPredicate { + ty: clean_middle_ty(bounded_ty, cx, None, None), + bounds, + bound_params: Vec::new(), // FIXME: reconstruct outer binder + }) +} + +fn clean_bound<'tcx>(cx: &mut DocContext<'tcx>, bound: Bound<'tcx>) -> GenericBound { + match bound { + // FIXME: filter out non-const Destruct + Bound::Trait(trait_ref, constraints) => { + let constraints = constraints + .into_iter() + .map(|constraint| clean_assoc_item_constraint(cx, constraint)) + .collect(); + + clean_poly_trait_ref_with_constraints(cx, trait_ref, constraints) + } + Bound::Outlives(bound) => { + // FIXME: expect instead of unwrap + GenericBound::Outlives(clean_middle_region(bound).unwrap()) + } + } +} + +fn clean_assoc_item_constraint<'tcx>( + cx: &mut DocContext<'tcx>, + constraint: Constraint<'tcx>, +) -> AssocItemConstraint { + match constraint { + Constraint::Equality(proj_pred) => AssocItemConstraint { + assoc: projection_to_path_segment( + // FIXME: This needs to be made resilient for `AliasTerm`s that are associated consts. + proj_pred.map_bound(|pred| pred.projection_term.expect_ty(cx.tcx)), + cx, + ), + kind: AssocItemConstraintKind::Equality { + term: clean_middle_term(proj_pred.term(), cx), + }, + }, + Constraint::Bounds(alias_ty, bounds) => AssocItemConstraint { + assoc: projection_to_path_segment(alias_ty, cx), + kind: AssocItemConstraintKind::Bound { + bounds: bounds.into_iter().map(|bound| clean_bound(cx, bound)).collect(), + }, + }, + } +} + +fn clean_re_clause<'tcx>( + bounded_re: ty::Region<'tcx>, + bounds: Vec>, +) -> WherePredicate { + WherePredicate::RegionPredicate { + lifetime: clean_middle_region(bounded_re).unwrap(), // FIXME: expect + // FIXME: expect + bounds: bounds + .into_iter() + .map(|bound| GenericBound::Outlives(clean_middle_region(bound).unwrap())) + .collect(), + } +} + +// FIXME: it's not really a "Bound" bc we duplicate self_ty for poly trait preds +// more appropriately, it's type-reindexed preds, kinda +// FIXME: explain that we have intermediary because relating clean types is slow and imprecise etc. +enum Clause<'tcx> { + BoundedTy { ty: ty::Binder<'tcx, Ty<'tcx>>, bounds: Vec>, span: Span }, // maybe record "outer bound var candidates" + BoundedRe { re: ty::Region<'tcx>, bounds: Vec> }, +} + +enum Bound<'tcx> { + Trait(ty::PolyTraitRef<'tcx>, Vec>), + Outlives(ty::Region<'tcx>), +} + +// FIXME: bad name, I guess +enum Constraint<'tcx> { + Equality(ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>), + Bounds(ty::Binder<'tcx, ty::AliasTy<'tcx>>, Vec>), +} + +// FIXME(fmease): Better name +// FIXME(fmease): Docs +fn is_instance_of<'tcx>( + tcx: TyCtxt<'tcx>, + child: ty::TraitRef<'tcx>, + trait_: ty::TraitRef<'tcx>, +) -> bool { + if child == trait_ { + return true; + } + + debug_assert!(tcx.generics_of(child.def_id).has_self); + + // FIXME: these are not the elaborated ones, can you find an example where this matters? + tcx.explicit_super_predicates_of(child.def_id) + .predicates + .iter() + .filter_map(|(pred, _)| { + let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder() else { + return None; + }; + if pred.trait_ref.self_ty() != tcx.types.self_param { + return None; + } + + Some(ty::EarlyBinder::bind(pred.trait_ref).instantiate(tcx, child.args)) + }) + .any(|child| is_instance_of(tcx, child, trait_)) +} diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index 1b7d84add1f85..d9c22b5e1bcef 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -11,165 +11,9 @@ //! This module attempts to reconstruct the original where and/or parameter //! bounds by special casing scenarios such as these. Fun! -use rustc_data_structures::fx::FxIndexMap; -use rustc_data_structures::unord::UnordSet; -use rustc_hir::def_id::DefId; -use rustc_middle::ty; use thin_vec::ThinVec; use crate::clean; -use crate::clean::GenericArgs as PP; -use crate::clean::WherePredicate as WP; -use crate::core::DocContext; - -pub(crate) fn where_clauses(cx: &DocContext<'_>, clauses: ThinVec) -> ThinVec { - // First, partition the where clause into its separate components. - // - // We use `FxIndexMap` so that the insertion order is preserved to prevent messing up to - // the order of the generated bounds. - let mut tybounds = FxIndexMap::default(); - let mut lifetimes = Vec::new(); - let mut equalities = Vec::new(); - - for clause in clauses { - match clause { - WP::BoundPredicate { ty, bounds, bound_params } => { - let (b, p): &mut (Vec<_>, Vec<_>) = tybounds.entry(ty).or_default(); - b.extend(bounds); - p.extend(bound_params); - } - WP::RegionPredicate { lifetime, bounds } => { - lifetimes.push((lifetime, bounds)); - } - WP::EqPredicate { lhs, rhs } => equalities.push((lhs, rhs)), - } - } - - // Look for equality predicates on associated types that can be merged into - // general bound predicates. - equalities.retain(|(lhs, rhs)| { - let Some((ty, trait_did, name)) = lhs.projection() else { - return true; - }; - let Some((bounds, _)) = tybounds.get_mut(ty) else { return true }; - merge_bounds(cx, bounds, trait_did, name, rhs) - }); - - // And finally, let's reassemble everything - let mut clauses = ThinVec::with_capacity(lifetimes.len() + tybounds.len() + equalities.len()); - clauses.extend( - lifetimes.into_iter().map(|(lt, bounds)| WP::RegionPredicate { lifetime: lt, bounds }), - ); - clauses.extend(tybounds.into_iter().map(|(ty, (bounds, bound_params))| WP::BoundPredicate { - ty, - bounds, - bound_params, - })); - clauses.extend(equalities.into_iter().map(|(lhs, rhs)| WP::EqPredicate { lhs, rhs })); - clauses -} - -pub(crate) fn merge_bounds( - cx: &clean::DocContext<'_>, - bounds: &mut Vec, - trait_did: DefId, - assoc: clean::PathSegment, - rhs: &clean::Term, -) -> bool { - !bounds.iter_mut().any(|b| { - let trait_ref = match *b { - clean::GenericBound::TraitBound(ref mut tr, _) => tr, - clean::GenericBound::Outlives(..) | clean::GenericBound::Use(_) => return false, - }; - // If this QPath's trait `trait_did` is the same as, or a supertrait - // of, the bound's trait `did` then we can keep going, otherwise - // this is just a plain old equality bound. - if !trait_is_same_or_supertrait(cx, trait_ref.trait_.def_id(), trait_did) { - return false; - } - let last = trait_ref.trait_.segments.last_mut().expect("segments were empty"); - - match last.args { - PP::AngleBracketed { ref mut constraints, .. } => { - constraints.push(clean::AssocItemConstraint { - assoc: assoc.clone(), - kind: clean::AssocItemConstraintKind::Equality { term: rhs.clone() }, - }); - } - PP::Parenthesized { ref mut output, .. } => match output { - Some(o) => assert_eq!(&clean::Term::Type(o.as_ref().clone()), rhs), - None => { - if *rhs != clean::Term::Type(clean::Type::Tuple(Vec::new())) { - *output = Some(Box::new(rhs.ty().unwrap().clone())); - } - } - }, - }; - true - }) -} - -fn trait_is_same_or_supertrait(cx: &DocContext<'_>, child: DefId, trait_: DefId) -> bool { - if child == trait_ { - return true; - } - let predicates = cx.tcx.explicit_super_predicates_of(child); - debug_assert!(cx.tcx.generics_of(child).has_self); - let self_ty = cx.tcx.types.self_param; - predicates - .predicates - .iter() - .filter_map(|(pred, _)| { - if let ty::ClauseKind::Trait(pred) = pred.kind().skip_binder() { - if pred.trait_ref.self_ty() == self_ty { Some(pred.def_id()) } else { None } - } else { - None - } - }) - .any(|did| trait_is_same_or_supertrait(cx, did, trait_)) -} - -pub(crate) fn sized_bounds(cx: &mut DocContext<'_>, generics: &mut clean::Generics) { - let mut sized_params = UnordSet::new(); - - // In the surface language, all type parameters except `Self` have an - // implicit `Sized` bound unless removed with `?Sized`. - // However, in the list of where-predicates below, `Sized` appears like a - // normal bound: It's either present (the type is sized) or - // absent (the type might be unsized) but never *maybe* (i.e. `?Sized`). - // - // This is unsuitable for rendering. - // Thus, as a first step remove all `Sized` bounds that should be implicit. - // - // Note that associated types also have an implicit `Sized` bound but we - // don't actually know the set of associated types right here so that - // should be handled when cleaning associated types. - generics.where_predicates.retain(|pred| { - if let WP::BoundPredicate { ty: clean::Generic(param), bounds, .. } = pred - && *param != rustc_span::symbol::kw::SelfUpper - && bounds.iter().any(|b| b.is_sized_bound(cx)) - { - sized_params.insert(*param); - false - } else { - true - } - }); - - // As a final step, go through the type parameters again and insert a - // `?Sized` bound for each one we didn't find to be `Sized`. - for param in &generics.params { - if let clean::GenericParamDefKind::Type { .. } = param.kind - && !sized_params.contains(¶m.name) - { - generics.where_predicates.push(WP::BoundPredicate { - ty: clean::Type::Generic(param.name), - bounds: vec![clean::GenericBound::maybe_sized(cx)], - bound_params: Vec::new(), - }) - } - } -} /// Move bounds that are (likely) directly attached to generic parameters from the where-clause to /// the respective parameter. diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 3709953159686..5a6360c563eb7 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -3,19 +3,14 @@ use std::cell::RefCell; use std::hash::Hash; use std::path::PathBuf; use std::rc::Rc; -use std::sync::Arc; -use std::sync::OnceLock as OnceCell; +use std::sync::{Arc, OnceLock as OnceCell}; use std::{fmt, iter}; use arrayvec::ArrayVec; -use thin_vec::ThinVec; - -use rustc_ast as ast; use rustc_ast_pretty::pprust; use rustc_attr::{ConstStability, Deprecation, Stability, StabilityLevel, StableSince}; use rustc_const_eval::const_eval::is_unstable_const_fn; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc_hir::lang_items::LangItem; @@ -35,7 +30,14 @@ use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{FileName, Loc, DUMMY_SP}; use rustc_target::abi::VariantIdx; use rustc_target::spec::abi::Abi; +use thin_vec::ThinVec; +use {rustc_ast as ast, rustc_hir as hir}; +pub(crate) use self::ItemKind::*; +pub(crate) use self::Type::{ + Array, BareFunction, BorrowedRef, DynTrait, Generic, ImplTrait, Infer, Primitive, QPath, + RawPointer, SelfTy, Slice, Tuple, +}; use crate::clean::cfg::Cfg; use crate::clean::clean_middle_path; use crate::clean::inline::{self, print_inlined_const}; @@ -46,13 +48,6 @@ use crate::formats::item_type::ItemType; use crate::html::render::Context; use crate::passes::collect_intra_doc_links::UrlFragment; -pub(crate) use self::ItemKind::*; -pub(crate) use self::SelfTy::*; -pub(crate) use self::Type::{ - Array, BareFunction, BorrowedRef, DynTrait, Generic, ImplTrait, Infer, Primitive, QPath, - RawPointer, Slice, Tuple, -}; - #[cfg(test)] mod tests; @@ -828,7 +823,6 @@ pub(crate) enum ItemKind { FunctionItem(Box), ModuleItem(Module), TypeAliasItem(Box), - OpaqueTyItem(OpaqueTy), StaticItem(Static), TraitItem(Box), TraitAliasItem(TraitAlias), @@ -852,9 +846,9 @@ pub(crate) enum ItemKind { PrimitiveItem(PrimitiveType), /// A required associated constant in a trait declaration. TyAssocConstItem(Generics, Box), - ConstantItem(Generics, Box, Constant), + ConstantItem(Box), /// An associated constant in a trait impl or a provided one in a trait declaration. - AssocConstItem(Generics, Box, ConstantKind), + AssocConstItem(Box), /// A required associated type in a trait declaration. /// /// The bounds may be non-empty if there is a `where` clause. @@ -886,9 +880,8 @@ impl ItemKind { | ImportItem(_) | FunctionItem(_) | TypeAliasItem(_) - | OpaqueTyItem(_) | StaticItem(_) - | ConstantItem(_, _, _) + | ConstantItem(_) | TraitAliasItem(_) | TyMethodItem(_) | MethodItem(_, _) @@ -920,9 +913,8 @@ impl ItemKind { | ExternCrateItem { .. } | FunctionItem(_) | TypeAliasItem(_) - | OpaqueTyItem(_) | StaticItem(_) - | ConstantItem(_, _, _) + | ConstantItem(_) | TraitAliasItem(_) | ForeignFunctionItem(_, _) | ForeignStaticItem(_, _) @@ -1391,8 +1383,8 @@ pub(crate) struct FnDecl { } impl FnDecl { - pub(crate) fn self_type(&self) -> Option { - self.inputs.values.get(0).and_then(|v| v.to_self()) + pub(crate) fn receiver_type(&self) -> Option<&Type> { + self.inputs.values.get(0).and_then(|v| v.to_receiver()) } } @@ -1410,27 +1402,9 @@ pub(crate) struct Argument { pub(crate) is_const: bool, } -#[derive(Clone, PartialEq, Debug)] -pub(crate) enum SelfTy { - SelfValue, - SelfBorrowed(Option, Mutability), - SelfExplicit(Type), -} - impl Argument { - pub(crate) fn to_self(&self) -> Option { - if self.name != kw::SelfLower { - return None; - } - if self.type_.is_self_type() { - return Some(SelfValue); - } - match self.type_ { - BorrowedRef { ref lifetime, mutability, ref type_ } if type_.is_self_type() => { - Some(SelfBorrowed(lifetime.clone(), mutability)) - } - _ => Some(SelfExplicit(self.type_.clone())), - } + pub(crate) fn to_receiver(&self) -> Option<&Type> { + if self.name == kw::SelfLower { Some(&self.type_) } else { None } } } @@ -1484,6 +1458,8 @@ pub(crate) enum Type { DynTrait(Vec, Option), /// A type parameter. Generic(Symbol), + /// The `Self` type. + SelfTy, /// A primitive (aka, builtin) type. Primitive(PrimitiveType), /// A function pointer: `extern "ABI" fn(...) -> ...` @@ -1578,6 +1554,8 @@ impl Type { // If both sides are generic, this returns true. (_, Type::Generic(_)) => true, (Type::Generic(_), _) => false, + // `Self` only matches itself. + (Type::SelfTy, Type::SelfTy) => true, // Paths account for both the path itself and its generics. (Type::Path { path: a }, Type::Path { path: b }) => { a.def_id() == b.def_id() @@ -1649,7 +1627,7 @@ impl Type { pub(crate) fn is_self_type(&self) -> bool { match *self { - Generic(name) => name == kw::SelfUpper, + SelfTy => true, _ => false, } } @@ -1676,21 +1654,16 @@ impl Type { matches!(self, Type::Tuple(v) if v.is_empty()) } - pub(crate) fn projection(&self) -> Option<(&Type, DefId, PathSegment)> { - if let QPath(box QPathData { self_type, trait_, assoc, .. }) = self { - Some((self_type, trait_.as_ref()?.def_id(), assoc.clone())) - } else { - None - } - } - - fn inner_def_id(&self, cache: Option<&Cache>) -> Option { + /// Use this method to get the [DefId] of a [clean] AST node, including [PrimitiveType]s. + /// + /// [clean]: crate::clean + pub(crate) fn def_id(&self, cache: &Cache) -> Option { let t: PrimitiveType = match *self { Type::Path { ref path } => return Some(path.def_id()), DynTrait(ref bounds, _) => return bounds.get(0).map(|b| b.trait_.def_id()), - Primitive(p) => return cache.and_then(|c| c.primitive_locations.get(&p).cloned()), + Primitive(p) => return cache.primitive_locations.get(&p).cloned(), BorrowedRef { type_: box Generic(..), .. } => PrimitiveType::Reference, - BorrowedRef { ref type_, .. } => return type_.inner_def_id(cache), + BorrowedRef { ref type_, .. } => return type_.def_id(cache), Tuple(ref tys) => { if tys.is_empty() { PrimitiveType::Unit @@ -1703,17 +1676,10 @@ impl Type { Array(..) => PrimitiveType::Array, Type::Pat(..) => PrimitiveType::Pat, RawPointer(..) => PrimitiveType::RawPointer, - QPath(box QPathData { ref self_type, .. }) => return self_type.inner_def_id(cache), - Generic(_) | Infer | ImplTrait(_) => return None, + QPath(box QPathData { ref self_type, .. }) => return self_type.def_id(cache), + Generic(_) | SelfTy | Infer | ImplTrait(_) => return None, }; - cache.and_then(|c| Primitive(t).def_id(c)) - } - - /// Use this method to get the [DefId] of a [clean] AST node, including [PrimitiveType]s. - /// - /// [clean]: crate::clean - pub(crate) fn def_id(&self, cache: &Cache) -> Option { - self.inner_def_id(Some(cache)) + Primitive(t).def_id(cache) } } @@ -2050,7 +2016,7 @@ impl From for PrimitiveType { pub(crate) struct Struct { pub(crate) ctor_kind: Option, pub(crate) generics: Generics, - pub(crate) fields: Vec, + pub(crate) fields: ThinVec, } impl Struct { @@ -2076,7 +2042,7 @@ impl Union { /// only as a variant in an enum. #[derive(Clone, Debug)] pub(crate) struct VariantStruct { - pub(crate) fields: Vec, + pub(crate) fields: ThinVec, } impl VariantStruct { @@ -2110,7 +2076,7 @@ pub(crate) struct Variant { #[derive(Clone, Debug)] pub(crate) enum VariantKind { CLike, - Tuple(Vec), + Tuple(ThinVec), Struct(VariantStruct), } @@ -2246,7 +2212,7 @@ impl Path { pub(crate) enum GenericArg { Lifetime(Lifetime), Type(Type), - Const(Box), + Const(Box), Infer, } @@ -2343,12 +2309,6 @@ pub(crate) struct TypeAlias { pub(crate) item_type: Option, } -#[derive(Clone, Debug)] -pub(crate) struct OpaqueTy { - pub(crate) bounds: Vec, - pub(crate) generics: Generics, -} - #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub(crate) struct BareFunctionDecl { pub(crate) safety: hir::Safety, @@ -2359,26 +2319,22 @@ pub(crate) struct BareFunctionDecl { #[derive(Clone, Debug)] pub(crate) struct Static { - pub(crate) type_: Type, + pub(crate) type_: Box, pub(crate) mutability: Mutability, pub(crate) expr: Option, } #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub(crate) struct Constant { + pub(crate) generics: Generics, pub(crate) kind: ConstantKind, + pub(crate) type_: Type, } #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub(crate) enum Term { Type(Type), - Constant(Constant), -} - -impl Term { - pub(crate) fn ty(&self) -> Option<&Type> { - if let Term::Type(ty) = self { Some(ty) } else { None } - } + Constant(ConstantKind), } impl From for Term { @@ -2584,8 +2540,9 @@ pub(crate) enum AssocItemConstraintKind { // Some nodes are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { - use super::*; use rustc_data_structures::static_assert_size; + + use super::*; // tidy-alphabetical-start static_assert_size!(Crate, 64); // frequently moved by-value static_assert_size!(DocFragment, 32); @@ -2594,7 +2551,7 @@ mod size_asserts { static_assert_size!(GenericParamDef, 40); static_assert_size!(Generics, 16); static_assert_size!(Item, 56); - static_assert_size!(ItemKind, 56); + static_assert_size!(ItemKind, 48); static_assert_size!(PathSegment, 40); static_assert_size!(Type, 32); // tidy-alphabetical-end diff --git a/src/librustdoc/clean/types/tests.rs b/src/librustdoc/clean/types/tests.rs index 4befce0717017..ddf6a11ec4e65 100644 --- a/src/librustdoc/clean/types/tests.rs +++ b/src/librustdoc/clean/types/tests.rs @@ -1,8 +1,8 @@ -use super::*; - use rustc_resolve::rustdoc::{unindent_doc_fragments, DocFragmentKind}; use rustc_span::create_default_session_globals_then; +use super::*; + fn create_doc_fragment(s: &str) -> Vec { vec![DocFragment { span: DUMMY_SP, diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 7c83d4387193f..68266f3506a01 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -1,3 +1,18 @@ +use std::assert_matches::debug_assert_matches; +use std::fmt::Write as _; +use std::mem; +use std::sync::LazyLock as Lazy; + +use rustc_ast::tokenstream::TokenTree; +use rustc_hir::def::{DefKind, Res}; +use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; +use rustc_metadata::rendered_const; +use rustc_middle::mir; +use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt, TypeVisitableExt}; +use rustc_span::symbol::{kw, sym, Symbol}; +use thin_vec::{thin_vec, ThinVec}; +use {rustc_ast as ast, rustc_hir as hir}; + use crate::clean::auto_trait::synthesize_auto_trait_impls; use crate::clean::blanket_impl::synthesize_blanket_impls; use crate::clean::render_macro_matchers::render_macro_matcher; @@ -10,22 +25,6 @@ use crate::clean::{ use crate::core::DocContext; use crate::html::format::visibility_to_src_with_space; -use rustc_ast as ast; -use rustc_ast::tokenstream::TokenTree; -use rustc_hir as hir; -use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; -use rustc_metadata::rendered_const; -use rustc_middle::mir; -use rustc_middle::ty::TypeVisitableExt; -use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt}; -use rustc_span::symbol::{kw, sym, Symbol}; -use std::assert_matches::debug_assert_matches; -use std::fmt::Write as _; -use std::mem; -use std::sync::LazyLock as Lazy; -use thin_vec::{thin_vec, ThinVec}; - #[cfg(test)] mod tests; @@ -469,7 +468,7 @@ pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type { match path.res { Res::PrimTy(p) => Primitive(PrimitiveType::from(p)), Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } if path.segments.len() == 1 => { - Generic(kw::SelfUpper) + Type::SelfTy } Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => Generic(path.segments[0].name), _ => { diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 45bd1616e83cd..e4549796b3e83 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -1,38 +1,32 @@ use std::collections::BTreeMap; use std::ffi::OsStr; -use std::fmt; -use std::io; use std::io::Read; -use std::path::Path; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::str::FromStr; +use std::{fmt, io}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::DiagCtxtHandle; use rustc_session::config::{ - self, parse_crate_types_from_list, parse_externs, parse_target_triple, CrateType, + self, get_cmd_lint_options, nightly_options, parse_crate_types_from_list, parse_externs, + parse_target_triple, CodegenOptions, CrateType, ErrorOutputType, Externs, Input, + JsonUnusedExterns, UnstableOptions, }; -use rustc_session::config::{get_cmd_lint_options, nightly_options}; -use rustc_session::config::{CodegenOptions, ErrorOutputType, Externs, Input}; -use rustc_session::config::{JsonUnusedExterns, UnstableOptions}; -use rustc_session::getopts; use rustc_session::lint::Level; use rustc_session::search_paths::SearchPath; -use rustc_session::EarlyDiagCtxt; +use rustc_session::{getopts, EarlyDiagCtxt}; use rustc_span::edition::Edition; use rustc_span::FileName; use rustc_target::spec::TargetTriple; use crate::core::new_dcx; use crate::externalfiles::ExternalHtml; -use crate::html; use crate::html::markdown::IdMap; use crate::html::render::StylePath; use crate::html::static_files; -use crate::opts; use crate::passes::{self, Condition}; use crate::scrape_examples::{AllCallLocations, ScrapeExamplesOptions}; -use crate::theme; +use crate::{html, opts, theme}; #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] pub(crate) enum OutputFormat { diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 5d8e61f9fa0d4..3e1271f198ca7 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -1,9 +1,16 @@ +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, LazyLock}; +use std::{io, mem}; + use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::sync::Lrc; use rustc_data_structures::unord::UnordSet; +use rustc_errors::codes::*; use rustc_errors::emitter::{stderr_destination, DynEmitter, HumanEmitter}; use rustc_errors::json::JsonEmitter; -use rustc_errors::{codes::*, DiagCtxtHandle, ErrorGuaranteed, TerminalUrl}; +use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, TerminalUrl}; use rustc_feature::UnstableFeatures; use rustc_hir::def::Res; use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId}; @@ -14,25 +21,17 @@ use rustc_lint::{late_lint_mod, MissingDoc}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::{ParamEnv, Ty, TyCtxt}; use rustc_session::config::{self, CrateType, ErrorOutputType, ResolveDocLinks}; -use rustc_session::lint; -use rustc_session::Session; +pub(crate) use rustc_session::config::{Options, UnstableOptions}; +use rustc_session::{lint, Session}; use rustc_span::symbol::sym; use rustc_span::{source_map, Span}; -use std::cell::RefCell; -use std::io; -use std::mem; -use std::rc::Rc; -use std::sync::LazyLock; -use std::sync::{atomic::AtomicBool, Arc}; - use crate::clean::inline::build_external_trait; use crate::clean::{self, ItemId}; use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions}; use crate::formats::cache::Cache; -use crate::passes::{self, Condition::*}; - -pub(crate) use rustc_session::config::{Options, UnstableOptions}; +use crate::passes::Condition::*; +use crate::passes::{self}; pub(crate) struct DocContext<'tcx> { pub(crate) tcx: TyCtxt<'tcx>, diff --git a/src/librustdoc/docfs.rs b/src/librustdoc/docfs.rs index 1f7abdfc31598..0ca070ddb8e66 100644 --- a/src/librustdoc/docfs.rs +++ b/src/librustdoc/docfs.rs @@ -9,11 +9,11 @@ //! abstraction. use std::cmp::max; -use std::fs; -use std::io; use std::path::{Path, PathBuf}; use std::sync::mpsc::Sender; use std::thread::available_parallelism; +use std::{fs, io}; + use threadpool::ThreadPool; pub(crate) trait PathError { diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 40cc4a9d44122..41eb142dd1e29 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -2,9 +2,16 @@ mod make; mod markdown; mod rust; +use std::fs::File; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::process::{self, Command, Stdio}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::{panic, str}; + pub(crate) use make::make_test; pub(crate) use markdown::test as test_markdown; - use rustc_ast as ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_errors::{ColorConfig, DiagCtxtHandle, ErrorGuaranteed, FatalError}; @@ -17,24 +24,13 @@ use rustc_span::edition::Edition; use rustc_span::symbol::sym; use rustc_span::FileName; use rustc_target::spec::{Target, TargetTriple}; - -use std::fs::File; -use std::io::{self, Write}; -use std::panic; -use std::path::{Path, PathBuf}; -use std::process::{self, Command, Stdio}; -use std::str; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; - use tempfile::{Builder as TempFileBuilder, TempDir}; +use self::rust::HirCollector; use crate::config::Options as RustdocOptions; use crate::html::markdown::{ErrorCodes, Ignore, LangString, MdRelLine}; use crate::lint::init_lints; -use self::rust::HirCollector; - /// Options that apply to all doctests in a crate or Markdown file (for `rustdoc foo.md`). #[derive(Clone)] pub(crate) struct GlobalTestOptions { diff --git a/src/librustdoc/doctest/rust.rs b/src/librustdoc/doctest/rust.rs index fc8e119ccc232..f179f3aa1c99b 100644 --- a/src/librustdoc/doctest/rust.rs +++ b/src/librustdoc/doctest/rust.rs @@ -2,7 +2,8 @@ use std::env; -use rustc_data_structures::{fx::FxHashSet, sync::Lrc}; +use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::sync::Lrc; use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; use rustc_hir::{self as hir, intravisit, CRATE_HIR_ID}; use rustc_middle::hir::map::Map; @@ -14,7 +15,8 @@ use rustc_span::source_map::SourceMap; use rustc_span::{BytePos, FileName, Pos, Span, DUMMY_SP}; use super::{DoctestVisitor, ScrapedDoctest}; -use crate::clean::{types::AttributesExt, Attributes}; +use crate::clean::types::AttributesExt; +use crate::clean::Attributes; use crate::html::markdown::{self, ErrorCodes, LangString, MdRelLine}; struct RustCollector { diff --git a/src/librustdoc/doctest/tests.rs b/src/librustdoc/doctest/tests.rs index 9124ec63267c3..0f13ee404c682 100644 --- a/src/librustdoc/doctest/tests.rs +++ b/src/librustdoc/doctest/tests.rs @@ -1,8 +1,9 @@ use std::path::PathBuf; -use super::{make_test, GlobalTestOptions}; use rustc_span::edition::DEFAULT_EDITION; +use super::{make_test, GlobalTestOptions}; + /// Default [`GlobalTestOptions`] for these unit tests. fn default_global_opts(crate_name: impl Into) -> GlobalTestOptions { GlobalTestOptions { diff --git a/src/librustdoc/externalfiles.rs b/src/librustdoc/externalfiles.rs index 62cdc0bd5a602..b81fc5a0a718e 100644 --- a/src/librustdoc/externalfiles.rs +++ b/src/librustdoc/externalfiles.rs @@ -1,12 +1,12 @@ -use crate::html::markdown::{ErrorCodes, HeadingOffset, IdMap, Markdown, Playground}; -use rustc_errors::DiagCtxtHandle; -use rustc_span::edition::Edition; -use std::fs; use std::path::Path; -use std::str; +use std::{fs, str}; +use rustc_errors::DiagCtxtHandle; +use rustc_span::edition::Edition; use serde::Serialize; +use crate::html::markdown::{ErrorCodes, HeadingOffset, IdMap, Markdown, Playground}; + #[derive(Clone, Debug, Serialize)] pub(crate) struct ExternalHtml { /// Content that will be included inline in the `` section of a diff --git a/src/librustdoc/fold.rs b/src/librustdoc/fold.rs index 346e9a4e113a5..bf82c911f290f 100644 --- a/src/librustdoc/fold.rs +++ b/src/librustdoc/fold.rs @@ -77,9 +77,8 @@ pub(crate) trait DocFolder: Sized { ExternCrateItem { src: _ } | ImportItem(_) | FunctionItem(_) - | OpaqueTyItem(_) | StaticItem(_) - | ConstantItem(_, _, _) + | ConstantItem(..) | TraitAliasItem(_) | TyMethodItem(_) | MethodItem(_, _) diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs index a3b88a880f2af..947bae99305a8 100644 --- a/src/librustdoc/formats/cache.rs +++ b/src/librustdoc/formats/cache.rs @@ -5,7 +5,8 @@ use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet}; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::Symbol; -use crate::clean::{self, types::ExternalLocation, ExternalCrate, ItemId, PrimitiveType}; +use crate::clean::types::ExternalLocation; +use crate::clean::{self, ExternalCrate, ItemId, PrimitiveType}; use crate::core::DocContext; use crate::fold::DocFolder; use crate::formats::item_type::ItemType; @@ -259,153 +260,21 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { } // Index this method for searching later on. - if let Some(s) = item.name.or_else(|| { - if item.is_stripped() { - None - } else if let clean::ImportItem(ref i) = *item.kind - && let clean::ImportKind::Simple(s) = i.kind - { - Some(s) - } else { - None - } - }) { - let (parent, is_inherent_impl_item) = match *item.kind { - clean::StrippedItem(..) => ((None, None), false), - clean::AssocConstItem(..) | clean::AssocTypeItem(..) - if self - .cache - .parent_stack - .last() - .is_some_and(|parent| parent.is_trait_impl()) => + let search_name = if !item.is_stripped() { + item.name.or_else(|| { + if let clean::ImportItem(ref i) = *item.kind + && let clean::ImportKind::Simple(s) = i.kind { - // skip associated items in trait impls - ((None, None), false) - } - clean::TyMethodItem(..) - | clean::TyAssocConstItem(..) - | clean::TyAssocTypeItem(..) - | clean::StructFieldItem(..) - | clean::VariantItem(..) => ( - ( - Some( - self.cache - .parent_stack - .last() - .expect("parent_stack is empty") - .item_id() - .expect_def_id(), - ), - Some(&self.cache.stack[..self.cache.stack.len() - 1]), - ), - false, - ), - clean::MethodItem(..) | clean::AssocConstItem(..) | clean::AssocTypeItem(..) => { - if self.cache.parent_stack.is_empty() { - ((None, None), false) - } else { - let last = self.cache.parent_stack.last().expect("parent_stack is empty 2"); - let did = match &*last { - ParentStackItem::Impl { - // impl Trait for &T { fn method(self); } - // - // When generating a function index with the above shape, we want it - // associated with `T`, not with the primitive reference type. It should - // show up as `T::method`, rather than `reference::method`, in the search - // results page. - for_: clean::Type::BorrowedRef { type_, .. }, - .. - } => type_.def_id(&self.cache), - ParentStackItem::Impl { for_, .. } => for_.def_id(&self.cache), - ParentStackItem::Type(item_id) => item_id.as_def_id(), - }; - let path = did - .and_then(|did| self.cache.paths.get(&did)) - // The current stack not necessarily has correlation - // for where the type was defined. On the other - // hand, `paths` always has the right - // information if present. - .map(|(fqp, _)| &fqp[..fqp.len() - 1]); - ((did, path), true) - } - } - _ => ((None, Some(&*self.cache.stack)), false), - }; - - match parent { - (parent, Some(path)) if is_inherent_impl_item || !self.cache.stripped_mod => { - debug_assert!(!item.is_stripped()); - - // A crate has a module at its root, containing all items, - // which should not be indexed. The crate-item itself is - // inserted later on when serializing the search-index. - if item.item_id.as_def_id().is_some_and(|idx| !idx.is_crate_root()) - && let ty = item.type_() - && (ty != ItemType::StructField - || u16::from_str_radix(s.as_str(), 10).is_err()) - { - let desc = - short_markdown_summary(&item.doc_value(), &item.link_names(self.cache)); - // For searching purposes, a re-export is a duplicate if: - // - // - It's either an inline, or a true re-export - // - It's got the same name - // - Both of them have the same exact path - let defid = (match &*item.kind { - &clean::ItemKind::ImportItem(ref import) => import.source.did, - _ => None, - }) - .or_else(|| item.item_id.as_def_id()); - // In case this is a field from a tuple struct, we don't add it into - // the search index because its name is something like "0", which is - // not useful for rustdoc search. - self.cache.search_index.push(IndexItem { - ty, - defid, - name: s, - path: join_with_double_colon(path), - desc, - parent, - parent_idx: None, - exact_path: None, - impl_id: if let Some(ParentStackItem::Impl { item_id, .. }) = - self.cache.parent_stack.last() - { - item_id.as_def_id() - } else { - None - }, - search_type: get_function_type_for_search( - &item, - self.tcx, - clean_impl_generics(self.cache.parent_stack.last()).as_ref(), - parent, - self.cache, - ), - aliases: item.attrs.get_doc_aliases(), - deprecation: item.deprecation(self.tcx), - }); - } + Some(s) + } else { + None } - (Some(parent), None) if is_inherent_impl_item => { - // We have a parent, but we don't know where they're - // defined yet. Wait for later to index this item. - let impl_generics = clean_impl_generics(self.cache.parent_stack.last()); - self.cache.orphan_impl_items.push(OrphanImplItem { - parent, - item: item.clone(), - impl_generics, - impl_id: if let Some(ParentStackItem::Impl { item_id, .. }) = - self.cache.parent_stack.last() - { - item_id.as_def_id() - } else { - None - }, - }); - } - _ => {} - } + }) + } else { + None + }; + if let Some(name) = search_name { + add_item_to_search_index(self.tcx, &mut self.cache, &item, name) } // Keep track of the fully qualified path for this item. @@ -441,16 +310,16 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { // `public_items` map, so we can skip inserting into the // paths map if there was already an entry present and we're // not a public item. - if !self.cache.paths.contains_key(&item.item_id.expect_def_id()) + let item_def_id = item.item_id.expect_def_id(); + if !self.cache.paths.contains_key(&item_def_id) || self .cache .effective_visibilities - .is_directly_public(self.tcx, item.item_id.expect_def_id()) + .is_directly_public(self.tcx, item_def_id) { - self.cache.paths.insert( - item.item_id.expect_def_id(), - (self.cache.stack.clone(), item.type_()), - ); + self.cache + .paths + .insert(item_def_id, (self.cache.stack.clone(), item.type_())); } } } @@ -462,7 +331,6 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { clean::ExternCrateItem { .. } | clean::ImportItem(..) - | clean::OpaqueTyItem(..) | clean::ImplItem(..) | clean::TyMethodItem(..) | clean::MethodItem(..) @@ -513,9 +381,7 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { && adt.is_fundamental() { for ty in generics { - if let Some(did) = ty.def_id(self.cache) { - dids.insert(did); - } + dids.extend(ty.def_id(self.cache)); } } } @@ -528,32 +394,26 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { .primitive_type() .and_then(|t| self.cache.primitive_locations.get(&t).cloned()); - if let Some(did) = did { - dids.insert(did); - } + dids.extend(did); } } if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) { for bound in generics { - if let Some(did) = bound.def_id(self.cache) { - dids.insert(did); - } + dids.extend(bound.def_id(self.cache)); } } let impl_item = Impl { impl_item: item }; - if impl_item.trait_did().map_or(true, |d| self.cache.traits.contains_key(&d)) { + let impl_did = impl_item.def_id(); + let trait_did = impl_item.trait_did(); + if trait_did.map_or(true, |d| self.cache.traits.contains_key(&d)) { for did in dids { - if self.impl_ids.entry(did).or_default().insert(impl_item.def_id()) { - self.cache - .impls - .entry(did) - .or_insert_with(Vec::new) - .push(impl_item.clone()); + if self.impl_ids.entry(did).or_default().insert(impl_did) { + self.cache.impls.entry(did).or_default().push(impl_item.clone()); } } } else { - let trait_did = impl_item.trait_did().expect("no trait did"); + let trait_did = trait_did.expect("no trait did"); self.cache.orphan_trait_impls.push((trait_did, dids, impl_item)); } None @@ -572,6 +432,152 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { } } +fn add_item_to_search_index(tcx: TyCtxt<'_>, cache: &mut Cache, item: &clean::Item, name: Symbol) { + // Item has a name, so it must also have a DefId (can't be an impl, let alone a blanket or auto impl). + let item_def_id = item.item_id.as_def_id().unwrap(); + let (parent_did, parent_path) = match *item.kind { + clean::StrippedItem(..) => return, + clean::AssocConstItem(..) | clean::AssocTypeItem(..) + if cache.parent_stack.last().is_some_and(|parent| parent.is_trait_impl()) => + { + // skip associated items in trait impls + return; + } + clean::TyMethodItem(..) + | clean::TyAssocConstItem(..) + | clean::TyAssocTypeItem(..) + | clean::StructFieldItem(..) + | clean::VariantItem(..) => { + // Don't index if containing module is stripped (i.e., private), + // or if item is tuple struct/variant field (name is a number -> not useful for search). + if cache.stripped_mod + || item.type_() == ItemType::StructField + && name.as_str().chars().all(|c| c.is_digit(10)) + { + return; + } + let parent_did = + cache.parent_stack.last().expect("parent_stack is empty").item_id().expect_def_id(); + let parent_path = &cache.stack[..cache.stack.len() - 1]; + (Some(parent_did), parent_path) + } + clean::MethodItem(..) | clean::AssocConstItem(..) | clean::AssocTypeItem(..) => { + let last = cache.parent_stack.last().expect("parent_stack is empty 2"); + let parent_did = match &*last { + // impl Trait for &T { fn method(self); } + // + // When generating a function index with the above shape, we want it + // associated with `T`, not with the primitive reference type. It should + // show up as `T::method`, rather than `reference::method`, in the search + // results page. + ParentStackItem::Impl { for_: clean::Type::BorrowedRef { type_, .. }, .. } => { + type_.def_id(&cache) + } + ParentStackItem::Impl { for_, .. } => for_.def_id(&cache), + ParentStackItem::Type(item_id) => item_id.as_def_id(), + }; + let Some(parent_did) = parent_did else { return }; + // The current stack reflects the CacheBuilder's recursive + // walk over HIR. For associated items, this is the module + // where the `impl` block is defined. That's an implementation + // detail that we don't want to affect the search engine. + // + // In particular, you can arrange things like this: + // + // #![crate_name="me"] + // mod private_mod { + // impl Clone for MyThing { fn clone(&self) -> MyThing { MyThing } } + // } + // pub struct MyThing; + // + // When that happens, we need to: + // - ignore the `cache.stripped_mod` flag, since the Clone impl is actually + // part of the public API even though it's defined in a private module + // - present the method as `me::MyThing::clone`, its publicly-visible path + // - deal with the fact that the recursive walk hasn't actually reached `MyThing` + // until it's already past `private_mod`, since that's first, and doesn't know + // yet if `MyThing` will actually be public or not (it could be re-exported) + // + // We accomplish the last two points by recording children of "orphan impls" + // in a field of the cache whose elements are added to the search index later, + // after cache building is complete (see `handle_orphan_impl_child`). + match cache.paths.get(&parent_did) { + Some((fqp, _)) => (Some(parent_did), &fqp[..fqp.len() - 1]), + None => { + handle_orphan_impl_child(cache, item, parent_did); + return; + } + } + } + _ => { + // Don't index if item is crate root, which is inserted later on when serializing the index. + // Don't index if containing module is stripped (i.e., private), + if item_def_id.is_crate_root() || cache.stripped_mod { + return; + } + (None, &*cache.stack) + } + }; + + debug_assert!(!item.is_stripped()); + + let desc = short_markdown_summary(&item.doc_value(), &item.link_names(cache)); + // For searching purposes, a re-export is a duplicate if: + // + // - It's either an inline, or a true re-export + // - It's got the same name + // - Both of them have the same exact path + let defid = match &*item.kind { + clean::ItemKind::ImportItem(import) => import.source.did.unwrap_or(item_def_id), + _ => item_def_id, + }; + let path = join_with_double_colon(parent_path); + let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() { + item_id.as_def_id() + } else { + None + }; + let search_type = get_function_type_for_search( + &item, + tcx, + clean_impl_generics(cache.parent_stack.last()).as_ref(), + parent_did, + cache, + ); + let aliases = item.attrs.get_doc_aliases(); + let deprecation = item.deprecation(tcx); + let index_item = IndexItem { + ty: item.type_(), + defid: Some(defid), + name, + path, + desc, + parent: parent_did, + parent_idx: None, + exact_path: None, + impl_id, + search_type, + aliases, + deprecation, + }; + cache.search_index.push(index_item); +} + +/// We have a parent, but we don't know where they're +/// defined yet. Wait for later to index this item. +/// See [`Cache::orphan_impl_items`]. +fn handle_orphan_impl_child(cache: &mut Cache, item: &clean::Item, parent_did: DefId) { + let impl_generics = clean_impl_generics(cache.parent_stack.last()); + let impl_id = if let Some(ParentStackItem::Impl { item_id, .. }) = cache.parent_stack.last() { + item_id.as_def_id() + } else { + None + }; + let orphan_item = + OrphanImplItem { parent: parent_did, item: item.clone(), impl_generics, impl_id }; + cache.orphan_impl_items.push(orphan_item); +} + pub(crate) struct OrphanImplItem { pub(crate) parent: DefId, pub(crate) impl_id: Option, diff --git a/src/librustdoc/formats/item_type.rs b/src/librustdoc/formats/item_type.rs index d5468798bd397..3dcef15b552b2 100644 --- a/src/librustdoc/formats/item_type.rs +++ b/src/librustdoc/formats/item_type.rs @@ -2,10 +2,9 @@ use std::fmt; -use serde::{Serialize, Serializer}; - use rustc_hir::def::{CtorOf, DefKind}; use rustc_span::hygiene::MacroKind; +use serde::{Serialize, Serializer}; use crate::clean; @@ -52,7 +51,7 @@ pub(crate) enum ItemType { AssocConst = 19, Union = 20, ForeignType = 21, - OpaqueTy = 22, + // OpaqueTy used to be here, but it was removed in #127276 ProcAttribute = 23, ProcDerive = 24, TraitAlias = 25, @@ -85,7 +84,6 @@ impl<'a> From<&'a clean::Item> for ItemType { clean::EnumItem(..) => ItemType::Enum, clean::FunctionItem(..) => ItemType::Function, clean::TypeAliasItem(..) => ItemType::TypeAlias, - clean::OpaqueTyItem(..) => ItemType::OpaqueTy, clean::StaticItem(..) => ItemType::Static, clean::ConstantItem(..) => ItemType::Constant, clean::TraitItem(..) => ItemType::Trait, @@ -192,7 +190,6 @@ impl ItemType { ItemType::AssocConst => "associatedconstant", ItemType::ForeignType => "foreigntype", ItemType::Keyword => "keyword", - ItemType::OpaqueTy => "opaque", ItemType::ProcAttribute => "attr", ItemType::ProcDerive => "derive", ItemType::TraitAlias => "traitalias", diff --git a/src/librustdoc/formats/mod.rs b/src/librustdoc/formats/mod.rs index 0056fb4853088..84adca8efa997 100644 --- a/src/librustdoc/formats/mod.rs +++ b/src/librustdoc/formats/mod.rs @@ -2,9 +2,8 @@ pub(crate) mod cache; pub(crate) mod item_type; pub(crate) mod renderer; -use rustc_hir::def_id::DefId; - pub(crate) use renderer::{run_format, FormatRenderer}; +use rustc_hir::def_id::DefId; use crate::clean::{self, ItemId}; use crate::html::render::Context; diff --git a/src/librustdoc/html/escape.rs b/src/librustdoc/html/escape.rs index ea4b573aeb955..691f86847b56d 100644 --- a/src/librustdoc/html/escape.rs +++ b/src/librustdoc/html/escape.rs @@ -5,6 +5,8 @@ use std::fmt; +use unicode_segmentation::UnicodeSegmentation; + /// Wrapper struct which will emit the HTML-escaped version of the contained /// string when passed to a format string. pub(crate) struct Escape<'a>(pub &'a str); @@ -74,3 +76,56 @@ impl<'a> fmt::Display for EscapeBodyText<'a> { Ok(()) } } + +/// Wrapper struct which will emit the HTML-escaped version of the contained +/// string when passed to a format string. This function also word-breaks +/// CamelCase and snake_case word names. +/// +/// This is only safe to use for text nodes. If you need your output to be +/// safely contained in an attribute, use [`Escape`]. If you don't know the +/// difference, use [`Escape`]. +pub(crate) struct EscapeBodyTextWithWbr<'a>(pub &'a str); + +impl<'a> fmt::Display for EscapeBodyTextWithWbr<'a> { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + let EscapeBodyTextWithWbr(text) = *self; + if text.len() < 8 { + return EscapeBodyText(text).fmt(fmt); + } + let mut last = 0; + let mut it = text.grapheme_indices(true).peekable(); + let _ = it.next(); // don't insert wbr before first char + while let Some((i, s)) = it.next() { + let pk = it.peek(); + if s.chars().all(|c| c.is_whitespace()) { + // don't need "First Second"; the space is enough + EscapeBodyText(&text[last..i]).fmt(fmt)?; + last = i; + continue; + } + let is_uppercase = || s.chars().any(|c| c.is_uppercase()); + let next_is_uppercase = + || pk.map_or(true, |(_, t)| t.chars().any(|c| c.is_uppercase())); + let next_is_underscore = || pk.map_or(true, |(_, t)| t.contains('_')); + let next_is_colon = || pk.map_or(true, |(_, t)| t.contains(':')); + if i - last > 3 && is_uppercase() && !next_is_uppercase() { + EscapeBodyText(&text[last..i]).fmt(fmt)?; + fmt.write_str("")?; + last = i; + } else if (s.contains(':') && !next_is_colon()) + || (s.contains('_') && !next_is_underscore()) + { + EscapeBodyText(&text[last..i + 1]).fmt(fmt)?; + fmt.write_str("")?; + last = i + 1; + } + } + if last < text.len() { + EscapeBodyText(&text[last..]).fmt(fmt)?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests; diff --git a/src/librustdoc/html/escape/tests.rs b/src/librustdoc/html/escape/tests.rs new file mode 100644 index 0000000000000..a09649e9e18dc --- /dev/null +++ b/src/librustdoc/html/escape/tests.rs @@ -0,0 +1,68 @@ +// basic examples +#[test] +fn escape_body_text_with_wbr() { + use super::EscapeBodyTextWithWbr as E; + // extreme corner cases + assert_eq!(&E("").to_string(), ""); + assert_eq!(&E("a").to_string(), "a"); + assert_eq!(&E("A").to_string(), "A"); + assert_eq!(&E("_").to_string(), "_"); + assert_eq!(&E(":").to_string(), ":"); + assert_eq!(&E(" ").to_string(), " "); + assert_eq!(&E("___________").to_string(), "___________"); + assert_eq!(&E(":::::::::::").to_string(), ":::::::::::"); + assert_eq!(&E(" ").to_string(), " "); + // real(istic) examples + assert_eq!(&E("FirstSecond").to_string(), "FirstSecond"); + assert_eq!(&E("First_Second").to_string(), "First_Second"); + assert_eq!(&E("First Second").to_string(), "First Second"); + assert_eq!(&E("First HSecond").to_string(), "First HSecond"); + assert_eq!(&E("First HTTPSecond").to_string(), "First HTTPSecond"); + assert_eq!(&E("First SecondThird").to_string(), "First SecondThird"); + assert_eq!(&E("First_Second").to_string(), "First<T>_Second"); + assert_eq!(&E("first_second").to_string(), "first_second"); + assert_eq!(&E("first:second").to_string(), "first:second"); + assert_eq!(&E("first::second").to_string(), "first::second"); + assert_eq!(&E("MY_CONSTANT").to_string(), "MY_CONSTANT"); + // a string won't get wrapped if it's less than 8 bytes + assert_eq!(&E("HashSet").to_string(), "HashSet"); + // an individual word won't get wrapped if it's less than 4 bytes + assert_eq!(&E("VecDequeue").to_string(), "VecDequeue"); + assert_eq!(&E("VecDequeueSet").to_string(), "VecDequeueSet"); + // how to handle acronyms + assert_eq!(&E("BTreeMap").to_string(), "BTreeMap"); + assert_eq!(&E("HTTPSProxy").to_string(), "HTTPSProxy"); + // more corners + assert_eq!(&E("ṼẽçÑñéå").to_string(), "ṼẽçÑñéå"); + assert_eq!(&E("V\u{0300}e\u{0300}c\u{0300}D\u{0300}e\u{0300}q\u{0300}u\u{0300}e\u{0300}u\u{0300}e\u{0300}").to_string(), "V\u{0300}e\u{0300}c\u{0300}D\u{0300}e\u{0300}q\u{0300}u\u{0300}e\u{0300}u\u{0300}e\u{0300}"); + assert_eq!(&E("LPFNACCESSIBLEOBJECTFROMWINDOW").to_string(), "LPFNACCESSIBLEOBJECTFROMWINDOW"); +} +// property test +#[test] +fn escape_body_text_with_wbr_makes_sense() { + use itertools::Itertools as _; + + use super::EscapeBodyTextWithWbr as E; + const C: [u8; 3] = [b'a', b'A', b'_']; + for chars in [ + C.into_iter(), + C.into_iter(), + C.into_iter(), + C.into_iter(), + C.into_iter(), + C.into_iter(), + C.into_iter(), + C.into_iter(), + ] + .into_iter() + .multi_cartesian_product() + { + let s = String::from_utf8(chars).unwrap(); + assert_eq!(s.len(), 8); + let esc = E(&s).to_string(); + assert!(!esc.contains("")); + assert!(!esc.ends_with("")); + assert!(!esc.starts_with("")); + assert_eq!(&esc.replace("", ""), &s); + } +} diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 055781f7fed72..b5ab6a35fdb9d 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -12,11 +12,10 @@ use std::cell::Cell; use std::fmt::{self, Display, Write}; use std::iter::{self, once}; -use rustc_ast as ast; +use itertools::Itertools; use rustc_attr::{ConstStability, StabilityLevel, StableSince}; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxHashSet; -use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_metadata::creader::{CStore, LoadedMacro}; @@ -25,21 +24,18 @@ use rustc_middle::ty::TyCtxt; use rustc_span::symbol::kw; use rustc_span::{sym, Symbol}; use rustc_target::spec::abi::Abi; +use {rustc_ast as ast, rustc_hir as hir}; -use itertools::Itertools; - -use crate::clean::{ - self, types::ExternalLocation, utils::find_nearest_parent_module, ExternalCrate, PrimitiveType, -}; +use super::url_parts_builder::{estimate_item_path_byte_length, UrlPartsBuilder}; +use crate::clean::types::ExternalLocation; +use crate::clean::utils::find_nearest_parent_module; +use crate::clean::{self, ExternalCrate, PrimitiveType}; use crate::formats::cache::Cache; use crate::formats::item_type::ItemType; -use crate::html::escape::Escape; +use crate::html::escape::{Escape, EscapeBodyText}; use crate::html::render::Context; use crate::passes::collect_intra_doc_links::UrlFragment; -use super::url_parts_builder::estimate_item_path_byte_length; -use super::url_parts_builder::UrlPartsBuilder; - pub(crate) trait Print { fn print(self, buffer: &mut Buffer); } @@ -375,7 +371,7 @@ impl clean::Lifetime { } } -impl clean::Constant { +impl clean::ConstantKind { pub(crate) fn print(&self, tcx: TyCtxt<'_>) -> impl Display + '_ { let expr = self.expr(tcx); display_fn( @@ -992,6 +988,7 @@ pub(crate) fn anchor<'a, 'cx: 'a>( f, r#"{text}"#, path = join_with_double_colon(&fqp), + text = EscapeBodyText(text.as_str()), ) } else { f.write_str(text.as_str()) @@ -1009,6 +1006,7 @@ fn fmt_type<'cx>( match *t { clean::Generic(name) => f.write_str(name.as_str()), + clean::SelfTy => f.write_str("Self"), clean::Type::Path { ref path } => { // Paths like `T::Output` and `Self::Output` should be rendered with all segments. let did = path.def_id(); @@ -1455,29 +1453,22 @@ impl clean::FnDecl { let last_input_index = self.inputs.values.len().checked_sub(1); for (i, input) in self.inputs.values.iter().enumerate() { - if let Some(selfty) = input.to_self() { + if let Some(selfty) = input.to_receiver() { match selfty { - clean::SelfValue => { + clean::SelfTy => { write!(f, "self")?; } - clean::SelfBorrowed(Some(ref lt), mutability) => { - write!( - f, - "{amp}{lifetime} {mutability}self", - lifetime = lt.print(), - mutability = mutability.print_with_space(), - )?; - } - clean::SelfBorrowed(None, mutability) => { - write!( - f, - "{amp}{mutability}self", - mutability = mutability.print_with_space(), - )?; + clean::BorrowedRef { lifetime, mutability, type_: box clean::SelfTy } => { + write!(f, "{amp}")?; + match lifetime { + Some(lt) => write!(f, "{lt} ", lt = lt.print())?, + None => {} + } + write!(f, "{mutability}self", mutability = mutability.print_with_space())?; } - clean::SelfExplicit(ref typ) => { + _ => { write!(f, "self: ")?; - typ.print(cx).fmt(f)?; + selfty.print(cx).fmt(f)?; } } } else { diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index 336d18a1df1c6..29b4889a6abbd 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -5,10 +5,6 @@ //! //! Use the `render_with_highlighting` to highlight some rust code. -use crate::clean::PrimitiveType; -use crate::html::escape::EscapeBodyText; -use crate::html::render::{Context, LinkFromSrc}; - use std::collections::VecDeque; use std::fmt::{Display, Write}; @@ -19,6 +15,9 @@ use rustc_span::symbol::Symbol; use rustc_span::{BytePos, Span, DUMMY_SP}; use super::format::{self, Buffer}; +use crate::clean::PrimitiveType; +use crate::html::escape::EscapeBodyText; +use crate::html::render::{Context, LinkFromSrc}; /// This type is needed in case we want to render links on items to allow to go to their definition. pub(crate) struct HrefContext<'a, 'tcx> { diff --git a/src/librustdoc/html/highlight/tests.rs b/src/librustdoc/html/highlight/tests.rs index 4c0874a686fe9..9d511018decd6 100644 --- a/src/librustdoc/html/highlight/tests.rs +++ b/src/librustdoc/html/highlight/tests.rs @@ -1,9 +1,10 @@ -use super::{write_code, DecorationInfo}; -use crate::html::format::Buffer; use expect_test::expect_file; use rustc_data_structures::fx::FxHashMap; use rustc_span::create_default_session_globals_then; +use super::{write_code, DecorationInfo}; +use crate::html::format::Buffer; + const STYLE: &str = r#"