From 75657d5289b9ac3ca4b72279fb700a037975eb57 Mon Sep 17 00:00:00 2001 From: schneems Date: Fri, 17 Mar 2023 12:42:40 -0500 Subject: [PATCH 001/116] Add Command environment variable inheritance docs The interaction between the environment variable methods can be confusing. Specifically `env_clear` and `remove_env` have a side effects not mentioned: they disable inheriting environment variables from the parent process. I wanted to fully document this behavior as well as explain relevant edge cases in each of the `Command` env methods. This is further confused by the return of `get_envs` which will return key/None if `remove_env` has been used, but an empty iterator if `env_clear` has been called. Or a non-empty iterator if `env_clear` was called and later explicit mappings are added. Currently there is no way (that I'm able to find) of observing whether or not the internal `env_clear=true` been toggled on the `Command` struct via its public API. Ultimately environment variable mappings can be in one of several states: - Explicitly set value (via `envs` / `env`) will take precedence over parent mapping - Not explicitly set, will inherit mapping from parent - Explicitly removed via `remove_env`, this single mapping will not inherit from parent - Implicitly removed via `env_clear`, no mappings will inherit from parent I tried to represent this in the relevant sections of the docs. This is my second ever doc PR (whoop!). I'm happy to take specific or general doc feedback. Also happy to explain the logic behind any changes or additions I made. --- library/std/src/process.rs | 76 ++++++++++++++++++++++++++++++-------- 1 file changed, 61 insertions(+), 15 deletions(-) diff --git a/library/std/src/process.rs b/library/std/src/process.rs index 1952e19e6072..086eae334404 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -644,10 +644,19 @@ impl Command { self } - /// Inserts or updates an environment variable mapping. + /// Inserts or updates an explicit environment variable mapping. /// - /// Note that environment variable names are case-insensitive (but case-preserving) on Windows, - /// and case-sensitive on all other platforms. + /// This method allows you to add an environment variable mapping to the spawned process or + /// overwrite a previously set value. You can use [`Command::envs`] to set multiple environment + /// variables simultaneously. + /// + /// Child processes will inherit environment variables from their parent process by default. + /// Environment variables explicitly set using [`Command::env`] take precedence over inherited + /// variables. You can disable environment variable inheritance entirely using + /// [`Command::env_clear`] or for a single key using [`Command::env_remove`]. + /// + /// Note that environment variable names are case-insensitive (but + /// case-preserving) on Windows and case-sensitive on all other platforms. /// /// # Examples /// @@ -671,7 +680,19 @@ impl Command { self } - /// Adds or updates multiple environment variable mappings. + /// Inserts or updates multiple explicit environment variable mappings. + /// + /// This method allows you to add multiple environment variable mappings to the spawned process + /// or overwrite previously set values. You can use [`Command::env`] to set a single environment + /// variable. + /// + /// Child processes will inherit environment variables from their parent process by default. + /// Environment variables explicitly set using [`Command::envs`] take precedence over inherited + /// variables. You can disable environment variable inheritance entirely using + /// [`Command::env_clear`] or for a single key using [`Command::env_remove`]. + /// + /// Note that environment variable names are case-insensitive (but case-preserving) on Windows + /// and case-sensitive on all other platforms. /// /// # Examples /// @@ -708,7 +729,18 @@ impl Command { self } - /// Removes an environment variable mapping. + /// Removes an explicitly set environment variable and prevents inheriting it from a parent + /// process. + /// + /// This method will remove the explicit value of an environment variable set via + /// [`Command::env`] or [`Command::envs`]. In addition, it will prevent the spawned child + /// process from inheriting that environment variable from its parent process. + /// + /// After calling [`Command::env_remove`], the value associated with its key from + /// [`Command::get_envs`] will be [`None`]. + /// + /// To clear all explicitly set environment variables and disable all environment variable + /// inheritance, you can use [`Command::env_clear`]. /// /// # Examples /// @@ -728,7 +760,17 @@ impl Command { self } - /// Clears the entire environment map for the child process. + /// Clears all explicitly set environment variables and prevents inheriting any parent process + /// environment variables. + /// + /// This method will remove all explicitly added environment variables set via [`Command::env`] + /// or [`Command::envs`]. In addition, it will prevent the spawned child process from inheriting + /// any environment variable from its parent process. + /// + /// After calling [`Command::env_remove`], the iterator from [`Command::get_envs`] will be + /// empty. + /// + /// You can use [`Command::env_remove`] to clear a single mapping. /// /// # Examples /// @@ -980,17 +1022,21 @@ impl Command { CommandArgs { inner: self.inner.get_args() } } - /// Returns an iterator of the environment variables that will be set when - /// the process is spawned. + /// Returns an iterator of the environment variables explicitly set for the child process. /// - /// Each element is a tuple `(&OsStr, Option<&OsStr>)`, where the first - /// value is the key, and the second is the value, which is [`None`] if - /// the environment variable is to be explicitly removed. + /// Environment variables explicitly set using [`Command::env`], [`Command::envs`], and + /// [`Command::env_remove`] can be retrieved with this method. /// - /// This only includes environment variables explicitly set with - /// [`Command::env`], [`Command::envs`], and [`Command::env_remove`]. It - /// does not include environment variables that will be inherited by the - /// child process. + /// Note that this output does not include environment variables inherited from the parent + /// process. + /// + /// Each element is a tuple key/value pair `(&OsStr, Option<&OsStr>)`. A [`None`] value + /// indicates its key was explicitly removed via [`Command::env_clear`]. The associated key for + /// the [`None`] value will no longer inherit from its parent process. + /// + /// An empty iterator can indicate that no explicit mappings were added or that + /// [`Command::env_clear`] was called. After calling [`Command::env_clear`], the child process + /// will not inherit any environment variables from its parent process. /// /// # Examples /// From 2e924bbef303ee8fc610e49d81825c2263b0b4bf Mon Sep 17 00:00:00 2001 From: Arpad Borsos Date: Fri, 28 Oct 2022 11:43:30 +0200 Subject: [PATCH 002/116] Stabilize rustdoc `--test-run-directory` --- src/doc/rustdoc/src/command-line-arguments.md | 15 ++++++++++++++- .../write-documentation/documentation-tests.md | 12 ++++++++++++ src/librustdoc/lib.rs | 2 +- tests/rustdoc-ui/run-directory.rs | 4 ++-- 4 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/doc/rustdoc/src/command-line-arguments.md b/src/doc/rustdoc/src/command-line-arguments.md index 2a2e51b2f633..e80ee08aa305 100644 --- a/src/doc/rustdoc/src/command-line-arguments.md +++ b/src/doc/rustdoc/src/command-line-arguments.md @@ -179,7 +179,7 @@ $ rustdoc src/lib.rs --test This flag will run your code examples as tests. For more, see [the chapter on documentation tests](write-documentation/documentation-tests.md). -See also `--test-args`. +See also `--test-args` and `--test-run-directory`. ## `--test-args`: pass options to test runner @@ -194,6 +194,19 @@ For more, see [the chapter on documentation tests](write-documentation/documenta See also `--test`. +## `--test-run-directory`: run code examples in a specific directory + +Using this flag looks like this: + +```bash +$ rustdoc src/lib.rs --test --test-run-directory=/path/to/working/directory +``` + +This flag will run your code examples in the specified working directory. +For more, see [the chapter on documentation tests](write-documentation/documentation-tests.md). + +See also `--test`. + ## `--target`: generate documentation for the specified target triple Using this flag looks like this: diff --git a/src/doc/rustdoc/src/write-documentation/documentation-tests.md b/src/doc/rustdoc/src/write-documentation/documentation-tests.md index 1cb5b049df40..a7d3186fb78b 100644 --- a/src/doc/rustdoc/src/write-documentation/documentation-tests.md +++ b/src/doc/rustdoc/src/write-documentation/documentation-tests.md @@ -443,3 +443,15 @@ pub struct ReadmeDoctests; This will include your README as documentation on the hidden struct `ReadmeDoctests`, which will then be tested alongside the rest of your doctests. + +## Controlling the compilation and run directories + +By default, `rustdoc --test` will compile and run documentation test examples +from the same working directory. +The compilation directory is being used for compiler diagnostics, the `file!()` macro and +the output of `rustdoc` test runner itself, whereas the run directory has an influence on file-system +operations within documentation test examples, such as `std::fs::read_to_string`. + +The `--test-run-directory` flag allows controlling the run directory separately from the compilation directory. +This is particularly useful in workspaces, where compiler invocations and thus diagnostics should be +relative to the workspace directory, but documentation test examples should run relative to the crate directory. diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 4fcf0873600a..6d78bd6b9a77 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -284,7 +284,7 @@ fn opts() -> Vec { stable("test-args", |o| { o.optmulti("", "test-args", "arguments to pass to the test runner", "ARGS") }), - unstable("test-run-directory", |o| { + stable("test-run-directory", |o| { o.optopt( "", "test-run-directory", diff --git a/tests/rustdoc-ui/run-directory.rs b/tests/rustdoc-ui/run-directory.rs index bbceaaf824f9..b8d0647f08d8 100644 --- a/tests/rustdoc-ui/run-directory.rs +++ b/tests/rustdoc-ui/run-directory.rs @@ -2,8 +2,8 @@ // revisions: correct incorrect // check-pass -// [correct]compile-flags:--test --test-run-directory={{src-base}} -Zunstable-options -// [incorrect]compile-flags:--test --test-run-directory={{src-base}}/coverage -Zunstable-options +// [correct]compile-flags:--test --test-run-directory={{src-base}} +// [incorrect]compile-flags:--test --test-run-directory={{src-base}}/coverage // normalize-stdout-test: "tests/rustdoc-ui" -> "$$DIR" // normalize-stdout-test "finished in \d+\.\d+s" -> "finished in $$TIME" From 8d4cccd168772849895492fad9486c6f6c7a74f4 Mon Sep 17 00:00:00 2001 From: clubby789 Date: Tue, 4 Apr 2023 21:59:06 +0100 Subject: [PATCH 003/116] Add links from `core::cmp` derives to their traits --- library/core/src/cmp.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index 5b5f55d0e65b..55331475aff2 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -231,7 +231,8 @@ pub trait PartialEq { } } -/// Derive macro generating an impl of the trait `PartialEq`. +/// Derive macro generating an impl of the trait [`PartialEq`]. +/// The behavior of this macro is described in detail [here](PartialEq#derivable). #[rustc_builtin_macro] #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] #[allow_internal_unstable(core_intrinsics, structural_match)] @@ -297,7 +298,7 @@ pub trait Eq: PartialEq { fn assert_receiver_is_total_eq(&self) {} } -/// Derive macro generating an impl of the trait `Eq`. +/// Derive macro generating an impl of the trait [`Eq`]. #[rustc_builtin_macro] #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match, no_coverage)] @@ -859,7 +860,8 @@ pub trait Ord: Eq + PartialOrd { } } -/// Derive macro generating an impl of the trait `Ord`. +/// Derive macro generating an impl of the trait [`Ord`]. +/// The behavior of this macro is described in detail [here](Ord#derivable). #[rustc_builtin_macro] #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] #[allow_internal_unstable(core_intrinsics)] @@ -1138,7 +1140,8 @@ pub trait PartialOrd: PartialEq { } } -/// Derive macro generating an impl of the trait `PartialOrd`. +/// Derive macro generating an impl of the trait [`PartialOrd`]. +/// The behavior of this macro is described in detail [here](PartialOrd#derivable). #[rustc_builtin_macro] #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] #[allow_internal_unstable(core_intrinsics)] From af3bf85311023f8cbee6a8268a917aec1b090218 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Thu, 6 Apr 2023 17:41:51 -0700 Subject: [PATCH 004/116] Add 1.69.0 release notes --- RELEASES.md | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/RELEASES.md b/RELEASES.md index b923f87abfd4..f07b97e2acdc 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,3 +1,112 @@ +Version 1.69.0 (2023-04-20) +========================== + + + +Language +-------- + +- [Deriving built-in traits on packed structs works with `Copy` fields.](https://github.com/rust-lang/rust/pull/104429/) +- [Stabilize the `cmpxchg16b` target feature on x86 and x86_64.](https://github.com/rust-lang/rust/pull/106774/) +- [Add normalization to satisfy trait bounds involving type projections.](https://github.com/rust-lang/rust/pull/103695/) +- [Add normalization that allows type projections in union fields.](https://github.com/rust-lang/rust/pull/106938/) +- [Allow `Self: Autotrait` bounds on dyn-safe trait methods.](https://github.com/rust-lang/rust/pull/107082/) +- [Treat `str` as containing `[u8]` for auto trait purposes.](https://github.com/rust-lang/rust/pull/107941/) + + + +Compiler +-------- + +- [Upgrade mingw-w64 on CI to GCC 12.3.](https://github.com/rust-lang/rust/pull/100178/) +- [Rework min_choice algorithm of member constraints.](https://github.com/rust-lang/rust/pull/105300/) +- [Support `true` and `false` as boolean flags in compiler arguments.](https://github.com/rust-lang/rust/pull/107043/) +- [Default `repr(C)` enums to `c_int` size.](https://github.com/rust-lang/rust/pull/107592/) + + + +Libraries +--------- + +- [Implement the unstable `DispatchFromDyn` for cell types, allowing downstream experimentation with custom method receivers.](https://github.com/rust-lang/rust/pull/97373/) +- [Document that `fmt::Arguments::as_str()` may return `Some(_)` in more cases after optimization, subject to change.](https://github.com/rust-lang/rust/pull/106823/) +- [Implement `AsFd` and `AsRawFd` for `Rc`.](https://github.com/rust-lang/rust/pull/107317/) +- [Move `IpAddr`, `SocketAddr` and V4+V6 related types to `core`](https://github.com/rust-lang/rust/pull/104265/) + + + +Stabilized APIs +--------------- + +- [`CStr::from_bytes_until_nul`](https://doc.rust-lang.org/stable/core/ffi/struct.CStr.html#method.from_bytes_until_nul) +- [`core::ffi::FromBytesUntilNulError`](https://doc.rust-lang.org/stable/core/ffi/struct.FromBytesUntilNulError.html) + +These APIs are now stable in const contexts: + +- [`SocketAddr::new`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.new) +- [`SocketAddr::ip`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.ip) +- [`SocketAddr::port`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.port) +- [`SocketAddr::is_ipv4`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.is_ipv4) +- [`SocketAddr::is_ipv6`](https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.is_ipv6) +- [`SocketAddrV4::new`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.new) +- [`SocketAddrV4::ip`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.ip) +- [`SocketAddrV4::port`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.port) +- [`SocketAddrV6::new`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.new) +- [`SocketAddrV6::ip`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.ip) +- [`SocketAddrV6::port`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.port) +- [`SocketAddrV6::flowinfo`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.flowinfo) +- [`SocketAddrV6::scope_id`](https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.scope_id) + + + +Cargo +----- + +- [Added '-C' flag for changing current dir before build](https://github.com/rust-lang/cargo/pull/10952/) +- [Cargo now suggests `cargo fix` or `cargo clippy --fix` when compilation warnings/errors are auto-fixable.](https://github.com/rust-lang/cargo/pull/11558/) +- [Cargo now suggests `cargo add` if you try to install a library crate.](https://github.com/rust-lang/cargo/pull/11410/) +- [Cargo now sets `CARGO_BIN_NAME` environment variable also for binary examples.](https://github.com/rust-lang/cargo/pull/11705/) + + + +Rustdoc +----- + +- [Vertically compact trait bound formatting.](https://github.com/rust-lang/rust/pull/102842/) +- [Only include stable lints in `rustdoc::all` group.](https://github.com/rust-lang/rust/pull/106316/) +- [Compute maximum Levenshtein distance based on the query.](https://github.com/rust-lang/rust/pull/107141/) +- [Remove inconsistently-present sidebar tooltips.](https://github.com/rust-lang/rust/pull/107490/) +- [Search by macro when query ends with `!`.](https://github.com/rust-lang/rust/pull/108143/) + + + +Misc +---- + + + +Compatibility Notes +------------------- + +- [Remove `-Zsave-analysis` from the compiler, which was primarily intended for RLS.](https://github.com/rust-lang/rust/pull/101841/) The `rust-analysis` component from `rustup` now only contains a warning placeholder. +- [Unaligned references to packed fields are now a hard error.](https://github.com/rust-lang/rust/pull/102513/) This has been a warning since 1.53, and denied by default with a future-compatibility warning since 1.62. +- [Update the minimum external LLVM to 14.](https://github.com/rust-lang/rust/pull/107573/) +- [Cargo now emits errors on invalid alphanumeric token for crates.io.](https://github.com/rust-lang/cargo/pull/11600/) +- [When `default-features` is set to false of a workspace dependency, and an inherited dependency of a member has `default-features = true`, Cargo will enable default features of that dependency.](https://github.com/rust-lang/cargo/pull/11409/) +- [Cargo denies `CARGO_HOME` in the `[env]` configuration table. Cargo itself doesn't pick up this value, but recursive calls to cargo will.](https://github.com/rust-lang/cargo/pull/11644/) +- [Debuginfo for build dependencies is now off if not explicit set. This is expected to boost the overall build time.](https://github.com/rust-lang/cargo/pull/11252/) + + + +Internal Changes +---------------- + +These changes do not affect any public interfaces of Rust, but they represent +significant improvements to the performance or internals of rustc and related +tools. + +- [Move format_args!() into AST (and expand it during AST lowering)](https://github.com/rust-lang/rust/pull/106745/) + Version 1.68.2 (2023-03-28) =========================== From 21f10dd1b9f30199d0553d581399d6bb9dac5be8 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Thu, 6 Apr 2023 19:25:49 -0700 Subject: [PATCH 005/116] Cargo only suggests fixes for warnings Co-authored-by: Scott Schafer --- RELEASES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index f07b97e2acdc..e33a695212b7 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -63,7 +63,7 @@ Cargo ----- - [Added '-C' flag for changing current dir before build](https://github.com/rust-lang/cargo/pull/10952/) -- [Cargo now suggests `cargo fix` or `cargo clippy --fix` when compilation warnings/errors are auto-fixable.](https://github.com/rust-lang/cargo/pull/11558/) +- [Cargo now suggests `cargo fix` or `cargo clippy --fix` when compilation warnings are auto-fixable.](https://github.com/rust-lang/cargo/pull/11558/) - [Cargo now suggests `cargo add` if you try to install a library crate.](https://github.com/rust-lang/cargo/pull/11410/) - [Cargo now sets `CARGO_BIN_NAME` environment variable also for binary examples.](https://github.com/rust-lang/cargo/pull/11705/) From 6b33156d3444db2baf043834f71f5c4d01daafaf Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 7 Apr 2023 08:22:54 -0700 Subject: [PATCH 006/116] `core::net` is not stable yet Co-authored-by: Slanterns --- RELEASES.md | 1 - 1 file changed, 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index e33a695212b7..920a0655d8c4 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -31,7 +31,6 @@ Libraries - [Implement the unstable `DispatchFromDyn` for cell types, allowing downstream experimentation with custom method receivers.](https://github.com/rust-lang/rust/pull/97373/) - [Document that `fmt::Arguments::as_str()` may return `Some(_)` in more cases after optimization, subject to change.](https://github.com/rust-lang/rust/pull/106823/) - [Implement `AsFd` and `AsRawFd` for `Rc`.](https://github.com/rust-lang/rust/pull/107317/) -- [Move `IpAddr`, `SocketAddr` and V4+V6 related types to `core`](https://github.com/rust-lang/rust/pull/104265/) From f6a47f304e7524f66c4c1c7b7ec19d2f521fea2b Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 7 Apr 2023 08:23:38 -0700 Subject: [PATCH 007/116] Rephrase the analysis removal Co-authored-by: Mark Rousskov --- RELEASES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index 920a0655d8c4..6d8233f2cfda 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -87,7 +87,7 @@ Misc Compatibility Notes ------------------- -- [Remove `-Zsave-analysis` from the compiler, which was primarily intended for RLS.](https://github.com/rust-lang/rust/pull/101841/) The `rust-analysis` component from `rustup` now only contains a warning placeholder. +- [The `rust-analysis` component from `rustup` now only contains a warning placeholder.](https://github.com/rust-lang/rust/pull/101841/) This was primarily intended for RLS, and the corresponding `-Zsave-analysis` flag has been removed from the compiler as well. - [Unaligned references to packed fields are now a hard error.](https://github.com/rust-lang/rust/pull/102513/) This has been a warning since 1.53, and denied by default with a future-compatibility warning since 1.62. - [Update the minimum external LLVM to 14.](https://github.com/rust-lang/rust/pull/107573/) - [Cargo now emits errors on invalid alphanumeric token for crates.io.](https://github.com/rust-lang/cargo/pull/11600/) From c21b1044256bdda63375e64137e1f4ebdde1fccf Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 7 Apr 2023 08:29:02 -0700 Subject: [PATCH 008/116] Remove empty "Misc" section --- RELEASES.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index 6d8233f2cfda..e712e222bf3e 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -77,11 +77,6 @@ Rustdoc - [Remove inconsistently-present sidebar tooltips.](https://github.com/rust-lang/rust/pull/107490/) - [Search by macro when query ends with `!`.](https://github.com/rust-lang/rust/pull/108143/) - - -Misc ----- - Compatibility Notes From 361b453e33744e45583a352a25ab3f03dfcc3429 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 7 Apr 2023 08:45:11 -0700 Subject: [PATCH 009/116] Avoid normalization/projection jargon Co-authored-by: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> --- RELEASES.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index e712e222bf3e..f56b9a360cb6 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -8,8 +8,8 @@ Language - [Deriving built-in traits on packed structs works with `Copy` fields.](https://github.com/rust-lang/rust/pull/104429/) - [Stabilize the `cmpxchg16b` target feature on x86 and x86_64.](https://github.com/rust-lang/rust/pull/106774/) -- [Add normalization to satisfy trait bounds involving type projections.](https://github.com/rust-lang/rust/pull/103695/) -- [Add normalization that allows type projections in union fields.](https://github.com/rust-lang/rust/pull/106938/) +- [Improve analysis of trait bounds for associated types.](https://github.com/rust-lang/rust/pull/103695/) +- [Allow associated types to be used as union fields.](https://github.com/rust-lang/rust/pull/106938/) - [Allow `Self: Autotrait` bounds on dyn-safe trait methods.](https://github.com/rust-lang/rust/pull/107082/) - [Treat `str` as containing `[u8]` for auto trait purposes.](https://github.com/rust-lang/rust/pull/107941/) From 02b3165310ed3cfdb9ac0c654a04eda7ee2052d8 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 7 Apr 2023 08:53:00 -0700 Subject: [PATCH 010/116] Apply code formatting --- RELEASES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index f56b9a360cb6..18b673949b0a 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -99,7 +99,7 @@ These changes do not affect any public interfaces of Rust, but they represent significant improvements to the performance or internals of rustc and related tools. -- [Move format_args!() into AST (and expand it during AST lowering)](https://github.com/rust-lang/rust/pull/106745/) +- [Move `format_args!()` into AST (and expand it during AST lowering)](https://github.com/rust-lang/rust/pull/106745/) Version 1.68.2 (2023-03-28) =========================== From e3126b1084fe93376458933d85c131dffd6086f2 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Thu, 16 Mar 2023 22:18:28 -0400 Subject: [PATCH 011/116] Permit MIR inlining without #[inline] --- compiler/rustc_mir_transform/src/inline.rs | 10 ++-------- tests/codegen/array-map.rs | 2 +- tests/codegen/inline-hint.rs | 2 +- tests/codegen/local-generics-in-exe-internalized.rs | 2 +- 4 files changed, 5 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index f0cb317f449f..1525933aee3f 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -350,14 +350,8 @@ impl<'tcx> Inliner<'tcx> { callsite: &CallSite<'tcx>, callee_attrs: &CodegenFnAttrs, ) -> Result<(), &'static str> { - match callee_attrs.inline { - InlineAttr::Never => return Err("never inline hint"), - InlineAttr::Always | InlineAttr::Hint => {} - InlineAttr::None => { - if self.tcx.sess.mir_opt_level() <= 2 { - return Err("at mir-opt-level=2, only #[inline] is inlined"); - } - } + if let InlineAttr::Never = callee_attrs.inline { + return Err("never inline hint"); } // Only inline local functions if they would be eligible for cross-crate diff --git a/tests/codegen/array-map.rs b/tests/codegen/array-map.rs index 7b8ab2c79a7f..3706ddf99fd9 100644 --- a/tests/codegen/array-map.rs +++ b/tests/codegen/array-map.rs @@ -21,7 +21,7 @@ pub fn short_integer_map(x: [u32; 8]) -> [u32; 8] { pub fn short_integer_zip_map(x: [u32; 8], y: [u32; 8]) -> [u32; 8] { // CHECK: %[[A:.+]] = load <8 x i32> // CHECK: %[[B:.+]] = load <8 x i32> - // CHECK: sub <8 x i32> %[[A]], %[[B]] + // CHECK: sub <8 x i32> %[[B]], %[[A]] // CHECK: store <8 x i32> x.zip(y).map(|(x, y)| x - y) } diff --git a/tests/codegen/inline-hint.rs b/tests/codegen/inline-hint.rs index d3ea1915a8b1..bb2a8e6a649d 100644 --- a/tests/codegen/inline-hint.rs +++ b/tests/codegen/inline-hint.rs @@ -1,7 +1,7 @@ // Checks that closures, constructors, and shims except // for a drop glue receive inline hint by default. // -// compile-flags: -Cno-prepopulate-passes -Csymbol-mangling-version=v0 +// compile-flags: -Cno-prepopulate-passes -Csymbol-mangling-version=v0 -Zinline-mir=no #![crate_type = "lib"] pub fn f() { diff --git a/tests/codegen/local-generics-in-exe-internalized.rs b/tests/codegen/local-generics-in-exe-internalized.rs index e5430fbf17a1..449c5ca75fcd 100644 --- a/tests/codegen/local-generics-in-exe-internalized.rs +++ b/tests/codegen/local-generics-in-exe-internalized.rs @@ -1,4 +1,4 @@ -// compile-flags: -C no-prepopulate-passes -Zshare-generics=yes +// compile-flags: -C no-prepopulate-passes -Zshare-generics=yes -Zinline-mir=no // Check that local generics are internalized if they are in the same CGU From e88e2af959559220412e21f66e9063aeed2f7a8b Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Fri, 24 Mar 2023 16:24:37 -0400 Subject: [PATCH 012/116] Give the cross-crate generic some work to do --- tests/codegen/remap_path_prefix/auxiliary/xcrate-generic.rs | 4 +++- tests/codegen/remap_path_prefix/xcrate-generic.rs | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/codegen/remap_path_prefix/auxiliary/xcrate-generic.rs b/tests/codegen/remap_path_prefix/auxiliary/xcrate-generic.rs index 59092dbf6376..15bd0f174218 100644 --- a/tests/codegen/remap_path_prefix/auxiliary/xcrate-generic.rs +++ b/tests/codegen/remap_path_prefix/auxiliary/xcrate-generic.rs @@ -3,4 +3,6 @@ #![crate_type = "lib"] -pub fn foo() {} +pub fn foo() -> T { + T::default() +} diff --git a/tests/codegen/remap_path_prefix/xcrate-generic.rs b/tests/codegen/remap_path_prefix/xcrate-generic.rs index 7a9d2ca9b6bb..399deec1fc93 100644 --- a/tests/codegen/remap_path_prefix/xcrate-generic.rs +++ b/tests/codegen/remap_path_prefix/xcrate-generic.rs @@ -7,7 +7,7 @@ extern crate xcrate_generic; pub fn foo() { - xcrate_generic::foo::(); + println!("{}", xcrate_generic::foo::()); } // Here we check that local debuginfo is mapped correctly. From 354177504757c3b79e38daa3f6c81004470f455f Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Fri, 24 Mar 2023 17:04:05 -0400 Subject: [PATCH 013/116] Turn off inlining for codegen-unit tests --- .../codegen-units/item-collection/cross-crate-trait-method.rs | 2 +- tests/codegen-units/item-collection/function-as-argument.rs | 3 +-- tests/codegen-units/item-collection/generic-functions.rs | 2 +- tests/codegen-units/item-collection/generic-impl.rs | 2 +- tests/codegen-units/item-collection/trait-implementations.rs | 2 +- .../codegen-units/item-collection/trait-method-as-argument.rs | 3 +-- .../codegen-units/item-collection/trait-method-default-impl.rs | 2 +- 7 files changed, 7 insertions(+), 9 deletions(-) diff --git a/tests/codegen-units/item-collection/cross-crate-trait-method.rs b/tests/codegen-units/item-collection/cross-crate-trait-method.rs index dc0984c8a981..b7216a143180 100644 --- a/tests/codegen-units/item-collection/cross-crate-trait-method.rs +++ b/tests/codegen-units/item-collection/cross-crate-trait-method.rs @@ -1,4 +1,4 @@ -// compile-flags:-Zprint-mono-items=eager +// compile-flags:-Zprint-mono-items=eager -Zinline-mir=no #![deny(dead_code)] #![feature(start)] diff --git a/tests/codegen-units/item-collection/function-as-argument.rs b/tests/codegen-units/item-collection/function-as-argument.rs index ea500c3111a2..d951cbfacec6 100644 --- a/tests/codegen-units/item-collection/function-as-argument.rs +++ b/tests/codegen-units/item-collection/function-as-argument.rs @@ -1,5 +1,4 @@ -// -// compile-flags:-Zprint-mono-items=eager +// compile-flags:-Zprint-mono-items=eager -Zinline-mir=no #![deny(dead_code)] #![feature(start)] diff --git a/tests/codegen-units/item-collection/generic-functions.rs b/tests/codegen-units/item-collection/generic-functions.rs index 04383bb8edb7..f790cd0dadd7 100644 --- a/tests/codegen-units/item-collection/generic-functions.rs +++ b/tests/codegen-units/item-collection/generic-functions.rs @@ -1,4 +1,4 @@ -// compile-flags:-Zprint-mono-items=eager +// compile-flags:-Zprint-mono-items=eager -Zinline-mir=no #![deny(dead_code)] #![feature(start)] diff --git a/tests/codegen-units/item-collection/generic-impl.rs b/tests/codegen-units/item-collection/generic-impl.rs index 4260230c2c67..e19eec36b31e 100644 --- a/tests/codegen-units/item-collection/generic-impl.rs +++ b/tests/codegen-units/item-collection/generic-impl.rs @@ -1,4 +1,4 @@ -// compile-flags:-Zprint-mono-items=eager +// compile-flags:-Zprint-mono-items=eager -Zinline-mir=no #![deny(dead_code)] #![feature(start)] diff --git a/tests/codegen-units/item-collection/trait-implementations.rs b/tests/codegen-units/item-collection/trait-implementations.rs index a816cb032413..ad0ed7da28e6 100644 --- a/tests/codegen-units/item-collection/trait-implementations.rs +++ b/tests/codegen-units/item-collection/trait-implementations.rs @@ -1,4 +1,4 @@ -// compile-flags:-Zprint-mono-items=eager +// compile-flags:-Zprint-mono-items=eager -Zinline-mir=no #![deny(dead_code)] #![feature(start)] diff --git a/tests/codegen-units/item-collection/trait-method-as-argument.rs b/tests/codegen-units/item-collection/trait-method-as-argument.rs index 235569728a2e..164ef794ca7e 100644 --- a/tests/codegen-units/item-collection/trait-method-as-argument.rs +++ b/tests/codegen-units/item-collection/trait-method-as-argument.rs @@ -1,5 +1,4 @@ -// -// compile-flags:-Zprint-mono-items=eager +// compile-flags:-Zprint-mono-items=eager -Zinline-mir=no #![deny(dead_code)] #![feature(start)] diff --git a/tests/codegen-units/item-collection/trait-method-default-impl.rs b/tests/codegen-units/item-collection/trait-method-default-impl.rs index bfcdb6fa142b..d953582cce9b 100644 --- a/tests/codegen-units/item-collection/trait-method-default-impl.rs +++ b/tests/codegen-units/item-collection/trait-method-default-impl.rs @@ -1,4 +1,4 @@ -// compile-flags:-Zprint-mono-items=eager -Zpolymorphize=on +// compile-flags:-Zprint-mono-items=eager -Zpolymorphize=on -Zinline-mir=no #![deny(dead_code)] #![feature(start)] From 954d9a8f8eb2777671395d83c67025488a3b49fa Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 27 Mar 2023 14:39:32 +0000 Subject: [PATCH 014/116] Remove `remap_env_constness` in queries --- compiler/rustc_macros/src/query.rs | 8 ------ compiler/rustc_middle/src/infer/canonical.rs | 8 ------ compiler/rustc_middle/src/query/mod.rs | 25 ------------------- compiler/rustc_middle/src/ty/mod.rs | 6 ----- compiler/rustc_middle/src/ty/query.rs | 14 ----------- .../traits/query/type_op/prove_predicate.rs | 8 +----- tests/ui/const-generics/issues/issue-88119.rs | 8 +++++- .../const-generics/issues/issue-88119.stderr | 17 +++++++++++++ 8 files changed, 25 insertions(+), 69 deletions(-) create mode 100644 tests/ui/const-generics/issues/issue-88119.stderr diff --git a/compiler/rustc_macros/src/query.rs b/compiler/rustc_macros/src/query.rs index f85ba38003c1..a8b25ff66d78 100644 --- a/compiler/rustc_macros/src/query.rs +++ b/compiler/rustc_macros/src/query.rs @@ -112,9 +112,6 @@ struct QueryModifiers { /// Use a separate query provider for local and extern crates separate_provide_extern: Option, - /// Always remap the ParamEnv's constness before hashing. - remap_env_constness: Option, - /// Generate a `feed` method to set the query's value from another query. feedable: Option, } @@ -130,7 +127,6 @@ fn parse_query_modifiers(input: ParseStream<'_>) -> Result { let mut eval_always = None; let mut depth_limit = None; let mut separate_provide_extern = None; - let mut remap_env_constness = None; let mut feedable = None; while !input.is_empty() { @@ -189,8 +185,6 @@ fn parse_query_modifiers(input: ParseStream<'_>) -> Result { try_insert!(depth_limit = modifier); } else if modifier == "separate_provide_extern" { try_insert!(separate_provide_extern = modifier); - } else if modifier == "remap_env_constness" { - try_insert!(remap_env_constness = modifier); } else if modifier == "feedable" { try_insert!(feedable = modifier); } else { @@ -211,7 +205,6 @@ fn parse_query_modifiers(input: ParseStream<'_>) -> Result { eval_always, depth_limit, separate_provide_extern, - remap_env_constness, feedable, }) } @@ -332,7 +325,6 @@ pub fn rustc_queries(input: TokenStream) -> TokenStream { eval_always, depth_limit, separate_provide_extern, - remap_env_constness, ); if modifiers.cache.is_some() { diff --git a/compiler/rustc_middle/src/infer/canonical.rs b/compiler/rustc_middle/src/infer/canonical.rs index f668c4e77bea..1b3b15fe641f 100644 --- a/compiler/rustc_middle/src/infer/canonical.rs +++ b/compiler/rustc_middle/src/infer/canonical.rs @@ -336,14 +336,6 @@ impl<'tcx, R> Canonical<'tcx, QueryResponse<'tcx, R>> { } } -impl<'tcx, R> Canonical<'tcx, ty::ParamEnvAnd<'tcx, R>> { - #[inline] - pub fn without_const(mut self) -> Self { - self.value = self.value.without_const(); - self - } -} - impl<'tcx, V> Canonical<'tcx, V> { /// Allows you to map the `value` of a canonical while keeping the /// same set of bound variables. diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 964168967564..f411f7a8f417 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -1088,7 +1088,6 @@ rustc_queries! { key: ty::ParamEnvAnd<'tcx, mir::ConstantKind<'tcx>> ) -> Option> { desc { "destructuring MIR constant"} - remap_env_constness } /// Dereference a constant reference or raw pointer and turn the result into a constant @@ -1097,7 +1096,6 @@ rustc_queries! { key: ty::ParamEnvAnd<'tcx, mir::ConstantKind<'tcx>> ) -> mir::ConstantKind<'tcx> { desc { "dereferencing MIR constant" } - remap_env_constness } query const_caller_location(key: (rustc_span::Symbol, u32, u32)) -> ConstValue<'tcx> { @@ -1340,32 +1338,26 @@ rustc_queries! { /// `ty.is_copy()`, etc, since that will prune the environment where possible. query is_copy_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` is `Copy`", env.value } - remap_env_constness } /// Query backing `Ty::is_sized`. query is_sized_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` is `Sized`", env.value } - remap_env_constness } /// Query backing `Ty::is_freeze`. query is_freeze_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` is freeze", env.value } - remap_env_constness } /// Query backing `Ty::is_unpin`. query is_unpin_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` is `Unpin`", env.value } - remap_env_constness } /// Query backing `Ty::needs_drop`. query needs_drop_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` needs drop", env.value } - remap_env_constness } /// Query backing `Ty::has_significant_drop_raw`. query has_significant_drop_raw(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> bool { desc { "computing whether `{}` has a significant drop", env.value } - remap_env_constness } /// Query backing `Ty::is_structural_eq_shallow`. @@ -1405,7 +1397,6 @@ rustc_queries! { ) -> Result, ty::layout::LayoutError<'tcx>> { depth_limit desc { "computing layout of `{}`", key.value } - remap_env_constness } /// Compute a `FnAbi` suitable for indirect calls, i.e. to `fn` pointers. @@ -1416,7 +1407,6 @@ rustc_queries! { key: ty::ParamEnvAnd<'tcx, (ty::PolyFnSig<'tcx>, &'tcx ty::List>)> ) -> Result<&'tcx abi::call::FnAbi<'tcx, Ty<'tcx>>, ty::layout::FnAbiError<'tcx>> { desc { "computing call ABI of `{}` function pointers", key.value.0 } - remap_env_constness } /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for @@ -1428,7 +1418,6 @@ rustc_queries! { key: ty::ParamEnvAnd<'tcx, (ty::Instance<'tcx>, &'tcx ty::List>)> ) -> Result<&'tcx abi::call::FnAbi<'tcx, Ty<'tcx>>, ty::layout::FnAbiError<'tcx>> { desc { "computing call ABI of `{}`", key.value.0 } - remap_env_constness } query dylib_dependency_formats(_: CrateNum) @@ -1935,7 +1924,6 @@ rustc_queries! { NoSolution, > { desc { "normalizing `{}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: invoke `try_normalize_erasing_regions` instead. @@ -1943,7 +1931,6 @@ rustc_queries! { goal: ParamEnvAnd<'tcx, GenericArg<'tcx>> ) -> Result, NoSolution> { desc { "normalizing `{}`", goal.value } - remap_env_constness } query implied_outlives_bounds( @@ -1953,7 +1940,6 @@ rustc_queries! { NoSolution, > { desc { "computing implied outlives bounds for `{}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: @@ -1965,7 +1951,6 @@ rustc_queries! { NoSolution, > { desc { "computing dropck types for `{}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: invoke `infcx.predicate_may_hold()` or @@ -1993,7 +1978,6 @@ rustc_queries! { NoSolution, > { desc { "evaluating `type_op_ascribe_user_type` `{:?}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: part of the `Eq` type-op @@ -2004,7 +1988,6 @@ rustc_queries! { NoSolution, > { desc { "evaluating `type_op_eq` `{:?}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: part of the `Subtype` type-op @@ -2015,7 +1998,6 @@ rustc_queries! { NoSolution, > { desc { "evaluating `type_op_subtype` `{:?}`", goal.value.value } - remap_env_constness } /// Do not call this query directly: part of the `ProvePredicate` type-op @@ -2036,7 +2018,6 @@ rustc_queries! { NoSolution, > { desc { "normalizing `{}`", goal.value.value.value } - remap_env_constness } /// Do not call this query directly: part of the `Normalize` type-op @@ -2047,7 +2028,6 @@ rustc_queries! { NoSolution, > { desc { "normalizing `{:?}`", goal.value.value.value } - remap_env_constness } /// Do not call this query directly: part of the `Normalize` type-op @@ -2058,7 +2038,6 @@ rustc_queries! { NoSolution, > { desc { "normalizing `{:?}`", goal.value.value.value } - remap_env_constness } /// Do not call this query directly: part of the `Normalize` type-op @@ -2069,7 +2048,6 @@ rustc_queries! { NoSolution, > { desc { "normalizing `{:?}`", goal.value.value.value } - remap_env_constness } query subst_and_check_impossible_predicates(key: (DefId, SubstsRef<'tcx>)) -> bool { @@ -2091,7 +2069,6 @@ rustc_queries! { goal: CanonicalTyGoal<'tcx> ) -> MethodAutoderefStepsResult<'tcx> { desc { "computing autoderef types for `{}`", goal.value.value } - remap_env_constness } query supported_target_features(_: CrateNum) -> &'tcx FxHashMap> { @@ -2136,7 +2113,6 @@ rustc_queries! { key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)> ) -> Result>, ErrorGuaranteed> { desc { "resolving instance `{}`", ty::Instance::new(key.value.0, key.value.1) } - remap_env_constness } query resolve_instance_of_const_arg( @@ -2146,7 +2122,6 @@ rustc_queries! { "resolving instance of the const argument `{}`", ty::Instance::new(key.value.0.to_def_id(), key.value.2), } - remap_env_constness } query reveal_opaque_types_in_bounds(key: &'tcx ty::List>) -> &'tcx ty::List> { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index c856bb25e147..5d07153fa8c7 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1849,12 +1849,6 @@ impl<'tcx, T> ParamEnvAnd<'tcx, T> { pub fn into_parts(self) -> (ParamEnv<'tcx>, T) { (self.param_env, self.value) } - - #[inline] - pub fn without_const(mut self) -> Self { - self.param_env = self.param_env.without_const(); - self - } } #[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)] diff --git a/compiler/rustc_middle/src/ty/query.rs b/compiler/rustc_middle/src/ty/query.rs index fa9fea723448..97592cbc567d 100644 --- a/compiler/rustc_middle/src/ty/query.rs +++ b/compiler/rustc_middle/src/ty/query.rs @@ -202,16 +202,6 @@ macro_rules! separate_provide_extern_default { }; } -macro_rules! opt_remap_env_constness { - ([][$name:ident]) => {}; - ([(remap_env_constness) $($rest:tt)*][$name:ident]) => { - let $name = $name.without_const(); - }; - ([$other:tt $($modifiers:tt)*][$name:ident]) => { - opt_remap_env_constness!([$($modifiers)*][$name]) - }; -} - macro_rules! define_callbacks { ( $($(#[$attr:meta])* @@ -353,7 +343,6 @@ macro_rules! define_callbacks { #[inline(always)] pub fn $name(self, key: query_helper_param_ty!($($K)*)) { let key = key.into_query_param(); - opt_remap_env_constness!([$($modifiers)*][key]); match try_get_cached(self.tcx, &self.tcx.query_system.caches.$name, &key) { Some(_) => return, @@ -372,7 +361,6 @@ macro_rules! define_callbacks { #[inline(always)] pub fn $name(self, key: query_helper_param_ty!($($K)*)) { let key = key.into_query_param(); - opt_remap_env_constness!([$($modifiers)*][key]); match try_get_cached(self.tcx, &self.tcx.query_system.caches.$name, &key) { Some(_) => return, @@ -402,7 +390,6 @@ macro_rules! define_callbacks { pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> $V { let key = key.into_query_param(); - opt_remap_env_constness!([$($modifiers)*][key]); restore::<$V>(match try_get_cached(self.tcx, &self.tcx.query_system.caches.$name, &key) { Some(value) => value, @@ -492,7 +479,6 @@ macro_rules! define_feedable { #[inline(always)] pub fn $name(self, value: query_provided::$name<'tcx>) -> $V { let key = self.key().into_query_param(); - opt_remap_env_constness!([$($modifiers)*][key]); let tcx = self.tcx; let erased = query_provided_to_value::$name(tcx, value); 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 b63da28e2747..baa2fbb6751c 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 @@ -32,14 +32,8 @@ impl<'tcx> super::QueryTypeOp<'tcx> for ProvePredicate<'tcx> { fn perform_query( tcx: TyCtxt<'tcx>, - mut canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, + canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Self>>, ) -> Fallible> { - match canonicalized.value.value.predicate.kind().skip_binder() { - ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => { - canonicalized.value.param_env.remap_constness_with(pred.constness); - } - _ => canonicalized.value.param_env = canonicalized.value.param_env.without_const(), - } tcx.type_op_prove_predicate(canonicalized) } } diff --git a/tests/ui/const-generics/issues/issue-88119.rs b/tests/ui/const-generics/issues/issue-88119.rs index 647b0eea86da..ddc6599a53ee 100644 --- a/tests/ui/const-generics/issues/issue-88119.rs +++ b/tests/ui/const-generics/issues/issue-88119.rs @@ -1,4 +1,10 @@ -// check-pass +// known-bug: #88119 +// failure-status: 101 +// normalize-stderr-test "note: .*\n" -> "" +// normalize-stderr-test "thread 'rustc' panicked.*\n" -> "" +// normalize-stderr-test "\s\d{1,}: .*\n" -> "" +// normalize-stderr-test "\s at .*\n" -> "" +// rustc-env:RUST_BACKTRACE=0 #![allow(incomplete_features)] #![feature(const_trait_impl, generic_const_exprs)] diff --git a/tests/ui/const-generics/issues/issue-88119.stderr b/tests/ui/const-generics/issues/issue-88119.stderr new file mode 100644 index 000000000000..b4e18c86b1fd --- /dev/null +++ b/tests/ui/const-generics/issues/issue-88119.stderr @@ -0,0 +1,17 @@ +error: internal compiler error: no errors encountered even though `delay_span_bug` issued + +error: internal compiler error: broken MIR in DefId(0:7 ~ issue_88119[4c3c]::name_len) ($DIR/issue-88119.rs:22:5: 22:18 (#0)): ascribe_user_type `&[u8]==TypeOf(DefId(0:4 ~ issue_88119[4c3c]::ConstName::NAME_BYTES), UserSubsts { substs: [T], user_self_ty: None })` failed with `NoSolution` + | + = + +error: internal compiler error: broken MIR in DefId(0:7 ~ issue_88119[4c3c]::name_len) ($DIR/issue-88119.rs:22:5: 22:18 (#0)): ascribe_user_type `&[u8]==TypeOf(DefId(0:4 ~ issue_88119[4c3c]::ConstName::NAME_BYTES), UserSubsts { substs: [T], user_self_ty: None })` failed with `NoSolution` + | + = + + + + +query stack during panic: +end of query stack +error: aborting due to 3 previous errors + From 886c0e638806a2541b08ffb1efb88366376aac4b Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sat, 8 Apr 2023 09:27:48 +0000 Subject: [PATCH 015/116] fix ICE --- compiler/rustc_traits/src/type_op.rs | 1 + tests/ui/const-generics/issues/issue-88119.rs | 8 +------ .../const-generics/issues/issue-88119.stderr | 17 -------------- .../trait-method-ptr-in-consts-ice.rs | 23 +++++++++++++++++++ 4 files changed, 25 insertions(+), 24 deletions(-) delete mode 100644 tests/ui/const-generics/issues/issue-88119.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/trait-method-ptr-in-consts-ice.rs diff --git a/compiler/rustc_traits/src/type_op.rs b/compiler/rustc_traits/src/type_op.rs index e0fd487b3d37..19622112f2a2 100644 --- a/compiler/rustc_traits/src/type_op.rs +++ b/compiler/rustc_traits/src/type_op.rs @@ -89,6 +89,7 @@ fn relate_mir_and_user_substs<'tcx>( def_id: hir::def_id::DefId, user_substs: UserSubsts<'tcx>, ) -> Result<(), NoSolution> { + let param_env = param_env.without_const(); let UserSubsts { user_self_ty, substs } = user_substs; let tcx = ocx.infcx.tcx; let cause = ObligationCause::dummy_with_span(span); diff --git a/tests/ui/const-generics/issues/issue-88119.rs b/tests/ui/const-generics/issues/issue-88119.rs index ddc6599a53ee..647b0eea86da 100644 --- a/tests/ui/const-generics/issues/issue-88119.rs +++ b/tests/ui/const-generics/issues/issue-88119.rs @@ -1,10 +1,4 @@ -// known-bug: #88119 -// failure-status: 101 -// normalize-stderr-test "note: .*\n" -> "" -// normalize-stderr-test "thread 'rustc' panicked.*\n" -> "" -// normalize-stderr-test "\s\d{1,}: .*\n" -> "" -// normalize-stderr-test "\s at .*\n" -> "" -// rustc-env:RUST_BACKTRACE=0 +// check-pass #![allow(incomplete_features)] #![feature(const_trait_impl, generic_const_exprs)] diff --git a/tests/ui/const-generics/issues/issue-88119.stderr b/tests/ui/const-generics/issues/issue-88119.stderr deleted file mode 100644 index b4e18c86b1fd..000000000000 --- a/tests/ui/const-generics/issues/issue-88119.stderr +++ /dev/null @@ -1,17 +0,0 @@ -error: internal compiler error: no errors encountered even though `delay_span_bug` issued - -error: internal compiler error: broken MIR in DefId(0:7 ~ issue_88119[4c3c]::name_len) ($DIR/issue-88119.rs:22:5: 22:18 (#0)): ascribe_user_type `&[u8]==TypeOf(DefId(0:4 ~ issue_88119[4c3c]::ConstName::NAME_BYTES), UserSubsts { substs: [T], user_self_ty: None })` failed with `NoSolution` - | - = - -error: internal compiler error: broken MIR in DefId(0:7 ~ issue_88119[4c3c]::name_len) ($DIR/issue-88119.rs:22:5: 22:18 (#0)): ascribe_user_type `&[u8]==TypeOf(DefId(0:4 ~ issue_88119[4c3c]::ConstName::NAME_BYTES), UserSubsts { substs: [T], user_self_ty: None })` failed with `NoSolution` - | - = - - - - -query stack during panic: -end of query stack -error: aborting due to 3 previous errors - diff --git a/tests/ui/rfc-2632-const-trait-impl/trait-method-ptr-in-consts-ice.rs b/tests/ui/rfc-2632-const-trait-impl/trait-method-ptr-in-consts-ice.rs new file mode 100644 index 000000000000..7d7cb967c661 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/trait-method-ptr-in-consts-ice.rs @@ -0,0 +1,23 @@ +// check-pass + +struct LazyLock { + data: (Option, fn() -> T), +} + +impl LazyLock { + pub const fn new(f: fn() -> T) -> LazyLock { + LazyLock { data: (None, f) } + } +} + +struct A(Option); + +impl Default for A { + fn default() -> Self { + A(None) + } +} + +static EMPTY_SET: LazyLock> = LazyLock::new(A::default); + +fn main() {} From 1e95cddc74f88c1bb86f80103d0d7128f779f544 Mon Sep 17 00:00:00 2001 From: Ezra Shaw Date: Wed, 1 Mar 2023 22:17:08 +1300 Subject: [PATCH 016/116] feat: implement basic suggest-tests tool --- Cargo.lock | 13 ++- Cargo.toml | 1 + src/bootstrap/builder.rs | 22 ++++- src/bootstrap/config.rs | 24 ++--- src/bootstrap/flags.rs | 14 ++- src/bootstrap/lib.rs | 19 +++- src/bootstrap/suggest.rs | 72 ++++++++++++++ src/bootstrap/test.rs | 36 +++++++ src/bootstrap/tool.rs | 1 + src/tools/suggest-tests/Cargo.toml | 9 ++ .../suggest-tests/src/dynamic_suggestions.rs | 23 +++++ src/tools/suggest-tests/src/lib.rs | 96 +++++++++++++++++++ src/tools/suggest-tests/src/main.rs | 27 ++++++ .../suggest-tests/src/static_suggestions.rs | 24 +++++ src/tools/suggest-tests/src/tests.rs | 21 ++++ 15 files changed, 377 insertions(+), 25 deletions(-) create mode 100644 src/bootstrap/suggest.rs create mode 100644 src/tools/suggest-tests/Cargo.toml create mode 100644 src/tools/suggest-tests/src/dynamic_suggestions.rs create mode 100644 src/tools/suggest-tests/src/lib.rs create mode 100644 src/tools/suggest-tests/src/main.rs create mode 100644 src/tools/suggest-tests/src/static_suggestions.rs create mode 100644 src/tools/suggest-tests/src/tests.rs diff --git a/Cargo.lock b/Cargo.lock index d4fca32d750f..4167fd7de9ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3459,9 +3459,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.16.0" +version = "1.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" +checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" [[package]] name = "opener" @@ -6097,6 +6097,15 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" +[[package]] +name = "suggest-tests" +version = "0.1.0" +dependencies = [ + "build_helper", + "glob", + "once_cell", +] + [[package]] name = "syn" version = "1.0.102" diff --git a/Cargo.toml b/Cargo.toml index 15cbb2659c9b..1fcaaf6ddc4d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,6 +44,7 @@ members = [ "src/tools/lld-wrapper", "src/tools/collect-license-metadata", "src/tools/generate-copyright", + "src/tools/suggest-tests", ] exclude = [ diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index ade8fa4c74dc..e959ea06f8b6 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -591,6 +591,7 @@ pub enum Kind { Install, Run, Setup, + Suggest, } impl Kind { @@ -610,6 +611,7 @@ impl Kind { "install" => Kind::Install, "run" | "r" => Kind::Run, "setup" => Kind::Setup, + "suggest" => Kind::Suggest, _ => return None, }) } @@ -629,6 +631,7 @@ impl Kind { Kind::Install => "install", Kind::Run => "run", Kind::Setup => "setup", + Kind::Suggest => "suggest", } } } @@ -709,6 +712,7 @@ impl<'a> Builder<'a> { test::CrateRustdoc, test::CrateRustdocJsonTypes, test::CrateJsonDocLint, + test::SuggestTestsCrate, test::Linkcheck, test::TierCheck, test::ReplacePlaceholderTest, @@ -827,7 +831,7 @@ impl<'a> Builder<'a> { Kind::Setup => describe!(setup::Profile, setup::Hook, setup::Link, setup::Vscode), Kind::Clean => describe!(clean::CleanAll, clean::Rustc, clean::Std), // special-cased in Build::build() - Kind::Format => vec![], + Kind::Format | Kind::Suggest => vec![], } } @@ -891,6 +895,7 @@ impl<'a> Builder<'a> { Subcommand::Run { ref paths, .. } => (Kind::Run, &paths[..]), Subcommand::Clean { ref paths, .. } => (Kind::Clean, &paths[..]), Subcommand::Format { .. } => (Kind::Format, &[][..]), + Subcommand::Suggest { .. } => (Kind::Suggest, &[][..]), Subcommand::Setup { profile: ref path } => ( Kind::Setup, path.as_ref().map_or([].as_slice(), |path| std::slice::from_ref(path)), @@ -900,6 +905,21 @@ impl<'a> Builder<'a> { Self::new_internal(build, kind, paths.to_owned()) } + /// Creates a new standalone builder for use outside of the normal process + pub fn new_standalone( + build: &mut Build, + kind: Kind, + paths: Vec, + stage: Option, + ) -> Builder<'_> { + // FIXME: don't mutate `build` + if let Some(stage) = stage { + build.config.stage = stage; + } + + Self::new_internal(build, kind, paths.to_owned()) + } + pub fn execute_cli(&self) { self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths); } diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index dd65dc91c0cd..cc3b3bc25f3d 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -56,8 +56,7 @@ pub enum DryRun { /// filled out from the decoded forms of the structs below. For documentation /// each field, see the corresponding fields in /// `config.example.toml`. -#[derive(Default)] -#[cfg_attr(test, derive(Clone))] +#[derive(Default, Clone)] pub struct Config { pub changelog_seen: Option, pub ccache: Option, @@ -240,23 +239,20 @@ pub struct Config { pub initial_rustfmt: RefCell, } -#[derive(Default, Deserialize)] -#[cfg_attr(test, derive(Clone))] +#[derive(Default, Deserialize, Clone)] pub struct Stage0Metadata { pub compiler: CompilerMetadata, pub config: Stage0Config, pub checksums_sha256: HashMap, pub rustfmt: Option, } -#[derive(Default, Deserialize)] -#[cfg_attr(test, derive(Clone))] +#[derive(Default, Deserialize, Clone)] pub struct CompilerMetadata { pub date: String, pub version: String, } -#[derive(Default, Deserialize)] -#[cfg_attr(test, derive(Clone))] +#[derive(Default, Deserialize, Clone)] pub struct Stage0Config { pub dist_server: String, pub artifacts_server: String, @@ -264,8 +260,7 @@ pub struct Stage0Config { pub git_merge_commit_email: String, pub nightly_branch: String, } -#[derive(Default, Deserialize)] -#[cfg_attr(test, derive(Clone))] +#[derive(Default, Deserialize, Clone)] pub struct RustfmtMetadata { pub date: String, pub version: String, @@ -443,8 +438,7 @@ impl PartialEq<&str> for TargetSelection { } /// Per-target configuration stored in the global configuration structure. -#[derive(Default)] -#[cfg_attr(test, derive(Clone))] +#[derive(Default, Clone)] pub struct Target { /// Some(path to llvm-config) if using an external LLVM. pub llvm_config: Option, @@ -1396,7 +1390,8 @@ impl Config { | Subcommand::Fix { .. } | Subcommand::Run { .. } | Subcommand::Setup { .. } - | Subcommand::Format { .. } => flags.stage.unwrap_or(0), + | Subcommand::Format { .. } + | Subcommand::Suggest { .. } => flags.stage.unwrap_or(0), }; // CI should always run stage 2 builds, unless it specifically states otherwise @@ -1421,7 +1416,8 @@ impl Config { | Subcommand::Fix { .. } | Subcommand::Run { .. } | Subcommand::Setup { .. } - | Subcommand::Format { .. } => {} + | Subcommand::Format { .. } + | Subcommand::Suggest { .. } => {} } } diff --git a/src/bootstrap/flags.rs b/src/bootstrap/flags.rs index 2b0b772a6181..b6f5f3103983 100644 --- a/src/bootstrap/flags.rs +++ b/src/bootstrap/flags.rs @@ -84,8 +84,7 @@ pub struct Flags { pub free_args: Option>, } -#[derive(Debug)] -#[cfg_attr(test, derive(Clone))] +#[derive(Debug, Clone)] pub enum Subcommand { Build { paths: Vec, @@ -149,6 +148,9 @@ pub enum Subcommand { Setup { profile: Option, }, + Suggest { + run: bool, + }, } impl Default for Subcommand { @@ -183,6 +185,7 @@ Subcommands: install Install distribution artifacts run, r Run tools contained in this repository setup Create a config.toml (making it easier to use `x.py` itself) + suggest Suggest a subset of tests to run, based on modified files To learn more about a subcommand, run `./x.py -h`", ); @@ -349,6 +352,9 @@ To learn more about a subcommand, run `./x.py -h`", Kind::Run => { opts.optmulti("", "args", "arguments for the tool", "ARGS"); } + Kind::Suggest => { + opts.optflag("", "run", "run suggested tests"); + } _ => {} }; @@ -565,7 +571,7 @@ Arguments: Profile::all_for_help(" ").trim_end() )); } - Kind::Bench | Kind::Clean | Kind::Dist | Kind::Install => {} + Kind::Bench | Kind::Clean | Kind::Dist | Kind::Install | Kind::Suggest => {} }; // Get any optional paths which occur after the subcommand let mut paths = matches.free[1..].iter().map(|p| p.into()).collect::>(); @@ -626,6 +632,7 @@ Arguments: Kind::Format => Subcommand::Format { check: matches.opt_present("check"), paths }, Kind::Dist => Subcommand::Dist { paths }, Kind::Install => Subcommand::Install { paths }, + Kind::Suggest => Subcommand::Suggest { run: matches.opt_present("run") }, Kind::Run => { if paths.is_empty() { println!("\nrun requires at least a path!\n"); @@ -734,6 +741,7 @@ impl Subcommand { Subcommand::Install { .. } => Kind::Install, Subcommand::Run { .. } => Kind::Run, Subcommand::Setup { .. } => Kind::Setup, + Subcommand::Suggest { .. } => Kind::Suggest, } } diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index 5ee18cf64110..2ce9ddd2a680 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -58,6 +58,7 @@ mod render_tests; mod run; mod sanity; mod setup; +mod suggest; mod tarball; mod test; mod tool; @@ -189,6 +190,7 @@ pub enum GitRepo { /// although most functions are implemented as free functions rather than /// methods specifically on this structure itself (to make it easier to /// organize). +#[derive(Clone)] pub struct Build { /// User-specified configuration from `config.toml`. config: Config, @@ -242,7 +244,7 @@ pub struct Build { metrics: metrics::BuildMetrics, } -#[derive(Debug)] +#[derive(Debug, Clone)] struct Crate { name: Interned, deps: HashSet>, @@ -656,13 +658,20 @@ impl Build { job::setup(self); } - if let Subcommand::Format { check, paths } = &self.config.cmd { - return format::format(&builder::Builder::new(&self), *check, &paths); - } - // Download rustfmt early so that it can be used in rust-analyzer configs. let _ = &builder::Builder::new(&self).initial_rustfmt(); + // hardcoded subcommands + match &self.config.cmd { + Subcommand::Format { check, paths } => { + return format::format(&builder::Builder::new(&self), *check, &paths); + } + Subcommand::Suggest { run } => { + return suggest::suggest(&builder::Builder::new(&self), *run); + } + _ => (), + } + { let builder = builder::Builder::new(&self); if let Some(path) = builder.paths.get(0) { diff --git a/src/bootstrap/suggest.rs b/src/bootstrap/suggest.rs new file mode 100644 index 000000000000..1a482e416594 --- /dev/null +++ b/src/bootstrap/suggest.rs @@ -0,0 +1,72 @@ +use std::str::FromStr; + +use std::path::PathBuf; + +use crate::{ + builder::{Builder, Kind}, + tool::Tool, +}; + +/// Suggests a list of possible `x.py` commands to run based on modified files in branch. +pub fn suggest(builder: &Builder<'_>, run: bool) { + let suggestions = + builder.tool_cmd(Tool::SuggestTests).output().expect("failed to run `suggest-tests` tool"); + + if !suggestions.status.success() { + println!("failed to run `suggest-tests` tool ({})", suggestions.status); + println!( + "`suggest_tests` stdout:\n{}`suggest_tests` stderr:\n{}", + String::from_utf8(suggestions.stdout).unwrap(), + String::from_utf8(suggestions.stderr).unwrap() + ); + panic!("failed to run `suggest-tests`"); + } + + let suggestions = String::from_utf8(suggestions.stdout).unwrap(); + let suggestions = suggestions + .lines() + .map(|line| { + let mut sections = line.split_ascii_whitespace(); + + // this code expects one suggestion per line in the following format: + // {some number of flags} [optional stage number] + let cmd = sections.next().unwrap(); + let stage = sections.next_back().map(|s| str::parse(s).ok()).flatten(); + let paths: Vec = sections.map(|p| PathBuf::from_str(p).unwrap()).collect(); + + (cmd, stage, paths) + }) + .collect::>(); + + if !suggestions.is_empty() { + println!("==== SUGGESTIONS ===="); + for sug in &suggestions { + print!("x {} ", sug.0); + if let Some(stage) = sug.1 { + print!("--stage {stage} "); + } + + for path in &sug.2 { + print!("{} ", path.display()); + } + println!(); + } + println!("====================="); + } else { + println!("No suggestions found!"); + return; + } + + if run { + for sug in suggestions { + let mut build = builder.build.clone(); + + let builder = + Builder::new_standalone(&mut build, Kind::parse(&sug.0).unwrap(), sug.2, sug.1); + + builder.execute_cli() + } + } else { + println!("help: consider using the `--run` flag to automatically run suggested tests"); + } +} diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index 058ff429e80f..1d55992446eb 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -128,6 +128,42 @@ impl Step for CrateJsonDocLint { } } +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub struct SuggestTestsCrate { + host: TargetSelection, +} + +impl Step for SuggestTestsCrate { + type Output = (); + const ONLY_HOSTS: bool = true; + const DEFAULT: bool = true; + + fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { + run.path("src/tools/suggest-tests") + } + + fn make_run(run: RunConfig<'_>) { + run.builder.ensure(SuggestTestsCrate { host: run.target }); + } + + fn run(self, builder: &Builder<'_>) { + let bootstrap_host = builder.config.build; + let compiler = builder.compiler(0, bootstrap_host); + + let suggest_tests = tool::prepare_tool_cargo( + builder, + compiler, + Mode::ToolBootstrap, + bootstrap_host, + "test", + "src/tools/suggest-tests", + SourceType::InTree, + &[], + ); + add_flags_and_try_run_tests(builder, &mut suggest_tests.into()); + } +} + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct Linkcheck { host: TargetSelection, diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index 6a687a7903e0..d1fd2e8c42cb 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -433,6 +433,7 @@ bootstrap_tool!( ReplaceVersionPlaceholder, "src/tools/replace-version-placeholder", "replace-version-placeholder"; CollectLicenseMetadata, "src/tools/collect-license-metadata", "collect-license-metadata"; GenerateCopyright, "src/tools/generate-copyright", "generate-copyright"; + SuggestTests, "src/tools/suggest-tests", "suggest-tests"; ); #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)] diff --git a/src/tools/suggest-tests/Cargo.toml b/src/tools/suggest-tests/Cargo.toml new file mode 100644 index 000000000000..f4f4d548bb79 --- /dev/null +++ b/src/tools/suggest-tests/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "suggest-tests" +version = "0.1.0" +edition = "2021" + +[dependencies] +glob = "0.3.0" +build_helper = { version = "0.1.0", path = "../build_helper" } +once_cell = "1.17.1" diff --git a/src/tools/suggest-tests/src/dynamic_suggestions.rs b/src/tools/suggest-tests/src/dynamic_suggestions.rs new file mode 100644 index 000000000000..2b0213cdc223 --- /dev/null +++ b/src/tools/suggest-tests/src/dynamic_suggestions.rs @@ -0,0 +1,23 @@ +use std::path::Path; + +use crate::Suggestion; + +type DynamicSuggestion = fn(&Path) -> Vec; + +pub(crate) const DYNAMIC_SUGGESTIONS: &[DynamicSuggestion] = &[|path: &Path| -> Vec { + if path.starts_with("compiler/") || path.starts_with("library/") { + let path = path.components().take(2).collect::>(); + + vec![Suggestion::with_single_path( + "test", + None, + &format!( + "{}/{}", + path[0].as_os_str().to_str().unwrap(), + path[1].as_os_str().to_str().unwrap() + ), + )] + } else { + Vec::new() + } +}]; diff --git a/src/tools/suggest-tests/src/lib.rs b/src/tools/suggest-tests/src/lib.rs new file mode 100644 index 000000000000..44cd3c7f6a84 --- /dev/null +++ b/src/tools/suggest-tests/src/lib.rs @@ -0,0 +1,96 @@ +use std::{ + fmt::{self, Display}, + path::Path, +}; + +use dynamic_suggestions::DYNAMIC_SUGGESTIONS; +use glob::Pattern; +use static_suggestions::STATIC_SUGGESTIONS; + +mod dynamic_suggestions; +mod static_suggestions; + +#[cfg(test)] +mod tests; + +macro_rules! sug { + ($cmd:expr) => { + Suggestion::new($cmd, None, &[]) + }; + + ($cmd:expr, $paths:expr) => { + Suggestion::new($cmd, None, $paths.as_slice()) + }; + + ($cmd:expr, $stage:expr, $paths:expr) => { + Suggestion::new($cmd, Some($stage), $paths.as_slice()) + }; +} + +pub(crate) use sug; + +pub fn get_suggestions>(modified_files: &[T]) -> Vec { + let mut suggestions = Vec::new(); + + // static suggestions + for sug in STATIC_SUGGESTIONS.iter() { + let glob = Pattern::new(&sug.0).expect("Found invalid glob pattern!"); + + for file in modified_files { + if glob.matches(file.as_ref()) { + suggestions.extend_from_slice(&sug.1); + } + } + } + + // dynamic suggestions + for sug in DYNAMIC_SUGGESTIONS { + for file in modified_files { + let sugs = sug(Path::new(file.as_ref())); + + suggestions.extend_from_slice(&sugs); + } + } + + suggestions.sort(); + suggestions.dedup(); + + suggestions +} + +#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Debug)] +pub struct Suggestion { + pub cmd: String, + pub stage: Option, + pub paths: Vec, +} + +impl Suggestion { + pub fn new(cmd: &str, stage: Option, paths: &[&str]) -> Self { + Self { cmd: cmd.to_owned(), stage, paths: paths.iter().map(|p| p.to_string()).collect() } + } + + pub fn with_single_path(cmd: &str, stage: Option, path: &str) -> Self { + Self::new(cmd, stage, &[path]) + } +} + +impl Display for Suggestion { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + write!(f, "{} ", self.cmd)?; + + for path in &self.paths { + write!(f, "{} ", path)?; + } + + if let Some(stage) = self.stage { + write!(f, "{}", stage)?; + } else { + // write a sentinel value here (in place of a stage) to be consumed + // by the shim in bootstrap, it will be read and ignored. + write!(f, "N/A")?; + } + + Ok(()) + } +} diff --git a/src/tools/suggest-tests/src/main.rs b/src/tools/suggest-tests/src/main.rs new file mode 100644 index 000000000000..0b541b60cba9 --- /dev/null +++ b/src/tools/suggest-tests/src/main.rs @@ -0,0 +1,27 @@ +use std::process::ExitCode; + +use build_helper::git::get_git_modified_files; +use suggest_tests::get_suggestions; + +fn main() -> ExitCode { + let modified_files = get_git_modified_files(None, &Vec::new()); + let modified_files = match modified_files { + Ok(Some(files)) => files, + Ok(None) => { + eprintln!("git error"); + return ExitCode::FAILURE; + } + Err(err) => { + eprintln!("Could not get modified files from git: \"{err}\""); + return ExitCode::FAILURE; + } + }; + + let suggestions = get_suggestions(&modified_files); + + for sug in &suggestions { + println!("{sug}"); + } + + ExitCode::SUCCESS +} diff --git a/src/tools/suggest-tests/src/static_suggestions.rs b/src/tools/suggest-tests/src/static_suggestions.rs new file mode 100644 index 000000000000..d8166ead8c49 --- /dev/null +++ b/src/tools/suggest-tests/src/static_suggestions.rs @@ -0,0 +1,24 @@ +use crate::{sug, Suggestion}; + +// FIXME: perhaps this could use `std::lazy` when it is stablizied +macro_rules! static_suggestions { + ($( $glob:expr => [ $( $suggestion:expr ),* ] ),*) => { + pub(crate) const STATIC_SUGGESTIONS: ::once_cell::unsync::Lazy)>> + = ::once_cell::unsync::Lazy::new(|| vec![ $( ($glob, vec![ $($suggestion),* ]) ),*]); + } +} + +static_suggestions! { + "*.md" => [ + sug!("test", 0, ["linkchecker"]) + ], + + "compiler/*" => [ + sug!("check"), + sug!("test", 1, ["src/test/ui", "src/test/run-make"]) + ], + + "src/librustdoc/*" => [ + sug!("test", 1, ["rustdoc"]) + ] +} diff --git a/src/tools/suggest-tests/src/tests.rs b/src/tools/suggest-tests/src/tests.rs new file mode 100644 index 000000000000..5bc1a7df7ca1 --- /dev/null +++ b/src/tools/suggest-tests/src/tests.rs @@ -0,0 +1,21 @@ +macro_rules! sugg_test { + ( $( $name:ident: $paths:expr => $suggestions:expr ),* ) => { + $( + #[test] + fn $name() { + let suggestions = crate::get_suggestions(&$paths).into_iter().map(|s| s.to_string()).collect::>(); + assert_eq!(suggestions, $suggestions); + } + )* + }; +} + +sugg_test! { + test_error_code_docs: ["compiler/rustc_error_codes/src/error_codes/E0000.md"] => + ["check N/A", "test compiler/rustc_error_codes N/A", "test linkchecker 0", "test src/test/ui src/test/run-make 1"], + + test_rustdoc: ["src/librustdoc/src/lib.rs"] => ["test rustdoc 1"], + + test_rustdoc_and_libstd: ["src/librustdoc/src/lib.rs", "library/std/src/lib.rs"] => + ["test library/std N/A", "test rustdoc 1"] +} From d9f99c36fe5122618a44caf393f9743e84a38c19 Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Sun, 9 Apr 2023 14:29:16 +0200 Subject: [PATCH 017/116] Use `Display` in top-level example for `PanicInfo` --- library/core/src/panic/panic_info.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/library/core/src/panic/panic_info.rs b/library/core/src/panic/panic_info.rs index 0d385c9d1874..06fbe083ca13 100644 --- a/library/core/src/panic/panic_info.rs +++ b/library/core/src/panic/panic_info.rs @@ -15,14 +15,10 @@ use crate::panic::Location; /// use std::panic; /// /// panic::set_hook(Box::new(|panic_info| { -/// if let Some(s) = panic_info.payload().downcast_ref::<&str>() { -/// println!("panic occurred: {s:?}"); -/// } else { -/// println!("panic occurred"); -/// } +/// println!("panic occurred: {panic_info}"); /// })); /// -/// panic!("Normal panic"); +/// panic!("critical system failure"); /// ``` #[lang = "panic_info"] #[stable(feature = "panic_hooks", since = "1.10.0")] From e612d785d75b84832725f3c265592c0e512f2ed3 Mon Sep 17 00:00:00 2001 From: Richard Schneeman Date: Sun, 9 Apr 2023 09:21:19 -0500 Subject: [PATCH 018/116] Apply suggestions from code review Fixes documentation. I wrote `env_clear` when I meant `env_remove`. Good catch. Co-authored-by: Josh Stone --- library/std/src/process.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/process.rs b/library/std/src/process.rs index 086eae334404..aeb9897e5e61 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -1031,7 +1031,7 @@ impl Command { /// process. /// /// Each element is a tuple key/value pair `(&OsStr, Option<&OsStr>)`. A [`None`] value - /// indicates its key was explicitly removed via [`Command::env_clear`]. The associated key for + /// indicates its key was explicitly removed via [`Command::env_remove`]. The associated key for /// the [`None`] value will no longer inherit from its parent process. /// /// An empty iterator can indicate that no explicit mappings were added or that From 53a4003e499bef096e2ed65f645425d963796d75 Mon Sep 17 00:00:00 2001 From: Mark Rousskov Date: Sun, 19 Mar 2023 19:12:39 -0400 Subject: [PATCH 019/116] Switch all job names to include core count This will allow moving jobs between 8 and 16 core VMs in the next commit more easily. --- src/ci/github-actions/ci.yml | 136 ++++++++++++++++++----------------- 1 file changed, 72 insertions(+), 64 deletions(-) diff --git a/src/ci/github-actions/ci.yml b/src/ci/github-actions/ci.yml index 403953b5047d..fdacc2ad95e7 100644 --- a/src/ci/github-actions/ci.yml +++ b/src/ci/github-actions/ci.yml @@ -73,7 +73,11 @@ x--expand-yaml-anchors--remove: - &base-job env: {} - - &job-linux-xl + - &job-linux-8c + os: ubuntu-20.04-8core-32gb + <<: *base-job + + - &job-linux-16c os: ubuntu-20.04-16core-64gb <<: *base-job @@ -81,10 +85,14 @@ x--expand-yaml-anchors--remove: os: macos-12-xl <<: *base-job - - &job-windows-xl + - &job-windows-8c os: windows-2019-8core-32gb <<: *base-job + - &job-windows-16c + os: windows-2019-16core-64gb + <<: *base-job + - &job-aarch64-linux os: [self-hosted, ARM64, linux] @@ -293,19 +301,19 @@ jobs: matrix: include: - name: mingw-check - <<: *job-linux-xl + <<: *job-linux-16c tidy: false - name: mingw-check-tidy - <<: *job-linux-xl + <<: *job-linux-16c tidy: true - name: x86_64-gnu-llvm-14 - <<: *job-linux-xl + <<: *job-linux-16c tidy: false - name: x86_64-gnu-tools - <<: *job-linux-xl + <<: *job-linux-16c tidy: false auto: @@ -327,103 +335,103 @@ jobs: <<: *job-aarch64-linux - name: arm-android - <<: *job-linux-xl + <<: *job-linux-16c - name: armhf-gnu - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-aarch64-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-android - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-arm-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-armhf-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-armv7-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-i586-gnu-i586-i686-musl - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-i686-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-mips-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-mips64-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-mips64el-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-mipsel-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-powerpc-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-powerpc64-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-powerpc64le-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-riscv64-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-s390x-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-various-1 - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-various-2 - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-x86_64-freebsd - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-x86_64-illumos - <<: *job-linux-xl + <<: *job-linux-16c - &dist-x86_64-linux name: dist-x86_64-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-x86_64-linux-alt env: IMAGE: dist-x86_64-linux - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-x86_64-musl - <<: *job-linux-xl + <<: *job-linux-16c - name: dist-x86_64-netbsd - <<: *job-linux-xl + <<: *job-linux-16c - name: i686-gnu - <<: *job-linux-xl + <<: *job-linux-16c - name: i686-gnu-nopt - <<: *job-linux-xl + <<: *job-linux-16c - name: mingw-check - <<: *job-linux-xl + <<: *job-linux-16c - name: test-various - <<: *job-linux-xl + <<: *job-linux-16c - name: wasm32 - <<: *job-linux-xl + <<: *job-linux-16c - name: x86_64-gnu - <<: *job-linux-xl + <<: *job-linux-16c # This job ensures commits landing on nightly still pass the full # test suite on the stable channel. There are some UI tests that @@ -438,39 +446,39 @@ jobs: # could cause failures when `dev: 1` in `stage0.txt`, and running # this on stable is useless. CI_ONLY_WHEN_CHANNEL: nightly - <<: *job-linux-xl + <<: *job-linux-16c - name: x86_64-gnu-aux - <<: *job-linux-xl + <<: *job-linux-16c - name: x86_64-gnu-debug - <<: *job-linux-xl + <<: *job-linux-16c - name: x86_64-gnu-distcheck - <<: *job-linux-xl + <<: *job-linux-16c - name: x86_64-gnu-llvm-15 env: RUST_BACKTRACE: 1 - <<: *job-linux-xl + <<: *job-linux-16c - name: x86_64-gnu-llvm-14 env: RUST_BACKTRACE: 1 - <<: *job-linux-xl + <<: *job-linux-16c - name: x86_64-gnu-llvm-14-stage1 env: RUST_BACKTRACE: 1 - <<: *job-linux-xl + <<: *job-linux-16c - name: x86_64-gnu-nopt - <<: *job-linux-xl + <<: *job-linux-16c - name: x86_64-gnu-tools env: DEPLOY_TOOLSTATES_JSON: toolstates-linux.json - <<: *job-linux-xl + <<: *job-linux-16c #################### # macOS Builders # @@ -572,38 +580,38 @@ jobs: env: RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc --enable-profiler SCRIPT: make ci-subset-1 - <<: *job-windows-xl + <<: *job-windows-8c - name: x86_64-msvc-2 env: RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc --enable-profiler SCRIPT: make ci-subset-2 - <<: *job-windows-xl + <<: *job-windows-8c - name: i686-msvc-1 env: RUST_CONFIGURE_ARGS: --build=i686-pc-windows-msvc SCRIPT: make ci-subset-1 - <<: *job-windows-xl + <<: *job-windows-8c - name: i686-msvc-2 env: RUST_CONFIGURE_ARGS: --build=i686-pc-windows-msvc SCRIPT: make ci-subset-2 - <<: *job-windows-xl + <<: *job-windows-8c - name: x86_64-msvc-cargo env: SCRIPT: python x.py --stage 2 test src/tools/cargotest src/tools/cargo RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc --enable-lld - <<: *job-windows-xl + <<: *job-windows-8c - name: x86_64-msvc-tools env: SCRIPT: src/ci/docker/host-x86_64/x86_64-gnu-tools/checktools.sh x.py /tmp/toolstate/toolstates.json windows RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc --save-toolstates=/tmp/toolstate/toolstates.json DEPLOY_TOOLSTATES_JSON: toolstates-windows.json - <<: *job-windows-xl + <<: *job-windows-8c # 32/64-bit MinGW builds. # @@ -629,7 +637,7 @@ jobs: # incompatible with LLVM downloads today). NO_DOWNLOAD_CI_LLVM: 1 CUSTOM_MINGW: 1 - <<: *job-windows-xl + <<: *job-windows-8c - name: i686-mingw-2 env: @@ -639,7 +647,7 @@ jobs: # incompatible with LLVM downloads today). NO_DOWNLOAD_CI_LLVM: 1 CUSTOM_MINGW: 1 - <<: *job-windows-xl + <<: *job-windows-8c - name: x86_64-mingw-1 env: @@ -651,7 +659,7 @@ jobs: # incompatible with LLVM downloads today). NO_DOWNLOAD_CI_LLVM: 1 CUSTOM_MINGW: 1 - <<: *job-windows-xl + <<: *job-windows-8c - name: x86_64-mingw-2 env: @@ -663,7 +671,7 @@ jobs: # incompatible with LLVM downloads today). NO_DOWNLOAD_CI_LLVM: 1 CUSTOM_MINGW: 1 - <<: *job-windows-xl + <<: *job-windows-8c - name: dist-x86_64-msvc env: @@ -675,7 +683,7 @@ jobs: --enable-profiler SCRIPT: PGO_HOST=x86_64-pc-windows-msvc python src/ci/stage-build.py python x.py dist bootstrap --include-default-paths DIST_REQUIRE_ALL_TOOLS: 1 - <<: *job-windows-xl + <<: *job-windows-8c - name: dist-i686-msvc env: @@ -687,7 +695,7 @@ jobs: --enable-profiler SCRIPT: python x.py dist bootstrap --include-default-paths DIST_REQUIRE_ALL_TOOLS: 1 - <<: *job-windows-xl + <<: *job-windows-8c - name: dist-aarch64-msvc env: @@ -701,7 +709,7 @@ jobs: # Hack around this SDK version, because it doesn't work with clang. # See https://github.com/rust-lang/rust/issues/88796 WINDOWS_SDK_20348_HACK: 1 - <<: *job-windows-xl + <<: *job-windows-8c - name: dist-i686-mingw env: @@ -715,7 +723,7 @@ jobs: SCRIPT: python x.py dist bootstrap --include-default-paths CUSTOM_MINGW: 1 DIST_REQUIRE_ALL_TOOLS: 1 - <<: *job-windows-xl + <<: *job-windows-8c - name: dist-x86_64-mingw env: @@ -729,13 +737,13 @@ jobs: NO_DOWNLOAD_CI_LLVM: 1 CUSTOM_MINGW: 1 DIST_REQUIRE_ALL_TOOLS: 1 - <<: *job-windows-xl + <<: *job-windows-8c - name: dist-x86_64-msvc-alt env: RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc --enable-extended --enable-profiler SCRIPT: python x.py dist bootstrap --include-default-paths - <<: *job-windows-xl + <<: *job-windows-8c try: permissions: @@ -750,7 +758,7 @@ jobs: include: - &dist-x86_64-linux name: dist-x86_64-linux - <<: *job-linux-xl + <<: *job-linux-16c master: name: master From 3153eaaeb547430fd64f3b16318183fd757ab472 Mon Sep 17 00:00:00 2001 From: Mark Rousskov Date: Mon, 10 Apr 2023 08:36:45 -0400 Subject: [PATCH 020/116] Trim down core counts for fast builders These builders aren't particularly high on overall average CPU usage and finish in typically around 30 minutes. Cutting their core counts will hopefully not significantly increase wall-time while cutting costs, allowing us to shift some of the wins into our slower builders. --- .github/workflows/ci.yml | 72 ++++++++++++++++++------------------ src/ci/github-actions/ci.yml | 72 ++++++++++++++++++------------------ 2 files changed, 72 insertions(+), 72 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a917d9a7d55d..bce88472f96f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -181,70 +181,70 @@ jobs: - ARM64 - linux - name: arm-android - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: armhf-gnu - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-aarch64-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-android - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-arm-linux os: ubuntu-20.04-16core-64gb env: {} - name: dist-armhf-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-armv7-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-i586-gnu-i586-i686-musl - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-i686-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-mips-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-mips64-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-mips64el-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-mipsel-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-powerpc-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-powerpc64-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-powerpc64le-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-riscv64-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-s390x-linux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-various-1 - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-various-2 - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-x86_64-freebsd - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-x86_64-illumos - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-x86_64-linux os: ubuntu-20.04-16core-64gb @@ -254,10 +254,10 @@ jobs: IMAGE: dist-x86_64-linux os: ubuntu-20.04-16core-64gb - name: dist-x86_64-musl - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: dist-x86_64-netbsd - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: i686-gnu os: ubuntu-20.04-16core-64gb @@ -266,51 +266,51 @@ jobs: os: ubuntu-20.04-16core-64gb env: {} - name: mingw-check - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: test-various - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: wasm32 - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: x86_64-gnu - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: x86_64-gnu-stable env: IMAGE: x86_64-gnu RUST_CI_OVERRIDE_RELEASE_CHANNEL: stable CI_ONLY_WHEN_CHANNEL: nightly - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb - name: x86_64-gnu-aux - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: x86_64-gnu-debug - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: x86_64-gnu-distcheck - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: x86_64-gnu-llvm-15 env: RUST_BACKTRACE: 1 - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb - name: x86_64-gnu-llvm-14 env: RUST_BACKTRACE: 1 - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb - name: x86_64-gnu-llvm-14-stage1 env: RUST_BACKTRACE: 1 - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb - name: x86_64-gnu-nopt - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb env: {} - name: x86_64-gnu-tools env: DEPLOY_TOOLSTATES_JSON: toolstates-linux.json - os: ubuntu-20.04-16core-64gb + os: ubuntu-20.04-8core-32gb - name: dist-x86_64-apple env: SCRIPT: "./x.py dist bootstrap --include-default-paths --host=x86_64-apple-darwin --target=x86_64-apple-darwin" diff --git a/src/ci/github-actions/ci.yml b/src/ci/github-actions/ci.yml index fdacc2ad95e7..dbf4be4be24e 100644 --- a/src/ci/github-actions/ci.yml +++ b/src/ci/github-actions/ci.yml @@ -335,70 +335,70 @@ jobs: <<: *job-aarch64-linux - name: arm-android - <<: *job-linux-16c + <<: *job-linux-8c - name: armhf-gnu - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-aarch64-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-android - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-arm-linux <<: *job-linux-16c - name: dist-armhf-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-armv7-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-i586-gnu-i586-i686-musl - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-i686-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-mips-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-mips64-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-mips64el-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-mipsel-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-powerpc-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-powerpc64-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-powerpc64le-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-riscv64-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-s390x-linux - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-various-1 - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-various-2 - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-x86_64-freebsd - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-x86_64-illumos - <<: *job-linux-16c + <<: *job-linux-8c - &dist-x86_64-linux name: dist-x86_64-linux @@ -410,10 +410,10 @@ jobs: <<: *job-linux-16c - name: dist-x86_64-musl - <<: *job-linux-16c + <<: *job-linux-8c - name: dist-x86_64-netbsd - <<: *job-linux-16c + <<: *job-linux-8c - name: i686-gnu <<: *job-linux-16c @@ -422,16 +422,16 @@ jobs: <<: *job-linux-16c - name: mingw-check - <<: *job-linux-16c + <<: *job-linux-8c - name: test-various - <<: *job-linux-16c + <<: *job-linux-8c - name: wasm32 - <<: *job-linux-16c + <<: *job-linux-8c - name: x86_64-gnu - <<: *job-linux-16c + <<: *job-linux-8c # This job ensures commits landing on nightly still pass the full # test suite on the stable channel. There are some UI tests that @@ -446,39 +446,39 @@ jobs: # could cause failures when `dev: 1` in `stage0.txt`, and running # this on stable is useless. CI_ONLY_WHEN_CHANNEL: nightly - <<: *job-linux-16c + <<: *job-linux-8c - name: x86_64-gnu-aux - <<: *job-linux-16c + <<: *job-linux-8c - name: x86_64-gnu-debug - <<: *job-linux-16c + <<: *job-linux-8c - name: x86_64-gnu-distcheck - <<: *job-linux-16c + <<: *job-linux-8c - name: x86_64-gnu-llvm-15 env: RUST_BACKTRACE: 1 - <<: *job-linux-16c + <<: *job-linux-8c - name: x86_64-gnu-llvm-14 env: RUST_BACKTRACE: 1 - <<: *job-linux-16c + <<: *job-linux-8c - name: x86_64-gnu-llvm-14-stage1 env: RUST_BACKTRACE: 1 - <<: *job-linux-16c + <<: *job-linux-8c - name: x86_64-gnu-nopt - <<: *job-linux-16c + <<: *job-linux-8c - name: x86_64-gnu-tools env: DEPLOY_TOOLSTATES_JSON: toolstates-linux.json - <<: *job-linux-16c + <<: *job-linux-8c #################### # macOS Builders # From a0daf22b95ff1cd3f7ac55ea9370987535f3134d Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Mon, 10 Apr 2023 21:07:29 +0200 Subject: [PATCH 021/116] Fix typos in library --- library/core/src/intrinsics/mir.rs | 2 +- library/core/src/slice/sort.rs | 2 +- library/core/src/str/pattern.rs | 2 +- library/std/src/sys/unix/fs.rs | 2 +- library/std/src/sys/windows/c/errors.rs | 2 +- library/std/src/sys_common/thread_parking/id.rs | 2 +- library/test/src/lib.rs | 10 +++++----- 7 files changed, 11 insertions(+), 11 deletions(-) diff --git a/library/core/src/intrinsics/mir.rs b/library/core/src/intrinsics/mir.rs index 6690c1a76d5f..3f6c445af7b6 100644 --- a/library/core/src/intrinsics/mir.rs +++ b/library/core/src/intrinsics/mir.rs @@ -246,7 +246,7 @@ //! - The exception is the last arm, which must be `_ => basic_block` and corresponds to the //! otherwise branch. //! - [`Call`] has an associated function as well. The third argument of this function is a normal -//! function call expresion, for example `my_other_function(a, 5)`. +//! function call expression, for example `my_other_function(a, 5)`. //! #![unstable( diff --git a/library/core/src/slice/sort.rs b/library/core/src/slice/sort.rs index 2333f60a8889..07fd96f92958 100644 --- a/library/core/src/slice/sort.rs +++ b/library/core/src/slice/sort.rs @@ -1486,7 +1486,7 @@ where } /// Finds a streak of presorted elements starting at the beginning of the slice. Returns the first -/// value that is not part of said streak, and a bool denoting wether the streak was reversed. +/// value that is not part of said streak, and a bool denoting whether the streak was reversed. /// Streaks can be increasing or decreasing. fn find_streak(v: &[T], is_less: &mut F) -> (usize, bool) where diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index 19da6d2fbecb..e3a464a1c51a 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -1891,7 +1891,7 @@ unsafe fn small_slice_eq(x: &[u8], y: &[u8]) -> bool { // SAFETY: Via the conditional above, we know that both `px` and `py` // have the same length, so `px < pxend` implies that `py < pyend`. - // Thus, derefencing both `px` and `py` in the loop below is safe. + // Thus, dereferencing both `px` and `py` in the loop below is safe. // // Moreover, we set `pxend` and `pyend` to be 4 bytes before the actual // end of `px` and `py`. Thus, the final dereference outside of the diff --git a/library/std/src/sys/unix/fs.rs b/library/std/src/sys/unix/fs.rs index 7566fafda24a..b29a51f21929 100644 --- a/library/std/src/sys/unix/fs.rs +++ b/library/std/src/sys/unix/fs.rs @@ -1892,7 +1892,7 @@ mod remove_dir_impl { // file descriptor is automatically closed by libc::closedir() now, so give up ownership let new_parent_fd = dir_fd.into_raw_fd(); // a valid root is not needed because we do not call any functions involving the full path - // of the DirEntrys. + // of the `DirEntry`s. let dummy_root = PathBuf::new(); let inner = InnerReadDir { dirp, root: dummy_root }; Ok((ReadDir::new(inner), new_parent_fd)) diff --git a/library/std/src/sys/windows/c/errors.rs b/library/std/src/sys/windows/c/errors.rs index 23dcc119db9f..ad8da19b6daa 100644 --- a/library/std/src/sys/windows/c/errors.rs +++ b/library/std/src/sys/windows/c/errors.rs @@ -12,7 +12,7 @@ pub const ERROR_RESOURCE_CALL_TIMED_OUT: DWORD = 5910; pub const FRS_ERR_SYSVOL_POPULATE_TIMEOUT: DWORD = 8014; pub const DNS_ERROR_RECORD_TIMED_OUT: DWORD = 9705; -// The followiung list was obtained from +// The following list was obtained from // `/usr/x86_64-w64-mingw32/include/winerror.h` // in the Debian package // mingw-w64_6.0.0-3_all.deb diff --git a/library/std/src/sys_common/thread_parking/id.rs b/library/std/src/sys_common/thread_parking/id.rs index 575988ec760c..15042fc3beec 100644 --- a/library/std/src/sys_common/thread_parking/id.rs +++ b/library/std/src/sys_common/thread_parking/id.rs @@ -79,7 +79,7 @@ impl Parker { park_timeout(dur, self.state.as_ptr().addr()); // Swap to ensure that we observe all state changes with acquire // ordering, even if the state has been changed after the timeout - // occured. + // occurred. self.state.swap(EMPTY, Acquire); } } diff --git a/library/test/src/lib.rs b/library/test/src/lib.rs index 88d8e5fe97ad..ae3a65d5ea6e 100644 --- a/library/test/src/lib.rs +++ b/library/test/src/lib.rs @@ -220,14 +220,14 @@ pub fn assert_test_result(result: T) -> Result<(), String> { struct FilteredTests { tests: Vec<(TestId, TestDescAndFn)>, - benchs: Vec<(TestId, TestDescAndFn)>, + benches: Vec<(TestId, TestDescAndFn)>, next_id: usize, } impl FilteredTests { fn add_bench(&mut self, desc: TestDesc, testfn: TestFn) { let test = TestDescAndFn { desc, testfn }; - self.benchs.push((TestId(self.next_id), test)); + self.benches.push((TestId(self.next_id), test)); self.next_id += 1; } fn add_test(&mut self, desc: TestDesc, testfn: TestFn) { @@ -246,7 +246,7 @@ impl FilteredTests { self.add_test(desc, testfn); } fn total_len(&self) -> usize { - self.tests.len() + self.benchs.len() + self.tests.len() + self.benches.len() } } @@ -291,7 +291,7 @@ where let tests_len = tests.len(); - let mut filtered = FilteredTests { tests: Vec::new(), benchs: Vec::new(), next_id: 0 }; + let mut filtered = FilteredTests { tests: Vec::new(), benches: Vec::new(), next_id: 0 }; for test in filter_tests(opts, tests) { let mut desc = test.desc; @@ -458,7 +458,7 @@ where if opts.bench_benchmarks { // All benchmarks run at the end, in serial. - for (id, b) in filtered.benchs { + for (id, b) in filtered.benches { let event = TestEvent::TeWait(b.desc.clone()); notify_about_test_event(event)?; let join_handle = run_test(opts, false, id, b, run_strategy, tx.clone()); From 873ab04d898b32cd9196d15e68c724d583c07f17 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Tue, 11 Apr 2023 08:04:09 +0200 Subject: [PATCH 022/116] fix running Miri tests --- src/bootstrap/test.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index 058ff429e80f..7b212d9cfbd4 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -638,7 +638,10 @@ impl Step for Miri { // Forward test filters. cargo.arg("--").args(builder.config.cmd.test_args()); - add_flags_and_try_run_tests(builder, &mut cargo.into()); + // This can NOT be `add_flags_and_try_run_tests` since the Miri test runner + // does not understand those flags! + let mut cargo = Command::from(cargo); + builder.run(&mut cargo); // # Run `cargo miri test`. // This is just a smoke test (Miri's own CI invokes this in a bunch of different ways and ensures From a159dcda6292c03faf3adb37f0a176ca7a35f0dc Mon Sep 17 00:00:00 2001 From: Ezra Shaw Date: Wed, 12 Apr 2023 14:01:59 +1200 Subject: [PATCH 023/116] fix: disable `x suggest` when using `build-metrics` --- src/bootstrap/lib.rs | 2 +- src/bootstrap/suggest.rs | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index 2ce9ddd2a680..1f2fa3df98e1 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -190,7 +190,7 @@ pub enum GitRepo { /// although most functions are implemented as free functions rather than /// methods specifically on this structure itself (to make it easier to /// organize). -#[derive(Clone)] +#[cfg_attr(not(feature = "build-metrics"), derive(Clone))] pub struct Build { /// User-specified configuration from `config.toml`. config: Config, diff --git a/src/bootstrap/suggest.rs b/src/bootstrap/suggest.rs index 1a482e416594..ff20ebec2677 100644 --- a/src/bootstrap/suggest.rs +++ b/src/bootstrap/suggest.rs @@ -1,3 +1,5 @@ +#![cfg_attr(feature = "build-metrics", allow(unused))] + use std::str::FromStr; use std::path::PathBuf; @@ -7,7 +9,13 @@ use crate::{ tool::Tool, }; +#[cfg(feature = "build-metrics")] +pub fn suggest(builder: &Builder<'_>, run: bool) { + panic!("`x suggest` is not supported with `build-metrics`") +} + /// Suggests a list of possible `x.py` commands to run based on modified files in branch. +#[cfg(not(feature = "build-metrics"))] pub fn suggest(builder: &Builder<'_>, run: bool) { let suggestions = builder.tool_cmd(Tool::SuggestTests).output().expect("failed to run `suggest-tests` tool"); From 5badbefd706addb8ab501eed745139e1846b09f9 Mon Sep 17 00:00:00 2001 From: klensy Date: Wed, 12 Apr 2023 14:52:11 +0300 Subject: [PATCH 024/116] drop some windows features --- src/bootstrap/Cargo.toml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/bootstrap/Cargo.toml b/src/bootstrap/Cargo.toml index eeda6d7c121f..7b9eaceb00f6 100644 --- a/src/bootstrap/Cargo.toml +++ b/src/bootstrap/Cargo.toml @@ -69,13 +69,9 @@ version = "0.46.0" features = [ "Win32_Foundation", "Win32_Security", - "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", - "Win32_System_IO", - "Win32_System_Ioctl", "Win32_System_JobObjects", "Win32_System_ProcessStatus", - "Win32_System_SystemServices", "Win32_System_Threading", "Win32_System_Time", ] From ad2b34d0e37e2f968f226e2401bcb894207ca1c5 Mon Sep 17 00:00:00 2001 From: KaDiWa Date: Tue, 9 Aug 2022 02:14:43 +0200 Subject: [PATCH 025/116] remove some unneeded imports --- library/alloc/benches/btree/map.rs | 1 - library/alloc/benches/vec.rs | 2 +- library/alloc/src/boxed.rs | 7 +--- .../alloc/src/collections/binary_heap/mod.rs | 4 +- library/alloc/src/collections/btree/map.rs | 5 +-- .../alloc/src/collections/btree/map/tests.rs | 3 +- library/alloc/src/collections/btree/set.rs | 4 +- .../alloc/src/collections/btree/set/tests.rs | 1 - library/alloc/src/collections/linked_list.rs | 3 +- .../src/collections/vec_deque/into_iter.rs | 1 - .../alloc/src/collections/vec_deque/mod.rs | 2 +- library/alloc/src/raw_vec.rs | 1 - library/alloc/src/rc.rs | 22 +++++----- library/alloc/src/string.rs | 4 +- library/alloc/src/sync.rs | 13 +++--- library/alloc/src/vec/cow.rs | 1 - library/alloc/src/vec/into_iter.rs | 2 +- library/alloc/src/vec/mod.rs | 7 +--- library/core/src/iter/sources/repeat_with.rs | 1 - library/core/src/iter/traits/iterator.rs | 1 - library/core/src/net/parser.rs | 2 +- library/core/src/primitive_docs.rs | 6 --- library/core/src/sync/exclusive.rs | 3 -- .../crates/core_simd/src/masks/full_masks.rs | 2 +- library/proc_macro/src/bridge/fxhash.rs | 2 - library/proc_macro/src/lib.rs | 6 +-- library/std/src/collections/hash/map.rs | 1 - library/std/src/collections/hash/set.rs | 1 - library/std/src/collections/mod.rs | 2 - library/std/src/ffi/os_str.rs | 1 - library/std/src/io/error.rs | 1 - library/std/src/keyword_docs.rs | 2 +- library/std/src/path.rs | 42 +++++++++---------- library/std/src/prelude/mod.rs | 6 +-- library/std/src/primitive_docs.rs | 6 --- .../std/src/sys/sgx/abi/usercalls/alloc.rs | 1 - library/std/src/sys/unix/futex.rs | 2 - library/std/src/sys/unix/os.rs | 1 - .../src/sys/unix/process/process_fuchsia.rs | 2 - library/std/src/sys_common/net.rs | 1 - src/bootstrap/cache.rs | 3 +- src/librustdoc/clean/mod.rs | 1 - src/librustdoc/clean/types.rs | 3 +- src/librustdoc/config.rs | 1 - src/librustdoc/html/markdown.rs | 1 - src/librustdoc/html/render/mod.rs | 1 - src/librustdoc/html/render/search_index.rs | 2 +- src/librustdoc/json/conversions.rs | 1 - src/librustdoc/lib.rs | 1 - src/tools/bump-stage0/src/main.rs | 1 - src/tools/tidy/src/bins.rs | 4 +- src/tools/tidy/src/pal.rs | 1 - .../src/raw_emitter.rs | 1 - .../unicode-table-generator/src/skiplist.rs | 1 - tests/ui/hygiene/panic-location.run.stderr | 2 +- 55 files changed, 64 insertions(+), 135 deletions(-) diff --git a/library/alloc/benches/btree/map.rs b/library/alloc/benches/btree/map.rs index 1f6b87fb0e40..ec1b0a8eba03 100644 --- a/library/alloc/benches/btree/map.rs +++ b/library/alloc/benches/btree/map.rs @@ -1,5 +1,4 @@ use std::collections::BTreeMap; -use std::iter::Iterator; use std::ops::RangeBounds; use std::vec::Vec; diff --git a/library/alloc/benches/vec.rs b/library/alloc/benches/vec.rs index 663f6b9dd1c9..c1d3e1bdfe79 100644 --- a/library/alloc/benches/vec.rs +++ b/library/alloc/benches/vec.rs @@ -1,5 +1,5 @@ use rand::RngCore; -use std::iter::{repeat, FromIterator}; +use std::iter::repeat; use test::{black_box, Bencher}; #[bench] diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 09041bb119bb..7f88327bf190 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -150,16 +150,13 @@ use core::any::Any; use core::async_iter::AsyncIterator; use core::borrow; use core::cmp::Ordering; -use core::convert::{From, TryFrom}; use core::error::Error; use core::fmt; use core::future::Future; use core::hash::{Hash, Hasher}; -#[cfg(not(no_global_oom_handling))] -use core::iter::FromIterator; -use core::iter::{FusedIterator, Iterator}; +use core::iter::FusedIterator; use core::marker::Tuple; -use core::marker::{Unpin, Unsize}; +use core::marker::Unsize; use core::mem; use core::ops::{ CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver, diff --git a/library/alloc/src/collections/binary_heap/mod.rs b/library/alloc/src/collections/binary_heap/mod.rs index bc86125c7c33..8aa4d342e6e3 100644 --- a/library/alloc/src/collections/binary_heap/mod.rs +++ b/library/alloc/src/collections/binary_heap/mod.rs @@ -144,7 +144,7 @@ #![stable(feature = "rust1", since = "1.0.0")] use core::fmt; -use core::iter::{FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen}; +use core::iter::{FusedIterator, InPlaceIterable, SourceIter, TrustedLen}; use core::mem::{self, swap, ManuallyDrop}; use core::num::NonZeroUsize; use core::ops::{Deref, DerefMut}; @@ -263,7 +263,6 @@ mod tests; /// more detailed analysis. /// /// [`core::cmp::Reverse`]: core::cmp::Reverse -/// [`Ord`]: core::cmp::Ord /// [`Cell`]: core::cell::Cell /// [`RefCell`]: core::cell::RefCell /// [push]: BinaryHeap::push @@ -1418,7 +1417,6 @@ impl FusedIterator for Iter<'_, T> {} /// (provided by the [`IntoIterator`] trait). See its documentation for more. /// /// [`into_iter`]: BinaryHeap::into_iter -/// [`IntoIterator`]: core::iter::IntoIterator #[stable(feature = "rust1", since = "1.0.0")] #[derive(Clone)] pub struct IntoIter { diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs index 61db46314b78..7b378ccc01ad 100644 --- a/library/alloc/src/collections/btree/map.rs +++ b/library/alloc/src/collections/btree/map.rs @@ -3,7 +3,7 @@ use core::borrow::Borrow; use core::cmp::Ordering; use core::fmt::{self, Debug}; use core::hash::{Hash, Hasher}; -use core::iter::{FromIterator, FusedIterator}; +use core::iter::FusedIterator; use core::marker::PhantomData; use core::mem::{self, ManuallyDrop}; use core::ops::{Bound, Index, RangeBounds}; @@ -420,7 +420,6 @@ impl<'a, K: 'a, V: 'a> Default for IterMut<'a, K, V> { /// (provided by the [`IntoIterator`] trait). See its documentation for more. /// /// [`into_iter`]: IntoIterator::into_iter -/// [`IntoIterator`]: core::iter::IntoIterator #[stable(feature = "rust1", since = "1.0.0")] #[rustc_insignificant_dtor] pub struct IntoIter< @@ -650,7 +649,7 @@ impl BTreeMap { #[stable(feature = "rust1", since = "1.0.0")] pub fn clear(&mut self) { // avoid moving the allocator - mem::drop(BTreeMap { + drop(BTreeMap { root: mem::replace(&mut self.root, None), length: mem::replace(&mut self.length, 0), alloc: self.alloc.clone(), diff --git a/library/alloc/src/collections/btree/map/tests.rs b/library/alloc/src/collections/btree/map/tests.rs index 76c2f27b4663..1c6ed0b4f8bc 100644 --- a/library/alloc/src/collections/btree/map/tests.rs +++ b/library/alloc/src/collections/btree/map/tests.rs @@ -9,8 +9,7 @@ use crate::testing::ord_chaos::{Cyclic3, Governed, Governor}; use crate::testing::rng::DeterministicRng; use crate::vec::Vec; use std::cmp::Ordering; -use std::convert::TryFrom; -use std::iter::{self, FromIterator}; +use std::iter; use std::mem; use std::ops::Bound::{self, Excluded, Included, Unbounded}; use std::ops::RangeBounds; diff --git a/library/alloc/src/collections/btree/set.rs b/library/alloc/src/collections/btree/set.rs index a7cb3948aa11..232a017314e5 100644 --- a/library/alloc/src/collections/btree/set.rs +++ b/library/alloc/src/collections/btree/set.rs @@ -4,7 +4,7 @@ use core::cmp::Ordering::{self, Equal, Greater, Less}; use core::cmp::{max, min}; use core::fmt::{self, Debug}; use core::hash::{Hash, Hasher}; -use core::iter::{FromIterator, FusedIterator, Peekable}; +use core::iter::{FusedIterator, Peekable}; use core::mem::ManuallyDrop; use core::ops::{BitAnd, BitOr, BitXor, RangeBounds, Sub}; @@ -30,7 +30,6 @@ use crate::alloc::{Allocator, Global}; /// Iterators returned by [`BTreeSet::iter`] produce their items in order, and take worst-case /// logarithmic and amortized constant time per item returned. /// -/// [`Ord`]: core::cmp::Ord /// [`Cell`]: core::cell::Cell /// [`RefCell`]: core::cell::RefCell /// @@ -147,7 +146,6 @@ impl fmt::Debug for Iter<'_, T> { /// (provided by the [`IntoIterator`] trait). See its documentation for more. /// /// [`into_iter`]: BTreeSet#method.into_iter -/// [`IntoIterator`]: core::iter::IntoIterator #[stable(feature = "rust1", since = "1.0.0")] #[derive(Debug)] pub struct IntoIter< diff --git a/library/alloc/src/collections/btree/set/tests.rs b/library/alloc/src/collections/btree/set/tests.rs index 7b8d41a60317..a7c839d77ed4 100644 --- a/library/alloc/src/collections/btree/set/tests.rs +++ b/library/alloc/src/collections/btree/set/tests.rs @@ -4,7 +4,6 @@ use crate::testing::rng::DeterministicRng; use crate::vec::Vec; use std::cmp::Ordering; use std::hash::{Hash, Hasher}; -use std::iter::FromIterator; use std::ops::Bound::{Excluded, Included}; use std::panic::{catch_unwind, AssertUnwindSafe}; diff --git a/library/alloc/src/collections/linked_list.rs b/library/alloc/src/collections/linked_list.rs index 080a4a14eda6..1743a155c5ab 100644 --- a/library/alloc/src/collections/linked_list.rs +++ b/library/alloc/src/collections/linked_list.rs @@ -15,7 +15,7 @@ use core::cmp::Ordering; use core::fmt; use core::hash::{Hash, Hasher}; -use core::iter::{FromIterator, FusedIterator}; +use core::iter::FusedIterator; use core::marker::PhantomData; use core::mem; use core::ptr::NonNull; @@ -130,7 +130,6 @@ impl fmt::Debug for IterMut<'_, T> { /// (provided by the [`IntoIterator`] trait). See its documentation for more. /// /// [`into_iter`]: LinkedList::into_iter -/// [`IntoIterator`]: core::iter::IntoIterator #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter { diff --git a/library/alloc/src/collections/vec_deque/into_iter.rs b/library/alloc/src/collections/vec_deque/into_iter.rs index e2b40f7912e0..d9e274df0f5f 100644 --- a/library/alloc/src/collections/vec_deque/into_iter.rs +++ b/library/alloc/src/collections/vec_deque/into_iter.rs @@ -12,7 +12,6 @@ use super::VecDeque; /// (provided by the [`IntoIterator`] trait). See its documentation for more. /// /// [`into_iter`]: VecDeque::into_iter -/// [`IntoIterator`]: core::iter::IntoIterator #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter< diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index 05dbcdc904e0..8916b42eda05 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -10,7 +10,7 @@ use core::cmp::{self, Ordering}; use core::fmt; use core::hash::{Hash, Hasher}; -use core::iter::{repeat_n, repeat_with, ByRefSized, FromIterator}; +use core::iter::{repeat_n, repeat_with, ByRefSized}; use core::mem::{ManuallyDrop, SizedTypeProperties}; use core::ops::{Index, IndexMut, Range, RangeBounds}; use core::ptr; diff --git a/library/alloc/src/raw_vec.rs b/library/alloc/src/raw_vec.rs index 3751f2a24545..dfd30d99cf04 100644 --- a/library/alloc/src/raw_vec.rs +++ b/library/alloc/src/raw_vec.rs @@ -4,7 +4,6 @@ use core::alloc::LayoutError; use core::cmp; use core::intrinsics; use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties}; -use core::ops::Drop; use core::ptr::{self, NonNull, Unique}; use core::slice; diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 1e9cf404f77e..cf93a40496fd 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -15,7 +15,7 @@ //! //! [`Rc`] uses non-atomic reference counting. This means that overhead is very //! low, but an [`Rc`] cannot be sent between threads, and consequently [`Rc`] -//! does not implement [`Send`][send]. As a result, the Rust compiler +//! does not implement [`Send`]. As a result, the Rust compiler //! will check *at compile time* that you are not sending [`Rc`]s between //! threads. If you need multi-threaded, atomic reference counting, use //! [`sync::Arc`][arc]. @@ -232,7 +232,6 @@ //! [clone]: Clone::clone //! [`Cell`]: core::cell::Cell //! [`RefCell`]: core::cell::RefCell -//! [send]: core::marker::Send //! [arc]: crate::sync::Arc //! [`Deref`]: core::ops::Deref //! [downgrade]: Rc::downgrade @@ -251,13 +250,12 @@ use core::any::Any; use core::borrow; use core::cell::Cell; use core::cmp::Ordering; -use core::convert::{From, TryFrom}; use core::fmt; use core::hash::{Hash, Hasher}; use core::intrinsics::abort; #[cfg(not(no_global_oom_handling))] use core::iter; -use core::marker::{self, PhantomData, Unpin, Unsize}; +use core::marker::{PhantomData, Unsize}; #[cfg(not(no_global_oom_handling))] use core::mem::size_of_val; use core::mem::{self, align_of_val_raw, forget}; @@ -321,7 +319,7 @@ pub struct Rc { } #[stable(feature = "rust1", since = "1.0.0")] -impl !marker::Send for Rc {} +impl !Send for Rc {} // Note that this negative impl isn't strictly necessary for correctness, // as `Rc` transitively contains a `Cell`, which is itself `!Sync`. @@ -329,7 +327,7 @@ impl !marker::Send for Rc {} // having an explicit negative impl is nice for documentation purposes // and results in nicer error messages. #[stable(feature = "rust1", since = "1.0.0")] -impl !marker::Sync for Rc {} +impl !Sync for Rc {} #[stable(feature = "catch_unwind", since = "1.9.0")] impl UnwindSafe for Rc {} @@ -1060,7 +1058,7 @@ impl Rc { #[inline] #[stable(feature = "rc_mutate_strong_count", since = "1.53.0")] pub unsafe fn decrement_strong_count(ptr: *const T) { - unsafe { mem::drop(Rc::from_raw(ptr)) }; + unsafe { drop(Rc::from_raw(ptr)) }; } /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to @@ -1496,7 +1494,7 @@ impl Rc<[T]> { /// /// Behavior is undefined should the size be wrong. #[cfg(not(no_global_oom_handling))] - unsafe fn from_iter_exact(iter: impl iter::Iterator, len: usize) -> Rc<[T]> { + unsafe fn from_iter_exact(iter: impl Iterator, len: usize) -> Rc<[T]> { // Panic guard while cloning T elements. // In the event of a panic, elements that have been written // into the new RcBox will be dropped, then the memory freed. @@ -2088,7 +2086,7 @@ impl TryFrom> for Rc<[T; N]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_iter", since = "1.37.0")] -impl iter::FromIterator for Rc<[T]> { +impl FromIterator for Rc<[T]> { /// Takes each element in the `Iterator` and collects it into an `Rc<[T]>`. /// /// # Performance characteristics @@ -2127,7 +2125,7 @@ impl iter::FromIterator for Rc<[T]> { /// let evens: Rc<[u8]> = (0..10).collect(); // Just a single allocation happens here. /// # assert_eq!(&*evens, &*(0..10).collect::>()); /// ``` - fn from_iter>(iter: I) -> Self { + fn from_iter>(iter: I) -> Self { ToRcSlice::to_rc_slice(iter.into_iter()) } } @@ -2204,9 +2202,9 @@ pub struct Weak { } #[stable(feature = "rc_weak", since = "1.4.0")] -impl !marker::Send for Weak {} +impl !Send for Weak {} #[stable(feature = "rc_weak", since = "1.4.0")] -impl !marker::Sync for Weak {} +impl !Sync for Weak {} #[unstable(feature = "coerce_unsized", issue = "18598")] impl, U: ?Sized> CoerceUnsized> for Weak {} diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index c1cd3c74ab67..be41919b9dc2 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -45,9 +45,9 @@ use core::error::Error; use core::fmt; use core::hash; -use core::iter::FusedIterator; #[cfg(not(no_global_oom_handling))] -use core::iter::{from_fn, FromIterator}; +use core::iter::from_fn; +use core::iter::FusedIterator; #[cfg(not(no_global_oom_handling))] use core::ops::Add; #[cfg(not(no_global_oom_handling))] diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 150924851d21..5bfe537bc830 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -11,14 +11,13 @@ use core::any::Any; use core::borrow; use core::cmp::Ordering; -use core::convert::{From, TryFrom}; 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, Unpin, Unsize}; +use core::marker::{PhantomData, Unsize}; #[cfg(not(no_global_oom_handling))] use core::mem::size_of_val; use core::mem::{self, align_of_val_raw}; @@ -188,8 +187,6 @@ macro_rules! acquire { /// [mutex]: ../../std/sync/struct.Mutex.html /// [rwlock]: ../../std/sync/struct.RwLock.html /// [atomic]: core::sync::atomic -/// [`Send`]: core::marker::Send -/// [`Sync`]: core::marker::Sync /// [deref]: core::ops::Deref /// [downgrade]: Arc::downgrade /// [upgrade]: Weak::upgrade @@ -1241,7 +1238,7 @@ impl Arc { #[inline] #[stable(feature = "arc_mutate_strong_count", since = "1.51.0")] pub unsafe fn decrement_strong_count(ptr: *const T) { - unsafe { mem::drop(Arc::from_raw(ptr)) }; + unsafe { drop(Arc::from_raw(ptr)) }; } #[inline] @@ -1404,7 +1401,7 @@ impl Arc<[T]> { /// /// Behavior is undefined should the size be wrong. #[cfg(not(no_global_oom_handling))] - unsafe fn from_iter_exact(iter: impl iter::Iterator, len: usize) -> Arc<[T]> { + unsafe fn from_iter_exact(iter: impl Iterator, len: usize) -> Arc<[T]> { // Panic guard while cloning T elements. // In the event of a panic, elements that have been written // into the new ArcInner will be dropped, then the memory freed. @@ -2818,7 +2815,7 @@ impl TryFrom> for Arc<[T; N]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "shared_from_iter", since = "1.37.0")] -impl iter::FromIterator for Arc<[T]> { +impl FromIterator for Arc<[T]> { /// Takes each element in the `Iterator` and collects it into an `Arc<[T]>`. /// /// # Performance characteristics @@ -2857,7 +2854,7 @@ impl iter::FromIterator for Arc<[T]> { /// let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here. /// # assert_eq!(&*evens, &*(0..10).collect::>()); /// ``` - fn from_iter>(iter: I) -> Self { + fn from_iter>(iter: I) -> Self { ToArcSlice::to_arc_slice(iter.into_iter()) } } diff --git a/library/alloc/src/vec/cow.rs b/library/alloc/src/vec/cow.rs index 64943a273c9a..2c799605b7b6 100644 --- a/library/alloc/src/vec/cow.rs +++ b/library/alloc/src/vec/cow.rs @@ -1,5 +1,4 @@ use crate::borrow::Cow; -use core::iter::FromIterator; use super::Vec; diff --git a/library/alloc/src/vec/into_iter.rs b/library/alloc/src/vec/into_iter.rs index 6a05f70e4374..02faf8e63894 100644 --- a/library/alloc/src/vec/into_iter.rs +++ b/library/alloc/src/vec/into_iter.rs @@ -108,7 +108,7 @@ impl IntoIter { /// ``` /// # let mut into_iter = Vec::::with_capacity(10).into_iter(); /// let mut into_iter = std::mem::replace(&mut into_iter, Vec::new().into_iter()); - /// (&mut into_iter).for_each(core::mem::drop); + /// (&mut into_iter).for_each(drop); /// std::mem::forget(into_iter); /// ``` /// diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 9f0111db4524..3736a6e0b0ec 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -56,12 +56,9 @@ #[cfg(not(no_global_oom_handling))] use core::cmp; use core::cmp::Ordering; -use core::convert::TryFrom; use core::fmt; use core::hash::{Hash, Hasher}; use core::iter; -#[cfg(not(no_global_oom_handling))] -use core::iter::FromIterator; use core::marker::PhantomData; use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties}; use core::ops::{self, Index, IndexMut, Range, RangeBounds}; @@ -2990,7 +2987,7 @@ impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec { } } -/// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison). +/// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison). #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for Vec { #[inline] @@ -3002,7 +2999,7 @@ impl PartialOrd for Vec { #[stable(feature = "rust1", since = "1.0.0")] impl Eq for Vec {} -/// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison). +/// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison). #[stable(feature = "rust1", since = "1.0.0")] impl Ord for Vec { #[inline] diff --git a/library/core/src/iter/sources/repeat_with.rs b/library/core/src/iter/sources/repeat_with.rs index 3f34105a3e07..d3cd74a44837 100644 --- a/library/core/src/iter/sources/repeat_with.rs +++ b/library/core/src/iter/sources/repeat_with.rs @@ -19,7 +19,6 @@ use crate::ops::Try; /// please open a GitHub issue explaining your use case. /// /// [`repeat()`]: crate::iter::repeat -/// [`DoubleEndedIterator`]: crate::iter::DoubleEndedIterator /// /// # Examples /// diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index f3d1e45f4fb6..02877604248d 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -764,7 +764,6 @@ pub trait Iterator { /// more idiomatic to use [`for`] than `map()`. /// /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for - /// [`FnMut`]: crate::ops::FnMut /// /// # Examples /// diff --git a/library/core/src/net/parser.rs b/library/core/src/net/parser.rs index a08d2792d045..b9a1924d6689 100644 --- a/library/core/src/net/parser.rs +++ b/library/core/src/net/parser.rs @@ -9,7 +9,7 @@ use crate::fmt; use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; use crate::str::FromStr; -trait ReadNumberHelper: crate::marker::Sized { +trait ReadNumberHelper: Sized { const ZERO: Self; fn checked_mul(&self, other: u32) -> Option; fn checked_add(&self, other: u32) -> Option; diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index 51e6947a9c25..3df990e5dd9f 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -577,7 +577,6 @@ impl Copy for () { /// [`is_null`]: pointer::is_null /// [`offset`]: pointer::offset #[doc = concat!("[`into_raw`]: ", include_str!("../primitive_docs/box_into_raw.md"))] -/// [`drop`]: mem::drop /// [`write`]: ptr::write #[stable(feature = "rust1", since = "1.0.0")] mod prim_pointer {} @@ -1026,7 +1025,6 @@ mod prim_str {} /// * [`UnwindSafe`] /// * [`RefUnwindSafe`] /// -/// [`Unpin`]: marker::Unpin /// [`UnwindSafe`]: panic::UnwindSafe /// [`RefUnwindSafe`]: panic::RefUnwindSafe /// @@ -1405,10 +1403,6 @@ mod prim_ref {} /// /// *See also the traits [`Fn`], [`FnMut`], and [`FnOnce`].* /// -/// [`Fn`]: ops::Fn -/// [`FnMut`]: ops::FnMut -/// [`FnOnce`]: ops::FnOnce -/// /// Function pointers are pointers that point to *code*, not data. They can be called /// just like functions. Like references, function pointers are, among other things, assumed to /// not be null, so if you want to pass a function pointer over FFI and be able to accommodate null diff --git a/library/core/src/sync/exclusive.rs b/library/core/src/sync/exclusive.rs index 301ad41c9663..3f3e19c55d4b 100644 --- a/library/core/src/sync/exclusive.rs +++ b/library/core/src/sync/exclusive.rs @@ -69,9 +69,6 @@ use core::task::{Context, Poll}; /// for any value. This is a parallel with the fact that /// `&` and `&mut` references together can be thought of as a _compile-time_ /// version of a read-write lock. -/// -/// -/// [`Sync`]: core::marker::Sync #[unstable(feature = "exclusive_wrapper", issue = "98407")] #[doc(alias = "SyncWrapper")] #[doc(alias = "SyncCell")] diff --git a/library/portable-simd/crates/core_simd/src/masks/full_masks.rs b/library/portable-simd/crates/core_simd/src/masks/full_masks.rs index adf0fcbeae2b..b5ba198e5041 100644 --- a/library/portable-simd/crates/core_simd/src/masks/full_masks.rs +++ b/library/portable-simd/crates/core_simd/src/masks/full_masks.rs @@ -257,7 +257,7 @@ where } } -impl core::convert::From> for Simd +impl From> for Simd where T: MaskElement, LaneCount: SupportedLaneCount, diff --git a/library/proc_macro/src/bridge/fxhash.rs b/library/proc_macro/src/bridge/fxhash.rs index 17bd0a1b3364..f4e905441972 100644 --- a/library/proc_macro/src/bridge/fxhash.rs +++ b/library/proc_macro/src/bridge/fxhash.rs @@ -5,8 +5,6 @@ //! on the `rustc_hash` crate. use std::collections::HashMap; -use std::convert::TryInto; -use std::default::Default; use std::hash::BuildHasherDefault; use std::hash::Hasher; use std::mem::size_of; diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index 938935771d64..9d081c8b842d 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -47,7 +47,7 @@ use std::cmp::Ordering; use std::ops::RangeBounds; use std::path::PathBuf; use std::str::FromStr; -use std::{error, fmt, iter}; +use std::{error, fmt}; /// Determines whether proc_macro has been made accessible to the currently /// running program. @@ -310,7 +310,7 @@ impl ConcatStreamsHelper { /// Collects a number of token trees into a single stream. #[stable(feature = "proc_macro_lib2", since = "1.29.0")] -impl iter::FromIterator for TokenStream { +impl FromIterator for TokenStream { fn from_iter>(trees: I) -> Self { let iter = trees.into_iter(); let mut builder = ConcatTreesHelper::new(iter.size_hint().0); @@ -322,7 +322,7 @@ impl iter::FromIterator for TokenStream { /// A "flattening" operation on token streams, collects token trees /// from multiple token streams into a single stream. #[stable(feature = "proc_macro_lib", since = "1.15.0")] -impl iter::FromIterator for TokenStream { +impl FromIterator for TokenStream { fn from_iter>(streams: I) -> Self { let iter = streams.into_iter(); let mut builder = ConcatStreamsHelper::new(iter.size_hint().0); diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index 742c4cc7c553..3afc8287ecc0 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -1446,7 +1446,6 @@ impl<'a, K, V> IterMut<'a, K, V> { /// (provided by the [`IntoIterator`] trait). See its documentation for more. /// /// [`into_iter`]: IntoIterator::into_iter -/// [`IntoIterator`]: crate::iter::IntoIterator /// /// # Example /// diff --git a/library/std/src/collections/hash/set.rs b/library/std/src/collections/hash/set.rs index 837a18bff608..ac906e682d5f 100644 --- a/library/std/src/collections/hash/set.rs +++ b/library/std/src/collections/hash/set.rs @@ -1272,7 +1272,6 @@ pub struct Iter<'a, K: 'a> { /// (provided by the [`IntoIterator`] trait). See its documentation for more. /// /// [`into_iter`]: IntoIterator::into_iter -/// [`IntoIterator`]: crate::iter::IntoIterator /// /// # Examples /// diff --git a/library/std/src/collections/mod.rs b/library/std/src/collections/mod.rs index 575f56ff4df2..49d3b7a1f614 100644 --- a/library/std/src/collections/mod.rs +++ b/library/std/src/collections/mod.rs @@ -395,8 +395,6 @@ //! // ...but the key hasn't changed. b is still "baz", not "xyz". //! assert_eq!(map.keys().next().unwrap().b, "baz"); //! ``` -//! -//! [IntoIterator]: crate::iter::IntoIterator "iter::IntoIterator" #![stable(feature = "rust1", since = "1.0.0")] diff --git a/library/std/src/ffi/os_str.rs b/library/std/src/ffi/os_str.rs index 80ed34157e6d..5c0541d3caf3 100644 --- a/library/std/src/ffi/os_str.rs +++ b/library/std/src/ffi/os_str.rs @@ -6,7 +6,6 @@ use crate::cmp; use crate::collections::TryReserveError; use crate::fmt; use crate::hash::{Hash, Hasher}; -use crate::iter::Extend; use crate::ops; use crate::rc::Rc; use crate::str::FromStr; diff --git a/library/std/src/io/error.rs b/library/std/src/io/error.rs index 1cedd6eedfaf..34c0ce9dcf84 100644 --- a/library/std/src/io/error.rs +++ b/library/std/src/io/error.rs @@ -11,7 +11,6 @@ mod repr_unpacked; #[cfg(not(target_pointer_width = "64"))] use repr_unpacked::Repr; -use crate::convert::From; use crate::error; use crate::fmt; use crate::result; diff --git a/library/std/src/keyword_docs.rs b/library/std/src/keyword_docs.rs index 203c490fa29a..43842bee992a 100644 --- a/library/std/src/keyword_docs.rs +++ b/library/std/src/keyword_docs.rs @@ -1678,7 +1678,7 @@ mod super_keyword {} /// below `Iterator` is a **supertrait** and `ThreeIterator` is a **subtrait**: /// /// ```rust -/// trait ThreeIterator: std::iter::Iterator { +/// trait ThreeIterator: Iterator { /// fn next_three(&mut self) -> Option<[Self::Item; 3]>; /// } /// ``` diff --git a/library/std/src/path.rs b/library/std/src/path.rs index dbc18f7827e6..8014ba992eaf 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -78,7 +78,7 @@ use crate::fmt; use crate::fs; use crate::hash::{Hash, Hasher}; use crate::io; -use crate::iter::{self, FusedIterator}; +use crate::iter::FusedIterator; use crate::ops::{self, Deref}; use crate::rc::Rc; use crate::str::FromStr; @@ -450,26 +450,26 @@ impl<'a> PrefixComponent<'a> { } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a> cmp::PartialEq for PrefixComponent<'a> { +impl<'a> PartialEq for PrefixComponent<'a> { #[inline] fn eq(&self, other: &PrefixComponent<'a>) -> bool { - cmp::PartialEq::eq(&self.parsed, &other.parsed) + self.parsed == other.parsed } } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a> cmp::PartialOrd for PrefixComponent<'a> { +impl<'a> PartialOrd for PrefixComponent<'a> { #[inline] fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option { - cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed) + PartialOrd::partial_cmp(&self.parsed, &other.parsed) } } #[stable(feature = "rust1", since = "1.0.0")] -impl cmp::Ord for PrefixComponent<'_> { +impl Ord for PrefixComponent<'_> { #[inline] fn cmp(&self, other: &Self) -> cmp::Ordering { - cmp::Ord::cmp(&self.parsed, &other.parsed) + Ord::cmp(&self.parsed, &other.parsed) } } @@ -988,7 +988,7 @@ impl<'a> DoubleEndedIterator for Components<'a> { impl FusedIterator for Components<'_> {} #[stable(feature = "rust1", since = "1.0.0")] -impl<'a> cmp::PartialEq for Components<'a> { +impl<'a> PartialEq for Components<'a> { #[inline] fn eq(&self, other: &Components<'a>) -> bool { let Components { path: _, front: _, back: _, has_physical_root: _, prefix: _ } = self; @@ -1015,10 +1015,10 @@ impl<'a> cmp::PartialEq for Components<'a> { } #[stable(feature = "rust1", since = "1.0.0")] -impl cmp::Eq for Components<'_> {} +impl Eq for Components<'_> {} #[stable(feature = "rust1", since = "1.0.0")] -impl<'a> cmp::PartialOrd for Components<'a> { +impl<'a> PartialOrd for Components<'a> { #[inline] fn partial_cmp(&self, other: &Components<'a>) -> Option { Some(compare_components(self.clone(), other.clone())) @@ -1026,7 +1026,7 @@ impl<'a> cmp::PartialOrd for Components<'a> { } #[stable(feature = "rust1", since = "1.0.0")] -impl cmp::Ord for Components<'_> { +impl Ord for Components<'_> { #[inline] fn cmp(&self, other: &Self) -> cmp::Ordering { compare_components(self.clone(), other.clone()) @@ -1741,7 +1741,7 @@ impl FromStr for PathBuf { } #[stable(feature = "rust1", since = "1.0.0")] -impl> iter::FromIterator

for PathBuf { +impl> FromIterator

for PathBuf { fn from_iter>(iter: I) -> PathBuf { let mut buf = PathBuf::new(); buf.extend(iter); @@ -1750,7 +1750,7 @@ impl> iter::FromIterator

for PathBuf { } #[stable(feature = "rust1", since = "1.0.0")] -impl> iter::Extend

for PathBuf { +impl> Extend

for PathBuf { fn extend>(&mut self, iter: I) { iter.into_iter().for_each(move |p| self.push(p.as_ref())); } @@ -1904,7 +1904,7 @@ impl ToOwned for Path { } #[stable(feature = "rust1", since = "1.0.0")] -impl cmp::PartialEq for PathBuf { +impl PartialEq for PathBuf { #[inline] fn eq(&self, other: &PathBuf) -> bool { self.components() == other.components() @@ -1919,10 +1919,10 @@ impl Hash for PathBuf { } #[stable(feature = "rust1", since = "1.0.0")] -impl cmp::Eq for PathBuf {} +impl Eq for PathBuf {} #[stable(feature = "rust1", since = "1.0.0")] -impl cmp::PartialOrd for PathBuf { +impl PartialOrd for PathBuf { #[inline] fn partial_cmp(&self, other: &PathBuf) -> Option { Some(compare_components(self.components(), other.components())) @@ -1930,7 +1930,7 @@ impl cmp::PartialOrd for PathBuf { } #[stable(feature = "rust1", since = "1.0.0")] -impl cmp::Ord for PathBuf { +impl Ord for PathBuf { #[inline] fn cmp(&self, other: &PathBuf) -> cmp::Ordering { compare_components(self.components(), other.components()) @@ -3025,7 +3025,7 @@ impl fmt::Display for Display<'_> { } #[stable(feature = "rust1", since = "1.0.0")] -impl cmp::PartialEq for Path { +impl PartialEq for Path { #[inline] fn eq(&self, other: &Path) -> bool { self.components() == other.components() @@ -3084,10 +3084,10 @@ impl Hash for Path { } #[stable(feature = "rust1", since = "1.0.0")] -impl cmp::Eq for Path {} +impl Eq for Path {} #[stable(feature = "rust1", since = "1.0.0")] -impl cmp::PartialOrd for Path { +impl PartialOrd for Path { #[inline] fn partial_cmp(&self, other: &Path) -> Option { Some(compare_components(self.components(), other.components())) @@ -3095,7 +3095,7 @@ impl cmp::PartialOrd for Path { } #[stable(feature = "rust1", since = "1.0.0")] -impl cmp::Ord for Path { +impl Ord for Path { #[inline] fn cmp(&self, other: &Path) -> cmp::Ordering { compare_components(self.components(), other.components()) diff --git a/library/std/src/prelude/mod.rs b/library/std/src/prelude/mod.rs index c314bbbb68e5..1b29c887d210 100644 --- a/library/std/src/prelude/mod.rs +++ b/library/std/src/prelude/mod.rs @@ -34,7 +34,7 @@ //! marker traits that indicate fundamental properties of types. //! * [std::ops]::{[Drop], [Fn], [FnMut], [FnOnce]}, various //! operations for both destructors and overloading `()`. -//! * [std::mem]::[drop][mem::drop], a convenience function for explicitly +//! * [std::mem]::[drop], a convenience function for explicitly //! dropping a value. //! * [std::boxed]::[Box], a way to allocate values on the heap. //! * [std::borrow]::[ToOwned], the conversion trait that defines @@ -66,7 +66,6 @@ //! * [std::convert]::{[TryFrom], [TryInto]}, //! * [std::iter]::[FromIterator]. //! -//! [mem::drop]: crate::mem::drop //! [std::borrow]: crate::borrow //! [std::boxed]: crate::boxed //! [std::clone]: crate::clone @@ -86,9 +85,6 @@ //! [std::slice]: crate::slice //! [std::string]: crate::string //! [std::vec]: mod@crate::vec -//! [TryFrom]: crate::convert::TryFrom -//! [TryInto]: crate::convert::TryInto -//! [FromIterator]: crate::iter::FromIterator //! [`to_owned`]: crate::borrow::ToOwned::to_owned //! [book-closures]: ../../book/ch13-01-closures.html //! [book-dtor]: ../../book/ch15-03-drop.html diff --git a/library/std/src/primitive_docs.rs b/library/std/src/primitive_docs.rs index 51e6947a9c25..3df990e5dd9f 100644 --- a/library/std/src/primitive_docs.rs +++ b/library/std/src/primitive_docs.rs @@ -577,7 +577,6 @@ impl Copy for () { /// [`is_null`]: pointer::is_null /// [`offset`]: pointer::offset #[doc = concat!("[`into_raw`]: ", include_str!("../primitive_docs/box_into_raw.md"))] -/// [`drop`]: mem::drop /// [`write`]: ptr::write #[stable(feature = "rust1", since = "1.0.0")] mod prim_pointer {} @@ -1026,7 +1025,6 @@ mod prim_str {} /// * [`UnwindSafe`] /// * [`RefUnwindSafe`] /// -/// [`Unpin`]: marker::Unpin /// [`UnwindSafe`]: panic::UnwindSafe /// [`RefUnwindSafe`]: panic::RefUnwindSafe /// @@ -1405,10 +1403,6 @@ mod prim_ref {} /// /// *See also the traits [`Fn`], [`FnMut`], and [`FnOnce`].* /// -/// [`Fn`]: ops::Fn -/// [`FnMut`]: ops::FnMut -/// [`FnOnce`]: ops::FnOnce -/// /// Function pointers are pointers that point to *code*, not data. They can be called /// just like functions. Like references, function pointers are, among other things, assumed to /// not be null, so if you want to pass a function pointer over FFI and be able to accommodate null diff --git a/library/std/src/sys/sgx/abi/usercalls/alloc.rs b/library/std/src/sys/sgx/abi/usercalls/alloc.rs index 0d934318c22a..01505e94487b 100644 --- a/library/std/src/sys/sgx/abi/usercalls/alloc.rs +++ b/library/std/src/sys/sgx/abi/usercalls/alloc.rs @@ -3,7 +3,6 @@ use crate::arch::asm; use crate::cell::UnsafeCell; use crate::cmp; -use crate::convert::TryInto; use crate::mem; use crate::ops::{CoerceUnsized, Deref, DerefMut, Index, IndexMut}; use crate::ptr::{self, NonNull}; diff --git a/library/std/src/sys/unix/futex.rs b/library/std/src/sys/unix/futex.rs index 8d5b540212a1..d310be6c7a1e 100644 --- a/library/std/src/sys/unix/futex.rs +++ b/library/std/src/sys/unix/futex.rs @@ -273,8 +273,6 @@ pub mod zircon { #[cfg(target_os = "fuchsia")] pub fn futex_wait(futex: &AtomicU32, expected: u32, timeout: Option) -> bool { - use crate::convert::TryFrom; - // Sleep forever if the timeout is longer than fits in a i64. let deadline = timeout .and_then(|d| { diff --git a/library/std/src/sys/unix/os.rs b/library/std/src/sys/unix/os.rs index 1c44058aff79..a345af76fa21 100644 --- a/library/std/src/sys/unix/os.rs +++ b/library/std/src/sys/unix/os.rs @@ -7,7 +7,6 @@ mod tests; use crate::os::unix::prelude::*; -use crate::convert::TryFrom; use crate::error::Error as StdError; use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; diff --git a/library/std/src/sys/unix/process/process_fuchsia.rs b/library/std/src/sys/unix/process/process_fuchsia.rs index d4c7e58b34d2..e45c380a0bb8 100644 --- a/library/std/src/sys/unix/process/process_fuchsia.rs +++ b/library/std/src/sys/unix/process/process_fuchsia.rs @@ -166,7 +166,6 @@ impl Process { } pub fn wait(&mut self) -> io::Result { - use crate::default::Default; use crate::sys::process::zircon::*; let mut proc_info: zx_info_process_t = Default::default(); @@ -199,7 +198,6 @@ impl Process { } pub fn try_wait(&mut self) -> io::Result> { - use crate::default::Default; use crate::sys::process::zircon::*; let mut proc_info: zx_info_process_t = Default::default(); diff --git a/library/std/src/sys_common/net.rs b/library/std/src/sys_common/net.rs index eb427dbda239..cb24caa1e8a6 100644 --- a/library/std/src/sys_common/net.rs +++ b/library/std/src/sys_common/net.rs @@ -2,7 +2,6 @@ mod tests; use crate::cmp; -use crate::convert::{TryFrom, TryInto}; use crate::fmt; use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}; use crate::mem; diff --git a/src/bootstrap/cache.rs b/src/bootstrap/cache.rs index 05f25af68ea8..5376c4ec9c32 100644 --- a/src/bootstrap/cache.rs +++ b/src/bootstrap/cache.rs @@ -1,9 +1,8 @@ use std::any::{Any, TypeId}; use std::borrow::Borrow; use std::cell::RefCell; -use std::cmp::{Ord, Ordering, PartialOrd}; +use std::cmp::Ordering; use std::collections::HashMap; -use std::convert::AsRef; use std::fmt; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index b3df12a9df13..02cec16b35c4 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -35,7 +35,6 @@ use rustc_span::{self, ExpnKind}; use std::borrow::Cow; use std::collections::hash_map::Entry; use std::collections::BTreeMap; -use std::default::Default; use std::hash::Hash; use std::mem; use thin_vec::ThinVec; diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index e34ece9264cf..6d2ce9e2833f 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -1,6 +1,5 @@ use std::borrow::Cow; use std::cell::RefCell; -use std::default::Default; use std::hash::Hash; use std::path::PathBuf; use std::rc::Rc; @@ -980,7 +979,7 @@ pub(crate) trait NestedAttributesExt { /// Returns `true` if the attribute list contains a specific `word` fn has_word(self, word: Symbol) -> bool where - Self: std::marker::Sized, + Self: Sized, { ::get_word_attr(self, word).is_some() } diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index c848089dad6b..b97bb190dd8c 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -1,5 +1,4 @@ use std::collections::BTreeMap; -use std::convert::TryFrom; use std::ffi::OsStr; use std::fmt; use std::path::PathBuf; diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index fd81a21f5a99..00aadb8e82ae 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -36,7 +36,6 @@ use rustc_span::{Span, Symbol}; use once_cell::sync::Lazy; use std::borrow::Cow; use std::collections::VecDeque; -use std::default::Default; use std::fmt::Write; use std::ops::{ControlFlow, Range}; use std::str; diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 1e3cd2668506..463184acaa14 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -38,7 +38,6 @@ pub(crate) use self::context::*; pub(crate) use self::span_map::{collect_spans_and_sources, LinkFromSrc}; use std::collections::VecDeque; -use std::default::Default; use std::fmt::{self, Write}; use std::fs; use std::iter::Peekable; diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index 08a0e1c377ef..f5b4a3f5abd6 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -59,7 +59,7 @@ pub(crate) fn build_index<'tcx>( // `sort_unstable_by_key` produces lifetime errors let k1 = (&k1.path, k1.name.as_str(), &k1.ty, &k1.parent); let k2 = (&k2.path, k2.name.as_str(), &k2.ty, &k2.parent); - std::cmp::Ord::cmp(&k1, &k2) + Ord::cmp(&k1, &k2) }); // Set up alias indexes. diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index c39caf73a936..cd6509607d56 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -4,7 +4,6 @@ #![allow(rustc::default_hash_types)] -use std::convert::From; use std::fmt; use rustc_ast::ast; diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 79f53ee57cc9..9fd130c4717b 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -69,7 +69,6 @@ extern crate test; #[cfg(feature = "jemalloc")] extern crate jemalloc_sys; -use std::default::Default; use std::env::{self, VarError}; use std::io::{self, IsTerminal}; use std::process; diff --git a/src/tools/bump-stage0/src/main.rs b/src/tools/bump-stage0/src/main.rs index f530a4d73d36..b007f9a22c36 100644 --- a/src/tools/bump-stage0/src/main.rs +++ b/src/tools/bump-stage0/src/main.rs @@ -2,7 +2,6 @@ use anyhow::{Context, Error}; use curl::easy::Easy; use indexmap::IndexMap; use std::collections::HashMap; -use std::convert::TryInto; const PATH: &str = "src/stage0.json"; const COMPILER_COMPONENTS: &[&str] = &["rustc", "rust-std", "cargo"]; diff --git a/src/tools/tidy/src/bins.rs b/src/tools/tidy/src/bins.rs index 7e5b4d810ba9..197e9a9965f7 100644 --- a/src/tools/tidy/src/bins.rs +++ b/src/tools/tidy/src/bins.rs @@ -57,8 +57,8 @@ mod os_impl { match fs::File::create(&path) { Ok(file) => { let exec = is_executable(&path).unwrap_or(false); - std::mem::drop(file); - std::fs::remove_file(&path).expect("Deleted temp file"); + drop(file); + fs::remove_file(&path).expect("Deleted temp file"); // If the file is executable, then we assume that this // filesystem does not track executability, so skip this check. return if exec { Unsupported } else { Supported }; diff --git a/src/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index d40c4ad0711c..6fd41e833624 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -31,7 +31,6 @@ //! this in the long term. use crate::walk::{filter_dirs, walk}; -use std::iter::Iterator; use std::path::Path; // Paths that may contain platform-specific code. diff --git a/src/tools/unicode-table-generator/src/raw_emitter.rs b/src/tools/unicode-table-generator/src/raw_emitter.rs index 890ff986c2be..7547b49ab2a5 100644 --- a/src/tools/unicode-table-generator/src/raw_emitter.rs +++ b/src/tools/unicode-table-generator/src/raw_emitter.rs @@ -1,6 +1,5 @@ use crate::fmt_list; use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::convert::TryFrom; use std::fmt::{self, Write}; use std::ops::Range; diff --git a/src/tools/unicode-table-generator/src/skiplist.rs b/src/tools/unicode-table-generator/src/skiplist.rs index 6e439968c3bf..9b613a94c579 100644 --- a/src/tools/unicode-table-generator/src/skiplist.rs +++ b/src/tools/unicode-table-generator/src/skiplist.rs @@ -1,6 +1,5 @@ use crate::fmt_list; use crate::raw_emitter::RawEmitter; -use std::convert::TryInto; use std::fmt::Write as _; use std::ops::Range; diff --git a/tests/ui/hygiene/panic-location.run.stderr b/tests/ui/hygiene/panic-location.run.stderr index 1c6a7b02f8e7..a7252a400277 100644 --- a/tests/ui/hygiene/panic-location.run.stderr +++ b/tests/ui/hygiene/panic-location.run.stderr @@ -1,2 +1,2 @@ -thread 'main' panicked at 'capacity overflow', library/alloc/src/raw_vec.rs:525:5 +thread 'main' panicked at 'capacity overflow', library/alloc/src/raw_vec.rs:524:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace From f9f25162bf62ef6325443168e4200236729c2234 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Wed, 12 Apr 2023 14:36:10 -0700 Subject: [PATCH 026/116] Apply suggestions from code review Co-authored-by: Eric Huss --- RELEASES.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index 18b673949b0a..3298e43d89e3 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -85,10 +85,10 @@ Compatibility Notes - [The `rust-analysis` component from `rustup` now only contains a warning placeholder.](https://github.com/rust-lang/rust/pull/101841/) This was primarily intended for RLS, and the corresponding `-Zsave-analysis` flag has been removed from the compiler as well. - [Unaligned references to packed fields are now a hard error.](https://github.com/rust-lang/rust/pull/102513/) This has been a warning since 1.53, and denied by default with a future-compatibility warning since 1.62. - [Update the minimum external LLVM to 14.](https://github.com/rust-lang/rust/pull/107573/) -- [Cargo now emits errors on invalid alphanumeric token for crates.io.](https://github.com/rust-lang/cargo/pull/11600/) +- [Cargo now emits errors on invalid characters in a registry token.](https://github.com/rust-lang/cargo/pull/11600/) - [When `default-features` is set to false of a workspace dependency, and an inherited dependency of a member has `default-features = true`, Cargo will enable default features of that dependency.](https://github.com/rust-lang/cargo/pull/11409/) -- [Cargo denies `CARGO_HOME` in the `[env]` configuration table. Cargo itself doesn't pick up this value, but recursive calls to cargo will.](https://github.com/rust-lang/cargo/pull/11644/) -- [Debuginfo for build dependencies is now off if not explicit set. This is expected to boost the overall build time.](https://github.com/rust-lang/cargo/pull/11252/) +- [Cargo denies `CARGO_HOME` in the `[env]` configuration table. Cargo itself doesn't pick up this value, but recursive calls to cargo would, which was not intended.](https://github.com/rust-lang/cargo/pull/11644/) +- [Debuginfo for build dependencies is now off if not explicitly set. This is expected to improve the overall build time.](https://github.com/rust-lang/cargo/pull/11252/) From c9358e9a0051286fc5f33ed4d2f9aa013cafdd57 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Wed, 12 Apr 2023 14:36:43 -0700 Subject: [PATCH 027/116] Apply suggestions from code review Co-authored-by: est31 --- RELEASES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index 3298e43d89e3..db9e19a9814d 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -64,7 +64,7 @@ Cargo - [Added '-C' flag for changing current dir before build](https://github.com/rust-lang/cargo/pull/10952/) - [Cargo now suggests `cargo fix` or `cargo clippy --fix` when compilation warnings are auto-fixable.](https://github.com/rust-lang/cargo/pull/11558/) - [Cargo now suggests `cargo add` if you try to install a library crate.](https://github.com/rust-lang/cargo/pull/11410/) -- [Cargo now sets `CARGO_BIN_NAME` environment variable also for binary examples.](https://github.com/rust-lang/cargo/pull/11705/) +- [Cargo now sets the `CARGO_BIN_NAME` environment variable also for binary examples.](https://github.com/rust-lang/cargo/pull/11705/) From ae60b362d949848ee1e7adc85a5973717af24fe8 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Wed, 12 Apr 2023 14:42:39 -0700 Subject: [PATCH 028/116] Cargo '-C' was reverted Co-authored-by: Eric Huss --- RELEASES.md | 1 - 1 file changed, 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index db9e19a9814d..802637652832 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -61,7 +61,6 @@ These APIs are now stable in const contexts: Cargo ----- -- [Added '-C' flag for changing current dir before build](https://github.com/rust-lang/cargo/pull/10952/) - [Cargo now suggests `cargo fix` or `cargo clippy --fix` when compilation warnings are auto-fixable.](https://github.com/rust-lang/cargo/pull/11558/) - [Cargo now suggests `cargo add` if you try to install a library crate.](https://github.com/rust-lang/cargo/pull/11410/) - [Cargo now sets the `CARGO_BIN_NAME` environment variable also for binary examples.](https://github.com/rust-lang/cargo/pull/11705/) From 42c4373ad11a86d3028ddfe29d7f33edc9670ba8 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 2 Mar 2023 22:55:37 +0000 Subject: [PATCH 029/116] Make note_source_of_type_mismatch_constraint simpler --- compiler/rustc_hir_typeck/src/demand.rs | 274 +++++------------- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 22 +- .../type/type-check/assignment-in-if.stderr | 9 - .../type-check/point-at-inference-3.fixed | 1 - .../type/type-check/point-at-inference-3.rs | 1 - .../type-check/point-at-inference-3.stderr | 5 +- .../type/type-check/point-at-inference-4.rs | 1 + .../type-check/point-at-inference-4.stderr | 5 +- .../type/type-check/point-at-inference.fixed | 2 +- .../type/type-check/point-at-inference.stderr | 6 +- .../ui/typeck/bad-type-in-vec-contains.stderr | 1 - tests/ui/typeck/bad-type-in-vec-push.stderr | 2 - tests/ui/typeck/issue-107775.stderr | 4 +- 13 files changed, 93 insertions(+), 240 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index a4c3be1d1774..0c4f73e0db0e 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -1,6 +1,5 @@ use crate::FnCtxt; use rustc_ast::util::parser::PREC_POSTFIX; -use rustc_data_structures::fx::FxHashMap; use rustc_errors::MultiSpan; use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed}; use rustc_hir as hir; @@ -13,15 +12,13 @@ use rustc_middle::lint::in_external_macro; use rustc_middle::middle::stability::EvalResult; use rustc_middle::ty::adjustment::AllowTwoPhase; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::fold::{BottomUpFolder, TypeFolder}; -use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths}; -use rustc_middle::ty::relate::TypeRelation; -use rustc_middle::ty::{self, Article, AssocItem, Ty, TypeAndMut, TypeVisitableExt}; +use rustc_middle::ty::fold::BottomUpFolder; +use rustc_middle::ty::print::with_no_trimmed_paths; +use rustc_middle::ty::{self, Article, AssocItem, Ty, TypeAndMut, TypeFoldable}; use rustc_span::symbol::{sym, Symbol}; -use rustc_span::{BytePos, Span}; +use rustc_span::{BytePos, Span, DUMMY_SP}; use rustc_target::abi::FieldIdx; use rustc_trait_selection::infer::InferCtxtExt as _; -use rustc_trait_selection::traits::error_reporting::method_chain::CollectAllMismatches; use rustc_trait_selection::traits::ObligationCause; use super::method::probe; @@ -62,9 +59,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { || self.suggest_into(err, expr, expr_ty, expected) || self.suggest_floating_point_literal(err, expr, expected) || self.suggest_null_ptr_for_literal_zero_given_to_ptr_arg(err, expr, expected) - || self.note_result_coercion(err, expr, expected, expr_ty); + || self.suggest_coercing_result_via_try_operator(err, expr, expected, expr_ty); + if !suggested { - self.point_at_expr_source_of_inferred_type(err, expr, expr_ty, expected, expr.span); + self.note_source_of_type_mismatch_constraint(err, expr, expected); } } @@ -218,37 +216,34 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (expected, Some(err)) } - pub fn point_at_expr_source_of_inferred_type( + /// Notes the point at which a variable is constrained to some type incompatible + /// with `expected_ty`. + pub fn note_source_of_type_mismatch_constraint( &self, err: &mut Diagnostic, expr: &hir::Expr<'_>, - found: Ty<'tcx>, - expected: Ty<'tcx>, - mismatch_span: Span, + expected_ty: Ty<'tcx>, ) -> bool { - let map = self.tcx.hir(); + let hir = self.tcx.hir(); let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind else { return false; }; let [hir::PathSegment { ident, args: None, .. }] = p.segments else { return false; }; - let hir::def::Res::Local(hir_id) = p.res else { return false; }; - let Some(hir::Node::Pat(pat)) = map.find(hir_id) else { return false; }; - let Some(hir::Node::Local(hir::Local { - ty: None, - init: Some(init), - .. - })) = map.find_parent(pat.hir_id) else { return false; }; - let Some(ty) = self.node_ty_opt(init.hir_id) else { return false; }; - if ty.is_closure() || init.span.overlaps(expr.span) || pat.span.from_expansion() { - return false; - } + let hir::def::Res::Local(local_hir_id) = p.res else { return false; }; + let hir::Node::Pat(pat) = hir.get(local_hir_id) else { return false; }; + let (init_ty_hir_id, init) = match hir.get_parent(pat.hir_id) { + hir::Node::Local(hir::Local { ty: Some(ty), init, .. }) => (ty.hir_id, *init), + hir::Node::Local(hir::Local { init: Some(init), .. }) => (init.hir_id, Some(*init)), + _ => return false, + }; + let Some(init_ty) = self.node_ty_opt(init_ty_hir_id) else { return false; }; // Locate all the usages of the relevant binding. - struct FindExprs<'hir> { + struct FindExprs<'tcx> { hir_id: hir::HirId, - uses: Vec<&'hir hir::Expr<'hir>>, + uses: Vec<&'tcx hir::Expr<'tcx>>, } - impl<'v> Visitor<'v> for FindExprs<'v> { - fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) { + impl<'tcx> Visitor<'tcx> for FindExprs<'tcx> { + fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = ex.kind && let hir::def::Res::Local(hir_id) = path.res && hir_id == self.hir_id @@ -259,180 +254,71 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - let mut expr_finder = FindExprs { hir_id, uses: vec![] }; - let id = map.get_parent_item(hir_id); - let hir_id: hir::HirId = id.into(); - - let Some(node) = map.find(hir_id) else { return false; }; - let Some(body_id) = node.body_id() else { return false; }; - let body = map.body(body_id); + let mut expr_finder = FindExprs { hir_id: local_hir_id, uses: init.into_iter().collect() }; + let body = + hir.body(hir.maybe_body_owned_by(self.body_id).expect("expected item to have body")); expr_finder.visit_expr(body.value); - // Hack to make equality checks on types with inference variables and regions useful. - let mut eraser = BottomUpFolder { - tcx: self.tcx, - lt_op: |_| self.tcx.lifetimes.re_erased, - ct_op: |c| c, - ty_op: |t| match *t.kind() { - ty::Infer(ty::TyVar(_)) => self.tcx.mk_ty_var(ty::TyVid::from_u32(0)), - ty::Infer(ty::IntVar(_)) => self.tcx.mk_int_var(ty::IntVid { index: 0 }), - ty::Infer(ty::FloatVar(_)) => self.tcx.mk_float_var(ty::FloatVid { index: 0 }), - _ => t, - }, - }; - let mut prev = eraser.fold_ty(ty); - let mut prev_span: Option = None; - for binding in expr_finder.uses { - // In every expression where the binding is referenced, we will look at that - // expression's type and see if it is where the incorrect found type was fully - // "materialized" and point at it. We will also try to provide a suggestion there. - if let Some(hir::Node::Expr(expr) - | hir::Node::Stmt(hir::Stmt { - kind: hir::StmtKind::Expr(expr) | hir::StmtKind::Semi(expr), - .. - })) = &map.find_parent(binding.hir_id) - && let hir::ExprKind::MethodCall(segment, rcvr, args, _span) = expr.kind - && rcvr.hir_id == binding.hir_id - && let Some(def_id) = self.typeck_results.borrow().type_dependent_def_id(expr.hir_id) - { - // We special case methods, because they can influence inference through the - // call's arguments and we can provide a more explicit span. - let sig = self.tcx.fn_sig(def_id).subst_identity(); - let def_self_ty = sig.input(0).skip_binder(); - let param_tys = sig.inputs().skip_binder().iter().skip(1); - // If there's an arity mismatch, pointing out the call as the source of an inference - // can be misleading, so we skip it. - if param_tys.len() != args.len() { - continue; - } - let rcvr_ty = self.node_ty(rcvr.hir_id); - // Get the evaluated type *after* calling the method call, so that the influence - // of the arguments can be reflected in the receiver type. The receiver - // expression has the type *before* this analysis is done. - let ty = match self.lookup_probe_for_diagnostic( - segment.ident, - rcvr_ty, - expr, - probe::ProbeScope::TraitsInScope, - None, - ) { - Ok(pick) => eraser.fold_ty(pick.self_ty), - Err(_) => rcvr_ty, - }; - // Remove one layer of references to account for `&mut self` and - // `&self`, so that we can compare it against the binding. - let (ty, def_self_ty) = match (ty.kind(), def_self_ty.kind()) { - (ty::Ref(_, ty, a), ty::Ref(_, self_ty, b)) if a == b => (*ty, *self_ty), - _ => (ty, def_self_ty), - }; - let mut param_args = FxHashMap::default(); - let mut param_expected = FxHashMap::default(); - let mut param_found = FxHashMap::default(); - if self.can_eq(self.param_env, ty, found) { - // We only point at the first place where the found type was inferred. - for (param_ty, arg) in param_tys.zip(args) { - if def_self_ty.contains(*param_ty) && let ty::Param(_) = param_ty.kind() { - // We found an argument that references a type parameter in `Self`, - // so we assume that this is the argument that caused the found - // type, which we know already because of `can_eq` above was first - // inferred in this method call. - let arg_ty = self.node_ty(arg.hir_id); - if !arg.span.overlaps(mismatch_span) { - err.span_label( - arg.span, - &format!( - "this is of type `{arg_ty}`, which causes `{ident}` to be \ - inferred as `{ty}`", - ), - ); - } - param_args.insert(param_ty, (arg, arg_ty)); + let fudge_equals_found_ty = |use_ty: Ty<'tcx>| { + use rustc_infer::infer::type_variable::*; + use rustc_middle::infer::unify_key::*; + let use_ty = use_ty.fold_with(&mut BottomUpFolder { + tcx: self.tcx, + ty_op: |ty| { + if let ty::Infer(infer) = ty.kind() { + match infer { + ty::InferTy::TyVar(_) => self.next_ty_var(TypeVariableOrigin { + kind: TypeVariableOriginKind::MiscVariable, + span: DUMMY_SP, + }), + ty::InferTy::IntVar(_) => self.next_int_var(), + ty::InferTy::FloatVar(_) => self.next_float_var(), + _ => bug!(), } + } else { + ty } - } + }, + lt_op: |_| self.tcx.lifetimes.re_erased, + ct_op: |ct| { + if let ty::ConstKind::Infer(_) = ct.kind() { + self.next_const_var( + ct.ty(), + ConstVariableOrigin { + kind: ConstVariableOriginKind::MiscVariable, + span: DUMMY_SP, + }, + ) + } else { + ct + } + }, + }); + self.can_eq(self.param_env, expected_ty, use_ty) + }; - // Here we find, for a type param `T`, the type that `T` is in the current - // method call *and* in the original expected type. That way, we can see if we - // can give any structured suggestion for the function argument. - let mut c = CollectAllMismatches { - infcx: &self.infcx, - param_env: self.param_env, - errors: vec![], - }; - let _ = c.relate(def_self_ty, ty); - for error in c.errors { - if let TypeError::Sorts(error) = error { - param_found.insert(error.expected, error.found); - } - } - c.errors = vec![]; - let _ = c.relate(def_self_ty, expected); - for error in c.errors { - if let TypeError::Sorts(error) = error { - param_expected.insert(error.expected, error.found); - } - } - for (param, (arg, arg_ty)) in param_args.iter() { - let Some(expected) = param_expected.get(param) else { continue; }; - let Some(found) = param_found.get(param) else { continue; }; - if !self.can_eq(self.param_env, *arg_ty, *found) { continue; } - self.emit_coerce_suggestions(err, arg, *found, *expected, None, None); - } + if !fudge_equals_found_ty(init_ty) { + return false; + } - let ty = eraser.fold_ty(ty); - if ty.references_error() { - break; - } - if ty != prev - && param_args.is_empty() - && self.can_eq(self.param_env, ty, found) - { - // We only point at the first place where the found type was inferred. - if !segment.ident.span.overlaps(mismatch_span) { - err.span_label( - segment.ident.span, - with_forced_trimmed_paths!(format!( - "here the type of `{ident}` is inferred to be `{ty}`", - )), - );} - break; - } else if !param_args.is_empty() { - break; - } - prev = ty; - } else { - let ty = eraser.fold_ty(self.node_ty(binding.hir_id)); - if ty.references_error() { - break; - } - if ty != prev - && let Some(span) = prev_span - && self.can_eq(self.param_env, ty, found) - { - // We only point at the first place where the found type was inferred. - // We use the *previous* span because if the type is known *here* it means - // it was *evaluated earlier*. We don't do this for method calls because we - // evaluate the method's self type eagerly, but not in any other case. - if !span.overlaps(mismatch_span) { - err.span_label( - span, - with_forced_trimmed_paths!(format!( - "here the type of `{ident}` is inferred to be `{ty}`", - )), - ); - } - break; - } - prev = ty; + for window in expr_finder.uses.windows(2) { + let [binding, next_usage] = *window else { continue; }; + let Some(next_use_ty) = self.node_ty_opt(next_usage.hir_id) else { continue; }; + if !fudge_equals_found_ty(next_use_ty) { + err.span_label( + binding.span, + format!("here the type of `{ident}` is inferred to be `{next_use_ty}`"), + ); + return true; } - if binding.hir_id == expr.hir_id { - // Do not look at expressions that come after the expression we were originally - // evaluating and had a type error. + + if next_usage.hir_id == expr.hir_id { break; } - prev_span = Some(binding.span); } - true + + // We must've not found something that constrained the expr. + false } fn annotate_expected_due_to_let_ty( @@ -708,7 +594,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } - pub(crate) fn note_result_coercion( + pub(crate) fn suggest_coercing_result_via_try_operator( &self, err: &mut Diagnostic, expr: &hir::Expr<'tcx>, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index a009ae5d44eb..d98e0d9096f5 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -807,24 +807,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { full_call_span, format!("arguments to this {} are incorrect", call_name), ); - if let (Some(callee_ty), hir::ExprKind::MethodCall(_, rcvr, _, _)) = - (callee_ty, &call_expr.kind) - { - // Type that would have accepted this argument if it hadn't been inferred earlier. - // FIXME: We leave an inference variable for now, but it'd be nice to get a more - // specific type to increase the accuracy of the diagnostic. - let expected = self.infcx.next_ty_var(TypeVariableOrigin { - kind: TypeVariableOriginKind::MiscVariable, - span: full_call_span, - }); - self.point_at_expr_source_of_inferred_type( - &mut err, - rcvr, - expected, - callee_ty, - provided_arg_span, - ); - } + + // TODO: We would like to point out when the rcvr was constrained + // such that the arg mismatch occurs. + // Call out where the function is defined self.label_fn_like( &mut err, diff --git a/tests/ui/type/type-check/assignment-in-if.stderr b/tests/ui/type/type-check/assignment-in-if.stderr index de133e5599cf..9f4558adab15 100644 --- a/tests/ui/type/type-check/assignment-in-if.stderr +++ b/tests/ui/type/type-check/assignment-in-if.stderr @@ -67,9 +67,6 @@ LL | x == 5 error[E0308]: mismatched types --> $DIR/assignment-in-if.rs:44:18 | -LL | if y = (Foo { foo: x }) { - | - here the type of `x` is inferred to be `usize` -... LL | if x == x && x = x && x == x { | ------ ^ expected `bool`, found `usize` | | @@ -78,9 +75,6 @@ LL | if x == x && x = x && x == x { error[E0308]: mismatched types --> $DIR/assignment-in-if.rs:44:22 | -LL | if y = (Foo { foo: x }) { - | - here the type of `x` is inferred to be `usize` -... LL | if x == x && x = x && x == x { | ^ expected `bool`, found `usize` @@ -98,9 +92,6 @@ LL | if x == x && x == x && x == x { error[E0308]: mismatched types --> $DIR/assignment-in-if.rs:51:28 | -LL | if y = (Foo { foo: x }) { - | - here the type of `x` is inferred to be `usize` -... LL | if x == x && x == x && x = x { | ---------------- ^ expected `bool`, found `usize` | | diff --git a/tests/ui/type/type-check/point-at-inference-3.fixed b/tests/ui/type/type-check/point-at-inference-3.fixed index edd4adf8bd25..9c93063e04ae 100644 --- a/tests/ui/type/type-check/point-at-inference-3.fixed +++ b/tests/ui/type/type-check/point-at-inference-3.fixed @@ -2,7 +2,6 @@ fn main() { let mut v = Vec::new(); v.push(0i32); - //~^ NOTE this is of type `i32`, which causes `v` to be inferred as `Vec` v.push(0); v.push(1i32); //~ ERROR mismatched types //~^ NOTE expected `i32`, found `u32` diff --git a/tests/ui/type/type-check/point-at-inference-3.rs b/tests/ui/type/type-check/point-at-inference-3.rs index 49d7b50075bb..8bb1487420ba 100644 --- a/tests/ui/type/type-check/point-at-inference-3.rs +++ b/tests/ui/type/type-check/point-at-inference-3.rs @@ -2,7 +2,6 @@ fn main() { let mut v = Vec::new(); v.push(0i32); - //~^ NOTE this is of type `i32`, which causes `v` to be inferred as `Vec` v.push(0); v.push(1u32); //~ ERROR mismatched types //~^ NOTE expected `i32`, found `u32` diff --git a/tests/ui/type/type-check/point-at-inference-3.stderr b/tests/ui/type/type-check/point-at-inference-3.stderr index 2c4907ed263b..32663bd632e1 100644 --- a/tests/ui/type/type-check/point-at-inference-3.stderr +++ b/tests/ui/type/type-check/point-at-inference-3.stderr @@ -1,9 +1,6 @@ error[E0308]: mismatched types - --> $DIR/point-at-inference-3.rs:7:12 + --> $DIR/point-at-inference-3.rs:6:12 | -LL | v.push(0i32); - | ---- this is of type `i32`, which causes `v` to be inferred as `Vec` -... LL | v.push(1u32); | ---- ^^^^ expected `i32`, found `u32` | | diff --git a/tests/ui/type/type-check/point-at-inference-4.rs b/tests/ui/type/type-check/point-at-inference-4.rs index aea9b2c6c14e..7c25b91fd89e 100644 --- a/tests/ui/type/type-check/point-at-inference-4.rs +++ b/tests/ui/type/type-check/point-at-inference-4.rs @@ -11,6 +11,7 @@ fn main() { let s = S(None); s.infer(0i32); //~^ ERROR this method takes 2 arguments but 1 argument was supplied + //~| NOTE here the type of `s` is inferred to be `S` //~| NOTE an argument is missing //~| HELP provide the argument let t: S = s; diff --git a/tests/ui/type/type-check/point-at-inference-4.stderr b/tests/ui/type/type-check/point-at-inference-4.stderr index 28833d2ed1c9..6181af70c8ed 100644 --- a/tests/ui/type/type-check/point-at-inference-4.stderr +++ b/tests/ui/type/type-check/point-at-inference-4.stderr @@ -15,8 +15,11 @@ LL | s.infer(0i32, /* b */); | ~~~~~~~~~~~~~~~ error[E0308]: mismatched types - --> $DIR/point-at-inference-4.rs:16:24 + --> $DIR/point-at-inference-4.rs:17:24 | +LL | s.infer(0i32); + | - here the type of `s` is inferred to be `S` +... LL | let t: S = s; | --------- ^ expected `S`, found `S` | | diff --git a/tests/ui/type/type-check/point-at-inference.fixed b/tests/ui/type/type-check/point-at-inference.fixed index f41fbe59fba6..6419e42e70d1 100644 --- a/tests/ui/type/type-check/point-at-inference.fixed +++ b/tests/ui/type/type-check/point-at-inference.fixed @@ -6,7 +6,7 @@ fn main() { let mut foo = vec![]; baz(&foo); for i in &v { - foo.push(*i); + foo.push(i); } baz(&foo); bar(foo); //~ ERROR E0308 diff --git a/tests/ui/type/type-check/point-at-inference.stderr b/tests/ui/type/type-check/point-at-inference.stderr index a76b4f90c734..89c4cd1c3763 100644 --- a/tests/ui/type/type-check/point-at-inference.stderr +++ b/tests/ui/type/type-check/point-at-inference.stderr @@ -2,7 +2,7 @@ error[E0308]: mismatched types --> $DIR/point-at-inference.rs:12:9 | LL | foo.push(i); - | - this is of type `&{integer}`, which causes `foo` to be inferred as `Vec<&{integer}>` + | --- here the type of `foo` is inferred to be `Vec<&{integer}>` ... LL | bar(foo); | --- ^^^ expected `Vec`, found `Vec<&{integer}>` @@ -16,10 +16,6 @@ note: function defined here | LL | fn bar(_: Vec) {} | ^^^ ----------- -help: consider dereferencing the borrow - | -LL | foo.push(*i); - | + error: aborting due to previous error diff --git a/tests/ui/typeck/bad-type-in-vec-contains.stderr b/tests/ui/typeck/bad-type-in-vec-contains.stderr index 0e03388d2d58..72533ab1fa37 100644 --- a/tests/ui/typeck/bad-type-in-vec-contains.stderr +++ b/tests/ui/typeck/bad-type-in-vec-contains.stderr @@ -7,7 +7,6 @@ LL | primes.contains(3); | | expected `&_`, found integer | | help: consider borrowing here: `&3` | arguments to this method are incorrect - | here the type of `primes` is inferred to be `[_]` | = note: expected reference `&_` found type `{integer}` diff --git a/tests/ui/typeck/bad-type-in-vec-push.stderr b/tests/ui/typeck/bad-type-in-vec-push.stderr index ae46050c91be..1d5337260fa0 100644 --- a/tests/ui/typeck/bad-type-in-vec-push.stderr +++ b/tests/ui/typeck/bad-type-in-vec-push.stderr @@ -1,8 +1,6 @@ error[E0308]: mismatched types --> $DIR/bad-type-in-vec-push.rs:11:17 | -LL | vector.sort(); - | ------ here the type of `vector` is inferred to be `Vec<_>` LL | result.push(vector); | ---- ^^^^^^ expected integer, found `Vec<_>` | | diff --git a/tests/ui/typeck/issue-107775.stderr b/tests/ui/typeck/issue-107775.stderr index 9ee9c022c6e8..39c727bd278b 100644 --- a/tests/ui/typeck/issue-107775.stderr +++ b/tests/ui/typeck/issue-107775.stderr @@ -2,9 +2,7 @@ error[E0308]: mismatched types --> $DIR/issue-107775.rs:35:16 | LL | map.insert(1, Struct::do_something); - | - -------------------- this is of type `fn(u8) -> Pin + Send>> {::do_something::<'_>}`, which causes `map` to be inferred as `HashMap<{integer}, fn(u8) -> Pin + Send>> {::do_something::<'_>}>` - | | - | this is of type `{integer}`, which causes `map` to be inferred as `HashMap<{integer}, fn(u8) -> Pin + Send>> {::do_something::<'_>}>` + | --- here the type of `map` is inferred to be `HashMap<{integer}, fn(u8) -> Pin + Send>> {::do_something::<'_>}>` LL | Self { map } | ^^^ expected `HashMap Pin<...>>`, found `HashMap<{integer}, ...>` | From e72c45ad987b296baee79865b7e2ca00c518fb8b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 2 Mar 2023 23:23:07 +0000 Subject: [PATCH 030/116] Point at which arg causes a binding to be constrained --- compiler/rustc_hir_typeck/src/demand.rs | 63 +++++++++++++++---- .../type/type-check/point-at-inference.stderr | 4 +- tests/ui/typeck/issue-107775.stderr | 4 +- 3 files changed, 57 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 0c4f73e0db0e..0d3e4bde497f 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -259,10 +259,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir.body(hir.maybe_body_owned_by(self.body_id).expect("expected item to have body")); expr_finder.visit_expr(body.value); - let fudge_equals_found_ty = |use_ty: Ty<'tcx>| { + let fudge_ty = |ty: Ty<'tcx>| { use rustc_infer::infer::type_variable::*; use rustc_middle::infer::unify_key::*; - let use_ty = use_ty.fold_with(&mut BottomUpFolder { + ty.fold_with(&mut BottomUpFolder { tcx: self.tcx, ty_op: |ty| { if let ty::Infer(infer) = ty.kind() { @@ -293,7 +293,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ct } }, - }); + }) + }; + + let fudge_equals_found_ty = |use_ty: Ty<'tcx>| { + let use_ty = fudge_ty(use_ty); self.can_eq(self.param_env, expected_ty, use_ty) }; @@ -303,18 +307,53 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for window in expr_finder.uses.windows(2) { let [binding, next_usage] = *window else { continue; }; - let Some(next_use_ty) = self.node_ty_opt(next_usage.hir_id) else { continue; }; - if !fudge_equals_found_ty(next_use_ty) { - err.span_label( - binding.span, - format!("here the type of `{ident}` is inferred to be `{next_use_ty}`"), - ); - return true; - } - if next_usage.hir_id == expr.hir_id { + // Don't go past the binding (always gonna be a nonsense label if so) + if binding.hir_id == expr.hir_id { break; } + + let Some(next_use_ty) = self.node_ty_opt(next_usage.hir_id) else { continue; }; + + // If the type is not constrained in a way making it not possible to + // equate with `expected_ty` by this point, skip. + if fudge_equals_found_ty(next_use_ty) { + continue; + } + + if let hir::Node::Expr(parent_expr) = hir.get_parent(binding.hir_id) + && let hir::ExprKind::MethodCall(segment, rcvr, args, _) = parent_expr.kind + && rcvr.hir_id == binding.hir_id + { + let Some(rcvr_ty) = self.node_ty_opt(rcvr.hir_id) else { continue; }; + let rcvr_ty = fudge_ty(rcvr_ty); + if let Ok(method) = + self.lookup_method(rcvr_ty, segment, DUMMY_SP, parent_expr, rcvr, args) + { + for (expected_arg_ty, arg_expr) in std::iter::zip(&method.sig.inputs()[1..], args) { + let Some(arg_ty) = self.node_ty_opt(arg_expr.hir_id) else { continue; }; + let arg_ty = fudge_ty(arg_ty); + let _ = self.try_coerce(arg_expr, arg_ty, *expected_arg_ty, AllowTwoPhase::No, None); + if !self.can_eq(self.param_env, rcvr_ty, expected_ty) { + err.span_label( + arg_expr.span, + format!("this argument has type `{arg_ty}`...") + ); + err.span_label( + binding.span, + format!("... which constrains `{ident}` to have type `{next_use_ty}`") + ); + return true; + } + } + } + } + + err.span_label( + binding.span, + format!("here the type of `{ident}` is inferred to be `{next_use_ty}`"), + ); + return true; } // We must've not found something that constrained the expr. diff --git a/tests/ui/type/type-check/point-at-inference.stderr b/tests/ui/type/type-check/point-at-inference.stderr index 89c4cd1c3763..5d46368b1fd3 100644 --- a/tests/ui/type/type-check/point-at-inference.stderr +++ b/tests/ui/type/type-check/point-at-inference.stderr @@ -2,7 +2,9 @@ error[E0308]: mismatched types --> $DIR/point-at-inference.rs:12:9 | LL | foo.push(i); - | --- here the type of `foo` is inferred to be `Vec<&{integer}>` + | --- - this argument has type `&{integer}`... + | | + | ... which causes `foo` to have type `Vec<&{integer}>` ... LL | bar(foo); | --- ^^^ expected `Vec`, found `Vec<&{integer}>` diff --git a/tests/ui/typeck/issue-107775.stderr b/tests/ui/typeck/issue-107775.stderr index 39c727bd278b..b97e74b7e53f 100644 --- a/tests/ui/typeck/issue-107775.stderr +++ b/tests/ui/typeck/issue-107775.stderr @@ -2,7 +2,9 @@ error[E0308]: mismatched types --> $DIR/issue-107775.rs:35:16 | LL | map.insert(1, Struct::do_something); - | --- here the type of `map` is inferred to be `HashMap<{integer}, fn(u8) -> Pin + Send>> {::do_something::<'_>}>` + | --- -------------------- this argument has type `fn(u8) -> Pin + Send>> {::do_something::<'_>}`... + | | + | ... which causes `map` to have type `HashMap<{integer}, fn(u8) -> Pin + Send>> {::do_something::<'_>}>` LL | Self { map } | ^^^ expected `HashMap Pin<...>>`, found `HashMap<{integer}, ...>` | From 29aee6a125ac65a01932cb0ece5485e7cf8cfe87 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 2 Mar 2023 23:49:24 +0000 Subject: [PATCH 031/116] Restore suggestion based off of backwards inference from bad usage to method call --- compiler/rustc_hir_typeck/src/demand.rs | 141 +++++++++++------- .../type/type-check/point-at-inference.fixed | 2 +- .../type/type-check/point-at-inference.stderr | 4 + 3 files changed, 88 insertions(+), 59 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 0d3e4bde497f..f219068b4e87 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -259,49 +259,43 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir.body(hir.maybe_body_owned_by(self.body_id).expect("expected item to have body")); expr_finder.visit_expr(body.value); - let fudge_ty = |ty: Ty<'tcx>| { - use rustc_infer::infer::type_variable::*; - use rustc_middle::infer::unify_key::*; - ty.fold_with(&mut BottomUpFolder { - tcx: self.tcx, - ty_op: |ty| { - if let ty::Infer(infer) = ty.kind() { - match infer { - ty::InferTy::TyVar(_) => self.next_ty_var(TypeVariableOrigin { - kind: TypeVariableOriginKind::MiscVariable, - span: DUMMY_SP, - }), - ty::InferTy::IntVar(_) => self.next_int_var(), - ty::InferTy::FloatVar(_) => self.next_float_var(), - _ => bug!(), - } - } else { - ty + use rustc_infer::infer::type_variable::*; + use rustc_middle::infer::unify_key::*; + + let mut fudger = BottomUpFolder { + tcx: self.tcx, + ty_op: |ty| { + if let ty::Infer(infer) = ty.kind() { + match infer { + ty::InferTy::TyVar(_) => self.next_ty_var(TypeVariableOrigin { + kind: TypeVariableOriginKind::MiscVariable, + span: DUMMY_SP, + }), + ty::InferTy::IntVar(_) => self.next_int_var(), + ty::InferTy::FloatVar(_) => self.next_float_var(), + _ => bug!(), } - }, - lt_op: |_| self.tcx.lifetimes.re_erased, - ct_op: |ct| { - if let ty::ConstKind::Infer(_) = ct.kind() { - self.next_const_var( - ct.ty(), - ConstVariableOrigin { - kind: ConstVariableOriginKind::MiscVariable, - span: DUMMY_SP, - }, - ) - } else { - ct - } - }, - }) + } else { + ty + } + }, + lt_op: |_| self.tcx.lifetimes.re_erased, + ct_op: |ct| { + if let ty::ConstKind::Infer(_) = ct.kind() { + self.next_const_var( + ct.ty(), + ConstVariableOrigin { + kind: ConstVariableOriginKind::MiscVariable, + span: DUMMY_SP, + }, + ) + } else { + ct + } + }, }; - let fudge_equals_found_ty = |use_ty: Ty<'tcx>| { - let use_ty = fudge_ty(use_ty); - self.can_eq(self.param_env, expected_ty, use_ty) - }; - - if !fudge_equals_found_ty(init_ty) { + if !self.can_eq(self.param_env, expected_ty, init_ty.fold_with(&mut fudger)) { return false; } @@ -317,7 +311,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // If the type is not constrained in a way making it not possible to // equate with `expected_ty` by this point, skip. - if fudge_equals_found_ty(next_use_ty) { + if self.can_eq(self.param_env, expected_ty, next_use_ty.fold_with(&mut fudger)) { continue; } @@ -326,26 +320,57 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && rcvr.hir_id == binding.hir_id { let Some(rcvr_ty) = self.node_ty_opt(rcvr.hir_id) else { continue; }; - let rcvr_ty = fudge_ty(rcvr_ty); - if let Ok(method) = + let rcvr_ty = rcvr_ty.fold_with(&mut fudger); + let Ok(method) = self.lookup_method(rcvr_ty, segment, DUMMY_SP, parent_expr, rcvr, args) + else { + continue; + }; + + // NOTE: For future removers of `fudge_inference_if_ok`, you + // can replace this with another call to `lookup_method` but + // using `expected_ty` as the rcvr. + let ideal_method_sig: Result<_, TypeError<'tcx>> = self.fudge_inference_if_ok(|| { + let _ = self.at(&ObligationCause::dummy(), self.param_env).eq(rcvr_ty, expected_ty)?; + Ok(method.sig) + }); + + for (idx, (expected_arg_ty, arg_expr)) in + std::iter::zip(&method.sig.inputs()[1..], args).enumerate() { - for (expected_arg_ty, arg_expr) in std::iter::zip(&method.sig.inputs()[1..], args) { - let Some(arg_ty) = self.node_ty_opt(arg_expr.hir_id) else { continue; }; - let arg_ty = fudge_ty(arg_ty); - let _ = self.try_coerce(arg_expr, arg_ty, *expected_arg_ty, AllowTwoPhase::No, None); - if !self.can_eq(self.param_env, rcvr_ty, expected_ty) { - err.span_label( - arg_expr.span, - format!("this argument has type `{arg_ty}`...") - ); - err.span_label( - binding.span, - format!("... which constrains `{ident}` to have type `{next_use_ty}`") - ); - return true; - } + let Some(arg_ty) = self.node_ty_opt(arg_expr.hir_id) else { continue; }; + let arg_ty = arg_ty.fold_with(&mut fudger); + let _ = self.try_coerce( + arg_expr, + arg_ty, + *expected_arg_ty, + AllowTwoPhase::No, + None, + ); + if self.can_eq(self.param_env, rcvr_ty, expected_ty) { + continue; } + err.span_label( + arg_expr.span, + format!("this argument has type `{arg_ty}`..."), + ); + err.span_label( + binding.span, + format!( + "... which constrains `{ident}` to have type `{next_use_ty}`" + ), + ); + if let Ok(ideal_method_sig) = ideal_method_sig { + self.emit_type_mismatch_suggestions( + err, + arg_expr, + arg_ty, + ideal_method_sig.inputs()[idx + 1], + None, + None, + ); + } + return true; } } diff --git a/tests/ui/type/type-check/point-at-inference.fixed b/tests/ui/type/type-check/point-at-inference.fixed index 6419e42e70d1..f41fbe59fba6 100644 --- a/tests/ui/type/type-check/point-at-inference.fixed +++ b/tests/ui/type/type-check/point-at-inference.fixed @@ -6,7 +6,7 @@ fn main() { let mut foo = vec![]; baz(&foo); for i in &v { - foo.push(i); + foo.push(*i); } baz(&foo); bar(foo); //~ ERROR E0308 diff --git a/tests/ui/type/type-check/point-at-inference.stderr b/tests/ui/type/type-check/point-at-inference.stderr index 5d46368b1fd3..5fc94d4d1b6b 100644 --- a/tests/ui/type/type-check/point-at-inference.stderr +++ b/tests/ui/type/type-check/point-at-inference.stderr @@ -18,6 +18,10 @@ note: function defined here | LL | fn bar(_: Vec) {} | ^^^ ----------- +help: consider dereferencing the borrow + | +LL | foo.push(*i); + | + error: aborting due to previous error From 5a71029dd3b54046fbd6144de20e320db539820f Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 3 Mar 2023 00:44:22 +0000 Subject: [PATCH 032/116] Properly note source of arg mismatch --- compiler/rustc_hir_typeck/src/demand.rs | 57 ++++++++++++++++++- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 13 ++++- .../type-check/point-at-inference-3.fixed | 2 + .../type/type-check/point-at-inference-3.rs | 2 + .../type-check/point-at-inference-3.stderr | 7 ++- 5 files changed, 74 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index f219068b4e87..9ffee5670232 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -62,7 +62,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { || self.suggest_coercing_result_via_try_operator(err, expr, expected, expr_ty); if !suggested { - self.note_source_of_type_mismatch_constraint(err, expr, expected); + self.note_source_of_type_mismatch_constraint( + err, + expr, + TypeMismatchSource::Ty(expected), + ); } } @@ -222,7 +226,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, err: &mut Diagnostic, expr: &hir::Expr<'_>, - expected_ty: Ty<'tcx>, + source: TypeMismatchSource<'tcx>, ) -> bool { let hir = self.tcx.hir(); @@ -295,6 +299,46 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }, }; + let expected_ty = match source { + TypeMismatchSource::Ty(expected_ty) => expected_ty, + TypeMismatchSource::Arg(call_expr, idx) => { + let hir::ExprKind::MethodCall(segment, _, args, _) = call_expr.kind else { + return false; + }; + let Some(arg_ty) = self.node_ty_opt(args[idx].hir_id) else { + return false; + }; + let possible_rcvr_ty = expr_finder.uses.iter().find_map(|binding| { + let possible_rcvr_ty = self.node_ty_opt(binding.hir_id)?; + let possible_rcvr_ty = possible_rcvr_ty.fold_with(&mut fudger); + let method = self + .lookup_method( + possible_rcvr_ty, + segment, + DUMMY_SP, + call_expr, + binding, + args, + ) + .ok()?; + let _ = self + .at(&ObligationCause::dummy(), self.param_env) + .eq(DefineOpaqueTypes::No, method.sig.inputs()[idx + 1], arg_ty) + .ok()?; + self.select_obligations_where_possible(|errs| { + // Yeet the errors, we're already reporting errors. + errs.clear(); + }); + Some(self.resolve_vars_if_possible(possible_rcvr_ty)) + }); + if let Some(rcvr_ty) = possible_rcvr_ty { + rcvr_ty + } else { + return false; + } + } + }; + if !self.can_eq(self.param_env, expected_ty, init_ty.fold_with(&mut fudger)) { return false; } @@ -360,7 +404,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "... which constrains `{ident}` to have type `{next_use_ty}`" ), ); - if let Ok(ideal_method_sig) = ideal_method_sig { + if matches!(source, TypeMismatchSource::Ty(_)) + && let Ok(ideal_method_sig) = ideal_method_sig + { self.emit_type_mismatch_suggestions( err, arg_expr, @@ -2044,3 +2090,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } } + +pub enum TypeMismatchSource<'tcx> { + Ty(Ty<'tcx>), + Arg(&'tcx hir::Expr<'tcx>, usize), +} diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index d98e0d9096f5..9ecb78e2dda8 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -472,7 +472,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err_code: &str, fn_def_id: Option, call_span: Span, - call_expr: &hir::Expr<'tcx>, + call_expr: &'tcx hir::Expr<'tcx>, ) { // Next, let's construct the error let (error_span, full_call_span, call_name, is_method) = match &call_expr.kind { @@ -808,8 +808,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { format!("arguments to this {} are incorrect", call_name), ); - // TODO: We would like to point out when the rcvr was constrained - // such that the arg mismatch occurs. + if let hir::ExprKind::MethodCall(_, rcvr, _, _) = call_expr.kind + && provided_idx.as_usize() == expected_idx.as_usize() + { + self.note_source_of_type_mismatch_constraint( + &mut err, + rcvr, + crate::demand::TypeMismatchSource::Arg(call_expr, provided_idx.as_usize()), + ); + } // Call out where the function is defined self.label_fn_like( diff --git a/tests/ui/type/type-check/point-at-inference-3.fixed b/tests/ui/type/type-check/point-at-inference-3.fixed index 9c93063e04ae..15a3b580568d 100644 --- a/tests/ui/type/type-check/point-at-inference-3.fixed +++ b/tests/ui/type/type-check/point-at-inference-3.fixed @@ -2,6 +2,8 @@ fn main() { let mut v = Vec::new(); v.push(0i32); + //~^ NOTE this argument has type `i32`... + //~| NOTE ... which causes `v` to have type `Vec` v.push(0); v.push(1i32); //~ ERROR mismatched types //~^ NOTE expected `i32`, found `u32` diff --git a/tests/ui/type/type-check/point-at-inference-3.rs b/tests/ui/type/type-check/point-at-inference-3.rs index 8bb1487420ba..a48c4f9862f7 100644 --- a/tests/ui/type/type-check/point-at-inference-3.rs +++ b/tests/ui/type/type-check/point-at-inference-3.rs @@ -2,6 +2,8 @@ fn main() { let mut v = Vec::new(); v.push(0i32); + //~^ NOTE this argument has type `i32`... + //~| NOTE ... which causes `v` to have type `Vec` v.push(0); v.push(1u32); //~ ERROR mismatched types //~^ NOTE expected `i32`, found `u32` diff --git a/tests/ui/type/type-check/point-at-inference-3.stderr b/tests/ui/type/type-check/point-at-inference-3.stderr index 32663bd632e1..238764812364 100644 --- a/tests/ui/type/type-check/point-at-inference-3.stderr +++ b/tests/ui/type/type-check/point-at-inference-3.stderr @@ -1,6 +1,11 @@ error[E0308]: mismatched types - --> $DIR/point-at-inference-3.rs:6:12 + --> $DIR/point-at-inference-3.rs:8:12 | +LL | v.push(0i32); + | - ---- this argument has type `i32`... + | | + | ... which causes `v` to have type `Vec` +... LL | v.push(1u32); | ---- ^^^^ expected `i32`, found `u32` | | From 5cc475742151cd458091ca3c67598ddece3ee39b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 3 Mar 2023 01:35:51 +0000 Subject: [PATCH 033/116] More accurate argument blames, add some comments --- compiler/rustc_hir_typeck/src/demand.rs | 75 +++++++++++++------ .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 5 +- .../type/type-check/point-at-inference-4.rs | 4 +- .../type-check/point-at-inference-4.stderr | 10 ++- 4 files changed, 69 insertions(+), 25 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 9ffee5670232..13442c316492 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -221,7 +221,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Notes the point at which a variable is constrained to some type incompatible - /// with `expected_ty`. + /// with some expectation given by `source`. pub fn note_source_of_type_mismatch_constraint( &self, err: &mut Diagnostic, @@ -265,7 +265,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { use rustc_infer::infer::type_variable::*; use rustc_middle::infer::unify_key::*; - + // Replaces all of the variables in the given type with a fresh inference variable. let mut fudger = BottomUpFolder { tcx: self.tcx, ty_op: |ty| { @@ -301,7 +301,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let expected_ty = match source { TypeMismatchSource::Ty(expected_ty) => expected_ty, - TypeMismatchSource::Arg(call_expr, idx) => { + // Try to deduce what the possible value of `expr` would be if the + // incompatible arg were compatible. For example, given `Vec` + // and `vec.push(1u32)`, we ideally want to deduce that the type of + // `vec` *should* have been `Vec`. This will allow us to then + // run the subsequent code with this expectation, finding out exactly + // when this type diverged from our expectation. + TypeMismatchSource::Arg { call_expr, incompatible_arg: idx } => { let hir::ExprKind::MethodCall(segment, _, args, _) = call_expr.kind else { return false; }; @@ -310,6 +316,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let possible_rcvr_ty = expr_finder.uses.iter().find_map(|binding| { let possible_rcvr_ty = self.node_ty_opt(binding.hir_id)?; + // Fudge the receiver, so we can do new inference on it. let possible_rcvr_ty = possible_rcvr_ty.fold_with(&mut fudger); let method = self .lookup_method( @@ -321,6 +328,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { args, ) .ok()?; + // Unify the method signature with our incompatible arg, to + // do inference in the *opposite* direction and to find out + // what our ideal rcvr ty would look like. let _ = self .at(&ObligationCause::dummy(), self.param_env) .eq(DefineOpaqueTypes::No, method.sig.inputs()[idx + 1], arg_ty) @@ -339,11 +349,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }; + // If our expected_ty does not equal init_ty, then it *began* as incompatible. + // No need to note in this case... if !self.can_eq(self.param_env, expected_ty, init_ty.fold_with(&mut fudger)) { return false; } for window in expr_finder.uses.windows(2) { + // Bindings always update their recorded type after the fact, so we + // need to look at the *following* usage's type to see when the + // binding became incompatible. let [binding, next_usage] = *window else { continue; }; // Don't go past the binding (always gonna be a nonsense label if so) @@ -363,6 +378,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && let hir::ExprKind::MethodCall(segment, rcvr, args, _) = parent_expr.kind && rcvr.hir_id == binding.hir_id { + // If our binding became incompatible while it was a receiver + // to a method call, we may be able to make a better guess to + // the source of a type mismatch. let Some(rcvr_ty) = self.node_ty_opt(rcvr.hir_id) else { continue; }; let rcvr_ty = rcvr_ty.fold_with(&mut fudger); let Ok(method) = @@ -371,14 +389,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { continue; }; - // NOTE: For future removers of `fudge_inference_if_ok`, you - // can replace this with another call to `lookup_method` but - // using `expected_ty` as the rcvr. - let ideal_method_sig: Result<_, TypeError<'tcx>> = self.fudge_inference_if_ok(|| { - let _ = self.at(&ObligationCause::dummy(), self.param_env).eq(rcvr_ty, expected_ty)?; - Ok(method.sig) - }); + let ideal_rcvr_ty = rcvr_ty.fold_with(&mut fudger); + let ideal_method = self + .lookup_method(ideal_rcvr_ty, segment, DUMMY_SP, parent_expr, rcvr, args) + .ok() + .and_then(|method| { + let _ = self.at(&ObligationCause::dummy(), self.param_env) + .eq(DefineOpaqueTypes::No, ideal_rcvr_ty, expected_ty) + .ok()?; + Some(method) + }); + // Find what argument caused our rcvr to become incompatible + // with the expected ty. for (idx, (expected_arg_ty, arg_expr)) in std::iter::zip(&method.sig.inputs()[1..], args).enumerate() { @@ -391,27 +414,33 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { AllowTwoPhase::No, None, ); + self.select_obligations_where_possible(|errs| { + // Yeet the errors, we're already reporting errors. + errs.clear(); + }); + // If our rcvr, after inference due to unifying the signature + // with the expected argument type, is still compatible with + // the rcvr, then it must've not been the source of blame. if self.can_eq(self.param_env, rcvr_ty, expected_ty) { continue; } - err.span_label( - arg_expr.span, - format!("this argument has type `{arg_ty}`..."), - ); + err.span_label(arg_expr.span, format!("this argument has type `{arg_ty}`...")); err.span_label( binding.span, - format!( - "... which constrains `{ident}` to have type `{next_use_ty}`" - ), + format!("... which causes `{ident}` to have type `{next_use_ty}`"), ); + // Using our "ideal" method signature, suggest a fix to this + // blame arg, if possible. Don't do this if we're coming from + // arg mismatch code, because we'll possibly suggest a mutually + // incompatible fix at the original mismatch site. if matches!(source, TypeMismatchSource::Ty(_)) - && let Ok(ideal_method_sig) = ideal_method_sig + && let Some(ideal_method) = ideal_method { self.emit_type_mismatch_suggestions( err, arg_expr, arg_ty, - ideal_method_sig.inputs()[idx + 1], + self.resolve_vars_if_possible(ideal_method.sig.inputs()[idx + 1]), None, None, ); @@ -419,7 +448,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return true; } } - err.span_label( binding.span, format!("here the type of `{ident}` is inferred to be `{next_use_ty}`"), @@ -2092,6 +2120,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } pub enum TypeMismatchSource<'tcx> { + /// Expected the binding to have the given type, but it was found to have + /// a different type. Find out when that type first became incompatible. Ty(Ty<'tcx>), - Arg(&'tcx hir::Expr<'tcx>, usize), + /// When we fail during method argument checking, try to find out if a previous + /// expression has constrained the method's receiver in a way that makes the + /// argument's type incompatible. + Arg { call_expr: &'tcx hir::Expr<'tcx>, incompatible_arg: usize }, } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 9ecb78e2dda8..ea1b52daaa5e 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -814,7 +814,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.note_source_of_type_mismatch_constraint( &mut err, rcvr, - crate::demand::TypeMismatchSource::Arg(call_expr, provided_idx.as_usize()), + crate::demand::TypeMismatchSource::Arg { + call_expr, + incompatible_arg: provided_idx.as_usize(), + }, ); } diff --git a/tests/ui/type/type-check/point-at-inference-4.rs b/tests/ui/type/type-check/point-at-inference-4.rs index 7c25b91fd89e..3deb234c2751 100644 --- a/tests/ui/type/type-check/point-at-inference-4.rs +++ b/tests/ui/type/type-check/point-at-inference-4.rs @@ -11,9 +11,11 @@ fn main() { let s = S(None); s.infer(0i32); //~^ ERROR this method takes 2 arguments but 1 argument was supplied - //~| NOTE here the type of `s` is inferred to be `S` + //~| NOTE this argument has type `i32`... + //~| NOTE ... which causes `s` to have type `S` //~| NOTE an argument is missing //~| HELP provide the argument + //~| HELP change the type of the numeric literal from `i32` to `u32` let t: S = s; //~^ ERROR mismatched types //~| NOTE expected `S`, found `S` diff --git a/tests/ui/type/type-check/point-at-inference-4.stderr b/tests/ui/type/type-check/point-at-inference-4.stderr index 6181af70c8ed..5f7bb8b9367e 100644 --- a/tests/ui/type/type-check/point-at-inference-4.stderr +++ b/tests/ui/type/type-check/point-at-inference-4.stderr @@ -15,10 +15,12 @@ LL | s.infer(0i32, /* b */); | ~~~~~~~~~~~~~~~ error[E0308]: mismatched types - --> $DIR/point-at-inference-4.rs:17:24 + --> $DIR/point-at-inference-4.rs:19:24 | LL | s.infer(0i32); - | - here the type of `s` is inferred to be `S` + | - ---- this argument has type `i32`... + | | + | ... which causes `s` to have type `S` ... LL | let t: S = s; | --------- ^ expected `S`, found `S` @@ -27,6 +29,10 @@ LL | let t: S = s; | = note: expected struct `S` found struct `S` +help: change the type of the numeric literal from `i32` to `u32` + | +LL | s.infer(0u32); + | ~~~ error: aborting due to 2 previous errors From 7d64c7cd024ac22e71df104577037d2e2fb42c49 Mon Sep 17 00:00:00 2001 From: jyn Date: Wed, 12 Apr 2023 21:17:08 -0500 Subject: [PATCH 034/116] Add `libLLVM.so` to the target libdir when download-rustc is enabled Previously, we would only add it to the host libdir, which meant it couldn't be loaded by `ui-fulldeps` tests that used rustc_private. --- src/bootstrap/compile.rs | 9 +++++---- src/bootstrap/dist.rs | 14 ++++++++++++++ src/bootstrap/lib.rs | 5 +++++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/bootstrap/compile.rs b/src/bootstrap/compile.rs index 85d1c12cc6a0..aaed5cf2e32b 100644 --- a/src/bootstrap/compile.rs +++ b/src/bootstrap/compile.rs @@ -1273,9 +1273,7 @@ impl Step for Sysroot { } // Copy the compiler into the correct sysroot. - let ci_rustc_dir = - builder.config.out.join(&*builder.config.build.triple).join("ci-rustc"); - builder.cp_r(&ci_rustc_dir, &sysroot); + builder.cp_r(&builder.ci_rustc_dir(builder.build.build), &sysroot); return INTERNER.intern_path(sysroot); } @@ -1377,7 +1375,10 @@ impl Step for Assemble { // If we're downloading a compiler from CI, we can use the same compiler for all stages other than 0. if builder.download_rustc() { - builder.ensure(Sysroot { compiler: target_compiler }); + let sysroot = builder.ensure(Sysroot { compiler: target_compiler }); + // Ensure that `libLLVM.so` ends up in the newly created target directory, + // so that tools using `rustc_private` can use it. + dist::maybe_install_llvm_target(builder, target_compiler.host, &sysroot); return target_compiler; } diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 8ce220c86478..28478aca4039 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -1960,6 +1960,20 @@ fn maybe_install_llvm(builder: &Builder<'_>, target: TargetSelection, dst_libdir } } + // FIXME: for reasons I don't understand, the LLVM so in the `rustc` component is different than the one in `rust-dev`. + // Only the one in `rustc` works with the downloaded compiler. + if builder.download_rustc() && target == builder.build.build { + let src_libdir = builder.ci_rustc_dir(target).join("lib"); + for entry in t!(std::fs::read_dir(&src_libdir)) { + let entry = t!(entry); + if entry.file_name().to_str().unwrap().starts_with("libLLVM-") { + install_llvm_file(builder, &entry.path(), dst_libdir); + return !builder.config.dry_run(); + } + } + panic!("libLLVM.so not found in src_libdir {}!", src_libdir.display()); + } + // On macOS, rustc (and LLVM tools) link to an unversioned libLLVM.dylib // instead of libLLVM-11-rust-....dylib, as on linux. It's not entirely // clear why this is the case, though. llvm-config will emit the versioned diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index eaa3afa4b7b2..6296fdad8a10 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -805,6 +805,11 @@ impl Build { self.stage_out(compiler, mode).join(&*target.triple).join(self.cargo_dir()) } + /// Directory where the extracted `rustc-dev` component is stored. + fn ci_rustc_dir(&self, target: TargetSelection) -> PathBuf { + self.out.join(&*target.triple).join("ci-rustc") + } + /// Root output directory for LLVM compiled for `target` /// /// Note that if LLVM is configured externally then the directory returned From 74076684a2fbda793e79406c55a3378f1b883c4d Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Thu, 13 Apr 2023 00:36:40 -0700 Subject: [PATCH 035/116] Add `tidy-alphabetical` to features in `core` So that people have to keep them sorted in future. --- library/core/src/lib.rs | 52 +++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 23 deletions(-) diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 4fd5a4bfc65f..04243544b835 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -98,11 +98,14 @@ #![warn(multiple_supertrait_upcastable)] // // Library features: -#![feature(const_align_offset)] +// tidy-alphabetical-start +#![feature(char_indices_offset)] #![feature(const_align_of_val)] #![feature(const_align_of_val_raw)] +#![feature(const_align_offset)] #![feature(const_alloc_layout)] #![feature(const_arguments_as_str)] +#![feature(const_array_from_ref)] #![feature(const_array_into_iter_constructors)] #![feature(const_bigint_helper_methods)] #![feature(const_black_box)] @@ -111,6 +114,9 @@ #![feature(const_char_from_u32_unchecked)] #![feature(const_clone)] #![feature(const_cmp)] +#![feature(const_convert)] +#![feature(const_cstr_methods)] +#![feature(const_default_impls)] #![feature(const_discriminant)] #![feature(const_eval_select)] #![feature(const_exact_div)] @@ -119,17 +125,17 @@ #![feature(const_fmt_arguments_new)] #![feature(const_hash)] #![feature(const_heap)] -#![feature(const_convert)] #![feature(const_index_range_slice_index)] #![feature(const_inherent_unchecked_arith)] #![feature(const_int_unchecked_arith)] #![feature(const_intrinsic_forget)] #![feature(const_ipv4)] #![feature(const_ipv6)] +#![feature(const_is_char_boundary)] #![feature(const_likely)] -#![feature(const_maybe_uninit_uninit_array)] #![feature(const_maybe_uninit_as_mut_ptr)] #![feature(const_maybe_uninit_assume_init)] +#![feature(const_maybe_uninit_uninit_array)] #![feature(const_nonnull_new)] #![feature(const_num_from_num)] #![feature(const_ops)] @@ -138,32 +144,35 @@ #![feature(const_pin)] #![feature(const_pointer_byte_offsets)] #![feature(const_pointer_is_aligned)] -#![feature(const_ptr_sub_ptr)] -#![feature(const_replace)] -#![feature(const_result_drop)] #![feature(const_ptr_as_ref)] #![feature(const_ptr_is_null)] #![feature(const_ptr_read)] +#![feature(const_ptr_sub_ptr)] #![feature(const_ptr_write)] #![feature(const_raw_ptr_comparison)] +#![feature(const_replace)] +#![feature(const_result_drop)] #![feature(const_size_of_val)] #![feature(const_size_of_val_raw)] #![feature(const_slice_from_raw_parts_mut)] +#![feature(const_slice_from_ref)] +#![feature(const_slice_index)] #![feature(const_slice_ptr_len)] #![feature(const_slice_split_at_mut)] #![feature(const_str_from_utf8_unchecked_mut)] #![feature(const_swap)] #![feature(const_trait_impl)] +#![feature(const_transmute_copy)] #![feature(const_try)] #![feature(const_type_id)] #![feature(const_type_name)] -#![feature(const_default_impls)] #![feature(const_unicode_case_lookup)] #![feature(const_unsafecell_get_mut)] #![feature(const_waker)] #![feature(core_panic)] -#![feature(char_indices_offset)] #![feature(duration_consts_float)] +#![feature(ip)] +#![feature(is_ascii_octdigit)] #![feature(maybe_uninit_uninit_array)] #![feature(ptr_alignment_type)] #![feature(ptr_metadata)] @@ -171,25 +180,21 @@ #![feature(slice_ptr_get)] #![feature(slice_split_at_unchecked)] #![feature(str_internals)] -#![feature(str_split_remainder)] #![feature(str_split_inclusive_remainder)] +#![feature(str_split_remainder)] #![feature(strict_provenance)] #![feature(utf16_extra)] #![feature(utf16_extra_const)] #![feature(variant_count)] -#![feature(const_array_from_ref)] -#![feature(const_slice_from_ref)] -#![feature(const_slice_index)] -#![feature(const_is_char_boundary)] -#![feature(const_cstr_methods)] -#![feature(ip)] -#![feature(is_ascii_octdigit)] +// tidy-alphabetical-end // // Language features: +// tidy-alphabetical-start #![feature(abi_unadjusted)] #![feature(adt_const_params)] #![feature(allow_internal_unsafe)] #![feature(allow_internal_unstable)] +#![feature(asm_const)] #![feature(associated_type_bounds)] #![feature(auto_traits)] #![feature(c_unwind)] @@ -206,13 +211,12 @@ #![feature(deprecated_suggestion)] #![feature(derive_const)] #![feature(doc_cfg)] -#![feature(doc_notable_trait)] -#![feature(generic_arg_infer)] -#![feature(rustdoc_internals)] -#![feature(exhaustive_patterns)] #![feature(doc_cfg_hide)] +#![feature(doc_notable_trait)] +#![feature(exhaustive_patterns)] #![feature(extern_types)] #![feature(fundamental)] +#![feature(generic_arg_infer)] #![feature(if_let_guard)] #![feature(inline_const)] #![feature(intra_doc_pointers)] @@ -221,6 +225,7 @@ #![feature(link_llvm_intrinsics)] #![feature(macro_metavar_expr)] #![feature(min_specialization)] +#![feature(multiple_supertrait_upcastable)] #![feature(must_not_suspend)] #![feature(negative_impls)] #![feature(never_type)] @@ -231,6 +236,7 @@ #![feature(repr_simd)] #![feature(rustc_allow_const_fn_unstable)] #![feature(rustc_attrs)] +#![feature(rustdoc_internals)] #![feature(simd_ffi)] #![feature(staged_api)] #![feature(stmt_expr_attributes)] @@ -240,11 +246,10 @@ #![feature(try_blocks)] #![feature(unboxed_closures)] #![feature(unsized_fn_params)] -#![feature(asm_const)] -#![feature(const_transmute_copy)] -#![feature(multiple_supertrait_upcastable)] +// tidy-alphabetical-end // // Target features: +// tidy-alphabetical-start #![feature(arm_target_feature)] #![feature(avx512_target_feature)] #![feature(hexagon_target_feature)] @@ -255,6 +260,7 @@ #![feature(sse4a_target_feature)] #![feature(tbm_target_feature)] #![feature(wasm_target_feature)] +// tidy-alphabetical-end // allow using `core::` in intra-doc links #[allow(unused_extern_crates)] From ecf2a9b75ec591db6e89f4bde391b87f35c2ea08 Mon Sep 17 00:00:00 2001 From: Ezra Shaw Date: Thu, 13 Apr 2023 20:29:41 +1200 Subject: [PATCH 036/116] fix: skip implied bounds if unconstrained lifetime exists --- .../src/traits/outlives_bounds.rs | 11 ++++++++- tests/ui/implied-bounds/issue-110161.rs | 24 +++++++++++++++++++ tests/ui/implied-bounds/issue-110161.stderr | 12 ++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 tests/ui/implied-bounds/issue-110161.rs create mode 100644 tests/ui/implied-bounds/issue-110161.stderr diff --git a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs index cff3d277a78f..64be4a55708a 100644 --- a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs @@ -55,7 +55,16 @@ impl<'a, 'tcx: 'a> InferCtxtExt<'a, 'tcx> for InferCtxt<'tcx> { ) -> Vec> { let ty = self.resolve_vars_if_possible(ty); let ty = OpportunisticRegionResolver::new(self).fold_ty(ty); - assert!(!ty.needs_infer()); + + // We must avoid processing constrained lifetime variables in implied + // bounds. See #110161 for context. + if ty.needs_infer() { + self.tcx.sess.delay_span_bug( + self.tcx.source_span_untracked(body_id), + "skipped implied_outlives_bounds due to unconstrained lifetimes", + ); + return vec![]; + } let span = self.tcx.def_span(body_id); let result = param_env diff --git a/tests/ui/implied-bounds/issue-110161.rs b/tests/ui/implied-bounds/issue-110161.rs new file mode 100644 index 000000000000..ca75026ffe84 --- /dev/null +++ b/tests/ui/implied-bounds/issue-110161.rs @@ -0,0 +1,24 @@ +// ICE regression relating to unconstrained lifetimes in implied +// bounds. See #110161. + +// compile-flags: --crate-type=lib + +trait Trait { + type Ty; +} + +// erroneous `Ty` impl +impl Trait for () { +//~^ ERROR not all trait items implemented, missing: `Ty` [E0046] +} + +// `'lt` is not constrained by the erroneous `Ty` +impl<'lt, T> Trait for Box +where + T: Trait, +{ + type Ty = &'lt (); +} + +// unconstrained lifetime appears in implied bounds +fn test(_: as Trait>::Ty) {} diff --git a/tests/ui/implied-bounds/issue-110161.stderr b/tests/ui/implied-bounds/issue-110161.stderr new file mode 100644 index 000000000000..c76b47376264 --- /dev/null +++ b/tests/ui/implied-bounds/issue-110161.stderr @@ -0,0 +1,12 @@ +error[E0046]: not all trait items implemented, missing: `Ty` + --> $DIR/issue-110161.rs:11:1 + | +LL | type Ty; + | ------- `Ty` from trait +... +LL | impl Trait for () { + | ^^^^^^^^^^^^^^^^^ missing `Ty` in implementation + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0046`. From d374620de46ecc731bef1f8845ffe2ea9c54fbd5 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Thu, 13 Apr 2023 11:05:02 -0700 Subject: [PATCH 037/116] Add `tidy-alphabetical` to features in `alloc` & `std` So that people have to keep them sorted in future, rather than just sticking them on the end where they conflict more often. --- library/alloc/src/lib.rs | 48 ++++++++++++++++++++++------------------ library/std/src/lib.rs | 26 ++++++++++++++++------ 2 files changed, 45 insertions(+), 29 deletions(-) diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index 55e18b049560..aa240c37e844 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -90,6 +90,11 @@ #![warn(multiple_supertrait_upcastable)] // // 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)] #![feature(array_chunks)] @@ -99,23 +104,21 @@ #![feature(assert_matches)] #![feature(async_iterator)] #![feature(coerce_unsized)] -#![cfg_attr(not(no_global_oom_handling), feature(const_alloc_error))] -#![feature(const_box)] -#![cfg_attr(not(no_global_oom_handling), feature(const_btree_len))] -#![feature(const_cow_is_borrowed)] -#![feature(const_convert)] -#![feature(const_size_of_val)] #![feature(const_align_of_val)] -#![feature(const_ptr_read)] -#![feature(const_maybe_uninit_zeroed)] -#![feature(const_maybe_uninit_write)] +#![feature(const_box)] +#![feature(const_convert)] +#![feature(const_cow_is_borrowed)] +#![feature(const_eval_select)] #![feature(const_maybe_uninit_as_mut_ptr)] +#![feature(const_maybe_uninit_write)] +#![feature(const_maybe_uninit_zeroed)] +#![feature(const_pin)] +#![feature(const_ptr_read)] #![feature(const_refs_to_cell)] +#![feature(const_size_of_val)] +#![feature(const_waker)] #![feature(core_intrinsics)] #![feature(core_panic)] -#![feature(const_eval_select)] -#![feature(const_pin)] -#![feature(const_waker)] #![feature(dispatch_from_dyn)] #![feature(error_generic_member_access)] #![feature(error_in_core)] @@ -126,7 +129,6 @@ #![feature(hasher_prefixfree_extras)] #![feature(inline_const)] #![feature(inplace_iteration)] -#![cfg_attr(test, feature(is_sorted))] #![feature(iter_advance_by)] #![feature(iter_next_chunk)] #![feature(iter_repeat_n)] @@ -134,7 +136,6 @@ #![feature(maybe_uninit_slice)] #![feature(maybe_uninit_uninit_array)] #![feature(maybe_uninit_uninit_array_transpose)] -#![cfg_attr(test, feature(new_uninit))] #![feature(pattern)] #![feature(pointer_byte_offsets)] #![feature(provide_any)] @@ -150,6 +151,7 @@ #![feature(slice_ptr_get)] #![feature(slice_ptr_len)] #![feature(slice_range)] +#![feature(std_internals)] #![feature(str_internals)] #![feature(strict_provenance)] #![feature(trusted_len)] @@ -160,41 +162,43 @@ #![feature(unicode_internals)] #![feature(unsize)] #![feature(utf8_chunks)] -#![feature(std_internals)] +// tidy-alphabetical-end // // Language features: +// tidy-alphabetical-start +#![cfg_attr(not(test), feature(generator_trait))] +#![cfg_attr(test, feature(panic_update_hook))] +#![cfg_attr(test, feature(test))] #![feature(allocator_internals)] #![feature(allow_internal_unstable)] #![feature(associated_type_bounds)] +#![feature(c_unwind)] #![feature(cfg_sanitize)] #![feature(const_deref)] #![feature(const_mut_refs)] -#![feature(const_ptr_write)] #![feature(const_precise_live_drops)] +#![feature(const_ptr_write)] #![feature(const_trait_impl)] #![feature(const_try)] #![feature(dropck_eyepatch)] #![feature(exclusive_range_pattern)] #![feature(fundamental)] -#![cfg_attr(not(test), feature(generator_trait))] #![feature(hashmap_internals)] #![feature(lang_items)] #![feature(min_specialization)] +#![feature(multiple_supertrait_upcastable)] #![feature(negative_impls)] #![feature(never_type)] +#![feature(pointer_is_aligned)] #![feature(rustc_allow_const_fn_unstable)] #![feature(rustc_attrs)] -#![feature(pointer_is_aligned)] #![feature(slice_internals)] #![feature(staged_api)] #![feature(stmt_expr_attributes)] -#![cfg_attr(test, feature(test))] #![feature(unboxed_closures)] #![feature(unsized_fn_params)] -#![feature(c_unwind)] #![feature(with_negative_coherence)] -#![cfg_attr(test, feature(panic_update_hook))] -#![feature(multiple_supertrait_upcastable)] +// tidy-alphabetical-end // // Rustdoc features: #![feature(doc_cfg)] diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 736b3c0497c4..289e9c3c5bf4 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -235,6 +235,7 @@ #![cfg_attr(windows, feature(round_char_boundary))] // // Language features: +// tidy-alphabetical-start #![feature(alloc_error_handler)] #![feature(allocator_internals)] #![feature(allow_internal_unsafe)] @@ -257,8 +258,8 @@ #![feature(is_terminal)] #![feature(lang_items)] #![feature(let_chains)] -#![feature(linkage)] #![feature(link_cfg)] +#![feature(linkage)] #![feature(min_specialization)] #![feature(must_not_suspend)] #![feature(needs_panic_runtime)] @@ -272,8 +273,10 @@ #![feature(thread_local)] #![feature(try_blocks)] #![feature(utf8_chunks)] +// tidy-alphabetical-end // // Library features (core): +// tidy-alphabetical-start #![feature(char_internals)] #![feature(core_intrinsics)] #![feature(duration_constants)] @@ -290,6 +293,7 @@ #![feature(ip)] #![feature(ip_in_core)] #![feature(maybe_uninit_slice)] +#![feature(maybe_uninit_uninit_array)] #![feature(maybe_uninit_write_slice)] #![feature(panic_can_unwind)] #![feature(panic_info_message)] @@ -307,25 +311,28 @@ #![feature(std_internals)] #![feature(str_internals)] #![feature(strict_provenance)] -#![feature(maybe_uninit_uninit_array)] -#![feature(const_maybe_uninit_uninit_array)] -#![feature(const_waker)] +// tidy-alphabetical-end // // Library features (alloc): +// tidy-alphabetical-start #![feature(alloc_layout_extra)] #![feature(allocator_api)] #![feature(get_mut_unchecked)] #![feature(map_try_insert)] #![feature(new_uninit)] +#![feature(slice_concat_trait)] #![feature(thin_box)] #![feature(try_reserve_kind)] #![feature(vec_into_raw_parts)] -#![feature(slice_concat_trait)] +// tidy-alphabetical-end // // Library features (unwind): +// tidy-alphabetical-start #![feature(panic_unwind)] +// tidy-alphabetical-end // // Only for re-exporting: +// tidy-alphabetical-start #![feature(assert_matches)] #![feature(async_iterator)] #![feature(c_variadic)] @@ -337,24 +344,29 @@ #![feature(custom_test_frameworks)] #![feature(edition_panic)] #![feature(format_args_nl)] -#![feature(log_syntax)] +#![feature(get_many_mut)] #![feature(lazy_cell)] +#![feature(log_syntax)] #![feature(saturating_int_impl)] #![feature(stdsimd)] #![feature(test)] #![feature(trace_macros)] -#![feature(get_many_mut)] +// tidy-alphabetical-end // // Only used in tests/benchmarks: // // Only for const-ness: +// tidy-alphabetical-start #![feature(const_collections_with_hasher)] #![feature(const_hash)] #![feature(const_io_structs)] #![feature(const_ip)] #![feature(const_ipv4)] #![feature(const_ipv6)] +#![feature(const_maybe_uninit_uninit_array)] +#![feature(const_waker)] #![feature(thread_local_internals)] +// tidy-alphabetical-end // #![default_lib_allocator] From 617648c43fb204213fefdbd903e3ed1452264b2a Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Thu, 13 Apr 2023 12:25:00 -0700 Subject: [PATCH 038/116] Update the mingw version note --- RELEASES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index 802637652832..b89178a6f68f 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -18,7 +18,7 @@ Language Compiler -------- -- [Upgrade mingw-w64 on CI to GCC 12.3.](https://github.com/rust-lang/rust/pull/100178/) +- [Upgrade `*-pc-windows-gnu` on CI to mingw-w64 v10 and GCC 12.2.](https://github.com/rust-lang/rust/pull/100178/) - [Rework min_choice algorithm of member constraints.](https://github.com/rust-lang/rust/pull/105300/) - [Support `true` and `false` as boolean flags in compiler arguments.](https://github.com/rust-lang/rust/pull/107043/) - [Default `repr(C)` enums to `c_int` size.](https://github.com/rust-lang/rust/pull/107592/) From 2179d9157ec0817ef0715f490382c6b95db355ee Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Thu, 13 Apr 2023 16:30:02 -0700 Subject: [PATCH 039/116] rustdoc-search: use ES6 `Map` for aliases instead of `Object` --- src/librustdoc/html/static/js/search.js | 27 +++++++++++++++---------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index c081578b8d4b..b0df5a28837d 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -191,7 +191,7 @@ function initSearch(rawSearchIndex) { */ let searchIndex; let currentResults; - const ALIASES = Object.create(null); + const ALIASES = new Map(); function isWhitespace(c) { return " \t\n\r".indexOf(c) !== -1; @@ -1424,22 +1424,22 @@ function initSearch(rawSearchIndex) { const aliases = []; const crateAliases = []; if (filterCrates !== null) { - if (ALIASES[filterCrates] && ALIASES[filterCrates][lowerQuery]) { - const query_aliases = ALIASES[filterCrates][lowerQuery]; + if (ALIASES.has(filterCrates) && ALIASES.get(filterCrates).has(lowerQuery)) { + const query_aliases = ALIASES.get(filterCrates).get(lowerQuery); for (const alias of query_aliases) { aliases.push(createAliasFromItem(searchIndex[alias])); } } } else { - Object.keys(ALIASES).forEach(crate => { - if (ALIASES[crate][lowerQuery]) { + for (const [crate, crateAliasesIndex] of ALIASES) { + if (crateAliasesIndex.has(lowerQuery)) { const pushTo = crate === currentCrate ? crateAliases : aliases; - const query_aliases = ALIASES[crate][lowerQuery]; + const query_aliases = crateAliasesIndex.get(lowerQuery); for (const alias of query_aliases) { pushTo.push(createAliasFromItem(searchIndex[alias])); } } - }); + } } const sortFunc = (aaa, bbb) => { @@ -2345,17 +2345,22 @@ function initSearch(rawSearchIndex) { } if (aliases) { - ALIASES[crate] = Object.create(null); + const currentCrateAliases = new Map(); + ALIASES.set(crate, currentCrateAliases); for (const alias_name in aliases) { if (!hasOwnPropertyRustdoc(aliases, alias_name)) { continue; } - if (!hasOwnPropertyRustdoc(ALIASES[crate], alias_name)) { - ALIASES[crate][alias_name] = []; + let currentNameAliases; + if (currentCrateAliases.has(alias_name)) { + currentNameAliases = currentCrateAliases.get(alias_name); + } else { + currentNameAliases = []; + currentCrateAliases.set(alias_name, currentNameAliases); } for (const local_alias of aliases[alias_name]) { - ALIASES[crate][alias_name].push(local_alias + currentIndex); + currentNameAliases.push(local_alias + currentIndex); } } } From e34dc7f437732861be7eb875f6d7b2213b046560 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Thu, 13 Apr 2023 16:48:07 -0700 Subject: [PATCH 040/116] rustdoc-search: use ES6 `Map` for generic matching instead of `Object` --- src/librustdoc/html/static/js/search.js | 37 ++++++++++--------------- 1 file changed, 14 insertions(+), 23 deletions(-) diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index b0df5a28837d..d19773f8d27b 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -1096,7 +1096,7 @@ function initSearch(rawSearchIndex) { // The names match, but we need to be sure that all generics kinda // match as well. if (elem.generics.length > 0 && row.generics.length >= elem.generics.length) { - const elems = Object.create(null); + const elems = new Map(); for (const entry of row.generics) { if (entry.name === "") { // Pure generic, needs to check into it. @@ -1106,39 +1106,30 @@ function initSearch(rawSearchIndex) { } continue; } - if (elems[entry.name] === undefined) { - elems[entry.name] = []; + let currentEntryElems; + if (elems.has(entry.name)) { + currentEntryElems = elems.get(entry.name); + } else { + currentEntryElems = []; + elems.set(entry.name, currentEntryElems); } - elems[entry.name].push(entry.ty); + currentEntryElems.push(entry.ty); } // We need to find the type that matches the most to remove it in order // to move forward. const handleGeneric = generic => { - let match = null; - if (elems[generic.name]) { - match = generic.name; - } else { - for (const elem_name in elems) { - if (!hasOwnPropertyRustdoc(elems, elem_name)) { - continue; - } - if (elem_name === generic) { - match = elem_name; - break; - } - } - } - if (match === null) { + if (!elems.has(generic.name)) { return false; } - const matchIdx = elems[match].findIndex(tmp_elem => + const matchElems = elems.get(generic.name); + const matchIdx = matchElems.findIndex(tmp_elem => typePassesFilter(generic.typeFilter, tmp_elem)); if (matchIdx === -1) { return false; } - elems[match].splice(matchIdx, 1); - if (elems[match].length === 0) { - delete elems[match]; + matchElems.splice(matchIdx, 1); + if (matchElems.length === 0) { + elems.delete(generic.name); } return true; }; From 8642c96a33bfc7470af01aabd1f9ad238178b8c4 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Thu, 13 Apr 2023 16:51:01 -0700 Subject: [PATCH 041/116] rustdoc-search: use ES6 `Set` for deduplication instead of `Object` --- src/librustdoc/html/static/js/search.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index d19773f8d27b..348af9505de8 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -906,7 +906,7 @@ function initSearch(rawSearchIndex) { const results_others = {}, results_in_args = {}, results_returned = {}; function transformResults(results) { - const duplicates = {}; + const duplicates = new Set(); const out = []; for (const result of results) { @@ -919,10 +919,10 @@ function initSearch(rawSearchIndex) { // To be sure than it some items aren't considered as duplicate. obj.fullPath += "|" + obj.ty; - if (duplicates[obj.fullPath]) { + if (duplicates.has(obj.fullPath)) { continue; } - duplicates[obj.fullPath] = true; + duplicates.add(obj.fullPath); obj.href = res[1]; out.push(obj); From 53f499d4752885cabcdecad22f76bfe1037ad41f Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Thu, 13 Apr 2023 17:05:12 -0700 Subject: [PATCH 042/116] rustdoc-search: use ES6 Map for `Result` instead of Object --- src/librustdoc/html/static/js/externs.js | 7 ++- src/librustdoc/html/static/js/search.js | 54 +++++++++++++++--------- 2 files changed, 40 insertions(+), 21 deletions(-) diff --git a/src/librustdoc/html/static/js/externs.js b/src/librustdoc/html/static/js/externs.js index ecbe15a59da3..4c81a0979c1a 100644 --- a/src/librustdoc/html/static/js/externs.js +++ b/src/librustdoc/html/static/js/externs.js @@ -65,6 +65,11 @@ let Row; */ let ResultsTable; +/** + * @typedef {Map} + */ +let Results; + /** * @typedef {{ * desc: string, @@ -80,7 +85,7 @@ let ResultsTable; * ty: number, * }} */ -let Results; +let ResultObject; /** * A pair of [inputs, outputs], or 0 for null. This is stored in the search index. diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index 348af9505de8..40cdc55bbc3b 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -903,8 +903,16 @@ function initSearch(rawSearchIndex) { * @return {ResultsTable} */ function execQuery(parsedQuery, searchWords, filterCrates, currentCrate) { - const results_others = {}, results_in_args = {}, results_returned = {}; + const results_others = new Map(), results_in_args = new Map(), + results_returned = new Map(); + /** + * Add extra data to result objects, and filter items that have been + * marked for removal. + * + * @param {[ResultObject]} results + * @returns {[ResultObject]} + */ function transformResults(results) { const duplicates = new Set(); const out = []; @@ -934,24 +942,30 @@ function initSearch(rawSearchIndex) { return out; } + /** + * This function takes a result map, and sorts it by various criteria, including edit + * distance, substring match, and the crate it comes from. + * + * @param {Results} results + * @param {boolean} isType + * @param {string} preferredCrate + * @returns {[ResultObject]} + */ function sortResults(results, isType, preferredCrate) { - const userQuery = parsedQuery.userQuery; - const ar = []; - for (const entry in results) { - if (hasOwnPropertyRustdoc(results, entry)) { - const result = results[entry]; - result.word = searchWords[result.id]; - result.item = searchIndex[result.id] || {}; - ar.push(result); - } - } - results = ar; // if there are no results then return to default and fail - if (results.length === 0) { + if (results.size === 0) { return []; } - results.sort((aaa, bbb) => { + const userQuery = parsedQuery.userQuery; + const result_list = []; + for (const result of results.values()) { + result.word = searchWords[result.id]; + result.item = searchIndex[result.id] || {}; + result_list.push(result); + } + + result_list.sort((aaa, bbb) => { let a, b; // sort by exact match with regard to the last word (mismatch goes later) @@ -1060,7 +1074,7 @@ function initSearch(rawSearchIndex) { nameSplit = hasPath ? null : parsedQuery.elems[0].path; } - for (const result of results) { + for (const result of result_list) { // this validation does not make sense when searching by types if (result.dontValidate) { continue; @@ -1073,7 +1087,7 @@ function initSearch(rawSearchIndex) { result.id = -1; } } - return transformResults(results); + return transformResults(result_list); } /** @@ -1487,19 +1501,19 @@ function initSearch(rawSearchIndex) { function addIntoResults(results, fullId, id, index, dist, path_dist, maxEditDistance) { const inBounds = dist <= maxEditDistance || index !== -1; if (dist === 0 || (!parsedQuery.literalSearch && inBounds)) { - if (results[fullId] !== undefined) { - const result = results[fullId]; + if (results.has(fullId)) { + const result = results.get(fullId); if (result.dontValidate || result.dist <= dist) { return; } } - results[fullId] = { + results.set(fullId, { id: id, index: index, dontValidate: parsedQuery.literalSearch, dist: dist, path_dist: path_dist, - }; + }); } } From 0aa958bab9b6a1e49e696dd2b1a5e89070eeffd5 Mon Sep 17 00:00:00 2001 From: est31 Date: Fri, 14 Apr 2023 04:55:27 +0200 Subject: [PATCH 043/116] Allow everyone to set the beta-nominated label It is allowed both in cargo and clippy's triagebot.toml, and nomination does not automatically mean that the PR will be backported. --- triagebot.toml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/triagebot.toml b/triagebot.toml index 2d7be7d12734..23e0ebb2466a 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -11,6 +11,7 @@ allow-unauthenticated = [ "S-*", "T-*", "WG-*", + "beta-nominated", "const-hack", "llvm-main", "needs-fcp", @@ -470,8 +471,8 @@ cc = ["@rust-lang/style"] [mentions."Cargo.lock"] message = """ -These commits modify the `Cargo.lock` file. Random changes to `Cargo.lock` can be introduced when switching branches and rebasing PRs. -This was probably unintentional and should be reverted before this PR is merged. +These commits modify the `Cargo.lock` file. Random changes to `Cargo.lock` can be introduced when switching branches and rebasing PRs. +This was probably unintentional and should be reverted before this PR is merged. If this was intentional then you can ignore this comment. """ From e404e77c0b148029f9903920d46362056c658be5 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Fri, 14 Apr 2023 07:28:56 +0000 Subject: [PATCH 044/116] Add a stable MIR way to get the main function --- compiler/rustc_smir/src/rustc_smir/mod.rs | 4 ++++ compiler/rustc_smir/src/stable_mir/mod.rs | 7 +++++++ tests/ui-fulldeps/stable-mir/crate-info.rs | 2 ++ 3 files changed, 13 insertions(+) diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 0befff894ef3..4dad3c6bce7f 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -40,6 +40,10 @@ pub fn all_local_items() -> stable_mir::CrateItems { with(|tcx| tcx.mir_keys(()).iter().map(|item| crate_item(item.to_def_id())).collect()) } +pub fn entry_fn() -> Option { + with(|tcx| Some(crate_item(tcx.entry_fn(())?.0))) +} + /// Build a stable mir crate from a given crate number. fn smir_crate(tcx: TyCtxt<'_>, crate_num: CrateNum) -> stable_mir::Crate { let crate_name = tcx.crate_name(crate_num).to_string(); diff --git a/compiler/rustc_smir/src/stable_mir/mod.rs b/compiler/rustc_smir/src/stable_mir/mod.rs index ba23186224a7..1d2efb5eab94 100644 --- a/compiler/rustc_smir/src/stable_mir/mod.rs +++ b/compiler/rustc_smir/src/stable_mir/mod.rs @@ -45,6 +45,13 @@ impl CrateItem { } } +/// Return the function where execution starts if the current +/// crate defines that. This is usually `main`, but could be +/// `start` if the crate is a no-std crate. +pub fn entry_fn() -> Option { + crate::rustc_smir::entry_fn() +} + /// Access to the local crate. pub fn local_crate() -> Crate { crate::rustc_smir::local_crate() diff --git a/tests/ui-fulldeps/stable-mir/crate-info.rs b/tests/ui-fulldeps/stable-mir/crate-info.rs index 03dab2350402..dfde8c97ec26 100644 --- a/tests/ui-fulldeps/stable-mir/crate-info.rs +++ b/tests/ui-fulldeps/stable-mir/crate-info.rs @@ -29,6 +29,8 @@ fn test_stable_mir(tcx: TyCtxt<'_>) { let local = stable_mir::local_crate(); assert_eq!(&local.name, CRATE_NAME); + assert_eq!(stable_mir::entry_fn(), None); + // Find items in the local crate. let items = stable_mir::all_local_items(); assert!(get_item(tcx, &items, (DefKind::Fn, "foo_bar")).is_some()); From b506d966a3e413f0d8f3a2fc470f941d7d8c471d Mon Sep 17 00:00:00 2001 From: Ezra Shaw Date: Fri, 14 Apr 2023 20:18:28 +1200 Subject: [PATCH 045/116] implement review suggestions --- .../src/traits/outlives_bounds.rs | 5 +++-- tests/ui/implied-bounds/issue-110161.rs | 12 +++++++----- tests/ui/implied-bounds/issue-110161.stderr | 4 ++-- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs index 64be4a55708a..5b8d9e7f0f75 100644 --- a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs @@ -56,11 +56,12 @@ impl<'a, 'tcx: 'a> InferCtxtExt<'a, 'tcx> for InferCtxt<'tcx> { let ty = self.resolve_vars_if_possible(ty); let ty = OpportunisticRegionResolver::new(self).fold_ty(ty); - // We must avoid processing constrained lifetime variables in implied + // We must avoid processing unconstrained lifetime variables in implied // bounds. See #110161 for context. + assert!(!ty.has_non_region_infer()); if ty.needs_infer() { self.tcx.sess.delay_span_bug( - self.tcx.source_span_untracked(body_id), + self.tcx.def_span(body_id), "skipped implied_outlives_bounds due to unconstrained lifetimes", ); return vec![]; diff --git a/tests/ui/implied-bounds/issue-110161.rs b/tests/ui/implied-bounds/issue-110161.rs index ca75026ffe84..e52c8356b52b 100644 --- a/tests/ui/implied-bounds/issue-110161.rs +++ b/tests/ui/implied-bounds/issue-110161.rs @@ -3,22 +3,24 @@ // compile-flags: --crate-type=lib -trait Trait { +trait LtTrait { type Ty; } // erroneous `Ty` impl -impl Trait for () { +impl LtTrait for () { //~^ ERROR not all trait items implemented, missing: `Ty` [E0046] } // `'lt` is not constrained by the erroneous `Ty` -impl<'lt, T> Trait for Box +impl<'lt, T> LtTrait for Box where - T: Trait, + T: LtTrait, { type Ty = &'lt (); } // unconstrained lifetime appears in implied bounds -fn test(_: as Trait>::Ty) {} +fn test(_: as LtTrait>::Ty) {} + +fn test2<'x>(_: &'x as LtTrait>::Ty) {} diff --git a/tests/ui/implied-bounds/issue-110161.stderr b/tests/ui/implied-bounds/issue-110161.stderr index c76b47376264..9e0188694ed9 100644 --- a/tests/ui/implied-bounds/issue-110161.stderr +++ b/tests/ui/implied-bounds/issue-110161.stderr @@ -4,8 +4,8 @@ error[E0046]: not all trait items implemented, missing: `Ty` LL | type Ty; | ------- `Ty` from trait ... -LL | impl Trait for () { - | ^^^^^^^^^^^^^^^^^ missing `Ty` in implementation +LL | impl LtTrait for () { + | ^^^^^^^^^^^^^^^^^^^ missing `Ty` in implementation error: aborting due to previous error From 18ca509e99cb3b7741e3d1124e59adb53f87f1ea Mon Sep 17 00:00:00 2001 From: Sergey Kaunov <65976143+skaunov@users.noreply.github.com> Date: Fri, 7 Apr 2023 13:18:31 +0300 Subject: [PATCH 046/116] Add links to docs to `Iterator` and couple of its methods --- library/std/src/collections/mod.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/library/std/src/collections/mod.rs b/library/std/src/collections/mod.rs index ae2baba09e68..75515d1f5d37 100644 --- a/library/std/src/collections/mod.rs +++ b/library/std/src/collections/mod.rs @@ -172,7 +172,8 @@ //! //! ## Iterators //! -//! Iterators are a powerful and robust mechanism used throughout Rust's +//! [Iterators][crate::iter] +//! are a powerful and robust mechanism used throughout Rust's //! standard libraries. Iterators provide a sequence of values in a generic, //! safe, efficient and convenient way. The contents of an iterator are usually //! *lazily* evaluated, so that only the values that are actually needed are @@ -252,7 +253,9 @@ //! //! Several other collection methods also return iterators to yield a sequence //! of results but avoid allocating an entire collection to store the result in. -//! This provides maximum flexibility as `collect` or `extend` can be called to +//! This provides maximum flexibility as +//! [`collect`][crate::iter::Iterator::collect] or +//! [`extend`][crate::iter::Extend::extend] can be called to //! "pipe" the sequence into any collection if desired. Otherwise, the sequence //! can be looped over with a `for` loop. The iterator can also be discarded //! after partial use, preventing the computation of the unused items. From 89281b3aa49702f456aab1b2808c62fb37b9cce3 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Thu, 13 Apr 2023 16:21:42 +0200 Subject: [PATCH 047/116] add pretty ignore reasons for llvm, cdb, gdb and lldb --- src/tools/compiletest/src/header.rs | 140 +++++++++++++++++++++------- 1 file changed, 107 insertions(+), 33 deletions(-) diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index 735351fbf605..bc90c413cfd7 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -934,6 +934,20 @@ pub fn make_test_description( } }; } + macro_rules! decision { + ($e:expr) => { + match $e { + IgnoreDecision::Ignore { reason } => { + ignore = true; + // The ignore reason must be a &'static str, so we have to leak memory to + // create it. This is fine, as the header is parsed only at the start of + // compiletest so it won't grow indefinitely. + ignore_message = Some(Box::leak(Box::::from(reason))); + } + IgnoreDecision::Continue => {} + } + }; + } { let parsed = parse_cfg_name_directive(config, ln, "ignore"); @@ -975,7 +989,11 @@ pub fn make_test_description( }; } - reason!(ignore_llvm(config, ln)); + decision!(ignore_llvm(config, ln)); + decision!(ignore_cdb(config, ln)); + decision!(ignore_gdb(config, ln)); + decision!(ignore_lldb(config, ln)); + reason!( config.run_clang_based_tests_with.is_none() && config.parse_needs_matching_clang(ln) ); @@ -1005,12 +1023,15 @@ pub fn make_test_description( config.target == "wasm32-unknown-unknown" && config.parse_name_directive(ln, directives::CHECK_RUN_RESULTS) ); - reason!(config.debugger == Some(Debugger::Cdb) && ignore_cdb(config, ln)); - reason!(config.debugger == Some(Debugger::Gdb) && ignore_gdb(config, ln)); - reason!(config.debugger == Some(Debugger::Lldb) && ignore_lldb(config, ln)); reason!(!has_rust_lld && config.parse_name_directive(ln, "needs-rust-lld")); reason!(config.parse_name_directive(ln, "needs-i686-dlltool") && !has_i686_dlltool()); reason!(config.parse_name_directive(ln, "needs-x86_64-dlltool") && !has_x86_64_dlltool()); + reason!( + config.parse_name_directive(ln, "rust-lldb") + && config.debugger == Some(Debugger::Lldb) + && !config.lldb_native_rust + ); + should_fail |= config.parse_name_directive(ln, "should-fail"); }); @@ -1044,22 +1065,34 @@ pub fn make_test_description( } } -fn ignore_cdb(config: &Config, line: &str) -> bool { +fn ignore_cdb(config: &Config, line: &str) -> IgnoreDecision { + if config.debugger != Some(Debugger::Cdb) { + return IgnoreDecision::Continue; + } + if let Some(actual_version) = config.cdb_version { - if let Some(min_version) = line.strip_prefix("min-cdb-version:").map(str::trim) { - let min_version = extract_cdb_version(min_version).unwrap_or_else(|| { - panic!("couldn't parse version range: {:?}", min_version); + if let Some(rest) = line.strip_prefix("min-cdb-version:").map(str::trim) { + let min_version = extract_cdb_version(rest).unwrap_or_else(|| { + panic!("couldn't parse version range: {:?}", rest); }); // Ignore if actual version is smaller than the minimum // required version - return actual_version < min_version; + if actual_version < min_version { + return IgnoreDecision::Ignore { + reason: format!("ignored when the CDB version is lower than {rest}"), + }; + } } } - false + IgnoreDecision::Continue } -fn ignore_gdb(config: &Config, line: &str) -> bool { +fn ignore_gdb(config: &Config, line: &str) -> IgnoreDecision { + if config.debugger != Some(Debugger::Gdb) { + return IgnoreDecision::Continue; + } + if let Some(actual_version) = config.gdb_version { if let Some(rest) = line.strip_prefix("min-gdb-version:").map(str::trim) { let (start_ver, end_ver) = extract_version_range(rest, extract_gdb_version) @@ -1072,7 +1105,11 @@ fn ignore_gdb(config: &Config, line: &str) -> bool { } // Ignore if actual version is smaller than the minimum // required version - return actual_version < start_ver; + if actual_version < start_ver { + return IgnoreDecision::Ignore { + reason: format!("ignored when the GDB version is lower than {rest}"), + }; + } } else if let Some(rest) = line.strip_prefix("ignore-gdb-version:").map(str::trim) { let (min_version, max_version) = extract_version_range(rest, extract_gdb_version) .unwrap_or_else(|| { @@ -1083,32 +1120,47 @@ fn ignore_gdb(config: &Config, line: &str) -> bool { panic!("Malformed GDB version range: max < min") } - return actual_version >= min_version && actual_version <= max_version; + if actual_version >= min_version && actual_version <= max_version { + if min_version == max_version { + return IgnoreDecision::Ignore { + reason: format!("ignored when the GDB version is {rest}"), + }; + } else { + return IgnoreDecision::Ignore { + reason: format!("ignored when the GDB version is between {rest}"), + }; + } + } } } - false + IgnoreDecision::Continue } -fn ignore_lldb(config: &Config, line: &str) -> bool { +fn ignore_lldb(config: &Config, line: &str) -> IgnoreDecision { + if config.debugger != Some(Debugger::Lldb) { + return IgnoreDecision::Continue; + } + if let Some(actual_version) = config.lldb_version { - if let Some(min_version) = line.strip_prefix("min-lldb-version:").map(str::trim) { - let min_version = min_version.parse().unwrap_or_else(|e| { - panic!("Unexpected format of LLDB version string: {}\n{:?}", min_version, e); + if let Some(rest) = line.strip_prefix("min-lldb-version:").map(str::trim) { + let min_version = rest.parse().unwrap_or_else(|e| { + panic!("Unexpected format of LLDB version string: {}\n{:?}", rest, e); }); // Ignore if actual version is smaller the minimum required // version - actual_version < min_version - } else { - line.starts_with("rust-lldb") && !config.lldb_native_rust + if actual_version < min_version { + return IgnoreDecision::Ignore { + reason: format!("ignored when the LLDB version is {rest}"), + }; + } } - } else { - false } + IgnoreDecision::Continue } -fn ignore_llvm(config: &Config, line: &str) -> bool { +fn ignore_llvm(config: &Config, line: &str) -> IgnoreDecision { if config.system_llvm && line.starts_with("no-system-llvm") { - return true; + return IgnoreDecision::Ignore { reason: "ignored when the system LLVM is used".into() }; } if let Some(needed_components) = config.parse_name_value_directive(line, "needs-llvm-components") @@ -1121,7 +1173,9 @@ fn ignore_llvm(config: &Config, line: &str) -> bool { if env::var_os("COMPILETEST_NEEDS_ALL_LLVM_COMPONENTS").is_some() { panic!("missing LLVM component: {}", missing_component); } - return true; + return IgnoreDecision::Ignore { + reason: format!("ignored when the {missing_component} LLVM component is missing"), + }; } } if let Some(actual_version) = config.llvm_version { @@ -1129,12 +1183,20 @@ fn ignore_llvm(config: &Config, line: &str) -> bool { let min_version = extract_llvm_version(rest).unwrap(); // Ignore if actual version is smaller the minimum required // version - actual_version < min_version + if actual_version < min_version { + return IgnoreDecision::Ignore { + reason: format!("ignored when the LLVM version is older than {rest}"), + }; + } } else if let Some(rest) = line.strip_prefix("min-system-llvm-version:").map(str::trim) { let min_version = extract_llvm_version(rest).unwrap(); // Ignore if using system LLVM and actual version // is smaller the minimum required version - config.system_llvm && actual_version < min_version + if config.system_llvm && actual_version < min_version { + return IgnoreDecision::Ignore { + reason: format!("ignored when the system LLVM version is older than {rest}"), + }; + } } else if let Some(rest) = line.strip_prefix("ignore-llvm-version:").map(str::trim) { // Syntax is: "ignore-llvm-version: [- ]" let (v_min, v_max) = @@ -1145,11 +1207,23 @@ fn ignore_llvm(config: &Config, line: &str) -> bool { panic!("Malformed LLVM version range: max < min") } // Ignore if version lies inside of range. - actual_version >= v_min && actual_version <= v_max - } else { - false + if actual_version >= v_min && actual_version <= v_max { + if v_min == v_max { + return IgnoreDecision::Ignore { + reason: format!("ignored when the LLVM version is {rest}"), + }; + } else { + return IgnoreDecision::Ignore { + reason: format!("ignored when the LLVM version is between {rest}"), + }; + } + } } - } else { - false } + IgnoreDecision::Continue +} + +enum IgnoreDecision { + Ignore { reason: String }, + Continue, } From aea43673f2efce50501e55c5186805cebc3deb4a Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Fri, 14 Apr 2023 11:36:09 +0200 Subject: [PATCH 048/116] refactor needs, validate them, and add ignore reasons --- src/tools/compiletest/src/header.rs | 128 +++--------- src/tools/compiletest/src/header/needs.rs | 226 ++++++++++++++++++++++ 2 files changed, 250 insertions(+), 104 deletions(-) create mode 100644 src/tools/compiletest/src/header/needs.rs diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index bc90c413cfd7..7613508077f4 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -11,10 +11,10 @@ use tracing::*; use crate::common::{Config, Debugger, FailMode, Mode, PassMode}; use crate::header::cfg::parse_cfg_name_directive; use crate::header::cfg::MatchOutcome; -use crate::util; use crate::{extract_cdb_version, extract_gdb_version}; mod cfg; +mod needs; #[cfg(test)] mod tests; @@ -660,14 +660,6 @@ impl Config { } } - fn parse_needs_matching_clang(&self, line: &str) -> bool { - self.parse_name_directive(line, "needs-matching-clang") - } - - fn parse_needs_profiler_support(&self, line: &str) -> bool { - self.parse_name_directive(line, "needs-profiler-support") - } - fn has_cfg_prefix(&self, line: &str, prefix: &str) -> bool { // returns whether this line contains this prefix or not. For prefix // "ignore", returns true if line says "ignore-x86_64", "ignore-arch", @@ -871,69 +863,13 @@ pub fn make_test_description( let mut ignore_message = None; let mut should_fail = false; - let rustc_has_profiler_support = env::var_os("RUSTC_PROFILER_SUPPORT").is_some(); - let rustc_has_sanitizer_support = env::var_os("RUSTC_SANITIZER_SUPPORT").is_some(); - let has_asm_support = config.has_asm_support(); - let has_asan = util::ASAN_SUPPORTED_TARGETS.contains(&&*config.target); - let has_cfi = util::CFI_SUPPORTED_TARGETS.contains(&&*config.target); - let has_kcfi = util::KCFI_SUPPORTED_TARGETS.contains(&&*config.target); - let has_kasan = util::KASAN_SUPPORTED_TARGETS.contains(&&*config.target); - let has_lsan = util::LSAN_SUPPORTED_TARGETS.contains(&&*config.target); - let has_msan = util::MSAN_SUPPORTED_TARGETS.contains(&&*config.target); - let has_tsan = util::TSAN_SUPPORTED_TARGETS.contains(&&*config.target); - let has_hwasan = util::HWASAN_SUPPORTED_TARGETS.contains(&&*config.target); - let has_memtag = util::MEMTAG_SUPPORTED_TARGETS.contains(&&*config.target); - let has_shadow_call_stack = util::SHADOWCALLSTACK_SUPPORTED_TARGETS.contains(&&*config.target); - let has_xray = util::XRAY_SUPPORTED_TARGETS.contains(&&*config.target); - - // For tests using the `needs-rust-lld` directive (e.g. for `-Zgcc-ld=lld`), we need to find - // whether `rust-lld` is present in the compiler under test. - // - // The --compile-lib-path is the path to host shared libraries, but depends on the OS. For - // example: - // - on linux, it can be /lib - // - on windows, it can be /bin - // - // However, `rust-lld` is only located under the lib path, so we look for it there. - let has_rust_lld = config - .compile_lib_path - .parent() - .expect("couldn't traverse to the parent of the specified --compile-lib-path") - .join("lib") - .join("rustlib") - .join(&config.target) - .join("bin") - .join(if config.host.contains("windows") { "rust-lld.exe" } else { "rust-lld" }) - .exists(); - - fn is_on_path(file: &'static str) -> impl Fn() -> bool { - move || env::split_paths(&env::var_os("PATH").unwrap()).any(|dir| dir.join(file).is_file()) - } - - // On Windows, dlltool.exe is used for all architectures. - #[cfg(windows)] - let (has_i686_dlltool, has_x86_64_dlltool) = - (is_on_path("dlltool.exe"), is_on_path("dlltool.exe")); - // For non-Windows, there are architecture specific dlltool binaries. - #[cfg(not(windows))] - let (has_i686_dlltool, has_x86_64_dlltool) = - (is_on_path("i686-w64-mingw32-dlltool"), is_on_path("x86_64-w64-mingw32-dlltool")); + let needs_cache = needs::CachedNeedsConditions::load(config); iter_header(path, src, &mut |revision, ln| { if revision.is_some() && revision != cfg { return; } - macro_rules! reason { - ($e:expr) => { - ignore |= match $e { - true => { - ignore_message = Some(stringify!($e)); - true - } - false => ignore, - } - }; - } + macro_rules! decision { ($e:expr) => { match $e { @@ -944,6 +880,10 @@ pub fn make_test_description( // compiletest so it won't grow indefinitely. ignore_message = Some(Box::leak(Box::::from(reason))); } + IgnoreDecision::Error { message } => { + eprintln!("error: {}: {message}", path.display()); + panic!(); + } IgnoreDecision::Continue => {} } }; @@ -989,48 +929,27 @@ pub fn make_test_description( }; } + decision!(needs::handle_needs(&needs_cache, config, ln)); decision!(ignore_llvm(config, ln)); decision!(ignore_cdb(config, ln)); decision!(ignore_gdb(config, ln)); decision!(ignore_lldb(config, ln)); - reason!( - config.run_clang_based_tests_with.is_none() && config.parse_needs_matching_clang(ln) - ); - reason!(!has_asm_support && config.parse_name_directive(ln, "needs-asm-support")); - reason!(!rustc_has_profiler_support && config.parse_needs_profiler_support(ln)); - reason!(!config.run_enabled() && config.parse_name_directive(ln, "needs-run-enabled")); - reason!( - !rustc_has_sanitizer_support - && config.parse_name_directive(ln, "needs-sanitizer-support") - ); - reason!(!has_asan && config.parse_name_directive(ln, "needs-sanitizer-address")); - reason!(!has_cfi && config.parse_name_directive(ln, "needs-sanitizer-cfi")); - reason!(!has_kcfi && config.parse_name_directive(ln, "needs-sanitizer-kcfi")); - reason!(!has_kasan && config.parse_name_directive(ln, "needs-sanitizer-kasan")); - reason!(!has_lsan && config.parse_name_directive(ln, "needs-sanitizer-leak")); - reason!(!has_msan && config.parse_name_directive(ln, "needs-sanitizer-memory")); - reason!(!has_tsan && config.parse_name_directive(ln, "needs-sanitizer-thread")); - reason!(!has_hwasan && config.parse_name_directive(ln, "needs-sanitizer-hwaddress")); - reason!(!has_memtag && config.parse_name_directive(ln, "needs-sanitizer-memtag")); - reason!( - !has_shadow_call_stack - && config.parse_name_directive(ln, "needs-sanitizer-shadow-call-stack") - ); - reason!(!config.can_unwind() && config.parse_name_directive(ln, "needs-unwind")); - reason!(!has_xray && config.parse_name_directive(ln, "needs-xray")); - reason!( - config.target == "wasm32-unknown-unknown" - && config.parse_name_directive(ln, directives::CHECK_RUN_RESULTS) - ); - reason!(!has_rust_lld && config.parse_name_directive(ln, "needs-rust-lld")); - reason!(config.parse_name_directive(ln, "needs-i686-dlltool") && !has_i686_dlltool()); - reason!(config.parse_name_directive(ln, "needs-x86_64-dlltool") && !has_x86_64_dlltool()); - reason!( - config.parse_name_directive(ln, "rust-lldb") - && config.debugger == Some(Debugger::Lldb) - && !config.lldb_native_rust - ); + if config.target == "wasm32-unknown-unknown" { + if config.parse_name_directive(ln, directives::CHECK_RUN_RESULTS) { + decision!(IgnoreDecision::Ignore { + reason: "ignored when checking the run results on WASM".into(), + }); + } + } + + if config.debugger == Some(Debugger::Lldb) && !config.lldb_native_rust { + if config.parse_name_directive(ln, "rust-lldb") { + decision!(IgnoreDecision::Ignore { + reason: "ignored on targets wihtout Rust's LLDB".into() + }); + } + } should_fail |= config.parse_name_directive(ln, "should-fail"); }); @@ -1226,4 +1145,5 @@ fn ignore_llvm(config: &Config, line: &str) -> IgnoreDecision { enum IgnoreDecision { Ignore { reason: String }, Continue, + Error { message: String }, } diff --git a/src/tools/compiletest/src/header/needs.rs b/src/tools/compiletest/src/header/needs.rs new file mode 100644 index 000000000000..9a7c4b86115e --- /dev/null +++ b/src/tools/compiletest/src/header/needs.rs @@ -0,0 +1,226 @@ +use crate::common::Config; +use crate::header::IgnoreDecision; +use crate::util; + +pub(super) fn handle_needs( + cache: &CachedNeedsConditions, + config: &Config, + ln: &str, +) -> IgnoreDecision { + // Note thet we intentionally still put the needs- prefix here to make the file show up when + // grepping for a directive name, even though we could technically strip that. + let needs = &[ + Need { + name: "needs-asm-support", + condition: config.has_asm_support(), + ignore_reason: "ignored on targets without inline assembly support", + }, + Need { + name: "needs-sanitizer-support", + condition: cache.sanitizer_support, + ignore_reason: "ignored on targets without sanitizers support", + }, + Need { + name: "needs-sanitizer-address", + condition: cache.sanitizer_address, + ignore_reason: "ignored on targets without address sanitizer", + }, + Need { + name: "needs-sanitizer-cfi", + condition: cache.sanitizer_cfi, + ignore_reason: "ignored on targets without CFI sanitizer", + }, + Need { + name: "needs-sanitizer-kcfi", + condition: cache.sanitizer_kcfi, + ignore_reason: "ignored on targets without kernel CFI sanitizer", + }, + Need { + name: "needs-sanitizer-kasan", + condition: cache.sanitizer_kasan, + ignore_reason: "ignored on targets without kernel address sanitizer", + }, + Need { + name: "needs-sanitizer-leak", + condition: cache.sanitizer_leak, + ignore_reason: "ignored on targets without leak sanitizer", + }, + Need { + name: "needs-sanitizer-memory", + condition: cache.sanitizer_memory, + ignore_reason: "ignored on targets without memory sanitizer", + }, + Need { + name: "needs-sanitizer-thread", + condition: cache.sanitizer_thread, + ignore_reason: "ignored on targets without thread sanitizer", + }, + Need { + name: "needs-sanitizer-hwaddress", + condition: cache.sanitizer_hwaddress, + ignore_reason: "ignored on targets without hardware-assisted address sanitizer", + }, + Need { + name: "needs-sanitizer-memtag", + condition: cache.sanitizer_memtag, + ignore_reason: "ignored on targets without memory tagging sanitizer", + }, + Need { + name: "needs-sanitizer-shadow-call-stack", + condition: cache.sanitizer_shadow_call_stack, + ignore_reason: "ignored on targets without shadow call stacks", + }, + Need { + name: "needs-run-enabled", + condition: config.run_enabled(), + ignore_reason: "ignored when running the resulting test binaries is disabled", + }, + Need { + name: "needs-unwind", + condition: config.can_unwind(), + ignore_reason: "ignored on targets without unwinding support", + }, + Need { + name: "needs-profiler-support", + condition: std::env::var_os("RUSTC_PROFILER_SUPPORT").is_some(), + ignore_reason: "ignored when profiler support is disabled", + }, + Need { + name: "needs-matching-clang", + condition: config.run_clang_based_tests_with.is_some(), + ignore_reason: "ignored when the used clang does not match the built LLVM", + }, + Need { + name: "needs-xray", + condition: cache.xray, + ignore_reason: "ignored on targets without xray tracing", + }, + Need { + name: "needs-rust-lld", + condition: cache.rust_lld, + ignore_reason: "ignored on targets without Rust's LLD", + }, + Need { + name: "needs-i686-dlltool", + condition: cache.i686_dlltool, + ignore_reason: "ignored when dlltool for i686 is not present", + }, + Need { + name: "needs-x86_64-dlltool", + condition: cache.x86_64_dlltool, + ignore_reason: "ignored when dlltool for x86_64 is not present", + }, + ]; + + let (name, comment) = match ln.split_once([':', ' ']) { + Some((name, comment)) => (name, Some(comment)), + None => (ln, None), + }; + + if !name.starts_with("needs-") { + return IgnoreDecision::Continue; + } + + let mut found_valid = false; + for need in needs { + if need.name == name { + if need.condition { + found_valid = true; + break; + } else { + return IgnoreDecision::Ignore { + reason: if let Some(comment) = comment { + format!("{} ({comment})", need.ignore_reason) + } else { + need.ignore_reason.into() + }, + }; + } + } + } + + if found_valid { + IgnoreDecision::Continue + } else { + IgnoreDecision::Error { message: format!("invalid needs directive: {name}") } + } +} + +struct Need { + name: &'static str, + condition: bool, + ignore_reason: &'static str, +} + +pub(super) struct CachedNeedsConditions { + sanitizer_support: bool, + sanitizer_address: bool, + sanitizer_cfi: bool, + sanitizer_kcfi: bool, + sanitizer_kasan: bool, + sanitizer_leak: bool, + sanitizer_memory: bool, + sanitizer_thread: bool, + sanitizer_hwaddress: bool, + sanitizer_memtag: bool, + sanitizer_shadow_call_stack: bool, + xray: bool, + rust_lld: bool, + i686_dlltool: bool, + x86_64_dlltool: bool, +} + +impl CachedNeedsConditions { + pub(super) fn load(config: &Config) -> Self { + let path = std::env::var_os("PATH").expect("missing PATH environment variable"); + let path = std::env::split_paths(&path).collect::>(); + + let target = &&*config.target; + Self { + sanitizer_support: std::env::var_os("RUSTC_SANITIZER_SUPPORT").is_some(), + sanitizer_address: util::ASAN_SUPPORTED_TARGETS.contains(target), + sanitizer_cfi: util::CFI_SUPPORTED_TARGETS.contains(target), + sanitizer_kcfi: util::KCFI_SUPPORTED_TARGETS.contains(target), + sanitizer_kasan: util::KASAN_SUPPORTED_TARGETS.contains(target), + sanitizer_leak: util::LSAN_SUPPORTED_TARGETS.contains(target), + sanitizer_memory: util::MSAN_SUPPORTED_TARGETS.contains(target), + sanitizer_thread: util::TSAN_SUPPORTED_TARGETS.contains(target), + sanitizer_hwaddress: util::HWASAN_SUPPORTED_TARGETS.contains(target), + sanitizer_memtag: util::MEMTAG_SUPPORTED_TARGETS.contains(target), + sanitizer_shadow_call_stack: util::SHADOWCALLSTACK_SUPPORTED_TARGETS.contains(target), + xray: util::XRAY_SUPPORTED_TARGETS.contains(target), + + // For tests using the `needs-rust-lld` directive (e.g. for `-Zgcc-ld=lld`), we need to find + // whether `rust-lld` is present in the compiler under test. + // + // The --compile-lib-path is the path to host shared libraries, but depends on the OS. For + // example: + // - on linux, it can be /lib + // - on windows, it can be /bin + // + // However, `rust-lld` is only located under the lib path, so we look for it there. + rust_lld: config + .compile_lib_path + .parent() + .expect("couldn't traverse to the parent of the specified --compile-lib-path") + .join("lib") + .join("rustlib") + .join(target) + .join("bin") + .join(if config.host.contains("windows") { "rust-lld.exe" } else { "rust-lld" }) + .exists(), + + // On Windows, dlltool.exe is used for all architectures. + #[cfg(windows)] + i686_dlltool: path.iter().any(|dir| dir.join("dlltool.exe").is_file()), + #[cfg(windows)] + x86_64_dlltool: path.iter().any(|dir| dir.join("dlltool.exe").is_file()), + + // For non-Windows, there are architecture specific dlltool binaries. + #[cfg(not(windows))] + i686_dlltool: path.iter().any(|dir| dir.join("i686-w64-mingw32-dlltool").is_file()), + #[cfg(not(windows))] + x86_64_dlltool: path.iter().any(|dir| dir.join("x86_64-w64-mingw32-dlltool").is_file()), + } + } +} From ffe4ccd4ad1a96239b82b700a626a3644ddc364d Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Fri, 14 Apr 2023 11:40:07 +0200 Subject: [PATCH 049/116] rename rust-lldb to needs-rust-lldb for consistency --- src/tools/compiletest/src/header.rs | 8 -------- src/tools/compiletest/src/header/needs.rs | 7 ++++++- tests/debuginfo/associated-types.rs | 2 +- tests/debuginfo/borrowed-enum.rs | 2 +- tests/debuginfo/generic-method-on-generic-struct.rs | 2 +- tests/debuginfo/generic-struct.rs | 2 +- tests/debuginfo/generic-tuple-style-enum.rs | 2 +- tests/debuginfo/method-on-generic-struct.rs | 2 +- tests/debuginfo/struct-style-enum.rs | 2 +- tests/debuginfo/tuple-style-enum.rs | 2 +- tests/debuginfo/unique-enum.rs | 2 +- 11 files changed, 15 insertions(+), 18 deletions(-) diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index 7613508077f4..ac659c894054 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -943,14 +943,6 @@ pub fn make_test_description( } } - if config.debugger == Some(Debugger::Lldb) && !config.lldb_native_rust { - if config.parse_name_directive(ln, "rust-lldb") { - decision!(IgnoreDecision::Ignore { - reason: "ignored on targets wihtout Rust's LLDB".into() - }); - } - } - should_fail |= config.parse_name_directive(ln, "should-fail"); }); diff --git a/src/tools/compiletest/src/header/needs.rs b/src/tools/compiletest/src/header/needs.rs index 9a7c4b86115e..8b42ef5db596 100644 --- a/src/tools/compiletest/src/header/needs.rs +++ b/src/tools/compiletest/src/header/needs.rs @@ -1,4 +1,4 @@ -use crate::common::Config; +use crate::common::{Config, Debugger}; use crate::header::IgnoreDecision; use crate::util; @@ -100,6 +100,11 @@ pub(super) fn handle_needs( condition: cache.rust_lld, ignore_reason: "ignored on targets without Rust's LLD", }, + Need { + name: "needs-rust-lldb", + condition: config.debugger != Some(Debugger::Lldb) || config.lldb_native_rust, + ignore_reason: "ignored on targets without Rust's LLDB", + }, Need { name: "needs-i686-dlltool", condition: cache.i686_dlltool, diff --git a/tests/debuginfo/associated-types.rs b/tests/debuginfo/associated-types.rs index 0a0ce3c671f0..a1735520b117 100644 --- a/tests/debuginfo/associated-types.rs +++ b/tests/debuginfo/associated-types.rs @@ -1,6 +1,6 @@ // Some versions of the non-rust-enabled LLDB print the wrong generic // parameter type names in this test. -// rust-lldb +// needs-rust-lldb // compile-flags:-g diff --git a/tests/debuginfo/borrowed-enum.rs b/tests/debuginfo/borrowed-enum.rs index f3e465dc652d..37d458cb494c 100644 --- a/tests/debuginfo/borrowed-enum.rs +++ b/tests/debuginfo/borrowed-enum.rs @@ -1,6 +1,6 @@ // Require a gdb or lldb that can read DW_TAG_variant_part. // min-gdb-version: 8.2 -// rust-lldb +// needs-rust-lldb // compile-flags:-g diff --git a/tests/debuginfo/generic-method-on-generic-struct.rs b/tests/debuginfo/generic-method-on-generic-struct.rs index 97609ef5d934..2d54c2b07df3 100644 --- a/tests/debuginfo/generic-method-on-generic-struct.rs +++ b/tests/debuginfo/generic-method-on-generic-struct.rs @@ -2,7 +2,7 @@ // Some versions of the non-rust-enabled LLDB print the wrong generic // parameter type names in this test. -// rust-lldb +// needs-rust-lldb // === GDB TESTS =================================================================================== diff --git a/tests/debuginfo/generic-struct.rs b/tests/debuginfo/generic-struct.rs index 5fa5ce800993..5213eebc18bd 100644 --- a/tests/debuginfo/generic-struct.rs +++ b/tests/debuginfo/generic-struct.rs @@ -1,6 +1,6 @@ // Some versions of the non-rust-enabled LLDB print the wrong generic // parameter type names in this test. -// rust-lldb +// needs-rust-lldb // compile-flags:-g diff --git a/tests/debuginfo/generic-tuple-style-enum.rs b/tests/debuginfo/generic-tuple-style-enum.rs index 60362e54e7db..a55402691dc3 100644 --- a/tests/debuginfo/generic-tuple-style-enum.rs +++ b/tests/debuginfo/generic-tuple-style-enum.rs @@ -1,6 +1,6 @@ // Require a gdb or lldb that can read DW_TAG_variant_part. // min-gdb-version: 8.2 -// rust-lldb +// needs-rust-lldb // compile-flags:-g diff --git a/tests/debuginfo/method-on-generic-struct.rs b/tests/debuginfo/method-on-generic-struct.rs index bf047449164b..138d8391d40a 100644 --- a/tests/debuginfo/method-on-generic-struct.rs +++ b/tests/debuginfo/method-on-generic-struct.rs @@ -1,6 +1,6 @@ // Some versions of the non-rust-enabled LLDB print the wrong generic // parameter type names in this test. -// rust-lldb +// needs-rust-lldb // compile-flags:-g diff --git a/tests/debuginfo/struct-style-enum.rs b/tests/debuginfo/struct-style-enum.rs index 3d819e368988..0152dd9ea9b1 100644 --- a/tests/debuginfo/struct-style-enum.rs +++ b/tests/debuginfo/struct-style-enum.rs @@ -1,6 +1,6 @@ // Require a gdb or lldb that can read DW_TAG_variant_part. // min-gdb-version: 8.2 -// rust-lldb +// needs-rust-lldb // compile-flags:-g diff --git a/tests/debuginfo/tuple-style-enum.rs b/tests/debuginfo/tuple-style-enum.rs index 39ead172e651..60f3ecbd21e2 100644 --- a/tests/debuginfo/tuple-style-enum.rs +++ b/tests/debuginfo/tuple-style-enum.rs @@ -1,6 +1,6 @@ // Require a gdb or lldb that can read DW_TAG_variant_part. // min-gdb-version: 8.2 -// rust-lldb +// needs-rust-lldb // compile-flags:-g diff --git a/tests/debuginfo/unique-enum.rs b/tests/debuginfo/unique-enum.rs index d7dfaeefe2b7..1ff6f5d9cbe1 100644 --- a/tests/debuginfo/unique-enum.rs +++ b/tests/debuginfo/unique-enum.rs @@ -1,6 +1,6 @@ // Require a gdb or lldb that can read DW_TAG_variant_part. // min-gdb-version: 8.2 -// rust-lldb +// needs-rust-lldb // compile-flags:-g From 55c07678cd80772be719416427f2986dd3524022 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Fri, 14 Apr 2023 11:57:22 +0200 Subject: [PATCH 050/116] refactor ignore- and only- to use decisions --- src/tools/compiletest/src/header.rs | 51 ++---------------------- src/tools/compiletest/src/header/cfg.rs | 52 ++++++++++++++++++++++--- 2 files changed, 50 insertions(+), 53 deletions(-) diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index ac659c894054..8d2fd881d26a 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -660,13 +660,6 @@ impl Config { } } - fn has_cfg_prefix(&self, line: &str, prefix: &str) -> bool { - // returns whether this line contains this prefix or not. For prefix - // "ignore", returns true if line says "ignore-x86_64", "ignore-arch", - // "ignore-android" etc. - line.starts_with(prefix) && line.as_bytes().get(prefix.len()) == Some(&b'-') - } - fn parse_name_directive(&self, line: &str, directive: &str) -> bool { // Ensure the directive is a whole word. Do not match "ignore-x86" when // the line says "ignore-x86_64". @@ -878,7 +871,7 @@ pub fn make_test_description( // The ignore reason must be a &'static str, so we have to leak memory to // create it. This is fine, as the header is parsed only at the start of // compiletest so it won't grow indefinitely. - ignore_message = Some(Box::leak(Box::::from(reason))); + ignore_message = Some(&*Box::leak(Box::::from(reason))); } IgnoreDecision::Error { message } => { eprintln!("error: {}: {message}", path.display()); @@ -889,46 +882,8 @@ pub fn make_test_description( }; } - { - let parsed = parse_cfg_name_directive(config, ln, "ignore"); - ignore = match parsed.outcome { - MatchOutcome::Match => { - let reason = parsed.pretty_reason.unwrap(); - // The ignore reason must be a &'static str, so we have to leak memory to - // create it. This is fine, as the header is parsed only at the start of - // compiletest so it won't grow indefinitely. - ignore_message = Some(Box::leak(Box::::from(match parsed.comment { - Some(comment) => format!("ignored {reason} ({comment})"), - None => format!("ignored {reason}"), - })) as &str); - true - } - MatchOutcome::NoMatch => ignore, - MatchOutcome::External => ignore, - MatchOutcome::Invalid => panic!("invalid line in {}: {ln}", path.display()), - }; - } - - if config.has_cfg_prefix(ln, "only") { - let parsed = parse_cfg_name_directive(config, ln, "only"); - ignore = match parsed.outcome { - MatchOutcome::Match => ignore, - MatchOutcome::NoMatch => { - let reason = parsed.pretty_reason.unwrap(); - // The ignore reason must be a &'static str, so we have to leak memory to - // create it. This is fine, as the header is parsed only at the start of - // compiletest so it won't grow indefinitely. - ignore_message = Some(Box::leak(Box::::from(match parsed.comment { - Some(comment) => format!("only executed {reason} ({comment})"), - None => format!("only executed {reason}"), - })) as &str); - true - } - MatchOutcome::External => ignore, - MatchOutcome::Invalid => panic!("invalid line in {}: {ln}", path.display()), - }; - } - + decision!(cfg::handle_ignore(config, ln)); + decision!(cfg::handle_only(config, ln)); decision!(needs::handle_needs(&needs_cache, config, ln)); decision!(ignore_llvm(config, ln)); decision!(ignore_cdb(config, ln)); diff --git a/src/tools/compiletest/src/header/cfg.rs b/src/tools/compiletest/src/header/cfg.rs index 3b9333dfe7a0..a9694d4d52c8 100644 --- a/src/tools/compiletest/src/header/cfg.rs +++ b/src/tools/compiletest/src/header/cfg.rs @@ -1,8 +1,43 @@ use crate::common::{CompareMode, Config, Debugger}; +use crate::header::IgnoreDecision; use std::collections::HashSet; const EXTRA_ARCHS: &[&str] = &["spirv"]; +pub(super) fn handle_ignore(config: &Config, line: &str) -> IgnoreDecision { + let parsed = parse_cfg_name_directive(config, line, "ignore"); + match parsed.outcome { + MatchOutcome::NoMatch => IgnoreDecision::Continue, + MatchOutcome::Match => IgnoreDecision::Ignore { + reason: match parsed.comment { + Some(comment) => format!("ignored {} ({comment})", parsed.pretty_reason.unwrap()), + None => format!("ignored {}", parsed.pretty_reason.unwrap()), + }, + }, + MatchOutcome::Invalid => IgnoreDecision::Error { message: format!("invalid line: {line}") }, + MatchOutcome::External => IgnoreDecision::Continue, + MatchOutcome::NotADirective => IgnoreDecision::Continue, + } +} + +pub(super) fn handle_only(config: &Config, line: &str) -> IgnoreDecision { + let parsed = parse_cfg_name_directive(config, line, "only"); + match parsed.outcome { + MatchOutcome::Match => IgnoreDecision::Continue, + MatchOutcome::NoMatch => IgnoreDecision::Ignore { + reason: match parsed.comment { + Some(comment) => { + format!("only executed {} ({comment})", parsed.pretty_reason.unwrap()) + } + None => format!("only executed {}", parsed.pretty_reason.unwrap()), + }, + }, + MatchOutcome::Invalid => IgnoreDecision::Error { message: format!("invalid line: {line}") }, + MatchOutcome::External => IgnoreDecision::Continue, + MatchOutcome::NotADirective => IgnoreDecision::Continue, + } +} + /// Parses a name-value directive which contains config-specific information, e.g., `ignore-x86` /// or `normalize-stderr-32bit`. pub(super) fn parse_cfg_name_directive<'a>( @@ -11,10 +46,10 @@ pub(super) fn parse_cfg_name_directive<'a>( prefix: &str, ) -> ParsedNameDirective<'a> { if !line.as_bytes().starts_with(prefix.as_bytes()) { - return ParsedNameDirective::invalid(); + return ParsedNameDirective::not_a_directive(); } if line.as_bytes().get(prefix.len()) != Some(&b'-') { - return ParsedNameDirective::invalid(); + return ParsedNameDirective::not_a_directive(); } let line = &line[prefix.len() + 1..]; @@ -24,7 +59,7 @@ pub(super) fn parse_cfg_name_directive<'a>( // Some of the matchers might be "" depending on what the target information is. To avoid // problems we outright reject empty directives. if name == "" { - return ParsedNameDirective::invalid(); + return ParsedNameDirective::not_a_directive(); } let mut outcome = MatchOutcome::Invalid; @@ -218,8 +253,13 @@ pub(super) struct ParsedNameDirective<'a> { } impl ParsedNameDirective<'_> { - fn invalid() -> Self { - Self { name: None, pretty_reason: None, comment: None, outcome: MatchOutcome::NoMatch } + fn not_a_directive() -> Self { + Self { + name: None, + pretty_reason: None, + comment: None, + outcome: MatchOutcome::NotADirective, + } } } @@ -233,6 +273,8 @@ pub(super) enum MatchOutcome { Invalid, /// The directive is handled by other parts of our tooling. External, + /// The line is not actually a directive. + NotADirective, } trait CustomContains { From 741a0ec8429424e10689a1da24820bc4c84f1bcc Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Fri, 14 Apr 2023 12:07:36 +0200 Subject: [PATCH 051/116] show all invalid directives errors rather than just the first one --- src/tools/compiletest/src/header.rs | 4 +++- src/tools/compiletest/src/header/tests.rs | 18 +++++++++++++++++- src/tools/compiletest/src/main.rs | 19 ++++++++++++++++--- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index 8d2fd881d26a..a83cf33589f4 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -851,6 +851,7 @@ pub fn make_test_description( path: &Path, src: R, cfg: Option<&str>, + poisoned: &mut bool, ) -> test::TestDesc { let mut ignore = false; let mut ignore_message = None; @@ -875,7 +876,8 @@ pub fn make_test_description( } IgnoreDecision::Error { message } => { eprintln!("error: {}: {message}", path.display()); - panic!(); + *poisoned = true; + return; } IgnoreDecision::Continue => {} } diff --git a/src/tools/compiletest/src/header/tests.rs b/src/tools/compiletest/src/header/tests.rs index acd588d7fee0..8ee8aa144019 100644 --- a/src/tools/compiletest/src/header/tests.rs +++ b/src/tools/compiletest/src/header/tests.rs @@ -1,7 +1,23 @@ +use std::io::Read; use std::path::Path; use crate::common::{Config, Debugger}; -use crate::header::{make_test_description, parse_normalization_string, EarlyProps}; +use crate::header::{parse_normalization_string, EarlyProps}; + +fn make_test_description( + config: &Config, + name: test::TestName, + path: &Path, + src: R, + cfg: Option<&str>, +) -> test::TestDesc { + let mut poisoned = false; + let test = crate::header::make_test_description(config, name, path, src, cfg, &mut poisoned); + if poisoned { + panic!("poisoned!"); + } + test +} #[test] fn test_parse_normalization_string() { diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index cfb1ee34f679..5bffd05dbd5f 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -555,6 +555,8 @@ pub fn make_tests( let modified_tests = modified_tests(&config, &config.src_base).unwrap_or_else(|err| { panic!("modified_tests got error from dir: {}, error: {}", config.src_base.display(), err) }); + + let mut poisoned = false; collect_tests_from_dir( config.clone(), &config.src_base, @@ -563,8 +565,14 @@ pub fn make_tests( tests, found_paths, &modified_tests, + &mut poisoned, ) .unwrap_or_else(|_| panic!("Could not read tests from {}", config.src_base.display())); + + if poisoned { + eprintln!(); + panic!("there are errors in tests"); + } } /// Returns a stamp constructed from input files common to all test cases. @@ -634,6 +642,7 @@ fn collect_tests_from_dir( tests: &mut Vec, found_paths: &mut BTreeSet, modified_tests: &Vec, + poisoned: &mut bool, ) -> io::Result<()> { // Ignore directories that contain a file named `compiletest-ignore-dir`. if dir.join("compiletest-ignore-dir").exists() { @@ -645,7 +654,7 @@ fn collect_tests_from_dir( file: dir.to_path_buf(), relative_dir: relative_dir_path.parent().unwrap().to_path_buf(), }; - tests.extend(make_test(config, &paths, inputs)); + tests.extend(make_test(config, &paths, inputs, poisoned)); return Ok(()); } @@ -671,7 +680,7 @@ fn collect_tests_from_dir( let paths = TestPaths { file: file_path, relative_dir: relative_dir_path.to_path_buf() }; - tests.extend(make_test(config.clone(), &paths, inputs)) + tests.extend(make_test(config.clone(), &paths, inputs, poisoned)) } else if file_path.is_dir() { let relative_file_path = relative_dir_path.join(file.file_name()); if &file_name != "auxiliary" { @@ -684,6 +693,7 @@ fn collect_tests_from_dir( tests, found_paths, modified_tests, + poisoned, )?; } } else { @@ -710,6 +720,7 @@ fn make_test( config: Arc, testpaths: &TestPaths, inputs: &Stamp, + poisoned: &mut bool, ) -> Vec { let test_path = if config.mode == Mode::RunMake { // Parse directives in the Makefile @@ -726,6 +737,7 @@ fn make_test( } else { early_props.revisions.iter().map(Some).collect() }; + revisions .into_iter() .map(|revision| { @@ -733,7 +745,8 @@ fn make_test( std::fs::File::open(&test_path).expect("open test file to parse ignores"); let cfg = revision.map(|v| &**v); let test_name = crate::make_test_name(&config, testpaths, revision); - let mut desc = make_test_description(&config, test_name, &test_path, src_file, cfg); + let mut desc = + make_test_description(&config, test_name, &test_path, src_file, cfg, poisoned); // Ignore tests that already run and are up to date with respect to inputs. if !config.force_rerun { desc.ignore |= is_up_to_date( From 0f364ac3821a58411407f2fd1547ae823f8f0143 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Fri, 14 Apr 2023 12:09:57 +0200 Subject: [PATCH 052/116] add line numbers to error messages --- src/tools/compiletest/src/header.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index a83cf33589f4..91a23776de72 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -35,7 +35,7 @@ impl EarlyProps { pub fn from_reader(config: &Config, testfile: &Path, rdr: R) -> Self { let mut props = EarlyProps::default(); - iter_header(testfile, rdr, &mut |_, ln| { + iter_header(testfile, rdr, &mut |_, ln, _| { config.push_name_value_directive(ln, directives::AUX_BUILD, &mut props.aux, |r| { r.trim().to_string() }); @@ -283,7 +283,7 @@ impl TestProps { if !testfile.is_dir() { let file = File::open(testfile).unwrap(); - iter_header(testfile, file, &mut |revision, ln| { + iter_header(testfile, file, &mut |revision, ln, _| { if revision.is_some() && revision != cfg { return; } @@ -577,7 +577,7 @@ pub fn line_directive<'line>( } } -fn iter_header(testfile: &Path, rdr: R, it: &mut dyn FnMut(Option<&str>, &str)) { +fn iter_header(testfile: &Path, rdr: R, it: &mut dyn FnMut(Option<&str>, &str, usize)) { if testfile.is_dir() { return; } @@ -586,8 +586,10 @@ fn iter_header(testfile: &Path, rdr: R, it: &mut dyn FnMut(Option<&str> let mut rdr = BufReader::new(rdr); let mut ln = String::new(); + let mut line_number = 0; loop { + line_number += 1; ln.clear(); if rdr.read_line(&mut ln).unwrap() == 0 { break; @@ -600,7 +602,7 @@ fn iter_header(testfile: &Path, rdr: R, it: &mut dyn FnMut(Option<&str> if ln.starts_with("fn") || ln.starts_with("mod") { return; } else if let Some((lncfg, ln)) = line_directive(comment, ln) { - it(lncfg, ln); + it(lncfg, ln, line_number); } } } @@ -859,7 +861,7 @@ pub fn make_test_description( let needs_cache = needs::CachedNeedsConditions::load(config); - iter_header(path, src, &mut |revision, ln| { + iter_header(path, src, &mut |revision, ln, line_number| { if revision.is_some() && revision != cfg { return; } @@ -875,7 +877,7 @@ pub fn make_test_description( ignore_message = Some(&*Box::leak(Box::::from(reason))); } IgnoreDecision::Error { message } => { - eprintln!("error: {}: {message}", path.display()); + eprintln!("error: {}:{line_number}: {message}", path.display()); *poisoned = true; return; } From 0f8a06b6c070b2c79228fcb6cd0dc210fcb7869a Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Fri, 14 Apr 2023 12:14:19 +0200 Subject: [PATCH 053/116] use a shared headers cache --- src/tools/compiletest/src/header.rs | 16 +++++++++++++--- src/tools/compiletest/src/header/tests.rs | 6 ++++-- src/tools/compiletest/src/main.rs | 15 +++++++++++---- 3 files changed, 28 insertions(+), 9 deletions(-) diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index 91a23776de72..02382f8d4c64 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -11,6 +11,7 @@ use tracing::*; use crate::common::{Config, Debugger, FailMode, Mode, PassMode}; use crate::header::cfg::parse_cfg_name_directive; use crate::header::cfg::MatchOutcome; +use crate::header::needs::CachedNeedsConditions; use crate::{extract_cdb_version, extract_gdb_version}; mod cfg; @@ -18,6 +19,16 @@ mod needs; #[cfg(test)] mod tests; +pub struct HeadersCache { + needs: CachedNeedsConditions, +} + +impl HeadersCache { + pub fn load(config: &Config) -> Self { + Self { needs: CachedNeedsConditions::load(config) } + } +} + /// Properties which must be known very early, before actually running /// the test. #[derive(Default)] @@ -849,6 +860,7 @@ where pub fn make_test_description( config: &Config, + cache: &HeadersCache, name: test::TestName, path: &Path, src: R, @@ -859,8 +871,6 @@ pub fn make_test_description( let mut ignore_message = None; let mut should_fail = false; - let needs_cache = needs::CachedNeedsConditions::load(config); - iter_header(path, src, &mut |revision, ln, line_number| { if revision.is_some() && revision != cfg { return; @@ -888,7 +898,7 @@ pub fn make_test_description( decision!(cfg::handle_ignore(config, ln)); decision!(cfg::handle_only(config, ln)); - decision!(needs::handle_needs(&needs_cache, config, ln)); + decision!(needs::handle_needs(&cache.needs, config, ln)); decision!(ignore_llvm(config, ln)); decision!(ignore_cdb(config, ln)); decision!(ignore_gdb(config, ln)); diff --git a/src/tools/compiletest/src/header/tests.rs b/src/tools/compiletest/src/header/tests.rs index 8ee8aa144019..9af7bd5e2014 100644 --- a/src/tools/compiletest/src/header/tests.rs +++ b/src/tools/compiletest/src/header/tests.rs @@ -2,7 +2,7 @@ use std::io::Read; use std::path::Path; use crate::common::{Config, Debugger}; -use crate::header::{parse_normalization_string, EarlyProps}; +use crate::header::{parse_normalization_string, EarlyProps, HeadersCache}; fn make_test_description( config: &Config, @@ -11,8 +11,10 @@ fn make_test_description( src: R, cfg: Option<&str>, ) -> test::TestDesc { + let cache = HeadersCache::load(config); let mut poisoned = false; - let test = crate::header::make_test_description(config, name, path, src, cfg, &mut poisoned); + let test = + crate::header::make_test_description(config, &cache, name, path, src, cfg, &mut poisoned); if poisoned { panic!("poisoned!"); } diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index 5bffd05dbd5f..0e49822c1b7c 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -25,6 +25,7 @@ use tracing::*; use walkdir::WalkDir; use self::header::{make_test_description, EarlyProps}; +use crate::header::HeadersCache; use std::sync::Arc; #[cfg(test)] @@ -556,9 +557,11 @@ pub fn make_tests( panic!("modified_tests got error from dir: {}, error: {}", config.src_base.display(), err) }); + let cache = HeadersCache::load(&config); let mut poisoned = false; collect_tests_from_dir( config.clone(), + &cache, &config.src_base, &PathBuf::new(), &inputs, @@ -636,6 +639,7 @@ fn modified_tests(config: &Config, dir: &Path) -> Result, String> { fn collect_tests_from_dir( config: Arc, + cache: &HeadersCache, dir: &Path, relative_dir_path: &Path, inputs: &Stamp, @@ -654,7 +658,7 @@ fn collect_tests_from_dir( file: dir.to_path_buf(), relative_dir: relative_dir_path.parent().unwrap().to_path_buf(), }; - tests.extend(make_test(config, &paths, inputs, poisoned)); + tests.extend(make_test(config, cache, &paths, inputs, poisoned)); return Ok(()); } @@ -680,13 +684,14 @@ fn collect_tests_from_dir( let paths = TestPaths { file: file_path, relative_dir: relative_dir_path.to_path_buf() }; - tests.extend(make_test(config.clone(), &paths, inputs, poisoned)) + tests.extend(make_test(config.clone(), cache, &paths, inputs, poisoned)) } else if file_path.is_dir() { let relative_file_path = relative_dir_path.join(file.file_name()); if &file_name != "auxiliary" { debug!("found directory: {:?}", file_path.display()); collect_tests_from_dir( config.clone(), + cache, &file_path, &relative_file_path, inputs, @@ -718,6 +723,7 @@ pub fn is_test(file_name: &OsString) -> bool { fn make_test( config: Arc, + cache: &HeadersCache, testpaths: &TestPaths, inputs: &Stamp, poisoned: &mut bool, @@ -745,8 +751,9 @@ fn make_test( std::fs::File::open(&test_path).expect("open test file to parse ignores"); let cfg = revision.map(|v| &**v); let test_name = crate::make_test_name(&config, testpaths, revision); - let mut desc = - make_test_description(&config, test_name, &test_path, src_file, cfg, poisoned); + let mut desc = make_test_description( + &config, cache, test_name, &test_path, src_file, cfg, poisoned, + ); // Ignore tests that already run and are up to date with respect to inputs. if !config.force_rerun { desc.ignore |= is_up_to_date( From 34a52dfc7a8a650d940fac1a6258c7a4fb2ae19a Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Fri, 14 Apr 2023 12:15:17 +0200 Subject: [PATCH 054/116] mark needs-llvm-components as being handled elsewhere --- src/tools/compiletest/src/header/needs.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/tools/compiletest/src/header/needs.rs b/src/tools/compiletest/src/header/needs.rs index 8b42ef5db596..35d6179abaa6 100644 --- a/src/tools/compiletest/src/header/needs.rs +++ b/src/tools/compiletest/src/header/needs.rs @@ -126,6 +126,11 @@ pub(super) fn handle_needs( return IgnoreDecision::Continue; } + // Handled elsewhere. + if name == "needs-llvm-components" { + return IgnoreDecision::Continue; + } + let mut found_valid = false; for need in needs { if need.name == name { From 64fbdc37799b44a85a2dd6cb491ee96e6931cb5d Mon Sep 17 00:00:00 2001 From: lcnr Date: Fri, 14 Apr 2023 15:44:05 +0200 Subject: [PATCH 055/116] explicit adt_dtorck_constraint for ManuallyDrop --- compiler/rustc_traits/src/dropck_outlives.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_traits/src/dropck_outlives.rs b/compiler/rustc_traits/src/dropck_outlives.rs index b5924e949146..58117c46f043 100644 --- a/compiler/rustc_traits/src/dropck_outlives.rs +++ b/compiler/rustc_traits/src/dropck_outlives.rs @@ -292,7 +292,9 @@ pub(crate) fn adt_dtorck_constraint( let span = tcx.def_span(def_id); debug!("dtorck_constraint: {:?}", def); - if def.is_phantom_data() { + if def.is_manually_drop() { + bug!("`ManuallyDrop` should have been handled by `trivial_dropck_outlives`"); + } else if def.is_phantom_data() { // The first generic parameter here is guaranteed to be a type because it's // `PhantomData`. let substs = InternalSubsts::identity_for_item(tcx, def_id); From 6e17349b12ee5c8c76c742f4be96f6eba60a8a93 Mon Sep 17 00:00:00 2001 From: Alex Chi Date: Sun, 12 Mar 2023 21:10:11 -0400 Subject: [PATCH 056/116] suggest lifetime for closure parameter type when mismatch --- .../src/infer/error_reporting/mod.rs | 1 + .../src/infer/error_reporting/suggest.rs | 58 ++++++++++++++++++- tests/ui/lifetimes/issue-79187-2.stderr | 4 ++ tests/ui/lifetimes/issue-79187.stderr | 4 ++ tests/ui/mismatched_types/closure-mismatch.rs | 3 + .../mismatched_types/closure-mismatch.stderr | 38 +++++++++++- 6 files changed, 106 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 9e5f6d107d13..721842772229 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -1927,6 +1927,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { { let span = self.tcx.def_span(def_id); diag.span_note(span, "this closure does not fulfill the lifetime requirements"); + self.suggest_for_all_lifetime_closure(span, &exp_found, diag); } // It reads better to have the error origin as the final diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index b5aeca12a1f0..3755d80874c2 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -8,7 +8,7 @@ use rustc_middle::traits::{ StatementAsExpression, }; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::{self as ty, IsSuggestable, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self as ty, GenericArgKind, IsSuggestable, Ty, TypeVisitableExt}; use rustc_span::{sym, BytePos, Span}; use rustc_target::abi::FieldIdx; @@ -536,6 +536,62 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } None } + + /// For "one type is more general than the other" errors on closures, suggest changing the lifetime + /// of the parameters to accept all lifetimes. + pub(super) fn suggest_for_all_lifetime_closure( + &self, + span: Span, + exp_found: &ty::error::ExpectedFound>, + diag: &mut Diagnostic, + ) { + // 1. Get the substs of the closure. + // 2. Assume exp_found is FnOnce / FnMut / Fn, we can extract function parameters from [1]. + let expected = exp_found.expected.map_bound(|x| x.substs.get(1).cloned()).transpose(); + let found = exp_found.found.map_bound(|x| x.substs.get(1).cloned()).transpose(); + + // 3. Extract the tuple type from Fn trait and suggest the change. + if let (Some(expected), Some(found)) = (expected, found) { + let expected = expected.skip_binder().unpack(); + let found = found.skip_binder().unpack(); + if let (GenericArgKind::Type(expected), GenericArgKind::Type(found)) = (expected, found) + && let (ty::Tuple(expected), ty::Tuple(found)) = (expected.kind(), found.kind()) + && expected.len() == found.len() { + let mut suggestion = "|".to_string(); + let mut is_first = true; + let mut has_suggestion = false; + + for (expected, found) in expected.iter().zip(found.iter()) { + if is_first { + is_first = true; + } else { + suggestion += ", "; + } + + if let (ty::Ref(expected_region, _, _), ty::Ref(found_region, _, _)) = (expected.kind(), found.kind()) + && expected_region.is_late_bound() && !found_region.is_late_bound() { + // If the expected region is late bound, and the found region is not, we can suggest adding `: &_`. + // FIXME: use the actual type + variable name provided by user instead of `_`. + suggestion += "_: &_"; + has_suggestion = true; + } else { + // Otherwise, keep it as-is. + suggestion += "_"; + } + } + suggestion += "|"; + + if has_suggestion { + diag.span_suggestion_verbose( + span, + "consider changing the type of the closure parameters", + suggestion, + Applicability::MaybeIncorrect, + ); + } + } + } + } } impl<'tcx> TypeErrCtxt<'_, 'tcx> { diff --git a/tests/ui/lifetimes/issue-79187-2.stderr b/tests/ui/lifetimes/issue-79187-2.stderr index c5f654b37bf6..c14d3e0c61b8 100644 --- a/tests/ui/lifetimes/issue-79187-2.stderr +++ b/tests/ui/lifetimes/issue-79187-2.stderr @@ -43,6 +43,10 @@ note: the lifetime requirement is introduced here | LL | fn take_foo(_: impl Foo) {} | ^^^ +help: consider changing the type of the closure parameters + | +LL | take_foo(|_: &_| a); + | ~~~~~~~ error[E0308]: mismatched types --> $DIR/issue-79187-2.rs:11:5 diff --git a/tests/ui/lifetimes/issue-79187.stderr b/tests/ui/lifetimes/issue-79187.stderr index ee6e7b89d5f0..16eaf654cf3f 100644 --- a/tests/ui/lifetimes/issue-79187.stderr +++ b/tests/ui/lifetimes/issue-79187.stderr @@ -16,6 +16,10 @@ note: the lifetime requirement is introduced here | LL | fn thing(x: impl FnOnce(&u32)) {} | ^^^^^^^^^^^^ +help: consider changing the type of the closure parameters + | +LL | let f = |_: &_| (); + | ~~~~~~~ error: implementation of `FnOnce` is not general enough --> $DIR/issue-79187.rs:5:5 diff --git a/tests/ui/mismatched_types/closure-mismatch.rs b/tests/ui/mismatched_types/closure-mismatch.rs index b0644e79611f..4eb33497c395 100644 --- a/tests/ui/mismatched_types/closure-mismatch.rs +++ b/tests/ui/mismatched_types/closure-mismatch.rs @@ -8,4 +8,7 @@ fn main() { baz(|_| ()); //~^ ERROR implementation of `FnOnce` is not general enough //~| ERROR mismatched types + baz(|x| ()); + //~^ ERROR implementation of `FnOnce` is not general enough + //~| ERROR mismatched types } diff --git a/tests/ui/mismatched_types/closure-mismatch.stderr b/tests/ui/mismatched_types/closure-mismatch.stderr index a7ef8fa08923..ab0e137418ae 100644 --- a/tests/ui/mismatched_types/closure-mismatch.stderr +++ b/tests/ui/mismatched_types/closure-mismatch.stderr @@ -25,7 +25,43 @@ note: the lifetime requirement is introduced here | LL | fn baz(_: T) {} | ^^^ +help: consider changing the type of the closure parameters + | +LL | baz(|_: &_| ()); + | ~~~~~~~ -error: aborting due to 2 previous errors +error: implementation of `FnOnce` is not general enough + --> $DIR/closure-mismatch.rs:11:5 + | +LL | baz(|x| ()); + | ^^^^^^^^^^^ implementation of `FnOnce` is not general enough + | + = note: closure with signature `fn(&'2 ())` must implement `FnOnce<(&'1 (),)>`, for any lifetime `'1`... + = note: ...but it actually implements `FnOnce<(&'2 (),)>`, for some specific lifetime `'2` + +error[E0308]: mismatched types + --> $DIR/closure-mismatch.rs:11:5 + | +LL | baz(|x| ()); + | ^^^^^^^^^^^ one type is more general than the other + | + = note: expected trait `for<'a> Fn<(&'a (),)>` + found trait `Fn<(&(),)>` +note: this closure does not fulfill the lifetime requirements + --> $DIR/closure-mismatch.rs:11:9 + | +LL | baz(|x| ()); + | ^^^ +note: the lifetime requirement is introduced here + --> $DIR/closure-mismatch.rs:5:11 + | +LL | fn baz(_: T) {} + | ^^^ +help: consider changing the type of the closure parameters + | +LL | baz(|_: &_| ()); + | ~~~~~~~ + +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0308`. From 54c11a688f38a979e789fa50592088654ed56680 Mon Sep 17 00:00:00 2001 From: Alex Chi Date: Fri, 17 Mar 2023 22:22:49 -0400 Subject: [PATCH 057/116] better suggestion based on hir Signed-off-by: Alex Chi --- .../src/infer/error_reporting/mod.rs | 2 +- .../src/infer/error_reporting/suggest.rs | 88 ++++++------ tests/ui/lifetimes/issue-105675.rs | 16 +++ tests/ui/lifetimes/issue-105675.stderr | 131 ++++++++++++++++++ tests/ui/lifetimes/issue-79187.stderr | 2 +- .../mismatched_types/closure-mismatch.stderr | 6 +- 6 files changed, 200 insertions(+), 45 deletions(-) create mode 100644 tests/ui/lifetimes/issue-105675.rs create mode 100644 tests/ui/lifetimes/issue-105675.stderr diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 721842772229..992b07db1543 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -1927,7 +1927,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { { let span = self.tcx.def_span(def_id); diag.span_note(span, "this closure does not fulfill the lifetime requirements"); - self.suggest_for_all_lifetime_closure(span, &exp_found, diag); + self.suggest_for_all_lifetime_closure(span, self.tcx.hir().get_by_def_id(def_id), &exp_found, diag); } // It reads better to have the error origin as the final diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index 3755d80874c2..ec0aa77cef38 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -542,54 +542,62 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { pub(super) fn suggest_for_all_lifetime_closure( &self, span: Span, + hir: hir::Node<'_>, exp_found: &ty::error::ExpectedFound>, diag: &mut Diagnostic, ) { + // 0. Extract fn_decl from hir + let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(hir::Closure { fn_decl, .. }), .. }) = hir else { return; }; + // 1. Get the substs of the closure. // 2. Assume exp_found is FnOnce / FnMut / Fn, we can extract function parameters from [1]. - let expected = exp_found.expected.map_bound(|x| x.substs.get(1).cloned()).transpose(); - let found = exp_found.found.map_bound(|x| x.substs.get(1).cloned()).transpose(); - + let Some(expected) = exp_found.expected.skip_binder().substs.get(1) else { return; }; + let Some(found) = exp_found.found.skip_binder().substs.get(1) else { return; }; + let expected = expected.unpack(); + let found = found.unpack(); // 3. Extract the tuple type from Fn trait and suggest the change. - if let (Some(expected), Some(found)) = (expected, found) { - let expected = expected.skip_binder().unpack(); - let found = found.skip_binder().unpack(); - if let (GenericArgKind::Type(expected), GenericArgKind::Type(found)) = (expected, found) - && let (ty::Tuple(expected), ty::Tuple(found)) = (expected.kind(), found.kind()) - && expected.len() == found.len() { - let mut suggestion = "|".to_string(); - let mut is_first = true; - let mut has_suggestion = false; + if let GenericArgKind::Type(expected) = expected && + let GenericArgKind::Type(found) = found && + let ty::Tuple(expected) = expected.kind() && + let ty::Tuple(found)= found.kind() && + expected.len() == found.len() { + let mut suggestion = "|".to_string(); + let mut is_first = true; + let mut has_suggestion = false; - for (expected, found) in expected.iter().zip(found.iter()) { - if is_first { - is_first = true; - } else { - suggestion += ", "; - } - - if let (ty::Ref(expected_region, _, _), ty::Ref(found_region, _, _)) = (expected.kind(), found.kind()) - && expected_region.is_late_bound() && !found_region.is_late_bound() { - // If the expected region is late bound, and the found region is not, we can suggest adding `: &_`. - // FIXME: use the actual type + variable name provided by user instead of `_`. - suggestion += "_: &_"; - has_suggestion = true; - } else { - // Otherwise, keep it as-is. - suggestion += "_"; - } - } - suggestion += "|"; - - if has_suggestion { - diag.span_suggestion_verbose( - span, - "consider changing the type of the closure parameters", - suggestion, - Applicability::MaybeIncorrect, - ); - } + for ((expected, found), arg_hir) in expected.iter().zip(found.iter()).zip(fn_decl.inputs.iter()) { + if is_first { + is_first = false; + } else { + suggestion += ", "; } + + if let ty::Ref(expected_region, _, _) = expected.kind() && + let ty::Ref(found_region, _, _) = found.kind() && + expected_region.is_late_bound() && + !found_region.is_late_bound() && + let hir::TyKind::Infer = arg_hir.kind { + // If the expected region is late bound, the found region is not, and users are asking compiler + // to infer the type, we can suggest adding `: &_`. + let Ok(arg) = self.tcx.sess.source_map().span_to_snippet(arg_hir.span) else { return; }; + suggestion += &format!("{}: &_", arg); + has_suggestion = true; + } else { + let Ok(arg) = self.tcx.sess.source_map().span_to_snippet(arg_hir.span) else { return; }; + // Otherwise, keep it as-is. + suggestion += &arg; + } + } + suggestion += "|"; + + if has_suggestion { + diag.span_suggestion_verbose( + span, + "consider specifying the type of the closure parameters", + suggestion, + Applicability::MaybeIncorrect, + ); + } } } } diff --git a/tests/ui/lifetimes/issue-105675.rs b/tests/ui/lifetimes/issue-105675.rs new file mode 100644 index 000000000000..a01fbef4b3bc --- /dev/null +++ b/tests/ui/lifetimes/issue-105675.rs @@ -0,0 +1,16 @@ +fn thing(x: impl FnOnce(&u32, &u32)) {} + +fn main() { + let f = |_, _| (); + thing(f); + //~^ ERROR mismatched types + //~^^ ERROR mismatched types + //~^^^ ERROR implementation of `FnOnce` is not general enough + //~^^^^ ERROR implementation of `FnOnce` is not general enough + let f = |x, y| (); + thing(f); + //~^ ERROR mismatched types + //~^^ ERROR mismatched types + //~^^^ ERROR implementation of `FnOnce` is not general enough + //~^^^^ ERROR implementation of `FnOnce` is not general enough +} diff --git a/tests/ui/lifetimes/issue-105675.stderr b/tests/ui/lifetimes/issue-105675.stderr new file mode 100644 index 000000000000..3d8172ad14a3 --- /dev/null +++ b/tests/ui/lifetimes/issue-105675.stderr @@ -0,0 +1,131 @@ +error[E0308]: mismatched types + --> $DIR/issue-105675.rs:5:5 + | +LL | thing(f); + | ^^^^^^^^ one type is more general than the other + | + = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32)>` + found trait `FnOnce<(&u32, &u32)>` +note: this closure does not fulfill the lifetime requirements + --> $DIR/issue-105675.rs:4:13 + | +LL | let f = |_, _| (); + | ^^^^^^ +note: the lifetime requirement is introduced here + --> $DIR/issue-105675.rs:1:18 + | +LL | fn thing(x: impl FnOnce(&u32, &u32)) {} + | ^^^^^^^^^^^^^^^^^^ +help: consider specifying the type of the closure parameters + | +LL | let f = |_: &_, _: &_| (); + | ~~~~~~~~~~~~~~ + +error[E0308]: mismatched types + --> $DIR/issue-105675.rs:5:5 + | +LL | thing(f); + | ^^^^^^^^ one type is more general than the other + | + = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32)>` + found trait `FnOnce<(&u32, &u32)>` +note: this closure does not fulfill the lifetime requirements + --> $DIR/issue-105675.rs:4:13 + | +LL | let f = |_, _| (); + | ^^^^^^ +note: the lifetime requirement is introduced here + --> $DIR/issue-105675.rs:1:18 + | +LL | fn thing(x: impl FnOnce(&u32, &u32)) {} + | ^^^^^^^^^^^^^^^^^^ +help: consider specifying the type of the closure parameters + | +LL | let f = |_: &_, _: &_| (); + | ~~~~~~~~~~~~~~ + +error: implementation of `FnOnce` is not general enough + --> $DIR/issue-105675.rs:5:5 + | +LL | thing(f); + | ^^^^^^^^ implementation of `FnOnce` is not general enough + | + = note: closure with signature `fn(&'2 u32, &u32)` must implement `FnOnce<(&'1 u32, &u32)>`, for any lifetime `'1`... + = note: ...but it actually implements `FnOnce<(&'2 u32, &u32)>`, for some specific lifetime `'2` + +error: implementation of `FnOnce` is not general enough + --> $DIR/issue-105675.rs:5:5 + | +LL | thing(f); + | ^^^^^^^^ implementation of `FnOnce` is not general enough + | + = note: closure with signature `fn(&u32, &'2 u32)` must implement `FnOnce<(&u32, &'1 u32)>`, for any lifetime `'1`... + = note: ...but it actually implements `FnOnce<(&u32, &'2 u32)>`, for some specific lifetime `'2` + +error[E0308]: mismatched types + --> $DIR/issue-105675.rs:11:5 + | +LL | thing(f); + | ^^^^^^^^ one type is more general than the other + | + = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32)>` + found trait `FnOnce<(&u32, &u32)>` +note: this closure does not fulfill the lifetime requirements + --> $DIR/issue-105675.rs:10:13 + | +LL | let f = |x, y| (); + | ^^^^^^ +note: the lifetime requirement is introduced here + --> $DIR/issue-105675.rs:1:18 + | +LL | fn thing(x: impl FnOnce(&u32, &u32)) {} + | ^^^^^^^^^^^^^^^^^^ +help: consider specifying the type of the closure parameters + | +LL | let f = |x: &_, y: &_| (); + | ~~~~~~~~~~~~~~ + +error[E0308]: mismatched types + --> $DIR/issue-105675.rs:11:5 + | +LL | thing(f); + | ^^^^^^^^ one type is more general than the other + | + = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32)>` + found trait `FnOnce<(&u32, &u32)>` +note: this closure does not fulfill the lifetime requirements + --> $DIR/issue-105675.rs:10:13 + | +LL | let f = |x, y| (); + | ^^^^^^ +note: the lifetime requirement is introduced here + --> $DIR/issue-105675.rs:1:18 + | +LL | fn thing(x: impl FnOnce(&u32, &u32)) {} + | ^^^^^^^^^^^^^^^^^^ +help: consider specifying the type of the closure parameters + | +LL | let f = |x: &_, y: &_| (); + | ~~~~~~~~~~~~~~ + +error: implementation of `FnOnce` is not general enough + --> $DIR/issue-105675.rs:11:5 + | +LL | thing(f); + | ^^^^^^^^ implementation of `FnOnce` is not general enough + | + = note: closure with signature `fn(&'2 u32, &u32)` must implement `FnOnce<(&'1 u32, &u32)>`, for any lifetime `'1`... + = note: ...but it actually implements `FnOnce<(&'2 u32, &u32)>`, for some specific lifetime `'2` + +error: implementation of `FnOnce` is not general enough + --> $DIR/issue-105675.rs:11:5 + | +LL | thing(f); + | ^^^^^^^^ implementation of `FnOnce` is not general enough + | + = note: closure with signature `fn(&u32, &'2 u32)` must implement `FnOnce<(&u32, &'1 u32)>`, for any lifetime `'1`... + = note: ...but it actually implements `FnOnce<(&u32, &'2 u32)>`, for some specific lifetime `'2` + +error: aborting due to 8 previous errors + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/lifetimes/issue-79187.stderr b/tests/ui/lifetimes/issue-79187.stderr index 16eaf654cf3f..209f2b7b7398 100644 --- a/tests/ui/lifetimes/issue-79187.stderr +++ b/tests/ui/lifetimes/issue-79187.stderr @@ -16,7 +16,7 @@ note: the lifetime requirement is introduced here | LL | fn thing(x: impl FnOnce(&u32)) {} | ^^^^^^^^^^^^ -help: consider changing the type of the closure parameters +help: consider specifying the type of the closure parameters | LL | let f = |_: &_| (); | ~~~~~~~ diff --git a/tests/ui/mismatched_types/closure-mismatch.stderr b/tests/ui/mismatched_types/closure-mismatch.stderr index ab0e137418ae..c5b8270ba84d 100644 --- a/tests/ui/mismatched_types/closure-mismatch.stderr +++ b/tests/ui/mismatched_types/closure-mismatch.stderr @@ -25,7 +25,7 @@ note: the lifetime requirement is introduced here | LL | fn baz(_: T) {} | ^^^ -help: consider changing the type of the closure parameters +help: consider specifying the type of the closure parameters | LL | baz(|_: &_| ()); | ~~~~~~~ @@ -57,9 +57,9 @@ note: the lifetime requirement is introduced here | LL | fn baz(_: T) {} | ^^^ -help: consider changing the type of the closure parameters +help: consider specifying the type of the closure parameters | -LL | baz(|_: &_| ()); +LL | baz(|x: &_| ()); | ~~~~~~~ error: aborting due to 4 previous errors From 173b8567ee7055de80debec1067d441a9909345b Mon Sep 17 00:00:00 2001 From: Alex Chi Date: Fri, 17 Mar 2023 23:21:01 -0400 Subject: [PATCH 058/116] use param instead of ty Signed-off-by: Alex Chi --- .../src/infer/error_reporting/suggest.rs | 22 +++- tests/ui/lifetimes/issue-105675.rs | 8 +- tests/ui/lifetimes/issue-105675.stderr | 104 +++++++----------- tests/ui/lifetimes/issue-79187-2.stderr | 4 +- 4 files changed, 63 insertions(+), 75 deletions(-) diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index ec0aa77cef38..473ce3d635de 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -547,7 +547,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { diag: &mut Diagnostic, ) { // 0. Extract fn_decl from hir - let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(hir::Closure { fn_decl, .. }), .. }) = hir else { return; }; + let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(hir::Closure { body, fn_decl, .. }), .. }) = hir else { return; }; + let hir::Body { params, .. } = self.tcx.hir().body(*body); // 1. Get the substs of the closure. // 2. Assume exp_found is FnOnce / FnMut / Fn, we can extract function parameters from [1]. @@ -565,7 +566,10 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let mut is_first = true; let mut has_suggestion = false; - for ((expected, found), arg_hir) in expected.iter().zip(found.iter()).zip(fn_decl.inputs.iter()) { + for (((expected, found), param_hir), arg_hir) in expected.iter() + .zip(found.iter()) + .zip(params.iter()) + .zip(fn_decl.inputs.iter()) { if is_first { is_first = false; } else { @@ -579,11 +583,19 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let hir::TyKind::Infer = arg_hir.kind { // If the expected region is late bound, the found region is not, and users are asking compiler // to infer the type, we can suggest adding `: &_`. - let Ok(arg) = self.tcx.sess.source_map().span_to_snippet(arg_hir.span) else { return; }; - suggestion += &format!("{}: &_", arg); + if param_hir.pat.span == param_hir.ty_span { + // for `|x|`, `|_|`, `|x: impl Foo|` + let Ok(pat) = self.tcx.sess.source_map().span_to_snippet(param_hir.pat.span) else { return; }; + suggestion += &format!("{}: &_", pat); + } else { + // for `|x: ty|`, `|_: ty|` + let Ok(pat) = self.tcx.sess.source_map().span_to_snippet(param_hir.pat.span) else { return; }; + let Ok(ty) = self.tcx.sess.source_map().span_to_snippet(param_hir.ty_span) else { return; }; + suggestion += &format!("{}: &{}", pat, ty); + } has_suggestion = true; } else { - let Ok(arg) = self.tcx.sess.source_map().span_to_snippet(arg_hir.span) else { return; }; + let Ok(arg) = self.tcx.sess.source_map().span_to_snippet(param_hir.span) else { return; }; // Otherwise, keep it as-is. suggestion += &arg; } diff --git a/tests/ui/lifetimes/issue-105675.rs b/tests/ui/lifetimes/issue-105675.rs index a01fbef4b3bc..58d8be8b65f7 100644 --- a/tests/ui/lifetimes/issue-105675.rs +++ b/tests/ui/lifetimes/issue-105675.rs @@ -1,13 +1,11 @@ -fn thing(x: impl FnOnce(&u32, &u32)) {} +fn thing(x: impl FnOnce(&u32, &u32, u32)) {} fn main() { - let f = |_, _| (); + let f = | _ , y: &u32 , z | (); thing(f); //~^ ERROR mismatched types //~^^ ERROR mismatched types - //~^^^ ERROR implementation of `FnOnce` is not general enough - //~^^^^ ERROR implementation of `FnOnce` is not general enough - let f = |x, y| (); + let f = | x, y: _ , z: u32 | (); thing(f); //~^ ERROR mismatched types //~^^ ERROR mismatched types diff --git a/tests/ui/lifetimes/issue-105675.stderr b/tests/ui/lifetimes/issue-105675.stderr index 3d8172ad14a3..66415f72bcb4 100644 --- a/tests/ui/lifetimes/issue-105675.stderr +++ b/tests/ui/lifetimes/issue-105675.stderr @@ -4,22 +4,22 @@ error[E0308]: mismatched types LL | thing(f); | ^^^^^^^^ one type is more general than the other | - = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32)>` - found trait `FnOnce<(&u32, &u32)>` + = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32, u32)>` + found trait `for<'a> FnOnce<(&u32, &'a u32, u32)>` note: this closure does not fulfill the lifetime requirements --> $DIR/issue-105675.rs:4:13 | -LL | let f = |_, _| (); - | ^^^^^^ +LL | let f = | _ , y: &u32 , z | (); + | ^^^^^^^^^^^^^^^^^^^ note: the lifetime requirement is introduced here --> $DIR/issue-105675.rs:1:18 | -LL | fn thing(x: impl FnOnce(&u32, &u32)) {} - | ^^^^^^^^^^^^^^^^^^ +LL | fn thing(x: impl FnOnce(&u32, &u32, u32)) {} + | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider specifying the type of the closure parameters | -LL | let f = |_: &_, _: &_| (); - | ~~~~~~~~~~~~~~ +LL | let f = |_: &_, y: &u32, z| (); + | ~~~~~~~~~~~~~~~~~~~ error[E0308]: mismatched types --> $DIR/issue-105675.rs:5:5 @@ -27,105 +27,83 @@ error[E0308]: mismatched types LL | thing(f); | ^^^^^^^^ one type is more general than the other | - = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32)>` - found trait `FnOnce<(&u32, &u32)>` + = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32, u32)>` + found trait `for<'a> FnOnce<(&u32, &'a u32, u32)>` note: this closure does not fulfill the lifetime requirements --> $DIR/issue-105675.rs:4:13 | -LL | let f = |_, _| (); - | ^^^^^^ +LL | let f = | _ , y: &u32 , z | (); + | ^^^^^^^^^^^^^^^^^^^ note: the lifetime requirement is introduced here --> $DIR/issue-105675.rs:1:18 | -LL | fn thing(x: impl FnOnce(&u32, &u32)) {} - | ^^^^^^^^^^^^^^^^^^ -help: consider specifying the type of the closure parameters - | -LL | let f = |_: &_, _: &_| (); - | ~~~~~~~~~~~~~~ - -error: implementation of `FnOnce` is not general enough - --> $DIR/issue-105675.rs:5:5 - | -LL | thing(f); - | ^^^^^^^^ implementation of `FnOnce` is not general enough - | - = note: closure with signature `fn(&'2 u32, &u32)` must implement `FnOnce<(&'1 u32, &u32)>`, for any lifetime `'1`... - = note: ...but it actually implements `FnOnce<(&'2 u32, &u32)>`, for some specific lifetime `'2` - -error: implementation of `FnOnce` is not general enough - --> $DIR/issue-105675.rs:5:5 - | -LL | thing(f); - | ^^^^^^^^ implementation of `FnOnce` is not general enough - | - = note: closure with signature `fn(&u32, &'2 u32)` must implement `FnOnce<(&u32, &'1 u32)>`, for any lifetime `'1`... - = note: ...but it actually implements `FnOnce<(&u32, &'2 u32)>`, for some specific lifetime `'2` +LL | fn thing(x: impl FnOnce(&u32, &u32, u32)) {} + | ^^^^^^^^^^^^^^^^^^^^^^^ error[E0308]: mismatched types - --> $DIR/issue-105675.rs:11:5 + --> $DIR/issue-105675.rs:9:5 | LL | thing(f); | ^^^^^^^^ one type is more general than the other | - = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32)>` - found trait `FnOnce<(&u32, &u32)>` + = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32, u32)>` + found trait `FnOnce<(&u32, &u32, u32)>` note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-105675.rs:10:13 + --> $DIR/issue-105675.rs:8:13 | -LL | let f = |x, y| (); - | ^^^^^^ +LL | let f = | x, y: _ , z: u32 | (); + | ^^^^^^^^^^^^^^^^^^^^^ note: the lifetime requirement is introduced here --> $DIR/issue-105675.rs:1:18 | -LL | fn thing(x: impl FnOnce(&u32, &u32)) {} - | ^^^^^^^^^^^^^^^^^^ +LL | fn thing(x: impl FnOnce(&u32, &u32, u32)) {} + | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider specifying the type of the closure parameters | -LL | let f = |x: &_, y: &_| (); - | ~~~~~~~~~~~~~~ +LL | let f = |x: &_, y: &_, z: u32| (); + | ~~~~~~~~~~~~~~~~~~~~~~ error[E0308]: mismatched types - --> $DIR/issue-105675.rs:11:5 + --> $DIR/issue-105675.rs:9:5 | LL | thing(f); | ^^^^^^^^ one type is more general than the other | - = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32)>` - found trait `FnOnce<(&u32, &u32)>` + = note: expected trait `for<'a, 'b> FnOnce<(&'a u32, &'b u32, u32)>` + found trait `FnOnce<(&u32, &u32, u32)>` note: this closure does not fulfill the lifetime requirements - --> $DIR/issue-105675.rs:10:13 + --> $DIR/issue-105675.rs:8:13 | -LL | let f = |x, y| (); - | ^^^^^^ +LL | let f = | x, y: _ , z: u32 | (); + | ^^^^^^^^^^^^^^^^^^^^^ note: the lifetime requirement is introduced here --> $DIR/issue-105675.rs:1:18 | -LL | fn thing(x: impl FnOnce(&u32, &u32)) {} - | ^^^^^^^^^^^^^^^^^^ +LL | fn thing(x: impl FnOnce(&u32, &u32, u32)) {} + | ^^^^^^^^^^^^^^^^^^^^^^^ help: consider specifying the type of the closure parameters | -LL | let f = |x: &_, y: &_| (); - | ~~~~~~~~~~~~~~ +LL | let f = |x: &_, y: &_, z: u32| (); + | ~~~~~~~~~~~~~~~~~~~~~~ error: implementation of `FnOnce` is not general enough - --> $DIR/issue-105675.rs:11:5 + --> $DIR/issue-105675.rs:9:5 | LL | thing(f); | ^^^^^^^^ implementation of `FnOnce` is not general enough | - = note: closure with signature `fn(&'2 u32, &u32)` must implement `FnOnce<(&'1 u32, &u32)>`, for any lifetime `'1`... - = note: ...but it actually implements `FnOnce<(&'2 u32, &u32)>`, for some specific lifetime `'2` + = note: closure with signature `fn(&'2 u32, &u32, u32)` must implement `FnOnce<(&'1 u32, &u32, u32)>`, for any lifetime `'1`... + = note: ...but it actually implements `FnOnce<(&'2 u32, &u32, u32)>`, for some specific lifetime `'2` error: implementation of `FnOnce` is not general enough - --> $DIR/issue-105675.rs:11:5 + --> $DIR/issue-105675.rs:9:5 | LL | thing(f); | ^^^^^^^^ implementation of `FnOnce` is not general enough | - = note: closure with signature `fn(&u32, &'2 u32)` must implement `FnOnce<(&u32, &'1 u32)>`, for any lifetime `'1`... - = note: ...but it actually implements `FnOnce<(&u32, &'2 u32)>`, for some specific lifetime `'2` + = note: closure with signature `fn(&u32, &'2 u32, u32)` must implement `FnOnce<(&u32, &'1 u32, u32)>`, for any lifetime `'1`... + = note: ...but it actually implements `FnOnce<(&u32, &'2 u32, u32)>`, for some specific lifetime `'2` -error: aborting due to 8 previous errors +error: aborting due to 6 previous errors For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/lifetimes/issue-79187-2.stderr b/tests/ui/lifetimes/issue-79187-2.stderr index c14d3e0c61b8..75fd87b3fe9b 100644 --- a/tests/ui/lifetimes/issue-79187-2.stderr +++ b/tests/ui/lifetimes/issue-79187-2.stderr @@ -43,9 +43,9 @@ note: the lifetime requirement is introduced here | LL | fn take_foo(_: impl Foo) {} | ^^^ -help: consider changing the type of the closure parameters +help: consider specifying the type of the closure parameters | -LL | take_foo(|_: &_| a); +LL | take_foo(|a: &_| a); | ~~~~~~~ error[E0308]: mismatched types From 90dc6fe71d6a245b175da6293a41c3156e955526 Mon Sep 17 00:00:00 2001 From: Alex Chi Date: Fri, 14 Apr 2023 11:42:37 -0400 Subject: [PATCH 059/116] fix import Applicability Signed-off-by: Alex Chi --- compiler/rustc_infer/src/infer/error_reporting/suggest.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index 473ce3d635de..4dc5fc451ddd 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -1,7 +1,7 @@ use hir::def::CtorKind; use hir::intravisit::{walk_expr, walk_stmt, Visitor}; use rustc_data_structures::fx::FxIndexSet; -use rustc_errors::Diagnostic; +use rustc_errors::{Applicability, Diagnostic}; use rustc_hir as hir; use rustc_middle::traits::{ IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode, From 65c334ee8c1bb8ba9316f82a1cbcef3880cc5db2 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Tue, 11 Apr 2023 17:20:54 +0000 Subject: [PATCH 060/116] Fortify tests againts mir-opts. --- tests/ui/enum-discriminant/issue-104519.rs | 10 -------- .../issue-61696.rs | 25 +++++++++++++------ 2 files changed, 18 insertions(+), 17 deletions(-) rename tests/ui/{issues => enum-discriminant}/issue-61696.rs (90%) diff --git a/tests/ui/enum-discriminant/issue-104519.rs b/tests/ui/enum-discriminant/issue-104519.rs index c4630f76b3a1..507c0988fcc1 100644 --- a/tests/ui/enum-discriminant/issue-104519.rs +++ b/tests/ui/enum-discriminant/issue-104519.rs @@ -23,14 +23,4 @@ fn some_match(result: OpenResult) -> u8 { fn main() { let result = OpenResult::Ok(()); assert_eq!(some_match(result), 0); - - let result = OpenResult::Ok(()); - match result { - OpenResult::Ok(()) => (), - _ => unreachable!("message a"), - } - match result { - OpenResult::Ok(()) => (), - _ => unreachable!("message b"), - } } diff --git a/tests/ui/issues/issue-61696.rs b/tests/ui/enum-discriminant/issue-61696.rs similarity index 90% rename from tests/ui/issues/issue-61696.rs rename to tests/ui/enum-discriminant/issue-61696.rs index dca52927fd7c..8a633a916c83 100644 --- a/tests/ui/issues/issue-61696.rs +++ b/tests/ui/enum-discriminant/issue-61696.rs @@ -55,12 +55,23 @@ pub enum E2 { V4, } -fn main() { - if let E1::V2 { .. } = (E1::V1 { f: true }) { - unreachable!() - } - - if let E2::V1 { .. } = E2::V3:: { - unreachable!() +#[inline(never)] +fn match_e1(y: E1) -> u8 { + match y { + E1::V2 { .. } => 1, + _ => 0, } } + +#[inline(never)] +fn match_e2(y: E2) -> u8 { + match y { + E2::V1 { .. } => 1, + _ => 0, + } +} + +fn main() { + assert_eq!(match_e1(E1::V1 { f: true }), 0); + assert_eq!(match_e2(E2::V3), 0); +} From 194497a1a1b7dcf663aa86e385598afe2662ddb7 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 10 Apr 2023 09:06:59 +0000 Subject: [PATCH 061/116] Remove attempt to optimize codegen for discriminants. --- compiler/rustc_codegen_ssa/src/mir/place.rs | 92 --------------------- 1 file changed, 92 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/mir/place.rs b/compiler/rustc_codegen_ssa/src/mir/place.rs index 1633cfef19d2..a58a61cd567f 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -211,7 +211,6 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { ) -> V { let dl = &bx.tcx().data_layout; let cast_to_layout = bx.cx().layout_of(cast_to); - let cast_to_size = cast_to_layout.layout.size(); let cast_to = bx.cx().immediate_backend_type(cast_to_layout); if self.layout.abi.is_uninhabited() { return bx.cx().const_poison(cast_to); @@ -261,21 +260,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { _ => (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)), }; - let tag_size = tag_scalar.size(bx.cx()); - let max_unsigned = tag_size.unsigned_int_max(); - let max_signed = tag_size.signed_int_max() as u128; - let min_signed = max_signed + 1; let relative_max = niche_variants.end().as_u32() - niche_variants.start().as_u32(); - let niche_end = niche_start.wrapping_add(relative_max as u128) & max_unsigned; - let range = tag_scalar.valid_range(bx.cx()); - - let sle = |lhs: u128, rhs: u128| -> bool { - // Signed and unsigned comparisons give the same results, - // except that in signed comparisons an integer with the - // sign bit set is less than one with the sign bit clear. - // Toggle the sign bit to do a signed comparison. - (lhs ^ min_signed) <= (rhs ^ min_signed) - }; // We have a subrange `niche_start..=niche_end` inside `range`. // If the value of the tag is inside this subrange, it's a @@ -291,49 +276,6 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { // untagged_variant // } // However, we will likely be able to emit simpler code. - - // Find the least and greatest values in `range`, considered - // both as signed and unsigned. - let (low_unsigned, high_unsigned) = if range.start <= range.end { - (range.start, range.end) - } else { - (0, max_unsigned) - }; - let (low_signed, high_signed) = if sle(range.start, range.end) { - (range.start, range.end) - } else { - (min_signed, max_signed) - }; - - let niches_ule = niche_start <= niche_end; - let niches_sle = sle(niche_start, niche_end); - let cast_smaller = cast_to_size <= tag_size; - - // In the algorithm above, we can change - // cast(relative_tag) + niche_variants.start() - // into - // cast(tag + (niche_variants.start() - niche_start)) - // if either the casted type is no larger than the original - // type, or if the niche values are contiguous (in either the - // signed or unsigned sense). - let can_incr = cast_smaller || niches_ule || niches_sle; - - let data_for_boundary_niche = || -> Option<(IntPredicate, u128)> { - if !can_incr { - None - } else if niche_start == low_unsigned { - Some((IntPredicate::IntULE, niche_end)) - } else if niche_end == high_unsigned { - Some((IntPredicate::IntUGE, niche_start)) - } else if niche_start == low_signed { - Some((IntPredicate::IntSLE, niche_end)) - } else if niche_end == high_signed { - Some((IntPredicate::IntSGE, niche_start)) - } else { - None - } - }; - let (is_niche, tagged_discr, delta) = if relative_max == 0 { // Best case scenario: only one tagged variant. This will // likely become just a comparison and a jump. @@ -349,40 +291,6 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { let tagged_discr = bx.cx().const_uint(cast_to, niche_variants.start().as_u32() as u64); (is_niche, tagged_discr, 0) - } else if let Some((predicate, constant)) = data_for_boundary_niche() { - // The niche values are either the lowest or the highest in - // `range`. We can avoid the first subtraction in the - // algorithm. - // The algorithm is now this: - // is_niche = tag <= niche_end - // discr = if is_niche { - // cast(tag + (niche_variants.start() - niche_start)) - // } else { - // untagged_variant - // } - // (the first line may instead be tag >= niche_start, - // and may be a signed or unsigned comparison) - // The arithmetic must be done before the cast, so we can - // have the correct wrapping behavior. See issue #104519 for - // the consequences of getting this wrong. - let is_niche = - bx.icmp(predicate, tag, bx.cx().const_uint_big(tag_llty, constant)); - let delta = (niche_variants.start().as_u32() as u128).wrapping_sub(niche_start); - let incr_tag = if delta == 0 { - tag - } else { - bx.add(tag, bx.cx().const_uint_big(tag_llty, delta)) - }; - - let cast_tag = if cast_smaller { - bx.intcast(incr_tag, cast_to, false) - } else if niches_ule { - bx.zext(incr_tag, cast_to) - } else { - bx.sext(incr_tag, cast_to) - }; - - (is_niche, cast_tag, 0) } else { // The special cases don't apply, so we'll have to go with // the general algorithm. From df9342aa6f426bd786cf390110321338a6624e40 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Tue, 11 Apr 2023 17:41:20 +0000 Subject: [PATCH 062/116] Remove from cranelift too. --- .../src/discriminant.rs | 89 ------------------- 1 file changed, 89 deletions(-) diff --git a/compiler/rustc_codegen_cranelift/src/discriminant.rs b/compiler/rustc_codegen_cranelift/src/discriminant.rs index f740945a03c3..670384663e83 100644 --- a/compiler/rustc_codegen_cranelift/src/discriminant.rs +++ b/compiler/rustc_codegen_cranelift/src/discriminant.rs @@ -103,7 +103,6 @@ pub(crate) fn codegen_get_discriminant<'tcx>( } }; - let cast_to_size = dest_layout.layout.size(); let cast_to = fx.clif_type(dest_layout.ty).unwrap(); // Read the tag/niche-encoded discriminant from memory. @@ -122,21 +121,7 @@ pub(crate) fn codegen_get_discriminant<'tcx>( dest.write_cvalue(fx, res); } TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => { - let tag_size = tag_scalar.size(fx); - let max_unsigned = tag_size.unsigned_int_max(); - let max_signed = tag_size.signed_int_max() as u128; - let min_signed = max_signed + 1; let relative_max = niche_variants.end().as_u32() - niche_variants.start().as_u32(); - let niche_end = niche_start.wrapping_add(relative_max as u128) & max_unsigned; - let range = tag_scalar.valid_range(fx); - - let sle = |lhs: u128, rhs: u128| -> bool { - // Signed and unsigned comparisons give the same results, - // except that in signed comparisons an integer with the - // sign bit set is less than one with the sign bit clear. - // Toggle the sign bit to do a signed comparison. - (lhs ^ min_signed) <= (rhs ^ min_signed) - }; // We have a subrange `niche_start..=niche_end` inside `range`. // If the value of the tag is inside this subrange, it's a @@ -153,45 +138,6 @@ pub(crate) fn codegen_get_discriminant<'tcx>( // } // However, we will likely be able to emit simpler code. - // Find the least and greatest values in `range`, considered - // both as signed and unsigned. - let (low_unsigned, high_unsigned) = - if range.start <= range.end { (range.start, range.end) } else { (0, max_unsigned) }; - let (low_signed, high_signed) = if sle(range.start, range.end) { - (range.start, range.end) - } else { - (min_signed, max_signed) - }; - - let niches_ule = niche_start <= niche_end; - let niches_sle = sle(niche_start, niche_end); - let cast_smaller = cast_to_size <= tag_size; - - // In the algorithm above, we can change - // cast(relative_tag) + niche_variants.start() - // into - // cast(tag + (niche_variants.start() - niche_start)) - // if either the casted type is no larger than the original - // type, or if the niche values are contiguous (in either the - // signed or unsigned sense). - let can_incr = cast_smaller || niches_ule || niches_sle; - - let data_for_boundary_niche = || -> Option<(IntCC, u128)> { - if !can_incr { - None - } else if niche_start == low_unsigned { - Some((IntCC::UnsignedLessThanOrEqual, niche_end)) - } else if niche_end == high_unsigned { - Some((IntCC::UnsignedGreaterThanOrEqual, niche_start)) - } else if niche_start == low_signed { - Some((IntCC::SignedLessThanOrEqual, niche_end)) - } else if niche_end == high_signed { - Some((IntCC::SignedGreaterThanOrEqual, niche_start)) - } else { - None - } - }; - let (is_niche, tagged_discr, delta) = if relative_max == 0 { // Best case scenario: only one tagged variant. This will // likely become just a comparison and a jump. @@ -206,41 +152,6 @@ pub(crate) fn codegen_get_discriminant<'tcx>( let tagged_discr = fx.bcx.ins().iconst(cast_to, niche_variants.start().as_u32() as i64); (is_niche, tagged_discr, 0) - } else if let Some((predicate, constant)) = data_for_boundary_niche() { - // The niche values are either the lowest or the highest in - // `range`. We can avoid the first subtraction in the - // algorithm. - // The algorithm is now this: - // is_niche = tag <= niche_end - // discr = if is_niche { - // cast(tag + (niche_variants.start() - niche_start)) - // } else { - // untagged_variant - // } - // (the first line may instead be tag >= niche_start, - // and may be a signed or unsigned comparison) - // The arithmetic must be done before the cast, so we can - // have the correct wrapping behavior. See issue #104519 for - // the consequences of getting this wrong. - let is_niche = codegen_icmp_imm(fx, predicate, tag, constant as i128); - let delta = (niche_variants.start().as_u32() as u128).wrapping_sub(niche_start); - let incr_tag = if delta == 0 { - tag - } else { - let delta = match fx.bcx.func.dfg.value_type(tag) { - types::I128 => { - let lsb = fx.bcx.ins().iconst(types::I64, delta as u64 as i64); - let msb = fx.bcx.ins().iconst(types::I64, (delta >> 64) as u64 as i64); - fx.bcx.ins().iconcat(lsb, msb) - } - ty => fx.bcx.ins().iconst(ty, delta as i64), - }; - fx.bcx.ins().iadd(tag, delta) - }; - - let cast_tag = clif_intcast(fx, incr_tag, cast_to, !niches_ule); - - (is_niche, cast_tag, 0) } else { // The special cases don't apply, so we'll have to go with // the general algorithm. From 700084aa97e346acedc925dbd89b54cbb266b084 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Tue, 11 Apr 2023 18:34:44 +0000 Subject: [PATCH 063/116] Update codegen test. --- tests/codegen/enum-match.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/codegen/enum-match.rs b/tests/codegen/enum-match.rs index 5f8063a27f7a..36c6be19012f 100644 --- a/tests/codegen/enum-match.rs +++ b/tests/codegen/enum-match.rs @@ -34,8 +34,11 @@ pub enum Enum1 { // CHECK: define noundef i8 @match1{{.*}} // CHECK-NEXT: start: -// CHECK-NEXT: [[DISCR:%.*]] = {{.*}}call i8 @llvm.usub.sat.i8(i8 %0, i8 1) -// CHECK-NEXT: switch i8 [[DISCR]], label {{.*}} [ +// CHECK-NEXT: %1 = add i8 %0, -2 +// CHECK-NEXT: %2 = zext i8 %1 to i64 +// CHECK-NEXT: %3 = icmp ult i8 %1, 2 +// CHECK-NEXT: %4 = add nuw nsw i64 %2, 1 +// CHECK-NEXT: %_2 = select i1 %3, i64 %4, i64 0 #[no_mangle] pub fn match1(e: Enum1) -> u8 { use Enum1::*; From a8857d2fe153717e428742f6a8537abbe6793c50 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Thu, 13 Apr 2023 14:39:32 +0000 Subject: [PATCH 064/116] Pacify tidy. --- src/tools/tidy/src/ui_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index 3d7f9828a7eb..29664c854c87 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -10,7 +10,7 @@ use std::path::{Path, PathBuf}; // FIXME: The following limits should be reduced eventually. const ENTRY_LIMIT: usize = 885; const ROOT_ENTRY_LIMIT: usize = 891; -const ISSUES_ENTRY_LIMIT: usize = 1978; +const ISSUES_ENTRY_LIMIT: usize = 1977; fn check_entries(tests_path: &Path, bad: &mut bool) { let mut directories: HashMap = HashMap::new(); From d38fd29b5b2ed78ef801af19f8b6e6ae98f24210 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Fri, 14 Apr 2023 20:21:07 +0200 Subject: [PATCH 065/116] Add explanations for auto-disambiguation when an intra doc link is resolved to a proc-macro and a trait at the same time --- .../src/write-documentation/linking-to-items-by-name.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/doc/rustdoc/src/write-documentation/linking-to-items-by-name.md b/src/doc/rustdoc/src/write-documentation/linking-to-items-by-name.md index 36bc312b9c99..eb2285ef9064 100644 --- a/src/doc/rustdoc/src/write-documentation/linking-to-items-by-name.md +++ b/src/doc/rustdoc/src/write-documentation/linking-to-items-by-name.md @@ -103,6 +103,13 @@ macro_rules! foo { } ``` +There is one case where the disambiguation will be performed automatically: if an intra doc +link is resolved at the same time as a trait and as a derive proc-macro. In this case, it'll +always generate a link to the trait and not emit a "missing disambiguation" warning. A good +example of this case is when you link to the `Clone` trait: there is also a `Clone` +proc-macro but it ignores it in this case. If you want to link to the proc-macro, you can +use the `macro@` disambiguator. + ## Warnings, re-exports, and scoping Links are resolved in the scope of the module where the item is defined, even From afee2411e3fd5c6e8b3301fa748a760e01615904 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Thu, 30 Mar 2023 21:53:11 -0700 Subject: [PATCH 066/116] rustdoc-search: add support for nested generics --- src/librustdoc/html/static/js/search.js | 21 ++-- tests/rustdoc-js-std/parser-generics.js | 124 +++++++++++++++++++++++- tests/rustdoc-js/generics-nested.js | 33 +++++++ tests/rustdoc-js/generics-nested.rs | 19 ++++ 4 files changed, 184 insertions(+), 13 deletions(-) create mode 100644 tests/rustdoc-js/generics-nested.js create mode 100644 tests/rustdoc-js/generics-nested.rs diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index 40cdc55bbc3b..929dae81c8de 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -461,9 +461,7 @@ function initSearch(rawSearchIndex) { if (parserState.pos < parserState.length && parserState.userQuery[parserState.pos] === "<" ) { - if (isInGenerics) { - throw ["Unexpected ", "<", " after ", "<"]; - } else if (start >= end) { + if (start >= end) { throw ["Found generics without a path"]; } parserState.pos += 1; @@ -765,13 +763,10 @@ function initSearch(rawSearchIndex) { * ident = *(ALPHA / DIGIT / "_") * path = ident *(DOUBLE-COLON ident) [!] * arg = [type-filter *WS COLON *WS] path [generics] - * arg-without-generic = [type-filter *WS COLON *WS] path * type-sep = COMMA/WS *(COMMA/WS) * nonempty-arg-list = *(type-sep) arg *(type-sep arg) *(type-sep) - * nonempty-arg-list-without-generics = *(type-sep) arg-without-generic - * *(type-sep arg-without-generic) *(type-sep) - * generics = OPEN-ANGLE-BRACKET [ nonempty-arg-list-without-generics ] *(type-sep) - * CLOSE-ANGLE-BRACKET/EOF + * generics = OPEN-ANGLE-BRACKET [ nonempty-arg-list ] *(type-sep) + * CLOSE-ANGLE-BRACKET * return-args = RETURN-ARROW *(type-sep) nonempty-arg-list * * exact-search = [type-filter *WS COLON] [ RETURN-ARROW ] *WS QUOTE ident QUOTE [ generics ] @@ -1127,7 +1122,7 @@ function initSearch(rawSearchIndex) { currentEntryElems = []; elems.set(entry.name, currentEntryElems); } - currentEntryElems.push(entry.ty); + currentEntryElems.push(entry); } // We need to find the type that matches the most to remove it in order // to move forward. @@ -1136,8 +1131,12 @@ function initSearch(rawSearchIndex) { return false; } const matchElems = elems.get(generic.name); - const matchIdx = matchElems.findIndex(tmp_elem => - typePassesFilter(generic.typeFilter, tmp_elem)); + const matchIdx = matchElems.findIndex(tmp_elem => { + if (checkGenerics(tmp_elem, generic, 0, maxEditDistance) !== 0) { + return false; + } + return typePassesFilter(generic.typeFilter, tmp_elem.ty); + }); if (matchIdx === -1) { return false; } diff --git a/tests/rustdoc-js-std/parser-generics.js b/tests/rustdoc-js-std/parser-generics.js index c448d845acbd..5a2266dbe369 100644 --- a/tests/rustdoc-js-std/parser-generics.js +++ b/tests/rustdoc-js-std/parser-generics.js @@ -1,4 +1,11 @@ -const QUERY = ['A, E>', 'p<> u8', '"p"']; +const QUERY = [ + 'A, E>', + 'p<> u8', + '"p"', + 'p>', + 'p, r>', + 'p>', +]; const PARSED = [ { @@ -7,7 +14,7 @@ const PARSED = [ original: 'A, E>', returned: [], userQuery: 'a, e>', - error: 'Unexpected `<` after `<`', + error: 'Unclosed `<`', }, { elems: [ @@ -59,4 +66,117 @@ const PARSED = [ userQuery: '"p"', error: null, }, + { + elems: [ + { + name: "p", + fullPath: ["p"], + pathWithoutLast: [], + pathLast: "p", + generics: [ + { + name: "u", + fullPath: ["u"], + pathWithoutLast: [], + pathLast: "u", + generics: [ + { + name: "x", + fullPath: ["x"], + pathWithoutLast: [], + pathLast: "x", + generics: [], + }, + ], + }, + ], + typeFilter: -1, + }, + ], + foundElems: 1, + original: 'p>', + returned: [], + userQuery: 'p>', + error: null, + }, + { + elems: [ + { + name: "p", + fullPath: ["p"], + pathWithoutLast: [], + pathLast: "p", + generics: [ + { + name: "u", + fullPath: ["u"], + pathWithoutLast: [], + pathLast: "u", + generics: [ + { + name: "x", + fullPath: ["x"], + pathWithoutLast: [], + pathLast: "x", + generics: [], + }, + ], + }, + { + name: "r", + fullPath: ["r"], + pathWithoutLast: [], + pathLast: "r", + generics: [], + }, + ], + typeFilter: -1, + }, + ], + foundElems: 1, + original: 'p, r>', + returned: [], + userQuery: 'p, r>', + error: null, + }, + { + elems: [ + { + name: "p", + fullPath: ["p"], + pathWithoutLast: [], + pathLast: "p", + generics: [ + { + name: "u", + fullPath: ["u"], + pathWithoutLast: [], + pathLast: "u", + generics: [ + { + name: "x", + fullPath: ["x"], + pathWithoutLast: [], + pathLast: "x", + generics: [], + }, + { + name: "r", + fullPath: ["r"], + pathWithoutLast: [], + pathLast: "r", + generics: [], + }, + ], + }, + ], + typeFilter: -1, + }, + ], + foundElems: 1, + original: 'p>', + returned: [], + userQuery: 'p>', + error: null, + }, ]; diff --git a/tests/rustdoc-js/generics-nested.js b/tests/rustdoc-js/generics-nested.js new file mode 100644 index 000000000000..8701f2d49861 --- /dev/null +++ b/tests/rustdoc-js/generics-nested.js @@ -0,0 +1,33 @@ +// exact-check + +const QUERY = [ + '-> Out>', + '-> Out>', + '-> Out', + '-> Out', +]; + +const EXPECTED = [ + { + // -> Out> + 'others': [ + { 'path': 'generics_nested', 'name': 'alef' }, + ], + }, + { + // -> Out> + 'others': [], + }, + { + // -> Out + 'others': [ + { 'path': 'generics_nested', 'name': 'bet' }, + ], + }, + { + // -> Out + 'others': [ + { 'path': 'generics_nested', 'name': 'bet' }, + ], + }, +]; diff --git a/tests/rustdoc-js/generics-nested.rs b/tests/rustdoc-js/generics-nested.rs new file mode 100644 index 000000000000..5140422e3849 --- /dev/null +++ b/tests/rustdoc-js/generics-nested.rs @@ -0,0 +1,19 @@ +pub struct Out { + a: A, + b: B, +} + +pub struct First { + in_: In, +} + +pub struct Second; + +// Out> +pub fn alef() -> Out> { + loop {} +} + +pub fn bet() -> Out { + loop {} +} From 6ce53278e191f8047addc7f44b98e180bc80d66d Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Fri, 31 Mar 2023 09:31:44 -0700 Subject: [PATCH 067/116] Update how-to-read-rustdoc.md --- src/doc/rustdoc/src/how-to-read-rustdoc.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/doc/rustdoc/src/how-to-read-rustdoc.md b/src/doc/rustdoc/src/how-to-read-rustdoc.md index 2957916d56cc..56342f65d999 100644 --- a/src/doc/rustdoc/src/how-to-read-rustdoc.md +++ b/src/doc/rustdoc/src/how-to-read-rustdoc.md @@ -94,6 +94,17 @@ can be matched with the following queries: * `trait:Iterator -> primitive:usize` * `Iterator -> usize` +Generics and function parameters are order-agnostic, but sensitive to nesting +and number of matches. For example, a function with the signature +`fn read_all(&mut self: impl Read) -> Result, Error>` +will match these queries: + +* `Read -> Result, Error>` +* `Read -> Result` +* `Read -> Result>` + +But it *does not* match `Result` or `Result>`. + ### Changing displayed theme You can change the displayed theme by opening the settings menu (the gear From 2f45d197f3d6706e4bfd550a9e04ca1383d79a9b Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Fri, 14 Apr 2023 14:47:05 -0600 Subject: [PATCH 068/116] Fix rust-gdb and rust-gdbgui on FreeBSD "\w" is a GNU-specific extension to sed. Avoid it. Fixes #110334 Signed-off-by: Alan Somers --- src/etc/rust-gdb | 4 ++-- src/etc/rust-gdbgui | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/etc/rust-gdb b/src/etc/rust-gdb index d812f7a802b1..b04930425c0e 100755 --- a/src/etc/rust-gdb +++ b/src/etc/rust-gdb @@ -14,7 +14,7 @@ fi RUSTC_SYSROOT="$("$RUSTC" --print=sysroot)" GDB_PYTHON_MODULE_DIRECTORY="$RUSTC_SYSROOT/lib/rustlib/etc" # Get the commit hash for path remapping -RUSTC_COMMIT_HASH="$("$RUSTC" -vV | sed -n 's/commit-hash: \(\w*\)/\1/p')" +RUSTC_COMMIT_HASH="$("$RUSTC" -vV | sed -n 's/commit-hash: \([a-zA-z0-9_]*\)/\1/p')" # Run GDB with the additional arguments that load the pretty printers # Set the environment variable `RUST_GDB` to overwrite the call to a @@ -25,4 +25,4 @@ PYTHONPATH="$PYTHONPATH:$GDB_PYTHON_MODULE_DIRECTORY" exec ${RUST_GDB} \ -iex "add-auto-load-safe-path $GDB_PYTHON_MODULE_DIRECTORY" \ -iex "set substitute-path /rustc/$RUSTC_COMMIT_HASH $RUSTC_SYSROOT/lib/rustlib/src/rust" \ "$@" - \ No newline at end of file + diff --git a/src/etc/rust-gdbgui b/src/etc/rust-gdbgui index e7bafcc99b81..913269316bd4 100755 --- a/src/etc/rust-gdbgui +++ b/src/etc/rust-gdbgui @@ -43,7 +43,7 @@ fi RUSTC_SYSROOT="$("$RUSTC" --print=sysroot)" GDB_PYTHON_MODULE_DIRECTORY="$RUSTC_SYSROOT/lib/rustlib/etc" # Get the commit hash for path remapping -RUSTC_COMMIT_HASH="$("$RUSTC" -vV | sed -n 's/commit-hash: \(\w*\)/\1/p')" +RUSTC_COMMIT_HASH="$("$RUSTC" -vV | sed -n 's/commit-hash: \([a-zA-Z0-9_]*\)/\1/p')" # Set the environment variable `RUST_GDB` to overwrite the call to a # different/specific command (defaults to `gdb`). From c6b1f3144911854cb5c14d51303af882372ae488 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Fri, 14 Apr 2023 19:07:13 -0700 Subject: [PATCH 069/116] Typo fix in src/etc/rust-gdb Co-authored-by: SNCPlay42 --- src/etc/rust-gdb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/etc/rust-gdb b/src/etc/rust-gdb index b04930425c0e..9abed30ea6f7 100755 --- a/src/etc/rust-gdb +++ b/src/etc/rust-gdb @@ -14,7 +14,7 @@ fi RUSTC_SYSROOT="$("$RUSTC" --print=sysroot)" GDB_PYTHON_MODULE_DIRECTORY="$RUSTC_SYSROOT/lib/rustlib/etc" # Get the commit hash for path remapping -RUSTC_COMMIT_HASH="$("$RUSTC" -vV | sed -n 's/commit-hash: \([a-zA-z0-9_]*\)/\1/p')" +RUSTC_COMMIT_HASH="$("$RUSTC" -vV | sed -n 's/commit-hash: \([a-zA-Z0-9_]*\)/\1/p')" # Run GDB with the additional arguments that load the pretty printers # Set the environment variable `RUST_GDB` to overwrite the call to a From 8a515aab76009e302efc52de54419334a76dc24e Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Thu, 9 Feb 2023 18:46:46 +0000 Subject: [PATCH 070/116] Only enable ConstProp at mir-opt-level >= 2. --- compiler/rustc_mir_transform/src/const_prop.rs | 2 +- .../ui/associated-consts/defaults-not-assumed-fail.stderr | 8 -------- tests/ui/consts/const-err-late.stderr | 6 ------ tests/ui/consts/const-eval/issue-44578.stderr | 8 -------- tests/ui/consts/miri_unleashed/assoc_const.stderr | 6 ------ tests/ui/consts/miri_unleashed/assoc_const_2.stderr | 6 ------ tests/ui/consts/uninhabited-const-issue-61744.stderr | 6 ------ tests/ui/limits/issue-55878.stderr | 8 -------- 8 files changed, 1 insertion(+), 49 deletions(-) diff --git a/compiler/rustc_mir_transform/src/const_prop.rs b/compiler/rustc_mir_transform/src/const_prop.rs index 79a9ac7d20c1..ff12a0360aaa 100644 --- a/compiler/rustc_mir_transform/src/const_prop.rs +++ b/compiler/rustc_mir_transform/src/const_prop.rs @@ -54,7 +54,7 @@ pub struct ConstProp; impl<'tcx> MirPass<'tcx> for ConstProp { fn is_enabled(&self, sess: &rustc_session::Session) -> bool { - sess.mir_opt_level() >= 1 + sess.mir_opt_level() >= 2 } #[instrument(skip(self, tcx), level = "debug")] diff --git a/tests/ui/associated-consts/defaults-not-assumed-fail.stderr b/tests/ui/associated-consts/defaults-not-assumed-fail.stderr index fb7159e40c99..9b761b006912 100644 --- a/tests/ui/associated-consts/defaults-not-assumed-fail.stderr +++ b/tests/ui/associated-consts/defaults-not-assumed-fail.stderr @@ -26,14 +26,6 @@ LL | assert_eq!(<() as Tr>::B, 0); // causes the error above | = note: this note originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) -note: erroneous constant used - --> $DIR/defaults-not-assumed-fail.rs:33:5 - | -LL | assert_eq!(<() as Tr>::B, 0); // causes the error above - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this note originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) - error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/consts/const-err-late.stderr b/tests/ui/consts/const-err-late.stderr index 192b9ba204be..149d3b5236b2 100644 --- a/tests/ui/consts/const-err-late.stderr +++ b/tests/ui/consts/const-err-late.stderr @@ -28,12 +28,6 @@ note: erroneous constant used LL | black_box((S::::FOO, S::::FOO)); | ^^^^^^^^^^^^^ -note: erroneous constant used - --> $DIR/const-err-late.rs:19:16 - | -LL | black_box((S::::FOO, S::::FOO)); - | ^^^^^^^^^^^^^ - error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/consts/const-eval/issue-44578.stderr b/tests/ui/consts/const-eval/issue-44578.stderr index 0cbf5448000a..f3952809e4bb 100644 --- a/tests/ui/consts/const-eval/issue-44578.stderr +++ b/tests/ui/consts/const-eval/issue-44578.stderr @@ -26,14 +26,6 @@ LL | println!("{}", as Foo>::AMT); | = note: this note originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) -note: erroneous constant used - --> $DIR/issue-44578.rs:25:20 - | -LL | println!("{}", as Foo>::AMT); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this note originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) - error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/consts/miri_unleashed/assoc_const.stderr b/tests/ui/consts/miri_unleashed/assoc_const.stderr index e1da43c3aea4..8e22cb74bf56 100644 --- a/tests/ui/consts/miri_unleashed/assoc_const.stderr +++ b/tests/ui/consts/miri_unleashed/assoc_const.stderr @@ -25,12 +25,6 @@ note: erroneous constant used LL | let y = , String>>::F; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: erroneous constant used - --> $DIR/assoc_const.rs:29:13 - | -LL | let y = , String>>::F; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - warning: skipping const checks | help: skipping check that does not even have a feature gate diff --git a/tests/ui/consts/miri_unleashed/assoc_const_2.stderr b/tests/ui/consts/miri_unleashed/assoc_const_2.stderr index fc4b18056da5..ae7b03fc9dde 100644 --- a/tests/ui/consts/miri_unleashed/assoc_const_2.stderr +++ b/tests/ui/consts/miri_unleashed/assoc_const_2.stderr @@ -16,12 +16,6 @@ note: erroneous constant used LL | let y = >::F; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: erroneous constant used - --> $DIR/assoc_const_2.rs:27:13 - | -LL | let y = >::F; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ - error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/consts/uninhabited-const-issue-61744.stderr b/tests/ui/consts/uninhabited-const-issue-61744.stderr index 3a94e19313f6..adefbf336c24 100644 --- a/tests/ui/consts/uninhabited-const-issue-61744.stderr +++ b/tests/ui/consts/uninhabited-const-issue-61744.stderr @@ -657,12 +657,6 @@ note: erroneous constant used LL | dbg!(i32::CONSTANT); | ^^^^^^^^^^^^^ -note: erroneous constant used - --> $DIR/uninhabited-const-issue-61744.rs:18:10 - | -LL | dbg!(i32::CONSTANT); - | ^^^^^^^^^^^^^ - error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/limits/issue-55878.stderr b/tests/ui/limits/issue-55878.stderr index 99f1fdf755aa..510b36edd8f4 100644 --- a/tests/ui/limits/issue-55878.stderr +++ b/tests/ui/limits/issue-55878.stderr @@ -25,14 +25,6 @@ LL | println!("Size: {}", std::mem::size_of::<[u8; u64::MAX as usize]>()); | = note: this note originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) -note: erroneous constant used - --> $DIR/issue-55878.rs:7:26 - | -LL | println!("Size: {}", std::mem::size_of::<[u8; u64::MAX as usize]>()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this note originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) - error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. From 22bf5fd848f477a45a7d47012fa0118a7df837b3 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 5 Mar 2023 20:32:29 +0000 Subject: [PATCH 071/116] Remove useless methods in visit. --- compiler/rustc_mir_transform/src/const_prop.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/compiler/rustc_mir_transform/src/const_prop.rs b/compiler/rustc_mir_transform/src/const_prop.rs index ff12a0360aaa..c0146e3efb02 100644 --- a/compiler/rustc_mir_transform/src/const_prop.rs +++ b/compiler/rustc_mir_transform/src/const_prop.rs @@ -854,12 +854,6 @@ impl<'tcx> MutVisitor<'tcx> for ConstPropagator<'_, 'tcx> { } } - fn visit_constant(&mut self, constant: &mut Constant<'tcx>, location: Location) { - trace!("visit_constant: {:?}", constant); - self.super_constant(constant, location); - self.eval_constant(constant); - } - fn visit_assign( &mut self, place: &mut Place<'tcx>, From 9ec086709e23d8e6cbbabb0010a229c1eb4961a2 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 3 Apr 2023 17:22:03 +0000 Subject: [PATCH 072/116] Remove outdated comment. --- compiler/rustc_mir_transform/src/lib.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 2e418c1dafc4..fc12d423cb09 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -566,8 +566,6 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { &separate_const_switch::SeparateConstSwitch, &simplify::SimplifyLocals::new("before-const-prop"), ©_prop::CopyProp, - // - // FIXME(#70073): This pass is responsible for both optimization as well as some lints. &const_prop::ConstProp, &dataflow_const_prop::DataflowConstProp, // From 4a1ff5e04d0856cf9173973caf60097b833af9af Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Mon, 3 Apr 2023 17:50:17 +0000 Subject: [PATCH 073/116] Bless codegen test. --- tests/codegen/optimize-attr-1.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/codegen/optimize-attr-1.rs b/tests/codegen/optimize-attr-1.rs index 22abe06e7a9e..1d1f0a38657f 100644 --- a/tests/codegen/optimize-attr-1.rs +++ b/tests/codegen/optimize-attr-1.rs @@ -8,7 +8,6 @@ // CHECK-LABEL: define{{.*}}i32 @nothing // CHECK-SAME: [[NOTHING_ATTRS:#[0-9]+]] -// NO-OPT: ret i32 4 // SIZE-OPT: ret i32 4 // SPEEC-OPT: ret i32 4 #[no_mangle] @@ -18,7 +17,6 @@ pub fn nothing() -> i32 { // CHECK-LABEL: define{{.*}}i32 @size // CHECK-SAME: [[SIZE_ATTRS:#[0-9]+]] -// NO-OPT: ret i32 6 // SIZE-OPT: ret i32 6 // SPEED-OPT: ret i32 6 #[optimize(size)] @@ -31,7 +29,6 @@ pub fn size() -> i32 { // NO-OPT-SAME: [[NOTHING_ATTRS]] // SPEED-OPT-SAME: [[NOTHING_ATTRS]] // SIZE-OPT-SAME: [[SPEED_ATTRS:#[0-9]+]] -// NO-OPT: ret i32 8 // SIZE-OPT: ret i32 8 // SPEED-OPT: ret i32 8 #[optimize(speed)] From c9409136c7da51b403d18764128f93bb22b7fe22 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Wed, 5 Apr 2023 19:42:01 +0000 Subject: [PATCH 074/116] Bless run-make. --- tests/run-make/const_fn_mir/dump.mir | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/run-make/const_fn_mir/dump.mir b/tests/run-make/const_fn_mir/dump.mir index ab4084c952a3..9cc70d3b0e6b 100644 --- a/tests/run-make/const_fn_mir/dump.mir +++ b/tests/run-make/const_fn_mir/dump.mir @@ -2,9 +2,15 @@ // and is subject to change without notice. Knock yourself out. fn foo() -> i32 { let mut _0: i32; // return place in scope 0 at main.rs:4:19: 4:22 + let mut _1: (i32, bool); // in scope 0 at main.rs:5:5: 5:10 bb0: { - _0 = const 11_i32; // scope 0 at main.rs:5:5: 5:10 + _1 = CheckedAdd(const 5_i32, const 6_i32); // scope 0 at main.rs:5:5: 5:10 + assert(!move (_1.1: bool), "attempt to compute `{} + {}`, which would overflow", const 5_i32, const 6_i32) -> bb1; // scope 0 at main.rs:5:5: 5:10 + } + + bb1: { + _0 = move (_1.0: i32); // scope 0 at main.rs:5:5: 5:10 return; // scope 0 at main.rs:6:2: 6:2 } } From 483525eed300f3615f71ee05ddeeb8e0c232aa53 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Wed, 5 Apr 2023 19:45:00 +0000 Subject: [PATCH 075/116] Remove obsolete test. --- ...erflow.const_dividend.PreCodegen.after.mir | 17 ----------------- ...verflow.const_divisor.PreCodegen.after.mir | 11 ----------- tests/mir-opt/div_overflow.rs | 19 ------------------- 3 files changed, 47 deletions(-) delete mode 100644 tests/mir-opt/div_overflow.const_dividend.PreCodegen.after.mir delete mode 100644 tests/mir-opt/div_overflow.const_divisor.PreCodegen.after.mir delete mode 100644 tests/mir-opt/div_overflow.rs diff --git a/tests/mir-opt/div_overflow.const_dividend.PreCodegen.after.mir b/tests/mir-opt/div_overflow.const_dividend.PreCodegen.after.mir deleted file mode 100644 index 1a7fb916e56d..000000000000 --- a/tests/mir-opt/div_overflow.const_dividend.PreCodegen.after.mir +++ /dev/null @@ -1,17 +0,0 @@ -// MIR for `const_dividend` after PreCodegen - -fn const_dividend(_1: i32) -> i32 { - debug a => _1; // in scope 0 at $DIR/div_overflow.rs:+0:23: +0:24 - let mut _0: i32; // return place in scope 0 at $DIR/div_overflow.rs:+0:34: +0:37 - let mut _2: bool; // in scope 0 at $DIR/div_overflow.rs:+1:5: +1:12 - - bb0: { - _2 = Eq(_1, const 0_i32); // scope 0 at $DIR/div_overflow.rs:+1:5: +1:12 - assert(!move _2, "attempt to divide `{}` by zero", const 256_i32) -> bb1; // scope 0 at $DIR/div_overflow.rs:+1:5: +1:12 - } - - bb1: { - _0 = Div(const 256_i32, _1); // scope 0 at $DIR/div_overflow.rs:+1:5: +1:12 - return; // scope 0 at $DIR/div_overflow.rs:+2:2: +2:2 - } -} diff --git a/tests/mir-opt/div_overflow.const_divisor.PreCodegen.after.mir b/tests/mir-opt/div_overflow.const_divisor.PreCodegen.after.mir deleted file mode 100644 index 5526a194be56..000000000000 --- a/tests/mir-opt/div_overflow.const_divisor.PreCodegen.after.mir +++ /dev/null @@ -1,11 +0,0 @@ -// MIR for `const_divisor` after PreCodegen - -fn const_divisor(_1: i32) -> i32 { - debug a => _1; // in scope 0 at $DIR/div_overflow.rs:+0:22: +0:23 - let mut _0: i32; // return place in scope 0 at $DIR/div_overflow.rs:+0:33: +0:36 - - bb0: { - _0 = Div(_1, const 256_i32); // scope 0 at $DIR/div_overflow.rs:+1:5: +1:12 - return; // scope 0 at $DIR/div_overflow.rs:+2:2: +2:2 - } -} diff --git a/tests/mir-opt/div_overflow.rs b/tests/mir-opt/div_overflow.rs deleted file mode 100644 index fe34a865b93f..000000000000 --- a/tests/mir-opt/div_overflow.rs +++ /dev/null @@ -1,19 +0,0 @@ -// ignore-wasm32 compiled with panic=abort by default -// compile-flags: -Copt-level=0 -Coverflow-checks=yes - -// Tests that division with a const does not emit a panicking branch for overflow - -// EMIT_MIR div_overflow.const_divisor.PreCodegen.after.mir -pub fn const_divisor(a: i32) -> i32 { - a / 256 -} - -// EMIT_MIR div_overflow.const_dividend.PreCodegen.after.mir -pub fn const_dividend(a: i32) -> i32 { - 256 / a -} - -fn main() { - const_divisor(123); - const_dividend(123); -} From 578aedd2741822cb897f4132a59d246d2d0273e7 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Sat, 15 Apr 2023 12:29:51 +0200 Subject: [PATCH 076/116] bump to rust 1.71.0 --- src/version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/version b/src/version index 832e9afb6c13..df484cbb1d9f 100644 --- a/src/version +++ b/src/version @@ -1 +1 @@ -1.70.0 +1.71.0 From 714c276b9ca780308eb461993edc57090ac507e7 Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Sat, 15 Apr 2023 17:17:46 +0530 Subject: [PATCH 077/116] add UI test for #79605 --- tests/ui/generics/issue-79605.rs | 6 ++++++ tests/ui/generics/issue-79605.stderr | 14 ++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 tests/ui/generics/issue-79605.rs create mode 100644 tests/ui/generics/issue-79605.stderr diff --git a/tests/ui/generics/issue-79605.rs b/tests/ui/generics/issue-79605.rs new file mode 100644 index 000000000000..6f4c31e57a37 --- /dev/null +++ b/tests/ui/generics/issue-79605.rs @@ -0,0 +1,6 @@ +struct X<'a, T>(&'a T); + +impl X<'_, _> {} +//~^ ERROR the placeholder `_` is not allowed within types on item signatures for implementations + +fn main() {} diff --git a/tests/ui/generics/issue-79605.stderr b/tests/ui/generics/issue-79605.stderr new file mode 100644 index 000000000000..c5584962dc9e --- /dev/null +++ b/tests/ui/generics/issue-79605.stderr @@ -0,0 +1,14 @@ +error[E0121]: the placeholder `_` is not allowed within types on item signatures for implementations + --> $DIR/issue-79605.rs:3:12 + | +LL | impl X<'_, _> {} + | ^ not allowed in type signatures + | +help: use type parameters instead + | +LL | impl X<'_, T> {} + | +++ ~ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0121`. From 504a47b16d3195e8c857a064a850bbb28912db5e Mon Sep 17 00:00:00 2001 From: est31 Date: Sat, 15 Apr 2023 08:18:10 +0200 Subject: [PATCH 078/116] Add intra-doc links to size_of_* functions --- library/core/src/mem/mod.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index a67df7ed557a..30ec73cabf84 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -170,7 +170,7 @@ pub fn forget_unsized(t: T) { /// /// The following table gives the size for primitives. /// -/// Type | size_of::\() +/// Type | `size_of::()` /// ---- | --------------- /// () | 0 /// bool | 1 @@ -190,8 +190,8 @@ pub fn forget_unsized(t: T) { /// /// Furthermore, `usize` and `isize` have the same size. /// -/// The types `*const T`, `&T`, `Box`, `Option<&T>`, and `Option>` all have -/// the same size. If `T` is Sized, all of those types have the same size as `usize`. +/// The types [`*const T`], `&T`, [`Box`], [`Option<&T>`], and `Option>` all have +/// the same size. If `T` is `Sized`, all of those types have the same size as `usize`. /// /// The mutability of a pointer does not change its size. As such, `&T` and `&mut T` /// have the same size. Likewise for `*const T` and `*mut T`. @@ -203,7 +203,7 @@ pub fn forget_unsized(t: T) { /// /// ## Size of Structs /// -/// For `structs`, the size is determined by the following algorithm. +/// For `struct`s, the size is determined by the following algorithm. /// /// For each field in the struct ordered by declaration order: /// @@ -299,6 +299,10 @@ pub fn forget_unsized(t: T) { /// ``` /// /// [alignment]: align_of +/// [`*const T`]: primitive@pointer +/// [`Box`]: ../../std/boxed/struct.Box.html +/// [`Option<&T>`]: crate::option::Option +/// #[inline(always)] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] @@ -311,7 +315,7 @@ pub const fn size_of() -> usize { /// Returns the size of the pointed-to value in bytes. /// -/// This is usually the same as `size_of::()`. However, when `T` *has* no +/// This is usually the same as [`size_of::()`]. However, when `T` *has* no /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object], /// then `size_of_val` can be used to get the dynamically-known size. /// @@ -328,6 +332,8 @@ pub const fn size_of() -> usize { /// let y: &[u8] = &x; /// assert_eq!(13, mem::size_of_val(y)); /// ``` +/// +/// [`size_of::()`]: size_of #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] @@ -340,7 +346,7 @@ pub const fn size_of_val(val: &T) -> usize { /// Returns the size of the pointed-to value in bytes. /// -/// This is usually the same as `size_of::()`. However, when `T` *has* no +/// This is usually the same as [`size_of::()`]. However, when `T` *has* no /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object], /// then `size_of_val_raw` can be used to get the dynamically-known size. /// @@ -363,6 +369,7 @@ pub const fn size_of_val(val: &T) -> usize { /// [`size_of_val`] on a reference to a type with an extern type tail. /// - otherwise, it is conservatively not allowed to call this function. /// +/// [`size_of::()`]: size_of /// [trait object]: ../../book/ch17-02-trait-objects.html /// [extern type]: ../../unstable-book/language-features/extern-types.html /// From 4c80f58d4188165cc20f72223ec4d1ff46bfb4a8 Mon Sep 17 00:00:00 2001 From: Ali MJ Al-Nasrawy Date: Sat, 15 Apr 2023 15:41:42 +0300 Subject: [PATCH 079/116] Update compiler/rustc_trait_selection/src/traits/outlives_bounds.rs --- compiler/rustc_trait_selection/src/traits/outlives_bounds.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs index 5b8d9e7f0f75..e01a57ea4fee 100644 --- a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs @@ -56,8 +56,9 @@ impl<'a, 'tcx: 'a> InferCtxtExt<'a, 'tcx> for InferCtxt<'tcx> { let ty = self.resolve_vars_if_possible(ty); let ty = OpportunisticRegionResolver::new(self).fold_ty(ty); - // We must avoid processing unconstrained lifetime variables in implied - // bounds. See #110161 for context. + // We do not expect existential variables in implied bounds. + // We may however encounter unconstrained lifetime variables in invalid + // code. See #110161 for context. assert!(!ty.has_non_region_infer()); if ty.needs_infer() { self.tcx.sess.delay_span_bug( From b1feb45f59b47979b8ca919d3d232f4301e4e98d Mon Sep 17 00:00:00 2001 From: jyn Date: Sat, 15 Apr 2023 08:19:00 -0500 Subject: [PATCH 080/116] Fix `x test rust-installer` when `cargo` is set to a relative path Previously, this would give an error because the shell script had a different working directory: ``` test: basic_install $ sh /home/jyn/src/rust/src/tools/rust-installer/gen-installer.sh --image-dir=/home/jyn/src/rust/src/tools/rust-installer/test/image1 --work-dir=/home/jyn/src/rust/build/x86_64-unknown-linux-gnu/test/rust-installer/workdir --output-dir=/home/jyn/src/rust/build/x86_64-unknown-linux-gnu/test/rust-installer/outdir /home/jyn/src/rust/src/tools/rust-installer/gen-installer.sh: 15: ../rust3/build/host/stage2-tools-bin/cargo: not found TEST FAILED! ``` --- src/bootstrap/config.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index cc3b3bc25f3d..ca6dcaf49574 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -1009,7 +1009,9 @@ impl Config { }); config.initial_cargo = build .cargo - .map(PathBuf::from) + .map(|cargo| { + t!(PathBuf::from(cargo).canonicalize(), "`initial_cargo` not found on disk") + }) .unwrap_or_else(|| config.out.join(config.build.triple).join("stage0/bin/cargo")); // NOTE: it's important this comes *after* we set `initial_rustc` just above. From 79b3af3f623046bb1fccafdffab0432863a58315 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Sat, 15 Apr 2023 07:40:19 -0700 Subject: [PATCH 081/116] Temporarily disable the jobserver-error test --- tests/run-make/jobserver-error/Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/run-make/jobserver-error/Makefile b/tests/run-make/jobserver-error/Makefile index 39946ae5edbf..4a1699cc7408 100644 --- a/tests/run-make/jobserver-error/Makefile +++ b/tests/run-make/jobserver-error/Makefile @@ -1,6 +1,7 @@ include ../tools.mk # only-linux +# ignore-test: This test randomly fails, see https://github.com/rust-lang/rust/issues/110321 # Test compiler behavior in case: `jobserver-auth` points to correct pipe which is not jobserver. From 1077d574cf626fbe49f1150ade4c931353a01c8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 15 Apr 2023 18:04:51 +0200 Subject: [PATCH 082/116] remove redundant clones --- compiler/rustc_parse/src/parser/diagnostics.rs | 8 +++----- .../src/traits/error_reporting/mod.rs | 15 +++++++++------ 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index e03ce5d71205..c14c7f2fa0dc 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -570,15 +570,13 @@ impl<'a> Parser<'a> { let expect = tokens_to_string(&expected); let actual = super::token_descr(&self.token); let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 { + let fmt = format!("expected one of {expect}, found {actual}"); let short_expect = if expected.len() > 6 { format!("{} possible tokens", expected.len()) } else { - expect.clone() + expect }; - ( - format!("expected one of {expect}, found {actual}"), - (self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}")), - ) + (fmt, (self.prev_token.span.shrink_to_hi(), format!("expected one of {short_expect}"))) } else if expected.is_empty() { ( format!("unexpected token: {actual}"), diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index 1b741b7302b6..cef982fcb41e 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -2944,22 +2944,25 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { rustc_transmute::Answer::No(reason) => { let dst = trait_ref.skip_binder().substs.type_at(0); let src = trait_ref.skip_binder().substs.type_at(1); - let custom_err_msg = format!("`{src}` cannot be safely transmuted into `{dst}` in the defining scope of `{scope}`").to_string(); + let custom_err_msg = format!( + "`{src}` cannot be safely transmuted into `{dst}` in the defining scope of `{scope}`" + ); let reason_msg = match reason { rustc_transmute::Reason::SrcIsUnspecified => { - format!("`{src}` does not have a well-specified layout").to_string() + format!("`{src}` does not have a well-specified layout") } + rustc_transmute::Reason::DstIsUnspecified => { - format!("`{dst}` does not have a well-specified layout").to_string() + format!("`{dst}` does not have a well-specified layout") } + rustc_transmute::Reason::DstIsBitIncompatible => { format!("At least one value of `{src}` isn't a bit-valid value of `{dst}`") - .to_string() } + rustc_transmute::Reason::DstIsPrivate => format!( "`{dst}` is or contains a type or field that is not visible in that scope" - ) - .to_string(), + ), // FIXME(bryangarza): Include the number of bytes of src and dst rustc_transmute::Reason::DstIsTooBig => { format!("The size of `{src}` is smaller than the size of `{dst}`") From d666f6bf22b3b46f2f232507b328379e7bfaedb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 15 Apr 2023 18:56:25 +0200 Subject: [PATCH 083/116] fix clippy::{filter_map_identiy, map_identity, manual_flatten} --- .../src/fn_ctxt/adjust_fulfillment_errors.rs | 28 ++++++++----------- .../src/partitioning/default.rs | 2 +- .../passes/collect_intra_doc_links.rs | 2 +- 3 files changed, 14 insertions(+), 18 deletions(-) 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 f879ccbb3af1..c3e5f9cb745f 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 @@ -164,24 +164,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { for param in [param_to_point_at, fallback_param_to_point_at, self_param_to_point_at] + .into_iter() + .flatten() { - if let Some(param) = param { - let refined_expr = self.point_at_field_if_possible( - def_id, - param, - variant_def_id, - fields, - ); + let refined_expr = + self.point_at_field_if_possible(def_id, param, variant_def_id, fields); - match refined_expr { - None => {} - Some((refined_expr, _)) => { - error.obligation.cause.span = refined_expr - .span - .find_ancestor_in_same_ctxt(error.obligation.cause.span) - .unwrap_or(refined_expr.span); - return true; - } + match refined_expr { + None => {} + Some((refined_expr, _)) => { + error.obligation.cause.span = refined_expr + .span + .find_ancestor_in_same_ctxt(error.obligation.cause.span) + .unwrap_or(refined_expr.span); + return true; } } } diff --git a/compiler/rustc_monomorphize/src/partitioning/default.rs b/compiler/rustc_monomorphize/src/partitioning/default.rs index 482b78d42e37..769e12f77bf2 100644 --- a/compiler/rustc_monomorphize/src/partitioning/default.rs +++ b/compiler/rustc_monomorphize/src/partitioning/default.rs @@ -89,7 +89,7 @@ impl<'tcx> Partitioner<'tcx> for DefaultPartitioning { } PreInliningPartitioning { - codegen_units: codegen_units.into_values().map(|codegen_unit| codegen_unit).collect(), + codegen_units: codegen_units.into_values().collect(), roots, internalization_candidates, } diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 2cd9c8a87818..a835bd2de3b1 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -1349,7 +1349,7 @@ impl LinkCollector<'_, '_> { if has_derive_trait_collision { candidates.macro_ns = None; } - candidates.into_iter().filter_map(|res| res).flatten().collect::>() + candidates.into_iter().flatten().flatten().collect::>() } } } From bcd79c222ac7a316502e9537e86fae6512bc697d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 15 Apr 2023 19:02:26 +0200 Subject: [PATCH 084/116] fix clippy::{clone_on_copy, useless_conversion} --- compiler/rustc_borrowck/src/lib.rs | 2 +- compiler/rustc_hir_analysis/src/collect/predicates_of.rs | 5 ++--- compiler/rustc_query_impl/src/profiling_support.rs | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index a4b285a34fa4..70d0a101b4ed 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -528,7 +528,7 @@ impl<'cx, 'tcx> BorrowckInferCtxt<'cx, 'tcx> { where F: Fn() -> RegionCtxt, { - let next_region = self.infcx.next_nll_region_var(origin.clone()); + let next_region = self.infcx.next_nll_region_var(origin); let vid = next_region.as_var(); if cfg!(debug_assertions) && !self.inside_canonicalization_ctxt() { diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 9358ed612921..8c414521b765 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -645,9 +645,8 @@ pub(super) fn implied_predicates_with_filter( }; // Combine the two lists to form the complete set of superbounds: - let implied_bounds = &*tcx - .arena - .alloc_from_iter(superbounds.predicates().into_iter().chain(where_bounds_that_match)); + let implied_bounds = + &*tcx.arena.alloc_from_iter(superbounds.predicates().chain(where_bounds_that_match)); debug!(?implied_bounds); // Now require that immediate supertraits are converted, diff --git a/compiler/rustc_query_impl/src/profiling_support.rs b/compiler/rustc_query_impl/src/profiling_support.rs index 4743170e9bfd..579a789244bd 100644 --- a/compiler/rustc_query_impl/src/profiling_support.rs +++ b/compiler/rustc_query_impl/src/profiling_support.rs @@ -231,7 +231,7 @@ pub(crate) fn alloc_self_profile_query_strings_for_query_cache<'tcx, C>( // locked while doing so. Instead we copy out the // `(query_key, dep_node_index)` pairs and release the lock again. let mut query_keys_and_indices = Vec::new(); - query_cache.iter(&mut |k, _, i| query_keys_and_indices.push((k.clone(), i))); + query_cache.iter(&mut |k, _, i| query_keys_and_indices.push((*k, i))); // Now actually allocate the strings. If allocating the strings // generates new entries in the query cache, we'll miss them but From 0c61f58c11742452d2f51a893eb27e002f35667e Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Fri, 14 Apr 2023 16:09:20 -0700 Subject: [PATCH 085/116] rustdoc: stop passing a title to `replaceState` second argument As described on [MDN's replaceState page], this parameter is not currently used, and the empty string is "safe against future changes to the method." [MDN's replaceState page]: https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState --- src/librustdoc/html/static/js/main.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/librustdoc/html/static/js/main.js b/src/librustdoc/html/static/js/main.js index 6f5987e68bf1..93d657fd6050 100644 --- a/src/librustdoc/html/static/js/main.js +++ b/src/librustdoc/html/static/js/main.js @@ -275,8 +275,7 @@ function preLoadCss(cssUrl) { document.title = searchState.titleBeforeSearch; // We also remove the query parameter from the URL. if (browserSupportsHistoryApi()) { - history.replaceState(null, window.currentCrate + " - Rust", - getNakedUrl() + window.location.hash); + history.replaceState(null, "", getNakedUrl() + window.location.hash); } }, getQueryStringParams: () => { @@ -378,8 +377,7 @@ function preLoadCss(cssUrl) { searchState.clearInputTimeout(); switchDisplayedElement(null); if (browserSupportsHistoryApi()) { - history.replaceState(null, window.currentCrate + " - Rust", - getNakedUrl() + window.location.hash); + history.replaceState(null, "", getNakedUrl() + window.location.hash); } ev.preventDefault(); searchState.defocus(); From d7ed5a52ffcffccba62155968701c94e46e61fe8 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Sat, 15 Apr 2023 14:43:20 -0700 Subject: [PATCH 086/116] Unignore closure-bang. This test was ignored long ago in https://github.com/rust-lang/rust/pull/20578/ when the syntax for closures was changed. The current status is that a closure with an explicit `!` return type will trigger the `unreachable_code` lint which appears to be the original intent of the test (https://github.com/rust-lang/rust/pull/16836). A closure without a return type won't trigger the lint since the `!` type isn't inferred (AFAIK). This restores the test to its original form. --- tests/ui/lint/dead-code/closure-bang.rs | 4 +--- tests/ui/lint/dead-code/closure-bang.stderr | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) create mode 100644 tests/ui/lint/dead-code/closure-bang.stderr diff --git a/tests/ui/lint/dead-code/closure-bang.rs b/tests/ui/lint/dead-code/closure-bang.rs index 8e8636b1180e..bca131a15d32 100644 --- a/tests/ui/lint/dead-code/closure-bang.rs +++ b/tests/ui/lint/dead-code/closure-bang.rs @@ -1,9 +1,7 @@ -// ignore-test FIXME(#20574) - #![deny(unreachable_code)] fn main() { - let x = || panic!(); + let x = || -> ! { panic!() }; x(); println!("Foo bar"); //~ ERROR: unreachable statement } diff --git a/tests/ui/lint/dead-code/closure-bang.stderr b/tests/ui/lint/dead-code/closure-bang.stderr new file mode 100644 index 000000000000..119ce11e34a1 --- /dev/null +++ b/tests/ui/lint/dead-code/closure-bang.stderr @@ -0,0 +1,17 @@ +error: unreachable statement + --> $DIR/closure-bang.rs:6:5 + | +LL | x(); + | --- any code following this expression is unreachable +LL | println!("Foo bar"); + | ^^^^^^^^^^^^^^^^^^^ unreachable statement + | +note: the lint level is defined here + --> $DIR/closure-bang.rs:1:9 + | +LL | #![deny(unreachable_code)] + | ^^^^^^^^^^^^^^^^ + = note: this error originates in the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to previous error + From 266ec68d3d7dd6bf369f79baea7f0d889b86b7a1 Mon Sep 17 00:00:00 2001 From: Alona Enraght-Moony Date: Sat, 15 Apr 2023 21:48:39 +0000 Subject: [PATCH 087/116] Convert comment to doc comment on `Interner::get`. --- compiler/rustc_span/src/symbol.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 6bfae3771521..6ce0b66ef6a4 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1986,8 +1986,9 @@ impl Interner { name } - // Get the symbol as a string. `Symbol::as_str()` should be used in - // preference to this function. + /// Get the symbol as a string. + /// + /// [`Symbol::as_str()`] should be used in preference to this function. fn get(&self, symbol: Symbol) -> &str { self.0.lock().strings[symbol.0.as_usize()] } From 3a645659b89ff96d0d6123ca9c18bce41e69ec36 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Sat, 15 Apr 2023 15:23:32 -0700 Subject: [PATCH 088/116] Unignore issue-65918 This test was fixed by https://github.com/rust-lang/rust/pull/65989 --- tests/ui/type-alias-impl-trait/issue-65918.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/ui/type-alias-impl-trait/issue-65918.rs b/tests/ui/type-alias-impl-trait/issue-65918.rs index af6d50109201..82cc823e494c 100644 --- a/tests/ui/type-alias-impl-trait/issue-65918.rs +++ b/tests/ui/type-alias-impl-trait/issue-65918.rs @@ -1,5 +1,3 @@ -// ignore-test: This now ICEs again. - // build-pass #![feature(type_alias_impl_trait)] From a4e851cf622ffc365397f09a3ec2137a6c038ac8 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Sat, 15 Apr 2023 16:11:42 -0700 Subject: [PATCH 089/116] Add some reasons why tests are ignored. --- tests/mir-opt/simplify_arm.rs | 3 +-- tests/mir-opt/simplify_arm_identity.rs | 3 +-- tests/ui/borrowck/move-error-snippets-ext.rs | 2 +- tests/ui/codemap_tests/two_files_data.rs | 2 +- tests/ui/conditional-compilation/module_with_cfg.rs | 2 +- tests/ui/cross/cross-file-errors/main.stderr | 2 +- tests/ui/cross/cross-file-errors/underscore.rs | 4 +--- tests/ui/inline-const/const-match-pat-lifetime-err.rs | 2 +- tests/ui/issues/issue-49298.rs | 2 +- tests/ui/issues/issue-59756.rs | 2 +- tests/ui/macros/macro-expanded-include/foo/mod.rs | 2 +- tests/ui/match/issue-26996.rs | 2 +- tests/ui/match/issue-27021.rs | 2 +- tests/ui/numbers-arithmetic/saturating-float-casts-impl.rs | 2 +- tests/ui/panics/panic-short-backtrace-windows-x86_64.rs | 2 +- tests/ui/proc-macro/module.rs | 2 +- tests/ui/proc-macro/module_with_attrs.rs | 2 +- tests/ui/proc-macro/outer/inner.rs | 2 +- .../pretty-print-hack/allsorts-rental-0.5.6/src/lib.rs | 2 +- tests/ui/proc-macro/pretty-print-hack/rental-0.5.5/src/lib.rs | 2 +- tests/ui/proc-macro/pretty-print-hack/rental-0.5.6/src/lib.rs | 2 +- 21 files changed, 21 insertions(+), 25 deletions(-) diff --git a/tests/mir-opt/simplify_arm.rs b/tests/mir-opt/simplify_arm.rs index c247872e2af4..4c471ce04683 100644 --- a/tests/mir-opt/simplify_arm.rs +++ b/tests/mir-opt/simplify_arm.rs @@ -6,8 +6,7 @@ // EMIT_MIR simplify_arm.id_try.SimplifyArmIdentity.diff // EMIT_MIR simplify_arm.id_try.SimplifyBranchSame.diff -// This pass is broken since deaggregation changed -// ignore-test +// ignore-test This pass is broken since deaggregation changed fn id(o: Option) -> Option { match o { diff --git a/tests/mir-opt/simplify_arm_identity.rs b/tests/mir-opt/simplify_arm_identity.rs index cf6ff57aa96d..e122cd50e001 100644 --- a/tests/mir-opt/simplify_arm_identity.rs +++ b/tests/mir-opt/simplify_arm_identity.rs @@ -4,8 +4,7 @@ // compile-flags: -Zmir-opt-level=3 // EMIT_MIR_FOR_EACH_BIT_WIDTH -// This pass is broken since deaggregation changed -// ignore-test +// ignore-test This pass is broken since deaggregation changed enum Src { Foo(u8), diff --git a/tests/ui/borrowck/move-error-snippets-ext.rs b/tests/ui/borrowck/move-error-snippets-ext.rs index c77f6c8276e7..27041d55d8fa 100644 --- a/tests/ui/borrowck/move-error-snippets-ext.rs +++ b/tests/ui/borrowck/move-error-snippets-ext.rs @@ -1,4 +1,4 @@ -// ignore-test +// ignore-test (auxiliary, used by other tests) macro_rules! aaa { ($c:ident) => {{ diff --git a/tests/ui/codemap_tests/two_files_data.rs b/tests/ui/codemap_tests/two_files_data.rs index b4d2f5d3c6d0..6abeac0dd2e7 100644 --- a/tests/ui/codemap_tests/two_files_data.rs +++ b/tests/ui/codemap_tests/two_files_data.rs @@ -1,4 +1,4 @@ -// ignore-test +// ignore-test (auxiliary, used by other tests) trait Foo { } diff --git a/tests/ui/conditional-compilation/module_with_cfg.rs b/tests/ui/conditional-compilation/module_with_cfg.rs index 56c4baadf22b..55c8381cffeb 100644 --- a/tests/ui/conditional-compilation/module_with_cfg.rs +++ b/tests/ui/conditional-compilation/module_with_cfg.rs @@ -1,3 +1,3 @@ -// ignore-test +// ignore-test (auxiliary, used by other tests) #![cfg_attr(all(), cfg(FALSE))] diff --git a/tests/ui/cross/cross-file-errors/main.stderr b/tests/ui/cross/cross-file-errors/main.stderr index 293a300ed610..56eb6ad429af 100644 --- a/tests/ui/cross/cross-file-errors/main.stderr +++ b/tests/ui/cross/cross-file-errors/main.stderr @@ -1,5 +1,5 @@ error: in expressions, `_` can only be used on the left-hand side of an assignment - --> $DIR/underscore.rs:8:9 + --> $DIR/underscore.rs:6:9 | LL | _ | ^ `_` not allowed here diff --git a/tests/ui/cross/cross-file-errors/underscore.rs b/tests/ui/cross/cross-file-errors/underscore.rs index 76e72a93fcce..4dd91c13ea9c 100644 --- a/tests/ui/cross/cross-file-errors/underscore.rs +++ b/tests/ui/cross/cross-file-errors/underscore.rs @@ -1,6 +1,4 @@ -// We want this file only so we can test cross-file error -// messages, but we don't want it in an external crate. -// ignore-test +// ignore-test (auxiliary, used by other tests) #![crate_type = "lib"] macro_rules! underscore { diff --git a/tests/ui/inline-const/const-match-pat-lifetime-err.rs b/tests/ui/inline-const/const-match-pat-lifetime-err.rs index 436b8037f309..366ad26bb271 100644 --- a/tests/ui/inline-const/const-match-pat-lifetime-err.rs +++ b/tests/ui/inline-const/const-match-pat-lifetime-err.rs @@ -1,4 +1,4 @@ -// ignore-test +// ignore-test (This is currently broken) #![allow(incomplete_features)] #![feature(const_mut_refs)] diff --git a/tests/ui/issues/issue-49298.rs b/tests/ui/issues/issue-49298.rs index e3ffa8e7c6ef..6e58fa12ca70 100644 --- a/tests/ui/issues/issue-49298.rs +++ b/tests/ui/issues/issue-49298.rs @@ -6,7 +6,7 @@ // where #54986 is implemented and #54987 is *not* implemented. For // now: just ignore it // -// ignore-test +// ignore-test (#54987) // This test is checking that the space allocated for `x.1` does not // overlap with `y`. (The reason why such a thing happened at one diff --git a/tests/ui/issues/issue-59756.rs b/tests/ui/issues/issue-59756.rs index d6df0592be32..3742f31abade 100644 --- a/tests/ui/issues/issue-59756.rs +++ b/tests/ui/issues/issue-59756.rs @@ -1,5 +1,5 @@ // run-rustfix -// ignore-test +// ignore-test (rustfix needs multiple suggestions) // // FIXME: Re-enable this test once we support choosing // between multiple mutually exclusive suggestions for the same span diff --git a/tests/ui/macros/macro-expanded-include/foo/mod.rs b/tests/ui/macros/macro-expanded-include/foo/mod.rs index cff110470f21..2e4c4c7f8a99 100644 --- a/tests/ui/macros/macro-expanded-include/foo/mod.rs +++ b/tests/ui/macros/macro-expanded-include/foo/mod.rs @@ -1,4 +1,4 @@ -// ignore-test +// ignore-test (auxiliary, used by other tests) macro_rules! m { () => { include!("file.txt"); } diff --git a/tests/ui/match/issue-26996.rs b/tests/ui/match/issue-26996.rs index 84037b72a274..9ea4545268b4 100644 --- a/tests/ui/match/issue-26996.rs +++ b/tests/ui/match/issue-26996.rs @@ -4,7 +4,7 @@ // where #54986 is implemented and #54987 is *not* implemented. For // now: just ignore it // -// ignore-test +// ignore-test (#54987) // This test is checking that the write to `c.0` (which has been moved out of) // won't overwrite the state in `c2`. diff --git a/tests/ui/match/issue-27021.rs b/tests/ui/match/issue-27021.rs index ef3b114a5fa2..9630e9a03270 100644 --- a/tests/ui/match/issue-27021.rs +++ b/tests/ui/match/issue-27021.rs @@ -4,7 +4,7 @@ // where #54986 is implemented and #54987 is *not* implemented. For // now: just ignore it // -// ignore-test +// ignore-test (#54987) // These are variants of issue-26996.rs. In all cases we are writing // into a record field that has been moved out of, and ensuring that diff --git a/tests/ui/numbers-arithmetic/saturating-float-casts-impl.rs b/tests/ui/numbers-arithmetic/saturating-float-casts-impl.rs index 4c6929d6627a..088b2fcdd144 100644 --- a/tests/ui/numbers-arithmetic/saturating-float-casts-impl.rs +++ b/tests/ui/numbers-arithmetic/saturating-float-casts-impl.rs @@ -1,4 +1,4 @@ -// ignore-test +// ignore-test (auxiliary, used by other tests) // Tests saturating float->int casts. See u128-as-f32.rs for the opposite direction. // diff --git a/tests/ui/panics/panic-short-backtrace-windows-x86_64.rs b/tests/ui/panics/panic-short-backtrace-windows-x86_64.rs index 39ffe86dd496..be83eb748433 100644 --- a/tests/ui/panics/panic-short-backtrace-windows-x86_64.rs +++ b/tests/ui/panics/panic-short-backtrace-windows-x86_64.rs @@ -1,6 +1,6 @@ // This test has been spuriously failing a lot recently (#92000). // Ignore it until the underlying issue is fixed. -// ignore-test +// ignore-test (#92000) // Regression test for #87481: short backtrace formatting cut off the entire stack trace. diff --git a/tests/ui/proc-macro/module.rs b/tests/ui/proc-macro/module.rs index 5777ed899839..a750083c607f 100644 --- a/tests/ui/proc-macro/module.rs +++ b/tests/ui/proc-macro/module.rs @@ -1 +1 @@ -// ignore-test +// ignore-test (auxiliary, used by other tests) diff --git a/tests/ui/proc-macro/module_with_attrs.rs b/tests/ui/proc-macro/module_with_attrs.rs index 63e66a62ac38..0b2604f95b6c 100644 --- a/tests/ui/proc-macro/module_with_attrs.rs +++ b/tests/ui/proc-macro/module_with_attrs.rs @@ -1,4 +1,4 @@ -// ignore-test +// ignore-test (auxiliary, used by other tests) #![rustfmt::skip] #![print_attr] diff --git a/tests/ui/proc-macro/outer/inner.rs b/tests/ui/proc-macro/outer/inner.rs index 5777ed899839..a750083c607f 100644 --- a/tests/ui/proc-macro/outer/inner.rs +++ b/tests/ui/proc-macro/outer/inner.rs @@ -1 +1 @@ -// ignore-test +// ignore-test (auxiliary, used by other tests) diff --git a/tests/ui/proc-macro/pretty-print-hack/allsorts-rental-0.5.6/src/lib.rs b/tests/ui/proc-macro/pretty-print-hack/allsorts-rental-0.5.6/src/lib.rs index 9501980fa55d..889f399a7f25 100644 --- a/tests/ui/proc-macro/pretty-print-hack/allsorts-rental-0.5.6/src/lib.rs +++ b/tests/ui/proc-macro/pretty-print-hack/allsorts-rental-0.5.6/src/lib.rs @@ -1,4 +1,4 @@ -// ignore-test +// ignore-test (auxiliary, used by other tests) #[derive(Print)] enum ProceduralMasqueradeDummyType { diff --git a/tests/ui/proc-macro/pretty-print-hack/rental-0.5.5/src/lib.rs b/tests/ui/proc-macro/pretty-print-hack/rental-0.5.5/src/lib.rs index 9501980fa55d..889f399a7f25 100644 --- a/tests/ui/proc-macro/pretty-print-hack/rental-0.5.5/src/lib.rs +++ b/tests/ui/proc-macro/pretty-print-hack/rental-0.5.5/src/lib.rs @@ -1,4 +1,4 @@ -// ignore-test +// ignore-test (auxiliary, used by other tests) #[derive(Print)] enum ProceduralMasqueradeDummyType { diff --git a/tests/ui/proc-macro/pretty-print-hack/rental-0.5.6/src/lib.rs b/tests/ui/proc-macro/pretty-print-hack/rental-0.5.6/src/lib.rs index 9501980fa55d..889f399a7f25 100644 --- a/tests/ui/proc-macro/pretty-print-hack/rental-0.5.6/src/lib.rs +++ b/tests/ui/proc-macro/pretty-print-hack/rental-0.5.6/src/lib.rs @@ -1,4 +1,4 @@ -// ignore-test +// ignore-test (auxiliary, used by other tests) #[derive(Print)] enum ProceduralMasqueradeDummyType { From 4460a1dc28a10cd74a6e5636d6e2cd8c8f06ba4b Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sat, 15 Apr 2023 09:31:11 +1000 Subject: [PATCH 090/116] Remove `TypeSuper{Foldable,Visitable}` impls for `Region`. These traits exist so that folders/visitors can recurse into types of interest: binders, types, regions, predicates, and consts. But `Region` is non-recursive and cannot contain other types of interest, so its methods in these traits are trivial. This commit inlines and removes those trivial methods. --- .../rustc_hir_analysis/src/variance/mod.rs | 2 +- .../trait_impl_difference.rs | 4 +- compiler/rustc_middle/src/ty/fold.rs | 3 +- compiler/rustc_middle/src/ty/print/pretty.rs | 2 +- .../rustc_middle/src/ty/structural_impls.rs | 18 --------- compiler/rustc_middle/src/ty/visit.rs | 2 +- .../rustc_trait_selection/src/traits/mod.rs | 2 +- compiler/rustc_traits/src/chalk/lowering.rs | 8 ++-- compiler/rustc_type_ir/src/fold.rs | 37 +++++++++---------- compiler/rustc_type_ir/src/visit.rs | 28 ++++++++------ src/librustdoc/clean/auto_trait.rs | 11 +++--- 11 files changed, 51 insertions(+), 66 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/variance/mod.rs b/compiler/rustc_hir_analysis/src/variance/mod.rs index 0a45119ff055..4d240e90b143 100644 --- a/compiler/rustc_hir_analysis/src/variance/mod.rs +++ b/compiler/rustc_hir_analysis/src/variance/mod.rs @@ -105,7 +105,7 @@ fn variance_of_opaque(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[ty::Varianc if let ty::RegionKind::ReEarlyBound(ebr) = r.kind() { self.variances[ebr.index as usize] = ty::Invariant; } - r.super_visit_with(self) + ControlFlow::Continue(()) } #[instrument(level = "trace", skip(self), ret)] diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs index 2875448ee157..ce70bcc5c851 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs @@ -13,7 +13,7 @@ use rustc_hir::intravisit::Visitor; use rustc_middle::hir::nested_filter; use rustc_middle::ty::error::ExpectedFound; use rustc_middle::ty::print::RegionHighlightMode; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitor}; use rustc_span::Span; use std::ops::ControlFlow; @@ -81,7 +81,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { self.highlight.highlighting_region(r, self.counter); self.counter += 1; } - r.super_visit_with(self) + ControlFlow::Continue(()) } } diff --git a/compiler/rustc_middle/src/ty/fold.rs b/compiler/rustc_middle/src/ty/fold.rs index 203e16bea27f..25890eb15cde 100644 --- a/compiler/rustc_middle/src/ty/fold.rs +++ b/compiler/rustc_middle/src/ty/fold.rs @@ -37,7 +37,8 @@ where } fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { - let r = r.super_fold_with(self); + // This one is a little different, because `super_fold_with` is not + // implemented on non-recursive `Region`. (self.lt_op)(r) } diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 72caadaf6619..af76cf7cc4e0 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -2518,7 +2518,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { self.used_region_names.insert(name); } - r.super_visit_with(self) + ControlFlow::Continue(()) } // We collect types in order to prevent really large types from compiling for diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 5c604bb6db27..619fcea8b7d4 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -583,24 +583,6 @@ impl<'tcx> TypeVisitable> for ty::Region<'tcx> { } } -impl<'tcx> TypeSuperFoldable> for ty::Region<'tcx> { - fn try_super_fold_with>>( - self, - _folder: &mut F, - ) -> Result { - Ok(self) - } -} - -impl<'tcx> TypeSuperVisitable> for ty::Region<'tcx> { - fn super_visit_with>>( - &self, - _visitor: &mut V, - ) -> ControlFlow { - ControlFlow::Continue(()) - } -} - impl<'tcx> TypeFoldable> for ty::Predicate<'tcx> { fn try_fold_with>>( self, diff --git a/compiler/rustc_middle/src/ty/visit.rs b/compiler/rustc_middle/src/ty/visit.rs index 08a62c900f97..24a1f04c7e38 100644 --- a/compiler/rustc_middle/src/ty/visit.rs +++ b/compiler/rustc_middle/src/ty/visit.rs @@ -364,7 +364,7 @@ impl<'tcx> TypeVisitor> for ValidateBoundVars<'tcx> { _ => (), }; - r.super_visit_with(self) + ControlFlow::Continue(()) } } diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 8a203dec86ba..ed82b9c01527 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -450,7 +450,7 @@ fn is_impossible_method(tcx: TyCtxt<'_>, (impl_def_id, trait_item_def_id): (DefI { return ControlFlow::Break(()); } - r.super_visit_with(self) + ControlFlow::Continue(()) } fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow { if let ty::ConstKind::Param(param) = ct.kind() diff --git a/compiler/rustc_traits/src/chalk/lowering.rs b/compiler/rustc_traits/src/chalk/lowering.rs index 2be72879b7b1..31eea22d72b8 100644 --- a/compiler/rustc_traits/src/chalk/lowering.rs +++ b/compiler/rustc_traits/src/chalk/lowering.rs @@ -998,7 +998,7 @@ impl<'tcx> TypeVisitor> for BoundVarsCollector<'tcx> { _ => (), }; - r.super_visit_with(self) + ControlFlow::Continue(()) } } @@ -1048,7 +1048,7 @@ impl<'a, 'tcx> TypeFolder> for NamedBoundVarSubstitutor<'a, 'tcx> { _ => (), }; - r.super_fold_with(self) + r } } @@ -1142,7 +1142,7 @@ impl<'tcx> TypeFolder> for ParamsSubstitutor<'tcx> { } }, - _ => r.super_fold_with(self), + _ => r, } } } @@ -1223,6 +1223,6 @@ impl<'tcx> TypeVisitor> for PlaceholdersCollector { _ => (), }; - r.super_visit_with(self) + ControlFlow::Continue(()) } } diff --git a/compiler/rustc_type_ir/src/fold.rs b/compiler/rustc_type_ir/src/fold.rs index 3a053d4c6a99..371c61191228 100644 --- a/compiler/rustc_type_ir/src/fold.rs +++ b/compiler/rustc_type_ir/src/fold.rs @@ -16,8 +16,10 @@ //! - Types of interest, for which the methods delegate to the folder. //! - All other types, including generic containers like `Vec` and `Option`. //! It defines a "skeleton" of how they should be folded. -//! - `TypeSuperFoldable`. This is implemented only for each type of interest, -//! and defines the folding "skeleton" for these types. +//! - `TypeSuperFoldable`. This is implemented only for recursive types of +//! interest, and defines the folding "skeleton" for these types. (This +//! excludes `Region` because it is non-recursive, i.e. it never contains +//! other types of interest.) //! - `TypeFolder`/`FallibleTypeFolder`. One of these is implemented for each //! folder. This defines how types of interest are folded. //! @@ -72,9 +74,9 @@ pub trait TypeFoldable: TypeVisitable { // This trait is implemented for types of interest. pub trait TypeSuperFoldable: TypeFoldable { - /// Provides a default fold for a type of interest. This should only be - /// called within `TypeFolder` methods, when a non-custom traversal is - /// desired for the value of the type of interest passed to that method. + /// Provides a default fold for a recursive type of interest. This should + /// only be called within `TypeFolder` methods, when a non-custom traversal + /// is desired for the value of the type of interest passed to that method. /// For example, in `MyFolder::try_fold_ty(ty)`, it is valid to call /// `ty.try_super_fold_with(self)`, but any other folding should be done /// with `xyz.try_fold_with(self)`. @@ -118,11 +120,11 @@ pub trait TypeFolder: FallibleTypeFolder { t.super_fold_with(self) } - fn fold_region(&mut self, r: I::Region) -> I::Region - where - I::Region: TypeSuperFoldable, - { - r.super_fold_with(self) + // The default region folder is a no-op because `Region` is non-recursive + // and has no `super_visit_with` method to call. That also explains the + // lack of `I::Region: TypeSuperFoldable` bound on this method. + fn fold_region(&mut self, r: I::Region) -> I::Region { + r } fn fold_const(&mut self, c: I::Const) -> I::Const @@ -167,11 +169,11 @@ pub trait FallibleTypeFolder: Sized { t.try_super_fold_with(self) } - fn try_fold_region(&mut self, r: I::Region) -> Result - where - I::Region: TypeSuperFoldable, - { - r.try_super_fold_with(self) + // The default region folder is a no-op because `Region` is non-recursive + // and has no `super_visit_with` method to call. That also explains the + // lack of `I::Region: TypeSuperFoldable` bound on this method. + fn try_fold_region(&mut self, r: I::Region) -> Result { + Ok(r) } fn try_fold_const(&mut self, c: I::Const) -> Result @@ -216,10 +218,7 @@ where Ok(self.fold_ty(t)) } - fn try_fold_region(&mut self, r: I::Region) -> Result - where - I::Region: TypeSuperFoldable, - { + fn try_fold_region(&mut self, r: I::Region) -> Result { Ok(self.fold_region(r)) } diff --git a/compiler/rustc_type_ir/src/visit.rs b/compiler/rustc_type_ir/src/visit.rs index 62239fd20066..878c7aec6c18 100644 --- a/compiler/rustc_type_ir/src/visit.rs +++ b/compiler/rustc_type_ir/src/visit.rs @@ -13,8 +13,11 @@ //! - Types of interest, for which the methods delegate to the visitor. //! - All other types, including generic containers like `Vec` and `Option`. //! It defines a "skeleton" of how they should be visited. -//! - `TypeSuperVisitable`. This is implemented only for each type of interest, -//! and defines the visiting "skeleton" for these types. +//! - `TypeSuperVisitable`. This is implemented only for recursive types of +//! interest, and defines the visiting "skeleton" for these types. (This +//! excludes `Region` because it is non-recursive, i.e. it never contains +//! other types of interest.) +//! //! - `TypeVisitor`. This is implemented for each visitor. This defines how //! types of interest are visited. //! @@ -62,12 +65,13 @@ pub trait TypeVisitable: fmt::Debug + Clone { fn visit_with>(&self, visitor: &mut V) -> ControlFlow; } +// This trait is implemented for types of interest. pub trait TypeSuperVisitable: TypeVisitable { - /// Provides a default visit for a type of interest. This should only be - /// called within `TypeVisitor` methods, when a non-custom traversal is - /// desired for the value of the type of interest passed to that method. - /// For example, in `MyVisitor::visit_ty(ty)`, it is valid to call - /// `ty.super_visit_with(self)`, but any other visiting should be done + /// Provides a default visit for a recursive type of interest. This should + /// only be called within `TypeVisitor` methods, when a non-custom + /// traversal is desired for the value of the type of interest passed to + /// that method. For example, in `MyVisitor::visit_ty(ty)`, it is valid to + /// call `ty.super_visit_with(self)`, but any other visiting should be done /// with `xyz.visit_with(self)`. fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow; } @@ -92,11 +96,11 @@ pub trait TypeVisitor: Sized { t.super_visit_with(self) } - fn visit_region(&mut self, r: I::Region) -> ControlFlow - where - I::Region: TypeSuperVisitable, - { - r.super_visit_with(self) + // The default region visitor is a no-op because `Region` is non-recursive + // and has no `super_visit_with` method to call. That also explains the + // lack of `I::Region: TypeSuperVisitable` bound. + fn visit_region(&mut self, _r: I::Region) -> ControlFlow { + ControlFlow::Continue(()) } fn visit_const(&mut self, c: I::Const) -> ControlFlow diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 9479b3ee0369..f6088f4e64a4 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -1,7 +1,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; -use rustc_middle::ty::{self, Region, RegionVid, TypeFoldable, TypeSuperFoldable}; +use rustc_middle::ty::{self, Region, RegionVid, TypeFoldable}; use rustc_trait_selection::traits::auto_trait::{self, AutoTraitResult}; use thin_vec::ThinVec; @@ -740,10 +740,9 @@ impl<'a, 'tcx> TypeFolder> for RegionReplacer<'a, 'tcx> { } fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { - (match *r { - ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned(), - _ => None, - }) - .unwrap_or_else(|| r.super_fold_with(self)) + match *r { + ty::ReVar(vid) => self.vid_to_region.get(&vid).cloned().unwrap_or(r), + _ => r, + } } } From 1ffa331c728d1e850922588499111232c56d86c7 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sun, 16 Apr 2023 15:03:00 +1000 Subject: [PATCH 091/116] Don't `use rustc_hir as ast`(!) It makes for confusing code. This was introduced in a large commit in #67886 that rearranged a lot of `use` statements. I suspect it was an accident. --- compiler/rustc_middle/src/ty/relate.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index 46c931d61dc9..c6d10f4741af 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -7,7 +7,7 @@ use crate::ty::error::{ExpectedFound, TypeError}; use crate::ty::{self, Expr, ImplSubject, Term, TermKind, Ty, TyCtxt, TypeFoldable}; use crate::ty::{GenericArg, GenericArgKind, SubstsRef}; -use rustc_hir as ast; +use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_target::spec::abi; use std::iter; @@ -123,8 +123,8 @@ pub fn relate_type_and_mut<'tcx, R: TypeRelation<'tcx>>( } else { let mutbl = a.mutbl; let (variance, info) = match mutbl { - ast::Mutability::Not => (ty::Covariant, ty::VarianceDiagInfo::None), - ast::Mutability::Mut => { + hir::Mutability::Not => (ty::Covariant, ty::VarianceDiagInfo::None), + hir::Mutability::Mut => { (ty::Invariant, ty::VarianceDiagInfo::Invariant { ty: base_ty, param_index: 0 }) } }; @@ -239,12 +239,12 @@ impl<'tcx> Relate<'tcx> for ty::BoundConstness { } } -impl<'tcx> Relate<'tcx> for ast::Unsafety { +impl<'tcx> Relate<'tcx> for hir::Unsafety { fn relate>( relation: &mut R, - a: ast::Unsafety, - b: ast::Unsafety, - ) -> RelateResult<'tcx, ast::Unsafety> { + a: hir::Unsafety, + b: hir::Unsafety, + ) -> RelateResult<'tcx, hir::Unsafety> { if a != b { Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b))) } else { From d0603fdafa61d1cc8c774f5845035d661093c7e9 Mon Sep 17 00:00:00 2001 From: John Bobbo Date: Sat, 15 Apr 2023 22:14:46 -0700 Subject: [PATCH 092/116] Use a `saturating_mul` instead of a `checked_mul` and `unwrap` in `core::intrinsics`. --- library/core/src/intrinsics.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index a7c100e1b23e..44ed9f76c481 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -2519,7 +2519,7 @@ pub(crate) fn is_valid_allocation_size(len: usize) -> bool { pub(crate) fn is_nonoverlapping(src: *const T, dst: *const T, count: usize) -> bool { let src_usize = src.addr(); let dst_usize = dst.addr(); - let size = mem::size_of::().checked_mul(count).unwrap(); + let size = mem::size_of::().saturating_mul(count); let diff = if src_usize > dst_usize { src_usize - dst_usize } else { dst_usize - src_usize }; // If the absolute distance between the ptrs is at least as big as the size of the buffer, // they do not overlap. From 77821b2eb95733c399dea13db99d19053237de98 Mon Sep 17 00:00:00 2001 From: est31 Date: Sun, 16 Apr 2023 08:35:39 +0200 Subject: [PATCH 093/116] Remove unused unused_macros The macro is always used --- library/core/tests/num/ieee754.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/library/core/tests/num/ieee754.rs b/library/core/tests/num/ieee754.rs index f6e5dfc98c79..48ab75b6f17a 100644 --- a/library/core/tests/num/ieee754.rs +++ b/library/core/tests/num/ieee754.rs @@ -39,7 +39,6 @@ macro_rules! assert_biteq { // ToString uses the default fmt::Display impl without special concerns, and bypasses other parts // of the formatting infrastructure, which makes it ideal for testing here. -#[allow(unused_macros)] macro_rules! roundtrip { ($f:expr => $t:ty) => { ($f).to_string().parse::<$t>().unwrap() From ee8f92ba0a3f1ceb74a9474f61761b3e3e3e5ac5 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sun, 16 Apr 2023 11:48:01 +0200 Subject: [PATCH 094/116] Use lints via `lint_defs` instead of `lints` This gets rid of a blocking dependency edge from `rustc_lint->rustc_analysis->rustc_hir_typeck->rustc_interface` --- Cargo.lock | 2 +- compiler/rustc_hir_analysis/Cargo.toml | 2 +- compiler/rustc_hir_analysis/src/check/check.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 12be36ef8612..094eb6fa67ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4775,7 +4775,7 @@ dependencies = [ "rustc_hir", "rustc_index", "rustc_infer", - "rustc_lint", + "rustc_lint_defs", "rustc_macros", "rustc_middle", "rustc_session", diff --git a/compiler/rustc_hir_analysis/Cargo.toml b/compiler/rustc_hir_analysis/Cargo.toml index fab16b80fb59..a64466884d8b 100644 --- a/compiler/rustc_hir_analysis/Cargo.toml +++ b/compiler/rustc_hir_analysis/Cargo.toml @@ -23,7 +23,7 @@ rustc_span = { path = "../rustc_span" } rustc_index = { path = "../rustc_index" } rustc_infer = { path = "../rustc_infer" } rustc_trait_selection = { path = "../rustc_trait_selection" } -rustc_lint = { path = "../rustc_lint" } +rustc_lint_defs = { path = "../rustc_lint_defs" } rustc_type_ir = { path = "../rustc_type_ir" } rustc_feature = { path = "../rustc_feature" } thin-vec = "0.2.12" diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 0bb98fdf2a23..0c54fd70c9b5 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -15,7 +15,7 @@ use rustc_infer::infer::opaque_types::ConstrainOpaqueTypeRegionVisitor; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{DefiningAnchor, RegionVariableOrigin, TyCtxtInferExt}; use rustc_infer::traits::{Obligation, TraitEngineExt as _}; -use rustc_lint::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS; +use rustc_lint_defs::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS; use rustc_middle::hir::nested_filter; use rustc_middle::middle::stability::EvalResult; use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES}; From 2109fe4e4e3cd8b81a4f91fab8be9a30f2eee8bc Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sun, 16 Apr 2023 12:03:39 +0200 Subject: [PATCH 095/116] Move some utils out of `rustc_const_eval` This allows us to get rid of the `rustc_const_eval->rustc_borrowck` dependency edge which was delaying the compilation of borrowck. The added utils in `rustc_middle` are small and should not affect compile times there. --- Cargo.lock | 1 - compiler/rustc_borrowck/Cargo.toml | 1 - compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs | 4 ++-- compiler/rustc_borrowck/src/diagnostics/mod.rs | 6 +++--- .../rustc_borrowck/src/diagnostics/mutability_errors.rs | 2 +- compiler/rustc_borrowck/src/lib.rs | 1 + .../src/util/collect_writes.rs | 0 compiler/rustc_borrowck/src/util/mod.rs | 3 +++ .../rustc_const_eval/src/transform/check_consts/ops.rs | 2 +- compiler/rustc_const_eval/src/util/mod.rs | 5 ----- compiler/rustc_middle/src/lib.rs | 6 +----- .../src/util/call_kind.rs | 4 ++-- .../src/util/find_self_call.rs | 6 +++--- compiler/rustc_middle/src/util/mod.rs | 7 +++++++ .../rustc_mir_transform/src/check_const_item_mutation.rs | 7 ++++++- 15 files changed, 30 insertions(+), 25 deletions(-) rename compiler/{rustc_const_eval => rustc_borrowck}/src/util/collect_writes.rs (100%) create mode 100644 compiler/rustc_borrowck/src/util/mod.rs rename compiler/{rustc_const_eval => rustc_middle}/src/util/call_kind.rs (97%) rename compiler/{rustc_const_eval => rustc_middle}/src/util/find_self_call.rs (92%) create mode 100644 compiler/rustc_middle/src/util/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 12be36ef8612..670f4cc95620 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4421,7 +4421,6 @@ dependencies = [ "either", "itertools", "polonius-engine", - "rustc_const_eval", "rustc_data_structures", "rustc_errors", "rustc_graphviz", diff --git a/compiler/rustc_borrowck/Cargo.toml b/compiler/rustc_borrowck/Cargo.toml index 87c113f3e30b..e0bb87336e54 100644 --- a/compiler/rustc_borrowck/Cargo.toml +++ b/compiler/rustc_borrowck/Cargo.toml @@ -20,7 +20,6 @@ rustc_infer = { path = "../rustc_infer" } rustc_lexer = { path = "../rustc_lexer" } rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } -rustc_const_eval = { path = "../rustc_const_eval" } rustc_mir_dataflow = { path = "../rustc_mir_dataflow" } rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 75a3dd0c0f3d..6259ae47e896 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -1,5 +1,4 @@ use either::Either; -use rustc_const_eval::util::CallKind; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{ @@ -18,6 +17,7 @@ use rustc_middle::mir::{ ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind, VarBindingForm, }; use rustc_middle::ty::{self, suggest_constraining_type_params, PredicateKind, Ty}; +use rustc_middle::util::CallKind; use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex}; use rustc_span::def_id::LocalDefId; use rustc_span::hygiene::DesugaringKind; @@ -2424,7 +2424,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { Some((method_did, method_substs)), ) = ( &self.body[loan.reserve_location.block].terminator, - rustc_const_eval::util::find_self_call( + rustc_middle::util::find_self_call( tcx, self.body, loan.assigned_place.local, diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 110354a20d83..dd003b5b0402 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -1,7 +1,6 @@ //! Borrow checker diagnostics. use itertools::Itertools; -use rustc_const_eval::util::{call_kind, CallDesugaringKind}; use rustc_errors::{Applicability, Diagnostic}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, Namespace}; @@ -15,6 +14,7 @@ use rustc_middle::mir::{ }; use rustc_middle::ty::print::Print; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; +use rustc_middle::util::{call_kind, CallDesugaringKind}; use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult}; use rustc_span::def_id::LocalDefId; use rustc_span::{symbol::sym, Span, Symbol, DUMMY_SP}; @@ -45,7 +45,7 @@ pub(crate) use mutability_errors::AccessKind; pub(crate) use outlives_suggestion::OutlivesSuggestionBuilder; pub(crate) use region_errors::{ErrorConstraintInfo, RegionErrorKind, RegionErrors}; pub(crate) use region_name::{RegionName, RegionNameSource}; -pub(crate) use rustc_const_eval::util::CallKind; +pub(crate) use rustc_middle::util::CallKind; pub(super) struct DescribePlaceOpt { pub including_downcast: bool, @@ -874,7 +874,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { }) = &self.body[location.block].terminator { let Some((method_did, method_substs)) = - rustc_const_eval::util::find_self_call( + rustc_middle::util::find_self_call( self.infcx.tcx, &self.body, target_temp, diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 9d9040096504..9c907147e5ad 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -15,8 +15,8 @@ use rustc_span::{sym, BytePos, Span}; use rustc_target::abi::FieldIdx; use crate::diagnostics::BorrowedContentSource; +use crate::util::FindAssignments; use crate::MirBorrowckCtxt; -use rustc_const_eval::util::collect_writes::FindAssignments; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) enum AccessKind { diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 70d0a101b4ed..fdd82c7e3b28 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -88,6 +88,7 @@ mod session_diagnostics; mod type_check; mod universal_regions; mod used_muts; +mod util; /// A public API provided for the Rust compiler consumers. pub mod consumers; diff --git a/compiler/rustc_const_eval/src/util/collect_writes.rs b/compiler/rustc_borrowck/src/util/collect_writes.rs similarity index 100% rename from compiler/rustc_const_eval/src/util/collect_writes.rs rename to compiler/rustc_borrowck/src/util/collect_writes.rs diff --git a/compiler/rustc_borrowck/src/util/mod.rs b/compiler/rustc_borrowck/src/util/mod.rs new file mode 100644 index 000000000000..7377d4de7274 --- /dev/null +++ b/compiler/rustc_borrowck/src/util/mod.rs @@ -0,0 +1,3 @@ +mod collect_writes; + +pub use collect_writes::FindAssignments; diff --git a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs index c0f5b3725b36..4fe842856aad 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs @@ -14,6 +14,7 @@ use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; use rustc_middle::ty::{suggest_constraining_type_param, Adt, Closure, FnDef, FnPtr, Param, Ty}; use rustc_middle::ty::{Binder, TraitRef}; +use rustc_middle::util::{call_kind, CallDesugaringKind, CallKind}; use rustc_session::parse::feature_err; use rustc_span::symbol::sym; use rustc_span::{BytePos, Pos, Span, Symbol}; @@ -21,7 +22,6 @@ use rustc_trait_selection::traits::SelectionContext; use super::ConstCx; use crate::errors; -use crate::util::{call_kind, CallDesugaringKind, CallKind}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Status { diff --git a/compiler/rustc_const_eval/src/util/mod.rs b/compiler/rustc_const_eval/src/util/mod.rs index c0aabd77ceea..7641f560714d 100644 --- a/compiler/rustc_const_eval/src/util/mod.rs +++ b/compiler/rustc_const_eval/src/util/mod.rs @@ -1,14 +1,9 @@ mod alignment; -mod call_kind; mod check_validity_requirement; -pub mod collect_writes; mod compare_types; -mod find_self_call; mod type_name; pub use self::alignment::is_disaligned; -pub use self::call_kind::{call_kind, CallDesugaringKind, CallKind}; pub use self::check_validity_requirement::check_validity_requirement; pub use self::compare_types::{is_equal_up_to_subtyping, is_subtype}; -pub use self::find_self_call::find_self_call; pub use self::type_name::type_name; diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index b4edb02f6c48..1ddc08eac7df 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -99,13 +99,9 @@ pub mod mir; pub mod thir; pub mod traits; pub mod ty; +pub mod util; mod values; -pub mod util { - pub mod bug; - pub mod common; -} - // Allows macros to refer to this crate as `::rustc_middle` extern crate self as rustc_middle; diff --git a/compiler/rustc_const_eval/src/util/call_kind.rs b/compiler/rustc_middle/src/util/call_kind.rs similarity index 97% rename from compiler/rustc_const_eval/src/util/call_kind.rs rename to compiler/rustc_middle/src/util/call_kind.rs index 995363c0edd9..627c84c388c0 100644 --- a/compiler/rustc_const_eval/src/util/call_kind.rs +++ b/compiler/rustc_middle/src/util/call_kind.rs @@ -2,10 +2,10 @@ //! as well as errors when attempting to call a non-const function in a const //! context. +use crate::ty::subst::SubstsRef; +use crate::ty::{AssocItemContainer, Instance, ParamEnv, Ty, TyCtxt}; use rustc_hir::def_id::DefId; use rustc_hir::{lang_items, LangItem}; -use rustc_middle::ty::subst::SubstsRef; -use rustc_middle::ty::{AssocItemContainer, Instance, ParamEnv, Ty, TyCtxt}; use rustc_span::symbol::Ident; use rustc_span::{sym, DesugaringKind, Span}; diff --git a/compiler/rustc_const_eval/src/util/find_self_call.rs b/compiler/rustc_middle/src/util/find_self_call.rs similarity index 92% rename from compiler/rustc_const_eval/src/util/find_self_call.rs rename to compiler/rustc_middle/src/util/find_self_call.rs index 33ad128eeeb7..0eab0adf07e4 100644 --- a/compiler/rustc_const_eval/src/util/find_self_call.rs +++ b/compiler/rustc_middle/src/util/find_self_call.rs @@ -1,6 +1,6 @@ -use rustc_middle::mir::*; -use rustc_middle::ty::subst::SubstsRef; -use rustc_middle::ty::{self, TyCtxt}; +use crate::mir::*; +use crate::ty::subst::SubstsRef; +use crate::ty::{self, TyCtxt}; use rustc_span::def_id::DefId; /// Checks if the specified `local` is used as the `self` parameter of a method call diff --git a/compiler/rustc_middle/src/util/mod.rs b/compiler/rustc_middle/src/util/mod.rs new file mode 100644 index 000000000000..53b4257899bc --- /dev/null +++ b/compiler/rustc_middle/src/util/mod.rs @@ -0,0 +1,7 @@ +pub mod bug; +pub mod call_kind; +pub mod common; +pub mod find_self_call; + +pub use call_kind::{call_kind, CallDesugaringKind, CallKind}; +pub use find_self_call::find_self_call; diff --git a/compiler/rustc_mir_transform/src/check_const_item_mutation.rs b/compiler/rustc_mir_transform/src/check_const_item_mutation.rs index 3d32c586554d..57b24c9c552a 100644 --- a/compiler/rustc_mir_transform/src/check_const_item_mutation.rs +++ b/compiler/rustc_mir_transform/src/check_const_item_mutation.rs @@ -134,7 +134,12 @@ impl<'tcx> Visitor<'tcx> for ConstMutationChecker<'_, 'tcx> { // the `self` parameter of a method call (as the terminator of our current // BasicBlock). If so, we emit a more specific lint. let method_did = self.target_local.and_then(|target_local| { - crate::util::find_self_call(self.tcx, &self.body, target_local, loc.block) + rustc_middle::util::find_self_call( + self.tcx, + &self.body, + target_local, + loc.block, + ) }); let lint_loc = if method_did.is_some() { self.body.terminator_loc(loc.block) } else { loc }; From bcc15bba953dcb749d88950539b5e206a8bd86bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 15 Apr 2023 20:49:54 +0200 Subject: [PATCH 096/116] use matches! macro in more places --- compiler/rustc_ast/src/ast.rs | 20 +++++++++---------- compiler/rustc_ast_lowering/src/lib.rs | 5 +---- compiler/rustc_hir/src/def.rs | 5 +---- compiler/rustc_hir_analysis/src/collect.rs | 5 +---- compiler/rustc_hir_typeck/src/expr.rs | 6 ++---- .../nice_region_error/static_impl_trait.rs | 11 ++++------ compiler/rustc_infer/src/infer/mod.rs | 8 ++++---- compiler/rustc_infer/src/traits/mod.rs | 8 ++++---- compiler/rustc_mir_build/src/errors.rs | 9 ++------- .../src/thir/pattern/check_match.rs | 6 ++---- compiler/rustc_parse/src/parser/item.rs | 14 ++++++------- .../rustc_parse/src/parser/nonterminal.rs | 10 ++++------ compiler/rustc_resolve/src/diagnostics.rs | 20 ++++++++++--------- 13 files changed, 52 insertions(+), 75 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index df1a716755b4..ab0409efb3b2 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -1298,17 +1298,17 @@ impl Expr { /// To a first-order approximation, is this a pattern? pub fn is_approximately_pattern(&self) -> bool { - match &self.peel_parens().kind { + matches!( + &self.peel_parens().kind, ExprKind::Array(_) - | ExprKind::Call(_, _) - | ExprKind::Tup(_) - | ExprKind::Lit(_) - | ExprKind::Range(_, _, _) - | ExprKind::Underscore - | ExprKind::Path(_, _) - | ExprKind::Struct(_) => true, - _ => false, - } + | ExprKind::Call(_, _) + | ExprKind::Tup(_) + | ExprKind::Lit(_) + | ExprKind::Range(_, _, _) + | ExprKind::Underscore + | ExprKind::Path(_, _) + | ExprKind::Struct(_) + ) } } diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index f7ae96b7c4a3..2af47e11637c 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -332,10 +332,7 @@ enum FnDeclKind { impl FnDeclKind { fn param_impl_trait_allowed(&self) -> bool { - match self { - FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait => true, - _ => false, - } + matches!(self, FnDeclKind::Fn | FnDeclKind::Inherent | FnDeclKind::Impl | FnDeclKind::Trait) } fn return_impl_trait_allowed(&self, tcx: TyCtxt<'_>) -> bool { diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index 8c58129c800f..30bf8c2ad104 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -234,10 +234,7 @@ impl DefKind { #[inline] pub fn is_fn_like(self) -> bool { - match self { - DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator => true, - _ => false, - } + matches!(self, DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Generator) } /// Whether `query get_codegen_attrs` should be used with this definition. diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index cbbaf8f857da..7c07a1ebaec0 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -1457,10 +1457,7 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( } fn is_foreign_item(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { - match tcx.hir().get_by_def_id(def_id) { - Node::ForeignItem(..) => true, - _ => false, - } + matches!(tcx.hir().get_by_def_id(def_id), Node::ForeignItem(..)) } fn generator_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 6ffa0134f3d5..ffc73d64fc04 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -1735,10 +1735,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { self.check_expr_has_type_or_error(base_expr, adt_ty, |_| { let base_ty = self.typeck_results.borrow().expr_ty(*base_expr); - let same_adt = match (adt_ty.kind(), base_ty.kind()) { - (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt => true, - _ => false, - }; + let same_adt = matches!((adt_ty.kind(), base_ty.kind()), + (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt); if self.tcx.sess.is_nightly_build() && same_adt { feature_err( &self.tcx.sess.parse_sess, diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs index 22c1e3871175..27c3b796d14e 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -312,13 +312,10 @@ pub fn suggest_new_region_bound( Applicability::MaybeIncorrect, ); } - } else if opaque.bounds.iter().any(|arg| match arg { - GenericBound::Outlives(Lifetime { ident, .. }) - if ident.name.to_string() == lifetime_name => - { - true - } - _ => false, + } else if opaque.bounds.iter().any(|arg| { + matches!(arg, + GenericBound::Outlives(Lifetime { ident, .. }) + if ident.name.to_string() == lifetime_name ) }) { } else { // get a lifetime name of existing named lifetimes if any diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 66f51328bbe7..f263a0773e4e 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -1577,10 +1577,10 @@ impl<'tcx> InferCtxt<'tcx> { (TyOrConstInferVar::Ty(ty_var), Ok(inner)) => { use self::type_variable::TypeVariableValue; - match inner.try_type_variables_probe_ref(ty_var) { - Some(TypeVariableValue::Unknown { .. }) => true, - _ => false, - } + matches!( + inner.try_type_variables_probe_ref(ty_var), + Some(TypeVariableValue::Unknown { .. }) + ) } _ => false, }; diff --git a/compiler/rustc_infer/src/traits/mod.rs b/compiler/rustc_infer/src/traits/mod.rs index e01b6caf4306..9dd4f0a8e4ce 100644 --- a/compiler/rustc_infer/src/traits/mod.rs +++ b/compiler/rustc_infer/src/traits/mod.rs @@ -89,10 +89,10 @@ impl<'tcx> PredicateObligation<'tcx> { impl<'tcx> TraitObligation<'tcx> { /// Returns `true` if the trait predicate is considered `const` in its ParamEnv. pub fn is_const(&self) -> bool { - match (self.predicate.skip_binder().constness, self.param_env.constness()) { - (ty::BoundConstness::ConstIfConst, hir::Constness::Const) => true, - _ => false, - } + matches!( + (self.predicate.skip_binder().constness, self.param_env.constness()), + (ty::BoundConstness::ConstIfConst, hir::Constness::Const) + ) } pub fn derived_cause( diff --git a/compiler/rustc_mir_build/src/errors.rs b/compiler/rustc_mir_build/src/errors.rs index 43e787db41a8..dcdeaf008d67 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -384,13 +384,8 @@ impl<'a> IntoDiagnostic<'a> for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_> { diag.span_note(span, fluent::mir_build_def_note); } - let is_variant_list_non_exhaustive = match self.ty.kind() { - ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local() => { - true - } - _ => false, - }; - + let is_variant_list_non_exhaustive = matches!(self.ty.kind(), + ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local()); if is_variant_list_non_exhaustive { diag.note(fluent::mir_build_non_exhaustive_type_note); } else { 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 bac46db2b1e6..0ef48c42f875 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -671,10 +671,8 @@ fn non_exhaustive_match<'p, 'tcx>( }; }; - let is_variant_list_non_exhaustive = match scrut_ty.kind() { - ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local() => true, - _ => false, - }; + let is_variant_list_non_exhaustive = matches!(scrut_ty.kind(), + ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local()); adt_defined_here(cx, &mut err, scrut_ty, &witnesses); err.note(&format!( diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 6422b8ac1ba4..f5fef6ad019e 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -2577,14 +2577,12 @@ impl<'a> Parser<'a> { } fn recover_self_param(&mut self) -> bool { - match self - .parse_outer_attributes() - .and_then(|_| self.parse_self_param()) - .map_err(|e| e.cancel()) - { - Ok(Some(_)) => true, - _ => false, - } + matches!( + self.parse_outer_attributes() + .and_then(|_| self.parse_self_param()) + .map_err(|e| e.cancel()), + Ok(Some(_)) + ) } } diff --git a/compiler/rustc_parse/src/parser/nonterminal.rs b/compiler/rustc_parse/src/parser/nonterminal.rs index 7a4d53ed8bbe..adb0d372a40d 100644 --- a/compiler/rustc_parse/src/parser/nonterminal.rs +++ b/compiler/rustc_parse/src/parser/nonterminal.rs @@ -20,12 +20,10 @@ impl<'a> Parser<'a> { pub fn nonterminal_may_begin_with(kind: NonterminalKind, token: &Token) -> bool { /// Checks whether the non-terminal may contain a single (non-keyword) identifier. fn may_be_ident(nt: &token::Nonterminal) -> bool { - match *nt { - token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) | token::NtLifetime(_) => { - false - } - _ => true, - } + !matches!( + *nt, + token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) | token::NtLifetime(_) + ) } match kind { diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 0c9d306081eb..c5ec19732be0 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -663,15 +663,17 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { Ident::with_dummy_span(name), Namespace::ValueNS, &parent_scope, - &|res: Res| match res { - Res::Def( - DefKind::Ctor(CtorOf::Variant, CtorKind::Const) - | DefKind::Ctor(CtorOf::Struct, CtorKind::Const) - | DefKind::Const - | DefKind::AssocConst, - _, - ) => true, - _ => false, + &|res: Res| { + matches!( + res, + Res::Def( + DefKind::Ctor(CtorOf::Variant, CtorKind::Const) + | DefKind::Ctor(CtorOf::Struct, CtorKind::Const) + | DefKind::Const + | DefKind::AssocConst, + _, + ) + ) }, ); From 6ef8648a4860e5d6108ebd21839c750de4f79dff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 15 Apr 2023 19:17:08 +0200 Subject: [PATCH 097/116] more clippy fixes: clippy::{iter_cloned_collect, unwarp_or_else_default, option_map_or_none} --- compiler/rustc_hir_analysis/src/check/compare_impl_item.rs | 2 +- compiler/rustc_mir_transform/src/coverage/debug.rs | 6 ++---- compiler/rustc_transmute/src/layout/tree.rs | 2 +- src/librustdoc/clean/auto_trait.rs | 2 +- 4 files changed, 5 insertions(+), 7 deletions(-) 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 5d119a7737a4..863a9977446c 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -1317,7 +1317,7 @@ fn compare_number_of_generics<'tcx>( impl_count, kind, pluralize!(impl_count), - suffix.unwrap_or_else(String::new), + suffix.unwrap_or_default(), ), ); } diff --git a/compiler/rustc_mir_transform/src/coverage/debug.rs b/compiler/rustc_mir_transform/src/coverage/debug.rs index 725883b83fa9..e554c4706468 100644 --- a/compiler/rustc_mir_transform/src/coverage/debug.rs +++ b/compiler/rustc_mir_transform/src/coverage/debug.rs @@ -292,10 +292,8 @@ impl DebugCounters { } pub fn some_block_label(&self, operand: ExpressionOperandId) -> Option<&String> { - self.some_counters.as_ref().map_or(None, |counters| { - counters - .get(&operand) - .map_or(None, |debug_counter| debug_counter.some_block_label.as_ref()) + self.some_counters.as_ref().and_then(|counters| { + counters.get(&operand).and_then(|debug_counter| debug_counter.some_block_label.as_ref()) }) } diff --git a/compiler/rustc_transmute/src/layout/tree.rs b/compiler/rustc_transmute/src/layout/tree.rs index 2a89494c80b0..a6d88b1342ae 100644 --- a/compiler/rustc_transmute/src/layout/tree.rs +++ b/compiler/rustc_transmute/src/layout/tree.rs @@ -196,7 +196,7 @@ pub(crate) mod rustc { fn from(err: LayoutError<'tcx>) -> Self { match err { LayoutError::Unknown(..) => Self::Unknown, - err @ _ => unimplemented!("{:?}", err), + err => unimplemented!("{:?}", err), } } } diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 9479b3ee0369..767ea8c3100f 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -141,7 +141,7 @@ where let f = auto_trait::AutoTraitFinder::new(tcx); debug!("get_auto_trait_impls({:?})", ty); - let auto_traits: Vec<_> = self.cx.auto_traits.iter().copied().collect(); + let auto_traits: Vec<_> = self.cx.auto_traits.to_vec(); let mut auto_traits: Vec = auto_traits .into_iter() .filter_map(|trait_def_id| { From 99fd9cb6971fc68d6865c2e2cf7722030001f609 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sun, 16 Apr 2023 04:01:34 -0700 Subject: [PATCH 098/116] Remove the loop in `Align::from_bytes` Perf is almost certainly irrelevant, but might as well simplify it, since `trailing_zeros` does exactly what's needed. --- compiler/rustc_abi/src/lib.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index b0c0ee942ea8..7a3defd2a5dc 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -665,15 +665,12 @@ impl Align { format!("`{}` is too large", align) } - let mut bytes = align; - let mut pow2: u8 = 0; - while (bytes & 1) == 0 { - pow2 += 1; - bytes >>= 1; - } - if bytes != 1 { + let tz = align.trailing_zeros(); + if align != (1 << tz) { return Err(not_power_of_2(align)); } + + let pow2 = tz as u8; if pow2 > Self::MAX.pow2 { return Err(too_large(align)); } From 543f8bc38c78c05319b5774ec2337c6d3c9b434b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 15 Apr 2023 20:18:30 +0200 Subject: [PATCH 099/116] fix clippy::toplevel_ref_arg and ::manual_map --- compiler/rustc_builtin_macros/src/format.rs | 8 +--- compiler/rustc_data_structures/src/sso/map.rs | 7 +--- compiler/rustc_lint/src/unused.rs | 39 ++++++++----------- .../src/const_prop_lint.rs | 2 +- compiler/rustc_parse/src/parser/attr.rs | 6 +-- compiler/rustc_resolve/src/diagnostics.rs | 10 ++--- compiler/rustc_span/src/lib.rs | 7 ++-- compiler/rustc_span/src/source_map.rs | 4 +- .../rustc_trait_selection/src/traits/util.rs | 9 +---- compiler/rustc_ty_utils/src/instance.rs | 11 ++---- .../rustc_ty_utils/src/structural_match.rs | 2 +- src/librustdoc/formats/cache.rs | 7 ++-- 12 files changed, 42 insertions(+), 70 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index f0fc61d7c4f2..f17df5b0a83c 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -141,13 +141,7 @@ fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult< args: args .named_args() .iter() - .filter_map(|a| { - if let Some(ident) = a.kind.ident() { - Some((a, ident)) - } else { - None - } - }) + .filter_map(|a| a.kind.ident().map(|ident| (a, ident))) .map(|(arg, n)| n.span.to(arg.expr.span)) .collect(), }); diff --git a/compiler/rustc_data_structures/src/sso/map.rs b/compiler/rustc_data_structures/src/sso/map.rs index 89b8c8526496..99581ed23759 100644 --- a/compiler/rustc_data_structures/src/sso/map.rs +++ b/compiler/rustc_data_structures/src/sso/map.rs @@ -256,12 +256,9 @@ impl SsoHashMap { pub fn remove(&mut self, key: &K) -> Option { match self { SsoHashMap::Array(array) => { - if let Some(index) = array.iter().position(|(k, _v)| k == key) { - Some(array.swap_remove(index).1) - } else { - None - } + array.iter().position(|(k, _v)| k == key).map(|index| array.swap_remove(index).1) } + SsoHashMap::Map(map) => map.remove(key), } } diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 1159d11e5c0c..80a64e59c0f0 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -636,20 +636,14 @@ trait UnusedDelimLint { return; } let spans = match value.kind { - ast::ExprKind::Block(ref block, None) if block.stmts.len() == 1 => { - if let Some(span) = block.stmts[0].span.find_ancestor_inside(value.span) { - Some((value.span.with_hi(span.lo()), value.span.with_lo(span.hi()))) - } else { - None - } - } + ast::ExprKind::Block(ref block, None) if block.stmts.len() == 1 => block.stmts[0] + .span + .find_ancestor_inside(value.span) + .map(|span| (value.span.with_hi(span.lo()), value.span.with_lo(span.hi()))), ast::ExprKind::Paren(ref expr) => { - let expr_span = expr.span.find_ancestor_inside(value.span); - if let Some(expr_span) = expr_span { - Some((value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi()))) - } else { - None - } + expr.span.find_ancestor_inside(value.span).map(|expr_span| { + (value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi())) + }) } _ => return, }; @@ -928,11 +922,10 @@ impl UnusedParens { // Otherwise proceed with linting. _ => {} } - let spans = if let Some(inner) = inner.span.find_ancestor_inside(value.span) { - Some((value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi()))) - } else { - None - }; + let spans = inner + .span + .find_ancestor_inside(value.span) + .map(|inner| (value.span.with_hi(inner.lo()), value.span.with_lo(inner.hi()))); self.emit_unused_delims(cx, value.span, spans, "pattern", keep_space); } } @@ -1043,11 +1036,11 @@ impl EarlyLintPass for UnusedParens { if self.with_self_ty_parens && b.generic_params.len() > 0 => {} ast::TyKind::ImplTrait(_, bounds) if bounds.len() > 1 => {} _ => { - let spans = if let Some(r) = r.span.find_ancestor_inside(ty.span) { - Some((ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi()))) - } else { - None - }; + let spans = r + .span + .find_ancestor_inside(ty.span) + .map(|r| (ty.span.with_hi(r.lo()), ty.span.with_lo(r.hi()))); + self.emit_unused_delims(cx, ty.span, spans, "type", (false, false)); } } diff --git a/compiler/rustc_mir_transform/src/const_prop_lint.rs b/compiler/rustc_mir_transform/src/const_prop_lint.rs index 699fe44892b2..3a105a2abaeb 100644 --- a/compiler/rustc_mir_transform/src/const_prop_lint.rs +++ b/compiler/rustc_mir_transform/src/const_prop_lint.rs @@ -493,7 +493,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { cond: &Operand<'tcx>, location: Location, ) -> Option { - let ref value = self.eval_operand(&cond, location)?; + let value = &self.eval_operand(&cond, location)?; trace!("assertion on {:?} should be {:?}", value, expected); let expected = Scalar::from_bool(expected); diff --git a/compiler/rustc_parse/src/parser/attr.rs b/compiler/rustc_parse/src/parser/attr.rs index e3e7c63e3448..e1db19557cfe 100644 --- a/compiler/rustc_parse/src/parser/attr.rs +++ b/compiler/rustc_parse/src/parser/attr.rs @@ -45,10 +45,10 @@ impl<'a> Parser<'a> { Some(InnerAttrForbiddenReason::AfterOuterDocComment { prev_doc_comment_span: prev_outer_attr_sp.unwrap(), }) - } else if let Some(prev_outer_attr_sp) = prev_outer_attr_sp { - Some(InnerAttrForbiddenReason::AfterOuterAttribute { prev_outer_attr_sp }) } else { - None + prev_outer_attr_sp.map(|prev_outer_attr_sp| { + InnerAttrForbiddenReason::AfterOuterAttribute { prev_outer_attr_sp } + }) }; let inner_parse_policy = InnerAttrPolicy::Forbidden(inner_error_reason); just_parsed_doc_comment = false; diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 0c9d306081eb..4f8e966ff667 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1867,15 +1867,13 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { Some(LexicalScopeBinding::Item(name_binding)) => Some(name_binding.span), _ => None, }; - let suggestion = if let Some(span) = match_span { - Some(( + let suggestion = match_span.map(|span| { + ( vec![(span, String::from(""))], format!("`{}` is defined here, but is not a type", ident), Applicability::MaybeIncorrect, - )) - } else { - None - }; + ) + }); (format!("use of undeclared type `{}`", ident), suggestion) } else { diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index aa8859ed1a35..1e9653d0c5bb 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -1663,10 +1663,11 @@ impl SourceFile { if let Some(ref src) = self.src { Some(Cow::from(get_until_newline(src, begin))) - } else if let Some(src) = self.external_src.borrow().get_source() { - Some(Cow::Owned(String::from(get_until_newline(src, begin)))) } else { - None + self.external_src + .borrow() + .get_source() + .map(|src| Cow::Owned(String::from(get_until_newline(src, begin)))) } } diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index 88e3674f8994..29a7e74a8166 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -906,10 +906,8 @@ impl SourceMap { let snippet = if let Some(ref src) = local_begin.sf.src { Some(&src[start_index..]) - } else if let Some(src) = src.get_source() { - Some(&src[start_index..]) } else { - None + src.get_source().map(|src| &src[start_index..]) }; match snippet { diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index 20357d4d2501..7792ceabe7e4 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -243,16 +243,11 @@ pub fn get_vtable_index_of_object_method<'tcx, N>( ) -> Option { // Count number of methods preceding the one we are selecting and // add them to the total offset. - if let Some(index) = tcx - .own_existential_vtable_entries(object.upcast_trait_ref.def_id()) + tcx.own_existential_vtable_entries(object.upcast_trait_ref.def_id()) .iter() .copied() .position(|def_id| def_id == method_def_id) - { - Some(object.vtable_base + index) - } else { - None - } + .map(|index| object.vtable_base + index) } pub fn closure_trait_ref_and_return_type<'tcx>( diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index 0a6c118093e5..47cd7af221d2 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -234,15 +234,12 @@ fn resolve_associated_item<'tcx>( _ => None, }, traits::ImplSource::Object(ref data) => { - if let Some(index) = traits::get_vtable_index_of_object_method(tcx, data, trait_item_id) - { - Some(Instance { + traits::get_vtable_index_of_object_method(tcx, data, trait_item_id).map(|index| { + Instance { def: ty::InstanceDef::Virtual(trait_item_id, index), substs: rcvr_substs, - }) - } else { - None - } + } + }) } traits::ImplSource::Builtin(..) => { let lang_items = tcx.lang_items(); diff --git a/compiler/rustc_ty_utils/src/structural_match.rs b/compiler/rustc_ty_utils/src/structural_match.rs index a55bb7e7e904..9cb0fc105943 100644 --- a/compiler/rustc_ty_utils/src/structural_match.rs +++ b/compiler/rustc_ty_utils/src/structural_match.rs @@ -13,7 +13,7 @@ use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt}; /// Note that this does *not* recursively check if the substructure of `adt_ty` /// implements the traits. fn has_structural_eq_impls<'tcx>(tcx: TyCtxt<'tcx>, adt_ty: Ty<'tcx>) -> bool { - let ref infcx = tcx.infer_ctxt().build(); + let infcx = &tcx.infer_ctxt().build(); let cause = ObligationCause::dummy(); let ocx = ObligationCtxt::new(infcx); diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs index c0329182032a..841abfab666b 100644 --- a/src/librustdoc/formats/cache.rs +++ b/src/librustdoc/formats/cache.rs @@ -300,14 +300,13 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { ParentStackItem::Impl { for_, .. } => for_.def_id(&self.cache), ParentStackItem::Type(item_id) => item_id.as_def_id(), }; - let path = match did.and_then(|did| self.cache.paths.get(&did)) { + 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. - Some((fqp, _)) => Some(&fqp[..fqp.len() - 1]), - None => None, - }; + .map(|(fqp, _)| &fqp[..fqp.len() - 1]); ((did, path), true) } } From 606ca4da7ea3ba7ea4caec41709bd4952daf3c3b Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Sun, 12 Mar 2023 18:30:33 -0400 Subject: [PATCH 100/116] Report a backtrace for memory leaks under Miri --- .../src/interpret/eval_context.rs | 7 +--- .../rustc_const_eval/src/interpret/machine.rs | 2 +- .../rustc_const_eval/src/interpret/memory.rs | 27 +++++++------ src/tools/miri/src/borrow_tracker/mod.rs | 2 +- src/tools/miri/src/diagnostics.rs | 39 +++++++++++++++++-- src/tools/miri/src/eval.rs | 11 ++++-- src/tools/miri/src/machine.rs | 39 +++++++++++++------ src/tools/miri/src/tag_gc.rs | 2 +- src/tools/miri/tests/fail/memleak.rs | 2 +- src/tools/miri/tests/fail/memleak.stderr | 23 ++++++++--- .../miri/tests/fail/memleak_rc.32bit.stderr | 24 +++++++++--- .../miri/tests/fail/memleak_rc.64bit.stderr | 25 ++++++++---- src/tools/miri/tests/fail/memleak_rc.rs | 2 +- 13 files changed, 145 insertions(+), 60 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 3e58a58aef7d..b5b5cc4f1963 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -132,11 +132,10 @@ pub struct Frame<'mir, 'tcx, Prov: Provenance = AllocId, Extra = ()> { } /// What we store about a frame in an interpreter backtrace. -#[derive(Debug)] +#[derive(Clone, Debug)] pub struct FrameInfo<'tcx> { pub instance: ty::Instance<'tcx>, pub span: Span, - pub lint_root: Option, } #[derive(Clone, Copy, Eq, PartialEq, Debug)] // Miri debug-prints these @@ -947,10 +946,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // This deliberately does *not* honor `requires_caller_location` since it is used for much // more than just panics. for frame in stack.iter().rev() { - let lint_root = frame.lint_root(); let span = frame.current_span(); - - frames.push(FrameInfo { span, instance: frame.instance, lint_root }); + frames.push(FrameInfo { span, instance: frame.instance }); } trace!("generate stacktrace: {:#?}", frames); frames diff --git a/compiler/rustc_const_eval/src/interpret/machine.rs b/compiler/rustc_const_eval/src/interpret/machine.rs index 0291cca7378a..b448e3a24c68 100644 --- a/compiler/rustc_const_eval/src/interpret/machine.rs +++ b/compiler/rustc_const_eval/src/interpret/machine.rs @@ -104,7 +104,7 @@ pub trait Machine<'mir, 'tcx>: Sized { type FrameExtra; /// Extra data stored in every allocation. - type AllocExtra: Debug + Clone + 'static; + type AllocExtra: Debug + Clone + 'tcx; /// Type for the bytes of the allocation. type Bytes: AllocBytes + 'static; diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index a3764a7d1426..d5b6a581a79f 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -215,7 +215,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { self.allocate_raw_ptr(alloc, kind) } - /// This can fail only of `alloc` contains provenance. + /// This can fail only if `alloc` contains provenance. pub fn allocate_raw_ptr( &mut self, alloc: Allocation, @@ -807,9 +807,13 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { DumpAllocs { ecx: self, allocs } } - /// Print leaked memory. Allocations reachable from `static_roots` or a `Global` allocation - /// are not considered leaked. Leaks whose kind `may_leak()` returns true are not reported. - pub fn leak_report(&self, static_roots: &[AllocId]) -> usize { + /// Find leaked allocations. Allocations reachable from `static_roots` or a `Global` allocation + /// are not considered leaked, as well as leaks whose kind's `may_leak()` returns true. + pub fn find_leaked_allocations( + &self, + static_roots: &[AllocId], + ) -> Vec<(AllocId, MemoryKind, Allocation)> + { // Collect the set of allocations that are *reachable* from `Global` allocations. let reachable = { let mut reachable = FxHashSet::default(); @@ -833,14 +837,13 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { }; // All allocations that are *not* `reachable` and *not* `may_leak` are considered leaking. - let leaks: Vec<_> = self.memory.alloc_map.filter_map_collect(|&id, &(kind, _)| { - if kind.may_leak() || reachable.contains(&id) { None } else { Some(id) } - }); - let n = leaks.len(); - if n > 0 { - eprintln!("The following memory was leaked: {:?}", self.dump_allocs(leaks)); - } - n + self.memory.alloc_map.filter_map_collect(|id, (kind, alloc)| { + if kind.may_leak() || reachable.contains(id) { + None + } else { + Some((*id, *kind, alloc.clone())) + } + }) } } diff --git a/src/tools/miri/src/borrow_tracker/mod.rs b/src/tools/miri/src/borrow_tracker/mod.rs index ed958329f951..d54adb72887a 100644 --- a/src/tools/miri/src/borrow_tracker/mod.rs +++ b/src/tools/miri/src/borrow_tracker/mod.rs @@ -352,7 +352,7 @@ pub enum AllocState { TreeBorrows(Box>), } -impl machine::AllocExtra { +impl machine::AllocExtra<'_> { #[track_caller] pub fn borrow_tracker_sb(&self) -> &RefCell { match self.borrow_tracker { diff --git a/src/tools/miri/src/diagnostics.rs b/src/tools/miri/src/diagnostics.rs index 3c13118122ca..7a726be00da4 100644 --- a/src/tools/miri/src/diagnostics.rs +++ b/src/tools/miri/src/diagnostics.rs @@ -105,7 +105,7 @@ pub enum NonHaltingDiagnostic { } /// Level of Miri specific diagnostics -enum DiagLevel { +pub enum DiagLevel { Error, Warning, Note, @@ -114,7 +114,7 @@ enum DiagLevel { /// Attempts to prune a stacktrace to omit the Rust runtime, and returns a bool indicating if any /// frames were pruned. If the stacktrace does not have any local frames, we conclude that it must /// be pointing to a problem in the Rust runtime itself, and do not prune it at all. -fn prune_stacktrace<'tcx>( +pub fn prune_stacktrace<'tcx>( mut stacktrace: Vec>, machine: &MiriMachine<'_, 'tcx>, ) -> (Vec>, bool) { @@ -338,12 +338,45 @@ pub fn report_error<'tcx, 'mir>( None } +pub fn report_leaks<'mir, 'tcx>( + ecx: &InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>, + leaks: Vec<(AllocId, MemoryKind, Allocation>)>, +) { + let mut any_pruned = false; + for (id, kind, mut alloc) in leaks { + let Some(backtrace) = alloc.extra.backtrace.take() else { + continue; + }; + let (backtrace, pruned) = prune_stacktrace(backtrace, &ecx.machine); + any_pruned |= pruned; + report_msg( + DiagLevel::Error, + &format!( + "memory leaked: {id:?} ({}, size: {:?}, align: {:?}), allocated here:", + kind, + alloc.size().bytes(), + alloc.align.bytes() + ), + vec![], + vec![], + vec![], + &backtrace, + &ecx.machine, + ); + } + if any_pruned { + ecx.tcx.sess.diagnostic().note_without_error( + "some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace", + ); + } +} + /// Report an error or note (depending on the `error` argument) with the given stacktrace. /// Also emits a full stacktrace of the interpreter stack. /// We want to present a multi-line span message for some errors. Diagnostics do not support this /// directly, so we pass the lines as a `Vec` and display each line after the first with an /// additional `span_label` or `note` call. -fn report_msg<'tcx>( +pub fn report_msg<'tcx>( diag_level: DiagLevel, title: &str, span_msg: Vec, diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index a32b18595b53..60533687bed5 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -10,6 +10,7 @@ use std::thread; use log::info; use crate::borrow_tracker::RetagFields; +use crate::diagnostics::report_leaks; use rustc_data_structures::fx::FxHashSet; use rustc_hir::def::Namespace; use rustc_hir::def_id::DefId; @@ -457,10 +458,12 @@ pub fn eval_entry<'tcx>( } // Check for memory leaks. info!("Additonal static roots: {:?}", ecx.machine.static_roots); - let leaks = ecx.leak_report(&ecx.machine.static_roots); - if leaks != 0 { - tcx.sess.err("the evaluated program leaked memory"); - tcx.sess.note_without_error("pass `-Zmiri-ignore-leaks` to disable this check"); + let leaks = ecx.find_leaked_allocations(&ecx.machine.static_roots); + if !leaks.is_empty() { + report_leaks(&ecx, leaks); + tcx.sess.note_without_error( + "the evaluated program leaked memory, pass `-Zmiri-ignore-leaks` to disable this check", + ); // Ignore the provided return code - let the reported error // determine the return code. return None; diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index 477d8d33ebba..a9c1357fcf29 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -253,20 +253,24 @@ impl ProvenanceExtra { /// Extra per-allocation data #[derive(Debug, Clone)] -pub struct AllocExtra { +pub struct AllocExtra<'tcx> { /// Global state of the borrow tracker, if enabled. pub borrow_tracker: Option, - /// Data race detection via the use of a vector-clock, - /// this is only added if it is enabled. + /// Data race detection via the use of a vector-clock. + /// This is only added if it is enabled. pub data_race: Option, - /// Weak memory emulation via the use of store buffers, - /// this is only added if it is enabled. + /// Weak memory emulation via the use of store buffers. + /// This is only added if it is enabled. pub weak_memory: Option, + /// A backtrace to where this allocation was allocated. + /// As this is recorded for leak reports, it only exists + /// if this allocation is leakable. + pub backtrace: Option>>, } -impl VisitTags for AllocExtra { +impl VisitTags for AllocExtra<'_> { fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) { - let AllocExtra { borrow_tracker, data_race, weak_memory } = self; + let AllocExtra { borrow_tracker, data_race, weak_memory, backtrace: _ } = self; borrow_tracker.visit_tags(visit); data_race.visit_tags(visit); @@ -773,7 +777,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { type ExtraFnVal = Dlsym; type FrameExtra = FrameExtra<'tcx>; - type AllocExtra = AllocExtra; + type AllocExtra = AllocExtra<'tcx>; type Provenance = Provenance; type ProvenanceExtra = ProvenanceExtra; @@ -967,9 +971,20 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { ) }); let buffer_alloc = ecx.machine.weak_memory.then(weak_memory::AllocState::new_allocation); + + // If an allocation is leaked, we want to report a backtrace to indicate where it was + // allocated. We don't need to record a backtrace for allocations which are allowed to + // leak. + let backtrace = if kind.may_leak() { None } else { Some(ecx.generate_stacktrace()) }; + let alloc: Allocation = alloc.adjust_from_tcx( &ecx.tcx, - AllocExtra { borrow_tracker, data_race: race_alloc, weak_memory: buffer_alloc }, + AllocExtra { + borrow_tracker, + data_race: race_alloc, + weak_memory: buffer_alloc, + backtrace, + }, |ptr| ecx.global_base_pointer(ptr), )?; Ok(Cow::Owned(alloc)) @@ -1049,7 +1064,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { fn before_memory_read( _tcx: TyCtxt<'tcx>, machine: &Self, - alloc_extra: &AllocExtra, + alloc_extra: &AllocExtra<'tcx>, (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra), range: AllocRange, ) -> InterpResult<'tcx> { @@ -1069,7 +1084,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { fn before_memory_write( _tcx: TyCtxt<'tcx>, machine: &mut Self, - alloc_extra: &mut AllocExtra, + alloc_extra: &mut AllocExtra<'tcx>, (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra), range: AllocRange, ) -> InterpResult<'tcx> { @@ -1089,7 +1104,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { fn before_memory_deallocation( _tcx: TyCtxt<'tcx>, machine: &mut Self, - alloc_extra: &mut AllocExtra, + alloc_extra: &mut AllocExtra<'tcx>, (alloc_id, prove_extra): (AllocId, Self::ProvenanceExtra), range: AllocRange, ) -> InterpResult<'tcx> { diff --git a/src/tools/miri/src/tag_gc.rs b/src/tools/miri/src/tag_gc.rs index c1194fe22163..cefdcc2b5b83 100644 --- a/src/tools/miri/src/tag_gc.rs +++ b/src/tools/miri/src/tag_gc.rs @@ -125,7 +125,7 @@ impl VisitTags for Operand { } } -impl VisitTags for Allocation { +impl VisitTags for Allocation> { fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) { for prov in self.provenance().provenances() { prov.visit_tags(visit); diff --git a/src/tools/miri/tests/fail/memleak.rs b/src/tools/miri/tests/fail/memleak.rs index d384caf81a57..cbeb163b56c3 100644 --- a/src/tools/miri/tests/fail/memleak.rs +++ b/src/tools/miri/tests/fail/memleak.rs @@ -1,4 +1,4 @@ -//@error-pattern: the evaluated program leaked memory +//@error-pattern: memory leaked //@normalize-stderr-test: ".*│.*" -> "$$stripped$$" fn main() { diff --git a/src/tools/miri/tests/fail/memleak.stderr b/src/tools/miri/tests/fail/memleak.stderr index f8b62af3eb85..9b23a71f5abb 100644 --- a/src/tools/miri/tests/fail/memleak.stderr +++ b/src/tools/miri/tests/fail/memleak.stderr @@ -1,10 +1,21 @@ -The following memory was leaked: ALLOC (Rust heap, size: 4, align: 4) { -$stripped$ -} +error: memory leaked: ALLOC (Rust heap, size: 4, align: 4), allocated here: + --> RUSTLIB/alloc/src/alloc.rs:LL:CC + | +LL | unsafe { __rust_alloc(layout.size(), layout.align()) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: inside `std::alloc::alloc` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `std::alloc::Global::alloc_impl` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `::allocate` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `alloc::alloc::exchange_malloc` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `std::boxed::Box::::new` at RUSTLIB/alloc/src/boxed.rs:LL:CC +note: inside `main` + --> $DIR/memleak.rs:LL:CC + | +LL | std::mem::forget(Box::new(42)); + | ^^^^^^^^^^^^ -error: the evaluated program leaked memory - -note: pass `-Zmiri-ignore-leaks` to disable this check +note: the evaluated program leaked memory, pass `-Zmiri-ignore-leaks` to disable this check error: aborting due to previous error diff --git a/src/tools/miri/tests/fail/memleak_rc.32bit.stderr b/src/tools/miri/tests/fail/memleak_rc.32bit.stderr index da222609091a..0eaf84048e0a 100644 --- a/src/tools/miri/tests/fail/memleak_rc.32bit.stderr +++ b/src/tools/miri/tests/fail/memleak_rc.32bit.stderr @@ -1,10 +1,22 @@ -The following memory was leaked: ALLOC (Rust heap, size: 16, align: 4) { -$stripped$ -} +error: memory leaked: ALLOC (Rust heap, size: 16, align: 4), allocated here: + --> RUSTLIB/alloc/src/alloc.rs:LL:CC + | +LL | unsafe { __rust_alloc(layout.size(), layout.align()) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: inside `std::alloc::alloc` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `std::alloc::Global::alloc_impl` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `::allocate` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `alloc::alloc::exchange_malloc` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `std::boxed::Box::>>>::new` at RUSTLIB/alloc/src/boxed.rs:LL:CC + = note: inside `std::rc::Rc::>>::new` at RUSTLIB/alloc/src/rc.rs:LL:CC +note: inside `main` + --> $DIR/memleak_rc.rs:LL:CC + | +LL | let x = Dummy(Rc::new(RefCell::new(None))); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: the evaluated program leaked memory - -note: pass `-Zmiri-ignore-leaks` to disable this check +note: the evaluated program leaked memory, pass `-Zmiri-ignore-leaks` to disable this check error: aborting due to previous error diff --git a/src/tools/miri/tests/fail/memleak_rc.64bit.stderr b/src/tools/miri/tests/fail/memleak_rc.64bit.stderr index 8c24bbc779bd..9b7adc00ef5c 100644 --- a/src/tools/miri/tests/fail/memleak_rc.64bit.stderr +++ b/src/tools/miri/tests/fail/memleak_rc.64bit.stderr @@ -1,11 +1,22 @@ -The following memory was leaked: ALLOC (Rust heap, size: 32, align: 8) { -$stripped$ -$stripped$ -} +error: memory leaked: ALLOC (Rust heap, size: 32, align: 8), allocated here: + --> RUSTLIB/alloc/src/alloc.rs:LL:CC + | +LL | unsafe { __rust_alloc(layout.size(), layout.align()) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: inside `std::alloc::alloc` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `std::alloc::Global::alloc_impl` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `::allocate` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `alloc::alloc::exchange_malloc` at RUSTLIB/alloc/src/alloc.rs:LL:CC + = note: inside `std::boxed::Box::>>>::new` at RUSTLIB/alloc/src/boxed.rs:LL:CC + = note: inside `std::rc::Rc::>>::new` at RUSTLIB/alloc/src/rc.rs:LL:CC +note: inside `main` + --> $DIR/memleak_rc.rs:LL:CC + | +LL | let x = Dummy(Rc::new(RefCell::new(None))); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: the evaluated program leaked memory - -note: pass `-Zmiri-ignore-leaks` to disable this check +note: the evaluated program leaked memory, pass `-Zmiri-ignore-leaks` to disable this check error: aborting due to previous error diff --git a/src/tools/miri/tests/fail/memleak_rc.rs b/src/tools/miri/tests/fail/memleak_rc.rs index 76ecd71b011a..cf4671912ada 100644 --- a/src/tools/miri/tests/fail/memleak_rc.rs +++ b/src/tools/miri/tests/fail/memleak_rc.rs @@ -1,4 +1,4 @@ -//@error-pattern: the evaluated program leaked memory +//@error-pattern: memory leaked //@stderr-per-bitwidth //@normalize-stderr-test: ".*│.*" -> "$$stripped$$" From cbc7f94f113f7ae97db7e04b7f71b753c8349435 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Mon, 10 Apr 2023 22:37:11 -0400 Subject: [PATCH 101/116] Add a flag to disable leak backtraces --- src/tools/miri/README.md | 14 +++++++++----- src/tools/miri/src/bin/miri.rs | 3 +++ src/tools/miri/src/eval.rs | 14 +++++++++++--- src/tools/miri/src/machine.rs | 13 ++++++++++++- src/tools/miri/tests/fail/memleak.stderr | 2 ++ src/tools/miri/tests/fail/memleak_no_backtrace.rs | 7 +++++++ .../miri/tests/fail/memleak_no_backtrace.stderr | 4 ++++ src/tools/miri/tests/fail/memleak_rc.32bit.stderr | 2 ++ src/tools/miri/tests/fail/memleak_rc.64bit.stderr | 2 ++ 9 files changed, 52 insertions(+), 9 deletions(-) create mode 100644 src/tools/miri/tests/fail/memleak_no_backtrace.rs create mode 100644 src/tools/miri/tests/fail/memleak_no_backtrace.stderr diff --git a/src/tools/miri/README.md b/src/tools/miri/README.md index 4c7351879877..04a1d939d2e5 100644 --- a/src/tools/miri/README.md +++ b/src/tools/miri/README.md @@ -301,6 +301,15 @@ environment variable. We first document the most relevant and most commonly used * `-Zmiri-disable-isolation` disables host isolation. As a consequence, the program has access to host resources such as environment variables, file systems, and randomness. +* `-Zmiri-disable-leak-backtraces` disables backtraces reports for memory leaks. By default, a + backtrace is captured for every allocation when it is created, just in case it leaks. This incurs + some memory overhead to store data that is almost never used. This flag is implied by + `-Zmiri-ignore-leaks`. +* `-Zmiri-env-forward=` forwards the `var` environment variable to the interpreted program. Can + be used multiple times to forward several variables. Execution will still be deterministic if the + value of forwarded variables stays the same. Has no effect if `-Zmiri-disable-isolation` is set. +* `-Zmiri-ignore-leaks` disables the memory leak checker, and also allows some + remaining threads to exist when the main thread exits. * `-Zmiri-isolation-error=` configures Miri's response to operations requiring host access while isolation is enabled. `abort`, `hide`, `warn`, and `warn-nobacktrace` are the supported actions. The default is to `abort`, @@ -308,11 +317,6 @@ environment variable. We first document the most relevant and most commonly used execution with a "permission denied" error being returned to the program. `warn` prints a full backtrace when that happens; `warn-nobacktrace` is less verbose. `hide` hides the warning entirely. -* `-Zmiri-env-forward=` forwards the `var` environment variable to the interpreted program. Can - be used multiple times to forward several variables. Execution will still be deterministic if the - value of forwarded variables stays the same. Has no effect if `-Zmiri-disable-isolation` is set. -* `-Zmiri-ignore-leaks` disables the memory leak checker, and also allows some - remaining threads to exist when the main thread exits. * `-Zmiri-num-cpus` states the number of available CPUs to be reported by miri. By default, the number of available CPUs is `1`. Note that this flag does not affect how miri handles threads in any way. diff --git a/src/tools/miri/src/bin/miri.rs b/src/tools/miri/src/bin/miri.rs index 26a7ead2407c..3aa71bb7e3c8 100644 --- a/src/tools/miri/src/bin/miri.rs +++ b/src/tools/miri/src/bin/miri.rs @@ -359,6 +359,8 @@ fn main() { isolation_enabled = Some(false); } miri_config.isolated_op = miri::IsolatedOp::Allow; + } else if arg == "-Zmiri-disable-leak-backtraces" { + miri_config.collect_leak_backtraces = false; } else if arg == "-Zmiri-disable-weak-memory-emulation" { miri_config.weak_memory_emulation = false; } else if arg == "-Zmiri-track-weak-memory-loads" { @@ -385,6 +387,7 @@ fn main() { }; } else if arg == "-Zmiri-ignore-leaks" { miri_config.ignore_leaks = true; + miri_config.collect_leak_backtraces = false; } else if arg == "-Zmiri-panic-on-unsupported" { miri_config.panic_on_unsupported = true; } else if arg == "-Zmiri-tag-raw-pointers" { diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index 60533687bed5..defd37c37757 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -146,6 +146,8 @@ pub struct MiriConfig { pub num_cpus: u32, /// Requires Miri to emulate pages of a certain size pub page_size: Option, + /// Whether to collect a backtrace when each allocation is created, just in case it leaks. + pub collect_leak_backtraces: bool, } impl Default for MiriConfig { @@ -180,6 +182,7 @@ impl Default for MiriConfig { gc_interval: 10_000, num_cpus: 1, page_size: None, + collect_leak_backtraces: true, } } } @@ -461,9 +464,14 @@ pub fn eval_entry<'tcx>( let leaks = ecx.find_leaked_allocations(&ecx.machine.static_roots); if !leaks.is_empty() { report_leaks(&ecx, leaks); - tcx.sess.note_without_error( - "the evaluated program leaked memory, pass `-Zmiri-ignore-leaks` to disable this check", - ); + let leak_message = "the evaluated program leaked memory, pass `-Zmiri-ignore-leaks` to disable this check"; + if ecx.machine.collect_leak_backtraces { + // If we are collecting leak backtraces, each leak is a distinct error diagnostic. + tcx.sess.note_without_error(leak_message); + } else { + // If we do not have backtraces, we just report an error without any span. + tcx.sess.err(leak_message); + }; // Ignore the provided return code - let the reported error // determine the return code. return None; diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index a9c1357fcf29..37f54a4a5bd4 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -471,12 +471,17 @@ pub struct MiriMachine<'mir, 'tcx> { pub(crate) gc_interval: u32, /// The number of blocks that passed since the last BorTag GC pass. pub(crate) since_gc: u32, + /// The number of CPUs to be reported by miri. pub(crate) num_cpus: u32, + /// Determines Miri's page size and associated values pub(crate) page_size: u64, pub(crate) stack_addr: u64, pub(crate) stack_size: u64, + + /// Whether to collect a backtrace when each allocation is created, just in case it leaks. + pub(crate) collect_leak_backtraces: bool, } impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> { @@ -585,6 +590,7 @@ impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> { page_size, stack_addr, stack_size, + collect_leak_backtraces: config.collect_leak_backtraces, } } @@ -732,6 +738,7 @@ impl VisitTags for MiriMachine<'_, '_> { page_size: _, stack_addr: _, stack_size: _, + collect_leak_backtraces: _, } = self; threads.visit_tags(visit); @@ -975,7 +982,11 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { // If an allocation is leaked, we want to report a backtrace to indicate where it was // allocated. We don't need to record a backtrace for allocations which are allowed to // leak. - let backtrace = if kind.may_leak() { None } else { Some(ecx.generate_stacktrace()) }; + let backtrace = if kind.may_leak() || !ecx.machine.collect_leak_backtraces { + None + } else { + Some(ecx.generate_stacktrace()) + }; let alloc: Allocation = alloc.adjust_from_tcx( &ecx.tcx, diff --git a/src/tools/miri/tests/fail/memleak.stderr b/src/tools/miri/tests/fail/memleak.stderr index 9b23a71f5abb..6d9b664c8f48 100644 --- a/src/tools/miri/tests/fail/memleak.stderr +++ b/src/tools/miri/tests/fail/memleak.stderr @@ -15,6 +15,8 @@ note: inside `main` LL | std::mem::forget(Box::new(42)); | ^^^^^^^^^^^^ +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + note: the evaluated program leaked memory, pass `-Zmiri-ignore-leaks` to disable this check error: aborting due to previous error diff --git a/src/tools/miri/tests/fail/memleak_no_backtrace.rs b/src/tools/miri/tests/fail/memleak_no_backtrace.rs new file mode 100644 index 000000000000..24d4a02df712 --- /dev/null +++ b/src/tools/miri/tests/fail/memleak_no_backtrace.rs @@ -0,0 +1,7 @@ +//@compile-flags: -Zmiri-disable-leak-backtraces +//@error-pattern: the evaluated program leaked memory +//@normalize-stderr-test: ".*│.*" -> "$$stripped$$" + +fn main() { + std::mem::forget(Box::new(42)); +} diff --git a/src/tools/miri/tests/fail/memleak_no_backtrace.stderr b/src/tools/miri/tests/fail/memleak_no_backtrace.stderr new file mode 100644 index 000000000000..f44e6ce07977 --- /dev/null +++ b/src/tools/miri/tests/fail/memleak_no_backtrace.stderr @@ -0,0 +1,4 @@ +error: the evaluated program leaked memory, pass `-Zmiri-ignore-leaks` to disable this check + +error: aborting due to previous error + diff --git a/src/tools/miri/tests/fail/memleak_rc.32bit.stderr b/src/tools/miri/tests/fail/memleak_rc.32bit.stderr index 0eaf84048e0a..0e1146cf4ad9 100644 --- a/src/tools/miri/tests/fail/memleak_rc.32bit.stderr +++ b/src/tools/miri/tests/fail/memleak_rc.32bit.stderr @@ -16,6 +16,8 @@ note: inside `main` LL | let x = Dummy(Rc::new(RefCell::new(None))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + note: the evaluated program leaked memory, pass `-Zmiri-ignore-leaks` to disable this check error: aborting due to previous error diff --git a/src/tools/miri/tests/fail/memleak_rc.64bit.stderr b/src/tools/miri/tests/fail/memleak_rc.64bit.stderr index 9b7adc00ef5c..4979588f370f 100644 --- a/src/tools/miri/tests/fail/memleak_rc.64bit.stderr +++ b/src/tools/miri/tests/fail/memleak_rc.64bit.stderr @@ -16,6 +16,8 @@ note: inside `main` LL | let x = Dummy(Rc::new(RefCell::new(None))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + note: the evaluated program leaked memory, pass `-Zmiri-ignore-leaks` to disable this check error: aborting due to previous error From fb68292b24e5bd14c04d820fd352722cc060c789 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Mon, 10 Apr 2023 22:38:29 -0400 Subject: [PATCH 102/116] Improve doc comment of AllocExtra's backtrace Co-authored-by: Ralf Jung --- src/tools/miri/src/machine.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index 37f54a4a5bd4..ecb3e13dd54e 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -264,7 +264,8 @@ pub struct AllocExtra<'tcx> { pub weak_memory: Option, /// A backtrace to where this allocation was allocated. /// As this is recorded for leak reports, it only exists - /// if this allocation is leakable. + /// if this allocation is leakable. The backtrace is not + /// pruned yet; that should be done before printing it. pub backtrace: Option>>, } From 3dba5872a3b7e40e9c03aa89643266973c58fe1c Mon Sep 17 00:00:00 2001 From: John Bobbo Date: Sun, 16 Apr 2023 07:29:14 -0700 Subject: [PATCH 103/116] Add a message indicating overflow in `core::intrinsics::is_nonoverlapping`. --- library/core/src/intrinsics.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 44ed9f76c481..ba03da411e34 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -2519,7 +2519,9 @@ pub(crate) fn is_valid_allocation_size(len: usize) -> bool { pub(crate) fn is_nonoverlapping(src: *const T, dst: *const T, count: usize) -> bool { let src_usize = src.addr(); let dst_usize = dst.addr(); - let size = mem::size_of::().saturating_mul(count); + let size = mem::size_of::() + .checked_mul(count) + .expect("is_nonoverlapping: `size_of::() * count` overflows a usize"); let diff = if src_usize > dst_usize { src_usize - dst_usize } else { dst_usize - src_usize }; // If the absolute distance between the ptrs is at least as big as the size of the buffer, // they do not overlap. From 34ed5c3efc839913d2dcfcbc60e8f11c3423d87b Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sat, 25 Mar 2023 10:12:35 +0000 Subject: [PATCH 104/116] Alloc `hir::Lit` in an arena to remove the destructor from `Expr` This allows allocating `Expr`s into a dropless arena, which is useful for using length prefixed thing slices in HIR, since these can only be allocated in the dropless arena and not in a typed arena. This is something I'm working on. --- compiler/rustc_ast_lowering/src/expr.rs | 55 +++++++++---------- compiler/rustc_hir/src/arena.rs | 1 + compiler/rustc_hir/src/hir.rs | 2 +- .../src/fn_ctxt/suggestions.rs | 4 +- .../src/bool_assert_comparison.rs | 2 +- .../clippy/clippy_lints/src/manual_strip.rs | 2 +- .../src/matches/match_like_matches.rs | 2 +- .../clippy_lints/src/methods/open_options.rs | 2 +- .../clippy/clippy_lints/src/utils/author.rs | 2 +- 9 files changed, 34 insertions(+), 38 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 1b1c4765bc07..0d212b3e130a 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -121,12 +121,16 @@ impl<'hir> LoweringContext<'_, 'hir> { LitKind::Err } }; - hir::ExprKind::Lit(respan(self.lower_span(e.span), lit_kind)) + let lit = self.arena.alloc(respan(self.lower_span(e.span), lit_kind)); + hir::ExprKind::Lit(lit) + } + ExprKind::IncludedBytes(bytes) => { + let lit = self.arena.alloc(respan( + self.lower_span(e.span), + LitKind::ByteStr(bytes.clone(), StrStyle::Cooked), + )); + hir::ExprKind::Lit(lit) } - ExprKind::IncludedBytes(bytes) => hir::ExprKind::Lit(respan( - self.lower_span(e.span), - LitKind::ByteStr(bytes.clone(), StrStyle::Cooked), - )), ExprKind::Cast(expr, ty) => { let expr = self.lower_expr(expr); let ty = @@ -1746,40 +1750,31 @@ impl<'hir> LoweringContext<'_, 'hir> { } pub(super) fn expr_usize(&mut self, sp: Span, value: usize) -> hir::Expr<'hir> { - self.expr( - sp, - hir::ExprKind::Lit(hir::Lit { - span: sp, - node: ast::LitKind::Int( - value as u128, - ast::LitIntType::Unsigned(ast::UintTy::Usize), - ), - }), - ) + let lit = self.arena.alloc(hir::Lit { + span: sp, + node: ast::LitKind::Int(value as u128, ast::LitIntType::Unsigned(ast::UintTy::Usize)), + }); + self.expr(sp, hir::ExprKind::Lit(lit)) } pub(super) fn expr_u32(&mut self, sp: Span, value: u32) -> hir::Expr<'hir> { - self.expr( - sp, - hir::ExprKind::Lit(hir::Lit { - span: sp, - node: ast::LitKind::Int(value.into(), ast::LitIntType::Unsigned(ast::UintTy::U32)), - }), - ) + let lit = self.arena.alloc(hir::Lit { + span: sp, + node: ast::LitKind::Int(value.into(), ast::LitIntType::Unsigned(ast::UintTy::U32)), + }); + self.expr(sp, hir::ExprKind::Lit(lit)) } pub(super) fn expr_char(&mut self, sp: Span, value: char) -> hir::Expr<'hir> { - self.expr(sp, hir::ExprKind::Lit(hir::Lit { span: sp, node: ast::LitKind::Char(value) })) + let lit = self.arena.alloc(hir::Lit { span: sp, node: ast::LitKind::Char(value) }); + self.expr(sp, hir::ExprKind::Lit(lit)) } pub(super) fn expr_str(&mut self, sp: Span, value: Symbol) -> hir::Expr<'hir> { - self.expr( - sp, - hir::ExprKind::Lit(hir::Lit { - span: sp, - node: ast::LitKind::Str(value, ast::StrStyle::Cooked), - }), - ) + let lit = self + .arena + .alloc(hir::Lit { span: sp, node: ast::LitKind::Str(value, ast::StrStyle::Cooked) }); + self.expr(sp, hir::ExprKind::Lit(lit)) } pub(super) fn expr_call_mut( diff --git a/compiler/rustc_hir/src/arena.rs b/compiler/rustc_hir/src/arena.rs index c89e7eb75f8f..3e5b3c498eee 100644 --- a/compiler/rustc_hir/src/arena.rs +++ b/compiler/rustc_hir/src/arena.rs @@ -51,6 +51,7 @@ macro_rules! arena_types { [] type_binding: rustc_hir::TypeBinding<'tcx>, [] variant: rustc_hir::Variant<'tcx>, [] where_predicate: rustc_hir::WherePredicate<'tcx>, + [] lit: rustc_hir::Lit, ]); ) } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 35a72f868fbc..b274e6280798 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1957,7 +1957,7 @@ pub enum ExprKind<'hir> { /// A unary operation (e.g., `!x`, `*x`). Unary(UnOp, &'hir Expr<'hir>), /// A literal (e.g., `1`, `"foo"`). - Lit(Lit), + Lit(&'hir Lit), /// A cast (e.g., `foo as f64`). Cast(&'hir Expr<'hir>, &'hir Ty<'hir>), /// A type reference (e.g., `Foo`). diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 5fda4e191c2a..e82821850d62 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -1252,7 +1252,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed), span, }) => { - let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) else { return false; }; + let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(*span) else { return false; }; if !(snippet.starts_with("0x") || snippet.starts_with("0X")) { return false; } @@ -1311,7 +1311,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We have satisfied all requirements to provide a suggestion. Emit it. err.span_suggestion( - span, + *span, format!("if you meant to create a null pointer, use `{null_path_str}()`"), null_path_str + "()", Applicability::MachineApplicable, diff --git a/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs b/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs index 1d9096ea64d1..8c3ad24eeed4 100644 --- a/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs +++ b/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs @@ -41,7 +41,7 @@ fn extract_bool_lit(e: &Expr<'_>) -> Option { }) = e.kind && !e.span.from_expansion() { - Some(b) + Some(*b) } else { None } diff --git a/src/tools/clippy/clippy_lints/src/manual_strip.rs b/src/tools/clippy/clippy_lints/src/manual_strip.rs index c795c1d9a16c..7d28c1116245 100644 --- a/src/tools/clippy/clippy_lints/src/manual_strip.rs +++ b/src/tools/clippy/clippy_lints/src/manual_strip.rs @@ -159,7 +159,7 @@ fn eq_pattern_length<'tcx>(cx: &LateContext<'tcx>, pattern: &Expr<'_>, expr: &'t .. }) = expr.kind { - constant_length(cx, pattern).map_or(false, |length| length == n) + constant_length(cx, pattern).map_or(false, |length| length == *n) } else { len_arg(cx, expr).map_or(false, |arg| eq_expr_value(cx, pattern, arg)) } diff --git a/src/tools/clippy/clippy_lints/src/matches/match_like_matches.rs b/src/tools/clippy/clippy_lints/src/matches/match_like_matches.rs index 107fad32393c..33bc20dad6b7 100644 --- a/src/tools/clippy/clippy_lints/src/matches/match_like_matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches/match_like_matches.rs @@ -162,7 +162,7 @@ fn find_bool_lit(ex: &ExprKind<'_>) -> Option { node: LitKind::Bool(b), .. }) = exp.kind { - Some(b) + Some(*b) } else { None } diff --git a/src/tools/clippy/clippy_lints/src/methods/open_options.rs b/src/tools/clippy/clippy_lints/src/methods/open_options.rs index c6a27cdd6fac..23d23f25f14c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/open_options.rs +++ b/src/tools/clippy/clippy_lints/src/methods/open_options.rs @@ -48,7 +48,7 @@ fn get_open_options(cx: &LateContext<'_>, argument: &Expr<'_>, options: &mut Vec .. } = *span { - if lit { Argument::True } else { Argument::False } + if *lit { Argument::True } else { Argument::False } } else { // The function is called with a literal which is not a boolean literal. // This is theoretically possible, but not very likely. diff --git a/src/tools/clippy/clippy_lints/src/utils/author.rs b/src/tools/clippy/clippy_lints/src/utils/author.rs index bc4adf1596d4..2dac807c420e 100644 --- a/src/tools/clippy/clippy_lints/src/utils/author.rs +++ b/src/tools/clippy/clippy_lints/src/utils/author.rs @@ -430,7 +430,7 @@ impl<'a, 'tcx> PrintVisitor<'a, 'tcx> { kind!("Unary(UnOp::{op:?}, {inner})"); self.expr(inner); }, - ExprKind::Lit(ref lit) => { + ExprKind::Lit(lit) => { bind!(self, lit); kind!("Lit(ref {lit})"); self.lit(lit); From b1da6a750b64dba5b33e05e88a5666323c62db42 Mon Sep 17 00:00:00 2001 From: Josh Soref <2119212+jsoref@users.noreply.github.com> Date: Sun, 9 Apr 2023 20:50:31 -0400 Subject: [PATCH 105/116] Spelling src/doc * incompatibilities * invocation * keywords * nonexistent * shakespeare * the * toolchain * transparent Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> --- src/doc/rustc/src/instrument-coverage.md | 2 +- src/doc/rustc/src/json.md | 2 +- .../src/platform-support/armv7-unknown-linux-uclibceabi.md | 2 +- src/doc/rustc/src/platform-support/unknown-uefi.md | 2 +- src/doc/style-guide/src/principles.md | 2 +- src/doc/style-guide/src/types.md | 2 +- src/doc/unstable-book/src/compiler-flags/check-cfg.md | 2 +- src/doc/unstable-book/src/compiler-flags/move-size-limit.md | 2 +- .../unstable-book/src/language-features/transparent-unions.md | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/doc/rustc/src/instrument-coverage.md b/src/doc/rustc/src/instrument-coverage.md index b0b2f4196422..2535cd4f12ce 100644 --- a/src/doc/rustc/src/instrument-coverage.md +++ b/src/doc/rustc/src/instrument-coverage.md @@ -117,7 +117,7 @@ $ ls formatjson5.profraw formatjson5.profraw ``` -If `LLVM_PROFILE_FILE` contains a path to a non-existent directory, the missing directory structure will be created. Additionally, the following special pattern strings are rewritten: +If `LLVM_PROFILE_FILE` contains a path to a nonexistent directory, the missing directory structure will be created. Additionally, the following special pattern strings are rewritten: - `%p` - The process ID. - `%h` - The hostname of the machine running the program. diff --git a/src/doc/rustc/src/json.md b/src/doc/rustc/src/json.md index d8843280b844..11d7b5b59381 100644 --- a/src/doc/rustc/src/json.md +++ b/src/doc/rustc/src/json.md @@ -61,7 +61,7 @@ Diagnostics have the following format: /* The file where the span is located. Note that this path may not exist. For example, if the path points to the standard library, and the rust src is not - available in the sysroot, then it may point to a non-existent + available in the sysroot, then it may point to a nonexistent file. Beware that this may also point to the source of an external crate. */ diff --git a/src/doc/rustc/src/platform-support/armv7-unknown-linux-uclibceabi.md b/src/doc/rustc/src/platform-support/armv7-unknown-linux-uclibceabi.md index 09e03e4dc6f9..e351ea001300 100644 --- a/src/doc/rustc/src/platform-support/armv7-unknown-linux-uclibceabi.md +++ b/src/doc/rustc/src/platform-support/armv7-unknown-linux-uclibceabi.md @@ -66,7 +66,7 @@ After completing these steps you can use rust normally in a native environment. To cross compile, you'll need to: -* Build the rust cross toochain using [rust-bootstrap-armv7-unknown-linux-uclibceabi](https://github.com/lancethepants/rust-bootstrap-armv7-unknown-linux-uclibceabi) or your own built toolchain. +* Build the rust cross toolchain using [rust-bootstrap-armv7-unknown-linux-uclibceabi](https://github.com/lancethepants/rust-bootstrap-armv7-unknown-linux-uclibceabi) or your own built toolchain. * Link your built toolchain with ```text diff --git a/src/doc/rustc/src/platform-support/unknown-uefi.md b/src/doc/rustc/src/platform-support/unknown-uefi.md index e2bdf73a9299..03fa284620e4 100644 --- a/src/doc/rustc/src/platform-support/unknown-uefi.md +++ b/src/doc/rustc/src/platform-support/unknown-uefi.md @@ -123,7 +123,7 @@ There are 3 common ways to compile native C code for UEFI targets: targets. Be wary of any includes that are not specifically suitable for UEFI targets (especially the C standard library includes are not always compatible). Freestanding compilations are recommended to avoid - incompatibilites. + incompatibilities. ## Ecosystem diff --git a/src/doc/style-guide/src/principles.md b/src/doc/style-guide/src/principles.md index 21668973194e..2d203f264e62 100644 --- a/src/doc/style-guide/src/principles.md +++ b/src/doc/style-guide/src/principles.md @@ -6,7 +6,7 @@ following principles (in rough priority order): * readability - scan-ability - avoiding misleading formatting - - accessibility - readable and editable by users using the the widest + - accessibility - readable and editable by users using the widest variety of hardware, including non-visual accessibility interfaces - readability of code in contexts without syntax highlighting or IDE assistance, such as rustc error messages, diffs, grep, and other diff --git a/src/doc/style-guide/src/types.md b/src/doc/style-guide/src/types.md index 25861ddabb8d..ae456ef21c8d 100644 --- a/src/doc/style-guide/src/types.md +++ b/src/doc/style-guide/src/types.md @@ -6,7 +6,7 @@ * `[T; expr]`, e.g., `[u32; 42]`, `[Vec; 10 * 2 + foo()]` (space after colon, no spaces around square brackets) * `*const T`, `*mut T` (no space after `*`, space before type) * `&'a T`, `&T`, `&'a mut T`, `&mut T` (no space after `&`, single spaces separating other words) -* `unsafe extern "C" fn<'a, 'b, 'c>(T, U, V) -> W` or `fn()` (single spaces around keyowrds and sigils, and after commas, no trailing commas, no spaces around brackets) +* `unsafe extern "C" fn<'a, 'b, 'c>(T, U, V) -> W` or `fn()` (single spaces around keywords and sigils, and after commas, no trailing commas, no spaces around brackets) * `!` should be treated like any other type name, `Name` * `(A, B, C, D)` (spaces after commas, no spaces around parens, no trailing comma unless it is a one-tuple) * ` as SomeTrait>::Foo::Bar` or `Foo::Bar` or `::Foo::Bar` (no spaces around `::` or angle brackets, single spaces around `as`) diff --git a/src/doc/unstable-book/src/compiler-flags/check-cfg.md b/src/doc/unstable-book/src/compiler-flags/check-cfg.md index 321992f7b0d7..10f0fbc50626 100644 --- a/src/doc/unstable-book/src/compiler-flags/check-cfg.md +++ b/src/doc/unstable-book/src/compiler-flags/check-cfg.md @@ -202,5 +202,5 @@ fn shoot_lasers() {} #[cfg(feature = "monkeys")] // This is UNEXPECTED, because "monkeys" is not in // the values(feature) list -fn write_shakespear() {} +fn write_shakespeare() {} ``` diff --git a/src/doc/unstable-book/src/compiler-flags/move-size-limit.md b/src/doc/unstable-book/src/compiler-flags/move-size-limit.md index 88f022af2ecf..aea054ba911f 100644 --- a/src/doc/unstable-book/src/compiler-flags/move-size-limit.md +++ b/src/doc/unstable-book/src/compiler-flags/move-size-limit.md @@ -6,5 +6,5 @@ The `-Zmove-size-limit=N` compiler flag enables `large_assignments` lints which will warn when moving objects whose size exceeds `N` bytes. Lint warns only about moves in functions that participate in code generation. -Consequently it will be ineffective for compiler invocatation that emit +Consequently it will be ineffective for compiler invocation that emit metadata only, i.e., `cargo check` like workflows. diff --git a/src/doc/unstable-book/src/language-features/transparent-unions.md b/src/doc/unstable-book/src/language-features/transparent-unions.md index 9b39b8971644..bab88b148b26 100644 --- a/src/doc/unstable-book/src/language-features/transparent-unions.md +++ b/src/doc/unstable-book/src/language-features/transparent-unions.md @@ -65,7 +65,7 @@ pub union GenericUnion { // Unions with non-`Copy` fields are unstable. pub const THIS_IS_OKAY: GenericUnion<()> = GenericUnion { field: () }; ``` -Like transarent `struct`s, a transparent `union` of type `U` has the same +Like transparent `struct`s, a transparent `union` of type `U` has the same layout, size, and ABI as its single non-ZST field. If it is generic over a type `T`, and all its fields are ZSTs except for exactly one field of type `T`, then it has the same layout and ABI as `T` (even if `T` is a ZST when monomorphized). From f795a150fe01b68bdd62503c39fbdc9ed04a5219 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Wed, 15 Mar 2023 12:50:04 +0000 Subject: [PATCH 106/116] chore: allow `cargo` to have its own workspace This also * bumps cargo to the latest in rust-lang/cargo. * adds 0BSD to allowed list of licenses Co-authored-by: Scott Schafer Co-authored-by: Eric Huss --- Cargo.lock | 1705 +----------------------------------- Cargo.toml | 6 - src/bootstrap/bootstrap.py | 3 +- src/bootstrap/dist.rs | 3 + src/bootstrap/tool.rs | 5 +- src/tools/cargo | 2 +- src/tools/tidy/src/deps.rs | 68 +- 7 files changed, 75 insertions(+), 1717 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dee613226a89..2c1a498da779 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -42,7 +42,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf6ccdb167abbf410dcb915cabd428929d7f6a04980b54a11f26a39f1c7f7107" dependencies = [ "cfg-if", - "getrandom", "once_cell", "version_check", ] @@ -108,7 +107,7 @@ dependencies = [ "anstyle-parse", "anstyle-wincon", "concolor-override", - "concolor-query 0.3.3", + "concolor-query", "is-terminal", "utf8parse", ] @@ -153,24 +152,12 @@ dependencies = [ "object 0.30.1", ] -[[package]] -name = "arc-swap" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6" - [[package]] name = "array_tool" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f8cb5d814eb646a863c4f24978cff2880c4be96ad8cde2c0f0678732902e271" -[[package]] -name = "arrayvec" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" - [[package]] name = "arrayvec" version = "0.7.0" @@ -241,24 +228,6 @@ dependencies = [ "rustc-demangle", ] -[[package]] -name = "base16ct" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" - -[[package]] -name = "base64" -version = "0.21.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a" - -[[package]] -name = "base64ct" -version = "1.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b645a089122eccb6111b4f81cbc1a49f5900ac4666bb93ac027feaecf15607bf" - [[package]] name = "basic-toml" version = "0.1.2" @@ -274,15 +243,6 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" -[[package]] -name = "bitmaps" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "031043d04099746d8db04daf1fa424b2bc8bd69d92b25962dcde24da39ab64a2" -dependencies = [ - "typenum", -] - [[package]] name = "block-buffer" version = "0.10.2" @@ -315,15 +275,6 @@ dependencies = [ "serde", ] -[[package]] -name = "btoi" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd6407f73a9b8b6162d8a2ef999fe6afd7cc15902ebf42c5cd296addf17e0ad" -dependencies = [ - "num-traits", -] - [[package]] name = "build-manifest" version = "0.1.0" @@ -336,7 +287,7 @@ dependencies = [ "serde_json", "sha2", "tar", - "toml 0.5.7", + "toml", ] [[package]] @@ -352,7 +303,7 @@ dependencies = [ "indexmap", "serde", "serde_json", - "toml 0.5.7", + "toml", ] [[package]] @@ -376,12 +327,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b700ce4376041dcd0a327fd0097c41095743c4c8af8887265942faf1100bd040" -[[package]] -name = "bytesize" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81a18687293a1546b67c246452202bbbf143d239cb43494cc163da14979082da" - [[package]] name = "camino" version = "1.0.9" @@ -391,108 +336,6 @@ dependencies = [ "serde", ] -[[package]] -name = "cargo" -version = "0.71.0" -dependencies = [ - "anyhow", - "base64", - "bytesize", - "cargo-platform 0.1.2", - "cargo-test-macro", - "cargo-test-support", - "cargo-util", - "clap 4.2.1", - "crates-io", - "curl", - "curl-sys", - "env_logger 0.10.0", - "filetime", - "flate2", - "fwdansi", - "git2", - "git2-curl", - "gix", - "gix-features", - "glob", - "hex", - "hmac", - "home", - "http-auth", - "humantime 2.0.1", - "ignore", - "im-rc", - "indexmap", - "is-terminal", - "itertools", - "jobserver", - "lazy_static", - "lazycell", - "libc", - "libgit2-sys", - "log", - "memchr", - "opener", - "openssl", - "os_info", - "pasetors", - "pathdiff", - "pretty_env_logger", - "rand", - "rustc-workspace-hack", - "rustfix", - "same-file", - "semver", - "serde", - "serde-value", - "serde_ignored", - "serde_json", - "sha1", - "shell-escape", - "snapbox", - "strip-ansi-escapes", - "tar", - "tempfile", - "termcolor", - "time 0.3.17", - "toml 0.7.2", - "toml_edit", - "unicode-width", - "unicode-xid", - "url", - "walkdir", - "windows-sys 0.45.0", -] - -[[package]] -name = "cargo-credential" -version = "0.2.0" - -[[package]] -name = "cargo-credential-1password" -version = "0.2.0" -dependencies = [ - "cargo-credential", - "serde", - "serde_json", -] - -[[package]] -name = "cargo-credential-macos-keychain" -version = "0.2.0" -dependencies = [ - "cargo-credential", - "security-framework", -] - -[[package]] -name = "cargo-credential-wincred" -version = "0.2.0" -dependencies = [ - "cargo-credential", - "windows-sys 0.45.0", -] - [[package]] name = "cargo-miri" version = "0.1.0" @@ -507,13 +350,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "cargo-platform" -version = "0.1.2" -dependencies = [ - "serde", -] - [[package]] name = "cargo-platform" version = "0.1.2" @@ -523,56 +359,6 @@ dependencies = [ "serde", ] -[[package]] -name = "cargo-test-macro" -version = "0.1.0" - -[[package]] -name = "cargo-test-support" -version = "0.1.0" -dependencies = [ - "anyhow", - "cargo-test-macro", - "cargo-util", - "crates-io", - "filetime", - "flate2", - "git2", - "glob", - "itertools", - "lazy_static", - "pasetors", - "serde", - "serde_json", - "snapbox", - "tar", - "termcolor", - "time 0.3.17", - "toml 0.7.2", - "url", - "windows-sys 0.45.0", -] - -[[package]] -name = "cargo-util" -version = "0.2.4" -dependencies = [ - "anyhow", - "core-foundation", - "filetime", - "hex", - "jobserver", - "libc", - "log", - "miow 0.5.0", - "same-file", - "sha2", - "shell-escape", - "tempfile", - "walkdir", - "windows-sys 0.45.0", -] - [[package]] name = "cargo_metadata" version = "0.14.0" @@ -580,7 +366,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c297bd3135f558552f99a0daa180876984ea2c4ffa7470314540dff8c654109a" dependencies = [ "camino", - "cargo-platform 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "cargo-platform", "semver", "serde", "serde_json", @@ -593,7 +379,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08a1ec454bc3eead8719cb56e15dbbfecdbc14e4b3a3ae4936cc6e31f5fc0d07" dependencies = [ "camino", - "cargo-platform 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "cargo-platform", "semver", "serde", "serde_json", @@ -609,9 +395,6 @@ name = "cc" version = "1.0.77" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4" -dependencies = [ - "jobserver", -] [[package]] name = "cfg-if" @@ -687,7 +470,7 @@ dependencies = [ "num-integer", "num-traits", "serde", - "time 0.1.43", + "time", "winapi", ] @@ -809,7 +592,7 @@ dependencies = [ "termize", "tester", "tokio", - "toml 0.5.7", + "toml", "walkdir", ] @@ -830,7 +613,7 @@ dependencies = [ name = "clippy_lints" version = "0.1.70" dependencies = [ - "arrayvec 0.7.0", + "arrayvec", "cargo_metadata 0.15.3", "clippy_utils", "declare_clippy_lint", @@ -844,7 +627,7 @@ dependencies = [ "serde", "serde_json", "tempfile", - "toml 0.5.7", + "toml", "unicode-normalization", "unicode-script", "url", @@ -854,18 +637,12 @@ dependencies = [ name = "clippy_utils" version = "0.1.70" dependencies = [ - "arrayvec 0.7.0", + "arrayvec", "if_chain", "itertools", "rustc-semver", ] -[[package]] -name = "clru" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8191fa7302e03607ff0e237d4246cc043ff5b3cb9409d995172ba3bea16b807" - [[package]] name = "collect-license-metadata" version = "0.1.0" @@ -946,7 +723,7 @@ dependencies = [ "tracing-subscriber", "unified-diff", "walkdir", - "windows 0.46.0", + "windows", ] [[package]] @@ -972,29 +749,12 @@ dependencies = [ "winapi", ] -[[package]] -name = "concolor" -version = "0.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b90f9dcd9490a97db91a85ccd79e38a87e14323f0bb824659ee3274e9143ba37" -dependencies = [ - "atty", - "bitflags", - "concolor-query 0.1.0", -] - [[package]] name = "concolor-override" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a855d4a1978dc52fb0536a04d384c2c0c1aa273597f08b77c8c4d3b2eec6037f" -[[package]] -name = "concolor-query" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82a90734b3d5dcf656e7624cca6bce9c3a90ee11f900e80141a7427ccfb3d317" - [[package]] name = "concolor-query" version = "0.3.3" @@ -1004,21 +764,6 @@ dependencies = [ "windows-sys 0.45.0", ] -[[package]] -name = "const-oid" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cec318a675afcb6a1ea1d4340e2d377e56e47c266f28043ceccbf4412ddfdd3b" - -[[package]] -name = "content_inspector" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7bda66e858c683005a53a9a60c69a4aca7eeaa45d124526e389f7aec8e62f38" -dependencies = [ - "memchr", -] - [[package]] name = "convert_case" version = "0.4.0" @@ -1033,22 +778,6 @@ dependencies = [ "rand_xorshift", ] -[[package]] -name = "core-foundation" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b5ed8e7e76c45974e15e41bfa8d5b0483cd90191639e01d8f5f1e606299d3fb" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a21fa21941700a3cd8fcb4091f361a6a712fac632f85d9f487cc892045d55c6" - [[package]] name = "coverage_test_macros" version = "0.0.0" @@ -1062,18 +791,6 @@ dependencies = [ "libc", ] -[[package]] -name = "crates-io" -version = "0.36.0" -dependencies = [ - "anyhow", - "curl", - "percent-encoding", - "serde", - "serde_json", - "url", -] - [[package]] name = "crc32fast" version = "1.3.2" @@ -1126,18 +843,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "crypto-bigint" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef2b4b23cddf68b89b8f8069890e8c270d54e2d5fe1b143820234805e4cb17ef" -dependencies = [ - "generic-array", - "rand_core", - "subtle", - "zeroize", -] - [[package]] name = "crypto-common" version = "0.1.6" @@ -1158,22 +863,6 @@ dependencies = [ "quote", ] -[[package]] -name = "ct-codecs" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3b7eb4404b8195a9abb6356f4ac07d8ba267045c8d6d220ac4dc992e6cc75df" - -[[package]] -name = "ctor" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d2301688392eb071b0bf1a37be05c469d3cc4dbbd95df672fe28ab021e6a096" -dependencies = [ - "quote", - "syn 1.0.102", -] - [[package]] name = "curl" version = "0.4.44" @@ -1197,7 +886,6 @@ checksum = "14d05c10f541ae6f3bc5b3d923c20001f47db7d5f0b2bc6ad16490133842db79" dependencies = [ "cc", "libc", - "libnghttp2-sys", "libz-sys", "openssl-sys", "pkg-config", @@ -1220,17 +908,6 @@ dependencies = [ "syn 1.0.102", ] -[[package]] -name = "der" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de" -dependencies = [ - "const-oid", - "pem-rfc7468", - "zeroize", -] - [[package]] name = "derive-new" version = "0.5.8" @@ -1269,7 +946,6 @@ checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f" dependencies = [ "block-buffer", "crypto-common", - "subtle", ] [[package]] @@ -1350,33 +1026,6 @@ dependencies = [ "rustc-std-workspace-core", ] -[[package]] -name = "dunce" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bd4b30a6560bbd9b4620f4de34c3f14f60848e58a9b7216801afcb4c7b31c3c" - -[[package]] -name = "ecdsa" -version = "0.14.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c" -dependencies = [ - "der", - "elliptic-curve", - "rfc6979", - "signature", -] - -[[package]] -name = "ed25519-compact" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a3d382e8464107391c8706b4c14b087808ecb909f6c15c34114bc42e53a9e4c" -dependencies = [ - "getrandom", -] - [[package]] name = "either" version = "1.6.0" @@ -1395,28 +1044,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "elliptic-curve" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3" -dependencies = [ - "base16ct", - "crypto-bigint", - "der", - "digest", - "ff", - "generic-array", - "group", - "hkdf", - "pem-rfc7468", - "pkcs8", - "rand_core", - "sec1", - "subtle", - "zeroize", -] - [[package]] name = "elsa" version = "1.7.1" @@ -1546,22 +1173,6 @@ dependencies = [ "instant", ] -[[package]] -name = "ff" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d013fc25338cc558c5c2cfbad646908fb23591e2404481826742b651c9af7160" -dependencies = [ - "rand_core", - "subtle", -] - -[[package]] -name = "fiat-crypto" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a214f5bb88731d436478f3ae1f8a277b62124089ba9fb67f4f93fb100ef73c90" - [[package]] name = "filetime" version = "0.2.20" @@ -1589,7 +1200,6 @@ dependencies = [ "cfg-if", "crc32fast", "libc", - "libz-sys", "miniz_oxide", ] @@ -1633,21 +1243,6 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - [[package]] name = "form_urlencoded" version = "1.0.1" @@ -1773,16 +1368,6 @@ dependencies = [ "slab", ] -[[package]] -name = "fwdansi" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08c1f5787fe85505d1f7777268db5103d80a7a374d2316a7ce262e57baf8f208" -dependencies = [ - "memchr", - "termcolor", -] - [[package]] name = "generate-copyright" version = "0.1.0" @@ -1840,586 +1425,6 @@ dependencies = [ "stable_deref_trait", ] -[[package]] -name = "git2" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89511277159354bea13ae1e53e0c9ab85ba1b20d7e91618fa30e6bc5566857fb" -dependencies = [ - "bitflags", - "libc", - "libgit2-sys", - "log", - "openssl-probe", - "openssl-sys", - "url", -] - -[[package]] -name = "git2-curl" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8f8b7432b72928cff76f69e59ed5327f94a52763731e71274960dee72fe5f8c" -dependencies = [ - "curl", - "git2", - "log", - "url", -] - -[[package]] -name = "gix" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dabfac58aecb4a38cdd2568de66eb1f0d968fd6726f5a80cb8bea7944ef10cc0" -dependencies = [ - "gix-actor", - "gix-attributes", - "gix-config", - "gix-credentials", - "gix-date", - "gix-diff", - "gix-discover", - "gix-features", - "gix-glob", - "gix-hash", - "gix-hashtable", - "gix-index", - "gix-lock", - "gix-mailmap", - "gix-object", - "gix-odb", - "gix-pack", - "gix-path", - "gix-prompt", - "gix-protocol", - "gix-ref", - "gix-refspec", - "gix-revision", - "gix-sec", - "gix-tempfile", - "gix-transport", - "gix-traverse", - "gix-url", - "gix-validate", - "gix-worktree", - "log", - "once_cell", - "prodash", - "signal-hook", - "smallvec", - "thiserror", - "unicode-normalization", -] - -[[package]] -name = "gix-actor" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc22b0cdc52237667c301dd7cdc6ead8f8f73c9f824e9942c8ebd6b764f6c0bf" -dependencies = [ - "bstr 1.3.0", - "btoi", - "gix-date", - "itoa", - "nom", - "thiserror", -] - -[[package]] -name = "gix-attributes" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2231a25934a240d0a4b6f4478401c73ee81d8be52de0293eedbc172334abf3e1" -dependencies = [ - "bstr 1.3.0", - "gix-features", - "gix-glob", - "gix-path", - "gix-quote", - "thiserror", - "unicode-bom", -] - -[[package]] -name = "gix-bitmap" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "024bca0c7187517bda5ea24ab148c9ca8208dd0c3e2bea88cdb2008f91791a6d" -dependencies = [ - "thiserror", -] - -[[package]] -name = "gix-chunk" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0d39583cab06464b8bf73b3f1707458270f0e7383cb24c3c9c1a16e6f792978" -dependencies = [ - "thiserror", -] - -[[package]] -name = "gix-command" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2c6f75c1e0f924de39e750880a6e21307194bb1ab773efe3c7d2d787277f8ab" -dependencies = [ - "bstr 1.3.0", -] - -[[package]] -name = "gix-config" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52c62e26ce11f607712e4f49a0a192ed87675d30187fd61be070abbd607d12f1" -dependencies = [ - "bstr 1.3.0", - "gix-config-value", - "gix-features", - "gix-glob", - "gix-path", - "gix-ref", - "gix-sec", - "memchr", - "nom", - "once_cell", - "smallvec", - "thiserror", - "unicode-bom", -] - -[[package]] -name = "gix-config-value" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "693d4a4ba0531e46fe558459557a5b29fb86c3e4b2666c1c0861d93c7c678331" -dependencies = [ - "bitflags", - "bstr 1.3.0", - "gix-path", - "libc", - "thiserror", -] - -[[package]] -name = "gix-credentials" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5be32b5fe339a31b8e53fa854081dc914c45020dcb64637f3c21baf69c96fc1b" -dependencies = [ - "bstr 1.3.0", - "gix-command", - "gix-config-value", - "gix-path", - "gix-prompt", - "gix-sec", - "gix-url", - "thiserror", -] - -[[package]] -name = "gix-date" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96271912ce39822501616f177dea7218784e6c63be90d5f36322ff3a722aae2" -dependencies = [ - "bstr 1.3.0", - "itoa", - "thiserror", - "time 0.3.17", -] - -[[package]] -name = "gix-diff" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585b0834d4b6791a848637c4e109545fda9b0f29b591ba55edb33ceda6e7856b" -dependencies = [ - "gix-hash", - "gix-object", - "imara-diff", - "thiserror", -] - -[[package]] -name = "gix-discover" -version = "0.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c204adba5ebd211c74735cbb65817d277e154486bac0dffa3701f163b80350" -dependencies = [ - "bstr 1.3.0", - "dunce", - "gix-hash", - "gix-path", - "gix-ref", - "gix-sec", - "thiserror", -] - -[[package]] -name = "gix-features" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6a9dfa7b3c1a99315203e8b97f8f99f3bd95731590607abeaa5ca31bc41fe3" -dependencies = [ - "bytes", - "crc32fast", - "crossbeam-channel", - "flate2", - "gix-hash", - "libc", - "once_cell", - "parking_lot 0.12.1", - "prodash", - "sha1_smol", - "thiserror", - "walkdir", -] - -[[package]] -name = "gix-glob" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93e43efd776bc543f46f0fd0ca3d920c37af71a764a16f2aebd89765e9ff2993" -dependencies = [ - "bitflags", - "bstr 1.3.0", -] - -[[package]] -name = "gix-hash" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0c5a9f4d621d4f4ea046bb331df5c746ca735b8cae5b234cc2be70ee4dbef0" -dependencies = [ - "hex", - "thiserror", -] - -[[package]] -name = "gix-hashtable" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9609c1b8f36f12968e6a6098f7cdb52004f7d42d570f47a2d6d7c16612f19acb" -dependencies = [ - "gix-hash", - "hashbrown 0.13.1", - "parking_lot 0.12.1", -] - -[[package]] -name = "gix-index" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c12caf7886c7ba06f2b28835cdc2be1dca86bd047d00299d2d49e707ce1c2616" -dependencies = [ - "bitflags", - "bstr 1.3.0", - "btoi", - "filetime", - "gix-bitmap", - "gix-features", - "gix-hash", - "gix-lock", - "gix-object", - "gix-traverse", - "itoa", - "memmap2 0.5.10", - "smallvec", - "thiserror", -] - -[[package]] -name = "gix-lock" -version = "4.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66119ff8a4a395d0ea033fef718bc85f8b4f0855874f4ce1e005fc16cfe1f66e" -dependencies = [ - "fastrand", - "gix-tempfile", - "thiserror", -] - -[[package]] -name = "gix-mailmap" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b66aea5e52875cd4915f4957a6f4b75831a36981e2ec3f5fad9e370e444fe1a" -dependencies = [ - "bstr 1.3.0", - "gix-actor", - "thiserror", -] - -[[package]] -name = "gix-object" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df068db9180ee935fbb70504848369e270bdcb576b05c0faa8b9fd3b86fc017" -dependencies = [ - "bstr 1.3.0", - "btoi", - "gix-actor", - "gix-features", - "gix-hash", - "gix-validate", - "hex", - "itoa", - "nom", - "smallvec", - "thiserror", -] - -[[package]] -name = "gix-odb" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9a5f9e1afbd509761977a2ea02869cedaaba500b4e783deb2e4de5179a55a80" -dependencies = [ - "arc-swap", - "gix-features", - "gix-hash", - "gix-object", - "gix-pack", - "gix-path", - "gix-quote", - "parking_lot 0.12.1", - "tempfile", - "thiserror", -] - -[[package]] -name = "gix-pack" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51db84e1459a8022e518d40a8778028d793dbb28e4d35c9a5eaf92658fb0775" -dependencies = [ - "clru", - "gix-chunk", - "gix-diff", - "gix-features", - "gix-hash", - "gix-hashtable", - "gix-object", - "gix-path", - "gix-tempfile", - "gix-traverse", - "memmap2 0.5.10", - "parking_lot 0.12.1", - "smallvec", - "thiserror", -] - -[[package]] -name = "gix-packetline" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d63e5e5a9a92d4fc6b63ff9d94954d25c779ce25c98d5bbe2e4399aa42f7073c" -dependencies = [ - "bstr 1.3.0", - "hex", - "thiserror", -] - -[[package]] -name = "gix-path" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6c104a66dec149cb8f7aaafc6ab797654cf82d67f050fd0cb7e7294e328354b" -dependencies = [ - "bstr 1.3.0", - "thiserror", -] - -[[package]] -name = "gix-prompt" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a20cebf73229debaa82574c4fd20dcaf00fa8d4bfce823a862c4e990d7a0b5b4" -dependencies = [ - "gix-command", - "gix-config-value", - "nix", - "parking_lot 0.12.1", - "thiserror", -] - -[[package]] -name = "gix-protocol" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d372ab11d5d28ac21800e3f1a6603a67c1ead57f6f5fab07e1e73e960f331c1" -dependencies = [ - "bstr 1.3.0", - "btoi", - "gix-credentials", - "gix-features", - "gix-hash", - "gix-transport", - "maybe-async", - "nom", - "thiserror", -] - -[[package]] -name = "gix-quote" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a282f5a8d9ee0b09ec47390ac727350c48f2f5c76d803cd8da6b3e7ad56e0bcb" -dependencies = [ - "bstr 1.3.0", - "btoi", - "thiserror", -] - -[[package]] -name = "gix-ref" -version = "0.26.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90a0ed29e581f04b904ecd0c32b11f33b8209b5a0af9c43f415249a4f2fba632" -dependencies = [ - "gix-actor", - "gix-features", - "gix-hash", - "gix-lock", - "gix-object", - "gix-path", - "gix-tempfile", - "gix-validate", - "memmap2 0.5.10", - "nom", - "thiserror", -] - -[[package]] -name = "gix-refspec" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aba332462bda2e8efeae4302b39a6ed01ad56ef772fd5b7ef197cf2798294d65" -dependencies = [ - "bstr 1.3.0", - "gix-hash", - "gix-revision", - "gix-validate", - "smallvec", - "thiserror", -] - -[[package]] -name = "gix-revision" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed98e4a0254953c64bc913bd23146a1de662067d5cf974cbdde396958b39e5b0" -dependencies = [ - "bstr 1.3.0", - "gix-date", - "gix-hash", - "gix-hashtable", - "gix-object", - "thiserror", -] - -[[package]] -name = "gix-sec" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8ffa5bf0772f9b01de501c035b6b084cf9b8bb07dec41e3afc6a17336a65f47" -dependencies = [ - "bitflags", - "dirs", - "gix-path", - "libc", - "windows 0.43.0", -] - -[[package]] -name = "gix-tempfile" -version = "4.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88751f247234b1f73c8e8056fd835a0999b04e596e052302cb71186005dc4b27" -dependencies = [ - "libc", - "once_cell", - "parking_lot 0.12.1", - "signal-hook", - "signal-hook-registry", - "tempfile", -] - -[[package]] -name = "gix-transport" -version = "0.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d633947b36a2fbbc089195bdc71621158f1660c2ff2a6b12b0279c16e2f764bc" -dependencies = [ - "base64", - "bstr 1.3.0", - "curl", - "gix-command", - "gix-credentials", - "gix-features", - "gix-packetline", - "gix-quote", - "gix-sec", - "gix-url", - "thiserror", -] - -[[package]] -name = "gix-traverse" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd9a4a07bb22168dc79c60e1a6a41919d198187ca83d8a5940ad8d7122a45df3" -dependencies = [ - "gix-hash", - "gix-hashtable", - "gix-object", - "thiserror", -] - -[[package]] -name = "gix-url" -version = "0.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "044072b7ce8601b62dcec841b92129f5cc677072823324121b395d766ac5f528" -dependencies = [ - "bstr 1.3.0", - "gix-features", - "gix-path", - "home", - "thiserror", - "url", -] - -[[package]] -name = "gix-validate" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b69ddb780ea1465255e66818d75b7098371c58dbc9560da4488a44b9f5c7e443" -dependencies = [ - "bstr 1.3.0", - "thiserror", -] - -[[package]] -name = "gix-worktree" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7cb9af6e56152953d8fe113c4f9d7cf60cf7a982362711e9200a255579b49cb" -dependencies = [ - "bstr 1.3.0", - "gix-attributes", - "gix-features", - "gix-glob", - "gix-hash", - "gix-index", - "gix-object", - "gix-path", - "io-close", - "thiserror", -] - [[package]] name = "glob" version = "0.3.0" @@ -2439,17 +1444,6 @@ dependencies = [ "regex", ] -[[package]] -name = "group" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfbfb3a6cfbd390d5c9564ab283a0349b9b9fcd46a706c1eb10e0db70bfbac7" -dependencies = [ - "ff", - "rand_core", - "subtle", -] - [[package]] name = "gsgdt" version = "0.1.2" @@ -2459,21 +1453,6 @@ dependencies = [ "serde", ] -[[package]] -name = "handlebars" -version = "3.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4498fc115fa7d34de968184e473529abb40eeb6be8bc5f7faba3d08c316cb3e3" -dependencies = [ - "log", - "pest", - "pest_derive", - "quick-error 2.0.1", - "serde", - "serde_json", - "walkdir", -] - [[package]] name = "handlebars" version = "4.3.3" @@ -2541,33 +1520,6 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "644f9158b2f133fd50f5fb3242878846d9eb792e445c893805ff0e3824006e35" -[[package]] -name = "hkdf" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791a029f6b9fc27657f6f188ec6e5e43f6911f6f878e0dc5501396e09809d437" -dependencies = [ - "hmac", -] - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest", -] - -[[package]] -name = "home" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2456aef2e6b6a9784192ae780c0f15bc57df0e918585282325e8c8ac27737654" -dependencies = [ - "winapi", -] - [[package]] name = "html-checker" version = "0.1.0" @@ -2590,22 +1542,13 @@ dependencies = [ "syn 1.0.102", ] -[[package]] -name = "http-auth" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0b40b39d66c28829a0cf4d09f7e139ff8201f7500a5083732848ed3b4b4d850" -dependencies = [ - "memchr", -] - [[package]] name = "humantime" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" dependencies = [ - "quick-error 1.2.3", + "quick-error", ] [[package]] @@ -2714,30 +1657,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "im-rc" -version = "15.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af1955a75fa080c677d3972822ec4bad316169ab1cfc6c257a942c2265dbe5fe" -dependencies = [ - "bitmaps", - "rand_core", - "rand_xoshiro", - "sized-chunks", - "typenum", - "version_check", -] - -[[package]] -name = "imara-diff" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e98c1d0ad70fc91b8b9654b1f33db55e59579d3b3de2bffdced0fdb810570cb8" -dependencies = [ - "ahash 0.8.2", - "hashbrown 0.12.3", -] - [[package]] name = "indenter" version = "0.3.3" @@ -2805,16 +1724,6 @@ dependencies = [ "unic-langid", ] -[[package]] -name = "io-close" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cadcf447f06744f8ce713d2d6239bb5bde2c357a452397a9ed90c625da390bc" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "io-lifetimes" version = "1.0.3" @@ -2959,20 +1868,6 @@ dependencies = [ "cc", ] -[[package]] -name = "libgit2-sys" -version = "0.15.0+1.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "032e537ae4dd4e50c877f258dc55fcd0657b5021f454094a425bb6bcc9edea4c" -dependencies = [ - "cc", - "libc", - "libssh2-sys", - "libz-sys", - "openssl-sys", - "pkg-config", -] - [[package]] name = "libloading" version = "0.7.1" @@ -2989,30 +1884,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fc7aa29613bd6a620df431842069224d8bc9011086b1db4c0e0cd47fa03ec9a" -[[package]] -name = "libnghttp2-sys" -version = "0.1.4+1.41.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03624ec6df166e79e139a2310ca213283d6b3c30810c54844f307086d4488df1" -dependencies = [ - "cc", - "libc", -] - -[[package]] -name = "libssh2-sys" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dc8a030b787e2119a731f1951d6a773e2280c660f8ec4b0f5e1505a386e71ee" -dependencies = [ - "cc", - "libc", - "libz-sys", - "openssl-sys", - "pkg-config", - "vcpkg", -] - [[package]] name = "libz-sys" version = "1.1.3" @@ -3135,17 +2006,6 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" -[[package]] -name = "maybe-async" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f1b8c13cb1f814b634a96b2c725449fe7ed464a7b8781de8688be5ffbd3f305" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.102", -] - [[package]] name = "md-5" version = "0.10.0" @@ -3168,7 +2028,7 @@ dependencies = [ "clap_complete", "elasticlunr-rs", "env_logger 0.10.0", - "handlebars 4.3.3", + "handlebars", "log", "memchr", "once_cell", @@ -3179,23 +2039,10 @@ dependencies = [ "serde_json", "shlex", "tempfile", - "toml 0.5.7", + "toml", "topological-sort", ] -[[package]] -name = "mdman" -version = "0.1.0" -dependencies = [ - "anyhow", - "handlebars 3.5.5", - "pretty_assertions", - "pulldown-cmark", - "same-file", - "serde_json", - "url", -] - [[package]] name = "measureme" version = "10.1.0" @@ -3203,7 +2050,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cbdc226fa10994e8f66a4d2f6f000148bc563a1c671b6dcd2135737018033d8a" dependencies = [ "log", - "memmap2 0.2.1", + "memmap2", "parking_lot 0.11.2", "perf-event-open-sys", "rustc-hash", @@ -3229,15 +2076,6 @@ dependencies = [ "libc", ] -[[package]] -name = "memmap2" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83faa42c0a078c393f6b29d5db232d8be22776a891f8f56e5284faee4a20b327" -dependencies = [ - "libc", -] - [[package]] name = "memoffset" version = "0.7.1" @@ -3339,18 +2177,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54" -[[package]] -name = "nix" -version = "0.26.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfdda3d196821d6af13126e40375cdf7da646a96114af134d5f417a9a1dc8e1a" -dependencies = [ - "bitflags", - "cfg-if", - "libc", - "static_assertions", -] - [[package]] name = "nom" version = "7.1.0" @@ -3362,21 +2188,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "nom8" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae01545c9c7fc4486ab7debaf2aad7003ac19431791868fb2e8066df97fad2f8" -dependencies = [ - "memchr", -] - -[[package]] -name = "normalize-line-endings" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" - [[package]] name = "num-integer" version = "0.1.43" @@ -3406,15 +2217,6 @@ dependencies = [ "libc", ] -[[package]] -name = "num_threads" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" -dependencies = [ - "libc", -] - [[package]] name = "object" version = "0.29.0" @@ -3465,47 +2267,12 @@ dependencies = [ "winapi", ] -[[package]] -name = "openssl" -version = "0.10.49" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d2f106ab837a24e03672c59b1239669a0596406ff657c3c0835b6b7f0f35a33" -dependencies = [ - "bitflags", - "cfg-if", - "foreign-types", - "libc", - "once_cell", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.8", -] - [[package]] name = "openssl-probe" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" -[[package]] -name = "openssl-src" -version = "111.25.0+1.1.1t" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3173cd3626c43e3854b1b727422a276e568d9ec5fe8cec197822cf52cfb743d6" -dependencies = [ - "cc", -] - [[package]] name = "openssl-sys" version = "0.9.84" @@ -3514,74 +2281,22 @@ checksum = "3a20eace9dc2d82904039cb76dcf50fb1a0bba071cfd1629720b5d6f1ddba0fa" dependencies = [ "cc", "libc", - "openssl-src", "pkg-config", "vcpkg", ] -[[package]] -name = "ordered-float" -version = "2.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7940cf2ca942593318d07fcf2596cdca60a85c9e7fab408a5e21a4f9dcd40d87" -dependencies = [ - "num-traits", -] - -[[package]] -name = "orion" -version = "0.17.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2baf7fd2e326e3895c681176788dd227fcd8369350e53c570592d8563fecbb6" -dependencies = [ - "fiat-crypto", - "subtle", - "zeroize", -] - -[[package]] -name = "os_info" -version = "3.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5209b2162b2c140df493a93689e04f8deab3a67634f5bc7a553c0a98e5b8d399" -dependencies = [ - "log", - "serde", - "winapi", -] - [[package]] name = "os_str_bytes" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" -[[package]] -name = "output_vt100" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "628223faebab4e3e40667ee0b2336d34a5b960ff60ea743ddfdbcf7770bcfb66" -dependencies = [ - "winapi", -] - [[package]] name = "owo-colors" version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" -[[package]] -name = "p384" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfc8c5bf642dde52bb9e87c0ecd8ca5a76faac2eeed98dedb7c717997e1080aa" -dependencies = [ - "ecdsa", - "elliptic-curve", - "sha2", -] - [[package]] name = "packed_simd_2" version = "0.3.8" @@ -3663,42 +2378,12 @@ dependencies = [ "windows-sys 0.42.0", ] -[[package]] -name = "pasetors" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed20c4c21d893414f42e0cbfebe8a8036b5ae9b0264611fb6504e395eda6ceec" -dependencies = [ - "ct-codecs", - "ed25519-compact", - "getrandom", - "orion", - "p384", - "rand_core", - "regex", - "serde", - "serde_json", - "sha2", - "subtle", - "time 0.3.17", - "zeroize", -] - [[package]] name = "pathdiff" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" -[[package]] -name = "pem-rfc7468" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d159833a9105500e0398934e205e0773f0b27529557134ecfc51c27646adac" -dependencies = [ - "base64ct", -] - [[package]] name = "percent-encoding" version = "2.1.0" @@ -3818,16 +2503,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" -[[package]] -name = "pkcs8" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9eca2c590a5f85da82668fa685c09ce2888b9430e83299debf1f34b65fd4a4ba" -dependencies = [ - "der", - "spki", -] - [[package]] name = "pkg-config" version = "0.3.25" @@ -3857,28 +2532,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" -[[package]] -name = "pretty_assertions" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a25e9bcb20aa780fd0bb16b72403a9064d6b3f22f026946029acb941a50af755" -dependencies = [ - "ctor", - "diff", - "output_vt100", - "yansi", -] - -[[package]] -name = "pretty_env_logger" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "926d36b9553851b8b0005f1275891b392ee4d2d833852c417ed025477350fb9d" -dependencies = [ - "env_logger 0.7.1", - "log", -] - [[package]] name = "proc-macro-error" version = "1.0.4" @@ -3926,15 +2579,6 @@ dependencies = [ "std", ] -[[package]] -name = "prodash" -version = "23.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d73c6b64cb5b99eb63ca97d378685712617ec0172ff5c04cd47a489d3e2c51f8" -dependencies = [ - "parking_lot 0.12.1", -] - [[package]] name = "profiler_builtins" version = "0.0.0" @@ -3976,12 +2620,6 @@ version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" -[[package]] -name = "quick-error" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" - [[package]] name = "quine-mc_cluskey" version = "0.2.4" @@ -4148,17 +2786,6 @@ dependencies = [ "walkdir", ] -[[package]] -name = "rfc6979" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb" -dependencies = [ - "crypto-bigint", - "hmac", - "zeroize", -] - [[package]] name = "rls" version = "2.0.0" @@ -4567,7 +3194,7 @@ dependencies = [ name = "rustc_data_structures" version = "0.0.0" dependencies = [ - "arrayvec 0.7.0", + "arrayvec", "bitflags", "cfg-if", "elsa", @@ -4577,7 +3204,7 @@ dependencies = [ "jobserver", "libc", "measureme", - "memmap2 0.2.1", + "memmap2", "parking_lot 0.11.2", "rustc-hash", "rustc-rayon", @@ -4593,7 +3220,7 @@ dependencies = [ "tempfile", "thin-vec", "tracing", - "windows 0.46.0", + "windows", ] [[package]] @@ -4652,7 +3279,7 @@ dependencies = [ "rustc_ty_utils", "serde_json", "tracing", - "windows 0.46.0", + "windows", ] [[package]] @@ -4700,7 +3327,7 @@ dependencies = [ "termize", "tracing", "unicode-width", - "windows 0.46.0", + "windows", ] [[package]] @@ -4848,7 +3475,7 @@ dependencies = [ name = "rustc_index" version = "0.0.0" dependencies = [ - "arrayvec 0.7.0", + "arrayvec", "rustc_macros", "rustc_serialize", "smallvec", @@ -5343,7 +3970,7 @@ dependencies = [ "smallvec", "termize", "tracing", - "windows 0.46.0", + "windows", ] [[package]] @@ -5520,7 +4147,7 @@ dependencies = [ name = "rustdoc" version = "0.0.0" dependencies = [ - "arrayvec 0.7.0", + "arrayvec", "askama", "expect-test", "itertools", @@ -5605,7 +4232,7 @@ dependencies = [ "serde_json", "term", "thiserror", - "toml 0.5.7", + "toml", "unicode-segmentation", "unicode-width", "unicode_categories", @@ -5668,43 +4295,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" -[[package]] -name = "sec1" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928" -dependencies = [ - "base16ct", - "der", - "generic-array", - "pkcs8", - "subtle", - "zeroize", -] - -[[package]] -name = "security-framework" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1759c2e3c8580017a484a7ac56d3abc5a6c1feadf88db2f3633f12ae4268c69" -dependencies = [ - "bitflags", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f99b9d5e26d2a71633cc4f2ebae7cc9f874044e0c351a27e17892d76dce5678b" -dependencies = [ - "core-foundation-sys", - "libc", -] - [[package]] name = "self_cell" version = "0.10.2" @@ -5729,16 +4319,6 @@ dependencies = [ "serde_derive", ] -[[package]] -name = "serde-value" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" -dependencies = [ - "ordered-float", - "serde", -] - [[package]] name = "serde_derive" version = "1.0.159" @@ -5750,15 +4330,6 @@ dependencies = [ "syn 2.0.8", ] -[[package]] -name = "serde_ignored" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c2c7d39d14f2f2ea82239de71594782f186fd03501ac81f0ce08e674819ff2f" -dependencies = [ - "serde", -] - [[package]] name = "serde_json" version = "1.0.85" @@ -5771,15 +4342,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serde_spanned" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4" -dependencies = [ - "serde", -] - [[package]] name = "sha1" version = "0.10.5" @@ -5791,12 +4353,6 @@ dependencies = [ "digest", ] -[[package]] -name = "sha1_smol" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" - [[package]] name = "sha2" version = "0.10.6" @@ -5829,57 +4385,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42a568c8f2cd051a4d283bd6eb0343ac214c1b0f1ac19f93e1175b2dee38c73d" -[[package]] -name = "signal-hook" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "732768f1176d21d09e076c23a93123d40bba92d50c4058da34d45c8de8e682b9" -dependencies = [ - "libc", - "signal-hook-registry", -] - -[[package]] -name = "signal-hook-registry" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" -dependencies = [ - "libc", -] - -[[package]] -name = "signature" -version = "1.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" -dependencies = [ - "digest", - "rand_core", -] - -[[package]] -name = "similar" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e24979f63a11545f5f2c60141afe249d4f19f84581ea2138065e400941d83d3" - [[package]] name = "siphasher" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa8f3741c7372e75519bd9346068370c9cdaabcc1f9599cbcf2a2719352286b7" -[[package]] -name = "sized-chunks" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65e65d6a9f13cd78f361ea5a2cf53a45d67cdda421ba0316b9be101560f3d207" -dependencies = [ - "bitmaps", - "typenum", -] - [[package]] name = "slab" version = "0.4.2" @@ -5898,30 +4409,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e9f0ab6ef7eb7353d9119c170a436d1bf248eea575ac42d19d12f4e34130831" -[[package]] -name = "snapbox" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "827c00e91b15e2674d8a5270bae91f898693cbf9561cbb58d8eaa31974597293" -dependencies = [ - "concolor", - "content_inspector", - "dunce", - "filetime", - "normalize-line-endings", - "similar", - "snapbox-macros", - "tempfile", - "walkdir", - "yansi", -] - -[[package]] -name = "snapbox-macros" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a253e6f894cfa440cba00600a249fa90869d8e0ec45ab274a456e043a0ce8f2" - [[package]] name = "socket2" version = "0.4.1" @@ -5961,16 +4448,6 @@ dependencies = [ "uuid", ] -[[package]] -name = "spki" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b" -dependencies = [ - "base64ct", - "der", -] - [[package]] name = "stable_deref_trait" version = "1.2.0" @@ -6060,15 +4537,6 @@ dependencies = [ "quote", ] -[[package]] -name = "strip-ansi-escapes" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "011cbb39cf7c1f62871aea3cc46e5817b0937b49e9447370c93cacbe93a766d8" -dependencies = [ - "vte", -] - [[package]] name = "strsim" version = "0.10.0" @@ -6094,12 +4562,6 @@ dependencies = [ "syn 1.0.102", ] -[[package]] -name = "subtle" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" - [[package]] name = "suggest-tests" version = "0.1.0" @@ -6322,7 +4784,7 @@ dependencies = [ name = "tidy" version = "0.1.0" dependencies = [ - "cargo-platform 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "cargo-platform", "cargo_metadata 0.15.3", "ignore", "lazy_static", @@ -6347,35 +4809,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "time" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376" -dependencies = [ - "itoa", - "libc", - "num_threads", - "serde", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" - -[[package]] -name = "time-macros" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d967f99f534ca7e495c575c62638eebc2898a8c84c119b89e250477bc4ba16b2" -dependencies = [ - "time-core", -] - [[package]] name = "tinystr" version = "0.7.1" @@ -6422,40 +4855,6 @@ dependencies = [ "serde", ] -[[package]] -name = "toml" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7afcae9e3f0fe2c370fd4657108972cbb2fa9db1b9f84849cefd80741b01cb6" -dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", -] - -[[package]] -name = "toml_datetime" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_edit" -version = "0.19.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6a7712b49e1775fb9a7b998de6635b299237f48b404dde71704f2e0e7f37e5" -dependencies = [ - "indexmap", - "nom8", - "serde", - "serde_spanned", - "toml_datetime", -] - [[package]] name = "topological-sort" version = "0.2.2" @@ -6719,12 +5118,6 @@ dependencies = [ "matches", ] -[[package]] -name = "unicode-bom" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63ec69f541d875b783ca40184d655f2927c95f0bffd486faa83cd3ac3529ec32" - [[package]] name = "unicode-ident" version = "1.0.5" @@ -6865,27 +5258,6 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" -[[package]] -name = "vte" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cbce692ab4ca2f1f3047fcf732430249c0e971bfdd2b234cf2c47ad93af5983" -dependencies = [ - "arrayvec 0.5.2", - "utf8parse", - "vte_generate_state_changes", -] - -[[package]] -name = "vte_generate_state_changes" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d257817081c7dffcdbab24b9e62d2def62e2ff7d00b1c20062551e6cccc145ff" -dependencies = [ - "proc-macro2", - "quote", -] - [[package]] name = "walkdir" version = "2.3.2" @@ -6993,21 +5365,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows" -version = "0.43.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04662ed0e3e5630dfa9b26e4cb823b817f1a9addda855d973a9458c236556244" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - [[package]] name = "windows" version = "0.46.0" @@ -7142,12 +5499,6 @@ dependencies = [ "linked-hash-map", ] -[[package]] -name = "yansi" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" - [[package]] name = "yansi-term" version = "0.1.2" @@ -7202,12 +5553,6 @@ dependencies = [ "synstructure 0.12.6", ] -[[package]] -name = "zeroize" -version = "1.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c394b5bd0c6f669e7275d9c20aa90ae064cb22e75a1cad54e1b34088034b149f" - [[package]] name = "zerovec" version = "0.9.2" diff --git a/Cargo.toml b/Cargo.toml index 1fcaaf6ddc4d..64ac39900975 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,12 +22,6 @@ members = [ "src/tools/remote-test-server", "src/tools/rust-installer", "src/tools/rust-demangler", - "src/tools/cargo", - "src/tools/cargo/crates/credential/cargo-credential-1password", - "src/tools/cargo/crates/credential/cargo-credential-macos-keychain", - "src/tools/cargo/crates/credential/cargo-credential-wincred", - "src/tools/cargo/crates/mdman", - # "src/tools/cargo/crates/resolver-tests", "src/tools/rustdoc", "src/tools/rls", "src/tools/rustfmt", diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index 025145244c49..0f3a9f968268 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -822,7 +822,8 @@ class RustBuild(object): if self.use_vendored_sources: vendor_dir = os.path.join(self.rust_root, 'vendor') if not os.path.exists(vendor_dir): - sync_dirs = "--sync ./src/tools/rust-analyzer/Cargo.toml " \ + sync_dirs = "--sync ./src/tools/cargo/Cargo.toml " \ + "--sync ./src/tools/rust-analyzer/Cargo.toml " \ "--sync ./compiler/rustc_codegen_cranelift/Cargo.toml " \ "--sync ./src/bootstrap/Cargo.toml " print('error: vendoring required, but vendor directory does not exist.') diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 9498b772f58e..372d0708c5b9 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -996,11 +996,14 @@ impl Step for PlainSourceTarball { // If we're building from git sources, we need to vendor a complete distribution. if builder.rust_info().is_managed_git_subrepository() { // Ensure we have the submodules checked out. + builder.update_submodule(Path::new("src/tools/cargo")); builder.update_submodule(Path::new("src/tools/rust-analyzer")); // Vendor all Cargo dependencies let mut cmd = Command::new(&builder.initial_cargo); cmd.arg("vendor") + .arg("--sync") + .arg(builder.src.join("./src/tools/cargo/Cargo.toml")) .arg("--sync") .arg(builder.src.join("./src/tools/rust-analyzer/Cargo.toml")) .arg("--sync") diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index d1fd2e8c42cb..1cea3495ade4 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -124,7 +124,7 @@ impl Step for ToolBuild { let is_expected = compile::stream_cargo(builder, cargo, vec![], &mut |msg| { // Only care about big things like the RLS/Cargo for now match tool { - "rls" | "cargo" | "clippy-driver" | "miri" | "rustfmt" => {} + "rls" | "clippy-driver" | "miri" | "rustfmt" => {} _ => return, } @@ -301,6 +301,9 @@ pub fn prepare_tool_cargo( cargo.env("LIBZ_SYS_STATIC", "1"); features.push("rustc-workspace-hack/all-static".to_string()); } + if path.ends_with("cargo") { + features.push("all-static".to_string()); + } } // clippy tests need to know about the stage sysroot. Set them consistently while building to diff --git a/src/tools/cargo b/src/tools/cargo index 84b7041fd274..d0a4cbcee614 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit 84b7041fd2745ee6b3b4a150314f81aabb78e6b2 +Subproject commit d0a4cbcee614fdb7ba66e860e603a00a644d71f8 diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index a9eb6c8d03f7..c80557fb7579 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -18,6 +18,7 @@ const LICENSES: &[&str] = &[ "ISC", "Unlicense/MIT", "Unlicense OR MIT", + "0BSD", "0BSD OR MIT OR Apache-2.0", // adler license "Zlib OR Apache-2.0 OR MIT", // tinyvec "MIT OR Apache-2.0 OR Zlib", // tinyvec_macros @@ -33,30 +34,35 @@ const LICENSES: &[&str] = &[ const EXCEPTIONS: &[(&str, &str)] = &[ ("ar_archive_writer", "Apache-2.0 WITH LLVM-exception"), // rustc ("mdbook", "MPL-2.0"), // mdbook - ("openssl", "Apache-2.0"), // cargo, mdbook ("colored", "MPL-2.0"), // rustfmt ("ryu", "Apache-2.0 OR BSL-1.0"), // cargo/... (because of serde) - ("bytesize", "Apache-2.0"), // cargo - ("im-rc", "MPL-2.0+"), // cargo - ("sized-chunks", "MPL-2.0+"), // cargo via im-rc - ("bitmaps", "MPL-2.0+"), // cargo via im-rc - ("fiat-crypto", "MIT OR Apache-2.0 OR BSD-1-Clause"), // cargo via pasetors - ("subtle", "BSD-3-Clause"), // cargo via pasetors - ("dunce", "CC0-1.0 OR MIT-0"), // cargo via gix (and dev dependency) - ("imara-diff", "Apache-2.0"), // cargo via gix - ("sha1_smol", "BSD-3-Clause"), // cargo via gix - ("unicode-bom", "Apache-2.0"), // cargo via gix ("instant", "BSD-3-Clause"), // rustc_driver/tracing-subscriber/parking_lot ("snap", "BSD-3-Clause"), // rustc ("fluent-langneg", "Apache-2.0"), // rustc (fluent translations) ("self_cell", "Apache-2.0"), // rustc (fluent translations) // FIXME: this dependency violates the documentation comment above: ("fortanix-sgx-abi", "MPL-2.0"), // libstd but only for `sgx` target - ("similar", "Apache-2.0"), // cargo (dev dependency) - ("normalize-line-endings", "Apache-2.0"), // cargo (dev dependency) ("dissimilar", "Apache-2.0"), // rustdoc, rustc_lexer (few tests) via expect-test, (dev deps) ]; +const EXCEPTIONS_CARGO: &[(&str, &str)] = &[ + ("bitmaps", "MPL-2.0+"), + ("bytesize", "Apache-2.0"), + ("dunce", "CC0-1.0 OR MIT-0"), + ("fiat-crypto", "MIT OR Apache-2.0 OR BSD-1-Clause"), + ("im-rc", "MPL-2.0+"), + ("imara-diff", "Apache-2.0"), + ("instant", "BSD-3-Clause"), + ("normalize-line-endings", "Apache-2.0"), + ("openssl", "Apache-2.0"), + ("ryu", "Apache-2.0 OR BSL-1.0"), + ("sha1_smol", "BSD-3-Clause"), + ("similar", "Apache-2.0"), + ("sized-chunks", "MPL-2.0+"), + ("subtle", "BSD-3-Clause"), + ("unicode-bom", "Apache-2.0"), +]; + const EXCEPTIONS_CRANELIFT: &[(&str, &str)] = &[ ("cranelift-bforest", "Apache-2.0 WITH LLVM-exception"), ("cranelift-codegen", "Apache-2.0 WITH LLVM-exception"), @@ -156,7 +162,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "lazy_static", "libc", "libloading", - "libz-sys", "litemap", "lock_api", "log", @@ -177,7 +182,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "perf-event-open-sys", "petgraph", "pin-project-lite", - "pkg-config", "polonius-engine", "ppv-lite86", "proc-macro-hack", @@ -217,7 +221,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "stable_deref_trait", "stacker", "static_assertions", - "subtle", // dependency of cargo (via pasetors) "syn", "synstructure", "tempfile", @@ -256,7 +259,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "unicode-security", "unicode-width", "unicode-xid", - "vcpkg", "valuable", "version_check", "wasi", @@ -359,8 +361,18 @@ pub fn check(root: &Path, cargo: &Path, bad: &mut bool) { &["rustc_driver", "rustc_codegen_llvm"], bad, ); - check_crate_duplicate(&metadata, FORBIDDEN_TO_HAVE_DUPLICATES, bad); - check_rustfix(&metadata, bad); + check_crate_duplicate(&metadata, &[], bad); + + // Check cargo independently as it has it's own workspace. + let mut cmd = cargo_metadata::MetadataCommand::new(); + cmd.cargo_path(cargo) + .manifest_path(root.join("src/tools/cargo/Cargo.toml")) + .features(cargo_metadata::CargoOpt::AllFeatures); + let cargo_metadata = t!(cmd.exec()); + let runtime_ids = HashSet::new(); + check_license_exceptions(&cargo_metadata, EXCEPTIONS_CARGO, runtime_ids, bad); + check_crate_duplicate(&cargo_metadata, FORBIDDEN_TO_HAVE_DUPLICATES, bad); + check_rustfix(&metadata, &cargo_metadata, bad); // Check rustc_codegen_cranelift independently as it has it's own workspace. let mut cmd = cargo_metadata::MetadataCommand::new(); @@ -606,19 +618,19 @@ fn deps_of_filtered<'a>( } } -fn direct_deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> Vec<&'a Package> { +fn direct_deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> impl Iterator { let resolve = metadata.resolve.as_ref().unwrap(); let node = resolve.nodes.iter().find(|n| &n.id == pkg_id).unwrap(); - node.deps.iter().map(|dep| pkg_from_id(metadata, &dep.pkg)).collect() + node.deps.iter().map(|dep| pkg_from_id(metadata, &dep.pkg)) } -fn check_rustfix(metadata: &Metadata, bad: &mut bool) { - let cargo = pkg_from_name(metadata, "cargo"); - let compiletest = pkg_from_name(metadata, "compiletest"); - let cargo_deps = direct_deps_of(metadata, &cargo.id); - let compiletest_deps = direct_deps_of(metadata, &compiletest.id); - let cargo_rustfix = cargo_deps.iter().find(|p| p.name == "rustfix").unwrap(); - let compiletest_rustfix = compiletest_deps.iter().find(|p| p.name == "rustfix").unwrap(); +fn check_rustfix(rust_metadata: &Metadata, cargo_metadata: &Metadata, bad: &mut bool) { + let cargo = pkg_from_name(cargo_metadata, "cargo"); + let cargo_rustfix = direct_deps_of(cargo_metadata, &cargo.id).find(|p| p.name == "rustfix").unwrap(); + + let compiletest = pkg_from_name(rust_metadata, "compiletest"); + let compiletest_rustfix = direct_deps_of(rust_metadata, &compiletest.id).find(|p| p.name == "rustfix").unwrap(); + if cargo_rustfix.version != compiletest_rustfix.version { tidy_error!( bad, From 4c777710c6f5996e0967fe5b9d2924684c646626 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Mon, 20 Mar 2023 11:42:54 +0800 Subject: [PATCH 107/116] tidy: `check_crate_duplicate` is no longer useful After cargo becomes a workspace, no one uses `check_crate_duplicate` to check if cargo is a dependency anymore. --- src/tools/tidy/src/deps.rs | 55 ++++++-------------------------------- 1 file changed, 8 insertions(+), 47 deletions(-) diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index c80557fb7579..0e0a517ae49d 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -335,13 +335,6 @@ const PERMITTED_CRANELIFT_DEPENDENCIES: &[&str] = &[ "windows_x86_64_msvc", ]; -const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[ - // This crate takes quite a long time to build, so don't allow two versions of them - // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times - // under control. - "cargo", -]; - /// Dependency checks. /// /// `root` is path to the directory with the root `Cargo.toml` (for the workspace). `cargo` is path @@ -361,7 +354,6 @@ pub fn check(root: &Path, cargo: &Path, bad: &mut bool) { &["rustc_driver", "rustc_codegen_llvm"], bad, ); - check_crate_duplicate(&metadata, &[], bad); // Check cargo independently as it has it's own workspace. let mut cmd = cargo_metadata::MetadataCommand::new(); @@ -371,7 +363,6 @@ pub fn check(root: &Path, cargo: &Path, bad: &mut bool) { let cargo_metadata = t!(cmd.exec()); let runtime_ids = HashSet::new(); check_license_exceptions(&cargo_metadata, EXCEPTIONS_CARGO, runtime_ids, bad); - check_crate_duplicate(&cargo_metadata, FORBIDDEN_TO_HAVE_DUPLICATES, bad); check_rustfix(&metadata, &cargo_metadata, bad); // Check rustc_codegen_cranelift independently as it has it's own workspace. @@ -389,7 +380,6 @@ pub fn check(root: &Path, cargo: &Path, bad: &mut bool) { &["rustc_codegen_cranelift"], bad, ); - check_crate_duplicate(&metadata, &[], bad); let mut cmd = cargo_metadata::MetadataCommand::new(); cmd.cargo_path(cargo) @@ -535,40 +525,6 @@ fn check_permitted_dependencies( } } -/// Prevents multiple versions of some expensive crates. -fn check_crate_duplicate( - metadata: &Metadata, - forbidden_to_have_duplicates: &[&str], - bad: &mut bool, -) { - for &name in forbidden_to_have_duplicates { - let matches: Vec<_> = metadata.packages.iter().filter(|pkg| pkg.name == name).collect(); - match matches.len() { - 0 => { - tidy_error!( - bad, - "crate `{}` is missing, update `check_crate_duplicate` \ - if it is no longer used", - name - ); - } - 1 => {} - _ => { - tidy_error!( - bad, - "crate `{}` is duplicated in `Cargo.lock`, \ - it is too expensive to build multiple times, \ - so make sure only one version appears across all dependencies", - name - ); - for pkg in matches { - println!(" * {}", pkg.id); - } - } - } - } -} - /// Finds a package with the given name. fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package { let mut i = metadata.packages.iter().filter(|p| p.name == name); @@ -618,7 +574,10 @@ fn deps_of_filtered<'a>( } } -fn direct_deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> impl Iterator { +fn direct_deps_of<'a>( + metadata: &'a Metadata, + pkg_id: &'a PackageId, +) -> impl Iterator { let resolve = metadata.resolve.as_ref().unwrap(); let node = resolve.nodes.iter().find(|n| &n.id == pkg_id).unwrap(); node.deps.iter().map(|dep| pkg_from_id(metadata, &dep.pkg)) @@ -626,10 +585,12 @@ fn direct_deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> impl Ite fn check_rustfix(rust_metadata: &Metadata, cargo_metadata: &Metadata, bad: &mut bool) { let cargo = pkg_from_name(cargo_metadata, "cargo"); - let cargo_rustfix = direct_deps_of(cargo_metadata, &cargo.id).find(|p| p.name == "rustfix").unwrap(); + let cargo_rustfix = + direct_deps_of(cargo_metadata, &cargo.id).find(|p| p.name == "rustfix").unwrap(); let compiletest = pkg_from_name(rust_metadata, "compiletest"); - let compiletest_rustfix = direct_deps_of(rust_metadata, &compiletest.id).find(|p| p.name == "rustfix").unwrap(); + let compiletest_rustfix = + direct_deps_of(rust_metadata, &compiletest.id).find(|p| p.name == "rustfix").unwrap(); if cargo_rustfix.version != compiletest_rustfix.version { tidy_error!( From 82950f6895638b7fe5e80a961cb03fca27436629 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Tue, 14 Mar 2023 10:23:14 +0000 Subject: [PATCH 108/116] bootstrap: treat src/tools/cargo as a workspace member We remove `src/tools/cargo` from rust-lang/rust root workspace, but some underlying mechanism still needs it to be a member. for example, `./x.py doc`. This little hack make cargo's metadata available by invoking an extra `cargo metadata` for cargo the package itself. Co-authored-by: Scott Schafer Co-authored-by: Eric Huss --- src/bootstrap/metadata.rs | 59 +++++++++++++++++++++++++++++---------- 1 file changed, 44 insertions(+), 15 deletions(-) diff --git a/src/bootstrap/metadata.rs b/src/bootstrap/metadata.rs index bba4d65e8c31..597aefadcfe4 100644 --- a/src/bootstrap/metadata.rs +++ b/src/bootstrap/metadata.rs @@ -7,12 +7,16 @@ use crate::cache::INTERNER; use crate::util::output; use crate::{Build, Crate}; -#[derive(Deserialize)] +/// For more information, see the output of +/// +#[derive(Debug, Deserialize)] struct Output { packages: Vec, } -#[derive(Deserialize)] +/// For more information, see the output of +/// +#[derive(Debug, Deserialize)] struct Package { name: String, source: Option, @@ -20,25 +24,18 @@ struct Package { dependencies: Vec, } -#[derive(Deserialize)] +/// For more information, see the output of +/// +#[derive(Debug, Deserialize)] struct Dependency { name: String, source: Option, } +/// Collects and stores package metadata of each workspace members into `build`, +/// by executing `cargo metadata` commands. pub fn build(build: &mut Build) { - // Run `cargo metadata` to figure out what crates we're testing. - let mut cargo = Command::new(&build.initial_cargo); - cargo - .arg("metadata") - .arg("--format-version") - .arg("1") - .arg("--no-deps") - .arg("--manifest-path") - .arg(build.src.join("Cargo.toml")); - let output = output(&mut cargo); - let output: Output = serde_json::from_str(&output).unwrap(); - for package in output.packages { + for package in workspace_members(build) { if package.source.is_none() { let name = INTERNER.intern_string(package.name); let mut path = PathBuf::from(package.manifest_path); @@ -57,3 +54,35 @@ pub fn build(build: &mut Build) { } } } + +/// Invokes `cargo metadata` to get package metadata of each workspace member. +/// +/// Note that `src/tools/cargo` is no longer a workspace member but we still +/// treat it as one here, by invoking an additional `cargo metadata` command. +fn workspace_members(build: &Build) -> impl Iterator { + let cmd_metadata = |manifest_path| { + let mut cargo = Command::new(&build.initial_cargo); + cargo + .arg("metadata") + .arg("--format-version") + .arg("1") + .arg("--no-deps") + .arg("--manifest-path") + .arg(manifest_path); + cargo + }; + + // Collects `metadata.packages` from the root workspace. + let root_manifest_path = build.src.join("Cargo.toml"); + let root_output = output(&mut cmd_metadata(&root_manifest_path)); + let Output { packages, .. } = serde_json::from_str(&root_output).unwrap(); + + // Collects `metadata.packages` from src/tools/cargo separately. + let cargo_manifest_path = build.src.join("src/tools/cargo/Cargo.toml"); + let cargo_output = output(&mut cmd_metadata(&cargo_manifest_path)); + let Output { packages: cargo_packages, .. } = serde_json::from_str(&cargo_output).unwrap(); + + // We only care about the root package from `src/tool/cargo` workspace. + let cargo_package = cargo_packages.into_iter().find(|pkg| pkg.name == "cargo").into_iter(); + packages.into_iter().chain(cargo_package) +} From 1cfaa3431e9d8633472316c714962de960db0842 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Thu, 23 Mar 2023 23:54:10 +0800 Subject: [PATCH 109/116] chore: remove Cargo features in rustc-workspace-hack --- Cargo.lock | 82 ---------------------- src/bootstrap/tool.rs | 1 - src/tools/rustc-workspace-hack/Cargo.toml | 85 +---------------------- 3 files changed, 1 insertion(+), 167 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2c1a498da779..94de4403c63a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -306,12 +306,6 @@ dependencies = [ "toml", ] -[[package]] -name = "bumpalo" -version = "3.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "572f695136211188308f16ad2ca5c851a712c464060ae6974944458eb83880ba" - [[package]] name = "bytecount" version = "0.6.2" @@ -1405,10 +1399,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" dependencies = [ "cfg-if", - "js-sys", "libc", "wasi", - "wasm-bindgen", ] [[package]] @@ -1780,15 +1772,6 @@ dependencies = [ "libc", ] -[[package]] -name = "js-sys" -version = "0.3.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49409df3e3bf0856b916e2ceaca09ee28e6871cf7d9ce97a692cacfdb2a25a47" -dependencies = [ - "wasm-bindgen", -] - [[package]] name = "jsondocck" version = "0.1.0" @@ -2903,20 +2886,9 @@ dependencies = [ name = "rustc-workspace-hack" version = "1.0.0" dependencies = [ - "bstr 0.2.17", - "clap 3.2.20", - "getrandom", - "hashbrown 0.12.3", "libc", - "libz-sys", - "once_cell", - "rand", "regex", "serde_json", - "smallvec", - "syn 1.0.102", - "url", - "winapi", ] [[package]] @@ -5280,60 +5252,6 @@ dependencies = [ "rustc-std-workspace-core", ] -[[package]] -name = "wasm-bindgen" -version = "0.2.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268" -dependencies = [ - "cfg-if", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c8ffb332579b0557b52d268b91feab8df3615f265d5270fec2a8c95b17c1142" -dependencies = [ - "bumpalo", - "log", - "once_cell", - "proc-macro2", - "quote", - "syn 1.0.102", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "052be0f94026e6cbc75cdefc9bae13fd6052cdcaf532fa6c45e7ae33a1e6c810" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.102", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f" - [[package]] name = "winapi" version = "0.3.9" diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index 1cea3495ade4..0d6f16955187 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -299,7 +299,6 @@ pub fn prepare_tool_cargo( || path.ends_with("rustfmt") { cargo.env("LIBZ_SYS_STATIC", "1"); - features.push("rustc-workspace-hack/all-static".to_string()); } if path.ends_with("cargo") { features.push("all-static".to_string()); diff --git a/src/tools/rustc-workspace-hack/Cargo.toml b/src/tools/rustc-workspace-hack/Cargo.toml index e088ffbbe773..5d5d57fc9ef1 100644 --- a/src/tools/rustc-workspace-hack/Cargo.toml +++ b/src/tools/rustc-workspace-hack/Cargo.toml @@ -12,91 +12,8 @@ path = "lib.rs" # For documentation about what this is and why in the world these dependencies # are appearing, see `README.md`. - -[target.'cfg(windows)'.dependencies.winapi] -version = "0.3" -features = [ - "accctrl", - "aclapi", - "basetsd", - "cfg", - "consoleapi", - "errhandlingapi", - "evntrace", - "fibersapi", - "handleapi", - "in6addr", - "inaddr", - "ioapiset", - "jobapi", - "jobapi2", - "knownfolders", - "libloaderapi", - "lmcons", - "memoryapi", - "minschannel", - "minwinbase", - "mstcpip", - "mswsock", - "namedpipeapi", - "ntdef", - "ntsecapi", - "ntstatus", - "objbase", - "processenv", - "processthreadsapi", - "profileapi", - "psapi", - "schannel", - "securitybaseapi", - "shellapi", - "shlobj", - "sspi", - "synchapi", - "sysinfoapi", - "threadpoollegacyapiset", - "timezoneapi", - "userenv", - "winbase", - "wincon", - "wincrypt", - "windef", - "winioctl", - "winnt", - "winreg", - "winsock2", - "winuser", - "ws2def", - "ws2ipdef", - "ws2tcpip", -] - [dependencies] -bstr = { version = "0.2.17", features = ["default"] } -clap = { version = "3.1.1", features = ["derive", "clap_derive"]} -curl-sys = { version = "0.4.13", features = ["http2", "libnghttp2-sys"], optional = true } -# Ensure `extra_traits` of libc, which is used transitively by Cargo. libc = { version = "0.2", features = ["extra_traits"] } -# Ensure `js` of getrandom, which is (unfortunately) used transitively by Cargo. -getrandom = { version = "0.2", features = ["js"] } -# Ensure default features of libz-sys, which are disabled in some scenarios. -libz-sys = { version = "1.1.2" } +serde_json = { version = "1.0.31", features = ["unbounded_depth"] } # Ensure default features of regex, which are disabled in some scenarios. regex = { version = "1.5.6" } -serde_json = { version = "1.0.31", features = ["raw_value", "unbounded_depth"] } -syn = { version = "1", features = ['full', 'visit', 'visit-mut'] } # `visit-mut` required by Cargo via `gix` -url = { version = "2.0", features = ['serde'] } -# Ensure default features of rand, which are disabled in some scenarios. -rand = { version = "0.8.5" } - -# Ensure features of `hashbrown`, `smallvec`, and `once_cell`, -# which are used transitively by Cargo (via `gix`). -hashbrown = { version = "0.12.3", default-features = false, features = ["inline-more"] } -once_cell = { version = "1.16.0", default-features = false, features = ["unstable"] } -smallvec = { version = "1.10.0", features = ["write"] } - -[target.'cfg(not(windows))'.dependencies] -openssl = { version = "0.10.35", optional = true } - -[features] -all-static = ['openssl/vendored', 'curl-sys/static-curl', 'curl-sys/force-system-lib-on-osx'] From befa5c98c956bd499f741c582b96bf8d49fe7dbc Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Mon, 13 Mar 2023 17:46:38 +0000 Subject: [PATCH 110/116] chore: remove `rustc-workspace-hack` Co-authored-by: Scott Schafer Co-authored-by: Eric Huss --- Cargo.lock | 8 +- Cargo.toml | 4 - src/bootstrap/lib.rs | 3 - src/bootstrap/tool.rs | 131 +--------------------- src/tools/rls/Cargo.toml | 4 - src/tools/rustc-workspace-hack/Cargo.toml | 19 ---- src/tools/rustc-workspace-hack/README.md | 25 ----- src/tools/rustc-workspace-hack/lib.rs | 1 - 8 files changed, 4 insertions(+), 191 deletions(-) delete mode 100644 src/tools/rustc-workspace-hack/Cargo.toml delete mode 100644 src/tools/rustc-workspace-hack/README.md delete mode 100644 src/tools/rustc-workspace-hack/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 94de4403c63a..358b2f2e924c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2773,7 +2773,6 @@ dependencies = [ name = "rls" version = "2.0.0" dependencies = [ - "rustc-workspace-hack", "serde", "serde_json", ] @@ -2885,11 +2884,8 @@ dependencies = [ [[package]] name = "rustc-workspace-hack" version = "1.0.0" -dependencies = [ - "libc", - "regex", - "serde_json", -] +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc71d2faa173b74b232dedc235e3ee1696581bb132fc116fa3626d6151a1a8fb" [[package]] name = "rustc_abi" diff --git a/Cargo.toml b/Cargo.toml index 64ac39900975..a497d7321e02 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -100,10 +100,6 @@ miniz_oxide.debug = 0 object.debug = 0 [patch.crates-io] -# See comments in `src/tools/rustc-workspace-hack/README.md` for what's going on -# here -rustc-workspace-hack = { path = 'src/tools/rustc-workspace-hack' } - # 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' } diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index 419bcbc63cff..bfdb029951f2 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -238,8 +238,6 @@ pub struct Build { ci_env: CiEnv, delayed_failures: RefCell>, prerelease_version: Cell>, - tool_artifacts: - RefCell)>>>, #[cfg(feature = "build-metrics")] metrics: metrics::BuildMetrics, @@ -458,7 +456,6 @@ impl Build { ci_env: CiEnv::current(), delayed_failures: RefCell::new(Vec::new()), prerelease_version: Cell::new(None), - tool_artifacts: Default::default(), #[cfg(feature = "build-metrics")] metrics: metrics::BuildMetrics::init(), diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index 0d6f16955187..842aa91ad5a5 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -1,4 +1,3 @@ -use std::collections::HashSet; use std::env; use std::fs; use std::path::PathBuf; @@ -120,136 +119,10 @@ impl Step for ToolBuild { &self.target, ); builder.info(&msg); - let mut duplicates = Vec::new(); - let is_expected = compile::stream_cargo(builder, cargo, vec![], &mut |msg| { - // Only care about big things like the RLS/Cargo for now - match tool { - "rls" | "clippy-driver" | "miri" | "rustfmt" => {} - - _ => return, - } - let (id, features, filenames) = match msg { - compile::CargoMessage::CompilerArtifact { - package_id, - features, - filenames, - target: _, - } => (package_id, features, filenames), - _ => return, - }; - let features = features.iter().map(|s| s.to_string()).collect::>(); - - for path in filenames { - let val = (tool, PathBuf::from(&*path), features.clone()); - // we're only interested in deduplicating rlibs for now - if val.1.extension().and_then(|s| s.to_str()) != Some("rlib") { - continue; - } - - // Don't worry about compiles that turn out to be host - // dependencies or build scripts. To skip these we look for - // anything that goes in `.../release/deps` but *doesn't* go in - // `$target/release/deps`. This ensure that outputs in - // `$target/release` are still considered candidates for - // deduplication. - if let Some(parent) = val.1.parent() { - if parent.ends_with("release/deps") { - let maybe_target = parent - .parent() - .and_then(|p| p.parent()) - .and_then(|p| p.file_name()) - .and_then(|p| p.to_str()) - .unwrap(); - if maybe_target != &*target.triple { - continue; - } - } - } - - // Record that we've built an artifact for `id`, and if one was - // already listed then we need to see if we reused the same - // artifact or produced a duplicate. - let mut artifacts = builder.tool_artifacts.borrow_mut(); - let prev_artifacts = artifacts.entry(target).or_default(); - let prev = match prev_artifacts.get(&*id) { - Some(prev) => prev, - None => { - prev_artifacts.insert(id.to_string(), val); - continue; - } - }; - if prev.1 == val.1 { - return; // same path, same artifact - } - - // If the paths are different and one of them *isn't* inside of - // `release/deps`, then it means it's probably in - // `$target/release`, or it's some final artifact like - // `libcargo.rlib`. In these situations Cargo probably just - // copied it up from `$target/release/deps/libcargo-xxxx.rlib`, - // so if the features are equal we can just skip it. - let prev_no_hash = prev.1.parent().unwrap().ends_with("release/deps"); - let val_no_hash = val.1.parent().unwrap().ends_with("release/deps"); - if prev.2 == val.2 || !prev_no_hash || !val_no_hash { - return; - } - - // ... and otherwise this looks like we duplicated some sort of - // compilation, so record it to generate an error later. - duplicates.push((id.to_string(), val, prev.clone())); - } + let is_expected = compile::stream_cargo(builder, cargo, vec![], &mut |_msg| { + return; }); - if is_expected && !duplicates.is_empty() { - eprintln!( - "duplicate artifacts found when compiling a tool, this \ - typically means that something was recompiled because \ - a transitive dependency has different features activated \ - than in a previous build:\n" - ); - let (same, different): (Vec<_>, Vec<_>) = - duplicates.into_iter().partition(|(_, cur, prev)| cur.2 == prev.2); - if !same.is_empty() { - eprintln!( - "the following dependencies are duplicated although they \ - have the same features enabled:" - ); - for (id, cur, prev) in same { - eprintln!(" {}", id); - // same features - eprintln!(" `{}` ({:?})\n `{}` ({:?})", cur.0, cur.1, prev.0, prev.1); - } - } - if !different.is_empty() { - eprintln!("the following dependencies have different features:"); - for (id, cur, prev) in different { - eprintln!(" {}", id); - let cur_features: HashSet<_> = cur.2.into_iter().collect(); - let prev_features: HashSet<_> = prev.2.into_iter().collect(); - eprintln!( - " `{}` additionally enabled features {:?} at {:?}", - cur.0, - &cur_features - &prev_features, - cur.1 - ); - eprintln!( - " `{}` additionally enabled features {:?} at {:?}", - prev.0, - &prev_features - &cur_features, - prev.1 - ); - } - } - eprintln!(); - eprintln!( - "to fix this you will probably want to edit the local \ - src/tools/rustc-workspace-hack/Cargo.toml crate, as \ - that will update the dependency graph to ensure that \ - these crates all share the same feature set" - ); - panic!("tools should not compile multiple copies of the same crate"); - } - builder.save_toolstate( tool, if is_expected { ToolState::TestFail } else { ToolState::BuildFail }, diff --git a/src/tools/rls/Cargo.toml b/src/tools/rls/Cargo.toml index 92b50bf4cec3..b84647eb3327 100644 --- a/src/tools/rls/Cargo.toml +++ b/src/tools/rls/Cargo.toml @@ -7,7 +7,3 @@ license = "Apache-2.0/MIT" [dependencies] serde = { version = "1.0.143", features = ["derive"] } serde_json = "1.0.83" -# A noop dependency that changes in the Rust repository, it's a bit of a hack. -# See the `src/tools/rustc-workspace-hack/README.md` file in `rust-lang/rust` -# for more information. -rustc-workspace-hack = "1.0.0" diff --git a/src/tools/rustc-workspace-hack/Cargo.toml b/src/tools/rustc-workspace-hack/Cargo.toml deleted file mode 100644 index 5d5d57fc9ef1..000000000000 --- a/src/tools/rustc-workspace-hack/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "rustc-workspace-hack" -version = "1.0.0" -license = 'MIT OR Apache-2.0' -description = """ -Hack for the compiler's own build system -""" -edition = "2021" - -[lib] -path = "lib.rs" - -# For documentation about what this is and why in the world these dependencies -# are appearing, see `README.md`. -[dependencies] -libc = { version = "0.2", features = ["extra_traits"] } -serde_json = { version = "1.0.31", features = ["unbounded_depth"] } -# Ensure default features of regex, which are disabled in some scenarios. -regex = { version = "1.5.6" } diff --git a/src/tools/rustc-workspace-hack/README.md b/src/tools/rustc-workspace-hack/README.md deleted file mode 100644 index 3c61470358ba..000000000000 --- a/src/tools/rustc-workspace-hack/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# `rustc-workspace-hack` - -This crate is a bit of a hack to make workspaces in rustc work a bit better. -The rationale for this existence is a bit subtle, but the general idea is that -we want commands like `./x.py build src/tools/{clippy,cargo}` to share as -many dependencies as possible. - -Each invocation is a different invocation of Cargo, however. Each time Cargo -runs a build it will re-resolve the dependency graph, notably selecting -different features sometimes for each build. - -For example, let's say there's a very deep dependency like `winapi` in each of -these builds. For Cargo, `winapi` has 33 features enabled. In Clippy, however, -`winapi` has 22 features enabled. This means that building Cargo and then the -Clippy will actually build winapi twice, which in turn will build duplicates -of everything that depends on `winapi`. This is bad! - -The goal of this crate is to solve this problem and ensure that the resolved -dependency graph for all of these tools is the same in the various subsets of -each tool, notably enabling the same features of transitive dependencies. - -All tools vendored here depend on the `rustc-workspace-hack` crate on crates.io. -When on crates.io this crate is an empty crate that is just a noop. We override -it, however, in this workspace to this crate here, which means we can control -crates in the dependency graph for each of these tools. diff --git a/src/tools/rustc-workspace-hack/lib.rs b/src/tools/rustc-workspace-hack/lib.rs deleted file mode 100644 index 44425d9c15fc..000000000000 --- a/src/tools/rustc-workspace-hack/lib.rs +++ /dev/null @@ -1 +0,0 @@ -// intentionally left blank From 103ed0e5c800f87a27fe9c85902e8e6a3f443b52 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Wed, 12 Apr 2023 12:15:16 +0100 Subject: [PATCH 111/116] bootstrap: switch from `stream_cargo` to `try_run_quiet` It is unnecessary to stream cargo JSON output. --- src/bootstrap/tool.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index 842aa91ad5a5..c732fd7e8335 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -119,9 +119,9 @@ impl Step for ToolBuild { &self.target, ); builder.info(&msg); - let is_expected = compile::stream_cargo(builder, cargo, vec![], &mut |_msg| { - return; - }); + + let mut cargo = Command::from(cargo); + let is_expected = builder.try_run_quiet(&mut cargo); builder.save_toolstate( tool, From f6bfb4bf8e62e5f924790e62b4e8321b7658da2b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 7 Apr 2023 05:25:56 +0000 Subject: [PATCH 112/116] Erase regions when confirming transmutability candidate --- .../src/solve/eval_ctxt.rs | 2 +- .../src/traits/error_reporting/mod.rs | 22 ++++----- .../src/traits/select/confirmation.rs | 46 ++++++++++--------- compiler/rustc_transmute/src/lib.rs | 9 ++-- .../transmutability/references.current.stderr | 4 +- .../ui/transmutability/references.next.stderr | 4 +- tests/ui/transmutability/region-infer.rs | 22 +++++++++ tests/ui/transmutability/region-infer.stderr | 23 ++++++++++ 8 files changed, 88 insertions(+), 44 deletions(-) create mode 100644 tests/ui/transmutability/region-infer.rs create mode 100644 tests/ui/transmutability/region-infer.stderr diff --git a/compiler/rustc_trait_selection/src/solve/eval_ctxt.rs b/compiler/rustc_trait_selection/src/solve/eval_ctxt.rs index c29b5b04e000..bb574954587e 100644 --- a/compiler/rustc_trait_selection/src/solve/eval_ctxt.rs +++ b/compiler/rustc_trait_selection/src/solve/eval_ctxt.rs @@ -649,7 +649,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { // FIXME(transmutability): This really should be returning nested goals for `Answer::If*` match rustc_transmute::TransmuteTypeEnv::new(self.infcx).is_transmutable( ObligationCause::dummy(), - ty::Binder::dummy(src_and_dst), + src_and_dst, scope, assume, ) { diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index cef982fcb41e..0352f0f380db 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -742,7 +742,6 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { { // Recompute the safe transmute reason and use that for the error reporting self.get_safe_transmute_error_and_reason( - trait_predicate, obligation.clone(), trait_ref, span, @@ -1629,7 +1628,6 @@ trait InferCtxtPrivExt<'tcx> { fn get_safe_transmute_error_and_reason( &self, - trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>, obligation: Obligation<'tcx, ty::Predicate<'tcx>>, trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>, span: Span, @@ -2921,18 +2919,20 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { fn get_safe_transmute_error_and_reason( &self, - trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>, obligation: Obligation<'tcx, ty::Predicate<'tcx>>, trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>, span: Span, ) -> (String, Option) { - let src_and_dst = trait_predicate.map_bound(|p| rustc_transmute::Types { - dst: p.trait_ref.substs.type_at(0), - src: p.trait_ref.substs.type_at(1), - }); - let scope = trait_ref.skip_binder().substs.type_at(2); + // Erase regions because layout code doesn't particularly care about regions. + let trait_ref = self.tcx.erase_regions(self.tcx.erase_late_bound_regions(trait_ref)); + + let src_and_dst = rustc_transmute::Types { + dst: trait_ref.substs.type_at(0), + src: trait_ref.substs.type_at(1), + }; + let scope = trait_ref.substs.type_at(2); let Some(assume) = - rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, trait_ref.skip_binder().substs.const_at(3)) else { + rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, trait_ref.substs.const_at(3)) else { span_bug!(span, "Unable to construct rustc_transmute::Assume where it was previously possible"); }; match rustc_transmute::TransmuteTypeEnv::new(self.infcx).is_transmutable( @@ -2942,8 +2942,8 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { assume, ) { rustc_transmute::Answer::No(reason) => { - let dst = trait_ref.skip_binder().substs.type_at(0); - let src = trait_ref.skip_binder().substs.type_at(1); + let dst = trait_ref.substs.type_at(0); + let src = trait_ref.substs.type_at(1); let custom_err_msg = format!( "`{src}` cannot be safely transmuted into `{dst}` in the defining scope of `{scope}`" ); diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 5e60bc01bb64..3bba11262f5b 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -275,33 +275,35 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ) -> Result>, SelectionError<'tcx>> { debug!(?obligation, "confirm_transmutability_candidate"); - let predicate = obligation.predicate; + // We erase regions here because transmutability calls layout queries, + // which does not handle inference regions and doesn't particularly + // care about other regions. Erasing late-bound regions is equivalent + // to instantiating the binder with placeholders then erasing those + // placeholder regions. + let predicate = + self.tcx().erase_regions(self.tcx().erase_late_bound_regions(obligation.predicate)); - let type_at = |i| predicate.map_bound(|p| p.trait_ref.substs.type_at(i)); - let const_at = |i| predicate.skip_binder().trait_ref.substs.const_at(i); - - let src_and_dst = predicate.map_bound(|p| rustc_transmute::Types { - dst: p.trait_ref.substs.type_at(0), - src: p.trait_ref.substs.type_at(1), - }); - - let scope = type_at(2).skip_binder(); - - let Some(assume) = - rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, const_at(3)) else { - return Err(Unimplemented); - }; - - let cause = obligation.cause.clone(); + let Some(assume) = rustc_transmute::Assume::from_const( + self.infcx.tcx, + obligation.param_env, + predicate.trait_ref.substs.const_at(3) + ) else { + return Err(Unimplemented); + }; let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx); - - let maybe_transmutable = transmute_env.is_transmutable(cause, src_and_dst, scope, assume); - - use rustc_transmute::Answer; + let maybe_transmutable = transmute_env.is_transmutable( + obligation.cause.clone(), + rustc_transmute::Types { + dst: predicate.trait_ref.substs.type_at(0), + src: predicate.trait_ref.substs.type_at(1), + }, + predicate.trait_ref.substs.type_at(2), + assume, + ); match maybe_transmutable { - Answer::Yes => Ok(ImplSourceBuiltinData { nested: vec![] }), + rustc_transmute::Answer::Yes => Ok(ImplSourceBuiltinData { nested: vec![] }), _ => Err(Unimplemented), } } diff --git a/compiler/rustc_transmute/src/lib.rs b/compiler/rustc_transmute/src/lib.rs index a93a42987ed5..8be02c1d9888 100644 --- a/compiler/rustc_transmute/src/lib.rs +++ b/compiler/rustc_transmute/src/lib.rs @@ -64,7 +64,6 @@ mod rustc { use rustc_infer::infer::InferCtxt; use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_middle::traits::ObligationCause; - use rustc_middle::ty::Binder; use rustc_middle::ty::Const; use rustc_middle::ty::ParamEnv; use rustc_middle::ty::Ty; @@ -92,15 +91,13 @@ mod rustc { pub fn is_transmutable( &mut self, cause: ObligationCause<'tcx>, - src_and_dst: Binder<'tcx, Types<'tcx>>, + types: Types<'tcx>, scope: Ty<'tcx>, assume: crate::Assume, ) -> crate::Answer> { - let src = src_and_dst.map_bound(|types| types.src).skip_binder(); - let dst = src_and_dst.map_bound(|types| types.dst).skip_binder(); crate::maybe_transmutable::MaybeTransmutableQuery::new( - src, - dst, + types.src, + types.dst, scope, assume, self.infcx.tcx, diff --git a/tests/ui/transmutability/references.current.stderr b/tests/ui/transmutability/references.current.stderr index ecb095354a51..819c9b92bc81 100644 --- a/tests/ui/transmutability/references.current.stderr +++ b/tests/ui/transmutability/references.current.stderr @@ -1,8 +1,8 @@ -error[E0277]: `&'static Unit` cannot be safely transmuted into `&'static Unit` in the defining scope of `assert::Context` +error[E0277]: `&Unit` cannot be safely transmuted into `&Unit` in the defining scope of `assert::Context` --> $DIR/references.rs:29:52 | LL | assert::is_maybe_transmutable::<&'static Unit, &'static Unit>(); - | ^^^^^^^^^^^^^ `&'static Unit` does not have a well-specified layout + | ^^^^^^^^^^^^^ `&Unit` does not have a well-specified layout | note: required by a bound in `is_maybe_transmutable` --> $DIR/references.rs:16:14 diff --git a/tests/ui/transmutability/references.next.stderr b/tests/ui/transmutability/references.next.stderr index ecb095354a51..819c9b92bc81 100644 --- a/tests/ui/transmutability/references.next.stderr +++ b/tests/ui/transmutability/references.next.stderr @@ -1,8 +1,8 @@ -error[E0277]: `&'static Unit` cannot be safely transmuted into `&'static Unit` in the defining scope of `assert::Context` +error[E0277]: `&Unit` cannot be safely transmuted into `&Unit` in the defining scope of `assert::Context` --> $DIR/references.rs:29:52 | LL | assert::is_maybe_transmutable::<&'static Unit, &'static Unit>(); - | ^^^^^^^^^^^^^ `&'static Unit` does not have a well-specified layout + | ^^^^^^^^^^^^^ `&Unit` does not have a well-specified layout | note: required by a bound in `is_maybe_transmutable` --> $DIR/references.rs:16:14 diff --git a/tests/ui/transmutability/region-infer.rs b/tests/ui/transmutability/region-infer.rs new file mode 100644 index 000000000000..09f60277688c --- /dev/null +++ b/tests/ui/transmutability/region-infer.rs @@ -0,0 +1,22 @@ +#![feature(transmutability)] + +use std::mem::{Assume, BikeshedIntrinsicFrom}; +pub struct Context; + +#[repr(C)] +struct W<'a>(&'a ()); + +fn test<'a>() +where + W<'a>: BikeshedIntrinsicFrom< + (), + Context, + { Assume { alignment: true, lifetimes: true, safety: true, validity: true } }, + >, +{ +} + +fn main() { + test(); + //~^ ERROR `()` cannot be safely transmuted into `W<'_>` +} diff --git a/tests/ui/transmutability/region-infer.stderr b/tests/ui/transmutability/region-infer.stderr new file mode 100644 index 000000000000..d6b65e9e4a08 --- /dev/null +++ b/tests/ui/transmutability/region-infer.stderr @@ -0,0 +1,23 @@ +error[E0277]: `()` cannot be safely transmuted into `W<'_>` in the defining scope of `Context` + --> $DIR/region-infer.rs:20:5 + | +LL | test(); + | ^^^^ `W<'_>` does not have a well-specified layout + | +note: required by a bound in `test` + --> $DIR/region-infer.rs:11:12 + | +LL | fn test<'a>() + | ---- required by a bound in this function +LL | where +LL | W<'a>: BikeshedIntrinsicFrom< + | ____________^ +LL | | (), +LL | | Context, +LL | | { Assume { alignment: true, lifetimes: true, safety: true, validity: true } }, +LL | | >, + | |_________^ required by this bound in `test` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. From db8dfbdb7553e499e6a1e9e72f338eb7e4c91db9 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Sun, 16 Apr 2023 23:42:59 +0100 Subject: [PATCH 113/116] Windows: map a few more error codes to ErrorKind NotFound errors: * `ERROR_INVALID_DRIVE`: The system cannot find the drive specified * `ERROR_BAD_NETPATH`: The network path was not found * `ERROR_BAD_NET_NAME`: The network name cannot be found. InvalidFilename: * `ERROR_BAD_PATHNAME`: The specified path is invalid. --- library/std/src/sys/windows/mod.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/library/std/src/sys/windows/mod.rs b/library/std/src/sys/windows/mod.rs index 77359abe4299..bcc172b0fae3 100644 --- a/library/std/src/sys/windows/mod.rs +++ b/library/std/src/sys/windows/mod.rs @@ -68,10 +68,13 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind { c::ERROR_ALREADY_EXISTS => return AlreadyExists, c::ERROR_FILE_EXISTS => return AlreadyExists, c::ERROR_BROKEN_PIPE => return BrokenPipe, - c::ERROR_FILE_NOT_FOUND => return NotFound, - c::ERROR_PATH_NOT_FOUND => return NotFound, + c::ERROR_FILE_NOT_FOUND + | c::ERROR_PATH_NOT_FOUND + | c::ERROR_INVALID_DRIVE + | c::ERROR_BAD_NETPATH + | c::ERROR_BAD_NET_NAME => return NotFound, c::ERROR_NO_DATA => return BrokenPipe, - c::ERROR_INVALID_NAME => return InvalidFilename, + c::ERROR_INVALID_NAME | c::ERROR_BAD_PATHNAME => return InvalidFilename, c::ERROR_INVALID_PARAMETER => return InvalidInput, c::ERROR_NOT_ENOUGH_MEMORY | c::ERROR_OUTOFMEMORY => return OutOfMemory, c::ERROR_SEM_TIMEOUT From bb2f23c34f805e3df0baec1ac9b9cd8669b5f4be Mon Sep 17 00:00:00 2001 From: Josh Soref <2119212+jsoref@users.noreply.github.com> Date: Sun, 9 Apr 2023 10:13:54 -0400 Subject: [PATCH 114/116] Spelling librustdoc * associated * collected * correspondence * inlining * into * javascript * multiline * variadic Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> --- src/librustdoc/clean/inline.rs | 2 +- src/librustdoc/clean/mod.rs | 2 +- src/librustdoc/clean/types.rs | 8 ++++---- src/librustdoc/config.rs | 2 +- src/librustdoc/html/highlight.rs | 10 +++++----- src/librustdoc/html/markdown.rs | 2 +- src/librustdoc/html/render/context.rs | 10 +++++----- src/librustdoc/json/conversions.rs | 4 ++-- src/librustdoc/scrape_examples.rs | 2 +- src/librustdoc/theme/tests.rs | 4 ++-- src/tools/rustdoc-gui/tester.js | 10 +++++----- 11 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index cc5d13808b2f..3f6a5d6d9017 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -528,7 +528,7 @@ pub(crate) fn build_impl( items: trait_items, polarity, kind: if utils::has_doc_flag(tcx, did, sym::fake_variadic) { - ImplKind::FakeVaradic + ImplKind::FakeVariadic } else { ImplKind::Normal }, diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 5fa0c120fba1..04379c2bca97 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2356,7 +2356,7 @@ fn clean_impl<'tcx>( items, polarity: tcx.impl_polarity(def_id), kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) { - ImplKind::FakeVaradic + ImplKind::FakeVariadic } else { ImplKind::Normal }, diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 6d2ce9e2833f..03129b972f2e 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -156,7 +156,7 @@ impl ExternalCrate { } /// Attempts to find where an external crate is located, given that we're - /// rendering in to the specified source destination. + /// rendering into the specified source destination. pub(crate) fn location( &self, extern_url: Option<&str>, @@ -751,7 +751,7 @@ pub(crate) enum ItemKind { PrimitiveItem(PrimitiveType), /// A required associated constant in a trait declaration. TyAssocConstItem(Type), - /// An associated associated constant in a trait impl or a provided one in a trait declaration. + /// An associated constant in a trait impl or a provided one in a trait declaration. AssocConstItem(Type, ConstantKind), /// A required associated type in a trait declaration. /// @@ -2305,7 +2305,7 @@ impl Impl { pub(crate) enum ImplKind { Normal, Auto, - FakeVaradic, + FakeVariadic, Blanket(Box), } @@ -2319,7 +2319,7 @@ impl ImplKind { } pub(crate) fn is_fake_variadic(&self) -> bool { - matches!(self, ImplKind::FakeVaradic) + matches!(self, ImplKind::FakeVariadic) } pub(crate) fn as_blanket_ty(&self) -> Option<&Type> { diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 1be4f364eade..b579e7f5ae9c 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -491,7 +491,7 @@ impl Options { // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset // // The original key values we have are the same as the DOM storage API keys and the - // command line options, so contain `-`. Our Javascript needs to be able to look + // command line options, so contain `-`. Our JavaScript needs to be able to look // these values up both in `dataset` and in the storage API, so it needs to be able // to convert the names back and forth. Despite doing this kebab-case to // StudlyCaps transformation automatically, the JS DOM API does not provide a diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index b61dd5714580..946c85a205f5 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -514,7 +514,7 @@ struct Classifier<'src> { impl<'src> Classifier<'src> { /// Takes as argument the source code to HTML-ify, the rust edition to use and the source code - /// file span which will be used later on by the `span_correspondance_map`. + /// file span which will be used later on by the `span_correspondence_map`. fn new(src: &str, file_span: Span, decoration_info: Option) -> Classifier<'_> { let tokens = PeekIter::new(TokenIter { src, cursor: Cursor::new(src) }); let decorations = decoration_info.map(Decorations::new); @@ -649,7 +649,7 @@ impl<'src> Classifier<'src> { /// /// `before` is the position of the given token in the `source` string and is used as "lo" byte /// in case we want to try to generate a link for this token using the - /// `span_correspondance_map`. + /// `span_correspondence_map`. fn advance( &mut self, token: TokenKind, @@ -895,7 +895,7 @@ fn exit_span(out: &mut impl Write, closing_tag: &str) { /// flexible. /// /// Note that if `context` is not `None` and that the given `klass` contains a `Span`, the function -/// will then try to find this `span` in the `span_correspondance_map`. If found, it'll then +/// will then try to find this `span` in the `span_correspondence_map`. If found, it'll then /// generate a link for this element (which corresponds to where its definition is located). fn string( out: &mut impl Write, @@ -916,7 +916,7 @@ fn string( /// * If `klass` is `Some` but `klass.get_span()` is `None`, it writes the text wrapped in a /// `` with the provided `klass`. /// * If `klass` is `Some` and has a [`rustc_span::Span`], it then tries to generate a link (`` -/// element) by retrieving the link information from the `span_correspondance_map` that was filled +/// element) by retrieving the link information from the `span_correspondence_map` that was filled /// in `span_map.rs::collect_spans_and_sources`. If it cannot retrieve the information, then it's /// the same as the second point (`klass` is `Some` but doesn't have a [`rustc_span::Span`]). fn string_without_closing_tag( @@ -963,7 +963,7 @@ fn string_without_closing_tag( if let Some(href_context) = href_context { if let Some(href) = - href_context.context.shared.span_correspondance_map.get(&def_span).and_then(|href| { + href_context.context.shared.span_correspondence_map.get(&def_span).and_then(|href| { let context = href_context.context; // FIXME: later on, it'd be nice to provide two links (if possible) for all items: // one to the documentation page and one to the source definition. diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 00aadb8e82ae..4b0aee9c3add 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -1392,7 +1392,7 @@ static DEFAULT_ID_MAP: Lazy, usize>> = Lazy::new(|| fn init_id_map() -> FxHashMap, usize> { let mut map = FxHashMap::default(); - // This is the list of IDs used in Javascript. + // This is the list of IDs used in JavaScript. map.insert("help".into(), 1); map.insert("settings".into(), 1); map.insert("not-displayed".into(), 1); diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index ac5054ce1b6b..a063c8c9f02d 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -122,9 +122,9 @@ pub(crate) struct SharedContext<'tcx> { /// the crate. redirections: Option>>, - /// Correspondance map used to link types used in the source code pages to allow to click on + /// Correspondence map used to link types used in the source code pages to allow to click on /// links to jump to the type's definition. - pub(crate) span_correspondance_map: FxHashMap, + pub(crate) span_correspondence_map: FxHashMap, /// The [`Cache`] used during rendering. pub(crate) cache: Cache, @@ -531,7 +531,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { errors: receiver, redirections: if generate_redirect_map { Some(Default::default()) } else { None }, show_type_layout, - span_correspondance_map: matches, + span_correspondence_map: matches, cache, call_locations, }; @@ -647,7 +647,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { \

\ - You need to enable Javascript be able to update your settings.\ + You need to enable JavaScript be able to update your settings.\
\ \ FormatRenderer<'tcx> for Context<'tcx> { \ ", diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index cd6509607d56..edd046ab7723 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -665,7 +665,7 @@ impl FromWithTcx for Impl { let clean::Impl { unsafety, generics, trait_, for_, items, polarity, kind } = impl_; // FIXME: use something like ImplKind in JSON? let (synthetic, blanket_impl) = match kind { - clean::ImplKind::Normal | clean::ImplKind::FakeVaradic => (false, None), + clean::ImplKind::Normal | clean::ImplKind::FakeVariadic => (false, None), clean::ImplKind::Auto => (true, None), clean::ImplKind::Blanket(ty) => (false, Some(*ty)), }; @@ -740,7 +740,7 @@ impl FromWithTcx for Variant { impl FromWithTcx for Discriminant { fn from_tcx(disr: clean::Discriminant, tcx: TyCtxt<'_>) -> Self { Discriminant { - // expr is only none if going through the inlineing path, which gets + // expr is only none if going through the inlining path, which gets // `rustc_middle` types, not `rustc_hir`, but because JSON never inlines // the expr is always some. expr: disr.expr(tcx).unwrap(), diff --git a/src/librustdoc/scrape_examples.rs b/src/librustdoc/scrape_examples.rs index f28c164d61da..dfa99ffcb7c7 100644 --- a/src/librustdoc/scrape_examples.rs +++ b/src/librustdoc/scrape_examples.rs @@ -286,7 +286,7 @@ pub(crate) fn run( let (cx, _) = Context::init(krate, renderopts, cache, tcx).map_err(|e| e.to_string())?; // Collect CrateIds corresponding to provided target crates - // If two different versions of the crate in the dependency tree, then examples will be collcted from both. + // If two different versions of the crate in the dependency tree, then examples will be collected from both. let all_crates = tcx .crates(()) .iter() diff --git a/src/librustdoc/theme/tests.rs b/src/librustdoc/theme/tests.rs index 08a174d27d35..2a28c19c3fe7 100644 --- a/src/librustdoc/theme/tests.rs +++ b/src/librustdoc/theme/tests.rs @@ -13,11 +13,11 @@ rule d // another line comment e {} -rule f/* a multine +rule f/* a multiline comment*/{} -rule g/* another multine +rule g/* another multiline comment*/h diff --git a/src/tools/rustdoc-gui/tester.js b/src/tools/rustdoc-gui/tester.js index 72baad606f01..692d5e3fcef9 100644 --- a/src/tools/rustdoc-gui/tester.js +++ b/src/tools/rustdoc-gui/tester.js @@ -42,7 +42,7 @@ function parseOptions(args) { "executable_path": null, "no_sandbox": false, }; - const correspondances = { + const correspondences = { "--doc-folder": "doc_folder", "--tests-folder": "tests_folder", "--debug": "debug", @@ -73,7 +73,7 @@ function parseOptions(args) { } opts["jobs"] = parseInt(arg_value); } else if (arg !== "--file") { - opts[correspondances[arg]] = arg_value; + opts[correspondences[arg]] = arg_value; } else { opts["files"].push(arg_value); } @@ -82,9 +82,9 @@ function parseOptions(args) { process.exit(0); } else if (arg === "--no-sandbox") { console.log("`--no-sandbox` is being used. Be very careful!"); - opts[correspondances[arg]] = true; - } else if (correspondances[arg]) { - opts[correspondances[arg]] = true; + opts[correspondences[arg]] = true; + } else if (correspondences[arg]) { + opts[correspondences[arg]] = true; } else { console.log("Unknown option `" + arg + "`."); console.log("Use `--help` to see the list of options"); From 81e7b3491dbff196ac2865957cd08f3623ca32ad Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Mon, 17 Apr 2023 09:11:05 +0000 Subject: [PATCH 115/116] Preparing for merge from rustc --- src/tools/miri/rust-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version index d394ab5a7aea..6e0092308fa3 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -71ef9ecbdedb67c32f074884f503f8e582855c2f +53ac4f8e2fc15e49ef3a04f98622a9b9db755fd4 From f540548fa11854072c449cce937bf5d1200c4bac Mon Sep 17 00:00:00 2001 From: ripytide Date: Mon, 17 Apr 2023 11:14:09 +0100 Subject: [PATCH 116/116] cmp doc examples consistency improvements --- library/core/src/cmp.rs | 91 +++++++++++++++++++++-------------------- 1 file changed, 46 insertions(+), 45 deletions(-) diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index 55331475aff2..828148c4e4db 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -324,14 +324,11 @@ pub struct AssertParamIsEq { /// ``` /// use std::cmp::Ordering; /// -/// let result = 1.cmp(&2); -/// assert_eq!(Ordering::Less, result); +/// assert_eq!(1.cmp(&2), Ordering::Less); /// -/// let result = 1.cmp(&1); -/// assert_eq!(Ordering::Equal, result); +/// assert_eq!(1.cmp(&1), Ordering::Equal); /// -/// let result = 2.cmp(&1); -/// assert_eq!(Ordering::Greater, result); +/// assert_eq!(2.cmp(&1), Ordering::Greater); /// ``` #[derive(Clone, Copy, Eq, Debug, Hash)] #[derive_const(PartialOrd, Ord, PartialEq)] @@ -790,8 +787,8 @@ pub trait Ord: Eq + PartialOrd { /// # Examples /// /// ``` - /// assert_eq!(2, 1.max(2)); - /// assert_eq!(2, 2.max(2)); + /// assert_eq!(1.max(2), 2); + /// assert_eq!(2.max(2), 2); /// ``` #[stable(feature = "ord_max_min", since = "1.21.0")] #[inline] @@ -811,8 +808,8 @@ pub trait Ord: Eq + PartialOrd { /// # Examples /// /// ``` - /// assert_eq!(1, 1.min(2)); - /// assert_eq!(2, 2.min(2)); + /// assert_eq!(1.min(2), 1); + /// assert_eq!(2.min(2), 2); /// ``` #[stable(feature = "ord_max_min", since = "1.21.0")] #[inline] @@ -837,9 +834,9 @@ pub trait Ord: Eq + PartialOrd { /// # Examples /// /// ``` - /// assert!((-3).clamp(-2, 1) == -2); - /// assert!(0.clamp(-2, 1) == 0); - /// assert!(2.clamp(-2, 1) == 1); + /// assert_eq!((-3).clamp(-2, 1), -2); + /// assert_eq!(0.clamp(-2, 1), 0); + /// assert_eq!(2.clamp(-2, 1), 1); /// ``` #[must_use] #[stable(feature = "clamp", since = "1.50.0")] @@ -1070,11 +1067,9 @@ pub trait PartialOrd: PartialEq { /// # Examples /// /// ``` - /// let result = 1.0 < 2.0; - /// assert_eq!(result, true); - /// - /// let result = 2.0 < 1.0; - /// assert_eq!(result, false); + /// assert_eq!(1.0 < 1.0, false); + /// assert_eq!(1.0 < 2.0, true); + /// assert_eq!(2.0 < 1.0, false); /// ``` #[inline] #[must_use] @@ -1089,11 +1084,9 @@ pub trait PartialOrd: PartialEq { /// # Examples /// /// ``` - /// let result = 1.0 <= 2.0; - /// assert_eq!(result, true); - /// - /// let result = 2.0 <= 2.0; - /// assert_eq!(result, true); + /// assert_eq!(1.0 <= 1.0, true); + /// assert_eq!(1.0 <= 2.0, true); + /// assert_eq!(2.0 <= 1.0, false); /// ``` #[inline] #[must_use] @@ -1107,11 +1100,9 @@ pub trait PartialOrd: PartialEq { /// # Examples /// /// ``` - /// let result = 1.0 > 2.0; - /// assert_eq!(result, false); - /// - /// let result = 2.0 > 2.0; - /// assert_eq!(result, false); + /// assert_eq!(1.0 > 1.0, false); + /// assert_eq!(1.0 > 2.0, false); + /// assert_eq!(2.0 > 1.0, true); /// ``` #[inline] #[must_use] @@ -1126,11 +1117,9 @@ pub trait PartialOrd: PartialEq { /// # Examples /// /// ``` - /// let result = 2.0 >= 1.0; - /// assert_eq!(result, true); - /// - /// let result = 2.0 >= 2.0; - /// assert_eq!(result, true); + /// assert_eq!(1.0 >= 1.0, true); + /// assert_eq!(1.0 >= 2.0, false); + /// assert_eq!(2.0 >= 1.0, true); /// ``` #[inline] #[must_use] @@ -1160,8 +1149,8 @@ pub macro PartialOrd($item:item) { /// ``` /// use std::cmp; /// -/// assert_eq!(1, cmp::min(1, 2)); -/// assert_eq!(2, cmp::min(2, 2)); +/// assert_eq!(cmp::min(1, 2), 1); +/// assert_eq!(cmp::min(2, 2), 2); /// ``` #[inline] #[must_use] @@ -1181,8 +1170,11 @@ pub const fn min(v1: T, v2: T) -> T { /// ``` /// use std::cmp; /// -/// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1); -/// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); +/// let result = cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())); +/// assert_eq!(result, 1); +/// +/// let result = cmp::min_by(-2, 3, |x: &i32, y: &i32| x.abs().cmp(&y.abs())); +/// assert_eq!(result, -2); /// ``` #[inline] #[must_use] @@ -1208,8 +1200,11 @@ where /// ``` /// use std::cmp; /// -/// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1); -/// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2); +/// let result = cmp::min_by_key(-2, 1, |x: &i32| x.abs()); +/// assert_eq!(result, 1); +/// +/// let result = cmp::min_by_key(-2, 2, |x: &i32| x.abs()); +/// assert_eq!(result, -2); /// ``` #[inline] #[must_use] @@ -1235,8 +1230,8 @@ where /// ``` /// use std::cmp; /// -/// assert_eq!(2, cmp::max(1, 2)); -/// assert_eq!(2, cmp::max(2, 2)); +/// assert_eq!(cmp::max(1, 2), 2); +/// assert_eq!(cmp::max(2, 2), 2); /// ``` #[inline] #[must_use] @@ -1256,8 +1251,11 @@ pub const fn max(v1: T, v2: T) -> T { /// ``` /// use std::cmp; /// -/// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); -/// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2); +/// let result = cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())); +/// assert_eq!(result, -2); +/// +/// let result = cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())) ; +/// assert_eq!(result, 2); /// ``` #[inline] #[must_use] @@ -1283,8 +1281,11 @@ where /// ``` /// use std::cmp; /// -/// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2); -/// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2); +/// let result = cmp::max_by_key(-2, 1, |x: &i32| x.abs()); +/// assert_eq!(result, -2); +/// +/// let result = cmp::max_by_key(-2, 2, |x: &i32| x.abs()); +/// assert_eq!(result, 2); /// ``` #[inline] #[must_use]