From 9684c38450db1c1771d1fe71ce37862ad40f1578 Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Sun, 5 Mar 2023 15:37:55 -0800 Subject: [PATCH 001/228] Add support for the x86_64h-apple-darwin target --- compiler/rustc_target/src/spec/apple_base.rs | 21 ++++++--- compiler/rustc_target/src/spec/mod.rs | 1 + .../src/spec/x86_64h_apple_darwin.rs | 44 +++++++++++++++++++ 3 files changed, 61 insertions(+), 5 deletions(-) create mode 100644 compiler/rustc_target/src/spec/x86_64h_apple_darwin.rs diff --git a/compiler/rustc_target/src/spec/apple_base.rs b/compiler/rustc_target/src/spec/apple_base.rs index 5c6dcc0aba9c3..4c7f64b20785b 100644 --- a/compiler/rustc_target/src/spec/apple_base.rs +++ b/compiler/rustc_target/src/spec/apple_base.rs @@ -19,6 +19,7 @@ pub enum Arch { I386, I686, X86_64, + X86_64h, X86_64_sim, X86_64_macabi, Arm64_macabi, @@ -36,6 +37,7 @@ impl Arch { I386 => "i386", I686 => "i686", X86_64 | X86_64_sim | X86_64_macabi => "x86_64", + X86_64h => "x86_64h", } } @@ -44,13 +46,13 @@ impl Arch { Armv7 | Armv7k | Armv7s => "arm", Arm64 | Arm64_32 | Arm64_macabi | Arm64_sim => "aarch64", I386 | I686 => "x86", - X86_64 | X86_64_sim | X86_64_macabi => "x86_64", + X86_64 | X86_64_sim | X86_64_macabi | X86_64h => "x86_64", }) } fn target_abi(self) -> &'static str { match self { - Armv7 | Armv7k | Armv7s | Arm64 | Arm64_32 | I386 | I686 | X86_64 => "", + Armv7 | Armv7k | Armv7s | Arm64 | Arm64_32 | I386 | I686 | X86_64 | X86_64h => "", X86_64_macabi | Arm64_macabi => "macabi", // x86_64-apple-ios is a simulator target, even though it isn't // declared that way in the target like the other ones... @@ -67,6 +69,10 @@ impl Arch { Arm64_32 => "apple-s4", I386 | I686 => "yonah", X86_64 | X86_64_sim => "core2", + // Note: `core-avx2` is slightly more advanced than `x86_64h`, see + // comments (and disabled features) in `x86_64h_apple_darwin` for + // details. + X86_64h => "core-avx2", X86_64_macabi => "core2", Arm64_macabi => "apple-a12", Arm64_sim => "apple-a12", @@ -182,8 +188,13 @@ fn deployment_target(var_name: &str) -> Option<(u32, u32)> { } fn macos_default_deployment_target(arch: Arch) -> (u32, u32) { - // Note: Arm64_sim is not included since macOS has no simulator. - if matches!(arch, Arm64 | Arm64_macabi) { (11, 0) } else { (10, 7) } + match arch { + // Note: Arm64_sim is not included since macOS has no simulator. + Arm64 | Arm64_macabi => (11, 0), + // x86_64h-apple-darwin only supports macOS 10.8 and later + X86_64h => (10, 8), + _ => (10, 7), + } } fn macos_deployment_target(arch: Arch) -> (u32, u32) { @@ -227,7 +238,7 @@ fn link_env_remove(arch: Arch, os: &'static str) -> StaticCow<[StaticCow]> // of the linking environment that's wrong and reversed. match arch { Armv7 | Armv7k | Armv7s | Arm64 | Arm64_32 | I386 | I686 | X86_64 | X86_64_sim - | Arm64_sim => { + | X86_64h | Arm64_sim => { cvs!["MACOSX_DEPLOYMENT_TARGET"] } X86_64_macabi | Arm64_macabi => cvs!["IPHONEOS_DEPLOYMENT_TARGET"], diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 0d86a3032a659..9747789c25435 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -1110,6 +1110,7 @@ supported_targets! { ("aarch64-apple-darwin", aarch64_apple_darwin), ("x86_64-apple-darwin", x86_64_apple_darwin), + ("x86_64h-apple-darwin", x86_64h_apple_darwin), ("i686-apple-darwin", i686_apple_darwin), // FIXME(#106649): Remove aarch64-fuchsia in favor of aarch64-unknown-fuchsia diff --git a/compiler/rustc_target/src/spec/x86_64h_apple_darwin.rs b/compiler/rustc_target/src/spec/x86_64h_apple_darwin.rs new file mode 100644 index 0000000000000..54f7490b2c052 --- /dev/null +++ b/compiler/rustc_target/src/spec/x86_64h_apple_darwin.rs @@ -0,0 +1,44 @@ +use super::apple_base::{macos_llvm_target, opts, Arch}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, SanitizerSet}; +use crate::spec::{StackProbeType, Target, TargetOptions}; + +pub fn target() -> Target { + let arch = Arch::X86_64h; + let mut base = opts("macos", arch); + base.max_atomic_width = Some(128); + base.frame_pointer = FramePointer::Always; + base.add_pre_link_args(LinkerFlavor::Darwin(Cc::Yes, Lld::No), &["-m64"]); + base.stack_probes = StackProbeType::X86; + base.supported_sanitizers = + SanitizerSet::ADDRESS | SanitizerSet::CFI | SanitizerSet::LEAK | SanitizerSet::THREAD; + + // x86_64h is core2-avx without a few of the features which would otherwise + // be guaranteed, so we need to disable those. This imitates clang's logic: + // - https://github.com/llvm/llvm-project/blob/bd1f7c417/clang/lib/Driver/ToolChains/Arch/X86.cpp#L77-L78 + // - https://github.com/llvm/llvm-project/blob/bd1f7c417/clang/lib/Driver/ToolChains/Arch/X86.cpp#L133-L141 + // + // FIXME: Sadly, turning these off here disables them in such a way that they + // aren't re-enabled by `-Ctarget-cpu=native` (on a machine that has them). + // It would be nice if this were not the case, but fixing it seems tricky + // (and given that the main use-case for this target is for use in universal + // binaries, probably not that important). + base.features = "-rdrnd,-aes,-pclmul,-rtm,-fsgsbase".into(); + // Double-check that the `cpu` is what we expect (if it's not the list above + // may need updating). + assert_eq!( + base.cpu, "core-avx2", + "you need to adjust the feature list in x86_64h-apple-darwin if you change this", + ); + + Target { + // Clang automatically chooses a more specific target based on + // MACOSX_DEPLOYMENT_TARGET. To enable cross-language LTO to work + // correctly, we do too. + llvm_target: macos_llvm_target(arch).into(), + pointer_width: 64, + data_layout: "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" + .into(), + arch: arch.target_arch(), + options: TargetOptions { mcount: "\u{1}mcount".into(), ..base }, + } +} From 1c848f22f7dd5daeec9428396121906f3a9e6a85 Mon Sep 17 00:00:00 2001 From: Thom Chiovoloni Date: Sun, 5 Mar 2023 18:03:36 -0800 Subject: [PATCH 002/228] Add platform support documentation for x86_64h-apple-darwin --- src/doc/rustc/src/SUMMARY.md | 1 + src/doc/rustc/src/platform-support.md | 1 + .../platform-support/x86_64h-apple-darwin.md | 57 +++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 src/doc/rustc/src/platform-support/x86_64h-apple-darwin.md diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index 752f1cc4aba03..64197c0e27b7e 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -40,6 +40,7 @@ - [wasm64-unknown-unknown](platform-support/wasm64-unknown-unknown.md) - [x86_64-fortanix-unknown-sgx](platform-support/x86_64-fortanix-unknown-sgx.md) - [x86_64-unknown-none](platform-support/x86_64-unknown-none.md) + - [x86_64h-apple-darwin](platform-support/x86_64h-apple-darwin.md) - [Targets](targets/index.md) - [Built-in Targets](targets/built-in.md) - [Custom Targets](targets/custom.md) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index 9eafa27e2b7c8..29df3c7f1f1a0 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -322,5 +322,6 @@ target | std | host | notes `x86_64-uwp-windows-gnu` | ✓ | | `x86_64-uwp-windows-msvc` | ✓ | | `x86_64-wrs-vxworks` | ? | | +`x86_64h-apple-darwin` | ✓ | ✓ | macOS with late-gen Intel (at least Haswell) [runs on NVIDIA GPUs]: https://github.com/japaric-archived/nvptx#targets diff --git a/src/doc/rustc/src/platform-support/x86_64h-apple-darwin.md b/src/doc/rustc/src/platform-support/x86_64h-apple-darwin.md new file mode 100644 index 0000000000000..1a6f7bb834cf5 --- /dev/null +++ b/src/doc/rustc/src/platform-support/x86_64h-apple-darwin.md @@ -0,0 +1,57 @@ +# `x86_64h-apple-darwin` + +**Tier: 3** + +Target for macOS on late-generation `x86_64` Apple chips, usable as the +`x86_64h` entry in universal binaries, and equivalent to LLVM's +`x86_64h-apple-macosx*` targets. + +## Target maintainers + +- Thom Chiovoloni `thom@shift.click` + +## Requirements + +This target is an `x86_64` target that only supports Apple's late-gen +(Haswell-compatible) Intel chips. It enables a set of target features available +on these chips (AVX2 and similar), and MachO binaries built with this target may +be used as the `x86_64h` entry in universal binaries ("fat" MachO binaries), and +will fail to load on machines that do not support this. + +It should support the full standard library (`std` and `alloc` either with +default or user-defined allocators). This target is probably most useful when +targetted via cross-compilation (including from `x86_64-apple-darwin`), but if +built manually, the host tools work. + +It is similar to `x86_64-apple-darwin` in nearly all respects, although the +minimum supported OS version is slightly higher (it requires 10.8 rather than +`x86_64-apple-darwin`'s 10.7). + +## Building the target + +Users on Apple targets can build this by adding it to the `target` list in +`config.toml`, or with `-Zbuild-std`. + +## Building Rust programs + +Rust does not yet ship pre-compiled artifacts for this target. To compile for +this target, you will either need to build Rust with the target enabled (see +"Building the target" above), or build your own copy of `core` by using +`build-std` or similar. + +## Testing + +Code built with this target can be run on the set of Intel macOS machines that +support running `x86_64h` binaries (relatively recent Intel macs). The Rust test +suite seems to work. + +## Cross-compilation toolchains and C code + +Cross-compilation to this target from Apple hosts should generally work without +much configuration, so long as XCode and the CommandLineTools are installed. +Targetting it from non-Apple hosts is difficult, but no moreso than targetting +`x86_64-apple-darwin`. + +When compiling C code for this target, either the "`x86_64h-apple-macosx*`" LLVM +targets should be used, or an argument like `-arch x86_64h` should be passed to +the C compiler. From b8c6d2211eb059c3f4ddb77d1cc0ae7278c792fc Mon Sep 17 00:00:00 2001 From: Michael van Straten Date: Fri, 10 Mar 2023 21:16:35 +0100 Subject: [PATCH 003/228] added byte position range for proc_macro::Span --- compiler/rustc_expand/src/proc_macro_server.rs | 6 +++++- library/proc_macro/src/bridge/mod.rs | 7 +++++++ library/proc_macro/src/lib.rs | 8 +++++++- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index 341ae18541b37..a4578bd583574 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -18,7 +18,7 @@ use rustc_span::def_id::CrateNum; use rustc_span::symbol::{self, sym, Symbol}; use rustc_span::{BytePos, FileName, Pos, SourceFile, Span}; use smallvec::{smallvec, SmallVec}; -use std::ops::Bound; +use std::ops::{Bound, Range}; trait FromInternal { fn from_internal(x: T) -> Self; @@ -634,6 +634,10 @@ impl server::Span for Rustc<'_, '_> { span.source_callsite() } + fn position(&mut self, span: Self::Span) -> Range { + Range { start: span.lo().0, end: span.lo().0 } + } + fn start(&mut self, span: Self::Span) -> LineColumn { let loc = self.sess().source_map().lookup_char_pos(span.lo()); LineColumn { line: loc.line, column: loc.col.to_usize() } diff --git a/library/proc_macro/src/bridge/mod.rs b/library/proc_macro/src/bridge/mod.rs index 4c1e196b5ad16..aedfecf51a506 100644 --- a/library/proc_macro/src/bridge/mod.rs +++ b/library/proc_macro/src/bridge/mod.rs @@ -14,6 +14,7 @@ use std::hash::Hash; use std::marker; use std::mem; use std::ops::Bound; +use std::ops::Range; use std::panic; use std::sync::atomic::AtomicUsize; use std::sync::Once; @@ -93,6 +94,7 @@ macro_rules! with_api { fn source_file($self: $S::Span) -> $S::SourceFile; fn parent($self: $S::Span) -> Option<$S::Span>; fn source($self: $S::Span) -> $S::Span; + fn position($self: $S::Span) -> Range; fn start($self: $S::Span) -> LineColumn; fn end($self: $S::Span) -> LineColumn; fn before($self: $S::Span) -> $S::Span; @@ -293,6 +295,7 @@ mark_noop! { &'_ str, String, u8, + u32, usize, Delimiter, LitKind, @@ -519,3 +522,7 @@ pub struct ExpnGlobals { compound_traits!( struct ExpnGlobals { def_site, call_site, mixed_site } ); + +compound_traits!( + struct Range { start, end } +); diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index 938935771d64e..e37015f2c3bc8 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -44,7 +44,7 @@ mod diagnostic; pub use diagnostic::{Diagnostic, Level, MultiSpan}; use std::cmp::Ordering; -use std::ops::RangeBounds; +use std::ops::{Range, RangeBounds}; use std::path::PathBuf; use std::str::FromStr; use std::{error, fmt, iter}; @@ -488,6 +488,12 @@ impl Span { Span(self.0.source()) } + /// Returns the spans byte position range in the source file. + #[unstable(feature = "proc_macro_span", issue = "54725")] + pub fn position(&self) -> Range { + self.0.position() + } + /// Gets the starting line/column in the source file for this span. #[unstable(feature = "proc_macro_span", issue = "54725")] pub fn start(&self) -> LineColumn { From 3dbeb695036f47bb022fdbcad9c085e841f6343d Mon Sep 17 00:00:00 2001 From: Michael van Straten Date: Fri, 10 Mar 2023 21:19:07 +0100 Subject: [PATCH 004/228] added byte position range for proc_macro::Span --- library/proc_macro/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index e37015f2c3bc8..063de6f543809 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -488,7 +488,7 @@ impl Span { Span(self.0.source()) } - /// Returns the spans byte position range in the source file. + /// Returns the span's byte position range in the source file. #[unstable(feature = "proc_macro_span", issue = "54725")] pub fn position(&self) -> Range { self.0.position() From af24c376a20d6be830216ceba1b1398797096de5 Mon Sep 17 00:00:00 2001 From: Michael van Straten Date: Fri, 10 Mar 2023 22:16:23 +0100 Subject: [PATCH 005/228] Fixed rust-analyser: no implementation for position() --- .../crates/proc-macro-srv/src/abis/abi_sysroot/ra_server.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/abis/abi_sysroot/ra_server.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/abis/abi_sysroot/ra_server.rs index d258a02472909..e46d51f7b0594 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/abis/abi_sysroot/ra_server.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/abis/abi_sysroot/ra_server.rs @@ -20,7 +20,7 @@ use token_stream::TokenStreamBuilder; mod symbol; pub use symbol::*; -use std::ops::Bound; +use std::ops::{Bound, Range}; use crate::tt; @@ -298,6 +298,10 @@ impl server::Span for RustAnalyzer { // FIXME handle span span } + fn position(&mut self, _span: Self::Span) -> Range { + // FIXME handle span + Range { start: 0, end: 0 } + } fn start(&mut self, _span: Self::Span) -> LineColumn { // FIXME handle span LineColumn { line: 0, column: 0 } From 3a3ecbfae6a0975237f203a8a5be4d485bb789e7 Mon Sep 17 00:00:00 2001 From: Michael van Straten Date: Fri, 10 Mar 2023 23:48:17 +0100 Subject: [PATCH 006/228] Fixed extra call to lo in end [skip ci] --- compiler/rustc_expand/src/proc_macro_server.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index a4578bd583574..e240b7d45514f 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -635,7 +635,7 @@ impl server::Span for Rustc<'_, '_> { } fn position(&mut self, span: Self::Span) -> Range { - Range { start: span.lo().0, end: span.lo().0 } + Range { start: span.lo().0, end: span.hi().0 } } fn start(&mut self, span: Self::Span) -> LineColumn { From c67ae04acae514ba9a3ce04fde12d1bb23cf5ca1 Mon Sep 17 00:00:00 2001 From: Michael van Straten Date: Sat, 11 Mar 2023 12:14:06 +0100 Subject: [PATCH 007/228] Renamed to byte_range and changed Range generics [skip ci] --- compiler/rustc_expand/src/proc_macro_server.rs | 4 ++-- library/proc_macro/src/bridge/mod.rs | 3 +-- library/proc_macro/src/lib.rs | 4 ++-- .../crates/proc-macro-srv/src/abis/abi_sysroot/ra_server.rs | 2 +- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index e240b7d45514f..71dfd3158dcc8 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -634,8 +634,8 @@ impl server::Span for Rustc<'_, '_> { span.source_callsite() } - fn position(&mut self, span: Self::Span) -> Range { - Range { start: span.lo().0, end: span.hi().0 } + fn byte_range(&mut self, span: Self::Span) -> Range { + Range { start: span.lo().0 as usize, end: span.hi().0 as usize } } fn start(&mut self, span: Self::Span) -> LineColumn { diff --git a/library/proc_macro/src/bridge/mod.rs b/library/proc_macro/src/bridge/mod.rs index aedfecf51a506..54b11c543f162 100644 --- a/library/proc_macro/src/bridge/mod.rs +++ b/library/proc_macro/src/bridge/mod.rs @@ -94,7 +94,7 @@ macro_rules! with_api { fn source_file($self: $S::Span) -> $S::SourceFile; fn parent($self: $S::Span) -> Option<$S::Span>; fn source($self: $S::Span) -> $S::Span; - fn position($self: $S::Span) -> Range; + fn byte_range($self: $S::Span) -> Range; fn start($self: $S::Span) -> LineColumn; fn end($self: $S::Span) -> LineColumn; fn before($self: $S::Span) -> $S::Span; @@ -295,7 +295,6 @@ mark_noop! { &'_ str, String, u8, - u32, usize, Delimiter, LitKind, diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index 063de6f543809..c6cfc9c65f7e5 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -490,8 +490,8 @@ impl Span { /// Returns the span's byte position range in the source file. #[unstable(feature = "proc_macro_span", issue = "54725")] - pub fn position(&self) -> Range { - self.0.position() + pub fn byte_range(&self) -> Range { + self.0.byte_range() } /// Gets the starting line/column in the source file for this span. diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/abis/abi_sysroot/ra_server.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/abis/abi_sysroot/ra_server.rs index e46d51f7b0594..a9cd8e705a4cf 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/abis/abi_sysroot/ra_server.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/abis/abi_sysroot/ra_server.rs @@ -298,7 +298,7 @@ impl server::Span for RustAnalyzer { // FIXME handle span span } - fn position(&mut self, _span: Self::Span) -> Range { + fn byte_range(&mut self, _span: Self::Span) -> Range { // FIXME handle span Range { start: 0, end: 0 } } From 08f204e17f1f007d844743802e04d7f62689e966 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Tue, 4 Apr 2023 14:15:29 -0700 Subject: [PATCH 008/228] rustdoc: migrate `document_type_layout` to askama --- src/librustdoc/html/render/print_item.rs | 166 +++++++----------- .../html/templates/type_layout.html | 45 +++++ 2 files changed, 112 insertions(+), 99 deletions(-) create mode 100644 src/librustdoc/html/templates/type_layout.html diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 6bce57340040b..e089b55b9c4d1 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -5,13 +5,15 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def::CtorKind; use rustc_hir::def_id::DefId; +use rustc_index::vec::IndexVec; use rustc_middle::middle::stability; use rustc_middle::span_bug; -use rustc_middle::ty::layout::LayoutError; +use rustc_middle::ty::layout::{LayoutError, TyAndLayout}; use rustc_middle::ty::{self, Adt, TyCtxt}; use rustc_span::hygiene::MacroKind; use rustc_span::symbol::{kw, sym, Symbol}; -use rustc_target::abi::{LayoutS, Primitive, TagEncoding, Variants}; +use rustc_target::abi::{LayoutS, Primitive, TagEncoding, VariantIdx, Variants}; +use std::borrow::Borrow; use std::cmp::Ordering; use std::fmt; use std::rc::Rc; @@ -1936,111 +1938,77 @@ fn document_type_layout<'a, 'cx: 'a>( cx: &'a Context<'cx>, ty_def_id: DefId, ) -> impl fmt::Display + 'a + Captures<'cx> { - fn write_size_of_layout(mut w: impl fmt::Write, layout: &LayoutS, tag_size: u64) { - if layout.abi.is_unsized() { - write!(w, "(unsized)").unwrap(); - } else { - let size = layout.size.bytes() - tag_size; - write!(w, "{size} byte{pl}", pl = if size == 1 { "" } else { "s" }).unwrap(); - if layout.abi.is_uninhabited() { - write!( - w, - " (uninhabited)" - ).unwrap(); - } - } + #[derive(Template)] + #[template(path = "type_layout.html")] + struct TypeLayout<'a, 'cx> { + cx: &'a Context<'cx>, + ty_def_id: DefId, } - display_fn(move |mut f| { - if !cx.shared.show_type_layout { - return Ok(()); + impl<'a, 'cx: 'a> TypeLayout<'a, 'cx> { + fn variants<'b: 'a>(&'b self) -> Option<&'b IndexVec> { + if let Variants::Multiple { variants, .. } = + self.type_layout().unwrap().layout.variants() && !variants.is_empty() { + Some(&variants) + } else { + None + } } - - writeln!( - f, - "

\ - Layout§

" - )?; - writeln!(f, "
")?; - - let tcx = cx.tcx(); - let param_env = tcx.param_env(ty_def_id); - let ty = tcx.type_of(ty_def_id).subst_identity(); - match tcx.layout_of(param_env.and(ty)) { - Ok(ty_layout) => { - writeln!( - f, - "

Note: Most layout information is \ - completely unstable and may even differ between compilations. \ - The only exception is types with certain repr(...) attributes. \ - Please see the Rust Reference’s \ - “Type Layout” \ - chapter for details on type layout guarantees.

" - )?; - f.write_str("

Size: ")?; - write_size_of_layout(&mut f, &ty_layout.layout.0, 0); - writeln!(f, "

")?; - if let Variants::Multiple { variants, tag, tag_encoding, .. } = - &ty_layout.layout.variants() - { - if !variants.is_empty() { - f.write_str( - "

Size for each variant:

\ -
    ", + fn type_layout<'b: 'a>(&'b self) -> Result, LayoutError<'cx>> { + let tcx = self.cx.tcx(); + let param_env = tcx.param_env(self.ty_def_id); + let ty = tcx.type_of(self.ty_def_id).subst_identity(); + tcx.layout_of(param_env.and(ty)) + } + fn variant_name<'b: 'a>(&'b self, index: VariantIdx) -> Symbol { + let Adt(adt, _) = self.type_layout().unwrap().ty.kind() else { + span_bug!(self.cx.tcx().def_span(self.ty_def_id), "not an adt") + }; + adt.variant(index).name + } + fn tag_size<'b: 'a>(&'b self) -> u64 { + if let Variants::Multiple { variants, tag, tag_encoding, .. } = + self.type_layout().unwrap().layout.variants() && !variants.is_empty() { + if let TagEncoding::Niche { .. } = tag_encoding { + 0 + } else if let Primitive::Int(i, _) = tag.primitive() { + i.size().bytes() + } else { + span_bug!(self.cx.tcx().def_span(self.ty_def_id), "tag is neither niche nor int") + } + } else { + 0 + } + } + fn write_size<'b: 'a>( + &'b self, + layout: &'b LayoutS, + tag_size: u64, + ) -> impl fmt::Display + Captures<'cx> + Captures<'b> { + display_fn(move |f| { + if layout.abi.is_unsized() { + write!(f, "(unsized)")?; + } else { + let size = layout.size.bytes() - tag_size; + write!(f, "{size} byte{pl}", pl = if size == 1 { "" } else { "s" })?; + if layout.abi.is_uninhabited() { + write!( + f, + " (uninhabited)" )?; - - let Adt(adt, _) = ty_layout.ty.kind() else { - span_bug!(tcx.def_span(ty_def_id), "not an adt") - }; - - let tag_size = if let TagEncoding::Niche { .. } = tag_encoding { - 0 - } else if let Primitive::Int(i, _) = tag.primitive() { - i.size().bytes() - } else { - span_bug!(tcx.def_span(ty_def_id), "tag is neither niche nor int") - }; - - for (index, layout) in variants.iter_enumerated() { - let name = adt.variant(index).name; - write!(&mut f, "
  • {name}: ")?; - write_size_of_layout(&mut f, layout, tag_size); - writeln!(&mut f, "
  • ")?; - } - f.write_str("
")?; } } - } - // This kind of layout error can occur with valid code, e.g. if you try to - // get the layout of a generic type such as `Vec`. - Err(LayoutError::Unknown(_)) => { - writeln!( - f, - "

Note: Unable to compute type layout, \ - possibly due to this type having generic parameters. \ - Layout can only be computed for concrete, fully-instantiated types.

" - )?; - } - // This kind of error probably can't happen with valid code, but we don't - // want to panic and prevent the docs from building, so we just let the - // user know that we couldn't compute the layout. - Err(LayoutError::SizeOverflow(_)) => { - writeln!( - f, - "

Note: Encountered an error during type layout; \ - the type was too big.

" - )?; - } - Err(LayoutError::NormalizationFailure(_, _)) => { - writeln!( - f, - "

Note: Encountered an error during type layout; \ - the type failed to be normalized.

" - )?; - } + Ok(()) + }) + } + } + + display_fn(move |f| { + if !cx.shared.show_type_layout { + return Ok(()); } - writeln!(f, "
") + Ok(TypeLayout { cx, ty_def_id }.render_into(f).unwrap()) }) } diff --git a/src/librustdoc/html/templates/type_layout.html b/src/librustdoc/html/templates/type_layout.html new file mode 100644 index 0000000000000..70149d4e1ab85 --- /dev/null +++ b/src/librustdoc/html/templates/type_layout.html @@ -0,0 +1,45 @@ +

{# #} + Layout§ {# #} +

{# #} +
{# #} + {% match self.type_layout() %} + {% when Ok(ty_layout) %} +
{# #} +

{# #} + Note: Most layout information is completely {#+ #} + unstable and may even differ between compilations. {#+ #} + The only exception is types with certain repr(...) {#+ #} + attributes. Please see the Rust Reference’s {#+ #} + “Type Layout” {#+ #} + chapter for details on type layout guarantees. {# #} +

{# #} +
{# #} +

Size: {{ self.write_size(ty_layout.layout.0.borrow(), 0) | safe }}

{# #} + {% if let Some(variants) = self.variants() %} +

Size for each variant:

{# #} +
    {# #} + {% for (index, layout) in variants.iter_enumerated() %} +
  • {# #} + {{ self.variant_name(index.clone()) }}: {#+ #} + {{ self.write_size(layout, self.tag_size()) | safe }} +
  • {# #} + {% endfor %} +
{# #} + {% endif %} + {# This kind of layout error can occur with valid code, e.g. if you try to + get the layout of a generic type such as `Vec`. #} + {% when Err(LayoutError::Unknown(_)) %} +

Note: Unable to compute type layout, {#+ #} + possibly due to this type having generic parameters. {#+ #} + Layout can only be computed for concrete, fully-instantiated types.

{# #} + {# This kind of error probably can't happen with valid code, but we don't + want to panic and prevent the docs from building, so we just let the + user know that we couldn't compute the layout. #} + {% when Err(LayoutError::SizeOverflow(_)) %} +

Note: Encountered an error during type layout; {#+ #} + the type was too big.

{# #} + {% when Err(LayoutError::NormalizationFailure(_, _)) %} +

Note: Encountered an error during type layout; {#+ #} + the type failed to be normalized.

{# #} + {% endmatch %} +
{# #} From 9aa3f053d705502e60a5167afedbbcfe1d36cded Mon Sep 17 00:00:00 2001 From: Mads Ravn Date: Sun, 9 Apr 2023 22:50:42 +0200 Subject: [PATCH 009/228] './configure' now checks if 'config.toml' exists before writing to that destination --- src/bootstrap/configure.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/bootstrap/configure.py b/src/bootstrap/configure.py index abd28b4005d0b..716077adc754f 100755 --- a/src/bootstrap/configure.py +++ b/src/bootstrap/configure.py @@ -521,6 +521,10 @@ def write_config_toml(writer, section_order, targets, sections): else: writer = write_uncommented(sections[section], writer) +def quit_if_file_exists(file): + if os.path.isfile(file): + p("Existing '" + file + "' detected. EXITING") + quit() if __name__ == "__main__": p("processing command line") @@ -528,6 +532,8 @@ def write_config_toml(writer, section_order, targets, sections): # TOML we're going to write out p("") section_order, sections, targets = parse_args(sys.argv[1:]) + # If 'config.toml' already exists, exit the script at this point + quit_if_file_exists('config.toml') # Now that we've built up our `config.toml`, write it all out in the same # order that we read it in. From c738dcc284c17addbc0a311c29b4ecaaf2fcfbaa Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 11 Apr 2023 19:18:59 +0000 Subject: [PATCH 010/228] Add `bits_for` helper for tagged pointers & fixup docs --- .../rustc_data_structures/src/tagged_ptr.rs | 55 ++++++++++++++----- compiler/rustc_middle/src/ty/list.rs | 3 +- 2 files changed, 42 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index 651bc556c9853..c96d7835b2bee 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -24,32 +24,45 @@ mod drop; pub use copy::CopyTaggedPtr; pub use drop::TaggedPtr; -/// This describes the pointer type encapsulated by TaggedPtr. +/// This describes the pointer type encapsulated by [`TaggedPtr`] and +/// [`CopyTaggedPtr`]. /// /// # Safety /// /// The usize returned from `into_usize` must be a valid, dereferenceable, -/// pointer to `::Target`. Note that pointers to `Pointee` must -/// be thin, even though `Pointee` may not be sized. +/// pointer to [`::Target`]. Note that pointers to +/// [`Self::Target`] must be thin, even though [`Self::Target`] may not be +/// `Sized`. /// /// Note that the returned pointer from `into_usize` should be castable to `&mut -/// ::Target` if `Pointer: DerefMut`. +/// ::Target` if `Self: DerefMut`. /// /// The BITS constant must be correct. At least `BITS` bits, least-significant, /// must be zero on all returned pointers from `into_usize`. /// -/// For example, if the alignment of `Pointee` is 2, then `BITS` should be 1. +/// For example, if the alignment of [`Self::Target`] is 2, then `BITS` should be 1. +/// +/// [`::Target`]: Deref::Target +/// [`Self::Target`]: Deref::Target pub unsafe trait Pointer: Deref { + /// Number of unused (always zero) **least significant bits** in this + /// pointer, usually related to the pointees alignment. + /// /// Most likely the value you want to use here is the following, unless - /// your Pointee type is unsized (e.g., `ty::List` in rustc) in which - /// case you'll need to manually figure out what the right type to pass to - /// align_of is. + /// your [`Self::Target`] type is unsized (e.g., `ty::List` in rustc) + /// or your pointer is over/under aligned, in which case you'll need to + /// manually figure out what the right type to pass to [`bits_for`] is, or + /// what the value to set here. /// - /// ```ignore UNSOLVED (what to do about the Self) + /// ```rust /// # use std::ops::Deref; - /// std::mem::align_of::<::Target>().trailing_zeros() as usize; + /// # type Self = &'static u64; + /// bits_for::() /// ``` + /// + /// [`Self::Target`]: Deref::Target const BITS: usize; + fn into_usize(self) -> usize; /// # Safety @@ -90,7 +103,7 @@ pub unsafe trait Tag: Copy { } unsafe impl Pointer for Box { - const BITS: usize = std::mem::align_of::().trailing_zeros() as usize; + const BITS: usize = bits_for::(); #[inline] fn into_usize(self) -> usize { Box::into_raw(self) as usize @@ -106,7 +119,7 @@ unsafe impl Pointer for Box { } unsafe impl Pointer for Rc { - const BITS: usize = std::mem::align_of::().trailing_zeros() as usize; + const BITS: usize = bits_for::(); #[inline] fn into_usize(self) -> usize { Rc::into_raw(self) as usize @@ -122,7 +135,7 @@ unsafe impl Pointer for Rc { } unsafe impl Pointer for Arc { - const BITS: usize = std::mem::align_of::().trailing_zeros() as usize; + const BITS: usize = bits_for::(); #[inline] fn into_usize(self) -> usize { Arc::into_raw(self) as usize @@ -138,7 +151,7 @@ unsafe impl Pointer for Arc { } unsafe impl<'a, T: 'a> Pointer for &'a T { - const BITS: usize = std::mem::align_of::().trailing_zeros() as usize; + const BITS: usize = bits_for::(); #[inline] fn into_usize(self) -> usize { self as *const T as usize @@ -153,7 +166,7 @@ unsafe impl<'a, T: 'a> Pointer for &'a T { } unsafe impl<'a, T: 'a> Pointer for &'a mut T { - const BITS: usize = std::mem::align_of::().trailing_zeros() as usize; + const BITS: usize = bits_for::(); #[inline] fn into_usize(self) -> usize { self as *mut T as usize @@ -166,3 +179,15 @@ unsafe impl<'a, T: 'a> Pointer for &'a mut T { f(&*(&ptr as *const usize as *const Self)) } } + +/// Returns the number of bits available for use for tags in a pointer to `T` +/// (this is based on `T`'s alignment). +pub const fn bits_for() -> usize { + let bits = std::mem::align_of::().trailing_zeros(); + + // This is a replacement for `.try_into().unwrap()` unavailable in `const` + // (it's fine to make an assert here, since this is only called in compile time) + assert!((bits as u128) < usize::MAX as u128); + + bits as usize +} diff --git a/compiler/rustc_middle/src/ty/list.rs b/compiler/rustc_middle/src/ty/list.rs index 79365ef281be7..4526487cf1d53 100644 --- a/compiler/rustc_middle/src/ty/list.rs +++ b/compiler/rustc_middle/src/ty/list.rs @@ -1,4 +1,5 @@ use crate::arena::Arena; +use rustc_data_structures::tagged_ptr::bits_for; use rustc_serialize::{Encodable, Encoder}; use std::alloc::Layout; use std::cmp::Ordering; @@ -199,7 +200,7 @@ impl<'a, T: Copy> IntoIterator for &'a List { unsafe impl Sync for List {} unsafe impl<'a, T: 'a> rustc_data_structures::tagged_ptr::Pointer for &'a List { - const BITS: usize = std::mem::align_of::().trailing_zeros() as usize; + const BITS: usize = bits_for::(); #[inline] fn into_usize(self) -> usize { From f028636b1aec09366973468e8c347c1cf8291561 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 11 Apr 2023 19:21:43 +0000 Subject: [PATCH 011/228] Sprinkle some whitespace & uses --- compiler/rustc_data_structures/src/tagged_ptr.rs | 16 ++++++++++++++-- .../rustc_data_structures/src/tagged_ptr/copy.rs | 15 +++++++++++---- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index c96d7835b2bee..e69a11dae0a9d 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -13,7 +13,7 @@ //! The tag must implement the `Tag` trait. We assert that the tag and `Pointer` //! are compatible at compile time. -use std::mem::ManuallyDrop; +use std::mem::{self, ManuallyDrop}; use std::ops::Deref; use std::rc::Rc; use std::sync::Arc; @@ -104,14 +104,17 @@ pub unsafe trait Tag: Copy { unsafe impl Pointer for Box { const BITS: usize = bits_for::(); + #[inline] fn into_usize(self) -> usize { Box::into_raw(self) as usize } + #[inline] unsafe fn from_usize(ptr: usize) -> Self { Box::from_raw(ptr as *mut T) } + unsafe fn with_ref R>(ptr: usize, f: F) -> R { let raw = ManuallyDrop::new(Self::from_usize(ptr)); f(&raw) @@ -120,14 +123,17 @@ unsafe impl Pointer for Box { unsafe impl Pointer for Rc { const BITS: usize = bits_for::(); + #[inline] fn into_usize(self) -> usize { Rc::into_raw(self) as usize } + #[inline] unsafe fn from_usize(ptr: usize) -> Self { Rc::from_raw(ptr as *const T) } + unsafe fn with_ref R>(ptr: usize, f: F) -> R { let raw = ManuallyDrop::new(Self::from_usize(ptr)); f(&raw) @@ -136,14 +142,17 @@ unsafe impl Pointer for Rc { unsafe impl Pointer for Arc { const BITS: usize = bits_for::(); + #[inline] fn into_usize(self) -> usize { Arc::into_raw(self) as usize } + #[inline] unsafe fn from_usize(ptr: usize) -> Self { Arc::from_raw(ptr as *const T) } + unsafe fn with_ref R>(ptr: usize, f: F) -> R { let raw = ManuallyDrop::new(Self::from_usize(ptr)); f(&raw) @@ -152,14 +161,17 @@ unsafe impl Pointer for Arc { unsafe impl<'a, T: 'a> Pointer for &'a T { const BITS: usize = bits_for::(); + #[inline] fn into_usize(self) -> usize { self as *const T as usize } + #[inline] unsafe fn from_usize(ptr: usize) -> Self { &*(ptr as *const T) } + unsafe fn with_ref R>(ptr: usize, f: F) -> R { f(&*(&ptr as *const usize as *const Self)) } @@ -183,7 +195,7 @@ unsafe impl<'a, T: 'a> Pointer for &'a mut T { /// Returns the number of bits available for use for tags in a pointer to `T` /// (this is based on `T`'s alignment). pub const fn bits_for() -> usize { - let bits = std::mem::align_of::().trailing_zeros(); + let bits = mem::align_of::().trailing_zeros(); // This is a replacement for `.try_into().unwrap()` unavailable in `const` // (it's fine to make an assert here, since this is only called in compile time) diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index e1d3e0bd35a67..d0c2b91458493 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -3,6 +3,7 @@ use crate::stable_hasher::{HashStable, StableHasher}; use std::fmt; use std::marker::PhantomData; use std::num::NonZeroUsize; +use std::ops::{Deref, DerefMut}; /// A `Copy` TaggedPtr. /// @@ -73,6 +74,7 @@ where pub(super) fn pointer_raw(&self) -> usize { self.packed.get() << T::BITS } + pub fn pointer(self) -> P where P: Copy, @@ -83,21 +85,25 @@ where // P: Copy unsafe { P::from_usize(self.pointer_raw()) } } + pub fn pointer_ref(&self) -> &P::Target { // SAFETY: pointer_raw returns the original pointer unsafe { std::mem::transmute_copy(&self.pointer_raw()) } } + pub fn pointer_mut(&mut self) -> &mut P::Target where - P: std::ops::DerefMut, + P: DerefMut, { // SAFETY: pointer_raw returns the original pointer unsafe { std::mem::transmute_copy(&self.pointer_raw()) } } + #[inline] pub fn tag(&self) -> T { unsafe { T::from_usize(self.packed.get() >> Self::TAG_BIT_SHIFT) } } + #[inline] pub fn set_tag(&mut self, tag: T) { let mut packed = self.packed.get(); @@ -109,20 +115,21 @@ where } } -impl std::ops::Deref for CopyTaggedPtr +impl Deref for CopyTaggedPtr where P: Pointer, T: Tag, { type Target = P::Target; + fn deref(&self) -> &Self::Target { self.pointer_ref() } } -impl std::ops::DerefMut for CopyTaggedPtr +impl DerefMut for CopyTaggedPtr where - P: Pointer + std::ops::DerefMut, + P: Pointer + DerefMut, T: Tag, { fn deref_mut(&mut self) -> &mut Self::Target { From 3c6f4c126027aca4153ba3a6b48c6abc164ef94d Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 11 Apr 2023 21:31:23 +0000 Subject: [PATCH 012/228] Bless tagged pointers (comply to strict provenance) --- compiler/rustc_data_structures/src/lib.rs | 1 + .../rustc_data_structures/src/tagged_ptr.rs | 90 ++++++++++--------- .../src/tagged_ptr/copy.rs | 43 +++++---- .../src/tagged_ptr/drop.rs | 2 +- compiler/rustc_middle/src/ty/list.rs | 16 ++-- 5 files changed, 85 insertions(+), 67 deletions(-) diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index e373bd18402a8..0a3f5f32d16f7 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -29,6 +29,7 @@ #![feature(get_mut_unchecked)] #![feature(lint_reasons)] #![feature(unwrap_infallible)] +#![feature(strict_provenance)] #![allow(rustc::default_hash_types)] #![allow(rustc::potential_query_instability)] #![deny(rustc::untranslatable_diagnostic)] diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index e69a11dae0a9d..8ad2b2a41fdcd 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -15,6 +15,7 @@ use std::mem::{self, ManuallyDrop}; use std::ops::Deref; +use std::ptr::NonNull; use std::rc::Rc; use std::sync::Arc; @@ -29,21 +30,24 @@ pub use drop::TaggedPtr; /// /// # Safety /// -/// The usize returned from `into_usize` must be a valid, dereferenceable, -/// pointer to [`::Target`]. Note that pointers to -/// [`Self::Target`] must be thin, even though [`Self::Target`] may not be -/// `Sized`. +/// The pointer returned from [`into_ptr`] must be a [valid], pointer to +/// [`::Target`]. Note that pointers to [`Self::Target`] must be +/// thin, even though [`Self::Target`] may not be `Sized`. /// -/// Note that the returned pointer from `into_usize` should be castable to `&mut -/// ::Target` if `Self: DerefMut`. +/// Note that if `Self` implements [`DerefMut`] the pointer returned from +/// [`into_ptr`] must be valid for writes (and thus calling [`NonNull::as_mut`] +/// on it must be safe). /// -/// The BITS constant must be correct. At least `BITS` bits, least-significant, -/// must be zero on all returned pointers from `into_usize`. +/// The `BITS` constant must be correct. At least `BITS` bits, least-significant, +/// must be zero on all pointers returned from [`into_ptr`]. /// /// For example, if the alignment of [`Self::Target`] is 2, then `BITS` should be 1. /// +/// [`into_ptr`]: Pointer::into_ptr +/// [valid]: std::ptr#safety /// [`::Target`]: Deref::Target /// [`Self::Target`]: Deref::Target +/// [`DerefMut`]: std::ops::DerefMut pub unsafe trait Pointer: Deref { /// Number of unused (always zero) **least significant bits** in this /// pointer, usually related to the pointees alignment. @@ -63,7 +67,7 @@ pub unsafe trait Pointer: Deref { /// [`Self::Target`]: Deref::Target const BITS: usize; - fn into_usize(self) -> usize; + fn into_ptr(self) -> NonNull; /// # Safety /// @@ -71,7 +75,7 @@ pub unsafe trait Pointer: Deref { /// /// This acts as `ptr::read` semantically, it should not be called more than /// once on non-`Copy` `Pointer`s. - unsafe fn from_usize(ptr: usize) -> Self; + unsafe fn from_ptr(ptr: NonNull) -> Self; /// This provides a reference to the `Pointer` itself, rather than the /// `Deref::Target`. It is used for cases where we want to call methods that @@ -81,7 +85,7 @@ pub unsafe trait Pointer: Deref { /// # Safety /// /// The passed `ptr` must be returned from `into_usize`. - unsafe fn with_ref R>(ptr: usize, f: F) -> R; + unsafe fn with_ref R>(ptr: NonNull, f: F) -> R; } /// This describes tags that the `TaggedPtr` struct can hold. @@ -106,17 +110,18 @@ unsafe impl Pointer for Box { const BITS: usize = bits_for::(); #[inline] - fn into_usize(self) -> usize { - Box::into_raw(self) as usize + fn into_ptr(self) -> NonNull { + // Safety: pointers from `Box::into_raw` are valid & non-null + unsafe { NonNull::new_unchecked(Box::into_raw(self)) } } #[inline] - unsafe fn from_usize(ptr: usize) -> Self { - Box::from_raw(ptr as *mut T) + unsafe fn from_ptr(ptr: NonNull) -> Self { + Box::from_raw(ptr.as_ptr()) } - unsafe fn with_ref R>(ptr: usize, f: F) -> R { - let raw = ManuallyDrop::new(Self::from_usize(ptr)); + unsafe fn with_ref R>(ptr: NonNull, f: F) -> R { + let raw = ManuallyDrop::new(Self::from_ptr(ptr)); f(&raw) } } @@ -125,17 +130,17 @@ unsafe impl Pointer for Rc { const BITS: usize = bits_for::(); #[inline] - fn into_usize(self) -> usize { - Rc::into_raw(self) as usize + fn into_ptr(self) -> NonNull { + unsafe { NonNull::new_unchecked(Rc::into_raw(self).cast_mut()) } } #[inline] - unsafe fn from_usize(ptr: usize) -> Self { - Rc::from_raw(ptr as *const T) + unsafe fn from_ptr(ptr: NonNull) -> Self { + Rc::from_raw(ptr.as_ptr()) } - unsafe fn with_ref R>(ptr: usize, f: F) -> R { - let raw = ManuallyDrop::new(Self::from_usize(ptr)); + unsafe fn with_ref R>(ptr: NonNull, f: F) -> R { + let raw = ManuallyDrop::new(Self::from_ptr(ptr)); f(&raw) } } @@ -144,17 +149,17 @@ unsafe impl Pointer for Arc { const BITS: usize = bits_for::(); #[inline] - fn into_usize(self) -> usize { - Arc::into_raw(self) as usize + fn into_ptr(self) -> NonNull { + unsafe { NonNull::new_unchecked(Arc::into_raw(self).cast_mut()) } } #[inline] - unsafe fn from_usize(ptr: usize) -> Self { - Arc::from_raw(ptr as *const T) + unsafe fn from_ptr(ptr: NonNull) -> Self { + Arc::from_raw(ptr.as_ptr()) } - unsafe fn with_ref R>(ptr: usize, f: F) -> R { - let raw = ManuallyDrop::new(Self::from_usize(ptr)); + unsafe fn with_ref R>(ptr: NonNull, f: F) -> R { + let raw = ManuallyDrop::new(Self::from_ptr(ptr)); f(&raw) } } @@ -163,32 +168,35 @@ unsafe impl<'a, T: 'a> Pointer for &'a T { const BITS: usize = bits_for::(); #[inline] - fn into_usize(self) -> usize { - self as *const T as usize + fn into_ptr(self) -> NonNull { + NonNull::from(self) } #[inline] - unsafe fn from_usize(ptr: usize) -> Self { - &*(ptr as *const T) + unsafe fn from_ptr(ptr: NonNull) -> Self { + ptr.as_ref() } - unsafe fn with_ref R>(ptr: usize, f: F) -> R { - f(&*(&ptr as *const usize as *const Self)) + unsafe fn with_ref R>(ptr: NonNull, f: F) -> R { + f(&ptr.as_ref()) } } unsafe impl<'a, T: 'a> Pointer for &'a mut T { const BITS: usize = bits_for::(); + #[inline] - fn into_usize(self) -> usize { - self as *mut T as usize + fn into_ptr(self) -> NonNull { + NonNull::from(self) } + #[inline] - unsafe fn from_usize(ptr: usize) -> Self { - &mut *(ptr as *mut T) + unsafe fn from_ptr(mut ptr: NonNull) -> Self { + ptr.as_mut() } - unsafe fn with_ref R>(ptr: usize, f: F) -> R { - f(&*(&ptr as *const usize as *const Self)) + + unsafe fn with_ref R>(mut ptr: NonNull, f: F) -> R { + f(&ptr.as_mut()) } } diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index d0c2b91458493..958656f9a02b8 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -4,6 +4,7 @@ use std::fmt; use std::marker::PhantomData; use std::num::NonZeroUsize; use std::ops::{Deref, DerefMut}; +use std::ptr::NonNull; /// A `Copy` TaggedPtr. /// @@ -18,7 +19,7 @@ where P: Pointer, T: Tag, { - packed: NonZeroUsize, + packed: NonNull, data: PhantomData<(P, T)>, } @@ -53,26 +54,36 @@ where const ASSERTION: () = { assert!(T::BITS <= P::BITS); // Used for the transmute_copy's below + // TODO(waffle): do we need this assert anymore? assert!(std::mem::size_of::<&P::Target>() == std::mem::size_of::()); }; pub fn new(pointer: P, tag: T) -> Self { // Trigger assert! let () = Self::ASSERTION; + let packed_tag = tag.into_usize() << Self::TAG_BIT_SHIFT; Self { - // SAFETY: We know that the pointer is non-null, as it must be - // dereferenceable per `Pointer` safety contract. - packed: unsafe { - NonZeroUsize::new_unchecked((P::into_usize(pointer) >> T::BITS) | packed_tag) - }, + packed: P::into_ptr(pointer).map_addr(|addr| { + // SAFETY: + // - The pointer is `NonNull` => it's address is `NonZeroUsize` + // - `P::BITS` least significant bits are always zero (`Pointer` contract) + // - `T::BITS <= P::BITS` (from `Self::ASSERTION`) + // + // Thus `addr >> T::BITS` is guaranteed to be non-zero. + // + // `{non_zero} | packed_tag` can't make the value zero. + + let packed = (addr.get() >> T::BITS) | packed_tag; + unsafe { NonZeroUsize::new_unchecked(packed) } + }), data: PhantomData, } } - pub(super) fn pointer_raw(&self) -> usize { - self.packed.get() << T::BITS + pub(super) fn pointer_raw(&self) -> NonNull { + self.packed.map_addr(|addr| unsafe { NonZeroUsize::new_unchecked(addr.get() << T::BITS) }) } pub fn pointer(self) -> P @@ -83,12 +94,12 @@ where // // Note that this isn't going to double-drop or anything because we have // P: Copy - unsafe { P::from_usize(self.pointer_raw()) } + unsafe { P::from_ptr(self.pointer_raw()) } } pub fn pointer_ref(&self) -> &P::Target { // SAFETY: pointer_raw returns the original pointer - unsafe { std::mem::transmute_copy(&self.pointer_raw()) } + unsafe { self.pointer_raw().as_ref() } } pub fn pointer_mut(&mut self) -> &mut P::Target @@ -96,22 +107,22 @@ where P: DerefMut, { // SAFETY: pointer_raw returns the original pointer - unsafe { std::mem::transmute_copy(&self.pointer_raw()) } + unsafe { self.pointer_raw().as_mut() } } #[inline] pub fn tag(&self) -> T { - unsafe { T::from_usize(self.packed.get() >> Self::TAG_BIT_SHIFT) } + unsafe { T::from_usize(self.packed.addr().get() >> Self::TAG_BIT_SHIFT) } } #[inline] pub fn set_tag(&mut self, tag: T) { - let mut packed = self.packed.get(); + // TODO: refactor packing into a function and reuse it here let new_tag = T::into_usize(tag) << Self::TAG_BIT_SHIFT; let tag_mask = (1 << T::BITS) - 1; - packed &= !(tag_mask << Self::TAG_BIT_SHIFT); - packed |= new_tag; - self.packed = unsafe { NonZeroUsize::new_unchecked(packed) }; + self.packed = self.packed.map_addr(|addr| unsafe { + NonZeroUsize::new_unchecked(addr.get() & !(tag_mask << Self::TAG_BIT_SHIFT) | new_tag) + }); } } diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs index b0315c93d934d..c734dadefe9be 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs @@ -76,7 +76,7 @@ where fn drop(&mut self) { // No need to drop the tag, as it's Copy unsafe { - drop(P::from_usize(self.raw.pointer_raw())); + drop(P::from_ptr(self.raw.pointer_raw())); } } } diff --git a/compiler/rustc_middle/src/ty/list.rs b/compiler/rustc_middle/src/ty/list.rs index 4526487cf1d53..01b5e82cd2266 100644 --- a/compiler/rustc_middle/src/ty/list.rs +++ b/compiler/rustc_middle/src/ty/list.rs @@ -8,7 +8,7 @@ use std::hash::{Hash, Hasher}; use std::iter; use std::mem; use std::ops::Deref; -use std::ptr; +use std::ptr::{self, NonNull}; use std::slice; /// `List` is a bit like `&[T]`, but with some critical differences. @@ -203,18 +203,16 @@ unsafe impl<'a, T: 'a> rustc_data_structures::tagged_ptr::Pointer for &'a List(); #[inline] - fn into_usize(self) -> usize { - self as *const List as usize + fn into_ptr(self) -> NonNull> { + NonNull::from(self) } #[inline] - unsafe fn from_usize(ptr: usize) -> &'a List { - &*(ptr as *const List) + unsafe fn from_ptr(ptr: NonNull>) -> &'a List { + ptr.as_ref() } - unsafe fn with_ref R>(ptr: usize, f: F) -> R { - // `Self` is `&'a List` which impls `Copy`, so this is fine. - let ptr = Self::from_usize(ptr); - f(&ptr) + unsafe fn with_ref R>(ptr: NonNull>, f: F) -> R { + f(&ptr.as_ref()) } } From 12fd610e01bbab0c58170618caf03ac7d9ddb406 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 11 Apr 2023 21:40:39 +0000 Subject: [PATCH 013/228] Refactor tagged ptr packing into a function --- .../src/tagged_ptr/copy.rs | 45 +++++++++---------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 958656f9a02b8..065aaa40759a4 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -50,6 +50,10 @@ where P: Pointer, T: Tag, { + pub fn new(pointer: P, tag: T) -> Self { + Self { packed: Self::pack(P::into_ptr(pointer), tag), data: PhantomData } + } + const TAG_BIT_SHIFT: usize = usize::BITS as usize - T::BITS; const ASSERTION: () = { assert!(T::BITS <= P::BITS); @@ -58,28 +62,28 @@ where assert!(std::mem::size_of::<&P::Target>() == std::mem::size_of::()); }; - pub fn new(pointer: P, tag: T) -> Self { + /// Pack pointer `ptr` that comes from [`P::into_ptr`] with a `tag`. + /// + /// [`P::into_ptr`]: Pointer::into_ptr + fn pack(ptr: NonNull, tag: T) -> NonNull { // Trigger assert! let () = Self::ASSERTION; let packed_tag = tag.into_usize() << Self::TAG_BIT_SHIFT; - Self { - packed: P::into_ptr(pointer).map_addr(|addr| { - // SAFETY: - // - The pointer is `NonNull` => it's address is `NonZeroUsize` - // - `P::BITS` least significant bits are always zero (`Pointer` contract) - // - `T::BITS <= P::BITS` (from `Self::ASSERTION`) - // - // Thus `addr >> T::BITS` is guaranteed to be non-zero. - // - // `{non_zero} | packed_tag` can't make the value zero. - - let packed = (addr.get() >> T::BITS) | packed_tag; - unsafe { NonZeroUsize::new_unchecked(packed) } - }), - data: PhantomData, - } + ptr.map_addr(|addr| { + // SAFETY: + // - The pointer is `NonNull` => it's address is `NonZeroUsize` + // - `P::BITS` least significant bits are always zero (`Pointer` contract) + // - `T::BITS <= P::BITS` (from `Self::ASSERTION`) + // + // Thus `addr >> T::BITS` is guaranteed to be non-zero. + // + // `{non_zero} | packed_tag` can't make the value zero. + + let packed = (addr.get() >> T::BITS) | packed_tag; + unsafe { NonZeroUsize::new_unchecked(packed) } + }) } pub(super) fn pointer_raw(&self) -> NonNull { @@ -117,12 +121,7 @@ where #[inline] pub fn set_tag(&mut self, tag: T) { - // TODO: refactor packing into a function and reuse it here - let new_tag = T::into_usize(tag) << Self::TAG_BIT_SHIFT; - let tag_mask = (1 << T::BITS) - 1; - self.packed = self.packed.map_addr(|addr| unsafe { - NonZeroUsize::new_unchecked(addr.get() & !(tag_mask << Self::TAG_BIT_SHIFT) | new_tag) - }); + self.packed = Self::pack(self.pointer_raw(), tag); } } From ad92677008c23655744c92951c322dc5e453e6f9 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 11 Apr 2023 21:45:19 +0000 Subject: [PATCH 014/228] Fix doc test --- compiler/rustc_data_structures/src/tagged_ptr.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index 8ad2b2a41fdcd..511566bb575d0 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -60,8 +60,12 @@ pub unsafe trait Pointer: Deref { /// /// ```rust /// # use std::ops::Deref; - /// # type Self = &'static u64; - /// bits_for::() + /// # use rustc_data_structures::tagged_ptr::bits_for; + /// # struct T; + /// # impl Deref for T { type Target = u8; fn deref(&self) -> &u8 { &0 } } + /// # impl T { + /// const BITS: usize = bits_for::<::Target>(); + /// # } /// ``` /// /// [`Self::Target`]: Deref::Target From 26232f1ff5a28f1dadd159a9604e668c55e40585 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 12 Apr 2023 10:21:12 +0000 Subject: [PATCH 015/228] Remove useless parameter from ghost --- compiler/rustc_data_structures/src/tagged_ptr/copy.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 065aaa40759a4..0a2d38c21f0c1 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -20,7 +20,7 @@ where T: Tag, { packed: NonNull, - data: PhantomData<(P, T)>, + tag_ghost: PhantomData, } impl Copy for CopyTaggedPtr @@ -51,7 +51,7 @@ where T: Tag, { pub fn new(pointer: P, tag: T) -> Self { - Self { packed: Self::pack(P::into_ptr(pointer), tag), data: PhantomData } + Self { packed: Self::pack(P::into_ptr(pointer), tag), tag_ghost: PhantomData } } const TAG_BIT_SHIFT: usize = usize::BITS as usize - T::BITS; From 9051331dd751042c49119701e745463921106c8b Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 12 Apr 2023 11:00:35 +0000 Subject: [PATCH 016/228] Lift `Pointer`'s requirement for the pointer to be thin fat pointers rule! --- compiler/rustc_data_structures/src/aligned.rs | 31 +++++++++++++++++++ compiler/rustc_data_structures/src/lib.rs | 1 + .../rustc_data_structures/src/tagged_ptr.rs | 21 +++++++------ .../src/tagged_ptr/copy.rs | 7 +---- compiler/rustc_middle/src/ty/list.rs | 31 +++++++++---------- 5 files changed, 58 insertions(+), 33 deletions(-) create mode 100644 compiler/rustc_data_structures/src/aligned.rs diff --git a/compiler/rustc_data_structures/src/aligned.rs b/compiler/rustc_data_structures/src/aligned.rs new file mode 100644 index 0000000000000..2d0adfe2ae35b --- /dev/null +++ b/compiler/rustc_data_structures/src/aligned.rs @@ -0,0 +1,31 @@ +use std::mem; + +/// Returns the ABI-required minimum alignment of a type in bytes. +/// +/// This is equivalent to [`mem::align_of`], but also works for some unsized +/// types (e.g. slices or rustc's `List`s). +pub const fn align_of() -> usize { + T::ALIGN +} + +/// A type with a statically known alignment. +/// +/// # Safety +/// +/// `Self::ALIGN` must be equal to the alignment of `Self`. For sized types it +/// is [`mem::align_of()`], for unsized types it depends on the type, for +/// example `[T]` has alignment of `T`. +/// +/// [`mem::align_of()`]: mem::align_of +pub unsafe trait Aligned { + /// Alignment of `Self`. + const ALIGN: usize; +} + +unsafe impl Aligned for T { + const ALIGN: usize = mem::align_of::(); +} + +unsafe impl Aligned for [T] { + const ALIGN: usize = mem::align_of::(); +} diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index 0a3f5f32d16f7..ea1f71d7115ca 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -83,6 +83,7 @@ pub mod transitive_relation; pub mod vec_linked_list; pub mod work_queue; pub use atomic_ref::AtomicRef; +pub mod aligned; pub mod frozen; pub mod owned_slice; pub mod sso; diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index 511566bb575d0..f45f5a4215645 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -13,12 +13,14 @@ //! The tag must implement the `Tag` trait. We assert that the tag and `Pointer` //! are compatible at compile time. -use std::mem::{self, ManuallyDrop}; +use std::mem::ManuallyDrop; use std::ops::Deref; use std::ptr::NonNull; use std::rc::Rc; use std::sync::Arc; +use crate::aligned::Aligned; + mod copy; mod drop; @@ -31,8 +33,7 @@ pub use drop::TaggedPtr; /// # Safety /// /// The pointer returned from [`into_ptr`] must be a [valid], pointer to -/// [`::Target`]. Note that pointers to [`Self::Target`] must be -/// thin, even though [`Self::Target`] may not be `Sized`. +/// [`::Target`]. /// /// Note that if `Self` implements [`DerefMut`] the pointer returned from /// [`into_ptr`] must be valid for writes (and thus calling [`NonNull::as_mut`] @@ -110,7 +111,7 @@ pub unsafe trait Tag: Copy { unsafe fn from_usize(tag: usize) -> Self; } -unsafe impl Pointer for Box { +unsafe impl Pointer for Box { const BITS: usize = bits_for::(); #[inline] @@ -130,7 +131,7 @@ unsafe impl Pointer for Box { } } -unsafe impl Pointer for Rc { +unsafe impl Pointer for Rc { const BITS: usize = bits_for::(); #[inline] @@ -149,7 +150,7 @@ unsafe impl Pointer for Rc { } } -unsafe impl Pointer for Arc { +unsafe impl Pointer for Arc { const BITS: usize = bits_for::(); #[inline] @@ -168,7 +169,7 @@ unsafe impl Pointer for Arc { } } -unsafe impl<'a, T: 'a> Pointer for &'a T { +unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a T { const BITS: usize = bits_for::(); #[inline] @@ -186,7 +187,7 @@ unsafe impl<'a, T: 'a> Pointer for &'a T { } } -unsafe impl<'a, T: 'a> Pointer for &'a mut T { +unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a mut T { const BITS: usize = bits_for::(); #[inline] @@ -206,8 +207,8 @@ unsafe impl<'a, T: 'a> Pointer for &'a mut T { /// Returns the number of bits available for use for tags in a pointer to `T` /// (this is based on `T`'s alignment). -pub const fn bits_for() -> usize { - let bits = mem::align_of::().trailing_zeros(); +pub const fn bits_for() -> usize { + let bits = crate::aligned::align_of::().trailing_zeros(); // This is a replacement for `.try_into().unwrap()` unavailable in `const` // (it's fine to make an assert here, since this is only called in compile time) diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 0a2d38c21f0c1..09d55b20ab4de 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -55,12 +55,7 @@ where } const TAG_BIT_SHIFT: usize = usize::BITS as usize - T::BITS; - const ASSERTION: () = { - assert!(T::BITS <= P::BITS); - // Used for the transmute_copy's below - // TODO(waffle): do we need this assert anymore? - assert!(std::mem::size_of::<&P::Target>() == std::mem::size_of::()); - }; + const ASSERTION: () = { assert!(T::BITS <= P::BITS) }; /// Pack pointer `ptr` that comes from [`P::into_ptr`] with a `tag`. /// diff --git a/compiler/rustc_middle/src/ty/list.rs b/compiler/rustc_middle/src/ty/list.rs index 01b5e82cd2266..590beef7f7d42 100644 --- a/compiler/rustc_middle/src/ty/list.rs +++ b/compiler/rustc_middle/src/ty/list.rs @@ -1,5 +1,5 @@ use crate::arena::Arena; -use rustc_data_structures::tagged_ptr::bits_for; +use rustc_data_structures::aligned::Aligned; use rustc_serialize::{Encodable, Encoder}; use std::alloc::Layout; use std::cmp::Ordering; @@ -8,7 +8,7 @@ use std::hash::{Hash, Hasher}; use std::iter; use std::mem; use std::ops::Deref; -use std::ptr::{self, NonNull}; +use std::ptr; use std::slice; /// `List` is a bit like `&[T]`, but with some critical differences. @@ -199,20 +199,17 @@ impl<'a, T: Copy> IntoIterator for &'a List { unsafe impl Sync for List {} -unsafe impl<'a, T: 'a> rustc_data_structures::tagged_ptr::Pointer for &'a List { - const BITS: usize = bits_for::(); - - #[inline] - fn into_ptr(self) -> NonNull> { - NonNull::from(self) - } - - #[inline] - unsafe fn from_ptr(ptr: NonNull>) -> &'a List { - ptr.as_ref() - } +// Safety: +// Layouts of `Equivalent` and `List` are the same, modulo opaque tail, +// thus aligns of `Equivalent` and `List` must be the same. +unsafe impl Aligned for List { + const ALIGN: usize = { + #[repr(C)] + struct Equivalent { + _len: usize, + _data: [T; 0], + } - unsafe fn with_ref R>(ptr: NonNull>, f: F) -> R { - f(&ptr.as_ref()) - } + mem::align_of::>() + }; } From c6acd5c92fc9c193eb5ac71c24c6214d6105597b Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 12 Apr 2023 11:15:10 +0000 Subject: [PATCH 017/228] Remove `Pointer::with_ref` in favour implementing it on tagged pointers directly --- .../rustc_data_structures/src/tagged_ptr.rs | 34 ------------------- .../src/tagged_ptr/copy.rs | 23 +++++++++++-- .../src/tagged_ptr/drop.rs | 8 +++-- 3 files changed, 25 insertions(+), 40 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index f45f5a4215645..9a3d76fd4d4da 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -13,7 +13,6 @@ //! The tag must implement the `Tag` trait. We assert that the tag and `Pointer` //! are compatible at compile time. -use std::mem::ManuallyDrop; use std::ops::Deref; use std::ptr::NonNull; use std::rc::Rc; @@ -81,16 +80,6 @@ pub unsafe trait Pointer: Deref { /// This acts as `ptr::read` semantically, it should not be called more than /// once on non-`Copy` `Pointer`s. unsafe fn from_ptr(ptr: NonNull) -> Self; - - /// This provides a reference to the `Pointer` itself, rather than the - /// `Deref::Target`. It is used for cases where we want to call methods that - /// may be implement differently for the Pointer than the Pointee (e.g., - /// `Rc::clone` vs cloning the inner value). - /// - /// # Safety - /// - /// The passed `ptr` must be returned from `into_usize`. - unsafe fn with_ref R>(ptr: NonNull, f: F) -> R; } /// This describes tags that the `TaggedPtr` struct can hold. @@ -124,11 +113,6 @@ unsafe impl Pointer for Box { unsafe fn from_ptr(ptr: NonNull) -> Self { Box::from_raw(ptr.as_ptr()) } - - unsafe fn with_ref R>(ptr: NonNull, f: F) -> R { - let raw = ManuallyDrop::new(Self::from_ptr(ptr)); - f(&raw) - } } unsafe impl Pointer for Rc { @@ -143,11 +127,6 @@ unsafe impl Pointer for Rc { unsafe fn from_ptr(ptr: NonNull) -> Self { Rc::from_raw(ptr.as_ptr()) } - - unsafe fn with_ref R>(ptr: NonNull, f: F) -> R { - let raw = ManuallyDrop::new(Self::from_ptr(ptr)); - f(&raw) - } } unsafe impl Pointer for Arc { @@ -162,11 +141,6 @@ unsafe impl Pointer for Arc { unsafe fn from_ptr(ptr: NonNull) -> Self { Arc::from_raw(ptr.as_ptr()) } - - unsafe fn with_ref R>(ptr: NonNull, f: F) -> R { - let raw = ManuallyDrop::new(Self::from_ptr(ptr)); - f(&raw) - } } unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a T { @@ -181,10 +155,6 @@ unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a T { unsafe fn from_ptr(ptr: NonNull) -> Self { ptr.as_ref() } - - unsafe fn with_ref R>(ptr: NonNull, f: F) -> R { - f(&ptr.as_ref()) - } } unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a mut T { @@ -199,10 +169,6 @@ unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a mut T { unsafe fn from_ptr(mut ptr: NonNull) -> Self { ptr.as_mut() } - - unsafe fn with_ref R>(mut ptr: NonNull, f: F) -> R { - f(&ptr.as_mut()) - } } /// Returns the number of bits available for use for tags in a pointer to `T` diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 09d55b20ab4de..2900b883264af 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -2,6 +2,7 @@ use super::{Pointer, Tag}; use crate::stable_hasher::{HashStable, StableHasher}; use std::fmt; use std::marker::PhantomData; +use std::mem::ManuallyDrop; use std::num::NonZeroUsize; use std::ops::{Deref, DerefMut}; use std::ptr::NonNull; @@ -85,6 +86,24 @@ where self.packed.map_addr(|addr| unsafe { NonZeroUsize::new_unchecked(addr.get() << T::BITS) }) } + /// This provides a reference to the `P` pointer itself, rather than the + /// `Deref::Target`. It is used for cases where we want to call methods + /// that may be implement differently for the Pointer than the Pointee + /// (e.g., `Rc::clone` vs cloning the inner value). + pub(super) fn with_pointer_ref(&self, f: impl FnOnce(&P) -> R) -> R { + // Safety: + // - `self.raw.pointer_raw()` is originally returned from `P::into_ptr` + // and as such is valid for `P::from_ptr`. + // - This also allows us to not care whatever `f` panics or not. + // - Even though we create a copy of the pointer, we store it inside + // `ManuallyDrop` and only access it by-ref, so we don't double-drop. + // + // Semantically this is just `f(&self.pointer)` (where `self.pointer` + // is non-packed original pointer). + let ptr = unsafe { ManuallyDrop::new(P::from_ptr(self.pointer_raw())) }; + f(&ptr) + } + pub fn pointer(self) -> P where P: Copy, @@ -189,9 +208,7 @@ where T: Tag + HashStable, { fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) { - unsafe { - Pointer::with_ref(self.pointer_raw(), |p: &P| p.hash_stable(hcx, hasher)); - } + self.with_pointer_ref(|ptr| ptr.hash_stable(hcx, hasher)); self.tag().hash_stable(hcx, hasher); } } diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs index c734dadefe9be..a2b119e15b8a5 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs @@ -1,8 +1,8 @@ -use super::{Pointer, Tag}; -use crate::stable_hasher::{HashStable, StableHasher}; use std::fmt; use super::CopyTaggedPtr; +use super::{Pointer, Tag}; +use crate::stable_hasher::{HashStable, StableHasher}; /// A TaggedPtr implementing `Drop`. /// @@ -23,7 +23,9 @@ where T: Tag, { fn clone(&self) -> Self { - unsafe { Self::new(P::with_ref(self.raw.pointer_raw(), |p| p.clone()), self.raw.tag()) } + let ptr = self.raw.with_pointer_ref(P::clone); + + Self::new(ptr, self.tag()) } } From c7c0b85f676eff0811a15a99acb01bc98cb2c4d4 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 12 Apr 2023 11:30:45 +0000 Subject: [PATCH 018/228] Make tagged pointers debug impls print the pointer Does not really matter, but may be nicer in case the pointer has some specific debug impl. --- compiler/rustc_data_structures/src/tagged_ptr/copy.rs | 10 ++++------ compiler/rustc_data_structures/src/tagged_ptr/drop.rs | 10 ++++------ 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 2900b883264af..235c92da69958 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -163,15 +163,13 @@ where impl fmt::Debug for CopyTaggedPtr where - P: Pointer, - P::Target: fmt::Debug, + P: Pointer + fmt::Debug, T: Tag + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("CopyTaggedPtr") - .field("pointer", &self.pointer_ref()) - .field("tag", &self.tag()) - .finish() + self.with_pointer_ref(|ptr| { + f.debug_struct("CopyTaggedPtr").field("pointer", ptr).field("tag", &self.tag()).finish() + }) } } diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs index a2b119e15b8a5..d3fba0c30a9d0 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs @@ -85,15 +85,13 @@ where impl fmt::Debug for TaggedPtr where - P: Pointer, - P::Target: fmt::Debug, + P: Pointer + fmt::Debug, T: Tag + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("TaggedPtr") - .field("pointer", &self.pointer_ref()) - .field("tag", &self.tag()) - .finish() + self.raw.with_pointer_ref(|ptr| { + f.debug_struct("TaggedPtr").field("pointer", ptr).field("tag", &self.tag()).finish() + }) } } From 8f408202c3a99fb8d4798996287211240dab39f4 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 12 Apr 2023 11:41:41 +0000 Subject: [PATCH 019/228] Remove `pointer_{ref,mut}` from tagged pointers Just use `deref{,_mut}`! --- .../src/tagged_ptr/copy.rs | 24 +++++++------------ .../src/tagged_ptr/drop.rs | 7 ++---- 2 files changed, 11 insertions(+), 20 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 235c92da69958..644f1415e732e 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -115,19 +115,6 @@ where unsafe { P::from_ptr(self.pointer_raw()) } } - pub fn pointer_ref(&self) -> &P::Target { - // SAFETY: pointer_raw returns the original pointer - unsafe { self.pointer_raw().as_ref() } - } - - pub fn pointer_mut(&mut self) -> &mut P::Target - where - P: DerefMut, - { - // SAFETY: pointer_raw returns the original pointer - unsafe { self.pointer_raw().as_mut() } - } - #[inline] pub fn tag(&self) -> T { unsafe { T::from_usize(self.packed.addr().get() >> Self::TAG_BIT_SHIFT) } @@ -147,7 +134,10 @@ where type Target = P::Target; fn deref(&self) -> &Self::Target { - self.pointer_ref() + // Safety: + // `pointer_raw` returns the original pointer from `P::into_ptr` which, + // by the `Pointer`'s contract, must be valid. + unsafe { self.pointer_raw().as_ref() } } } @@ -157,7 +147,11 @@ where T: Tag, { fn deref_mut(&mut self) -> &mut Self::Target { - self.pointer_mut() + // Safety: + // `pointer_raw` returns the original pointer from `P::into_ptr` which, + // by the `Pointer`'s contract, must be valid for writes if + // `P: DerefMut`. + unsafe { self.pointer_raw().as_mut() } } } diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs index d3fba0c30a9d0..6e51916838fd9 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs @@ -41,9 +41,6 @@ where TaggedPtr { raw: CopyTaggedPtr::new(pointer, tag) } } - pub fn pointer_ref(&self) -> &P::Target { - self.raw.pointer_ref() - } pub fn tag(&self) -> T { self.raw.tag() } @@ -56,7 +53,7 @@ where { type Target = P::Target; fn deref(&self) -> &Self::Target { - self.raw.pointer_ref() + self.raw.deref() } } @@ -66,7 +63,7 @@ where T: Tag, { fn deref_mut(&mut self) -> &mut Self::Target { - self.raw.pointer_mut() + self.raw.deref_mut() } } From 3df9a7bde32e7ae9fab45024fd38db827531c48d Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 12 Apr 2023 11:44:52 +0000 Subject: [PATCH 020/228] Shorten `COMPARE_PACKED` => `CP` where it is not important why can't I _ it :'( --- .../rustc_data_structures/src/tagged_ptr/copy.rs | 14 +++++++------- .../rustc_data_structures/src/tagged_ptr/drop.rs | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 644f1415e732e..edf429abfe991 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -24,7 +24,7 @@ where tag_ghost: PhantomData, } -impl Copy for CopyTaggedPtr +impl Copy for CopyTaggedPtr where P: Pointer, T: Tag, @@ -32,7 +32,7 @@ where { } -impl Clone for CopyTaggedPtr +impl Clone for CopyTaggedPtr where P: Pointer, T: Tag, @@ -46,7 +46,7 @@ where // We pack the tag into the *upper* bits of the pointer to ease retrieval of the // value; a left shift is a multiplication and those are embeddable in // instruction encoding. -impl CopyTaggedPtr +impl CopyTaggedPtr where P: Pointer, T: Tag, @@ -126,7 +126,7 @@ where } } -impl Deref for CopyTaggedPtr +impl Deref for CopyTaggedPtr where P: Pointer, T: Tag, @@ -141,7 +141,7 @@ where } } -impl DerefMut for CopyTaggedPtr +impl DerefMut for CopyTaggedPtr where P: Pointer + DerefMut, T: Tag, @@ -155,7 +155,7 @@ where } } -impl fmt::Debug for CopyTaggedPtr +impl fmt::Debug for CopyTaggedPtr where P: Pointer + fmt::Debug, T: Tag + fmt::Debug, @@ -194,7 +194,7 @@ where } } -impl HashStable for CopyTaggedPtr +impl HashStable for CopyTaggedPtr where P: Pointer + HashStable, T: Tag + HashStable, diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs index 6e51916838fd9..a722a0f1f3215 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs @@ -17,7 +17,7 @@ where raw: CopyTaggedPtr, } -impl Clone for TaggedPtr +impl Clone for TaggedPtr where P: Pointer + Clone, T: Tag, @@ -32,7 +32,7 @@ where // We pack the tag into the *upper* bits of the pointer to ease retrieval of the // value; a right shift is a multiplication and those are embeddable in // instruction encoding. -impl TaggedPtr +impl TaggedPtr where P: Pointer, T: Tag, @@ -46,7 +46,7 @@ where } } -impl std::ops::Deref for TaggedPtr +impl std::ops::Deref for TaggedPtr where P: Pointer, T: Tag, @@ -57,7 +57,7 @@ where } } -impl std::ops::DerefMut for TaggedPtr +impl std::ops::DerefMut for TaggedPtr where P: Pointer + std::ops::DerefMut, T: Tag, @@ -67,7 +67,7 @@ where } } -impl Drop for TaggedPtr +impl Drop for TaggedPtr where P: Pointer, T: Tag, @@ -80,7 +80,7 @@ where } } -impl fmt::Debug for TaggedPtr +impl fmt::Debug for TaggedPtr where P: Pointer + fmt::Debug, T: Tag + fmt::Debug, @@ -119,7 +119,7 @@ where } } -impl HashStable for TaggedPtr +impl HashStable for TaggedPtr where P: Pointer + HashStable, T: Tag + HashStable, From 6f64ae3fbcf7a353537d250f91981ac336e12880 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 12 Apr 2023 11:50:45 +0000 Subject: [PATCH 021/228] Move code around --- .../src/tagged_ptr/copy.rs | 77 +++++++++---------- .../src/tagged_ptr/drop.rs | 36 +++++---- 2 files changed, 57 insertions(+), 56 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index edf429abfe991..90500b2de89d1 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -1,6 +1,7 @@ use super::{Pointer, Tag}; use crate::stable_hasher::{HashStable, StableHasher}; use std::fmt; +use std::hash::{Hash, Hasher}; use std::marker::PhantomData; use std::mem::ManuallyDrop; use std::num::NonZeroUsize; @@ -24,25 +25,6 @@ where tag_ghost: PhantomData, } -impl Copy for CopyTaggedPtr -where - P: Pointer, - T: Tag, - P: Copy, -{ -} - -impl Clone for CopyTaggedPtr -where - P: Pointer, - T: Tag, - P: Copy, -{ - fn clone(&self) -> Self { - *self - } -} - // We pack the tag into the *upper* bits of the pointer to ease retrieval of the // value; a left shift is a multiplication and those are embeddable in // instruction encoding. @@ -55,6 +37,27 @@ where Self { packed: Self::pack(P::into_ptr(pointer), tag), tag_ghost: PhantomData } } + pub fn pointer(self) -> P + where + P: Copy, + { + // SAFETY: pointer_raw returns the original pointer + // + // Note that this isn't going to double-drop or anything because we have + // P: Copy + unsafe { P::from_ptr(self.pointer_raw()) } + } + + #[inline] + pub fn tag(&self) -> T { + unsafe { T::from_usize(self.packed.addr().get() >> Self::TAG_BIT_SHIFT) } + } + + #[inline] + pub fn set_tag(&mut self, tag: T) { + self.packed = Self::pack(self.pointer_raw(), tag); + } + const TAG_BIT_SHIFT: usize = usize::BITS as usize - T::BITS; const ASSERTION: () = { assert!(T::BITS <= P::BITS) }; @@ -103,26 +106,22 @@ where let ptr = unsafe { ManuallyDrop::new(P::from_ptr(self.pointer_raw())) }; f(&ptr) } +} - pub fn pointer(self) -> P - where - P: Copy, - { - // SAFETY: pointer_raw returns the original pointer - // - // Note that this isn't going to double-drop or anything because we have - // P: Copy - unsafe { P::from_ptr(self.pointer_raw()) } - } - - #[inline] - pub fn tag(&self) -> T { - unsafe { T::from_usize(self.packed.addr().get() >> Self::TAG_BIT_SHIFT) } - } +impl Copy for CopyTaggedPtr +where + P: Pointer + Copy, + T: Tag, +{ +} - #[inline] - pub fn set_tag(&mut self, tag: T) { - self.packed = Self::pack(self.pointer_raw(), tag); +impl Clone for CopyTaggedPtr +where + P: Pointer + Copy, + T: Tag, +{ + fn clone(&self) -> Self { + *self } } @@ -184,12 +183,12 @@ where { } -impl std::hash::Hash for CopyTaggedPtr +impl Hash for CopyTaggedPtr where P: Pointer, T: Tag, { - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.packed.hash(state); } } diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs index a722a0f1f3215..60f3e1d24610c 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs @@ -1,4 +1,6 @@ use std::fmt; +use std::hash::{Hash, Hasher}; +use std::ops::{Deref, DerefMut}; use super::CopyTaggedPtr; use super::{Pointer, Tag}; @@ -17,18 +19,6 @@ where raw: CopyTaggedPtr, } -impl Clone for TaggedPtr -where - P: Pointer + Clone, - T: Tag, -{ - fn clone(&self) -> Self { - let ptr = self.raw.with_pointer_ref(P::clone); - - Self::new(ptr, self.tag()) - } -} - // We pack the tag into the *upper* bits of the pointer to ease retrieval of the // value; a right shift is a multiplication and those are embeddable in // instruction encoding. @@ -46,7 +36,19 @@ where } } -impl std::ops::Deref for TaggedPtr +impl Clone for TaggedPtr +where + P: Pointer + Clone, + T: Tag, +{ + fn clone(&self) -> Self { + let ptr = self.raw.with_pointer_ref(P::clone); + + Self::new(ptr, self.tag()) + } +} + +impl Deref for TaggedPtr where P: Pointer, T: Tag, @@ -57,9 +59,9 @@ where } } -impl std::ops::DerefMut for TaggedPtr +impl DerefMut for TaggedPtr where - P: Pointer + std::ops::DerefMut, + P: Pointer + DerefMut, T: Tag, { fn deref_mut(&mut self) -> &mut Self::Target { @@ -109,12 +111,12 @@ where { } -impl std::hash::Hash for TaggedPtr +impl Hash for TaggedPtr where P: Pointer, T: Tag, { - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.raw.hash(state); } } From 5e4577ec65a3dc327feee9618fa91a44797771d4 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 12 Apr 2023 12:35:43 +0000 Subject: [PATCH 022/228] Add `TaggedPtr::set_tag` --- compiler/rustc_data_structures/src/tagged_ptr/drop.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs index 60f3e1d24610c..de253a0b2552a 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs @@ -34,6 +34,10 @@ where pub fn tag(&self) -> T { self.raw.tag() } + + pub fn set_tag(&mut self, tag: T) { + self.raw.set_tag(tag) + } } impl Clone for TaggedPtr From 20a7b022896cf87766c258363350b544d4cc3323 Mon Sep 17 00:00:00 2001 From: beetrees Date: Wed, 12 Apr 2023 01:33:29 +0100 Subject: [PATCH 023/228] Add `indent_style = tab` for `Makefile`s to `.editorconfig` --- .editorconfig | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.editorconfig b/.editorconfig index 03aab32bfc6e1..d065fa46469fc 100644 --- a/.editorconfig +++ b/.editorconfig @@ -20,3 +20,6 @@ trim_trailing_whitespace = false [*.yml] indent_size = 2 + +[Makefile] +indent_style = tab From 6f9b15c40c909e80acc27aca3118654cb506241e Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 12 Apr 2023 12:46:19 +0000 Subject: [PATCH 024/228] Add tests for tagged pointers --- .../src/tagged_ptr/copy.rs | 30 ++++++ .../src/tagged_ptr/copy/tests.rs | 61 +++++++++++ .../src/tagged_ptr/drop.rs | 30 ++++++ .../src/tagged_ptr/drop/tests.rs | 101 ++++++++++++++++++ 4 files changed, 222 insertions(+) create mode 100644 compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs create mode 100644 compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 90500b2de89d1..aebf24ebbdeb7 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -203,3 +203,33 @@ where self.tag().hash_stable(hcx, hasher); } } + +/// Test that `new` does not compile if there is not enough alignment for the +/// tag in the pointer. +/// +/// ```compile_fail,E0080 +/// use rustc_data_structures::tagged_ptr::{CopyTaggedPtr, Tag}; +/// +/// #[derive(Copy, Clone, Debug, PartialEq, Eq)] +/// enum Tag2 { B00 = 0b00, B01 = 0b01, B10 = 0b10, B11 = 0b11 }; +/// +/// unsafe impl Tag for Tag2 { +/// const BITS: usize = 2; +/// +/// fn into_usize(self) -> usize { todo!() } +/// unsafe fn from_usize(tag: usize) -> Self { todo!() } +/// } +/// +/// let value = 12u16; +/// let reference = &value; +/// let tag = Tag2::B01; +/// +/// let _ptr = CopyTaggedPtr::<_, _, true>::new(reference, tag); +/// ``` +// For some reason miri does not get the compile error +// probably it `check`s instead of `build`ing? +#[cfg(not(miri))] +const _: () = (); + +#[cfg(test)] +mod tests; diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs new file mode 100644 index 0000000000000..77544f9c0324d --- /dev/null +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs @@ -0,0 +1,61 @@ +use std::ptr; + +use crate::tagged_ptr::{CopyTaggedPtr, Pointer, Tag}; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum Tag2 { + B00 = 0b00, + B01 = 0b01, + B10 = 0b10, + B11 = 0b11, +} + +unsafe impl Tag for Tag2 { + const BITS: usize = 2; + + fn into_usize(self) -> usize { + self as _ + } + + unsafe fn from_usize(tag: usize) -> Self { + const B00: usize = Tag2::B00 as _; + const B01: usize = Tag2::B01 as _; + const B10: usize = Tag2::B10 as _; + const B11: usize = Tag2::B11 as _; + match tag { + B00 => Tag2::B00, + B01 => Tag2::B01, + B10 => Tag2::B10, + B11 => Tag2::B11, + _ => unreachable!(), + } + } +} + +#[test] +fn smoke() { + let value = 12u32; + let reference = &value; + let tag = Tag2::B01; + + let ptr = tag_ptr(reference, tag); + + assert_eq!(ptr.tag(), tag); + assert_eq!(*ptr, 12); + assert!(ptr::eq(ptr.pointer(), reference)); + + let copy = ptr; + + let mut ptr = ptr; + ptr.set_tag(Tag2::B00); + assert_eq!(ptr.tag(), Tag2::B00); + + assert_eq!(copy.tag(), tag); + assert_eq!(*copy, 12); + assert!(ptr::eq(copy.pointer(), reference)); +} + +/// Helper to create tagged pointers without specifying `COMPARE_PACKED` if it does not matter. +fn tag_ptr(ptr: P, tag: T) -> CopyTaggedPtr { + CopyTaggedPtr::new(ptr, tag) +} diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs index de253a0b2552a..286951ce0e9c1 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs @@ -134,3 +134,33 @@ where self.raw.hash_stable(hcx, hasher); } } + +/// Test that `new` does not compile if there is not enough alignment for the +/// tag in the pointer. +/// +/// ```compile_fail,E0080 +/// use rustc_data_structures::tagged_ptr::{TaggedPtr, Tag}; +/// +/// #[derive(Copy, Clone, Debug, PartialEq, Eq)] +/// enum Tag2 { B00 = 0b00, B01 = 0b01, B10 = 0b10, B11 = 0b11 }; +/// +/// unsafe impl Tag for Tag2 { +/// const BITS: usize = 2; +/// +/// fn into_usize(self) -> usize { todo!() } +/// unsafe fn from_usize(tag: usize) -> Self { todo!() } +/// } +/// +/// let value = 12u16; +/// let reference = &value; +/// let tag = Tag2::B01; +/// +/// let _ptr = TaggedPtr::<_, _, true>::new(reference, tag); +/// ``` +// For some reason miri does not get the compile error +// probably it `check`s instead of `build`ing? +#[cfg(not(miri))] +const _: () = (); + +#[cfg(test)] +mod tests; diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs new file mode 100644 index 0000000000000..0c61cebaf7e6a --- /dev/null +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs @@ -0,0 +1,101 @@ +use std::{ptr, sync::Arc}; + +use crate::tagged_ptr::{Pointer, Tag, TaggedPtr}; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum Tag2 { + B00 = 0b00, + B01 = 0b01, + B10 = 0b10, + B11 = 0b11, +} + +unsafe impl Tag for Tag2 { + const BITS: usize = 2; + + fn into_usize(self) -> usize { + self as _ + } + + unsafe fn from_usize(tag: usize) -> Self { + const B00: usize = Tag2::B00 as _; + const B01: usize = Tag2::B01 as _; + const B10: usize = Tag2::B10 as _; + const B11: usize = Tag2::B11 as _; + match tag { + B00 => Tag2::B00, + B01 => Tag2::B01, + B10 => Tag2::B10, + B11 => Tag2::B11, + _ => unreachable!(), + } + } +} + +#[test] +fn smoke() { + let value = 12u32; + let reference = &value; + let tag = Tag2::B01; + + let ptr = tag_ptr(reference, tag); + + assert_eq!(ptr.tag(), tag); + assert_eq!(*ptr, 12); + + let clone = ptr.clone(); + assert_eq!(clone.tag(), tag); + assert_eq!(*clone, 12); + + let mut ptr = ptr; + ptr.set_tag(Tag2::B00); + assert_eq!(ptr.tag(), Tag2::B00); + + assert_eq!(clone.tag(), tag); + assert_eq!(*clone, 12); + assert!(ptr::eq(&*ptr, &*clone)) +} + +#[test] +fn boxed() { + let value = 12u32; + let boxed = Box::new(value); + let tag = Tag2::B01; + + let ptr = tag_ptr(boxed, tag); + + assert_eq!(ptr.tag(), tag); + assert_eq!(*ptr, 12); + + let clone = ptr.clone(); + assert_eq!(clone.tag(), tag); + assert_eq!(*clone, 12); + + let mut ptr = ptr; + ptr.set_tag(Tag2::B00); + assert_eq!(ptr.tag(), Tag2::B00); + + assert_eq!(clone.tag(), tag); + assert_eq!(*clone, 12); + assert!(!ptr::eq(&*ptr, &*clone)) +} + +#[test] +fn arclones() { + let value = 12u32; + let arc = Arc::new(value); + let tag = Tag2::B01; + + let ptr = tag_ptr(arc, tag); + + assert_eq!(ptr.tag(), tag); + assert_eq!(*ptr, 12); + + let clone = ptr.clone(); + assert!(ptr::eq(&*ptr, &*clone)) +} + +/// Helper to create tagged pointers without specifying `COMPARE_PACKED` if it does not matter. +fn tag_ptr(ptr: P, tag: T) -> TaggedPtr { + TaggedPtr::new(ptr, tag) +} From 838c5491a4296bb92891403c1a6d0e9d84991b51 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 12 Apr 2023 16:21:28 +0000 Subject: [PATCH 025/228] Document tagged pointers better --- .../rustc_data_structures/src/tagged_ptr.rs | 73 +++++++++++++++---- .../src/tagged_ptr/copy.rs | 71 +++++++++++++++--- .../src/tagged_ptr/drop.rs | 17 +++-- 3 files changed, 130 insertions(+), 31 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index 9a3d76fd4d4da..f10c12ceeda8e 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -3,15 +3,17 @@ //! In order to utilize the pointer packing, you must have two types: a pointer, //! and a tag. //! -//! The pointer must implement the `Pointer` trait, with the primary requirement -//! being conversion to and from a usize. Note that the pointer must be -//! dereferenceable, so raw pointers generally cannot implement the `Pointer` -//! trait. This implies that the pointer must also be nonzero. +//! The pointer must implement the [`Pointer`] trait, with the primary +//! requirement being convertible to and from a raw pointer. Note that the +//! pointer must be dereferenceable, so raw pointers generally cannot implement +//! the [`Pointer`] trait. This implies that the pointer must also be non-null. //! -//! Many common pointer types already implement the `Pointer` trait. +//! Many common pointer types already implement the [`Pointer`] trait. //! -//! The tag must implement the `Tag` trait. We assert that the tag and `Pointer` -//! are compatible at compile time. +//! The tag must implement the [`Tag`] trait. +//! +//! We assert that the tag and the [`Pointer`] types are compatible at compile +//! time. use std::ops::Deref; use std::ptr::NonNull; @@ -71,32 +73,66 @@ pub unsafe trait Pointer: Deref { /// [`Self::Target`]: Deref::Target const BITS: usize; + /// Turns this pointer into a raw, non-null pointer. + /// + /// The inverse of this function is [`from_ptr`]. + /// + /// This function guarantees that the least-significant [`Self::BITS`] bits + /// are zero. + /// + /// [`from_ptr`]: Pointer::from_ptr + /// [`Self::BITS`]: Pointer::BITS fn into_ptr(self) -> NonNull; + /// Re-creates the original pointer, from a raw pointer returned by [`into_ptr`]. + /// /// # Safety /// - /// The passed `ptr` must be returned from `into_usize`. + /// The passed `ptr` must be returned from [`into_ptr`]. + /// + /// This acts as [`ptr::read::()`] semantically, it should not be called more than + /// once on non-[`Copy`] `Pointer`s. /// - /// This acts as `ptr::read` semantically, it should not be called more than - /// once on non-`Copy` `Pointer`s. + /// [`into_ptr`]: Pointer::into_ptr + /// [`ptr::read::()`]: std::ptr::read unsafe fn from_ptr(ptr: NonNull) -> Self; } -/// This describes tags that the `TaggedPtr` struct can hold. +/// This describes tags that the [`TaggedPtr`] struct can hold. /// /// # Safety /// -/// The BITS constant must be correct. +/// The [`BITS`] constant must be correct. +/// +/// No more than [`BITS`] least significant bits may be set in the returned usize. /// -/// No more than `BITS` least significant bits may be set in the returned usize. +/// [`BITS`]: Tag::BITS pub unsafe trait Tag: Copy { + /// Number of least-significant bits in the return value of [`into_usize`] + /// which may be non-zero. In other words this is the bit width of the + /// value. + /// + /// [`into_usize`]: Tag::into_usize const BITS: usize; + /// Turns this tag into an integer. + /// + /// The inverse of this function is [`from_usize`]. + /// + /// This function guarantees that only the least-significant [`Self::BITS`] + /// bits can be non-zero. + /// + /// [`from_usize`]: Pointer::from_usize + /// [`Self::BITS`]: Tag::BITS fn into_usize(self) -> usize; + /// Re-creates the tag from the integer returned by [`into_usize`]. + /// /// # Safety /// - /// The passed `tag` must be returned from `into_usize`. + /// The passed `tag` must be returned from [`into_usize`]. + /// + /// [`into_usize`]: Tag::into_usize unsafe fn from_usize(tag: usize) -> Self; } @@ -111,6 +147,7 @@ unsafe impl Pointer for Box { #[inline] unsafe fn from_ptr(ptr: NonNull) -> Self { + // Safety: `ptr` comes from `into_ptr` which calls `Box::into_raw` Box::from_raw(ptr.as_ptr()) } } @@ -120,11 +157,13 @@ unsafe impl Pointer for Rc { #[inline] fn into_ptr(self) -> NonNull { + // Safety: pointers from `Rc::into_raw` are valid & non-null unsafe { NonNull::new_unchecked(Rc::into_raw(self).cast_mut()) } } #[inline] unsafe fn from_ptr(ptr: NonNull) -> Self { + // Safety: `ptr` comes from `into_ptr` which calls `Rc::into_raw` Rc::from_raw(ptr.as_ptr()) } } @@ -134,11 +173,13 @@ unsafe impl Pointer for Arc { #[inline] fn into_ptr(self) -> NonNull { + // Safety: pointers from `Arc::into_raw` are valid & non-null unsafe { NonNull::new_unchecked(Arc::into_raw(self).cast_mut()) } } #[inline] unsafe fn from_ptr(ptr: NonNull) -> Self { + // Safety: `ptr` comes from `into_ptr` which calls `Arc::into_raw` Arc::from_raw(ptr.as_ptr()) } } @@ -153,6 +194,8 @@ unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a T { #[inline] unsafe fn from_ptr(ptr: NonNull) -> Self { + // Safety: + // `ptr` comes from `into_ptr` which gets the pointer from a reference ptr.as_ref() } } @@ -167,6 +210,8 @@ unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a mut T { #[inline] unsafe fn from_ptr(mut ptr: NonNull) -> Self { + // Safety: + // `ptr` comes from `into_ptr` which gets the pointer from a reference ptr.as_mut() } } diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index aebf24ebbdeb7..02dcbd389dfdd 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -8,35 +8,75 @@ use std::num::NonZeroUsize; use std::ops::{Deref, DerefMut}; use std::ptr::NonNull; -/// A `Copy` TaggedPtr. +/// A [`Copy`] tagged pointer. /// -/// You should use this instead of the `TaggedPtr` type in all cases where -/// `P: Copy`. +/// This is essentially `{ pointer: P, tag: T }` packed in a single pointer. +/// +/// You should use this instead of the [`TaggedPtr`] type in all cases where +/// `P` implements [`Copy`]. /// /// If `COMPARE_PACKED` is true, then the pointers will be compared and hashed without -/// unpacking. Otherwise we don't implement PartialEq/Eq/Hash; if you want that, -/// wrap the TaggedPtr. +/// unpacking. Otherwise we don't implement [`PartialEq`], [`Eq`] and [`Hash`]; +/// if you want that, wrap the [`CopyTaggedPtr`]. +/// +/// [`TaggedPtr`]: crate::tagged_ptr::TaggedPtr pub struct CopyTaggedPtr where P: Pointer, T: Tag, { + /// This is semantically a pair of `pointer: P` and `tag: T` fields, + /// however we pack them in a single pointer, to save space. + /// + /// We pack the tag into the **most**-significant bits of the pointer to + /// ease retrieval of the value. A left shift is a multiplication and + /// those are embeddable in instruction encoding, for example: + /// + /// ```asm + /// // (https://godbolt.org/z/jqcYPWEr3) + /// example::shift_read3: + /// mov eax, dword ptr [8*rdi] + /// ret + /// + /// example::mask_read3: + /// and rdi, -8 + /// mov eax, dword ptr [rdi] + /// ret + /// ``` + /// + /// This is ASM outputted by rustc for reads of values behind tagged + /// pointers for different approaches of tagging: + /// - `shift_read3` uses `<< 3` (the tag is in the most-significant bits) + /// - `mask_read3` uses `& !0b111` (the tag is in the least-significant bits) + /// + /// The shift approach thus produces less instructions and is likely faster. + /// + /// Encoding diagram: + /// ```text + /// [ packed.addr ] + /// [ tag ] [ pointer.addr >> T::BITS ] <-- usize::BITS - T::BITS bits + /// ^ + /// | + /// T::BITS bits + /// ``` + /// + /// The tag can be retrieved by `packed.addr() >> T::BITS` and the pointer + /// can be retrieved by `packed.map_addr(|addr| addr << T::BITS)`. packed: NonNull, tag_ghost: PhantomData, } -// We pack the tag into the *upper* bits of the pointer to ease retrieval of the -// value; a left shift is a multiplication and those are embeddable in -// instruction encoding. impl CopyTaggedPtr where P: Pointer, T: Tag, { + /// Tags `pointer` with `tag`. pub fn new(pointer: P, tag: T) -> Self { Self { packed: Self::pack(P::into_ptr(pointer), tag), tag_ghost: PhantomData } } + /// Retrieves the pointer. pub fn pointer(self) -> P where P: Copy, @@ -48,11 +88,18 @@ where unsafe { P::from_ptr(self.pointer_raw()) } } + /// Retrieves the tag. #[inline] pub fn tag(&self) -> T { - unsafe { T::from_usize(self.packed.addr().get() >> Self::TAG_BIT_SHIFT) } + // Unpack the tag, according to the `self.packed` encoding scheme + let tag = self.packed.addr().get() >> Self::TAG_BIT_SHIFT; + + // Safety: + // + unsafe { T::from_usize(tag) } } + /// Sets the tag to a new value. #[inline] pub fn set_tag(&mut self, tag: T) { self.packed = Self::pack(self.pointer_raw(), tag); @@ -61,7 +108,8 @@ where const TAG_BIT_SHIFT: usize = usize::BITS as usize - T::BITS; const ASSERTION: () = { assert!(T::BITS <= P::BITS) }; - /// Pack pointer `ptr` that comes from [`P::into_ptr`] with a `tag`. + /// Pack pointer `ptr` that comes from [`P::into_ptr`] with a `tag`, + /// according to `self.packed` encoding scheme. /// /// [`P::into_ptr`]: Pointer::into_ptr fn pack(ptr: NonNull, tag: T) -> NonNull { @@ -71,7 +119,7 @@ where let packed_tag = tag.into_usize() << Self::TAG_BIT_SHIFT; ptr.map_addr(|addr| { - // SAFETY: + // Safety: // - The pointer is `NonNull` => it's address is `NonZeroUsize` // - `P::BITS` least significant bits are always zero (`Pointer` contract) // - `T::BITS <= P::BITS` (from `Self::ASSERTION`) @@ -85,6 +133,7 @@ where }) } + /// Retrieves the original raw pointer from `self.packed`. pub(super) fn pointer_raw(&self) -> NonNull { self.packed.map_addr(|addr| unsafe { NonZeroUsize::new_unchecked(addr.get() << T::BITS) }) } diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs index 286951ce0e9c1..6ca6c7d1283b4 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs @@ -6,11 +6,16 @@ use super::CopyTaggedPtr; use super::{Pointer, Tag}; use crate::stable_hasher::{HashStable, StableHasher}; -/// A TaggedPtr implementing `Drop`. +/// A tagged pointer that supports pointers that implement [`Drop`]. +/// +/// This is essentially `{ pointer: P, tag: T }` packed in a single pointer. +/// +/// You should use [`CopyTaggedPtr`] instead of the this type in all cases +/// where `P` implements [`Copy`]. /// /// If `COMPARE_PACKED` is true, then the pointers will be compared and hashed without -/// unpacking. Otherwise we don't implement PartialEq/Eq/Hash; if you want that, -/// wrap the TaggedPtr. +/// unpacking. Otherwise we don't implement [`PartialEq`], [`Eq`] and [`Hash`]; +/// if you want that, wrap the [`TaggedPtr`]. pub struct TaggedPtr where P: Pointer, @@ -19,22 +24,22 @@ where raw: CopyTaggedPtr, } -// We pack the tag into the *upper* bits of the pointer to ease retrieval of the -// value; a right shift is a multiplication and those are embeddable in -// instruction encoding. impl TaggedPtr where P: Pointer, T: Tag, { + /// Tags `pointer` with `tag`. pub fn new(pointer: P, tag: T) -> Self { TaggedPtr { raw: CopyTaggedPtr::new(pointer, tag) } } + /// Retrieves the tag. pub fn tag(&self) -> T { self.raw.tag() } + /// Sets the tag to a new value. pub fn set_tag(&mut self, tag: T) { self.raw.set_tag(tag) } From dc19dc29c9c384d2285a2a659111d670483562bb Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Wed, 12 Apr 2023 19:00:27 +0000 Subject: [PATCH 026/228] doc fixes --- compiler/rustc_data_structures/src/tagged_ptr.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index f10c12ceeda8e..2a74db1265499 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -40,11 +40,12 @@ pub use drop::TaggedPtr; /// [`into_ptr`] must be valid for writes (and thus calling [`NonNull::as_mut`] /// on it must be safe). /// -/// The `BITS` constant must be correct. At least `BITS` bits, least-significant, -/// must be zero on all pointers returned from [`into_ptr`]. +/// The [`BITS`] constant must be correct. At least [`BITS`] least significant +/// bits, must be zero on all pointers returned from [`into_ptr`]. /// /// For example, if the alignment of [`Self::Target`] is 2, then `BITS` should be 1. /// +/// [`BITS`]: Pointer::BITS /// [`into_ptr`]: Pointer::into_ptr /// [valid]: std::ptr#safety /// [`::Target`]: Deref::Target @@ -122,7 +123,7 @@ pub unsafe trait Tag: Copy { /// This function guarantees that only the least-significant [`Self::BITS`] /// bits can be non-zero. /// - /// [`from_usize`]: Pointer::from_usize + /// [`from_usize`]: Tag::from_usize /// [`Self::BITS`]: Tag::BITS fn into_usize(self) -> usize; From d0468a2283a7ee9a8c8a6f70f4c93f0fd6479229 Mon Sep 17 00:00:00 2001 From: AndyJado <101876416+AndyJado@users.noreply.github.com> Date: Fri, 10 Feb 2023 16:58:32 +0800 Subject: [PATCH 027/228] rm var_span_label to var_subdiag & eager subdiag --- .../src/diagnostics/conflict_errors.rs | 188 ++++++++----- .../rustc_borrowck/src/diagnostics/mod.rs | 246 +++++++---------- .../src/diagnostics/move_errors.rs | 53 ++-- .../src/diagnostics/mutability_errors.rs | 20 +- .../rustc_borrowck/src/session_diagnostics.rs | 207 +++++++++++++- .../locales/en-US/borrowck.ftl | 255 ++++++++++++++++++ 6 files changed, 729 insertions(+), 240 deletions(-) create mode 100644 compiler/rustc_error_messages/locales/en-US/borrowck.ftl diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 75a3dd0c0f3d6..8f4e0c171d047 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -30,8 +30,8 @@ use crate::borrow_set::TwoPhaseActivation; use crate::borrowck_errors; use crate::diagnostics::conflict_errors::StorageDeadOrDrop::LocalStorageDead; -use crate::diagnostics::find_all_local_uses; use crate::diagnostics::mutability_errors::mut_borrow_of_mutable_ref; +use crate::diagnostics::{find_all_local_uses, CapturedMessageOpt}; use crate::{ borrow_set::BorrowData, diagnostics::Instance, prefixes::IsPrefixOf, InitializationRequiringAction, MirBorrowckCtxt, PrefixSet, WriteKind, @@ -183,13 +183,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let move_spans = self.move_spans(moved_place.as_ref(), move_out.source); let move_span = move_spans.args_or_use(); - let move_msg = if move_spans.for_closure() { " into closure" } else { "" }; + let is_move_msg = move_spans.for_closure(); - let loop_message = if location == move_out.source || move_site.traversed_back_edge { - ", in previous iteration of loop" - } else { - "" - }; + let is_loop_message = location == move_out.source || move_site.traversed_back_edge; if location == move_out.source { is_loop_move = true; @@ -206,17 +202,21 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ); } + let msg_opt = CapturedMessageOpt { + is_partial_move, + is_loop_message, + is_move_msg, + is_loop_move, + maybe_reinitialized_locations_is_empty: maybe_reinitialized_locations + .is_empty(), + }; self.explain_captures( &mut err, span, move_span, move_spans, *moved_place, - partially_str, - loop_message, - move_msg, - is_loop_move, - maybe_reinitialized_locations.is_empty(), + msg_opt, ); } seen_spans.insert(move_span); @@ -282,12 +282,21 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } if needs_note { - let span = if let Some(local) = place.as_local() { - Some(self.body.local_decls[local].source_info.span) + if let Some(local) = place.as_local() { + let span = self.body.local_decls[local].source_info.span; + err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { + is_partial_move, + ty, + place: ¬e_msg, + span, + }); } else { - None + err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Note { + is_partial_move, + ty, + place: ¬e_msg, + }); }; - self.note_type_does_not_implement_copy(&mut err, ¬e_msg, ty, span, partial_str); } if let UseSpans::FnSelfUse { @@ -827,11 +836,13 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { borrow_spans.var_path_only_subdiag(&mut err, crate::InitializationRequiringAction::Borrow); - move_spans.var_span_label( - &mut err, - format!("move occurs due to use{}", move_spans.describe()), - "moved", - ); + move_spans.var_subdiag(None, &mut err, None, |kind, var_span| { + use crate::session_diagnostics::CaptureVarCause::*; + match kind { + Some(_) => MoveUseInGenerator { var_span }, + None => MoveUseInClosure { var_span }, + } + }); self.explain_why_borrow_contains_point(location, borrow, None) .add_explanation_to_diagnostic( @@ -868,13 +879,15 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { borrow_span, &self.describe_any_place(borrow.borrowed_place.as_ref()), ); - borrow_spans.var_subdiag(&mut err, Some(borrow.kind), |kind, var_span| { + borrow_spans.var_subdiag(None, &mut err, Some(borrow.kind), |kind, var_span| { use crate::session_diagnostics::CaptureVarCause::*; let place = &borrow.borrowed_place; let desc_place = self.describe_any_place(place.as_ref()); match kind { - Some(_) => BorrowUsePlaceGenerator { place: desc_place, var_span }, - None => BorrowUsePlaceClosure { place: desc_place, var_span }, + Some(_) => { + BorrowUsePlaceGenerator { place: desc_place, var_span, is_single_var: true } + } + None => BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: true }, } }); @@ -988,16 +1001,26 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { immutable_section_description, "mutably borrow", ); - borrow_spans.var_span_label( + borrow_spans.var_subdiag( + None, &mut err, - format!( - "borrow occurs due to use of {}{}", - desc_place, - borrow_spans.describe(), - ), - "immutable", + Some(BorrowKind::Unique), + |kind, var_span| { + use crate::session_diagnostics::CaptureVarCause::*; + match kind { + Some(_) => BorrowUsePlaceGenerator { + place: desc_place, + var_span, + is_single_var: true, + }, + None => BorrowUsePlaceClosure { + place: desc_place, + var_span, + is_single_var: true, + }, + } + }, ); - return err; } else { first_borrow_desc = "immutable "; @@ -1070,32 +1093,48 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { }; if issued_spans == borrow_spans { - borrow_spans.var_span_label( - &mut err, - format!("borrows occur due to use of {}{}", desc_place, borrow_spans.describe(),), - gen_borrow_kind.describe_mutability(), - ); + borrow_spans.var_subdiag(None, &mut err, Some(gen_borrow_kind), |kind, var_span| { + use crate::session_diagnostics::CaptureVarCause::*; + match kind { + Some(_) => BorrowUsePlaceGenerator { + place: desc_place, + var_span, + is_single_var: false, + }, + None => { + BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: false } + } + } + }); } else { - let borrow_place = &issued_borrow.borrowed_place; - let borrow_place_desc = self.describe_any_place(borrow_place.as_ref()); - issued_spans.var_span_label( + issued_spans.var_subdiag( + Some(&self.infcx.tcx.sess.parse_sess.span_diagnostic), &mut err, - format!( - "first borrow occurs due to use of {}{}", - borrow_place_desc, - issued_spans.describe(), - ), - issued_borrow.kind.describe_mutability(), + Some(issued_borrow.kind), + |kind, var_span| { + use crate::session_diagnostics::CaptureVarCause::*; + let borrow_place = &issued_borrow.borrowed_place; + let borrow_place_desc = self.describe_any_place(borrow_place.as_ref()); + match kind { + Some(_) => { + FirstBorrowUsePlaceGenerator { place: borrow_place_desc, var_span } + } + None => FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }, + } + }, ); - borrow_spans.var_span_label( + borrow_spans.var_subdiag( + Some(&self.infcx.tcx.sess.parse_sess.span_diagnostic), &mut err, - format!( - "second borrow occurs due to use of {}{}", - desc_place, - borrow_spans.describe(), - ), - gen_borrow_kind.describe_mutability(), + Some(gen_borrow_kind), + |kind, var_span| { + use crate::session_diagnostics::CaptureVarCause::*; + match kind { + Some(_) => SecondBorrowUsePlaceGenerator { place: desc_place, var_span }, + None => SecondBorrowUsePlaceClosure { place: desc_place, var_span }, + } + }, ); } @@ -1731,9 +1770,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { err.span_label(borrow_span, "borrowed value does not live long enough"); err.span_label(drop_span, format!("`{}` dropped here while still borrowed", name)); - let within = if borrow_spans.for_generator() { " by generator" } else { "" }; - - borrow_spans.args_span_label(&mut err, format!("value captured here{}", within)); + borrow_spans.args_subdiag(&mut err, |args_span| { + crate::session_diagnostics::CaptureArgLabel::Capture { + is_within: borrow_spans.for_generator(), + args_span, + } + }); explanation.add_explanation_to_diagnostic( self.infcx.tcx, @@ -1947,9 +1989,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { None, ); - let within = if borrow_spans.for_generator() { " by generator" } else { "" }; - - borrow_spans.args_span_label(&mut err, format!("value captured here{}", within)); + borrow_spans.args_subdiag(&mut err, |args_span| { + crate::session_diagnostics::CaptureArgLabel::Capture { + is_within: borrow_spans.for_generator(), + args_span, + } + }); err } @@ -2382,11 +2427,14 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { section, "assign", ); - loan_spans.var_span_label( - &mut err, - format!("borrow occurs due to use{}", loan_spans.describe()), - loan.kind.describe_mutability(), - ); + + loan_spans.var_subdiag(None, &mut err, Some(loan.kind), |kind, var_span| { + use crate::session_diagnostics::CaptureVarCause::*; + match kind { + Some(_) => BorrowUseInGenerator { var_span }, + None => BorrowUseInClosure { var_span }, + } + }); self.buffer_error(err); @@ -2396,11 +2444,13 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place); - loan_spans.var_span_label( - &mut err, - format!("borrow occurs due to use{}", loan_spans.describe()), - loan.kind.describe_mutability(), - ); + loan_spans.var_subdiag(None, &mut err, Some(loan.kind), |kind, var_span| { + use crate::session_diagnostics::CaptureVarCause::*; + match kind { + Some(_) => BorrowUseInGenerator { var_span }, + None => BorrowUseInClosure { var_span }, + } + }); self.explain_why_borrow_contains_point(location, loan, None).add_explanation_to_diagnostic( self.infcx.tcx, diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 110354a20d839..6a8755f8ad521 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -1,5 +1,9 @@ //! Borrow checker diagnostics. +use crate::session_diagnostics::{ + CaptureArgLabel, CaptureReasonLabel, CaptureReasonNote, CaptureReasonSuggest, CaptureVarCause, + CaptureVarKind, CaptureVarPathUseCause, OnClosureNote, +}; use itertools::Itertools; use rustc_const_eval::util::{call_kind, CallDesugaringKind}; use rustc_errors::{Applicability, Diagnostic}; @@ -117,13 +121,15 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() { let did = did.expect_local(); if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { - diag.span_note( - *span, - &format!( - "closure cannot be invoked more than once because it moves the \ - variable `{}` out of its environment", - ty::place_to_string_for_capture(self.infcx.tcx, hir_place) - ), + diag.eager_subdiagnostic( + &self.infcx.tcx.sess.parse_sess.span_diagnostic, + OnClosureNote::InvokedTwice { + place_name: &ty::place_to_string_for_capture( + self.infcx.tcx, + hir_place, + ), + span: *span, + }, ); return true; } @@ -137,13 +143,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() { let did = did.expect_local(); if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { - diag.span_note( - *span, - &format!( - "closure cannot be moved more than once as it is not `Copy` due to \ - moving the variable `{}` out of its environment", - ty::place_to_string_for_capture(self.infcx.tcx, hir_place) - ), + diag.eager_subdiagnostic( + &self.infcx.tcx.sess.parse_sess.span_diagnostic, + OnClosureNote::MovedTwice { + place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place), + span: *span, + }, ); return true; } @@ -380,25 +385,6 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } } - /// Add a note that a type does not implement `Copy` - pub(super) fn note_type_does_not_implement_copy( - &self, - err: &mut Diagnostic, - place_desc: &str, - ty: Ty<'tcx>, - span: Option, - move_prefix: &str, - ) { - let message = format!( - "{move_prefix}move occurs because {place_desc} has type `{ty}`, which does not implement the `Copy` trait", - ); - if let Some(span) = span { - err.span_label(span, message); - } else { - err.note(&message); - } - } - pub(super) fn borrowed_content_source( &self, deref_base: PlaceRef<'tcx>, @@ -582,9 +568,13 @@ impl UseSpans<'_> { } /// Add a span label to the arguments of the closure, if it exists. - pub(super) fn args_span_label(self, err: &mut Diagnostic, message: impl Into) { + pub(super) fn args_subdiag( + self, + err: &mut Diagnostic, + f: impl FnOnce(Span) -> CaptureArgLabel, + ) { if let UseSpans::ClosureUse { args_span, .. } = self { - err.span_label(args_span, message); + err.subdiagnostic(f(args_span)); } } @@ -595,8 +585,8 @@ impl UseSpans<'_> { err: &mut Diagnostic, action: crate::InitializationRequiringAction, ) { - use crate::session_diagnostics::CaptureVarPathUseCause::*; use crate::InitializationRequiringAction::*; + use CaptureVarPathUseCause::*; if let UseSpans::ClosureUse { generator_kind, path_span, .. } = self { match generator_kind { Some(_) => { @@ -619,34 +609,14 @@ impl UseSpans<'_> { } } - /// Add a span label to the use of the captured variable, if it exists. - pub(super) fn var_span_label( - self, - err: &mut Diagnostic, - message: impl Into, - kind_desc: impl Into, - ) { - if let UseSpans::ClosureUse { capture_kind_span, path_span, .. } = self { - if capture_kind_span == path_span { - err.span_label(capture_kind_span, message); - } else { - let capture_kind_label = - format!("capture is {} because of use here", kind_desc.into()); - let path_label = message; - err.span_label(capture_kind_span, capture_kind_label); - err.span_label(path_span, path_label); - } - } - } - /// Add a subdiagnostic to the use of the captured variable, if it exists. pub(super) fn var_subdiag( self, + handler: Option<&rustc_errors::Handler>, err: &mut Diagnostic, kind: Option, - f: impl Fn(Option, Span) -> crate::session_diagnostics::CaptureVarCause, + f: impl FnOnce(Option, Span) -> CaptureVarCause, ) { - use crate::session_diagnostics::CaptureVarKind::*; if let UseSpans::ClosureUse { generator_kind, capture_kind_span, path_span, .. } = self { if capture_kind_span != path_span { err.subdiagnostic(match kind { @@ -654,17 +624,21 @@ impl UseSpans<'_> { rustc_middle::mir::BorrowKind::Shared | rustc_middle::mir::BorrowKind::Shallow | rustc_middle::mir::BorrowKind::Unique => { - Immute { kind_span: capture_kind_span } + CaptureVarKind::Immut { kind_span: capture_kind_span } } rustc_middle::mir::BorrowKind::Mut { .. } => { - Mut { kind_span: capture_kind_span } + CaptureVarKind::Mut { kind_span: capture_kind_span } } }, - None => Move { kind_span: capture_kind_span }, + None => CaptureVarKind::Move { kind_span: capture_kind_span }, }); }; - err.subdiagnostic(f(generator_kind, path_span)); + let diag = f(generator_kind, path_span); + match handler { + Some(hd) => err.eager_subdiagnostic(hd, diag), + None => err.subdiagnostic(diag), + }; } } @@ -684,20 +658,6 @@ impl UseSpans<'_> { } } - /// Describe the span associated with a use of a place. - pub(super) fn describe(&self) -> &str { - match *self { - UseSpans::ClosureUse { generator_kind, .. } => { - if generator_kind.is_some() { - " in generator" - } else { - " in closure" - } - } - _ => "", - } - } - pub(super) fn or_else(self, if_other: F) -> Self where F: FnOnce() -> Self, @@ -788,6 +748,15 @@ impl<'tcx> BorrowedContentSource<'tcx> { } } +///helper struct for explain_captures() +struct CapturedMessageOpt { + is_partial_move: bool, + is_loop_message: bool, + is_move_msg: bool, + is_loop_move: bool, + maybe_reinitialized_locations_is_empty: bool, +} + impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { /// Finds the spans associated to a move or copy of move_place at location. pub(super) fn move_spans( @@ -1027,12 +996,15 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { move_span: Span, move_spans: UseSpans<'tcx>, moved_place: Place<'tcx>, - partially_str: &str, - loop_message: &str, - move_msg: &str, - is_loop_move: bool, - maybe_reinitialized_locations_is_empty: bool, + msg_opt: CapturedMessageOpt, ) { + let CapturedMessageOpt { + is_partial_move: is_partial, + is_loop_message, + is_move_msg, + is_loop_move, + maybe_reinitialized_locations_is_empty, + } = msg_opt; if let UseSpans::FnSelfUse { var_span, fn_call_span, fn_span, kind } = move_spans { let place_name = self .describe_place(moved_place.as_ref()) @@ -1042,30 +1014,26 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { CallKind::FnCall { fn_trait_id, .. } if Some(fn_trait_id) == self.infcx.tcx.lang_items().fn_once_trait() => { - err.span_label( + err.subdiagnostic(CaptureReasonLabel::Call { fn_call_span, - &format!( - "{place_name} {partially_str}moved due to this call{loop_message}", - ), - ); - err.span_note( - var_span, - "this value implements `FnOnce`, which causes it to be moved when called", - ); + place_name: &place_name, + is_partial, + is_loop_message, + }); + err.subdiagnostic(CaptureReasonNote::FnOnceMoveInCall { var_span }); } CallKind::Operator { self_arg, .. } => { let self_arg = self_arg.unwrap(); - err.span_label( + err.subdiagnostic(CaptureReasonLabel::OperatorUse { fn_call_span, - &format!( - "{place_name} {partially_str}moved due to usage in operator{loop_message}", - ), - ); + place_name: &place_name, + is_partial, + is_loop_message, + }); if self.fn_self_span_reported.insert(fn_span) { - err.span_note( - self_arg.span, - "calling this operator moves the left-hand side", - ); + err.subdiagnostic(CaptureReasonNote::LhsMoveByOperator { + span: self_arg.span, + }); } } CallKind::Normal { self_arg, desugaring, method_did, method_substs } => { @@ -1086,23 +1054,18 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { _ => false, }; if suggest { - err.span_suggestion_verbose( - move_span.shrink_to_lo(), - &format!( - "consider iterating over a slice of the `{ty}`'s content to \ - avoid moving into the `for` loop", - ), - "&", - Applicability::MaybeIncorrect, - ); + err.subdiagnostic(CaptureReasonSuggest::IterateSlice { + ty, + span: move_span.shrink_to_lo(), + }); } - err.span_label( + err.subdiagnostic(CaptureReasonLabel::ImplicitCall { fn_call_span, - &format!( - "{place_name} {partially_str}moved due to this implicit call to `.into_iter()`{loop_message}", - ), - ); + place_name: &place_name, + is_partial, + is_loop_message, + }); // If the moved place was a `&mut` ref, then we can // suggest to reborrow it where it was moved, so it // will still be valid by the time we get to the usage. @@ -1125,13 +1088,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } } } else { - err.span_label( + err.subdiagnostic(CaptureReasonLabel::MethodCall { fn_call_span, - &format!( - "{place_name} {partially_str}moved due to this method call{loop_message}", - ), - ); - + place_name: &place_name, + is_partial, + is_loop_message, + }); let infcx = tcx.infer_ctxt().build(); // Erase and shadow everything that could be passed to the new infcx. let ty = tcx.erase_regions(moved_place.ty(self.body, tcx).ty); @@ -1147,12 +1109,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ) && infcx.can_eq(self.param_env, ty, self_ty) { - err.span_suggestion_verbose( - fn_call_span.shrink_to_lo(), - "consider reborrowing the `Pin` instead of moving it", - "as_mut().".to_string(), - Applicability::MaybeIncorrect, - ); + err.eager_subdiagnostic( + &self.infcx.tcx.sess.parse_sess.span_diagnostic, + CaptureReasonSuggest::FreshReborrow { + span: fn_call_span.shrink_to_lo(), + }); } if let Some(clone_trait) = tcx.lang_items().clone_trait() && let trait_ref = tcx.mk_trait_ref(clone_trait, [ty]) @@ -1177,10 +1138,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // error messages. if span != DUMMY_SP && self.fn_self_span_reported.insert(self_arg.span) { let func = tcx.def_path_str(method_did); - err.span_note( - self_arg.span, - &format!("`{func}` takes ownership of the receiver `self`, which moves {place_name}") - ); + err.subdiagnostic(CaptureReasonNote::FuncTakeSelf { + func, + place_name, + span: self_arg.span, + }); } let parent_did = tcx.parent(method_did); let parent_self_ty = @@ -1194,30 +1156,28 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result)) }); if is_option_or_result && maybe_reinitialized_locations_is_empty { - err.span_label( - var_span, - "help: consider calling `.as_ref()` or `.as_mut()` to borrow the type's contents", - ); + err.subdiagnostic(CaptureReasonLabel::BorrowContent { var_span }); } } // Other desugarings takes &self, which cannot cause a move _ => {} } } else { - if move_span != span || !loop_message.is_empty() { - err.span_label( + if move_span != span || is_loop_message { + err.subdiagnostic(CaptureReasonLabel::MovedHere { move_span, - format!("value {partially_str}moved{move_msg} here{loop_message}"), - ); + is_partial, + is_move_msg, + is_loop_message, + }); } // If the move error occurs due to a loop, don't show // another message for the same span - if loop_message.is_empty() { - move_spans.var_span_label( - err, - format!("variable {partially_str}moved due to use{}", move_spans.describe()), - "moved", - ); + if !is_loop_message { + move_spans.var_subdiag(None, err, None, |kind, var_span| match kind { + Some(_) => CaptureVarCause::PartialMoveUseInGenerator { var_span, is_partial }, + None => CaptureVarCause::PartialMoveUseInClosure { var_span, is_partial }, + }) } } } diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 3662bec0c7636..67af96a71e30d 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -6,6 +6,7 @@ use rustc_mir_dataflow::move_paths::{ }; use rustc_span::{BytePos, Span}; +use crate::diagnostics::CapturedMessageOpt; use crate::diagnostics::{DescribePlaceOpt, UseSpans}; use crate::prefixes::PrefixSet; use crate::MirBorrowckCtxt; @@ -397,10 +398,15 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } } }; + let msg_opt = CapturedMessageOpt { + is_partial_move: false, + is_loop_message: false, + is_move_msg: false, + is_loop_move: false, + maybe_reinitialized_locations_is_empty: true, + }; if let Some(use_spans) = use_spans { - self.explain_captures( - &mut err, span, span, use_spans, move_place, "", "", "", false, true, - ); + self.explain_captures(&mut err, span, span, use_spans, move_place, msg_opt); } err } @@ -416,13 +422,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { None => "value".to_string(), }; - self.note_type_does_not_implement_copy( - err, - &place_desc, - place_ty, - Some(span), - "", - ); + err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { + is_partial_move: false, + ty: place_ty, + place: &place_desc, + span, + }); } else { binds_to.sort(); binds_to.dedup(); @@ -444,9 +449,19 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { Some(desc) => format!("`{desc}`"), None => "value".to_string(), }; - self.note_type_does_not_implement_copy(err, &place_desc, place_ty, Some(span), ""); + err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { + is_partial_move: false, + ty: place_ty, + place: &place_desc, + span, + }); - use_spans.args_span_label(err, format!("{place_desc} is moved here")); + use_spans.args_subdiag(err, |args_span| { + crate::session_diagnostics::CaptureArgLabel::MoveOutPlace { + place: place_desc, + args_span, + } + }); } } } @@ -534,13 +549,13 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } if binds_to.len() == 1 { - self.note_type_does_not_implement_copy( - err, - &format!("`{}`", self.local_names[*local].unwrap()), - bind_to.ty, - Some(binding_span), - "", - ); + let place_desc = &format!("`{}`", self.local_names[*local].unwrap()); + err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label { + is_partial_move: false, + ty: bind_to.ty, + place: &place_desc, + span: binding_span, + }); } } diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 9d90400965040..aa5c10de62ce5 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -231,14 +231,18 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } } if suggest { - borrow_spans.var_span_label( - &mut err, - format!( - "mutable borrow occurs due to use of {} in closure", - self.describe_any_place(access_place.as_ref()), - ), - "mutable", - ); + borrow_spans.var_subdiag( + None, + &mut err, + Some(mir::BorrowKind::Mut { allow_two_phase_borrow: false }), + |_kind, var_span| { + let place = self.describe_any_place(access_place.as_ref()); + crate::session_diagnostics::CaptureVarCause::MutableBorrowUsePlaceClosure { + place, + var_span, + } + }, + ); } borrow_span } diff --git a/compiler/rustc_borrowck/src/session_diagnostics.rs b/compiler/rustc_borrowck/src/session_diagnostics.rs index a3678929099d1..bb95101845f3e 100644 --- a/compiler/rustc_borrowck/src/session_diagnostics.rs +++ b/compiler/rustc_borrowck/src/session_diagnostics.rs @@ -184,7 +184,7 @@ pub(crate) enum CaptureVarPathUseCause { #[derive(Subdiagnostic)] pub(crate) enum CaptureVarKind { #[label(borrowck_capture_immute)] - Immute { + Immut { #[primary_span] kind_span: Span, }, @@ -204,16 +204,80 @@ pub(crate) enum CaptureVarKind { pub(crate) enum CaptureVarCause { #[label(borrowck_var_borrow_by_use_place_in_generator)] BorrowUsePlaceGenerator { + is_single_var: bool, place: String, #[primary_span] var_span: Span, }, #[label(borrowck_var_borrow_by_use_place_in_closure)] BorrowUsePlaceClosure { + is_single_var: bool, place: String, #[primary_span] var_span: Span, }, + #[label(borrowck_var_borrow_by_use_in_generator)] + BorrowUseInGenerator { + #[primary_span] + var_span: Span, + }, + #[label(borrowck_var_borrow_by_use_in_closure)] + BorrowUseInClosure { + #[primary_span] + var_span: Span, + }, + #[label(borrowck_var_move_by_use_in_generator)] + MoveUseInGenerator { + #[primary_span] + var_span: Span, + }, + #[label(borrowck_var_move_by_use_in_closure)] + MoveUseInClosure { + #[primary_span] + var_span: Span, + }, + #[label(borrowck_var_first_borrow_by_use_place_in_generator)] + FirstBorrowUsePlaceGenerator { + place: String, + #[primary_span] + var_span: Span, + }, + #[label(borrowck_var_first_borrow_by_use_place_in_closure)] + FirstBorrowUsePlaceClosure { + place: String, + #[primary_span] + var_span: Span, + }, + #[label(borrowck_var_second_borrow_by_use_place_in_generator)] + SecondBorrowUsePlaceGenerator { + place: String, + #[primary_span] + var_span: Span, + }, + #[label(borrowck_var_second_borrow_by_use_place_in_closure)] + SecondBorrowUsePlaceClosure { + place: String, + #[primary_span] + var_span: Span, + }, + #[label(borrowck_var_mutable_borrow_by_use_place_in_closure)] + MutableBorrowUsePlaceClosure { + place: String, + #[primary_span] + var_span: Span, + }, + #[label(borrowck_partial_var_move_by_use_in_generator)] + PartialMoveUseInGenerator { + #[primary_span] + var_span: Span, + is_partial: bool, + }, + #[label(borrowck_partial_var_move_by_use_in_closure)] + PartialMoveUseInClosure { + #[primary_span] + var_span: Span, + is_partial: bool, + }, } #[derive(Diagnostic)] @@ -239,3 +303,144 @@ pub(crate) struct NonGenericOpaqueTypeParam<'a, 'tcx> { #[label] pub param_span: Span, } + +#[derive(Subdiagnostic)] +pub(crate) enum CaptureReasonLabel<'a> { + #[label(borrowck_moved_due_to_call)] + Call { + #[primary_span] + fn_call_span: Span, + place_name: &'a str, + is_partial: bool, + is_loop_message: bool, + }, + #[label(borrowck_moved_due_to_usage_in_operator)] + OperatorUse { + #[primary_span] + fn_call_span: Span, + place_name: &'a str, + is_partial: bool, + is_loop_message: bool, + }, + #[label(borrowck_moved_due_to_implicit_into_iter_call)] + ImplicitCall { + #[primary_span] + fn_call_span: Span, + place_name: &'a str, + is_partial: bool, + is_loop_message: bool, + }, + #[label(borrowck_moved_due_to_method_call)] + MethodCall { + #[primary_span] + fn_call_span: Span, + place_name: &'a str, + is_partial: bool, + is_loop_message: bool, + }, + #[label(borrowck_value_moved_here)] + MovedHere { + #[primary_span] + move_span: Span, + is_partial: bool, + is_move_msg: bool, + is_loop_message: bool, + }, + #[label(borrowck_consider_borrow_type_contents)] + BorrowContent { + #[primary_span] + var_span: Span, + }, +} + +#[derive(Subdiagnostic)] +pub(crate) enum CaptureReasonNote { + #[note(borrowck_moved_a_fn_once_in_call)] + FnOnceMoveInCall { + #[primary_span] + var_span: Span, + }, + #[note(borrowck_calling_operator_moves_lhs)] + LhsMoveByOperator { + #[primary_span] + span: Span, + }, + #[note(borrowck_func_take_self_moved_place)] + FuncTakeSelf { + func: String, + place_name: String, + #[primary_span] + span: Span, + }, +} + +#[derive(Subdiagnostic)] +pub(crate) enum CaptureReasonSuggest<'tcx> { + #[suggestion( + borrowck_suggest_iterate_over_slice, + applicability = "maybe-incorrect", + code = "&", + style = "verbose" + )] + IterateSlice { + ty: Ty<'tcx>, + #[primary_span] + span: Span, + }, + #[suggestion( + borrowck_suggest_create_freash_reborrow, + applicability = "maybe-incorrect", + code = "as_mut().", + style = "verbose" + )] + FreshReborrow { + #[primary_span] + span: Span, + }, +} + +#[derive(Subdiagnostic)] +pub(crate) enum CaptureArgLabel { + #[label(borrowck_value_capture_here)] + Capture { + is_within: bool, + #[primary_span] + args_span: Span, + }, + #[label(borrowck_move_out_place_here)] + MoveOutPlace { + place: String, + #[primary_span] + args_span: Span, + }, +} + +#[derive(Subdiagnostic)] +pub(crate) enum OnClosureNote<'a> { + #[note(borrowck_closure_invoked_twice)] + InvokedTwice { + place_name: &'a str, + #[primary_span] + span: Span, + }, + #[note(borrowck_closure_moved_twice)] + MovedTwice { + place_name: &'a str, + #[primary_span] + span: Span, + }, +} + +#[derive(Subdiagnostic)] +pub(crate) enum TypeNoCopy<'a, 'tcx> { + #[label(borrowck_ty_no_impl_copy)] + Label { + is_partial_move: bool, + ty: Ty<'tcx>, + place: &'a str, + #[primary_span] + span: Span, + }, + #[note(borrowck_ty_no_impl_copy)] + Note { is_partial_move: bool, ty: Ty<'tcx>, place: &'a str }, +} diff --git a/compiler/rustc_error_messages/locales/en-US/borrowck.ftl b/compiler/rustc_error_messages/locales/en-US/borrowck.ftl new file mode 100644 index 0000000000000..5072841db57ef --- /dev/null +++ b/compiler/rustc_error_messages/locales/en-US/borrowck.ftl @@ -0,0 +1,255 @@ +borrowck_move_unsized = + cannot move a value of type `{$ty}` + .label = the size of `{$ty}` cannot be statically determined + +borrowck_higher_ranked_lifetime_error = + higher-ranked lifetime error + +borrowck_could_not_prove = + could not prove `{$predicate}` + +borrowck_could_not_normalize = + could not normalize `{$value}` + +borrowck_higher_ranked_subtype_error = + higher-ranked subtype error + +borrowck_generic_does_not_live_long_enough = + `{$kind}` does not live long enough + +borrowck_move_borrowed = + cannot move out of `{$desc}` beacause it is borrowed + +borrowck_var_does_not_need_mut = + variable does not need to be mutable + .suggestion = remove this `mut` + +borrowck_var_cannot_escape_closure = + captured variable cannot escape `FnMut` closure body + .note = `FnMut` closures only have access to their captured variables while they are executing... + .cannot_escape = ...therefore, they cannot allow references to captured variables to escape + +borrowck_var_here_defined = variable defined here + +borrowck_var_here_captured = variable captured here + +borrowck_closure_inferred_mut = inferred to be a `FnMut` closure + +borrowck_returned_closure_escaped = + returns a closure that contains a reference to a captured variable, which then escapes the closure body + +borrowck_returned_async_block_escaped = + returns an `async` block that contains a reference to a captured variable, which then escapes the closure body + +borrowck_returned_ref_escaped = + returns a reference to a captured variable which escapes the closure body + +borrowck_lifetime_constraints_error = + lifetime may not live long enough + +borrowck_returned_lifetime_wrong = + {$mir_def_name} was supposed to return data with lifetime `{$outlived_fr_name}` but it is returning data with lifetime `{$fr_name}` + +borrowck_returned_lifetime_short = + {$category_desc}requires that `{$free_region_name}` must outlive `{$outlived_fr_name}` + +borrowck_used_impl_require_static = + the used `impl` has a `'static` requirement + +borrowck_borrow_due_to_use_generator = + borrow occurs due to use in generator + +borrowck_use_due_to_use_generator = + use occurs due to use in generator + +borrowck_assign_due_to_use_generator = + assign occurs due to use in generator + +borrowck_assign_part_due_to_use_generator = + assign to part occurs due to use in generator + +borrowck_borrow_due_to_use_closure = + borrow occurs due to use in closure + +borrowck_use_due_to_use_closure = + use occurs due to use in closure + +borrowck_assign_due_to_use_closure = + assign occurs due to use in closure + +borrowck_assign_part_due_to_use_closure = + assign to part occurs due to use in closure + +borrowck_capture_immute = + capture is immutable because of use here + +borrowck_capture_mut = + capture is mutable because of use here + +borrowck_capture_move = + capture is moved because of use here + +borrowck_var_borrow_by_use_place_in_generator = + {$is_single_var -> + *[true] borrow occurs + [false] borrows occur + } due to use of {$place} in generator + +borrowck_var_borrow_by_use_place_in_closure = + {$is_single_var -> + *[true] borrow occurs + [false] borrows occur + } due to use of {$place} in closure + +borrowck_var_borrow_by_use_in_generator = + borrow occurs due to use in generator + +borrowck_var_borrow_by_use_in_closure = + borrow occurs due to use in closure + +borrowck_var_move_by_use_place_in_generator = + move occurs due to use of {$place} in generator + +borrowck_var_move_by_use_place_in_closure = + move occurs due to use of {$place} in closure + +borrowck_var_move_by_use_in_generator = + move occurs due to use in generator + +borrowck_var_move_by_use_in_closure = + move occurs due to use in closure + +borrowck_partial_var_move_by_use_in_generator = + variable {$is_partial -> + [true] partially moved + *[false] moved + } due to use in generator + +borrowck_partial_var_move_by_use_in_closure = + variable {$is_partial -> + [true] partially moved + *[false] moved + } due to use in closure + +borrowck_var_first_borrow_by_use_place_in_generator = + first borrow occurs due to use of {$place} in generator + +borrowck_var_first_borrow_by_use_place_in_closure = + first borrow occurs due to use of {$place} in closure + +borrowck_var_second_borrow_by_use_place_in_generator = + second borrow occurs due to use of {$place} in generator + +borrowck_var_second_borrow_by_use_place_in_closure = + second borrow occurs due to use of {$place} in closure + +borrowck_var_mutable_borrow_by_use_place_in_closure = + mutable borrow occurs due to use of {$place} in closure + +borrowck_cannot_move_when_borrowed = + cannot move out of {$place -> + [value] value + *[other] {$place} + } because it is borrowed + .label = borrow of {$borrow_place -> + [value] value + *[other] {$borrow_place} + } occurs here + .move_label = move out of {$value_place -> + [value] value + *[other] {$value_place} + } occurs here + +borrowck_opaque_type_non_generic_param = + expected generic {$kind} parameter, found `{$ty}` + .label = {STREQ($ty, "'static") -> + [true] cannot use static lifetime; use a bound lifetime instead or remove the lifetime parameter from the opaque type + *[other] this generic parameter must be used with a generic {$kind} parameter + } + +borrowck_moved_due_to_call = + {$place_name} {$is_partial -> + [true] partially moved + *[false] moved + } due to this {$is_loop_message -> + [true] call, in previous iteration of loop + *[false] call + } + +borrowck_moved_due_to_usage_in_operator = + {$place_name} {$is_partial -> + [true] partially moved + *[false] moved + } due to usage in {$is_loop_message -> + [true] operator, in previous iteration of loop + *[false] operator + } + +borrowck_moved_due_to_implicit_into_iter_call = + {$place_name} {$is_partial -> + [true] partially moved + *[false] moved + } due to this implicit call to {$is_loop_message -> + [true] `.into_iter()`, in previous iteration of loop + *[false] `.into_iter()` + } + +borrowck_moved_due_to_method_call = + {$place_name} {$is_partial -> + [true] partially moved + *[false] moved + } due to this method {$is_loop_message -> + [true] call, in previous iteration of loop + *[false] call + } + +borrowck_value_moved_here = + value {$is_partial -> + [true] partially moved + *[false] moved + } {$is_move_msg -> + [true] into closure here + *[false] here + }{$is_loop_message -> + [true] , in previous iteration of loop + *[false] {""} + } + +borrowck_consider_borrow_type_contents = + help: consider calling `.as_ref()` or `.as_mut()` to borrow the type's contents + +borrowck_moved_a_fn_once_in_call = + this value implements `FnOnce`, which causes it to be moved when called + +borrowck_calling_operator_moves_lhs = + calling this operator moves the left-hand side + +borrowck_func_take_self_moved_place = + `{$func}` takes ownership of the receiver `self`, which moves {$place_name} + +borrowck_suggest_iterate_over_slice = + consider iterating over a slice of the `{$ty}`'s content to avoid moving into the `for` loop + +borrowck_suggest_create_freash_reborrow = + consider reborrowing the `Pin` instead of moving it + +borrowck_value_capture_here = + value captured {$is_within -> + [true] here by generator + *[false] here + } + +borrowck_move_out_place_here = + {$place} is moved here + +borrowck_closure_invoked_twice = + closure cannot be invoked more than once because it moves the variable `{$place_name}` out of its environment + +borrowck_closure_moved_twice = + closure cannot be moved more than once as it is not `Copy` due to moving the variable `{$place_name}` out of its environment + +borrowck_ty_no_impl_copy = + {$is_partial_move -> + [true] partial move + *[false] move + } occurs because {$place} has type `{$ty}`, which does not implement the `Copy` trait From bdf0e74777dd92aed40c19a1b20eb08ac1c845a8 Mon Sep 17 00:00:00 2001 From: AndyJado <101876416+AndyJado@users.noreply.github.com> Date: Fri, 24 Feb 2023 13:26:27 +0800 Subject: [PATCH 028/228] migrate ftl msg accroding to #103042 --- compiler/rustc_borrowck/messages.ftl | 150 ++++++++++- .../locales/en-US/borrowck.ftl | 255 ------------------ 2 files changed, 138 insertions(+), 267 deletions(-) delete mode 100644 compiler/rustc_error_messages/locales/en-US/borrowck.ftl diff --git a/compiler/rustc_borrowck/messages.ftl b/compiler/rustc_borrowck/messages.ftl index a3b6b5e8138b6..0b8123c970360 100644 --- a/compiler/rustc_borrowck/messages.ftl +++ b/compiler/rustc_borrowck/messages.ftl @@ -56,18 +56,6 @@ borrowck_returned_lifetime_short = borrowck_used_impl_require_static = the used `impl` has a `'static` requirement -borrowck_capture_kind_label = - capture is {$kind_desc} because of use here - -borrowck_var_borrow_by_use_place_in_generator = - borrow occurs due to use of {$place} in closure in generator - -borrowck_var_borrow_by_use_place_in_closure = - borrow occurs due to use of {$place} in closure - -borrowck_var_borrow_by_use_place = - borrow occurs due to use of {$place} - borrowck_borrow_due_to_use_generator = borrow occurs due to use in generator @@ -101,12 +89,63 @@ borrowck_capture_mut = borrowck_capture_move = capture is moved because of use here +borrowck_var_borrow_by_use_place_in_generator = + {$is_single_var -> + *[true] borrow occurs + [false] borrows occur + } due to use of {$place} in generator + +borrowck_var_borrow_by_use_place_in_closure = + {$is_single_var -> + *[true] borrow occurs + [false] borrows occur + } due to use of {$place} in closure + +borrowck_var_borrow_by_use_in_generator = + borrow occurs due to use in generator + +borrowck_var_borrow_by_use_in_closure = + borrow occurs due to use in closure + borrowck_var_move_by_use_place_in_generator = move occurs due to use of {$place} in generator borrowck_var_move_by_use_place_in_closure = move occurs due to use of {$place} in closure +borrowck_var_move_by_use_in_generator = + move occurs due to use in generator + +borrowck_var_move_by_use_in_closure = + move occurs due to use in closure + +borrowck_partial_var_move_by_use_in_generator = + variable {$is_partial -> + [true] partially moved + *[false] moved + } due to use in generator + +borrowck_partial_var_move_by_use_in_closure = + variable {$is_partial -> + [true] partially moved + *[false] moved + } due to use in closure + +borrowck_var_first_borrow_by_use_place_in_generator = + first borrow occurs due to use of {$place} in generator + +borrowck_var_first_borrow_by_use_place_in_closure = + first borrow occurs due to use of {$place} in closure + +borrowck_var_second_borrow_by_use_place_in_generator = + second borrow occurs due to use of {$place} in generator + +borrowck_var_second_borrow_by_use_place_in_closure = + second borrow occurs due to use of {$place} in closure + +borrowck_var_mutable_borrow_by_use_place_in_closure = + mutable borrow occurs due to use of {$place} in closure + borrowck_cannot_move_when_borrowed = cannot move out of {$place -> [value] value @@ -127,3 +166,90 @@ borrowck_opaque_type_non_generic_param = [true] cannot use static lifetime; use a bound lifetime instead or remove the lifetime parameter from the opaque type *[other] this generic parameter must be used with a generic {$kind} parameter } + +borrowck_moved_due_to_call = + {$place_name} {$is_partial -> + [true] partially moved + *[false] moved + } due to this {$is_loop_message -> + [true] call, in previous iteration of loop + *[false] call + } + +borrowck_moved_due_to_usage_in_operator = + {$place_name} {$is_partial -> + [true] partially moved + *[false] moved + } due to usage in {$is_loop_message -> + [true] operator, in previous iteration of loop + *[false] operator + } + +borrowck_moved_due_to_implicit_into_iter_call = + {$place_name} {$is_partial -> + [true] partially moved + *[false] moved + } due to this implicit call to {$is_loop_message -> + [true] `.into_iter()`, in previous iteration of loop + *[false] `.into_iter()` + } + +borrowck_moved_due_to_method_call = + {$place_name} {$is_partial -> + [true] partially moved + *[false] moved + } due to this method {$is_loop_message -> + [true] call, in previous iteration of loop + *[false] call + } + +borrowck_value_moved_here = + value {$is_partial -> + [true] partially moved + *[false] moved + } {$is_move_msg -> + [true] into closure here + *[false] here + }{$is_loop_message -> + [true] , in previous iteration of loop + *[false] {""} + } + +borrowck_consider_borrow_type_contents = + help: consider calling `.as_ref()` or `.as_mut()` to borrow the type's contents + +borrowck_moved_a_fn_once_in_call = + this value implements `FnOnce`, which causes it to be moved when called + +borrowck_calling_operator_moves_lhs = + calling this operator moves the left-hand side + +borrowck_func_take_self_moved_place = + `{$func}` takes ownership of the receiver `self`, which moves {$place_name} + +borrowck_suggest_iterate_over_slice = + consider iterating over a slice of the `{$ty}`'s content to avoid moving into the `for` loop + +borrowck_suggest_create_freash_reborrow = + consider reborrowing the `Pin` instead of moving it + +borrowck_value_capture_here = + value captured {$is_within -> + [true] here by generator + *[false] here + } + +borrowck_move_out_place_here = + {$place} is moved here + +borrowck_closure_invoked_twice = + closure cannot be invoked more than once because it moves the variable `{$place_name}` out of its environment + +borrowck_closure_moved_twice = + closure cannot be moved more than once as it is not `Copy` due to moving the variable `{$place_name}` out of its environment + +borrowck_ty_no_impl_copy = + {$is_partial_move -> + [true] partial move + *[false] move + } occurs because {$place} has type `{$ty}`, which does not implement the `Copy` trait diff --git a/compiler/rustc_error_messages/locales/en-US/borrowck.ftl b/compiler/rustc_error_messages/locales/en-US/borrowck.ftl deleted file mode 100644 index 5072841db57ef..0000000000000 --- a/compiler/rustc_error_messages/locales/en-US/borrowck.ftl +++ /dev/null @@ -1,255 +0,0 @@ -borrowck_move_unsized = - cannot move a value of type `{$ty}` - .label = the size of `{$ty}` cannot be statically determined - -borrowck_higher_ranked_lifetime_error = - higher-ranked lifetime error - -borrowck_could_not_prove = - could not prove `{$predicate}` - -borrowck_could_not_normalize = - could not normalize `{$value}` - -borrowck_higher_ranked_subtype_error = - higher-ranked subtype error - -borrowck_generic_does_not_live_long_enough = - `{$kind}` does not live long enough - -borrowck_move_borrowed = - cannot move out of `{$desc}` beacause it is borrowed - -borrowck_var_does_not_need_mut = - variable does not need to be mutable - .suggestion = remove this `mut` - -borrowck_var_cannot_escape_closure = - captured variable cannot escape `FnMut` closure body - .note = `FnMut` closures only have access to their captured variables while they are executing... - .cannot_escape = ...therefore, they cannot allow references to captured variables to escape - -borrowck_var_here_defined = variable defined here - -borrowck_var_here_captured = variable captured here - -borrowck_closure_inferred_mut = inferred to be a `FnMut` closure - -borrowck_returned_closure_escaped = - returns a closure that contains a reference to a captured variable, which then escapes the closure body - -borrowck_returned_async_block_escaped = - returns an `async` block that contains a reference to a captured variable, which then escapes the closure body - -borrowck_returned_ref_escaped = - returns a reference to a captured variable which escapes the closure body - -borrowck_lifetime_constraints_error = - lifetime may not live long enough - -borrowck_returned_lifetime_wrong = - {$mir_def_name} was supposed to return data with lifetime `{$outlived_fr_name}` but it is returning data with lifetime `{$fr_name}` - -borrowck_returned_lifetime_short = - {$category_desc}requires that `{$free_region_name}` must outlive `{$outlived_fr_name}` - -borrowck_used_impl_require_static = - the used `impl` has a `'static` requirement - -borrowck_borrow_due_to_use_generator = - borrow occurs due to use in generator - -borrowck_use_due_to_use_generator = - use occurs due to use in generator - -borrowck_assign_due_to_use_generator = - assign occurs due to use in generator - -borrowck_assign_part_due_to_use_generator = - assign to part occurs due to use in generator - -borrowck_borrow_due_to_use_closure = - borrow occurs due to use in closure - -borrowck_use_due_to_use_closure = - use occurs due to use in closure - -borrowck_assign_due_to_use_closure = - assign occurs due to use in closure - -borrowck_assign_part_due_to_use_closure = - assign to part occurs due to use in closure - -borrowck_capture_immute = - capture is immutable because of use here - -borrowck_capture_mut = - capture is mutable because of use here - -borrowck_capture_move = - capture is moved because of use here - -borrowck_var_borrow_by_use_place_in_generator = - {$is_single_var -> - *[true] borrow occurs - [false] borrows occur - } due to use of {$place} in generator - -borrowck_var_borrow_by_use_place_in_closure = - {$is_single_var -> - *[true] borrow occurs - [false] borrows occur - } due to use of {$place} in closure - -borrowck_var_borrow_by_use_in_generator = - borrow occurs due to use in generator - -borrowck_var_borrow_by_use_in_closure = - borrow occurs due to use in closure - -borrowck_var_move_by_use_place_in_generator = - move occurs due to use of {$place} in generator - -borrowck_var_move_by_use_place_in_closure = - move occurs due to use of {$place} in closure - -borrowck_var_move_by_use_in_generator = - move occurs due to use in generator - -borrowck_var_move_by_use_in_closure = - move occurs due to use in closure - -borrowck_partial_var_move_by_use_in_generator = - variable {$is_partial -> - [true] partially moved - *[false] moved - } due to use in generator - -borrowck_partial_var_move_by_use_in_closure = - variable {$is_partial -> - [true] partially moved - *[false] moved - } due to use in closure - -borrowck_var_first_borrow_by_use_place_in_generator = - first borrow occurs due to use of {$place} in generator - -borrowck_var_first_borrow_by_use_place_in_closure = - first borrow occurs due to use of {$place} in closure - -borrowck_var_second_borrow_by_use_place_in_generator = - second borrow occurs due to use of {$place} in generator - -borrowck_var_second_borrow_by_use_place_in_closure = - second borrow occurs due to use of {$place} in closure - -borrowck_var_mutable_borrow_by_use_place_in_closure = - mutable borrow occurs due to use of {$place} in closure - -borrowck_cannot_move_when_borrowed = - cannot move out of {$place -> - [value] value - *[other] {$place} - } because it is borrowed - .label = borrow of {$borrow_place -> - [value] value - *[other] {$borrow_place} - } occurs here - .move_label = move out of {$value_place -> - [value] value - *[other] {$value_place} - } occurs here - -borrowck_opaque_type_non_generic_param = - expected generic {$kind} parameter, found `{$ty}` - .label = {STREQ($ty, "'static") -> - [true] cannot use static lifetime; use a bound lifetime instead or remove the lifetime parameter from the opaque type - *[other] this generic parameter must be used with a generic {$kind} parameter - } - -borrowck_moved_due_to_call = - {$place_name} {$is_partial -> - [true] partially moved - *[false] moved - } due to this {$is_loop_message -> - [true] call, in previous iteration of loop - *[false] call - } - -borrowck_moved_due_to_usage_in_operator = - {$place_name} {$is_partial -> - [true] partially moved - *[false] moved - } due to usage in {$is_loop_message -> - [true] operator, in previous iteration of loop - *[false] operator - } - -borrowck_moved_due_to_implicit_into_iter_call = - {$place_name} {$is_partial -> - [true] partially moved - *[false] moved - } due to this implicit call to {$is_loop_message -> - [true] `.into_iter()`, in previous iteration of loop - *[false] `.into_iter()` - } - -borrowck_moved_due_to_method_call = - {$place_name} {$is_partial -> - [true] partially moved - *[false] moved - } due to this method {$is_loop_message -> - [true] call, in previous iteration of loop - *[false] call - } - -borrowck_value_moved_here = - value {$is_partial -> - [true] partially moved - *[false] moved - } {$is_move_msg -> - [true] into closure here - *[false] here - }{$is_loop_message -> - [true] , in previous iteration of loop - *[false] {""} - } - -borrowck_consider_borrow_type_contents = - help: consider calling `.as_ref()` or `.as_mut()` to borrow the type's contents - -borrowck_moved_a_fn_once_in_call = - this value implements `FnOnce`, which causes it to be moved when called - -borrowck_calling_operator_moves_lhs = - calling this operator moves the left-hand side - -borrowck_func_take_self_moved_place = - `{$func}` takes ownership of the receiver `self`, which moves {$place_name} - -borrowck_suggest_iterate_over_slice = - consider iterating over a slice of the `{$ty}`'s content to avoid moving into the `for` loop - -borrowck_suggest_create_freash_reborrow = - consider reborrowing the `Pin` instead of moving it - -borrowck_value_capture_here = - value captured {$is_within -> - [true] here by generator - *[false] here - } - -borrowck_move_out_place_here = - {$place} is moved here - -borrowck_closure_invoked_twice = - closure cannot be invoked more than once because it moves the variable `{$place_name}` out of its environment - -borrowck_closure_moved_twice = - closure cannot be moved more than once as it is not `Copy` due to moving the variable `{$place_name}` out of its environment - -borrowck_ty_no_impl_copy = - {$is_partial_move -> - [true] partial move - *[false] move - } occurs because {$place} has type `{$ty}`, which does not implement the `Copy` trait From 1bcb0ec28cd169e1e80efffc824287287d374147 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Thu, 6 Apr 2023 00:36:36 -0700 Subject: [PATCH 029/228] `assume` value ranges in `transmute` Fixes #109958 --- compiler/rustc_codegen_ssa/src/mir/rvalue.rs | 63 ++++++- tests/codegen/intrinsics/transmute-niched.rs | 184 +++++++++++++++++++ tests/codegen/intrinsics/transmute.rs | 8 +- tests/codegen/transmute-scalar.rs | 14 +- 4 files changed, 253 insertions(+), 16 deletions(-) create mode 100644 tests/codegen/intrinsics/transmute-niched.rs diff --git a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs index d88226f5db053..e05d03d150fe3 100644 --- a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs +++ b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs @@ -12,6 +12,7 @@ use rustc_middle::mir::Operand; use rustc_middle::ty::cast::{CastTy, IntTy}; use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout}; use rustc_middle::ty::{self, adjustment::PointerCast, Instance, Ty, TyCtxt}; +use rustc_session::config::OptLevel; use rustc_span::source_map::{Span, DUMMY_SP}; use rustc_target::abi::{self, FIRST_VARIANT}; @@ -231,10 +232,16 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { (ScalarOrZst::Scalar(in_scalar), ScalarOrZst::Scalar(out_scalar)) if in_scalar.size(self.cx) == out_scalar.size(self.cx) => { + let operand_bty = bx.backend_type(operand.layout); let cast_bty = bx.backend_type(cast); - Some(OperandValue::Immediate( - self.transmute_immediate(bx, imm, in_scalar, out_scalar, cast_bty), - )) + Some(OperandValue::Immediate(self.transmute_immediate( + bx, + imm, + in_scalar, + operand_bty, + out_scalar, + cast_bty, + ))) } _ => None, } @@ -250,11 +257,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { && in_a.size(self.cx) == out_a.size(self.cx) && in_b.size(self.cx) == out_b.size(self.cx) { + let in_a_ibty = bx.scalar_pair_element_backend_type(operand.layout, 0, false); + let in_b_ibty = bx.scalar_pair_element_backend_type(operand.layout, 1, false); let out_a_ibty = bx.scalar_pair_element_backend_type(cast, 0, false); let out_b_ibty = bx.scalar_pair_element_backend_type(cast, 1, false); Some(OperandValue::Pair( - self.transmute_immediate(bx, imm_a, in_a, out_a, out_a_ibty), - self.transmute_immediate(bx, imm_b, in_b, out_b, out_b_ibty), + self.transmute_immediate(bx, imm_a, in_a, in_a_ibty, out_a, out_a_ibty), + self.transmute_immediate(bx, imm_b, in_b, in_b_ibty, out_b, out_b_ibty), )) } else { None @@ -273,6 +282,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx: &mut Bx, mut imm: Bx::Value, from_scalar: abi::Scalar, + from_backend_ty: Bx::Type, to_scalar: abi::Scalar, to_backend_ty: Bx::Type, ) -> Bx::Value { @@ -280,6 +290,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { use abi::Primitive::*; imm = bx.from_immediate(imm); + self.assume_scalar_range(bx, imm, from_scalar, from_backend_ty); imm = match (from_scalar.primitive(), to_scalar.primitive()) { (Int(..) | F32 | F64, Int(..) | F32 | F64) => bx.bitcast(imm, to_backend_ty), (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty), @@ -294,10 +305,52 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx.bitcast(int_imm, to_backend_ty) } }; + self.assume_scalar_range(bx, imm, to_scalar, to_backend_ty); imm = bx.to_immediate_scalar(imm, to_scalar); imm } + fn assume_scalar_range( + &self, + bx: &mut Bx, + imm: Bx::Value, + scalar: abi::Scalar, + backend_ty: Bx::Type, + ) { + if matches!(self.cx.sess().opts.optimize, OptLevel::No | OptLevel::Less) + || !matches!(scalar.primitive(), abi::Primitive::Int(..)) + || scalar.is_always_valid(self.cx) + { + return; + } + + let abi::WrappingRange { start, end } = scalar.valid_range(self.cx); + + if start <= end { + if start > 0 { + let low = bx.const_uint_big(backend_ty, start); + let cmp = bx.icmp(IntPredicate::IntUGE, imm, low); + bx.assume(cmp); + } + + let type_max = scalar.size(self.cx).unsigned_int_max(); + if end < type_max { + let high = bx.const_uint_big(backend_ty, end); + let cmp = bx.icmp(IntPredicate::IntULE, imm, high); + bx.assume(cmp); + } + } else { + let low = bx.const_uint_big(backend_ty, start); + let cmp_low = bx.icmp(IntPredicate::IntUGE, imm, low); + + let high = bx.const_uint_big(backend_ty, end); + let cmp_high = bx.icmp(IntPredicate::IntULE, imm, high); + + let or = bx.or(cmp_low, cmp_high); + bx.assume(or); + } + } + pub fn codegen_rvalue_unsized( &mut self, bx: &mut Bx, diff --git a/tests/codegen/intrinsics/transmute-niched.rs b/tests/codegen/intrinsics/transmute-niched.rs new file mode 100644 index 0000000000000..69e9b1d12062e --- /dev/null +++ b/tests/codegen/intrinsics/transmute-niched.rs @@ -0,0 +1,184 @@ +// revisions: OPT DBG +// [OPT] compile-flags: -C opt-level=3 -C no-prepopulate-passes +// [DBG] compile-flags: -C opt-level=0 -C no-prepopulate-passes +// only-64bit (so I don't need to worry about usize) +// min-llvm-version: 15.0 # this test assumes `ptr`s + +#![crate_type = "lib"] + +use std::mem::transmute; +use std::num::NonZeroU32; + +#[repr(u8)] +pub enum SmallEnum { + A = 10, + B = 11, + C = 12, +} + +// CHECK-LABEL: @check_to_enum( +#[no_mangle] +pub unsafe fn check_to_enum(x: i8) -> SmallEnum { + // OPT: %0 = icmp uge i8 %x, 10 + // OPT: call void @llvm.assume(i1 %0) + // OPT: %1 = icmp ule i8 %x, 12 + // OPT: call void @llvm.assume(i1 %1) + // DBG-NOT: icmp + // DBG-NOT: assume + // CHECK: ret i8 %x + + transmute(x) +} + +// CHECK-LABEL: @check_from_enum( +#[no_mangle] +pub unsafe fn check_from_enum(x: SmallEnum) -> i8 { + // OPT: %0 = icmp uge i8 %x, 10 + // OPT: call void @llvm.assume(i1 %0) + // OPT: %1 = icmp ule i8 %x, 12 + // OPT: call void @llvm.assume(i1 %1) + // DBG-NOT: icmp + // DBG-NOT: assume + // CHECK: ret i8 %x + + transmute(x) +} + +// CHECK-LABEL: @check_to_ordering( +#[no_mangle] +pub unsafe fn check_to_ordering(x: u8) -> std::cmp::Ordering { + // OPT: %0 = icmp uge i8 %x, -1 + // OPT: %1 = icmp ule i8 %x, 1 + // OPT: %2 = or i1 %0, %1 + // OPT: call void @llvm.assume(i1 %2) + // DBG-NOT: icmp + // DBG-NOT: assume + // CHECK: ret i8 %x + + transmute(x) +} + +// CHECK-LABEL: @check_from_ordering( +#[no_mangle] +pub unsafe fn check_from_ordering(x: std::cmp::Ordering) -> u8 { + // OPT: %0 = icmp uge i8 %x, -1 + // OPT: %1 = icmp ule i8 %x, 1 + // OPT: %2 = or i1 %0, %1 + // OPT: call void @llvm.assume(i1 %2) + // DBG-NOT: icmp + // DBG-NOT: assume + // CHECK: ret i8 %x + + transmute(x) +} + +#[repr(i32)] +pub enum Minus100ToPlus100 { + A = -100, + B = -90, + C = -80, + D = -70, + E = -60, + F = -50, + G = -40, + H = -30, + I = -20, + J = -10, + K = 0, + L = 10, + M = 20, + N = 30, + O = 40, + P = 50, + Q = 60, + R = 70, + S = 80, + T = 90, + U = 100, +} + +// CHECK-LABEL: @check_enum_from_char( +#[no_mangle] +pub unsafe fn check_enum_from_char(x: char) -> Minus100ToPlus100 { + // OPT: %0 = icmp ule i32 %x, 1114111 + // OPT: call void @llvm.assume(i1 %0) + // OPT: %1 = icmp uge i32 %x, -100 + // OPT: %2 = icmp ule i32 %x, 100 + // OPT: %3 = or i1 %1, %2 + // OPT: call void @llvm.assume(i1 %3) + // DBG-NOT: icmp + // DBG-NOT: assume + // CHECK: ret i32 %x + + transmute(x) +} + +// CHECK-LABEL: @check_enum_to_char( +#[no_mangle] +pub unsafe fn check_enum_to_char(x: Minus100ToPlus100) -> char { + // OPT: %0 = icmp uge i32 %x, -100 + // OPT: %1 = icmp ule i32 %x, 100 + // OPT: %2 = or i1 %0, %1 + // OPT: call void @llvm.assume(i1 %2) + // OPT: %3 = icmp ule i32 %x, 1114111 + // OPT: call void @llvm.assume(i1 %3) + // DBG-NOT: icmp + // DBG-NOT: assume + // CHECK: ret i32 %x + + transmute(x) +} + +// CHECK-LABEL: @check_swap_pair( +#[no_mangle] +pub unsafe fn check_swap_pair(x: (char, NonZeroU32)) -> (NonZeroU32, char) { + // OPT: %0 = icmp ule i32 %x.0, 1114111 + // OPT: call void @llvm.assume(i1 %0) + // OPT: %1 = icmp uge i32 %x.0, 1 + // OPT: call void @llvm.assume(i1 %1) + // OPT: %2 = icmp uge i32 %x.1, 1 + // OPT: call void @llvm.assume(i1 %2) + // OPT: %3 = icmp ule i32 %x.1, 1114111 + // OPT: call void @llvm.assume(i1 %3) + // DBG-NOT: icmp + // DBG-NOT: assume + // CHECK: %[[P1:.+]] = insertvalue { i32, i32 } poison, i32 %x.0, 0 + // CHECK: %[[P2:.+]] = insertvalue { i32, i32 } %[[P1]], i32 %x.1, 1 + // CHECK: ret { i32, i32 } %[[P2]] + + transmute(x) +} + +// CHECK-LABEL: @check_bool_from_ordering( +#[no_mangle] +pub unsafe fn check_bool_from_ordering(x: std::cmp::Ordering) -> bool { + // OPT: %0 = icmp uge i8 %x, -1 + // OPT: %1 = icmp ule i8 %x, 1 + // OPT: %2 = or i1 %0, %1 + // OPT: call void @llvm.assume(i1 %2) + // OPT: %3 = icmp ule i8 %x, 1 + // OPT: call void @llvm.assume(i1 %3) + // DBG-NOT: icmp + // DBG-NOT: assume + // CHECK: %[[R:.+]] = trunc i8 %x to i1 + // CHECK: ret i1 %[[R]] + + transmute(x) +} + +// CHECK-LABEL: @check_bool_to_ordering( +#[no_mangle] +pub unsafe fn check_bool_to_ordering(x: bool) -> std::cmp::Ordering { + // CHECK: %0 = zext i1 %x to i8 + // OPT: %1 = icmp ule i8 %0, 1 + // OPT: call void @llvm.assume(i1 %1) + // OPT: %2 = icmp uge i8 %0, -1 + // OPT: %3 = icmp ule i8 %0, 1 + // OPT: %4 = or i1 %2, %3 + // OPT: call void @llvm.assume(i1 %4) + // DBG-NOT: icmp + // DBG-NOT: assume + // CHECK: ret i8 %0 + + transmute(x) +} diff --git a/tests/codegen/intrinsics/transmute.rs b/tests/codegen/intrinsics/transmute.rs index 57f901c671992..51c000b82ea8a 100644 --- a/tests/codegen/intrinsics/transmute.rs +++ b/tests/codegen/intrinsics/transmute.rs @@ -169,8 +169,8 @@ pub unsafe fn check_aggregate_from_bool(x: bool) -> Aggregate8 { #[no_mangle] pub unsafe fn check_byte_to_bool(x: u8) -> bool { // CHECK-NOT: alloca - // CHECK: %0 = trunc i8 %x to i1 - // CHECK: ret i1 %0 + // CHECK: %[[R:.+]] = trunc i8 %x to i1 + // CHECK: ret i1 %[[R]] transmute(x) } @@ -178,8 +178,8 @@ pub unsafe fn check_byte_to_bool(x: u8) -> bool { #[no_mangle] pub unsafe fn check_byte_from_bool(x: bool) -> u8 { // CHECK-NOT: alloca - // CHECK: %0 = zext i1 %x to i8 - // CHECK: ret i8 %0 + // CHECK: %[[R:.+]] = zext i1 %x to i8 + // CHECK: ret i8 %[[R:.+]] transmute(x) } diff --git a/tests/codegen/transmute-scalar.rs b/tests/codegen/transmute-scalar.rs index af2cef472ec6a..a0894a505c7c6 100644 --- a/tests/codegen/transmute-scalar.rs +++ b/tests/codegen/transmute-scalar.rs @@ -1,4 +1,4 @@ -// compile-flags: -O -C no-prepopulate-passes +// compile-flags: -C opt-level=0 -C no-prepopulate-passes // min-llvm-version: 15.0 # this test assumes `ptr`s and thus no `pointercast`s #![crate_type = "lib"] @@ -10,7 +10,7 @@ // However, `bitcast`s and `ptrtoint`s and `inttoptr`s are still worth doing when // that allows us to avoid the `alloca`s entirely; see `rvalue_creates_operand`. -// CHECK-LABEL: define{{.*}}i32 @f32_to_bits(float noundef %x) +// CHECK-LABEL: define{{.*}}i32 @f32_to_bits(float %x) // CHECK: %0 = bitcast float %x to i32 // CHECK-NEXT: ret i32 %0 #[no_mangle] @@ -18,7 +18,7 @@ pub fn f32_to_bits(x: f32) -> u32 { unsafe { std::mem::transmute(x) } } -// CHECK-LABEL: define{{.*}}i8 @bool_to_byte(i1 noundef zeroext %b) +// CHECK-LABEL: define{{.*}}i8 @bool_to_byte(i1 zeroext %b) // CHECK: %0 = zext i1 %b to i8 // CHECK-NEXT: ret i8 %0 #[no_mangle] @@ -26,7 +26,7 @@ pub fn bool_to_byte(b: bool) -> u8 { unsafe { std::mem::transmute(b) } } -// CHECK-LABEL: define{{.*}}noundef zeroext i1 @byte_to_bool(i8 noundef %byte) +// CHECK-LABEL: define{{.*}}zeroext i1 @byte_to_bool(i8 %byte) // CHECK: %0 = trunc i8 %byte to i1 // CHECK-NEXT: ret i1 %0 #[no_mangle] @@ -34,14 +34,14 @@ pub unsafe fn byte_to_bool(byte: u8) -> bool { std::mem::transmute(byte) } -// CHECK-LABEL: define{{.*}}ptr @ptr_to_ptr(ptr noundef %p) +// CHECK-LABEL: define{{.*}}ptr @ptr_to_ptr(ptr %p) // CHECK: ret ptr %p #[no_mangle] pub fn ptr_to_ptr(p: *mut u16) -> *mut u8 { unsafe { std::mem::transmute(p) } } -// CHECK: define{{.*}}[[USIZE:i[0-9]+]] @ptr_to_int(ptr noundef %p) +// CHECK: define{{.*}}[[USIZE:i[0-9]+]] @ptr_to_int(ptr %p) // CHECK: %0 = ptrtoint ptr %p to [[USIZE]] // CHECK-NEXT: ret [[USIZE]] %0 #[no_mangle] @@ -49,7 +49,7 @@ pub fn ptr_to_int(p: *mut u16) -> usize { unsafe { std::mem::transmute(p) } } -// CHECK: define{{.*}}ptr @int_to_ptr([[USIZE]] noundef %i) +// CHECK: define{{.*}}ptr @int_to_ptr([[USIZE]] %i) // CHECK: %0 = inttoptr [[USIZE]] %i to ptr // CHECK-NEXT: ret ptr %0 #[no_mangle] From a77d39b5e2ac35357721e4d313fe271ae59164b7 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Thu, 6 Apr 2023 12:29:43 +0200 Subject: [PATCH 030/228] Enable flatten-format-args by default. --- compiler/rustc_session/src/options.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 631dd0a2146e8..8e8ad72ec8a3f 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1452,9 +1452,9 @@ options! { fewer_names: Option = (None, parse_opt_bool, [TRACKED], "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR) \ (default: no)"), - flatten_format_args: bool = (false, parse_bool, [TRACKED], + flatten_format_args: bool = (true, parse_bool, [TRACKED], "flatten nested format_args!() and literals into a simplified format_args!() call \ - (default: no)"), + (default: yes)"), force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED], "force all crates to be `rustc_private` unstable (default: no)"), fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED], From 8df1f41b9c11443a52050c653ac9d89ceea1cae3 Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Wed, 12 Apr 2023 22:53:38 +0200 Subject: [PATCH 031/228] fix false positives for `unused_parens` around unary and binary operations --- compiler/rustc_lint/src/unused.rs | 48 ++++++++++++------- .../issue-54538-unused-parens-lint.fixed | 8 ++++ .../unused/issue-54538-unused-parens-lint.rs | 8 ++++ .../issue-54538-unused-parens-lint.stderr | 36 +++++++------- 4 files changed, 64 insertions(+), 36 deletions(-) diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 1159d11e5c0c8..5df6ee4fdb9d0 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -569,36 +569,48 @@ trait UnusedDelimLint { } } - // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }` - let lhs_needs_parens = { + // Check if LHS needs parens to prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`. + { let mut innermost = inner; loop { innermost = match &innermost.kind { - ExprKind::Binary(_, lhs, _rhs) => lhs, + ExprKind::Binary(_op, lhs, _rhs) => lhs, ExprKind::Call(fn_, _params) => fn_, ExprKind::Cast(expr, _ty) => expr, ExprKind::Type(expr, _ty) => expr, ExprKind::Index(base, _subscript) => base, - _ => break false, + _ => break, }; if !classify::expr_requires_semi_to_be_stmt(innermost) { - break true; + return true; } } - }; + } - lhs_needs_parens - || (followed_by_block - && match &inner.kind { - ExprKind::Ret(_) - | ExprKind::Break(..) - | ExprKind::Yield(..) - | ExprKind::Yeet(..) => true, - ExprKind::Range(_lhs, Some(rhs), _limits) => { - matches!(rhs.kind, ExprKind::Block(..)) - } - _ => parser::contains_exterior_struct_lit(&inner), - }) + // Check if RHS needs parens to prevent false-positives in cases like `if (() == return) {}`. + if !followed_by_block { + return false; + } + let mut innermost = inner; + loop { + innermost = match &innermost.kind { + ExprKind::Unary(_op, expr) => expr, + ExprKind::Binary(_op, _lhs, rhs) => rhs, + ExprKind::AssignOp(_op, _lhs, rhs) => rhs, + ExprKind::Assign(_lhs, rhs, _span) => rhs, + + ExprKind::Ret(_) + | ExprKind::Break(..) + | ExprKind::Yield(..) + | ExprKind::Yeet(..) => return true, + + ExprKind::Range(_lhs, Some(rhs), _limits) => { + return matches!(rhs.kind, ExprKind::Block(..)); + } + + _ => return parser::contains_exterior_struct_lit(&inner), + } + } } fn emit_unused_delims_expr( diff --git a/tests/ui/lint/unused/issue-54538-unused-parens-lint.fixed b/tests/ui/lint/unused/issue-54538-unused-parens-lint.fixed index 71ebaea8ed2c1..9a1887017bb0d 100644 --- a/tests/ui/lint/unused/issue-54538-unused-parens-lint.fixed +++ b/tests/ui/lint/unused/issue-54538-unused-parens-lint.fixed @@ -32,6 +32,14 @@ fn _no_lint_yeet() -> Result<(), ()> { Ok(()) } +fn _no_lint_ops() { + #![allow(unreachable_code, irrefutable_let_patterns)] + if ((..{}) == ..{}) {} + if (!return) {} + loop { match (() = () = () = break {}) {} } + while let () = (*&mut false |= true && return) {} +} + // Don't lint in these cases (#64106). fn or_patterns_no_lint() { match Box::new(0) { diff --git a/tests/ui/lint/unused/issue-54538-unused-parens-lint.rs b/tests/ui/lint/unused/issue-54538-unused-parens-lint.rs index 28b662dd0242c..4fdd2b56b69ec 100644 --- a/tests/ui/lint/unused/issue-54538-unused-parens-lint.rs +++ b/tests/ui/lint/unused/issue-54538-unused-parens-lint.rs @@ -32,6 +32,14 @@ fn _no_lint_yeet() -> Result<(), ()> { Ok(()) } +fn _no_lint_ops() { + #![allow(unreachable_code, irrefutable_let_patterns)] + if ((..{}) == ..{}) {} + if (!return) {} + loop { match (() = () = () = break {}) {} } + while let () = (*&mut false |= true && return) {} +} + // Don't lint in these cases (#64106). fn or_patterns_no_lint() { match Box::new(0) { diff --git a/tests/ui/lint/unused/issue-54538-unused-parens-lint.stderr b/tests/ui/lint/unused/issue-54538-unused-parens-lint.stderr index a5e69e6d9385c..cfa4963d3b670 100644 --- a/tests/ui/lint/unused/issue-54538-unused-parens-lint.stderr +++ b/tests/ui/lint/unused/issue-54538-unused-parens-lint.stderr @@ -76,7 +76,7 @@ LL + let _ = |a: u8| 0; | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:56:12 + --> $DIR/issue-54538-unused-parens-lint.rs:64:12 | LL | if let (0 | 1) = 0 {} | ^ ^ @@ -88,7 +88,7 @@ LL + if let 0 | 1 = 0 {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:57:13 + --> $DIR/issue-54538-unused-parens-lint.rs:65:13 | LL | if let ((0 | 1),) = (0,) {} | ^ ^ @@ -100,7 +100,7 @@ LL + if let (0 | 1,) = (0,) {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:58:13 + --> $DIR/issue-54538-unused-parens-lint.rs:66:13 | LL | if let [(0 | 1)] = [0] {} | ^ ^ @@ -112,7 +112,7 @@ LL + if let [0 | 1] = [0] {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:59:16 + --> $DIR/issue-54538-unused-parens-lint.rs:67:16 | LL | if let 0 | (1 | 2) = 0 {} | ^ ^ @@ -124,7 +124,7 @@ LL + if let 0 | 1 | 2 = 0 {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:61:15 + --> $DIR/issue-54538-unused-parens-lint.rs:69:15 | LL | if let TS((0 | 1)) = TS(0) {} | ^ ^ @@ -136,7 +136,7 @@ LL + if let TS(0 | 1) = TS(0) {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:63:20 + --> $DIR/issue-54538-unused-parens-lint.rs:71:20 | LL | if let NS { f: (0 | 1) } = (NS { f: 0 }) {} | ^ ^ @@ -148,7 +148,7 @@ LL + if let NS { f: 0 | 1 } = (NS { f: 0 }) {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:73:9 + --> $DIR/issue-54538-unused-parens-lint.rs:81:9 | LL | (_) => {} | ^ ^ @@ -160,7 +160,7 @@ LL + _ => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:74:9 + --> $DIR/issue-54538-unused-parens-lint.rs:82:9 | LL | (y) => {} | ^ ^ @@ -172,7 +172,7 @@ LL + y => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:75:9 + --> $DIR/issue-54538-unused-parens-lint.rs:83:9 | LL | (ref r) => {} | ^ ^ @@ -184,7 +184,7 @@ LL + ref r => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:76:9 + --> $DIR/issue-54538-unused-parens-lint.rs:84:9 | LL | (e @ 1...2) => {} | ^ ^ @@ -196,7 +196,7 @@ LL + e @ 1...2 => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:82:9 + --> $DIR/issue-54538-unused-parens-lint.rs:90:9 | LL | (e @ &(1...2)) => {} | ^ ^ @@ -208,7 +208,7 @@ LL + e @ &(1...2) => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:83:10 + --> $DIR/issue-54538-unused-parens-lint.rs:91:10 | LL | &(_) => {} | ^ ^ @@ -220,7 +220,7 @@ LL + &_ => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:94:9 + --> $DIR/issue-54538-unused-parens-lint.rs:102:9 | LL | (_) => {} | ^ ^ @@ -232,7 +232,7 @@ LL + _ => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:95:9 + --> $DIR/issue-54538-unused-parens-lint.rs:103:9 | LL | (y) => {} | ^ ^ @@ -244,7 +244,7 @@ LL + y => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:96:9 + --> $DIR/issue-54538-unused-parens-lint.rs:104:9 | LL | (ref r) => {} | ^ ^ @@ -256,7 +256,7 @@ LL + ref r => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:97:9 + --> $DIR/issue-54538-unused-parens-lint.rs:105:9 | LL | (e @ 1..=2) => {} | ^ ^ @@ -268,7 +268,7 @@ LL + e @ 1..=2 => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:103:9 + --> $DIR/issue-54538-unused-parens-lint.rs:111:9 | LL | (e @ &(1..=2)) => {} | ^ ^ @@ -280,7 +280,7 @@ LL + e @ &(1..=2) => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:104:10 + --> $DIR/issue-54538-unused-parens-lint.rs:112:10 | LL | &(_) => {} | ^ ^ From 0d0949d87f00d677de679e25dc4ba374b68f8733 Mon Sep 17 00:00:00 2001 From: Lukas Markeffsky <@> Date: Wed, 12 Apr 2023 23:53:18 +0200 Subject: [PATCH 032/228] emit `unused_parens` for `break` if it is not immediately followed by a block --- compiler/rustc_lint/src/unused.rs | 10 +-- .../issue-54538-unused-parens-lint.fixed | 13 +++- .../unused/issue-54538-unused-parens-lint.rs | 13 +++- .../issue-54538-unused-parens-lint.stderr | 62 +++++++++++++------ 4 files changed, 69 insertions(+), 29 deletions(-) diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 5df6ee4fdb9d0..be7a651360184 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -599,10 +599,12 @@ trait UnusedDelimLint { ExprKind::AssignOp(_op, _lhs, rhs) => rhs, ExprKind::Assign(_lhs, rhs, _span) => rhs, - ExprKind::Ret(_) - | ExprKind::Break(..) - | ExprKind::Yield(..) - | ExprKind::Yeet(..) => return true, + ExprKind::Ret(_) | ExprKind::Yield(..) | ExprKind::Yeet(..) => return true, + + ExprKind::Break(_label, None) => return false, + ExprKind::Break(_label, Some(break_expr)) => { + return matches!(break_expr.kind, ExprKind::Block(..)); + } ExprKind::Range(_lhs, Some(rhs), _limits) => { return matches!(rhs.kind, ExprKind::Block(..)); diff --git a/tests/ui/lint/unused/issue-54538-unused-parens-lint.fixed b/tests/ui/lint/unused/issue-54538-unused-parens-lint.fixed index 9a1887017bb0d..9c52ca5577e4a 100644 --- a/tests/ui/lint/unused/issue-54538-unused-parens-lint.fixed +++ b/tests/ui/lint/unused/issue-54538-unused-parens-lint.fixed @@ -21,18 +21,18 @@ fn lint_on_top_level() { let _ = |a: u8| 0; //~ ERROR unnecessary parentheses around pattern } -fn _no_lint_attr() { +fn no_lint_attr() { let _x = #[allow(dead_code)] (1 + 2); } -fn _no_lint_yeet() -> Result<(), ()> { +fn no_lint_yeet() -> Result<(), ()> { #[allow(unreachable_code)] if (do yeet) {} Ok(()) } -fn _no_lint_ops() { +fn no_lint_ops() { #![allow(unreachable_code, irrefutable_let_patterns)] if ((..{}) == ..{}) {} if (!return) {} @@ -40,6 +40,13 @@ fn _no_lint_ops() { while let () = (*&mut false |= true && return) {} } +fn lint_break_if_not_followed_by_block() { + #![allow(unreachable_code)] + loop { if break {} } //~ ERROR unnecessary parentheses + loop { if break ({ println!("hello") }) {} } //~ ERROR unnecessary parentheses + loop { if (break { println!("hello") }) {} } +} + // Don't lint in these cases (#64106). fn or_patterns_no_lint() { match Box::new(0) { diff --git a/tests/ui/lint/unused/issue-54538-unused-parens-lint.rs b/tests/ui/lint/unused/issue-54538-unused-parens-lint.rs index 4fdd2b56b69ec..196ecf0c1bb85 100644 --- a/tests/ui/lint/unused/issue-54538-unused-parens-lint.rs +++ b/tests/ui/lint/unused/issue-54538-unused-parens-lint.rs @@ -21,18 +21,18 @@ fn lint_on_top_level() { let _ = |(a): u8| 0; //~ ERROR unnecessary parentheses around pattern } -fn _no_lint_attr() { +fn no_lint_attr() { let _x = #[allow(dead_code)] (1 + 2); } -fn _no_lint_yeet() -> Result<(), ()> { +fn no_lint_yeet() -> Result<(), ()> { #[allow(unreachable_code)] if (do yeet) {} Ok(()) } -fn _no_lint_ops() { +fn no_lint_ops() { #![allow(unreachable_code, irrefutable_let_patterns)] if ((..{}) == ..{}) {} if (!return) {} @@ -40,6 +40,13 @@ fn _no_lint_ops() { while let () = (*&mut false |= true && return) {} } +fn lint_break_if_not_followed_by_block() { + #![allow(unreachable_code)] + loop { if (break) {} } //~ ERROR unnecessary parentheses + loop { if (break ({ println!("hello") })) {} } //~ ERROR unnecessary parentheses + loop { if (break { println!("hello") }) {} } +} + // Don't lint in these cases (#64106). fn or_patterns_no_lint() { match Box::new(0) { diff --git a/tests/ui/lint/unused/issue-54538-unused-parens-lint.stderr b/tests/ui/lint/unused/issue-54538-unused-parens-lint.stderr index cfa4963d3b670..f916bba8194ff 100644 --- a/tests/ui/lint/unused/issue-54538-unused-parens-lint.stderr +++ b/tests/ui/lint/unused/issue-54538-unused-parens-lint.stderr @@ -75,8 +75,32 @@ LL - let _ = |(a): u8| 0; LL + let _ = |a: u8| 0; | +error: unnecessary parentheses around `if` condition + --> $DIR/issue-54538-unused-parens-lint.rs:45:15 + | +LL | loop { if (break) {} } + | ^ ^ + | +help: remove these parentheses + | +LL - loop { if (break) {} } +LL + loop { if break {} } + | + +error: unnecessary parentheses around `if` condition + --> $DIR/issue-54538-unused-parens-lint.rs:46:15 + | +LL | loop { if (break ({ println!("hello") })) {} } + | ^ ^ + | +help: remove these parentheses + | +LL - loop { if (break ({ println!("hello") })) {} } +LL + loop { if break ({ println!("hello") }) {} } + | + error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:64:12 + --> $DIR/issue-54538-unused-parens-lint.rs:71:12 | LL | if let (0 | 1) = 0 {} | ^ ^ @@ -88,7 +112,7 @@ LL + if let 0 | 1 = 0 {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:65:13 + --> $DIR/issue-54538-unused-parens-lint.rs:72:13 | LL | if let ((0 | 1),) = (0,) {} | ^ ^ @@ -100,7 +124,7 @@ LL + if let (0 | 1,) = (0,) {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:66:13 + --> $DIR/issue-54538-unused-parens-lint.rs:73:13 | LL | if let [(0 | 1)] = [0] {} | ^ ^ @@ -112,7 +136,7 @@ LL + if let [0 | 1] = [0] {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:67:16 + --> $DIR/issue-54538-unused-parens-lint.rs:74:16 | LL | if let 0 | (1 | 2) = 0 {} | ^ ^ @@ -124,7 +148,7 @@ LL + if let 0 | 1 | 2 = 0 {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:69:15 + --> $DIR/issue-54538-unused-parens-lint.rs:76:15 | LL | if let TS((0 | 1)) = TS(0) {} | ^ ^ @@ -136,7 +160,7 @@ LL + if let TS(0 | 1) = TS(0) {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:71:20 + --> $DIR/issue-54538-unused-parens-lint.rs:78:20 | LL | if let NS { f: (0 | 1) } = (NS { f: 0 }) {} | ^ ^ @@ -148,7 +172,7 @@ LL + if let NS { f: 0 | 1 } = (NS { f: 0 }) {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:81:9 + --> $DIR/issue-54538-unused-parens-lint.rs:88:9 | LL | (_) => {} | ^ ^ @@ -160,7 +184,7 @@ LL + _ => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:82:9 + --> $DIR/issue-54538-unused-parens-lint.rs:89:9 | LL | (y) => {} | ^ ^ @@ -172,7 +196,7 @@ LL + y => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:83:9 + --> $DIR/issue-54538-unused-parens-lint.rs:90:9 | LL | (ref r) => {} | ^ ^ @@ -184,7 +208,7 @@ LL + ref r => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:84:9 + --> $DIR/issue-54538-unused-parens-lint.rs:91:9 | LL | (e @ 1...2) => {} | ^ ^ @@ -196,7 +220,7 @@ LL + e @ 1...2 => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:90:9 + --> $DIR/issue-54538-unused-parens-lint.rs:97:9 | LL | (e @ &(1...2)) => {} | ^ ^ @@ -208,7 +232,7 @@ LL + e @ &(1...2) => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:91:10 + --> $DIR/issue-54538-unused-parens-lint.rs:98:10 | LL | &(_) => {} | ^ ^ @@ -220,7 +244,7 @@ LL + &_ => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:102:9 + --> $DIR/issue-54538-unused-parens-lint.rs:109:9 | LL | (_) => {} | ^ ^ @@ -232,7 +256,7 @@ LL + _ => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:103:9 + --> $DIR/issue-54538-unused-parens-lint.rs:110:9 | LL | (y) => {} | ^ ^ @@ -244,7 +268,7 @@ LL + y => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:104:9 + --> $DIR/issue-54538-unused-parens-lint.rs:111:9 | LL | (ref r) => {} | ^ ^ @@ -256,7 +280,7 @@ LL + ref r => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:105:9 + --> $DIR/issue-54538-unused-parens-lint.rs:112:9 | LL | (e @ 1..=2) => {} | ^ ^ @@ -268,7 +292,7 @@ LL + e @ 1..=2 => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:111:9 + --> $DIR/issue-54538-unused-parens-lint.rs:118:9 | LL | (e @ &(1..=2)) => {} | ^ ^ @@ -280,7 +304,7 @@ LL + e @ &(1..=2) => {} | error: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:112:10 + --> $DIR/issue-54538-unused-parens-lint.rs:119:10 | LL | &(_) => {} | ^ ^ @@ -291,5 +315,5 @@ LL - &(_) => {} LL + &_ => {} | -error: aborting due to 24 previous errors +error: aborting due to 26 previous errors From c155d5149fe49736cfb5b24eaa1c854b836019f3 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Thu, 13 Apr 2023 16:45:07 +0000 Subject: [PATCH 033/228] Implement `Send`/`Sync` for `CopyTaggedPtr` --- .../src/tagged_ptr/copy.rs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 02dcbd389dfdd..68d660f48b4da 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -253,6 +253,26 @@ where } } +// Safety: +// `CopyTaggedPtr` is semantically just `{ ptr: P, tag: T }`, as such +// it's ok to implement `Sync` as long as `P: Sync, T: Sync` +unsafe impl Sync for CopyTaggedPtr +where + P: Sync + Pointer, + T: Sync + Tag, +{ +} + +// Safety: +// `CopyTaggedPtr` is semantically just `{ ptr: P, tag: T }`, as such +// it's ok to implement `Send` as long as `P: Send, T: Send` +unsafe impl Send for CopyTaggedPtr +where + P: Send + Pointer, + T: Send + Tag, +{ +} + /// Test that `new` does not compile if there is not enough alignment for the /// tag in the pointer. /// From b59ec166adec6b1348421d7b558ad434351839be Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Fri, 14 Apr 2023 06:39:16 +0000 Subject: [PATCH 034/228] allow `repr(align = x)` on inherent methods --- compiler/rustc_passes/messages.ftl | 4 ++++ compiler/rustc_passes/src/check_attr.rs | 12 +++++++++--- compiler/rustc_passes/src/errors.rs | 4 ++-- tests/codegen/align-fn.rs | 9 +++++++++ 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index b354dca7cc44c..0d706996810f3 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -631,6 +631,10 @@ passes_attr_application_struct_enum_function_union = attribute should be applied to a struct, enum, function, or union .label = not a struct, enum, function, or union +passes_attr_application_struct_enum_function_inherent_method_union = + attribute should be applied to a struct, enum, function, inherent method, or union + .label = not a struct, enum, function, inherent method, or union + passes_transparent_incompatible = transparent {$target} cannot have other repr hints diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 80a93da2b45c4..a03c991d3bee0 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1728,7 +1728,9 @@ impl CheckAttrVisitor<'_> { } } sym::align => { - if let (Target::Fn, false) = (target, self.tcx.features().fn_align) { + if let (Target::Fn | Target::Method(MethodKind::Inherent), false) = + (target, self.tcx.features().fn_align) + { feature_err( &self.tcx.sess.parse_sess, sym::fn_align, @@ -1739,10 +1741,14 @@ impl CheckAttrVisitor<'_> { } match target { - Target::Struct | Target::Union | Target::Enum | Target::Fn => continue, + Target::Struct + | Target::Union + | Target::Enum + | Target::Fn + | Target::Method(MethodKind::Inherent) => continue, _ => { self.tcx.sess.emit_err( - errors::AttrApplication::StructEnumFunctionUnion { + errors::AttrApplication::StructEnumFunctionInherentMethodUnion { hint_span: hint.span(), span, }, diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 139ba8c967756..27039a2a5a21f 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1355,8 +1355,8 @@ pub enum AttrApplication { #[label] span: Span, }, - #[diag(passes_attr_application_struct_enum_function_union, code = "E0517")] - StructEnumFunctionUnion { + #[diag(passes_attr_application_struct_enum_function_inherent_method_union, code = "E0517")] + StructEnumFunctionInherentMethodUnion { #[primary_span] hint_span: Span, #[label] diff --git a/tests/codegen/align-fn.rs b/tests/codegen/align-fn.rs index c5886cf28081a..7238e7f53c368 100644 --- a/tests/codegen/align-fn.rs +++ b/tests/codegen/align-fn.rs @@ -7,3 +7,12 @@ #[no_mangle] #[repr(align(16))] pub fn fn_align() {} + +pub struct A; + +impl A { + // CHECK: align 16 + #[no_mangle] + #[repr(align(16))] + pub fn method_align(self) {} +} From 8d49e948a83faf8b88cd7f3327e9f65a7296a0f5 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Fri, 14 Apr 2023 11:04:20 +0000 Subject: [PATCH 035/228] Doc fixes from review --- .../rustc_data_structures/src/tagged_ptr.rs | 12 +++++++---- .../src/tagged_ptr/copy.rs | 21 ++++++++++++++++--- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index 2a74db1265499..750affa468b56 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -40,8 +40,8 @@ pub use drop::TaggedPtr; /// [`into_ptr`] must be valid for writes (and thus calling [`NonNull::as_mut`] /// on it must be safe). /// -/// The [`BITS`] constant must be correct. At least [`BITS`] least significant -/// bits, must be zero on all pointers returned from [`into_ptr`]. +/// The [`BITS`] constant must be correct. [`BITS`] least-significant bits, +/// must be zero on all pointers returned from [`into_ptr`]. /// /// For example, if the alignment of [`Self::Target`] is 2, then `BITS` should be 1. /// @@ -52,9 +52,12 @@ pub use drop::TaggedPtr; /// [`Self::Target`]: Deref::Target /// [`DerefMut`]: std::ops::DerefMut pub unsafe trait Pointer: Deref { - /// Number of unused (always zero) **least significant bits** in this + /// Number of unused (always zero) **least-significant bits** in this /// pointer, usually related to the pointees alignment. /// + /// For example if [`BITS`] = `2`, then given `ptr = Self::into_ptr(..)`, + /// `ptr.addr() & 0b11 == 0` must be true. + /// /// Most likely the value you want to use here is the following, unless /// your [`Self::Target`] type is unsized (e.g., `ty::List` in rustc) /// or your pointer is over/under aligned, in which case you'll need to @@ -71,6 +74,7 @@ pub unsafe trait Pointer: Deref { /// # } /// ``` /// + /// [`BITS`]: Pointer::BITS /// [`Self::Target`]: Deref::Target const BITS: usize; @@ -105,7 +109,7 @@ pub unsafe trait Pointer: Deref { /// /// The [`BITS`] constant must be correct. /// -/// No more than [`BITS`] least significant bits may be set in the returned usize. +/// No more than [`BITS`] least-significant bits may be set in the returned usize. /// /// [`BITS`]: Tag::BITS pub unsafe trait Tag: Copy { diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 68d660f48b4da..83dfdb0bd876d 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -33,7 +33,7 @@ where /// those are embeddable in instruction encoding, for example: /// /// ```asm - /// // (https://godbolt.org/z/jqcYPWEr3) + /// // () /// example::shift_read3: /// mov eax, dword ptr [8*rdi] /// ret @@ -49,7 +49,8 @@ where /// - `shift_read3` uses `<< 3` (the tag is in the most-significant bits) /// - `mask_read3` uses `& !0b111` (the tag is in the least-significant bits) /// - /// The shift approach thus produces less instructions and is likely faster. + /// The shift approach thus produces less instructions and is likely faster + /// (see ). /// /// Encoding diagram: /// ```text @@ -66,12 +67,21 @@ where tag_ghost: PhantomData, } +// Note that even though `CopyTaggedPtr` is only really expected to work with +// `P: Copy`, can't add `P: Copy` bound, because `CopyTaggedPtr` is used in the +// `TaggedPtr`'s implementation. impl CopyTaggedPtr where P: Pointer, T: Tag, { /// Tags `pointer` with `tag`. + /// + /// Note that this leaks `pointer`: it won't be dropped when + /// `CopyTaggedPtr` is dropped. If you have a pointer with a significant + /// drop, use [`TaggedPtr`] instead. + /// + /// [`TaggedPtr`]: crate::tagged_ptr::TaggedPtr pub fn new(pointer: P, tag: T) -> Self { Self { packed: Self::pack(P::into_ptr(pointer), tag), tag_ghost: PhantomData } } @@ -95,7 +105,8 @@ where let tag = self.packed.addr().get() >> Self::TAG_BIT_SHIFT; // Safety: - // + // The shift retrieves the original value from `T::into_usize`, + // satisfying `T::from_usize`'s preconditions. unsafe { T::from_usize(tag) } } @@ -152,6 +163,10 @@ where // // Semantically this is just `f(&self.pointer)` (where `self.pointer` // is non-packed original pointer). + // + // Note that even though `CopyTaggedPtr` is only really expected to + // work with `P: Copy`, we have to assume `P: ?Copy`, because + // `CopyTaggedPtr` is used in the `TaggedPtr`'s implementation. let ptr = unsafe { ManuallyDrop::new(P::from_ptr(self.pointer_raw())) }; f(&ptr) } From 251f662e4dc50055e8376f3c1bb8ac61ac7148c1 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Fri, 14 Apr 2023 11:09:26 +0000 Subject: [PATCH 036/228] Share `Tag2` impl between `CopyTaggedPtr` and `TaggedPtr` tests --- .../rustc_data_structures/src/tagged_ptr.rs | 29 +++++++++++++++++ .../src/tagged_ptr/copy/tests.rs | 32 +------------------ .../src/tagged_ptr/drop/tests.rs | 32 +------------------ 3 files changed, 31 insertions(+), 62 deletions(-) diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index 750affa468b56..14f282dcbebfe 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -232,3 +232,32 @@ pub const fn bits_for() -> usize { bits as usize } + +/// A tag type used in [`CopyTaggedPtr`] and [`TaggedPtr`] tests. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[cfg(test)] +enum Tag2 { + B00 = 0b00, + B01 = 0b01, + B10 = 0b10, + B11 = 0b11, +} + +#[cfg(test)] +unsafe impl Tag for Tag2 { + const BITS: usize = 2; + + fn into_usize(self) -> usize { + self as _ + } + + unsafe fn from_usize(tag: usize) -> Self { + match tag { + 0b00 => Tag2::B00, + 0b01 => Tag2::B01, + 0b10 => Tag2::B10, + 0b11 => Tag2::B11, + _ => unreachable!(), + } + } +} diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs index 77544f9c0324d..09e7b59fd64d5 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs @@ -1,36 +1,6 @@ use std::ptr; -use crate::tagged_ptr::{CopyTaggedPtr, Pointer, Tag}; - -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -enum Tag2 { - B00 = 0b00, - B01 = 0b01, - B10 = 0b10, - B11 = 0b11, -} - -unsafe impl Tag for Tag2 { - const BITS: usize = 2; - - fn into_usize(self) -> usize { - self as _ - } - - unsafe fn from_usize(tag: usize) -> Self { - const B00: usize = Tag2::B00 as _; - const B01: usize = Tag2::B01 as _; - const B10: usize = Tag2::B10 as _; - const B11: usize = Tag2::B11 as _; - match tag { - B00 => Tag2::B00, - B01 => Tag2::B01, - B10 => Tag2::B10, - B11 => Tag2::B11, - _ => unreachable!(), - } - } -} +use crate::tagged_ptr::{CopyTaggedPtr, Pointer, Tag, Tag2}; #[test] fn smoke() { diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs index 0c61cebaf7e6a..2c17d678d3aa0 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop/tests.rs @@ -1,36 +1,6 @@ use std::{ptr, sync::Arc}; -use crate::tagged_ptr::{Pointer, Tag, TaggedPtr}; - -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -enum Tag2 { - B00 = 0b00, - B01 = 0b01, - B10 = 0b10, - B11 = 0b11, -} - -unsafe impl Tag for Tag2 { - const BITS: usize = 2; - - fn into_usize(self) -> usize { - self as _ - } - - unsafe fn from_usize(tag: usize) -> Self { - const B00: usize = Tag2::B00 as _; - const B01: usize = Tag2::B01 as _; - const B10: usize = Tag2::B10 as _; - const B11: usize = Tag2::B11 as _; - match tag { - B00 => Tag2::B00, - B01 => Tag2::B01, - B10 => Tag2::B10, - B11 => Tag2::B11, - _ => unreachable!(), - } - } -} +use crate::tagged_ptr::{Pointer, Tag, Tag2, TaggedPtr}; #[test] fn smoke() { From 36f5918bf169a7ab5ae24a5aad12dd6ecd20b8c4 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Fri, 14 Apr 2023 11:59:53 +0000 Subject: [PATCH 037/228] Test `CopyTaggedPtr`'s `HashStable` impl --- .../rustc_data_structures/src/tagged_ptr.rs | 7 +++++++ .../src/tagged_ptr/copy/tests.rs | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index 14f282dcbebfe..1fc5dad1d95b4 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -261,3 +261,10 @@ unsafe impl Tag for Tag2 { } } } + +#[cfg(test)] +impl crate::stable_hasher::HashStable for Tag2 { + fn hash_stable(&self, hcx: &mut HCX, hasher: &mut crate::stable_hasher::StableHasher) { + (*self as u8).hash_stable(hcx, hasher); + } +} diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs index 09e7b59fd64d5..bfcc2e603de43 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy/tests.rs @@ -1,5 +1,6 @@ use std::ptr; +use crate::stable_hasher::{HashStable, StableHasher}; use crate::tagged_ptr::{CopyTaggedPtr, Pointer, Tag, Tag2}; #[test] @@ -25,6 +26,24 @@ fn smoke() { assert!(ptr::eq(copy.pointer(), reference)); } +#[test] +fn stable_hash_hashes_as_tuple() { + let hash_packed = { + let mut hasher = StableHasher::new(); + tag_ptr(&12, Tag2::B11).hash_stable(&mut (), &mut hasher); + + hasher.finalize() + }; + + let hash_tupled = { + let mut hasher = StableHasher::new(); + (&12, Tag2::B11).hash_stable(&mut (), &mut hasher); + hasher.finalize() + }; + + assert_eq!(hash_packed, hash_tupled); +} + /// Helper to create tagged pointers without specifying `COMPARE_PACKED` if it does not matter. fn tag_ptr(ptr: P, tag: T) -> CopyTaggedPtr { CopyTaggedPtr::new(ptr, tag) From 014c6f208e59534cf36b11fdf43f8c90a304073f Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Fri, 14 Apr 2023 12:29:10 +0000 Subject: [PATCH 038/228] Use `ptr::Alignment` for extra coolness points --- compiler/rustc_data_structures/src/aligned.rs | 10 +++---- compiler/rustc_data_structures/src/lib.rs | 1 + .../rustc_data_structures/src/tagged_ptr.rs | 28 ++++++++----------- .../src/tagged_ptr/copy.rs | 4 +-- .../src/tagged_ptr/drop.rs | 2 +- compiler/rustc_middle/src/lib.rs | 1 + compiler/rustc_middle/src/ty/list.rs | 6 ++-- compiler/rustc_middle/src/ty/mod.rs | 4 ++- 8 files changed, 27 insertions(+), 29 deletions(-) diff --git a/compiler/rustc_data_structures/src/aligned.rs b/compiler/rustc_data_structures/src/aligned.rs index 2d0adfe2ae35b..7ac073539fb4b 100644 --- a/compiler/rustc_data_structures/src/aligned.rs +++ b/compiler/rustc_data_structures/src/aligned.rs @@ -1,10 +1,10 @@ -use std::mem; +use std::ptr::Alignment; /// Returns the ABI-required minimum alignment of a type in bytes. /// /// This is equivalent to [`mem::align_of`], but also works for some unsized /// types (e.g. slices or rustc's `List`s). -pub const fn align_of() -> usize { +pub const fn align_of() -> Alignment { T::ALIGN } @@ -19,13 +19,13 @@ pub const fn align_of() -> usize { /// [`mem::align_of()`]: mem::align_of pub unsafe trait Aligned { /// Alignment of `Self`. - const ALIGN: usize; + const ALIGN: Alignment; } unsafe impl Aligned for T { - const ALIGN: usize = mem::align_of::(); + const ALIGN: Alignment = Alignment::of::(); } unsafe impl Aligned for [T] { - const ALIGN: usize = mem::align_of::(); + const ALIGN: Alignment = Alignment::of::(); } diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index ea1f71d7115ca..7768e0fdeb13b 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -30,6 +30,7 @@ #![feature(lint_reasons)] #![feature(unwrap_infallible)] #![feature(strict_provenance)] +#![feature(ptr_alignment_type)] #![allow(rustc::default_hash_types)] #![allow(rustc::potential_query_instability)] #![deny(rustc::untranslatable_diagnostic)] diff --git a/compiler/rustc_data_structures/src/tagged_ptr.rs b/compiler/rustc_data_structures/src/tagged_ptr.rs index 1fc5dad1d95b4..c26bffac67823 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr.rs @@ -70,13 +70,13 @@ pub unsafe trait Pointer: Deref { /// # struct T; /// # impl Deref for T { type Target = u8; fn deref(&self) -> &u8 { &0 } } /// # impl T { - /// const BITS: usize = bits_for::<::Target>(); + /// const BITS: u32 = bits_for::<::Target>(); /// # } /// ``` /// /// [`BITS`]: Pointer::BITS /// [`Self::Target`]: Deref::Target - const BITS: usize; + const BITS: u32; /// Turns this pointer into a raw, non-null pointer. /// @@ -118,7 +118,7 @@ pub unsafe trait Tag: Copy { /// value. /// /// [`into_usize`]: Tag::into_usize - const BITS: usize; + const BITS: u32; /// Turns this tag into an integer. /// @@ -142,7 +142,7 @@ pub unsafe trait Tag: Copy { } unsafe impl Pointer for Box { - const BITS: usize = bits_for::(); + const BITS: u32 = bits_for::(); #[inline] fn into_ptr(self) -> NonNull { @@ -158,7 +158,7 @@ unsafe impl Pointer for Box { } unsafe impl Pointer for Rc { - const BITS: usize = bits_for::(); + const BITS: u32 = bits_for::(); #[inline] fn into_ptr(self) -> NonNull { @@ -174,7 +174,7 @@ unsafe impl Pointer for Rc { } unsafe impl Pointer for Arc { - const BITS: usize = bits_for::(); + const BITS: u32 = bits_for::(); #[inline] fn into_ptr(self) -> NonNull { @@ -190,7 +190,7 @@ unsafe impl Pointer for Arc { } unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a T { - const BITS: usize = bits_for::(); + const BITS: u32 = bits_for::(); #[inline] fn into_ptr(self) -> NonNull { @@ -206,7 +206,7 @@ unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a T { } unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a mut T { - const BITS: usize = bits_for::(); + const BITS: u32 = bits_for::(); #[inline] fn into_ptr(self) -> NonNull { @@ -223,14 +223,8 @@ unsafe impl<'a, T: 'a + ?Sized + Aligned> Pointer for &'a mut T { /// Returns the number of bits available for use for tags in a pointer to `T` /// (this is based on `T`'s alignment). -pub const fn bits_for() -> usize { - let bits = crate::aligned::align_of::().trailing_zeros(); - - // This is a replacement for `.try_into().unwrap()` unavailable in `const` - // (it's fine to make an assert here, since this is only called in compile time) - assert!((bits as u128) < usize::MAX as u128); - - bits as usize +pub const fn bits_for() -> u32 { + crate::aligned::align_of::().as_nonzero().trailing_zeros() } /// A tag type used in [`CopyTaggedPtr`] and [`TaggedPtr`] tests. @@ -245,7 +239,7 @@ enum Tag2 { #[cfg(test)] unsafe impl Tag for Tag2 { - const BITS: usize = 2; + const BITS: u32 = 2; fn into_usize(self) -> usize { self as _ diff --git a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs index 83dfdb0bd876d..691e92f196a26 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/copy.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/copy.rs @@ -116,7 +116,7 @@ where self.packed = Self::pack(self.pointer_raw(), tag); } - const TAG_BIT_SHIFT: usize = usize::BITS as usize - T::BITS; + const TAG_BIT_SHIFT: u32 = usize::BITS - T::BITS; const ASSERTION: () = { assert!(T::BITS <= P::BITS) }; /// Pack pointer `ptr` that comes from [`P::into_ptr`] with a `tag`, @@ -298,7 +298,7 @@ where /// enum Tag2 { B00 = 0b00, B01 = 0b01, B10 = 0b10, B11 = 0b11 }; /// /// unsafe impl Tag for Tag2 { -/// const BITS: usize = 2; +/// const BITS: u32 = 2; /// /// fn into_usize(self) -> usize { todo!() } /// unsafe fn from_usize(tag: usize) -> Self { todo!() } diff --git a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs index 6ca6c7d1283b4..d418c06b7ebb4 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/drop.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/drop.rs @@ -150,7 +150,7 @@ where /// enum Tag2 { B00 = 0b00, B01 = 0b01, B10 = 0b10, B11 = 0b11 }; /// /// unsafe impl Tag for Tag2 { -/// const BITS: usize = 2; +/// const BITS: u32 = 2; /// /// fn into_usize(self) -> usize { todo!() } /// unsafe fn from_usize(tag: usize) -> Self { todo!() } diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index b4edb02f6c48d..51ed66dbafcc4 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -59,6 +59,7 @@ #![feature(result_option_inspect)] #![feature(const_option)] #![feature(trait_alias)] +#![feature(ptr_alignment_type)] #![recursion_limit = "512"] #![allow(rustc::potential_query_instability)] diff --git a/compiler/rustc_middle/src/ty/list.rs b/compiler/rustc_middle/src/ty/list.rs index 590beef7f7d42..30f036e471c42 100644 --- a/compiler/rustc_middle/src/ty/list.rs +++ b/compiler/rustc_middle/src/ty/list.rs @@ -1,5 +1,5 @@ use crate::arena::Arena; -use rustc_data_structures::aligned::Aligned; +use rustc_data_structures::aligned::{align_of, Aligned}; use rustc_serialize::{Encodable, Encoder}; use std::alloc::Layout; use std::cmp::Ordering; @@ -203,13 +203,13 @@ unsafe impl Sync for List {} // Layouts of `Equivalent` and `List` are the same, modulo opaque tail, // thus aligns of `Equivalent` and `List` must be the same. unsafe impl Aligned for List { - const ALIGN: usize = { + const ALIGN: ptr::Alignment = { #[repr(C)] struct Equivalent { _len: usize, _data: [T; 0], } - mem::align_of::>() + align_of::>() }; } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index c856bb25e1474..3d47f56d03122 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1626,7 +1626,8 @@ struct ParamTag { } unsafe impl rustc_data_structures::tagged_ptr::Tag for ParamTag { - const BITS: usize = 2; + const BITS: u32 = 2; + #[inline] fn into_usize(self) -> usize { match self { @@ -1636,6 +1637,7 @@ unsafe impl rustc_data_structures::tagged_ptr::Tag for ParamTag { Self { reveal: traits::Reveal::All, constness: hir::Constness::Const } => 3, } } + #[inline] unsafe fn from_usize(ptr: usize) -> Self { match ptr { From 5571dd061dac07644b9d9a3e799deefbd9971496 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Fri, 14 Apr 2023 13:04:58 +0000 Subject: [PATCH 039/228] fix broken intradoclinks --- compiler/rustc_data_structures/src/aligned.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_data_structures/src/aligned.rs b/compiler/rustc_data_structures/src/aligned.rs index 7ac073539fb4b..0e5ecfd9bff6e 100644 --- a/compiler/rustc_data_structures/src/aligned.rs +++ b/compiler/rustc_data_structures/src/aligned.rs @@ -4,6 +4,8 @@ use std::ptr::Alignment; /// /// This is equivalent to [`mem::align_of`], but also works for some unsized /// types (e.g. slices or rustc's `List`s). +/// +/// [`mem::align_of`]: std::mem::align_of pub const fn align_of() -> Alignment { T::ALIGN } @@ -16,7 +18,7 @@ pub const fn align_of() -> Alignment { /// is [`mem::align_of()`], for unsized types it depends on the type, for /// example `[T]` has alignment of `T`. /// -/// [`mem::align_of()`]: mem::align_of +/// [`mem::align_of()`]: std::mem::align_of pub unsafe trait Aligned { /// Alignment of `Self`. const ALIGN: Alignment; From 7a07c749a5d424bad109c8e1601257e7406fe9ae Mon Sep 17 00:00:00 2001 From: Adam Sunderland Date: Fri, 14 Apr 2023 17:02:45 -0400 Subject: [PATCH 040/228] Correct default value for default-linker-libraries This setting is false by default according to rustc code here: https://github.com/rust-lang/rust/blob/master/compiler/rustc_session/src/options.rs#L1236 I tested on a project and confirmed that setting this to false has no effect, the linker flag still appears. Setting it to true removes the linker flag. --- src/doc/rustc/src/codegen-options/index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/doc/rustc/src/codegen-options/index.md b/src/doc/rustc/src/codegen-options/index.md index 62347f169a5eb..d7c6a884fc8fb 100644 --- a/src/doc/rustc/src/codegen-options/index.md +++ b/src/doc/rustc/src/codegen-options/index.md @@ -84,8 +84,8 @@ Note: The [`-g` flag][option-g-debug] is an alias for `-C debuginfo=2`. This flag controls whether or not the linker includes its default libraries. It takes one of the following values: -* `y`, `yes`, `on`, `true` or no value: include default libraries (the default). -* `n`, `no`, `off` or `false`: exclude default libraries. +* `y`, `yes`, `on`, `true`: include default libraries. +* `n`, `no`, `off` or `false` or no value: exclude default libraries (the default). For example, for gcc flavor linkers, this issues the `-nodefaultlibs` flag to the linker. From 32f6e7a38ebc635493f83054f7826140798a1c6c Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sun, 16 Apr 2023 13:47:27 +1000 Subject: [PATCH 041/228] Remove `EnumTypeTraversalImpl`. I suspect this macro was around before `TypeFoldable`/`TypeVisitable` were derivable. But now it's only used for two types, `Result` and `Option`. Removing the macro and implementing the traits for those types by hand makes the code much simpler. --- compiler/rustc_type_ir/src/macros.rs | 141 ------------------ .../rustc_type_ir/src/structural_impls.rs | 58 ++++--- 2 files changed, 34 insertions(+), 165 deletions(-) diff --git a/compiler/rustc_type_ir/src/macros.rs b/compiler/rustc_type_ir/src/macros.rs index 6c181039730b7..8c3cb22832299 100644 --- a/compiler/rustc_type_ir/src/macros.rs +++ b/compiler/rustc_type_ir/src/macros.rs @@ -33,144 +33,3 @@ macro_rules! TrivialTypeTraversalImpls { )+ }; } - -macro_rules! EnumTypeTraversalImpl { - (impl<$($p:tt),*> TypeFoldable<$tcx:tt> for $s:path { - $($variants:tt)* - } $(where $($wc:tt)*)*) => { - impl<$($p),*> $crate::fold::TypeFoldable<$tcx> for $s - $(where $($wc)*)* - { - fn try_fold_with>( - self, - folder: &mut V, - ) -> ::std::result::Result { - EnumTypeTraversalImpl!(@FoldVariants(self, folder) input($($variants)*) output()) - } - } - }; - - (impl<$($p:tt),*> TypeVisitable<$tcx:tt> for $s:path { - $($variants:tt)* - } $(where $($wc:tt)*)*) => { - impl<$($p),*> $crate::visit::TypeVisitable<$tcx> for $s - $(where $($wc)*)* - { - fn visit_with>( - &self, - visitor: &mut V, - ) -> ::std::ops::ControlFlow { - EnumTypeTraversalImpl!(@VisitVariants(self, visitor) input($($variants)*) output()) - } - } - }; - - (@FoldVariants($this:expr, $folder:expr) input() output($($output:tt)*)) => { - Ok(match $this { - $($output)* - }) - }; - - (@FoldVariants($this:expr, $folder:expr) - input( ($variant:path) ( $($variant_arg:ident),* ) , $($input:tt)*) - output( $($output:tt)*) ) => { - EnumTypeTraversalImpl!( - @FoldVariants($this, $folder) - input($($input)*) - output( - $variant ( $($variant_arg),* ) => { - $variant ( - $($crate::fold::TypeFoldable::try_fold_with($variant_arg, $folder)?),* - ) - } - $($output)* - ) - ) - }; - - (@FoldVariants($this:expr, $folder:expr) - input( ($variant:path) { $($variant_arg:ident),* $(,)? } , $($input:tt)*) - output( $($output:tt)*) ) => { - EnumTypeTraversalImpl!( - @FoldVariants($this, $folder) - input($($input)*) - output( - $variant { $($variant_arg),* } => { - $variant { - $($variant_arg: $crate::fold::TypeFoldable::fold_with( - $variant_arg, $folder - )?),* } - } - $($output)* - ) - ) - }; - - (@FoldVariants($this:expr, $folder:expr) - input( ($variant:path), $($input:tt)*) - output( $($output:tt)*) ) => { - EnumTypeTraversalImpl!( - @FoldVariants($this, $folder) - input($($input)*) - output( - $variant => { $variant } - $($output)* - ) - ) - }; - - (@VisitVariants($this:expr, $visitor:expr) input() output($($output:tt)*)) => { - match $this { - $($output)* - } - }; - - (@VisitVariants($this:expr, $visitor:expr) - input( ($variant:path) ( $($variant_arg:ident),* ) , $($input:tt)*) - output( $($output:tt)*) ) => { - EnumTypeTraversalImpl!( - @VisitVariants($this, $visitor) - input($($input)*) - output( - $variant ( $($variant_arg),* ) => { - $($crate::visit::TypeVisitable::visit_with( - $variant_arg, $visitor - )?;)* - ::std::ops::ControlFlow::Continue(()) - } - $($output)* - ) - ) - }; - - (@VisitVariants($this:expr, $visitor:expr) - input( ($variant:path) { $($variant_arg:ident),* $(,)? } , $($input:tt)*) - output( $($output:tt)*) ) => { - EnumTypeTraversalImpl!( - @VisitVariants($this, $visitor) - input($($input)*) - output( - $variant { $($variant_arg),* } => { - $($crate::visit::TypeVisitable::visit_with( - $variant_arg, $visitor - )?;)* - ::std::ops::ControlFlow::Continue(()) - } - $($output)* - ) - ) - }; - - (@VisitVariants($this:expr, $visitor:expr) - input( ($variant:path), $($input:tt)*) - output( $($output:tt)*) ) => { - EnumTypeTraversalImpl!( - @VisitVariants($this, $visitor) - input($($input)*) - output( - $variant => { ::std::ops::ControlFlow::Continue(()) } - $($output)* - ) - ) - }; -} diff --git a/compiler/rustc_type_ir/src/structural_impls.rs b/compiler/rustc_type_ir/src/structural_impls.rs index 3ebe241042f25..c90c86b7690de 100644 --- a/compiler/rustc_type_ir/src/structural_impls.rs +++ b/compiler/rustc_type_ir/src/structural_impls.rs @@ -70,30 +70,40 @@ impl, B: TypeVisitable, C: TypeVisitable> } } -EnumTypeTraversalImpl! { - impl TypeFoldable for Option { - (Some)(a), - (None), - } where I: Interner, T: TypeFoldable -} -EnumTypeTraversalImpl! { - impl TypeVisitable for Option { - (Some)(a), - (None), - } where I: Interner, T: TypeVisitable -} - -EnumTypeTraversalImpl! { - impl TypeFoldable for Result { - (Ok)(a), - (Err)(a), - } where I: Interner, T: TypeFoldable, E: TypeFoldable, -} -EnumTypeTraversalImpl! { - impl TypeVisitable for Result { - (Ok)(a), - (Err)(a), - } where I: Interner, T: TypeVisitable, E: TypeVisitable, +impl> TypeFoldable for Option { + fn try_fold_with>(self, folder: &mut F) -> Result { + Ok(match self { + Some(v) => Some(v.try_fold_with(folder)?), + None => None, + }) + } +} + +impl> TypeVisitable for Option { + fn visit_with>(&self, visitor: &mut V) -> ControlFlow { + match self { + Some(v) => v.visit_with(visitor), + None => ControlFlow::Continue(()), + } + } +} + +impl, E: TypeFoldable> TypeFoldable for Result { + fn try_fold_with>(self, folder: &mut F) -> Result { + Ok(match self { + Ok(v) => Ok(v.try_fold_with(folder)?), + Err(e) => Err(e.try_fold_with(folder)?), + }) + } +} + +impl, E: TypeVisitable> TypeVisitable for Result { + fn visit_with>(&self, visitor: &mut V) -> ControlFlow { + match self { + Ok(v) => v.visit_with(visitor), + Err(e) => e.visit_with(visitor), + } + } } impl> TypeFoldable for Rc { From d2b5a64579aace20b1288f346787d0feb76e3742 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sun, 16 Apr 2023 14:01:43 +1000 Subject: [PATCH 042/228] Simplify `CloneLiftImpls` and `TrivialTypeTraversalImpls`. They both allow for a lifetime other than `'tcx`, but this isn't needed. --- compiler/rustc_middle/src/infer/canonical.rs | 6 ++-- compiler/rustc_middle/src/macros.rs | 34 +++++-------------- compiler/rustc_middle/src/mir/mod.rs | 4 +-- .../rustc_middle/src/mir/type_foldable.rs | 4 +-- compiler/rustc_middle/src/ty/context.rs | 9 +++-- .../rustc_middle/src/ty/structural_impls.rs | 4 +-- 6 files changed, 20 insertions(+), 41 deletions(-) diff --git a/compiler/rustc_middle/src/infer/canonical.rs b/compiler/rustc_middle/src/infer/canonical.rs index b5b712c367d08..bec8e7565a463 100644 --- a/compiler/rustc_middle/src/infer/canonical.rs +++ b/compiler/rustc_middle/src/infer/canonical.rs @@ -400,10 +400,8 @@ pub type QueryOutlivesConstraint<'tcx> = (ty::OutlivesPredicate, Region<'tcx>>, ConstraintCategory<'tcx>); TrivialTypeTraversalAndLiftImpls! { - for <'tcx> { - crate::infer::canonical::Certainty, - crate::infer::canonical::CanonicalTyVarKind, - } + crate::infer::canonical::Certainty, + crate::infer::canonical::CanonicalTyVarKind, } impl<'tcx> CanonicalVarValues<'tcx> { diff --git a/compiler/rustc_middle/src/macros.rs b/compiler/rustc_middle/src/macros.rs index 89014f62d4d69..cd1c6c330bc1e 100644 --- a/compiler/rustc_middle/src/macros.rs +++ b/compiler/rustc_middle/src/macros.rs @@ -43,34 +43,26 @@ macro_rules! span_bug { #[macro_export] macro_rules! CloneLiftImpls { - (for <$tcx:lifetime> { $($ty:ty,)+ }) => { + ($($ty:ty,)+) => { $( - impl<$tcx> $crate::ty::Lift<$tcx> for $ty { + impl<'tcx> $crate::ty::Lift<'tcx> for $ty { type Lifted = Self; - fn lift_to_tcx(self, _: $crate::ty::TyCtxt<$tcx>) -> Option { + fn lift_to_tcx(self, _: $crate::ty::TyCtxt<'tcx>) -> Option { Some(self) } } )+ }; - - ($($ty:ty,)+) => { - CloneLiftImpls! { - for <'tcx> { - $($ty,)+ - } - } - }; } /// Used for types that are `Copy` and which **do not care arena /// allocated data** (i.e., don't need to be folded). #[macro_export] macro_rules! TrivialTypeTraversalImpls { - (for <$tcx:lifetime> { $($ty:ty,)+ }) => { + ($($ty:ty,)+) => { $( - impl<$tcx> $crate::ty::fold::TypeFoldable<$crate::ty::TyCtxt<$tcx>> for $ty { - fn try_fold_with>>( + impl<'tcx> $crate::ty::fold::TypeFoldable<$crate::ty::TyCtxt<'tcx>> for $ty { + fn try_fold_with>>( self, _: &mut F, ) -> ::std::result::Result { @@ -78,7 +70,7 @@ macro_rules! TrivialTypeTraversalImpls { } #[inline] - fn fold_with>>( + fn fold_with>>( self, _: &mut F, ) -> Self { @@ -86,9 +78,9 @@ macro_rules! TrivialTypeTraversalImpls { } } - impl<$tcx> $crate::ty::visit::TypeVisitable<$crate::ty::TyCtxt<$tcx>> for $ty { + impl<'tcx> $crate::ty::visit::TypeVisitable<$crate::ty::TyCtxt<'tcx>> for $ty { #[inline] - fn visit_with>>( + fn visit_with>>( &self, _: &mut F) -> ::std::ops::ControlFlow @@ -98,14 +90,6 @@ macro_rules! TrivialTypeTraversalImpls { } )+ }; - - ($($ty:ty,)+) => { - TrivialTypeTraversalImpls! { - for<'tcx> { - $($ty,)+ - } - } - }; } #[macro_export] diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 2ea8602af12a1..f985aae9a2255 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -714,9 +714,7 @@ pub enum BindingForm<'tcx> { } TrivialTypeTraversalAndLiftImpls! { - for<'tcx> { - BindingForm<'tcx>, - } + BindingForm<'tcx>, } mod binding_form_impl { diff --git a/compiler/rustc_middle/src/mir/type_foldable.rs b/compiler/rustc_middle/src/mir/type_foldable.rs index 9881583214eb4..ace856b9f95e0 100644 --- a/compiler/rustc_middle/src/mir/type_foldable.rs +++ b/compiler/rustc_middle/src/mir/type_foldable.rs @@ -25,9 +25,7 @@ TrivialTypeTraversalAndLiftImpls! { } TrivialTypeTraversalImpls! { - for <'tcx> { - ConstValue<'tcx>, - } + ConstValue<'tcx>, } impl<'tcx> TypeFoldable> for &'tcx [InlineAsmTemplatePiece] { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 63f7cc2ee7352..e5356581e6e1d 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1329,9 +1329,12 @@ nop_list_lift! {bound_variable_kinds; ty::BoundVariableKind => ty::BoundVariable // This is the impl for `&'a InternalSubsts<'a>`. nop_list_lift! {substs; GenericArg<'a> => GenericArg<'tcx>} -CloneLiftImpls! { for<'tcx> { - Constness, traits::WellFormedLoc, ImplPolarity, crate::mir::ReturnConstraint, -} } +CloneLiftImpls! { + Constness, + traits::WellFormedLoc, + ImplPolarity, + crate::mir::ReturnConstraint, +} macro_rules! sty_debug_print { ($fmt: expr, $ctxt: expr, $($variant: ident),*) => {{ diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 5c604bb6db274..59c05739b3cef 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -276,9 +276,7 @@ TrivialTypeTraversalAndLiftImpls! { } TrivialTypeTraversalAndLiftImpls! { - for<'tcx> { - ty::ValTree<'tcx>, - } + ty::ValTree<'tcx>, } /////////////////////////////////////////////////////////////////////////// From dda89945b733897796250c46ca3cca8dcc6abb8a Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 06:30:45 +0000 Subject: [PATCH 043/228] Allow all associated functions and add test --- compiler/rustc_passes/messages.ftl | 10 +++----- compiler/rustc_passes/src/check_attr.rs | 4 ++-- compiler/rustc_passes/src/errors.rs | 4 ++-- tests/codegen/align-fn.rs | 31 +++++++++++++++++++++++++ 4 files changed, 38 insertions(+), 11 deletions(-) diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index 0d706996810f3..055682a1509ef 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -627,13 +627,9 @@ passes_attr_application_struct_enum_union = attribute should be applied to a struct, enum, or union .label = not a struct, enum, or union -passes_attr_application_struct_enum_function_union = - attribute should be applied to a struct, enum, function, or union - .label = not a struct, enum, function, or union - -passes_attr_application_struct_enum_function_inherent_method_union = - attribute should be applied to a struct, enum, function, inherent method, or union - .label = not a struct, enum, function, inherent method, or union +passes_attr_application_struct_enum_function_method_union = + attribute should be applied to a struct, enum, function, associated function, or union + .label = not a struct, enum, function, associated function, or union passes_transparent_incompatible = transparent {$target} cannot have other repr hints diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index a03c991d3bee0..085a28626ea00 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1745,10 +1745,10 @@ impl CheckAttrVisitor<'_> { | Target::Union | Target::Enum | Target::Fn - | Target::Method(MethodKind::Inherent) => continue, + | Target::Method(_) => continue, _ => { self.tcx.sess.emit_err( - errors::AttrApplication::StructEnumFunctionInherentMethodUnion { + errors::AttrApplication::StructEnumFunctionMethodUnion { hint_span: hint.span(), span, }, diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 27039a2a5a21f..e8603b3a2f173 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1355,8 +1355,8 @@ pub enum AttrApplication { #[label] span: Span, }, - #[diag(passes_attr_application_struct_enum_function_inherent_method_union, code = "E0517")] - StructEnumFunctionInherentMethodUnion { + #[diag(passes_attr_application_struct_enum_function_method_union, code = "E0517")] + StructEnumFunctionMethodUnion { #[primary_span] hint_span: Span, #[label] diff --git a/tests/codegen/align-fn.rs b/tests/codegen/align-fn.rs index 7238e7f53c368..f3cf614e185c9 100644 --- a/tests/codegen/align-fn.rs +++ b/tests/codegen/align-fn.rs @@ -15,4 +15,35 @@ impl A { #[no_mangle] #[repr(align(16))] pub fn method_align(self) {} + + // CHECK: align 16 + #[no_mangle] + #[repr(align(16))] + pub fn associated_fn() {} +} + +trait T: Sized { + fn trait_fn() {} + + // CHECK: align 32 + #[repr(align(32))] + fn trait_method(self) {} +} + +impl T for A { + // CHECK: align 16 + #[no_mangle] + #[repr(align(16))] + fn trait_fn() {} + + // CHECK: align 16 + #[no_mangle] + #[repr(align(16))] + fn trait_method(self) {} +} + +impl T for () {} + +pub fn foo() { + ().trait_method(); } From 76dbe2910465072f85e74d6f7115ec9e6803e8bf Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 06:49:27 +0000 Subject: [PATCH 044/228] rm const traits in libcore --- library/alloc/src/boxed.rs | 15 +- library/alloc/src/string.rs | 3 +- library/alloc/src/vec/mod.rs | 3 +- library/alloc/tests/boxed.rs | 2 +- library/core/src/alloc/mod.rs | 1 - library/core/src/any.rs | 3 +- library/core/src/array/mod.rs | 25 ++-- library/core/src/bool.rs | 13 +- library/core/src/borrow.rs | 17 +-- library/core/src/cell.rs | 12 +- library/core/src/cell/once.rs | 3 +- library/core/src/char/convert.rs | 12 +- library/core/src/clone.rs | 20 +-- library/core/src/cmp.rs | 94 ++++--------- library/core/src/convert/mod.rs | 48 +++---- library/core/src/convert/num.rs | 24 ++-- library/core/src/default.rs | 4 +- library/core/src/hash/mod.rs | 76 ++++------ library/core/src/hash/sip.rs | 15 +- library/core/src/internal_macros.rs | 71 +--------- library/core/src/iter/sources/empty.rs | 3 +- library/core/src/iter/traits/collect.rs | 3 +- library/core/src/iter/traits/iterator.rs | 1 - library/core/src/lib.rs | 7 - library/core/src/marker.rs | 4 +- library/core/src/mem/manually_drop.rs | 6 +- library/core/src/mem/transmutability.rs | 6 +- library/core/src/num/error.rs | 5 +- library/core/src/num/nonzero.rs | 24 ++-- library/core/src/num/wrapping.rs | 168 +++++++++-------------- library/core/src/ops/arith.rs | 76 ++++------ library/core/src/ops/bit.rs | 69 ++++------ library/core/src/ops/control_flow.rs | 9 +- library/core/src/ops/deref.rs | 8 +- library/core/src/ops/drop.rs | 1 - library/core/src/ops/function.rs | 28 ++-- library/core/src/ops/index.rs | 4 +- library/core/src/ops/range.rs | 86 +++++------- library/core/src/ops/try_trait.rs | 19 ++- library/core/src/option.rs | 120 ++++++++-------- library/core/src/ptr/alignment.rs | 16 +-- library/core/src/ptr/const_ptr.rs | 2 +- library/core/src/ptr/mut_ptr.rs | 2 +- library/core/src/ptr/non_null.rs | 14 +- library/core/src/ptr/unique.rs | 7 +- library/core/src/result.rs | 56 +++----- library/core/src/slice/index.rs | 27 ++-- library/core/src/slice/mod.rs | 14 +- library/core/src/str/mod.rs | 11 +- library/core/src/str/traits.rs | 22 ++- library/core/src/sync/atomic.rs | 18 +-- library/core/src/task/poll.rs | 3 +- library/core/src/tuple.rs | 12 +- library/core/tests/cmp.rs | 4 +- library/core/tests/hash/mod.rs | 16 +-- library/core/tests/hash/sip.rs | 2 +- library/std/src/collections/hash/map.rs | 6 +- library/std/src/sync/once_lock.rs | 3 +- 58 files changed, 475 insertions(+), 868 deletions(-) diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 7f88327bf190a..8278d400c8f27 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -1234,8 +1234,7 @@ impl Default for Box { #[cfg(not(no_global_oom_handling))] #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for Box<[T]> { +impl Default for Box<[T]> { #[inline] fn default() -> Self { let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling(); @@ -1245,8 +1244,7 @@ impl const Default for Box<[T]> { #[cfg(not(no_global_oom_handling))] #[stable(feature = "default_box_extra", since = "1.17.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for Box { +impl Default for Box { #[inline] fn default() -> Self { // SAFETY: This is the same as `Unique::cast` but with an unsized `U = str`. @@ -1443,8 +1441,7 @@ impl From for Box { } #[stable(feature = "pin", since = "1.33.0")] -#[rustc_const_unstable(feature = "const_box", issue = "92521")] -impl const From> for Pin> +impl From> for Pin> where A: 'static, { @@ -1880,8 +1877,7 @@ impl fmt::Pointer for Box { } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_box", issue = "92521")] -impl const Deref for Box { +impl Deref for Box { type Target = T; fn deref(&self) -> &T { @@ -1890,8 +1886,7 @@ impl const Deref for Box { } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_box", issue = "92521")] -impl const DerefMut for Box { +impl DerefMut for Box { fn deref_mut(&mut self) -> &mut T { &mut **self } diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index be41919b9dc23..cf16a3424a092 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -2247,8 +2247,7 @@ impl_eq! { Cow<'a, str>, &'b str } impl_eq! { Cow<'a, str>, String } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for String { +impl Default for String { /// Creates an empty `String`. #[inline] fn default() -> String { diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 3736a6e0b0ecb..765c095e37bfc 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -3022,8 +3022,7 @@ unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec { } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for Vec { +impl Default for Vec { /// Creates an empty `Vec`. /// /// The vector will not allocate until elements are pushed onto it. diff --git a/library/alloc/tests/boxed.rs b/library/alloc/tests/boxed.rs index 68ebd8e35ee3d..4cacee0414d7d 100644 --- a/library/alloc/tests/boxed.rs +++ b/library/alloc/tests/boxed.rs @@ -61,7 +61,7 @@ fn box_deref_lval() { pub struct ConstAllocator; -unsafe impl const Allocator for ConstAllocator { +unsafe impl Allocator for ConstAllocator { fn allocate(&self, layout: Layout) -> Result, AllocError> { match layout.size() { 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)), diff --git a/library/core/src/alloc/mod.rs b/library/core/src/alloc/mod.rs index ff390322d552d..d6ae2b8213f56 100644 --- a/library/core/src/alloc/mod.rs +++ b/library/core/src/alloc/mod.rs @@ -105,7 +105,6 @@ impl fmt::Display for AllocError { /// /// [*currently allocated*]: #currently-allocated-memory #[unstable(feature = "allocator_api", issue = "32838")] -#[const_trait] pub unsafe trait Allocator { /// Attempts to allocate a block of memory. /// diff --git a/library/core/src/any.rs b/library/core/src/any.rs index c27646b8f33df..bb93ea509d8ee 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -662,8 +662,7 @@ impl dyn Any + Send + Sync { /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth /// noting that the hashes and ordering will vary between Rust releases. Beware /// of relying on them inside of your code! -#[derive(Clone, Copy, Debug, Hash, Eq)] -#[derive_const(PartialEq, PartialOrd, Ord)] +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] #[stable(feature = "rust1", since = "1.0.0")] pub struct TypeId { t: u64, diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index 1643842d60756..98c87b2c393ea 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -148,8 +148,7 @@ impl Error for TryFromSliceError { } #[stable(feature = "try_from_slice_error", since = "1.36.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for TryFromSliceError { +impl From for TryFromSliceError { fn from(x: Infallible) -> TryFromSliceError { match x {} } @@ -172,16 +171,14 @@ impl AsMut<[T]> for [T; N] { } #[stable(feature = "array_borrow", since = "1.4.0")] -#[rustc_const_unstable(feature = "const_borrow", issue = "91522")] -impl const Borrow<[T]> for [T; N] { +impl Borrow<[T]> for [T; N] { fn borrow(&self) -> &[T] { self } } #[stable(feature = "array_borrow", since = "1.4.0")] -#[rustc_const_unstable(feature = "const_borrow", issue = "91522")] -impl const BorrowMut<[T]> for [T; N] { +impl BorrowMut<[T]> for [T; N] { fn borrow_mut(&mut self) -> &mut [T] { self } @@ -336,10 +333,9 @@ impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] { } #[stable(feature = "index_trait_on_arrays", since = "1.50.0")] -#[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -impl const Index for [T; N] +impl Index for [T; N] where - [T]: ~const Index, + [T]: Index, { type Output = <[T] as Index>::Output; @@ -350,10 +346,9 @@ where } #[stable(feature = "index_trait_on_arrays", since = "1.50.0")] -#[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -impl const IndexMut for [T; N] +impl IndexMut for [T; N] where - [T]: ~const IndexMut, + [T]: IndexMut, { #[inline] fn index_mut(&mut self, index: I) -> &mut Self::Output { @@ -435,8 +430,7 @@ impl SpecArrayClone for T { macro_rules! array_impl_default { {$n:expr, $t:ident $($ts:ident)*} => { #[stable(since = "1.4.0", feature = "array_default")] - #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] - impl const Default for [T; $n] where T: ~const Default { + impl Default for [T; $n] where T: Default { fn default() -> [T; $n] { [$t::default(), $($ts::default()),*] } @@ -445,8 +439,7 @@ macro_rules! array_impl_default { }; {$n:expr,} => { #[stable(since = "1.4.0", feature = "array_default")] - #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] - impl const Default for [T; $n] { + impl Default for [T; $n] { fn default() -> [T; $n] { [] } } }; diff --git a/library/core/src/bool.rs b/library/core/src/bool.rs index db1c505ba3851..374759e38161a 100644 --- a/library/core/src/bool.rs +++ b/library/core/src/bool.rs @@ -1,7 +1,5 @@ //! impl bool {} -use crate::marker::Destruct; - impl bool { /// Returns `Some(t)` if the `bool` is [`true`](../std/keyword.true.html), /// or `None` otherwise. @@ -31,11 +29,8 @@ impl bool { /// assert_eq!(a, 2); /// ``` #[stable(feature = "bool_to_option", since = "1.62.0")] - #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")] #[inline] - pub const fn then_some(self, t: T) -> Option - where - T: ~const Destruct, + pub fn then_some(self, t: T) -> Option { if self { Some(t) } else { None } } @@ -61,12 +56,8 @@ impl bool { /// assert_eq!(a, 1); /// ``` #[stable(feature = "lazy_bool_to_option", since = "1.50.0")] - #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")] #[inline] - pub const fn then(self, f: F) -> Option - where - F: ~const FnOnce() -> T, - F: ~const Destruct, + pub fn then T>(self, f: F) -> Option { if self { Some(f()) } else { None } } diff --git a/library/core/src/borrow.rs b/library/core/src/borrow.rs index 4a8302ee404c1..efc9ada3891a0 100644 --- a/library/core/src/borrow.rs +++ b/library/core/src/borrow.rs @@ -154,7 +154,6 @@ /// [`String`]: ../../std/string/struct.String.html #[stable(feature = "rust1", since = "1.0.0")] #[rustc_diagnostic_item = "Borrow"] -#[const_trait] pub trait Borrow { /// Immutably borrows from an owned value. /// @@ -185,7 +184,6 @@ pub trait Borrow { /// an underlying type by providing a mutable reference. See [`Borrow`] /// for more information on borrowing as another type. #[stable(feature = "rust1", since = "1.0.0")] -#[const_trait] pub trait BorrowMut: Borrow { /// Mutably borrows from an owned value. /// @@ -207,8 +205,7 @@ pub trait BorrowMut: Borrow { } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_borrow", issue = "91522")] -impl const Borrow for T { +impl Borrow for T { #[rustc_diagnostic_item = "noop_method_borrow"] fn borrow(&self) -> &T { self @@ -216,32 +213,28 @@ impl const Borrow for T { } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_borrow", issue = "91522")] -impl const BorrowMut for T { +impl BorrowMut for T { fn borrow_mut(&mut self) -> &mut T { self } } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_borrow", issue = "91522")] -impl const Borrow for &T { +impl Borrow for &T { fn borrow(&self) -> &T { &**self } } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_borrow", issue = "91522")] -impl const Borrow for &mut T { +impl Borrow for &mut T { fn borrow(&self) -> &T { &**self } } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_borrow", issue = "91522")] -impl const BorrowMut for &mut T { +impl BorrowMut for &mut T { fn borrow_mut(&mut self) -> &mut T { &mut **self } diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index d728dc038176c..bcca8d924cdd6 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -370,8 +370,7 @@ impl Ord for Cell { } #[stable(feature = "cell_from", since = "1.12.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for Cell { +impl From for Cell { /// Creates a new `Cell` containing the given value. fn from(t: T) -> Cell { Cell::new(t) @@ -1318,8 +1317,7 @@ impl Ord for RefCell { } #[stable(feature = "cell_from", since = "1.12.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for RefCell { +impl From for RefCell { /// Creates a new `RefCell` containing the given value. fn from(t: T) -> RefCell { RefCell::new(t) @@ -2126,8 +2124,7 @@ impl Default for UnsafeCell { } #[stable(feature = "cell_from", since = "1.12.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for UnsafeCell { +impl From for UnsafeCell { /// Creates a new `UnsafeCell` containing the given value. fn from(t: T) -> UnsafeCell { UnsafeCell::new(t) @@ -2226,8 +2223,7 @@ impl Default for SyncUnsafeCell { } #[unstable(feature = "sync_unsafe_cell", issue = "95439")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for SyncUnsafeCell { +impl From for SyncUnsafeCell { /// Creates a new `SyncUnsafeCell` containing the given value. fn from(t: T) -> SyncUnsafeCell { SyncUnsafeCell::new(t) diff --git a/library/core/src/cell/once.rs b/library/core/src/cell/once.rs index 5dc2d52319800..a7cd59e50fc31 100644 --- a/library/core/src/cell/once.rs +++ b/library/core/src/cell/once.rs @@ -284,8 +284,7 @@ impl PartialEq for OnceCell { impl Eq for OnceCell {} #[stable(feature = "once_cell", since = "CURRENT_RUSTC_VERSION")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for OnceCell { +impl From for OnceCell { /// Creates a new `OnceCell` which already contains the given `value`. #[inline] fn from(value: T) -> Self { diff --git a/library/core/src/char/convert.rs b/library/core/src/char/convert.rs index 136bbcb8b21b4..b84e4b35b1c77 100644 --- a/library/core/src/char/convert.rs +++ b/library/core/src/char/convert.rs @@ -27,8 +27,7 @@ pub(super) const unsafe fn from_u32_unchecked(i: u32) -> char { } #[stable(feature = "char_convert", since = "1.13.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for u32 { +impl From for u32 { /// Converts a [`char`] into a [`u32`]. /// /// # Examples @@ -47,8 +46,7 @@ impl const From for u32 { } #[stable(feature = "more_char_conversions", since = "1.51.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for u64 { +impl From for u64 { /// Converts a [`char`] into a [`u64`]. /// /// # Examples @@ -69,8 +67,7 @@ impl const From for u64 { } #[stable(feature = "more_char_conversions", since = "1.51.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for u128 { +impl From for u128 { /// Converts a [`char`] into a [`u128`]. /// /// # Examples @@ -123,8 +120,7 @@ impl TryFrom for u8 { /// for a superset of Windows-1252 that fills the remaining blanks with corresponding /// C0 and C1 control codes. #[stable(feature = "char_convert", since = "1.13.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for char { +impl From for char { /// Converts a [`u8`] into a [`char`]. /// /// # Examples diff --git a/library/core/src/clone.rs b/library/core/src/clone.rs index 398437d9a023d..5662ff8dfd9ae 100644 --- a/library/core/src/clone.rs +++ b/library/core/src/clone.rs @@ -36,8 +36,6 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::marker::Destruct; - /// A common trait for the ability to explicitly duplicate an object. /// /// Differs from [`Copy`] in that [`Copy`] is implicit and an inexpensive bit-wise copy, while @@ -106,7 +104,6 @@ use crate::marker::Destruct; #[lang = "clone"] #[rustc_diagnostic_item = "Clone"] #[rustc_trivial_field_reads] -#[const_trait] pub trait Clone: Sized { /// Returns a copy of the value. /// @@ -130,8 +127,6 @@ pub trait Clone: Sized { #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn clone_from(&mut self, source: &Self) - where - Self: ~const Destruct, { *self = source.clone() } @@ -182,8 +177,7 @@ mod impls { ($($t:ty)*) => { $( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_clone", issue = "91805")] - impl const Clone for $t { + impl Clone for $t { #[inline(always)] fn clone(&self) -> Self { *self @@ -201,8 +195,7 @@ mod impls { } #[unstable(feature = "never_type", issue = "35121")] - #[rustc_const_unstable(feature = "const_clone", issue = "91805")] - impl const Clone for ! { + impl Clone for ! { #[inline] fn clone(&self) -> Self { *self @@ -210,8 +203,7 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_clone", issue = "91805")] - impl const Clone for *const T { + impl Clone for *const T { #[inline(always)] fn clone(&self) -> Self { *self @@ -219,8 +211,7 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_clone", issue = "91805")] - impl const Clone for *mut T { + impl Clone for *mut T { #[inline(always)] fn clone(&self) -> Self { *self @@ -229,8 +220,7 @@ mod impls { /// Shared references can be cloned, but mutable references *cannot*! #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_clone", issue = "91805")] - impl const Clone for &T { + impl Clone for &T { #[inline(always)] #[rustc_diagnostic_item = "noop_method_clone"] fn clone(&self) -> Self { diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index 55331475aff2a..5582f1be4f438 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -212,7 +212,6 @@ use self::Ordering::*; label = "no implementation for `{Self} == {Rhs}`", append_const_msg )] -#[const_trait] #[rustc_diagnostic_item = "PartialEq"] pub trait PartialEq { /// This method tests for `self` and `other` values to be equal, and is used @@ -333,8 +332,7 @@ pub struct AssertParamIsEq { /// let result = 2.cmp(&1); /// assert_eq!(Ordering::Greater, result); /// ``` -#[derive(Clone, Copy, Eq, Debug, Hash)] -#[derive_const(PartialOrd, Ord, PartialEq)] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] #[stable(feature = "rust1", since = "1.0.0")] #[repr(i8)] pub enum Ordering { @@ -604,8 +602,7 @@ impl Ordering { pub struct Reverse(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T); #[stable(feature = "reverse_cmp_key", since = "1.19.0")] -#[rustc_const_unstable(feature = "const_cmp", issue = "92391")] -impl const PartialOrd for Reverse { +impl PartialOrd for Reverse { #[inline] fn partial_cmp(&self, other: &Reverse) -> Option { other.0.partial_cmp(&self.0) @@ -763,7 +760,6 @@ impl Clone for Reverse { #[doc(alias = ">=")] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_diagnostic_item = "Ord"] -#[const_trait] pub trait Ord: Eq + PartialOrd { /// This method returns an [`Ordering`] between `self` and `other`. /// @@ -799,7 +795,6 @@ pub trait Ord: Eq + PartialOrd { fn max(self, other: Self) -> Self where Self: Sized, - Self: ~const Destruct, { max_by(self, other, Ord::cmp) } @@ -820,7 +815,6 @@ pub trait Ord: Eq + PartialOrd { fn min(self, other: Self) -> Self where Self: Sized, - Self: ~const Destruct, { min_by(self, other, Ord::cmp) } @@ -846,8 +840,7 @@ pub trait Ord: Eq + PartialOrd { fn clamp(self, min: Self, max: Self) -> Self where Self: Sized, - Self: ~const Destruct, - Self: ~const PartialOrd, + Self: PartialOrd, { assert!(min <= max); if self < min { @@ -1035,7 +1028,6 @@ pub macro Ord($item:item) { label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`", append_const_msg )] -#[const_trait] #[rustc_diagnostic_item = "PartialOrd"] pub trait PartialOrd: PartialEq { /// This method returns an ordering between `self` and `other` values if one exists. @@ -1168,7 +1160,7 @@ pub macro PartialOrd($item:item) { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")] -pub const fn min(v1: T, v2: T) -> T { +pub const fn min(v1: T, v2: T) -> T { v1.min(v2) } @@ -1187,11 +1179,7 @@ pub const fn min(v1: T, v2: T) -> T { #[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] -#[rustc_const_unstable(feature = "const_cmp", issue = "92391")] -pub const fn min_by Ordering>(v1: T, v2: T, compare: F) -> T -where - T: ~const Destruct, - F: ~const Destruct, +pub fn min_by Ordering>(v1: T, v2: T, compare: F) -> T { match compare(&v1, &v2) { Ordering::Less | Ordering::Equal => v1, @@ -1214,14 +1202,9 @@ where #[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] -#[rustc_const_unstable(feature = "const_cmp", issue = "92391")] -pub const fn min_by_key K, K: ~const Ord>(v1: T, v2: T, mut f: F) -> T -where - T: ~const Destruct, - F: ~const Destruct, - K: ~const Destruct, +pub fn min_by_key K, K: Ord>(v1: T, v2: T, mut f: F) -> T { - min_by(v1, v2, const |v1, v2| f(v1).cmp(&f(v2))) + min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2))) } /// Compares and returns the maximum of two values. @@ -1241,9 +1224,8 @@ where #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_cmp", issue = "92391")] #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")] -pub const fn max(v1: T, v2: T) -> T { +pub fn max(v1: T, v2: T) -> T { v1.max(v2) } @@ -1262,11 +1244,7 @@ pub const fn max(v1: T, v2: T) -> T { #[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] -#[rustc_const_unstable(feature = "const_cmp", issue = "92391")] -pub const fn max_by Ordering>(v1: T, v2: T, compare: F) -> T -where - T: ~const Destruct, - F: ~const Destruct, +pub fn max_by Ordering>(v1: T, v2: T, compare: F) -> T { match compare(&v1, &v2) { Ordering::Less | Ordering::Equal => v2, @@ -1290,11 +1268,11 @@ where #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] -pub const fn max_by_key K, K: ~const Ord>(v1: T, v2: T, mut f: F) -> T +pub const fn max_by_key K, K: Ord>(v1: T, v2: T, mut f: F) -> T where - T: ~const Destruct, - F: ~const Destruct, - K: ~const Destruct, + T: Destruct, + F: Destruct, + K: Destruct, { max_by(v1, v2, const |v1, v2| f(v1).cmp(&f(v2))) } @@ -1307,8 +1285,7 @@ mod impls { macro_rules! partial_eq_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const PartialEq for $t { + impl PartialEq for $t { #[inline] fn eq(&self, other: &$t) -> bool { (*self) == (*other) } #[inline] @@ -1318,8 +1295,7 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const PartialEq for () { + impl PartialEq for () { #[inline] fn eq(&self, _other: &()) -> bool { true @@ -1346,8 +1322,7 @@ mod impls { macro_rules! partial_ord_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const PartialOrd for $t { + impl PartialOrd for $t { #[inline] fn partial_cmp(&self, other: &$t) -> Option { match (*self <= *other, *self >= *other) { @@ -1370,8 +1345,7 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const PartialOrd for () { + impl PartialOrd for () { #[inline] fn partial_cmp(&self, _: &()) -> Option { Some(Equal) @@ -1379,8 +1353,7 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const PartialOrd for bool { + impl PartialOrd for bool { #[inline] fn partial_cmp(&self, other: &bool) -> Option { Some(self.cmp(other)) @@ -1392,8 +1365,7 @@ mod impls { macro_rules! ord_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const PartialOrd for $t { + impl PartialOrd for $t { #[inline] fn partial_cmp(&self, other: &$t) -> Option { Some(self.cmp(other)) @@ -1409,8 +1381,7 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const Ord for $t { + impl Ord for $t { #[inline] fn cmp(&self, other: &$t) -> Ordering { // The order here is important to generate more optimal assembly. @@ -1424,8 +1395,7 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const Ord for () { + impl Ord for () { #[inline] fn cmp(&self, _other: &()) -> Ordering { Equal @@ -1433,8 +1403,7 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const Ord for bool { + impl Ord for bool { #[inline] fn cmp(&self, other: &bool) -> Ordering { // Casting to i8's and converting the difference to an Ordering generates @@ -1453,8 +1422,7 @@ mod impls { ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } #[unstable(feature = "never_type", issue = "35121")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const PartialEq for ! { + impl PartialEq for ! { fn eq(&self, _: &!) -> bool { *self } @@ -1464,16 +1432,14 @@ mod impls { impl Eq for ! {} #[unstable(feature = "never_type", issue = "35121")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const PartialOrd for ! { + impl PartialOrd for ! { fn partial_cmp(&self, _: &!) -> Option { *self } } #[unstable(feature = "never_type", issue = "35121")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const Ord for ! { + impl Ord for ! { fn cmp(&self, _: &!) -> Ordering { *self } @@ -1482,10 +1448,9 @@ mod impls { // & pointers #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const PartialEq<&B> for &A + impl PartialEq<&B> for &A where - A: ~const PartialEq, + A: PartialEq, { #[inline] fn eq(&self, other: &&B) -> bool { @@ -1497,10 +1462,9 @@ mod impls { } } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl const PartialOrd<&B> for &A + impl PartialOrd<&B> for &A where - A: ~const PartialOrd, + A: PartialOrd, { #[inline] fn partial_cmp(&self, other: &&B) -> Option { diff --git a/library/core/src/convert/mod.rs b/library/core/src/convert/mod.rs index 5888e2960bb7e..3ae787cac71f8 100644 --- a/library/core/src/convert/mod.rs +++ b/library/core/src/convert/mod.rs @@ -214,7 +214,6 @@ pub const fn identity(x: T) -> T { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "AsRef")] -#[const_trait] pub trait AsRef { /// Converts this type into a shared reference of the (usually inferred) input type. #[stable(feature = "rust1", since = "1.0.0")] @@ -366,7 +365,6 @@ pub trait AsRef { /// `&mut Vec`, for example, is the better choice (callers need to pass the correct type then). #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "AsMut")] -#[const_trait] pub trait AsMut { /// Converts this type into a mutable reference of the (usually inferred) input type. #[stable(feature = "rust1", since = "1.0.0")] @@ -443,7 +441,6 @@ pub trait AsMut { /// [`Vec`]: ../../std/vec/struct.Vec.html #[rustc_diagnostic_item = "Into"] #[stable(feature = "rust1", since = "1.0.0")] -#[const_trait] pub trait Into: Sized { /// Converts this type into the (usually inferred) input type. #[must_use] @@ -539,7 +536,6 @@ pub trait Into: Sized { all(_Self = "&str", T = "std::string::String"), note = "to coerce a `{T}` into a `{Self}`, use `&*` as a prefix", ))] -#[const_trait] pub trait From: Sized { /// Converts to this type from the input type. #[rustc_diagnostic_item = "from_fn"] @@ -564,7 +560,6 @@ pub trait From: Sized { /// [`Into`], see there for details. #[rustc_diagnostic_item = "TryInto"] #[stable(feature = "try_from", since = "1.34.0")] -#[const_trait] pub trait TryInto: Sized { /// The type returned in the event of a conversion error. #[stable(feature = "try_from", since = "1.34.0")] @@ -641,7 +636,6 @@ pub trait TryInto: Sized { /// [`try_from`]: TryFrom::try_from #[rustc_diagnostic_item = "TryFrom"] #[stable(feature = "try_from", since = "1.34.0")] -#[const_trait] pub trait TryFrom: Sized { /// The type returned in the event of a conversion error. #[stable(feature = "try_from", since = "1.34.0")] @@ -658,10 +652,9 @@ pub trait TryFrom: Sized { // As lifts over & #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const AsRef for &T +impl AsRef for &T where - T: ~const AsRef, + T: AsRef, { #[inline] fn as_ref(&self) -> &U { @@ -671,10 +664,9 @@ where // As lifts over &mut #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const AsRef for &mut T +impl AsRef for &mut T where - T: ~const AsRef, + T: AsRef, { #[inline] fn as_ref(&self) -> &U { @@ -692,10 +684,9 @@ where // AsMut lifts over &mut #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const AsMut for &mut T +impl AsMut for &mut T where - T: ~const AsMut, + T: AsMut, { #[inline] fn as_mut(&mut self) -> &mut U { @@ -713,10 +704,9 @@ where // From implies Into #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const Into for T +impl Into for T where - U: ~const From, + U: From, { /// Calls `U::from(self)`. /// @@ -730,8 +720,7 @@ where // From (and thus Into) is reflexive #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for T { +impl From for T { /// Returns the argument unchanged. #[inline(always)] fn from(t: T) -> T { @@ -748,8 +737,7 @@ impl const From for T { #[allow(unused_attributes)] // FIXME(#58633): do a principled fix instead. #[rustc_reservation_impl = "permitting this impl would forbid us from adding \ `impl From for T` later; see rust-lang/rust#64715 for details"] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for T { +impl From for T { fn from(t: !) -> T { t } @@ -757,10 +745,9 @@ impl const From for T { // TryFrom implies TryInto #[stable(feature = "try_from", since = "1.34.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const TryInto for T +impl TryInto for T where - U: ~const TryFrom, + U: TryFrom, { type Error = U::Error; @@ -773,10 +760,9 @@ where // Infallible conversions are semantically equivalent to fallible conversions // with an uninhabited error type. #[stable(feature = "try_from", since = "1.34.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const TryFrom for T +impl TryFrom for T where - U: ~const Into, + U: Into, { type Error = Infallible; @@ -876,8 +862,7 @@ impl AsMut for str { pub enum Infallible {} #[stable(feature = "convert_infallible", since = "1.34.0")] -#[rustc_const_unstable(feature = "const_clone", issue = "91805")] -impl const Clone for Infallible { +impl Clone for Infallible { fn clone(&self) -> Infallible { match *self {} } @@ -929,8 +914,7 @@ impl Ord for Infallible { } #[stable(feature = "convert_infallible", since = "1.34.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for Infallible { +impl From for Infallible { fn from(x: !) -> Self { x } diff --git a/library/core/src/convert/num.rs b/library/core/src/convert/num.rs index a74a56bc5b209..56ab63be27d37 100644 --- a/library/core/src/convert/num.rs +++ b/library/core/src/convert/num.rs @@ -44,8 +44,7 @@ impl_float_to_int!(f64 => u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize); macro_rules! impl_from { ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => { #[$attr] - #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")] - impl const From<$Small> for $Large { + impl From<$Small> for $Large { // Rustdocs on the impl block show a "[+] show undocumented items" toggle. // Rustdocs on functions do not. #[doc = $doc] @@ -170,8 +169,7 @@ impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0" // bool -> Float #[stable(feature = "float_from_bool", since = "1.68.0")] -#[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")] -impl const From for f32 { +impl From for f32 { /// Converts `bool` to `f32` losslessly. The resulting value is positive /// `0.0` for `false` and `1.0` for `true` values. /// @@ -190,8 +188,7 @@ impl const From for f32 { } } #[stable(feature = "float_from_bool", since = "1.68.0")] -#[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")] -impl const From for f64 { +impl From for f64 { /// Converts `bool` to `f64` losslessly. The resulting value is positive /// `0.0` for `false` and `1.0` for `true` values. /// @@ -214,8 +211,7 @@ impl const From for f64 { macro_rules! try_from_unbounded { ($source:ty, $($target:ty),*) => {$( #[stable(feature = "try_from", since = "1.34.0")] - #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")] - impl const TryFrom<$source> for $target { + impl TryFrom<$source> for $target { type Error = TryFromIntError; /// Try to create the target number type from a source @@ -233,8 +229,7 @@ macro_rules! try_from_unbounded { macro_rules! try_from_lower_bounded { ($source:ty, $($target:ty),*) => {$( #[stable(feature = "try_from", since = "1.34.0")] - #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")] - impl const TryFrom<$source> for $target { + impl TryFrom<$source> for $target { type Error = TryFromIntError; /// Try to create the target number type from a source @@ -256,8 +251,7 @@ macro_rules! try_from_lower_bounded { macro_rules! try_from_upper_bounded { ($source:ty, $($target:ty),*) => {$( #[stable(feature = "try_from", since = "1.34.0")] - #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")] - impl const TryFrom<$source> for $target { + impl TryFrom<$source> for $target { type Error = TryFromIntError; /// Try to create the target number type from a source @@ -279,8 +273,7 @@ macro_rules! try_from_upper_bounded { macro_rules! try_from_both_bounded { ($source:ty, $($target:ty),*) => {$( #[stable(feature = "try_from", since = "1.34.0")] - #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")] - impl const TryFrom<$source> for $target { + impl TryFrom<$source> for $target { type Error = TryFromIntError; /// Try to create the target number type from a source @@ -431,8 +424,7 @@ use crate::num::NonZeroUsize; macro_rules! nzint_impl_from { ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => { #[$attr] - #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")] - impl const From<$Small> for $Large { + impl From<$Small> for $Large { // Rustdocs on the impl block show a "[+] show undocumented items" toggle. // Rustdocs on functions do not. #[doc = $doc] diff --git a/library/core/src/default.rs b/library/core/src/default.rs index d96b53de0a338..09dbc95810f51 100644 --- a/library/core/src/default.rs +++ b/library/core/src/default.rs @@ -99,7 +99,6 @@ /// ``` #[cfg_attr(not(test), rustc_diagnostic_item = "Default")] #[stable(feature = "rust1", since = "1.0.0")] -#[const_trait] pub trait Default: Sized { /// Returns the "default value" for a type. /// @@ -190,8 +189,7 @@ pub macro Default($item:item) { macro_rules! default_impl { ($t:ty, $v:expr, $doc:tt) => { #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] - impl const Default for $t { + impl Default for $t { #[inline] #[doc = $doc] fn default() -> $t { diff --git a/library/core/src/hash/mod.rs b/library/core/src/hash/mod.rs index 4e7bae7bcb05a..4a28a6e40e830 100644 --- a/library/core/src/hash/mod.rs +++ b/library/core/src/hash/mod.rs @@ -87,7 +87,7 @@ use crate::fmt; use crate::intrinsics::const_eval_select; -use crate::marker::{self, Destruct}; +use crate::marker; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] @@ -184,7 +184,6 @@ mod sip; /// [impl]: ../../std/primitive.str.html#impl-Hash-for-str #[stable(feature = "rust1", since = "1.0.0")] #[rustc_diagnostic_item = "Hash"] -#[const_trait] pub trait Hash { /// Feeds this value into the given [`Hasher`]. /// @@ -199,7 +198,7 @@ pub trait Hash { /// println!("Hash is {:x}!", hasher.finish()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn hash(&self, state: &mut H); + fn hash(&self, state: &mut H); /// Feeds a slice of this type into the given [`Hasher`]. /// @@ -236,7 +235,7 @@ pub trait Hash { /// [`hash`]: Hash::hash /// [`hash_slice`]: Hash::hash_slice #[stable(feature = "hash_slice", since = "1.3.0")] - fn hash_slice(data: &[Self], state: &mut H) + fn hash_slice(data: &[Self], state: &mut H) where Self: Sized, { @@ -246,7 +245,7 @@ pub trait Hash { piece.hash(state) } } - const fn ct(data: &[T], state: &mut H) { + const fn ct(data: &[T], state: &mut H) { let mut i = 0; while i < data.len() { data[i].hash(state); @@ -327,7 +326,6 @@ pub use macros::Hash; /// [`write_u8`]: Hasher::write_u8 /// [`write_u32`]: Hasher::write_u32 #[stable(feature = "rust1", since = "1.0.0")] -#[const_trait] pub trait Hasher { /// Returns the hash value for the values written so far. /// @@ -573,8 +571,7 @@ pub trait Hasher { } #[stable(feature = "indirect_hasher_impl", since = "1.22.0")] -#[rustc_const_unstable(feature = "const_hash", issue = "104061")] -impl const Hasher for &mut H { +impl Hasher for &mut H { fn finish(&self) -> u64 { (**self).finish() } @@ -654,7 +651,6 @@ impl const Hasher for &mut H { /// [`build_hasher`]: BuildHasher::build_hasher /// [`HashMap`]: ../../std/collections/struct.HashMap.html #[stable(since = "1.7.0", feature = "build_hasher")] -#[const_trait] pub trait BuildHasher { /// Type of the hasher that will be created. #[stable(since = "1.7.0", feature = "build_hasher")] @@ -715,10 +711,10 @@ pub trait BuildHasher { /// ); /// ``` #[unstable(feature = "build_hasher_simple_hash_one", issue = "86161")] - fn hash_one(&self, x: T) -> u64 + fn hash_one(&self, x: T) -> u64 where Self: Sized, - Self::Hasher: ~const Hasher + ~const Destruct, + Self::Hasher: Hasher, { let mut hasher = self.build_hasher(); x.hash(&mut hasher); @@ -782,8 +778,7 @@ impl fmt::Debug for BuildHasherDefault { } #[stable(since = "1.7.0", feature = "build_hasher")] -#[rustc_const_unstable(feature = "const_hash", issue = "104061")] -impl const BuildHasher for BuildHasherDefault { +impl BuildHasher for BuildHasherDefault { type Hasher = H; fn build_hasher(&self) -> H { @@ -799,8 +794,7 @@ impl Clone for BuildHasherDefault { } #[stable(since = "1.7.0", feature = "build_hasher")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for BuildHasherDefault { +impl Default for BuildHasherDefault { fn default() -> BuildHasherDefault { BuildHasherDefault(marker::PhantomData) } @@ -825,15 +819,14 @@ mod impls { macro_rules! impl_write { ($(($ty:ident, $meth:ident),)*) => {$( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_hash", issue = "104061")] - impl const Hash for $ty { + impl Hash for $ty { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { state.$meth(*self) } #[inline] - fn hash_slice(data: &[$ty], state: &mut H) { + fn hash_slice(data: &[$ty], state: &mut H) { let newlen = mem::size_of_val(data); let ptr = data.as_ptr() as *const u8; // SAFETY: `ptr` is valid and aligned, as this macro is only used @@ -862,37 +855,33 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_hash", issue = "104061")] - impl const Hash for bool { + impl Hash for bool { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { state.write_u8(*self as u8) } } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_hash", issue = "104061")] - impl const Hash for char { + impl Hash for char { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { state.write_u32(*self as u32) } } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_hash", issue = "104061")] - impl const Hash for str { + impl Hash for str { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { state.write_str(self); } } #[stable(feature = "never_hash", since = "1.29.0")] - #[rustc_const_unstable(feature = "const_hash", issue = "104061")] - impl const Hash for ! { + impl Hash for ! { #[inline] - fn hash(&self, _: &mut H) { + fn hash(&self, _: &mut H) { *self } } @@ -900,10 +889,9 @@ mod impls { macro_rules! impl_hash_tuple { () => ( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_hash", issue = "104061")] - impl const Hash for () { + impl Hash for () { #[inline] - fn hash(&self, _state: &mut H) {} + fn hash(&self, _state: &mut H) {} } ); @@ -911,11 +899,10 @@ mod impls { maybe_tuple_doc! { $($name)+ @ #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_hash", issue = "104061")] - impl<$($name: ~const Hash),+> const Hash for ($($name,)+) where last_type!($($name,)+): ?Sized { + impl<$($name: Hash),+> Hash for ($($name,)+) where last_type!($($name,)+): ?Sized { #[allow(non_snake_case)] #[inline] - fn hash(&self, state: &mut S) { + fn hash(&self, state: &mut S) { let ($(ref $name,)+) = *self; $($name.hash(state);)+ } @@ -958,29 +945,26 @@ mod impls { impl_hash_tuple! { T B C D E F G H I J K L } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_hash", issue = "104061")] - impl const Hash for [T] { + impl Hash for [T] { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { state.write_length_prefix(self.len()); Hash::hash_slice(self, state) } } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_hash", issue = "104061")] - impl const Hash for &T { + impl Hash for &T { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { (**self).hash(state); } } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_hash", issue = "104061")] - impl const Hash for &mut T { + impl Hash for &mut T { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { (**self).hash(state); } } diff --git a/library/core/src/hash/sip.rs b/library/core/src/hash/sip.rs index 7f8287bf56f64..1a87671d1d994 100644 --- a/library/core/src/hash/sip.rs +++ b/library/core/src/hash/sip.rs @@ -225,8 +225,7 @@ impl Hasher { } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_hash", issue = "104061")] -impl const super::Hasher for SipHasher { +impl super::Hasher for SipHasher { #[inline] fn write(&mut self, msg: &[u8]) { self.0.hasher.write(msg) @@ -244,8 +243,7 @@ impl const super::Hasher for SipHasher { } #[unstable(feature = "hashmap_internals", issue = "none")] -#[rustc_const_unstable(feature = "const_hash", issue = "104061")] -impl const super::Hasher for SipHasher13 { +impl super::Hasher for SipHasher13 { #[inline] fn write(&mut self, msg: &[u8]) { self.hasher.write(msg) @@ -262,7 +260,7 @@ impl const super::Hasher for SipHasher13 { } } -impl const super::Hasher for Hasher { +impl super::Hasher for Hasher { // Note: no integer hashing methods (`write_u*`, `write_i*`) are defined // for this type. We could add them, copy the `short_write` implementation // in librustc_data_structures/sip128.rs, and add `write_u*`/`write_i*` @@ -342,7 +340,7 @@ impl const super::Hasher for Hasher { } } -impl const Clone for Hasher { +impl Clone for Hasher { #[inline] fn clone(&self) -> Hasher { Hasher { @@ -366,7 +364,6 @@ impl Default for Hasher { } #[doc(hidden)] -#[const_trait] trait Sip { fn c_rounds(_: &mut State); fn d_rounds(_: &mut State); @@ -375,7 +372,7 @@ trait Sip { #[derive(Debug, Clone, Default)] struct Sip13Rounds; -impl const Sip for Sip13Rounds { +impl Sip for Sip13Rounds { #[inline] fn c_rounds(state: &mut State) { compress!(state); @@ -392,7 +389,7 @@ impl const Sip for Sip13Rounds { #[derive(Debug, Clone, Default)] struct Sip24Rounds; -impl const Sip for Sip24Rounds { +impl Sip for Sip24Rounds { #[inline] fn c_rounds(state: &mut State) { compress!(state); diff --git a/library/core/src/internal_macros.rs b/library/core/src/internal_macros.rs index 5d4c9ba73951a..5774107f5207f 100644 --- a/library/core/src/internal_macros.rs +++ b/library/core/src/internal_macros.rs @@ -1,23 +1,10 @@ // implements the unary operator "op &T" // based on "op T" where T is expected to be `Copy`able macro_rules! forward_ref_unop { - (impl const $imp:ident, $method:ident for $t:ty) => { - forward_ref_unop!(impl const $imp, $method for $t, + (impl $imp:ident, $method:ident for $t:ty) => { + forward_ref_unop!(impl $imp, $method for $t, #[stable(feature = "rust1", since = "1.0.0")]); }; - // Equivalent to the non-const version, with the addition of `rustc_const_unstable` - (impl const $imp:ident, $method:ident for $t:ty, #[$attr:meta]) => { - #[$attr] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const $imp for &$t { - type Output = <$t as $imp>::Output; - - #[inline] - fn $method(self) -> <$t as $imp>::Output { - $imp::$method(*self) - } - } - }; (impl $imp:ident, $method:ident for $t:ty, #[$attr:meta]) => { #[$attr] impl $imp for &$t { @@ -34,45 +21,10 @@ macro_rules! forward_ref_unop { // implements binary operators "&T op U", "T op &U", "&T op &U" // based on "T op U" where T and U are expected to be `Copy`able macro_rules! forward_ref_binop { - (impl const $imp:ident, $method:ident for $t:ty, $u:ty) => { - forward_ref_binop!(impl const $imp, $method for $t, $u, + (impl $imp:ident, $method:ident for $t:ty, $u:ty) => { + forward_ref_binop!(impl $imp, $method for $t, $u, #[stable(feature = "rust1", since = "1.0.0")]); }; - // Equivalent to the non-const version, with the addition of `rustc_const_unstable` - (impl const $imp:ident, $method:ident for $t:ty, $u:ty, #[$attr:meta]) => { - #[$attr] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl<'a> const $imp<$u> for &'a $t { - type Output = <$t as $imp<$u>>::Output; - - #[inline] - fn $method(self, other: $u) -> <$t as $imp<$u>>::Output { - $imp::$method(*self, other) - } - } - - #[$attr] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const $imp<&$u> for $t { - type Output = <$t as $imp<$u>>::Output; - - #[inline] - fn $method(self, other: &$u) -> <$t as $imp<$u>>::Output { - $imp::$method(self, *other) - } - } - - #[$attr] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const $imp<&$u> for &$t { - type Output = <$t as $imp<$u>>::Output; - - #[inline] - fn $method(self, other: &$u) -> <$t as $imp<$u>>::Output { - $imp::$method(*self, *other) - } - } - }; (impl $imp:ident, $method:ident for $t:ty, $u:ty, #[$attr:meta]) => { #[$attr] impl<'a> $imp<$u> for &'a $t { @@ -113,21 +65,6 @@ macro_rules! forward_ref_op_assign { forward_ref_op_assign!(impl $imp, $method for $t, $u, #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]); }; - (impl const $imp:ident, $method:ident for $t:ty, $u:ty) => { - forward_ref_op_assign!(impl const $imp, $method for $t, $u, - #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]); - }; - // Equivalent to the non-const version, with the addition of `rustc_const_unstable` - (impl const $imp:ident, $method:ident for $t:ty, $u:ty, #[$attr:meta]) => { - #[$attr] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const $imp<&$u> for $t { - #[inline] - fn $method(&mut self, other: &$u) { - $imp::$method(self, *other); - } - } - }; (impl $imp:ident, $method:ident for $t:ty, $u:ty, #[$attr:meta]) => { #[$attr] impl $imp<&$u> for $t { diff --git a/library/core/src/iter/sources/empty.rs b/library/core/src/iter/sources/empty.rs index 617dfd12383fb..243df015f9a26 100644 --- a/library/core/src/iter/sources/empty.rs +++ b/library/core/src/iter/sources/empty.rs @@ -81,8 +81,7 @@ impl Clone for Empty { // not #[derive] because that adds a Default bound on T, // which isn't necessary. #[stable(feature = "iter_empty", since = "1.2.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for Empty { +impl Default for Empty { fn default() -> Empty { Empty(marker::PhantomData) } diff --git a/library/core/src/iter/traits/collect.rs b/library/core/src/iter/traits/collect.rs index e099700e3e7c8..76b3a32880d1b 100644 --- a/library/core/src/iter/traits/collect.rs +++ b/library/core/src/iter/traits/collect.rs @@ -228,7 +228,6 @@ pub trait FromIterator: Sized { #[rustc_diagnostic_item = "IntoIterator"] #[rustc_skip_array_during_method_dispatch] #[stable(feature = "rust1", since = "1.0.0")] -#[const_trait] pub trait IntoIterator { /// The type of the elements being iterated over. #[stable(feature = "rust1", since = "1.0.0")] @@ -264,7 +263,7 @@ pub trait IntoIterator { #[rustc_const_unstable(feature = "const_intoiterator_identity", issue = "90603")] #[stable(feature = "rust1", since = "1.0.0")] -impl const IntoIterator for I { +impl IntoIterator for I { type Item = I::Item; type IntoIter = I; diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 02877604248df..dabfce1447483 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -70,7 +70,6 @@ fn _assert_is_object_safe(_: &dyn Iterator) {} #[doc(notable_trait)] #[rustc_diagnostic_item = "Iterator"] #[must_use = "iterators are lazy and do nothing unless consumed"] -#[const_trait] pub trait Iterator { /// The type of the elements being iterated over. #[rustc_diagnostic_item = "IteratorItem"] diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 04243544b8359..8cc67c6a5260d 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -112,11 +112,8 @@ #![feature(const_caller_location)] #![feature(const_cell_into_inner)] #![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)] @@ -137,8 +134,6 @@ #![feature(const_maybe_uninit_assume_init)] #![feature(const_maybe_uninit_uninit_array)] #![feature(const_nonnull_new)] -#![feature(const_num_from_num)] -#![feature(const_ops)] #![feature(const_option)] #![feature(const_option_ext)] #![feature(const_pin)] @@ -161,7 +156,6 @@ #![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)] @@ -209,7 +203,6 @@ #![feature(const_refs_to_cell)] #![feature(decl_macro)] #![feature(deprecated_suggestion)] -#![feature(derive_const)] #![feature(doc_cfg)] #![feature(doc_cfg_hide)] #![feature(doc_notable_trait)] diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index 3cd4f5104ce71..d149ea0320993 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -732,8 +732,7 @@ impl Clone for PhantomData { } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for PhantomData { +impl Default for PhantomData { fn default() -> Self { Self } @@ -858,7 +857,6 @@ impl Unpin for *mut T {} #[unstable(feature = "const_trait_impl", issue = "67792")] #[lang = "destruct"] #[rustc_on_unimplemented(message = "can't drop `{Self}`", append_const_msg)] -#[const_trait] #[rustc_deny_explicit_impl] pub trait Destruct {} diff --git a/library/core/src/mem/manually_drop.rs b/library/core/src/mem/manually_drop.rs index 3d719afe49e4a..5f3d66e3773f1 100644 --- a/library/core/src/mem/manually_drop.rs +++ b/library/core/src/mem/manually_drop.rs @@ -146,8 +146,7 @@ impl ManuallyDrop { } #[stable(feature = "manually_drop", since = "1.20.0")] -#[rustc_const_unstable(feature = "const_deref", issue = "88955")] -impl const Deref for ManuallyDrop { +impl Deref for ManuallyDrop { type Target = T; #[inline(always)] fn deref(&self) -> &T { @@ -156,8 +155,7 @@ impl const Deref for ManuallyDrop { } #[stable(feature = "manually_drop", since = "1.20.0")] -#[rustc_const_unstable(feature = "const_deref", issue = "88955")] -impl const DerefMut for ManuallyDrop { +impl DerefMut for ManuallyDrop { #[inline(always)] fn deref_mut(&mut self) -> &mut T { &mut self.value diff --git a/library/core/src/mem/transmutability.rs b/library/core/src/mem/transmutability.rs index b53a330fa560b..87ae30619c63b 100644 --- a/library/core/src/mem/transmutability.rs +++ b/library/core/src/mem/transmutability.rs @@ -81,8 +81,7 @@ impl Assume { // FIXME(jswrenn): This const op is not actually usable. Why? // https://github.com/rust-lang/rust/pull/100726#issuecomment-1219928926 #[unstable(feature = "transmutability", issue = "99571")] -#[rustc_const_unstable(feature = "transmutability", issue = "99571")] -impl const core::ops::Add for Assume { +impl core::ops::Add for Assume { type Output = Assume; fn add(self, other_assumptions: Assume) -> Assume { @@ -93,8 +92,7 @@ impl const core::ops::Add for Assume { // FIXME(jswrenn): This const op is not actually usable. Why? // https://github.com/rust-lang/rust/pull/100726#issuecomment-1219928926 #[unstable(feature = "transmutability", issue = "99571")] -#[rustc_const_unstable(feature = "transmutability", issue = "99571")] -impl const core::ops::Sub for Assume { +impl core::ops::Sub for Assume { type Output = Assume; fn sub(self, other_assumptions: Assume) -> Assume { diff --git a/library/core/src/num/error.rs b/library/core/src/num/error.rs index 1bae4efe7d936..2ad0f1dc5063e 100644 --- a/library/core/src/num/error.rs +++ b/library/core/src/num/error.rs @@ -26,15 +26,14 @@ impl Error for TryFromIntError { } #[stable(feature = "try_from", since = "1.34.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for TryFromIntError { +impl From for TryFromIntError { fn from(x: Infallible) -> TryFromIntError { match x {} } } #[unstable(feature = "never_type", issue = "35121")] -impl const From for TryFromIntError { +impl From for TryFromIntError { fn from(never: !) -> TryFromIntError { // Match rather than coerce to make sure that code like // `From for TryFromIntError` above will keep working diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index ecfb735fad14a..54e03067d1c7a 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -96,8 +96,7 @@ macro_rules! nonzero_integers { } #[stable(feature = "from_nonzero", since = "1.31.0")] - #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")] - impl const From<$Ty> for $Int { + impl From<$Ty> for $Int { #[doc = concat!("Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`")] #[inline] fn from(nonzero: $Ty) -> Self { @@ -106,8 +105,7 @@ macro_rules! nonzero_integers { } #[stable(feature = "nonzero_bitor", since = "1.45.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitOr for $Ty { + impl BitOr for $Ty { type Output = Self; #[inline] fn bitor(self, rhs: Self) -> Self::Output { @@ -118,8 +116,7 @@ macro_rules! nonzero_integers { } #[stable(feature = "nonzero_bitor", since = "1.45.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitOr<$Int> for $Ty { + impl BitOr<$Int> for $Ty { type Output = Self; #[inline] fn bitor(self, rhs: $Int) -> Self::Output { @@ -131,8 +128,7 @@ macro_rules! nonzero_integers { } #[stable(feature = "nonzero_bitor", since = "1.45.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitOr<$Ty> for $Int { + impl BitOr<$Ty> for $Int { type Output = $Ty; #[inline] fn bitor(self, rhs: $Ty) -> Self::Output { @@ -144,8 +140,7 @@ macro_rules! nonzero_integers { } #[stable(feature = "nonzero_bitor", since = "1.45.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitOrAssign for $Ty { + impl BitOrAssign for $Ty { #[inline] fn bitor_assign(&mut self, rhs: Self) { *self = *self | rhs; @@ -153,8 +148,7 @@ macro_rules! nonzero_integers { } #[stable(feature = "nonzero_bitor", since = "1.45.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitOrAssign<$Int> for $Ty { + impl BitOrAssign<$Int> for $Ty { #[inline] fn bitor_assign(&mut self, rhs: $Int) { *self = *self | rhs; @@ -276,8 +270,7 @@ macro_rules! nonzero_integers_div { ( $( $Ty: ident($Int: ty); )+ ) => { $( #[stable(feature = "nonzero_div", since = "1.51.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Div<$Ty> for $Int { + impl Div<$Ty> for $Int { type Output = $Int; /// This operation rounds towards zero, /// truncating any fractional part of the exact result, and cannot panic. @@ -290,8 +283,7 @@ macro_rules! nonzero_integers_div { } #[stable(feature = "nonzero_div", since = "1.51.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Rem<$Ty> for $Int { + impl Rem<$Ty> for $Int { type Output = $Int; /// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic. #[inline] diff --git a/library/core/src/num/wrapping.rs b/library/core/src/num/wrapping.rs index 5353d900e7662..ed354a2e50bda 100644 --- a/library/core/src/num/wrapping.rs +++ b/library/core/src/num/wrapping.rs @@ -87,8 +87,7 @@ impl fmt::UpperHex for Wrapping { macro_rules! sh_impl_signed { ($t:ident, $f:ident) => { #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Shl<$f> for Wrapping<$t> { + impl Shl<$f> for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -100,22 +99,20 @@ macro_rules! sh_impl_signed { } } } - forward_ref_binop! { impl const Shl, shl for Wrapping<$t>, $f, + forward_ref_binop! { impl Shl, shl for Wrapping<$t>, $f, #[stable(feature = "wrapping_ref_ops", since = "1.39.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const ShlAssign<$f> for Wrapping<$t> { + impl ShlAssign<$f> for Wrapping<$t> { #[inline] fn shl_assign(&mut self, other: $f) { *self = *self << other; } } - forward_ref_op_assign! { impl const ShlAssign, shl_assign for Wrapping<$t>, $f } + forward_ref_op_assign! { impl ShlAssign, shl_assign for Wrapping<$t>, $f } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Shr<$f> for Wrapping<$t> { + impl Shr<$f> for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -127,26 +124,24 @@ macro_rules! sh_impl_signed { } } } - forward_ref_binop! { impl const Shr, shr for Wrapping<$t>, $f, + forward_ref_binop! { impl Shr, shr for Wrapping<$t>, $f, #[stable(feature = "wrapping_ref_ops", since = "1.39.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const ShrAssign<$f> for Wrapping<$t> { + impl ShrAssign<$f> for Wrapping<$t> { #[inline] fn shr_assign(&mut self, other: $f) { *self = *self >> other; } } - forward_ref_op_assign! { impl const ShrAssign, shr_assign for Wrapping<$t>, $f } + forward_ref_op_assign! { impl ShrAssign, shr_assign for Wrapping<$t>, $f } }; } macro_rules! sh_impl_unsigned { ($t:ident, $f:ident) => { #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Shl<$f> for Wrapping<$t> { + impl Shl<$f> for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -154,22 +149,20 @@ macro_rules! sh_impl_unsigned { Wrapping(self.0.wrapping_shl((other & self::shift_max::$t as $f) as u32)) } } - forward_ref_binop! { impl const Shl, shl for Wrapping<$t>, $f, + forward_ref_binop! { impl Shl, shl for Wrapping<$t>, $f, #[stable(feature = "wrapping_ref_ops", since = "1.39.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const ShlAssign<$f> for Wrapping<$t> { + impl ShlAssign<$f> for Wrapping<$t> { #[inline] fn shl_assign(&mut self, other: $f) { *self = *self << other; } } - forward_ref_op_assign! { impl const ShlAssign, shl_assign for Wrapping<$t>, $f } + forward_ref_op_assign! { impl ShlAssign, shl_assign for Wrapping<$t>, $f } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Shr<$f> for Wrapping<$t> { + impl Shr<$f> for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -177,18 +170,17 @@ macro_rules! sh_impl_unsigned { Wrapping(self.0.wrapping_shr((other & self::shift_max::$t as $f) as u32)) } } - forward_ref_binop! { impl const Shr, shr for Wrapping<$t>, $f, + forward_ref_binop! { impl Shr, shr for Wrapping<$t>, $f, #[stable(feature = "wrapping_ref_ops", since = "1.39.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const ShrAssign<$f> for Wrapping<$t> { + impl ShrAssign<$f> for Wrapping<$t> { #[inline] fn shr_assign(&mut self, other: $f) { *self = *self >> other; } } - forward_ref_op_assign! { impl const ShrAssign, shr_assign for Wrapping<$t>, $f } + forward_ref_op_assign! { impl ShrAssign, shr_assign for Wrapping<$t>, $f } }; } @@ -217,8 +209,7 @@ sh_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize } macro_rules! wrapping_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Add for Wrapping<$t> { + impl Add for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -226,32 +217,29 @@ macro_rules! wrapping_impl { Wrapping(self.0.wrapping_add(other.0)) } } - forward_ref_binop! { impl const Add, add for Wrapping<$t>, Wrapping<$t>, + forward_ref_binop! { impl Add, add for Wrapping<$t>, Wrapping<$t>, #[stable(feature = "wrapping_ref", since = "1.14.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const AddAssign for Wrapping<$t> { + impl AddAssign for Wrapping<$t> { #[inline] fn add_assign(&mut self, other: Wrapping<$t>) { *self = *self + other; } } - forward_ref_op_assign! { impl const AddAssign, add_assign for Wrapping<$t>, Wrapping<$t> } + forward_ref_op_assign! { impl AddAssign, add_assign for Wrapping<$t>, Wrapping<$t> } #[stable(feature = "wrapping_int_assign_impl", since = "1.60.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const AddAssign<$t> for Wrapping<$t> { + impl AddAssign<$t> for Wrapping<$t> { #[inline] fn add_assign(&mut self, other: $t) { *self = *self + Wrapping(other); } } - forward_ref_op_assign! { impl const AddAssign, add_assign for Wrapping<$t>, $t } + forward_ref_op_assign! { impl AddAssign, add_assign for Wrapping<$t>, $t } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Sub for Wrapping<$t> { + impl Sub for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -259,32 +247,29 @@ macro_rules! wrapping_impl { Wrapping(self.0.wrapping_sub(other.0)) } } - forward_ref_binop! { impl const Sub, sub for Wrapping<$t>, Wrapping<$t>, + forward_ref_binop! { impl Sub, sub for Wrapping<$t>, Wrapping<$t>, #[stable(feature = "wrapping_ref", since = "1.14.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const SubAssign for Wrapping<$t> { + impl SubAssign for Wrapping<$t> { #[inline] fn sub_assign(&mut self, other: Wrapping<$t>) { *self = *self - other; } } - forward_ref_op_assign! { impl const SubAssign, sub_assign for Wrapping<$t>, Wrapping<$t> } + forward_ref_op_assign! { impl SubAssign, sub_assign for Wrapping<$t>, Wrapping<$t> } #[stable(feature = "wrapping_int_assign_impl", since = "1.60.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const SubAssign<$t> for Wrapping<$t> { + impl SubAssign<$t> for Wrapping<$t> { #[inline] fn sub_assign(&mut self, other: $t) { *self = *self - Wrapping(other); } } - forward_ref_op_assign! { impl const SubAssign, sub_assign for Wrapping<$t>, $t } + forward_ref_op_assign! { impl SubAssign, sub_assign for Wrapping<$t>, $t } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Mul for Wrapping<$t> { + impl Mul for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -296,28 +281,25 @@ macro_rules! wrapping_impl { #[stable(feature = "wrapping_ref", since = "1.14.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const MulAssign for Wrapping<$t> { + impl MulAssign for Wrapping<$t> { #[inline] fn mul_assign(&mut self, other: Wrapping<$t>) { *self = *self * other; } } - forward_ref_op_assign! { impl const MulAssign, mul_assign for Wrapping<$t>, Wrapping<$t> } + forward_ref_op_assign! { impl MulAssign, mul_assign for Wrapping<$t>, Wrapping<$t> } #[stable(feature = "wrapping_int_assign_impl", since = "1.60.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const MulAssign<$t> for Wrapping<$t> { + impl MulAssign<$t> for Wrapping<$t> { #[inline] fn mul_assign(&mut self, other: $t) { *self = *self * Wrapping(other); } } - forward_ref_op_assign! { impl const MulAssign, mul_assign for Wrapping<$t>, $t } + forward_ref_op_assign! { impl MulAssign, mul_assign for Wrapping<$t>, $t } #[stable(feature = "wrapping_div", since = "1.3.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Div for Wrapping<$t> { + impl Div for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -325,32 +307,29 @@ macro_rules! wrapping_impl { Wrapping(self.0.wrapping_div(other.0)) } } - forward_ref_binop! { impl const Div, div for Wrapping<$t>, Wrapping<$t>, + forward_ref_binop! { impl Div, div for Wrapping<$t>, Wrapping<$t>, #[stable(feature = "wrapping_ref", since = "1.14.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const DivAssign for Wrapping<$t> { + impl DivAssign for Wrapping<$t> { #[inline] fn div_assign(&mut self, other: Wrapping<$t>) { *self = *self / other; } } - forward_ref_op_assign! { impl const DivAssign, div_assign for Wrapping<$t>, Wrapping<$t> } + forward_ref_op_assign! { impl DivAssign, div_assign for Wrapping<$t>, Wrapping<$t> } #[stable(feature = "wrapping_int_assign_impl", since = "1.60.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const DivAssign<$t> for Wrapping<$t> { + impl DivAssign<$t> for Wrapping<$t> { #[inline] fn div_assign(&mut self, other: $t) { *self = *self / Wrapping(other); } } - forward_ref_op_assign! { impl const DivAssign, div_assign for Wrapping<$t>, $t } + forward_ref_op_assign! { impl DivAssign, div_assign for Wrapping<$t>, $t } #[stable(feature = "wrapping_impls", since = "1.7.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Rem for Wrapping<$t> { + impl Rem for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -358,32 +337,29 @@ macro_rules! wrapping_impl { Wrapping(self.0.wrapping_rem(other.0)) } } - forward_ref_binop! { impl const Rem, rem for Wrapping<$t>, Wrapping<$t>, + forward_ref_binop! { impl Rem, rem for Wrapping<$t>, Wrapping<$t>, #[stable(feature = "wrapping_ref", since = "1.14.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const RemAssign for Wrapping<$t> { + impl RemAssign for Wrapping<$t> { #[inline] fn rem_assign(&mut self, other: Wrapping<$t>) { *self = *self % other; } } - forward_ref_op_assign! { impl const RemAssign, rem_assign for Wrapping<$t>, Wrapping<$t> } + forward_ref_op_assign! { impl RemAssign, rem_assign for Wrapping<$t>, Wrapping<$t> } #[stable(feature = "wrapping_int_assign_impl", since = "1.60.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const RemAssign<$t> for Wrapping<$t> { + impl RemAssign<$t> for Wrapping<$t> { #[inline] fn rem_assign(&mut self, other: $t) { *self = *self % Wrapping(other); } } - forward_ref_op_assign! { impl const RemAssign, rem_assign for Wrapping<$t>, $t } + forward_ref_op_assign! { impl RemAssign, rem_assign for Wrapping<$t>, $t } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Not for Wrapping<$t> { + impl Not for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -391,12 +367,11 @@ macro_rules! wrapping_impl { Wrapping(!self.0) } } - forward_ref_unop! { impl const Not, not for Wrapping<$t>, + forward_ref_unop! { impl Not, not for Wrapping<$t>, #[stable(feature = "wrapping_ref", since = "1.14.0")] } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitXor for Wrapping<$t> { + impl BitXor for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -404,32 +379,29 @@ macro_rules! wrapping_impl { Wrapping(self.0 ^ other.0) } } - forward_ref_binop! { impl const BitXor, bitxor for Wrapping<$t>, Wrapping<$t>, + forward_ref_binop! { impl BitXor, bitxor for Wrapping<$t>, Wrapping<$t>, #[stable(feature = "wrapping_ref", since = "1.14.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitXorAssign for Wrapping<$t> { + impl BitXorAssign for Wrapping<$t> { #[inline] fn bitxor_assign(&mut self, other: Wrapping<$t>) { *self = *self ^ other; } } - forward_ref_op_assign! { impl const BitXorAssign, bitxor_assign for Wrapping<$t>, Wrapping<$t> } + forward_ref_op_assign! { impl BitXorAssign, bitxor_assign for Wrapping<$t>, Wrapping<$t> } #[stable(feature = "wrapping_int_assign_impl", since = "1.60.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitXorAssign<$t> for Wrapping<$t> { + impl BitXorAssign<$t> for Wrapping<$t> { #[inline] fn bitxor_assign(&mut self, other: $t) { *self = *self ^ Wrapping(other); } } - forward_ref_op_assign! { impl const BitXorAssign, bitxor_assign for Wrapping<$t>, $t } + forward_ref_op_assign! { impl BitXorAssign, bitxor_assign for Wrapping<$t>, $t } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitOr for Wrapping<$t> { + impl BitOr for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -437,32 +409,29 @@ macro_rules! wrapping_impl { Wrapping(self.0 | other.0) } } - forward_ref_binop! { impl const BitOr, bitor for Wrapping<$t>, Wrapping<$t>, + forward_ref_binop! { impl BitOr, bitor for Wrapping<$t>, Wrapping<$t>, #[stable(feature = "wrapping_ref", since = "1.14.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitOrAssign for Wrapping<$t> { + impl BitOrAssign for Wrapping<$t> { #[inline] fn bitor_assign(&mut self, other: Wrapping<$t>) { *self = *self | other; } } - forward_ref_op_assign! { impl const BitOrAssign, bitor_assign for Wrapping<$t>, Wrapping<$t> } + forward_ref_op_assign! { impl BitOrAssign, bitor_assign for Wrapping<$t>, Wrapping<$t> } #[stable(feature = "wrapping_int_assign_impl", since = "1.60.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitOrAssign<$t> for Wrapping<$t> { + impl BitOrAssign<$t> for Wrapping<$t> { #[inline] fn bitor_assign(&mut self, other: $t) { *self = *self | Wrapping(other); } } - forward_ref_op_assign! { impl const BitOrAssign, bitor_assign for Wrapping<$t>, $t } + forward_ref_op_assign! { impl BitOrAssign, bitor_assign for Wrapping<$t>, $t } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitAnd for Wrapping<$t> { + impl BitAnd for Wrapping<$t> { type Output = Wrapping<$t>; #[inline] @@ -470,39 +439,36 @@ macro_rules! wrapping_impl { Wrapping(self.0 & other.0) } } - forward_ref_binop! { impl const BitAnd, bitand for Wrapping<$t>, Wrapping<$t>, + forward_ref_binop! { impl BitAnd, bitand for Wrapping<$t>, Wrapping<$t>, #[stable(feature = "wrapping_ref", since = "1.14.0")] } #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitAndAssign for Wrapping<$t> { + impl BitAndAssign for Wrapping<$t> { #[inline] fn bitand_assign(&mut self, other: Wrapping<$t>) { *self = *self & other; } } - forward_ref_op_assign! { impl const BitAndAssign, bitand_assign for Wrapping<$t>, Wrapping<$t> } + forward_ref_op_assign! { impl BitAndAssign, bitand_assign for Wrapping<$t>, Wrapping<$t> } #[stable(feature = "wrapping_int_assign_impl", since = "1.60.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitAndAssign<$t> for Wrapping<$t> { + impl BitAndAssign<$t> for Wrapping<$t> { #[inline] fn bitand_assign(&mut self, other: $t) { *self = *self & Wrapping(other); } } - forward_ref_op_assign! { impl const BitAndAssign, bitand_assign for Wrapping<$t>, $t } + forward_ref_op_assign! { impl BitAndAssign, bitand_assign for Wrapping<$t>, $t } #[stable(feature = "wrapping_neg", since = "1.10.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Neg for Wrapping<$t> { + impl Neg for Wrapping<$t> { type Output = Self; #[inline] fn neg(self) -> Self { Wrapping(0) - self } } - forward_ref_unop! { impl const Neg, neg for Wrapping<$t>, + forward_ref_unop! { impl Neg, neg for Wrapping<$t>, #[stable(feature = "wrapping_ref", since = "1.14.0")] } )*) diff --git a/library/core/src/ops/arith.rs b/library/core/src/ops/arith.rs index 0c7ee9630c6ee..1501dc4e38b71 100644 --- a/library/core/src/ops/arith.rs +++ b/library/core/src/ops/arith.rs @@ -73,7 +73,6 @@ append_const_msg )] #[doc(alias = "+")] -#[const_trait] pub trait Add { /// The resulting type after applying the `+` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -95,8 +94,7 @@ pub trait Add { macro_rules! add_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Add for $t { + impl Add for $t { type Output = $t; #[inline] @@ -104,7 +102,7 @@ macro_rules! add_impl { fn add(self, other: $t) -> $t { self + other } } - forward_ref_binop! { impl const Add, add for $t, $t } + forward_ref_binop! { impl Add, add for $t, $t } )*) } @@ -183,7 +181,6 @@ add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } append_const_msg )] #[doc(alias = "-")] -#[const_trait] pub trait Sub { /// The resulting type after applying the `-` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -205,8 +202,7 @@ pub trait Sub { macro_rules! sub_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Sub for $t { + impl Sub for $t { type Output = $t; #[inline] @@ -214,7 +210,7 @@ macro_rules! sub_impl { fn sub(self, other: $t) -> $t { self - other } } - forward_ref_binop! { impl const Sub, sub for $t, $t } + forward_ref_binop! { impl Sub, sub for $t, $t } )*) } @@ -314,7 +310,6 @@ sub_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } label = "no implementation for `{Self} * {Rhs}`" )] #[doc(alias = "*")] -#[const_trait] pub trait Mul { /// The resulting type after applying the `*` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -336,8 +331,7 @@ pub trait Mul { macro_rules! mul_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Mul for $t { + impl Mul for $t { type Output = $t; #[inline] @@ -345,7 +339,7 @@ macro_rules! mul_impl { fn mul(self, other: $t) -> $t { self * other } } - forward_ref_binop! { impl const Mul, mul for $t, $t } + forward_ref_binop! { impl Mul, mul for $t, $t } )*) } @@ -449,7 +443,6 @@ mul_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } label = "no implementation for `{Self} / {Rhs}`" )] #[doc(alias = "/")] -#[const_trait] pub trait Div { /// The resulting type after applying the `/` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -477,15 +470,14 @@ macro_rules! div_impl_integer { /// #[doc = $panic] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Div for $t { + impl Div for $t { type Output = $t; #[inline] fn div(self, other: $t) -> $t { self / other } } - forward_ref_binop! { impl const Div, div for $t, $t } + forward_ref_binop! { impl Div, div for $t, $t } )*)*) } @@ -497,15 +489,14 @@ div_impl_integer! { macro_rules! div_impl_float { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Div for $t { + impl Div for $t { type Output = $t; #[inline] fn div(self, other: $t) -> $t { self / other } } - forward_ref_binop! { impl const Div, div for $t, $t } + forward_ref_binop! { impl Div, div for $t, $t } )*) } @@ -553,7 +544,6 @@ div_impl_float! { f32 f64 } label = "no implementation for `{Self} % {Rhs}`" )] #[doc(alias = "%")] -#[const_trait] pub trait Rem { /// The resulting type after applying the `%` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -581,15 +571,14 @@ macro_rules! rem_impl_integer { /// #[doc = $panic] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Rem for $t { + impl Rem for $t { type Output = $t; #[inline] fn rem(self, other: $t) -> $t { self % other } } - forward_ref_binop! { impl const Rem, rem for $t, $t } + forward_ref_binop! { impl Rem, rem for $t, $t } )*)*) } @@ -616,15 +605,14 @@ macro_rules! rem_impl_float { /// assert_eq!(x % y, remainder); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Rem for $t { + impl Rem for $t { type Output = $t; #[inline] fn rem(self, other: $t) -> $t { self % other } } - forward_ref_binop! { impl const Rem, rem for $t, $t } + forward_ref_binop! { impl Rem, rem for $t, $t } )*) } @@ -669,7 +657,6 @@ rem_impl_float! { f32 f64 } #[lang = "neg"] #[stable(feature = "rust1", since = "1.0.0")] #[doc(alias = "-")] -#[const_trait] pub trait Neg { /// The resulting type after applying the `-` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -692,8 +679,7 @@ pub trait Neg { macro_rules! neg_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Neg for $t { + impl Neg for $t { type Output = $t; #[inline] @@ -701,7 +687,7 @@ macro_rules! neg_impl { fn neg(self) -> $t { -self } } - forward_ref_unop! { impl const Neg, neg for $t } + forward_ref_unop! { impl Neg, neg for $t } )*) } @@ -744,7 +730,6 @@ neg_impl! { isize i8 i16 i32 i64 i128 f32 f64 } )] #[doc(alias = "+")] #[doc(alias = "+=")] -#[const_trait] pub trait AddAssign { /// Performs the `+=` operation. /// @@ -762,14 +747,13 @@ pub trait AddAssign { macro_rules! add_assign_impl { ($($t:ty)+) => ($( #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const AddAssign for $t { + impl AddAssign for $t { #[inline] #[rustc_inherit_overflow_checks] fn add_assign(&mut self, other: $t) { *self += other } } - forward_ref_op_assign! { impl const AddAssign, add_assign for $t, $t } + forward_ref_op_assign! { impl AddAssign, add_assign for $t, $t } )+) } @@ -812,7 +796,6 @@ add_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } )] #[doc(alias = "-")] #[doc(alias = "-=")] -#[const_trait] pub trait SubAssign { /// Performs the `-=` operation. /// @@ -830,14 +813,13 @@ pub trait SubAssign { macro_rules! sub_assign_impl { ($($t:ty)+) => ($( #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const SubAssign for $t { + impl SubAssign for $t { #[inline] #[rustc_inherit_overflow_checks] fn sub_assign(&mut self, other: $t) { *self -= other } } - forward_ref_op_assign! { impl const SubAssign, sub_assign for $t, $t } + forward_ref_op_assign! { impl SubAssign, sub_assign for $t, $t } )+) } @@ -871,7 +853,6 @@ sub_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } )] #[doc(alias = "*")] #[doc(alias = "*=")] -#[const_trait] pub trait MulAssign { /// Performs the `*=` operation. /// @@ -889,14 +870,13 @@ pub trait MulAssign { macro_rules! mul_assign_impl { ($($t:ty)+) => ($( #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const MulAssign for $t { + impl MulAssign for $t { #[inline] #[rustc_inherit_overflow_checks] fn mul_assign(&mut self, other: $t) { *self *= other } } - forward_ref_op_assign! { impl const MulAssign, mul_assign for $t, $t } + forward_ref_op_assign! { impl MulAssign, mul_assign for $t, $t } )+) } @@ -930,7 +910,6 @@ mul_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } )] #[doc(alias = "/")] #[doc(alias = "/=")] -#[const_trait] pub trait DivAssign { /// Performs the `/=` operation. /// @@ -948,13 +927,12 @@ pub trait DivAssign { macro_rules! div_assign_impl { ($($t:ty)+) => ($( #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const DivAssign for $t { + impl DivAssign for $t { #[inline] fn div_assign(&mut self, other: $t) { *self /= other } } - forward_ref_op_assign! { impl const DivAssign, div_assign for $t, $t } + forward_ref_op_assign! { impl DivAssign, div_assign for $t, $t } )+) } @@ -992,7 +970,6 @@ div_assign_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } )] #[doc(alias = "%")] #[doc(alias = "%=")] -#[const_trait] pub trait RemAssign { /// Performs the `%=` operation. /// @@ -1010,13 +987,12 @@ pub trait RemAssign { macro_rules! rem_assign_impl { ($($t:ty)+) => ($( #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const RemAssign for $t { + impl RemAssign for $t { #[inline] fn rem_assign(&mut self, other: $t) { *self %= other } } - forward_ref_op_assign! { impl const RemAssign, rem_assign for $t, $t } + forward_ref_op_assign! { impl RemAssign, rem_assign for $t, $t } )+) } diff --git a/library/core/src/ops/bit.rs b/library/core/src/ops/bit.rs index 327009801d1bd..c70f4a3da2ed8 100644 --- a/library/core/src/ops/bit.rs +++ b/library/core/src/ops/bit.rs @@ -31,7 +31,6 @@ #[lang = "not"] #[stable(feature = "rust1", since = "1.0.0")] #[doc(alias = "!")] -#[const_trait] pub trait Not { /// The resulting type after applying the `!` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -55,23 +54,21 @@ pub trait Not { macro_rules! not_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Not for $t { + impl Not for $t { type Output = $t; #[inline] fn not(self) -> $t { !self } } - forward_ref_unop! { impl const Not, not for $t } + forward_ref_unop! { impl Not, not for $t } )*) } not_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } #[stable(feature = "not_never", since = "1.60.0")] -#[rustc_const_unstable(feature = "const_ops", issue = "90080")] -impl const Not for ! { +impl Not for ! { type Output = !; #[inline] @@ -144,7 +141,6 @@ impl const Not for ! { message = "no implementation for `{Self} & {Rhs}`", label = "no implementation for `{Self} & {Rhs}`" )] -#[const_trait] pub trait BitAnd { /// The resulting type after applying the `&` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -168,15 +164,14 @@ pub trait BitAnd { macro_rules! bitand_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitAnd for $t { + impl BitAnd for $t { type Output = $t; #[inline] fn bitand(self, rhs: $t) -> $t { self & rhs } } - forward_ref_binop! { impl const BitAnd, bitand for $t, $t } + forward_ref_binop! { impl BitAnd, bitand for $t, $t } )*) } @@ -246,7 +241,6 @@ bitand_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } message = "no implementation for `{Self} | {Rhs}`", label = "no implementation for `{Self} | {Rhs}`" )] -#[const_trait] pub trait BitOr { /// The resulting type after applying the `|` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -270,15 +264,14 @@ pub trait BitOr { macro_rules! bitor_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitOr for $t { + impl BitOr for $t { type Output = $t; #[inline] fn bitor(self, rhs: $t) -> $t { self | rhs } } - forward_ref_binop! { impl const BitOr, bitor for $t, $t } + forward_ref_binop! { impl BitOr, bitor for $t, $t } )*) } @@ -348,7 +341,6 @@ bitor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } message = "no implementation for `{Self} ^ {Rhs}`", label = "no implementation for `{Self} ^ {Rhs}`" )] -#[const_trait] pub trait BitXor { /// The resulting type after applying the `^` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -372,15 +364,14 @@ pub trait BitXor { macro_rules! bitxor_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitXor for $t { + impl BitXor for $t { type Output = $t; #[inline] fn bitxor(self, other: $t) -> $t { self ^ other } } - forward_ref_binop! { impl const BitXor, bitxor for $t, $t } + forward_ref_binop! { impl BitXor, bitxor for $t, $t } )*) } @@ -449,7 +440,6 @@ bitxor_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } message = "no implementation for `{Self} << {Rhs}`", label = "no implementation for `{Self} << {Rhs}`" )] -#[const_trait] pub trait Shl { /// The resulting type after applying the `<<` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -471,8 +461,7 @@ pub trait Shl { macro_rules! shl_impl { ($t:ty, $f:ty) => { #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Shl<$f> for $t { + impl Shl<$f> for $t { type Output = $t; #[inline] @@ -482,7 +471,7 @@ macro_rules! shl_impl { } } - forward_ref_binop! { impl const Shl, shl for $t, $f } + forward_ref_binop! { impl Shl, shl for $t, $f } }; } @@ -569,7 +558,6 @@ shl_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 isize i128 } message = "no implementation for `{Self} >> {Rhs}`", label = "no implementation for `{Self} >> {Rhs}`" )] -#[const_trait] pub trait Shr { /// The resulting type after applying the `>>` operator. #[stable(feature = "rust1", since = "1.0.0")] @@ -591,8 +579,7 @@ pub trait Shr { macro_rules! shr_impl { ($t:ty, $f:ty) => { #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const Shr<$f> for $t { + impl Shr<$f> for $t { type Output = $t; #[inline] @@ -602,7 +589,7 @@ macro_rules! shr_impl { } } - forward_ref_binop! { impl const Shr, shr for $t, $f } + forward_ref_binop! { impl Shr, shr for $t, $f } }; } @@ -698,7 +685,6 @@ shr_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize } message = "no implementation for `{Self} &= {Rhs}`", label = "no implementation for `{Self} &= {Rhs}`" )] -#[const_trait] pub trait BitAndAssign { /// Performs the `&=` operation. /// @@ -728,13 +714,12 @@ pub trait BitAndAssign { macro_rules! bitand_assign_impl { ($($t:ty)+) => ($( #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitAndAssign for $t { + impl BitAndAssign for $t { #[inline] fn bitand_assign(&mut self, other: $t) { *self &= other } } - forward_ref_op_assign! { impl const BitAndAssign, bitand_assign for $t, $t } + forward_ref_op_assign! { impl BitAndAssign, bitand_assign for $t, $t } )+) } @@ -771,7 +756,6 @@ bitand_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } message = "no implementation for `{Self} |= {Rhs}`", label = "no implementation for `{Self} |= {Rhs}`" )] -#[const_trait] pub trait BitOrAssign { /// Performs the `|=` operation. /// @@ -801,13 +785,12 @@ pub trait BitOrAssign { macro_rules! bitor_assign_impl { ($($t:ty)+) => ($( #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitOrAssign for $t { + impl BitOrAssign for $t { #[inline] fn bitor_assign(&mut self, other: $t) { *self |= other } } - forward_ref_op_assign! { impl const BitOrAssign, bitor_assign for $t, $t } + forward_ref_op_assign! { impl BitOrAssign, bitor_assign for $t, $t } )+) } @@ -844,7 +827,6 @@ bitor_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } message = "no implementation for `{Self} ^= {Rhs}`", label = "no implementation for `{Self} ^= {Rhs}`" )] -#[const_trait] pub trait BitXorAssign { /// Performs the `^=` operation. /// @@ -874,13 +856,12 @@ pub trait BitXorAssign { macro_rules! bitxor_assign_impl { ($($t:ty)+) => ($( #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const BitXorAssign for $t { + impl BitXorAssign for $t { #[inline] fn bitxor_assign(&mut self, other: $t) { *self ^= other } } - forward_ref_op_assign! { impl const BitXorAssign, bitxor_assign for $t, $t } + forward_ref_op_assign! { impl BitXorAssign, bitxor_assign for $t, $t } )+) } @@ -915,7 +896,6 @@ bitxor_assign_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 } message = "no implementation for `{Self} <<= {Rhs}`", label = "no implementation for `{Self} <<= {Rhs}`" )] -#[const_trait] pub trait ShlAssign { /// Performs the `<<=` operation. /// @@ -937,8 +917,7 @@ pub trait ShlAssign { macro_rules! shl_assign_impl { ($t:ty, $f:ty) => { #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const ShlAssign<$f> for $t { + impl ShlAssign<$f> for $t { #[inline] #[rustc_inherit_overflow_checks] fn shl_assign(&mut self, other: $f) { @@ -946,7 +925,7 @@ macro_rules! shl_assign_impl { } } - forward_ref_op_assign! { impl const ShlAssign, shl_assign for $t, $f } + forward_ref_op_assign! { impl ShlAssign, shl_assign for $t, $f } }; } @@ -999,7 +978,6 @@ shl_assign_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize } message = "no implementation for `{Self} >>= {Rhs}`", label = "no implementation for `{Self} >>= {Rhs}`" )] -#[const_trait] pub trait ShrAssign { /// Performs the `>>=` operation. /// @@ -1021,8 +999,7 @@ pub trait ShrAssign { macro_rules! shr_assign_impl { ($t:ty, $f:ty) => { #[stable(feature = "op_assign_traits", since = "1.8.0")] - #[rustc_const_unstable(feature = "const_ops", issue = "90080")] - impl const ShrAssign<$f> for $t { + impl ShrAssign<$f> for $t { #[inline] #[rustc_inherit_overflow_checks] fn shr_assign(&mut self, other: $f) { @@ -1030,7 +1007,7 @@ macro_rules! shr_assign_impl { } } - forward_ref_op_assign! { impl const ShrAssign, shr_assign for $t, $f } + forward_ref_op_assign! { impl ShrAssign, shr_assign for $t, $f } }; } diff --git a/library/core/src/ops/control_flow.rs b/library/core/src/ops/control_flow.rs index 117706fb4b28d..e10c438ef4300 100644 --- a/library/core/src/ops/control_flow.rs +++ b/library/core/src/ops/control_flow.rs @@ -97,8 +97,7 @@ pub enum ControlFlow { } #[unstable(feature = "try_trait_v2", issue = "84277")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const ops::Try for ControlFlow { +impl ops::Try for ControlFlow { type Output = C; type Residual = ControlFlow; @@ -117,8 +116,7 @@ impl const ops::Try for ControlFlow { } #[unstable(feature = "try_trait_v2", issue = "84277")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const ops::FromResidual for ControlFlow { +impl ops::FromResidual for ControlFlow { #[inline] fn from_residual(residual: ControlFlow) -> Self { match residual { @@ -128,8 +126,7 @@ impl const ops::FromResidual for ControlFlow { } #[unstable(feature = "try_trait_v2_residual", issue = "91285")] -#[rustc_const_unstable(feature = "const_try", issue = "74935")] -impl const ops::Residual for ControlFlow { +impl ops::Residual for ControlFlow { type TryType = ControlFlow; } diff --git a/library/core/src/ops/deref.rs b/library/core/src/ops/deref.rs index c67867f4436e4..08c35b6dac309 100644 --- a/library/core/src/ops/deref.rs +++ b/library/core/src/ops/deref.rs @@ -61,7 +61,6 @@ #[doc(alias = "&*")] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_diagnostic_item = "Deref"] -#[const_trait] pub trait Deref { /// The resulting type after dereferencing. #[stable(feature = "rust1", since = "1.0.0")] @@ -77,8 +76,7 @@ pub trait Deref { } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_deref", issue = "88955")] -impl const Deref for &T { +impl Deref for &T { type Target = T; #[rustc_diagnostic_item = "noop_method_deref"] @@ -91,8 +89,7 @@ impl const Deref for &T { impl !DerefMut for &T {} #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_deref", issue = "88955")] -impl const Deref for &mut T { +impl Deref for &mut T { type Target = T; fn deref(&self) -> &T { @@ -170,7 +167,6 @@ impl const Deref for &mut T { #[lang = "deref_mut"] #[doc(alias = "*")] #[stable(feature = "rust1", since = "1.0.0")] -#[const_trait] pub trait DerefMut: Deref { /// Mutably dereferences the value. #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/ops/drop.rs b/library/core/src/ops/drop.rs index a2c3d978cc4fa..de9ddb852df31 100644 --- a/library/core/src/ops/drop.rs +++ b/library/core/src/ops/drop.rs @@ -134,7 +134,6 @@ /// these types cannot have destructors. #[lang = "drop"] #[stable(feature = "rust1", since = "1.0.0")] -#[const_trait] pub trait Drop { /// Executes the destructor for this type. /// diff --git a/library/core/src/ops/function.rs b/library/core/src/ops/function.rs index b7e1aee9d84d1..6c16776b2c209 100644 --- a/library/core/src/ops/function.rs +++ b/library/core/src/ops/function.rs @@ -72,7 +72,6 @@ use crate::marker::Tuple; )] #[fundamental] // so that regex can rely that `&str: !FnMut` #[must_use = "closures are lazy and do nothing unless called"] -#[const_trait] pub trait Fn: FnMut { /// Performs the call operation. #[unstable(feature = "fn_traits", issue = "29625")] @@ -159,7 +158,6 @@ pub trait Fn: FnMut { )] #[fundamental] // so that regex can rely that `&str: !FnMut` #[must_use = "closures are lazy and do nothing unless called"] -#[const_trait] pub trait FnMut: FnOnce { /// Performs the call operation. #[unstable(feature = "fn_traits", issue = "29625")] @@ -238,7 +236,6 @@ pub trait FnMut: FnOnce { )] #[fundamental] // so that regex can rely that `&str: !FnMut` #[must_use = "closures are lazy and do nothing unless called"] -#[const_trait] pub trait FnOnce { /// The returned type after the call operator is used. #[lang = "fn_once_output"] @@ -254,10 +251,9 @@ mod impls { use crate::marker::Tuple; #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")] - impl const Fn for &F + impl Fn for &F where - F: ~const Fn, + F: Fn, { extern "rust-call" fn call(&self, args: A) -> F::Output { (**self).call(args) @@ -265,10 +261,9 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")] - impl const FnMut for &F + impl FnMut for &F where - F: ~const Fn, + F: Fn, { extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output { (**self).call(args) @@ -276,10 +271,9 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")] - impl const FnOnce for &F + impl FnOnce for &F where - F: ~const Fn, + F: Fn, { type Output = F::Output; @@ -289,10 +283,9 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")] - impl const FnMut for &mut F + impl FnMut for &mut F where - F: ~const FnMut, + F: FnMut, { extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output { (*self).call_mut(args) @@ -300,10 +293,9 @@ mod impls { } #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")] - impl const FnOnce for &mut F + impl FnOnce for &mut F where - F: ~const FnMut, + F: FnMut, { type Output = F::Output; extern "rust-call" fn call_once(self, args: A) -> F::Output { diff --git a/library/core/src/ops/index.rs b/library/core/src/ops/index.rs index 228efb0bc0a5c..e2e569cb7ea81 100644 --- a/library/core/src/ops/index.rs +++ b/library/core/src/ops/index.rs @@ -55,7 +55,6 @@ #[doc(alias = "]")] #[doc(alias = "[")] #[doc(alias = "[]")] -#[const_trait] pub trait Index { /// The returned type after indexing. #[stable(feature = "rust1", since = "1.0.0")] @@ -164,8 +163,7 @@ see chapter in The Book : ~const Index { +pub trait IndexMut: Index { /// Performs the mutable indexing (`container[index]`) operation. /// /// # Panics diff --git a/library/core/src/ops/range.rs b/library/core/src/ops/range.rs index b8ab2656473df..6342e40c41c90 100644 --- a/library/core/src/ops/range.rs +++ b/library/core/src/ops/range.rs @@ -96,7 +96,7 @@ impl fmt::Debug for Range { } } -impl> Range { +impl> Range { /// Returns `true` if `item` is contained in the range. /// /// # Examples @@ -119,8 +119,8 @@ impl> Range { #[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] pub const fn contains(&self, item: &U) -> bool where - Idx: ~const PartialOrd, - U: ?Sized + ~const PartialOrd, + Idx: PartialOrd, + U: ?Sized + PartialOrd, { >::contains(self, item) } @@ -201,7 +201,7 @@ impl fmt::Debug for RangeFrom { } } -impl> RangeFrom { +impl> RangeFrom { /// Returns `true` if `item` is contained in the range. /// /// # Examples @@ -216,11 +216,10 @@ impl> RangeFrom { /// assert!(!(f32::NAN..).contains(&0.5)); /// ``` #[stable(feature = "range_contains", since = "1.35.0")] - #[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] - pub const fn contains(&self, item: &U) -> bool + pub fn contains(&self, item: &U) -> bool where - Idx: ~const PartialOrd, - U: ?Sized + ~const PartialOrd, + Idx: PartialOrd, + U: ?Sized + PartialOrd, { >::contains(self, item) } @@ -283,7 +282,7 @@ impl fmt::Debug for RangeTo { } } -impl> RangeTo { +impl> RangeTo { /// Returns `true` if `item` is contained in the range. /// /// # Examples @@ -298,11 +297,10 @@ impl> RangeTo { /// assert!(!(..f32::NAN).contains(&0.5)); /// ``` #[stable(feature = "range_contains", since = "1.35.0")] - #[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] - pub const fn contains(&self, item: &U) -> bool + pub fn contains(&self, item: &U) -> bool where - Idx: ~const PartialOrd, - U: ?Sized + ~const PartialOrd, + Idx: PartialOrd, + U: ?Sized + PartialOrd, { >::contains(self, item) } @@ -474,7 +472,7 @@ impl fmt::Debug for RangeInclusive { } } -impl> RangeInclusive { +impl> RangeInclusive { /// Returns `true` if `item` is contained in the range. /// /// # Examples @@ -505,11 +503,10 @@ impl> RangeInclusive { /// assert!(!r.contains(&3) && !r.contains(&5)); /// ``` #[stable(feature = "range_contains", since = "1.35.0")] - #[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] - pub const fn contains(&self, item: &U) -> bool + pub fn contains(&self, item: &U) -> bool where - Idx: ~const PartialOrd, - U: ?Sized + ~const PartialOrd, + Idx: PartialOrd, + U: ?Sized + PartialOrd, { >::contains(self, item) } @@ -605,7 +602,7 @@ impl fmt::Debug for RangeToInclusive { } } -impl> RangeToInclusive { +impl> RangeToInclusive { /// Returns `true` if `item` is contained in the range. /// /// # Examples @@ -620,11 +617,10 @@ impl> RangeToInclusive { /// assert!(!(..=f32::NAN).contains(&0.5)); /// ``` #[stable(feature = "range_contains", since = "1.35.0")] - #[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] - pub const fn contains(&self, item: &U) -> bool + pub fn contains(&self, item: &U) -> bool where - Idx: ~const PartialOrd, - U: ?Sized + ~const PartialOrd, + Idx: PartialOrd, + U: ?Sized + PartialOrd, { >::contains(self, item) } @@ -765,7 +761,6 @@ impl Bound<&T> { /// `RangeBounds` is implemented by Rust's built-in range types, produced /// by range syntax like `..`, `a..`, `..b`, `..=c`, `d..e`, or `f..=g`. #[stable(feature = "collections_range", since = "1.28.0")] -#[const_trait] pub trait RangeBounds { /// Start index bound. /// @@ -818,8 +813,8 @@ pub trait RangeBounds { #[stable(feature = "range_contains", since = "1.35.0")] fn contains(&self, item: &U) -> bool where - T: ~const PartialOrd, - U: ?Sized + ~const PartialOrd, + T: PartialOrd, + U: ?Sized + PartialOrd, { (match self.start_bound() { Included(start) => start <= item, @@ -836,8 +831,7 @@ pub trait RangeBounds { use self::Bound::{Excluded, Included, Unbounded}; #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for RangeFull { +impl RangeBounds for RangeFull { fn start_bound(&self) -> Bound<&T> { Unbounded } @@ -847,8 +841,7 @@ impl const RangeBounds for RangeFull { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for RangeFrom { +impl RangeBounds for RangeFrom { fn start_bound(&self) -> Bound<&T> { Included(&self.start) } @@ -858,8 +851,7 @@ impl const RangeBounds for RangeFrom { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for RangeTo { +impl RangeBounds for RangeTo { fn start_bound(&self) -> Bound<&T> { Unbounded } @@ -869,8 +861,7 @@ impl const RangeBounds for RangeTo { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for Range { +impl RangeBounds for Range { fn start_bound(&self) -> Bound<&T> { Included(&self.start) } @@ -880,8 +871,7 @@ impl const RangeBounds for Range { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for RangeInclusive { +impl RangeBounds for RangeInclusive { fn start_bound(&self) -> Bound<&T> { Included(&self.start) } @@ -897,8 +887,7 @@ impl const RangeBounds for RangeInclusive { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for RangeToInclusive { +impl RangeBounds for RangeToInclusive { fn start_bound(&self) -> Bound<&T> { Unbounded } @@ -908,8 +897,7 @@ impl const RangeBounds for RangeToInclusive { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for (Bound, Bound) { +impl RangeBounds for (Bound, Bound) { fn start_bound(&self) -> Bound<&T> { match *self { (Included(ref start), _) => Included(start), @@ -928,8 +916,7 @@ impl const RangeBounds for (Bound, Bound) { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl<'a, T: ?Sized + 'a> const RangeBounds for (Bound<&'a T>, Bound<&'a T>) { +impl<'a, T: ?Sized + 'a> RangeBounds for (Bound<&'a T>, Bound<&'a T>) { fn start_bound(&self) -> Bound<&T> { self.0 } @@ -940,8 +927,7 @@ impl<'a, T: ?Sized + 'a> const RangeBounds for (Bound<&'a T>, Bound<&'a T>) { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for RangeFrom<&T> { +impl RangeBounds for RangeFrom<&T> { fn start_bound(&self) -> Bound<&T> { Included(self.start) } @@ -951,8 +937,7 @@ impl const RangeBounds for RangeFrom<&T> { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for RangeTo<&T> { +impl RangeBounds for RangeTo<&T> { fn start_bound(&self) -> Bound<&T> { Unbounded } @@ -962,8 +947,7 @@ impl const RangeBounds for RangeTo<&T> { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for Range<&T> { +impl RangeBounds for Range<&T> { fn start_bound(&self) -> Bound<&T> { Included(self.start) } @@ -973,8 +957,7 @@ impl const RangeBounds for Range<&T> { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for RangeInclusive<&T> { +impl RangeBounds for RangeInclusive<&T> { fn start_bound(&self) -> Bound<&T> { Included(self.start) } @@ -984,8 +967,7 @@ impl const RangeBounds for RangeInclusive<&T> { } #[stable(feature = "collections_range", since = "1.28.0")] -#[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] -impl const RangeBounds for RangeToInclusive<&T> { +impl RangeBounds for RangeToInclusive<&T> { fn start_bound(&self) -> Bound<&T> { Unbounded } diff --git a/library/core/src/ops/try_trait.rs b/library/core/src/ops/try_trait.rs index c254803fbf650..58cc1a408dae1 100644 --- a/library/core/src/ops/try_trait.rs +++ b/library/core/src/ops/try_trait.rs @@ -128,8 +128,7 @@ use crate::ops::ControlFlow; )] #[doc(alias = "?")] #[lang = "Try"] -#[const_trait] -pub trait Try: ~const FromResidual { +pub trait Try: FromResidual { /// The type of the value produced by `?` when *not* short-circuiting. #[unstable(feature = "try_trait_v2", issue = "84277")] type Output; @@ -305,7 +304,6 @@ pub trait Try: ~const FromResidual { )] #[rustc_diagnostic_item = "FromResidual"] #[unstable(feature = "try_trait_v2", issue = "84277")] -#[const_trait] pub trait FromResidual::Residual> { /// Constructs the type from a compatible `Residual` type. /// @@ -358,11 +356,10 @@ where /// and in the other direction, /// ` as Residual>::TryType = Result`. #[unstable(feature = "try_trait_v2_residual", issue = "91285")] -#[const_trait] pub trait Residual { /// The "return" type of this meta-function. #[unstable(feature = "try_trait_v2_residual", issue = "91285")] - type TryType: ~const Try; + type TryType: Try; } #[unstable(feature = "pub_crate_should_not_need_unstable_attr", issue = "none")] @@ -390,15 +387,15 @@ impl NeverShortCircuit { #[inline] pub fn wrap_mut_2( - mut f: impl ~const FnMut(A, B) -> T, - ) -> impl ~const FnMut(A, B) -> Self { - const move |a, b| NeverShortCircuit(f(a, b)) + mut f: impl FnMut(A, B) -> T, + ) -> impl FnMut(A, B) -> Self { + move |a, b| NeverShortCircuit(f(a, b)) } } pub(crate) enum NeverShortCircuitResidual {} -impl const Try for NeverShortCircuit { +impl Try for NeverShortCircuit { type Output = T; type Residual = NeverShortCircuitResidual; @@ -413,14 +410,14 @@ impl const Try for NeverShortCircuit { } } -impl const FromResidual for NeverShortCircuit { +impl FromResidual for NeverShortCircuit { #[inline] fn from_residual(never: NeverShortCircuitResidual) -> Self { match never {} } } -impl const Residual for NeverShortCircuitResidual { +impl Residual for NeverShortCircuitResidual { type TryType = NeverShortCircuit; } diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 057053297cd2d..6c6851d2e533d 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -970,7 +970,7 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn unwrap_or(self, default: T) -> T where - T: ~const Destruct, + T: Destruct, { match self { Some(x) => x, @@ -992,8 +992,8 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn unwrap_or_else(self, f: F) -> T where - F: ~const FnOnce() -> T, - F: ~const Destruct, + F: FnOnce() -> T, + F: Destruct, { match self { Some(x) => x, @@ -1025,7 +1025,7 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn unwrap_or_default(self) -> T where - T: ~const Default, + T: Default, { match self { Some(x) => x, @@ -1092,8 +1092,8 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn map(self, f: F) -> Option where - F: ~const FnOnce(T) -> U, - F: ~const Destruct, + F: FnOnce(T) -> U, + F: Destruct, { match self { Some(x) => Some(f(x)), @@ -1121,8 +1121,8 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn inspect(self, f: F) -> Self where - F: ~const FnOnce(&T), - F: ~const Destruct, + F: FnOnce(&T), + F: Destruct, { if let Some(ref x) = self { f(x); @@ -1154,9 +1154,9 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn map_or(self, default: U, f: F) -> U where - F: ~const FnOnce(T) -> U, - F: ~const Destruct, - U: ~const Destruct, + F: FnOnce(T) -> U, + F: Destruct, + U: Destruct, { match self { Some(t) => f(t), @@ -1183,10 +1183,10 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn map_or_else(self, default: D, f: F) -> U where - D: ~const FnOnce() -> U, - D: ~const Destruct, - F: ~const FnOnce(T) -> U, - F: ~const Destruct, + D: FnOnce() -> U, + D: Destruct, + F: FnOnce(T) -> U, + F: Destruct, { match self { Some(t) => f(t), @@ -1220,7 +1220,7 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn ok_or(self, err: E) -> Result where - E: ~const Destruct, + E: Destruct, { match self { Some(v) => Ok(v), @@ -1249,8 +1249,8 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn ok_or_else(self, err: F) -> Result where - F: ~const FnOnce() -> E, - F: ~const Destruct, + F: FnOnce() -> E, + F: Destruct, { match self { Some(v) => Ok(v), @@ -1277,7 +1277,7 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn as_deref(&self) -> Option<&T::Target> where - T: ~const Deref, + T: Deref, { match self.as_ref() { Some(t) => Some(t.deref()), @@ -1304,7 +1304,7 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn as_deref_mut(&mut self) -> Option<&mut T::Target> where - T: ~const DerefMut, + T: DerefMut, { match self.as_mut() { Some(t) => Some(t.deref_mut()), @@ -1391,8 +1391,8 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn and(self, optb: Option) -> Option where - T: ~const Destruct, - U: ~const Destruct, + T: Destruct, + U: Destruct, { match self { Some(_) => optb, @@ -1433,8 +1433,8 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn and_then(self, f: F) -> Option where - F: ~const FnOnce(T) -> Option, - F: ~const Destruct, + F: FnOnce(T) -> Option, + F: Destruct, { match self { Some(x) => f(x), @@ -1471,9 +1471,9 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn filter

(self, predicate: P) -> Self where - T: ~const Destruct, - P: ~const FnOnce(&T) -> bool, - P: ~const Destruct, + T: Destruct, + P: FnOnce(&T) -> bool, + P: Destruct, { if let Some(x) = self { if predicate(&x) { @@ -1515,7 +1515,7 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn or(self, optb: Option) -> Option where - T: ~const Destruct, + T: Destruct, { match self { Some(x) => Some(x), @@ -1541,8 +1541,8 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn or_else(self, f: F) -> Option where - F: ~const FnOnce() -> Option, - F: ~const Destruct, + F: FnOnce() -> Option, + F: Destruct, { match self { Some(x) => Some(x), @@ -1576,7 +1576,7 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn xor(self, optb: Option) -> Option where - T: ~const Destruct, + T: Destruct, { match (self, optb) { (Some(a), None) => Some(a), @@ -1614,7 +1614,7 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn insert(&mut self, value: T) -> &mut T where - T: ~const Destruct, + T: Destruct, { *self = Some(value); @@ -1647,7 +1647,7 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn get_or_insert(&mut self, value: T) -> &mut T where - T: ~const Destruct, + T: Destruct, { if let None = *self { *self = Some(value); @@ -1682,9 +1682,9 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn get_or_insert_default(&mut self) -> &mut T where - T: ~const Default, + T: Default, { - const fn default() -> T { + const fn default() -> T { T::default() } @@ -1713,8 +1713,8 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn get_or_insert_with(&mut self, f: F) -> &mut T where - F: ~const FnOnce() -> T, - F: ~const Destruct, + F: FnOnce() -> T, + F: Destruct, { if let None = *self { // the compiler isn't smart enough to know that we are not dropping a `T` @@ -1797,8 +1797,8 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn zip(self, other: Option) -> Option<(T, U)> where - T: ~const Destruct, - U: ~const Destruct, + T: Destruct, + U: Destruct, { match (self, other) { (Some(a), Some(b)) => Some((a, b)), @@ -1838,10 +1838,10 @@ impl Option { #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] pub const fn zip_with(self, other: Option, f: F) -> Option where - F: ~const FnOnce(T, U) -> R, - F: ~const Destruct, - T: ~const Destruct, - U: ~const Destruct, + F: FnOnce(T, U) -> R, + F: Destruct, + T: Destruct, + U: Destruct, { match (self, other) { (Some(a), Some(b)) => Some(f(a, b)), @@ -1870,8 +1870,8 @@ impl Option<(T, U)> { #[rustc_const_unstable(feature = "const_option", issue = "67441")] pub const fn unzip(self) -> (Option, Option) where - T: ~const Destruct, - U: ~const Destruct, + T: Destruct, + U: Destruct, { match self { Some((a, b)) => (Some(a), Some(b)), @@ -1925,7 +1925,7 @@ impl Option<&T> { #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] pub const fn cloned(self) -> Option where - T: ~const Clone, + T: Clone, { match self { Some(t) => Some(t.clone()), @@ -1977,7 +1977,7 @@ impl Option<&mut T> { #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] pub const fn cloned(self) -> Option where - T: ~const Clone, + T: Clone, { match self { Some(t) => Some(t.clone()), @@ -2030,10 +2030,9 @@ const fn expect_failed(msg: &str) -> ! { ///////////////////////////////////////////////////////////////////////////// #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_clone", issue = "91805")] -impl const Clone for Option +impl Clone for Option where - T: ~const Clone + ~const Destruct, + T: Clone, { #[inline] fn clone(&self) -> Self { @@ -2053,8 +2052,7 @@ where } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for Option { +impl Default for Option { /// Returns [`None`][Option::None]. /// /// # Examples @@ -2114,8 +2112,7 @@ impl<'a, T> IntoIterator for &'a mut Option { } #[stable(since = "1.12.0", feature = "option_from")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for Option { +impl From for Option { /// Moves `val` into a new [`Some`]. /// /// # Examples @@ -2131,8 +2128,7 @@ impl const From for Option { } #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl<'a, T> const From<&'a Option> for Option<&'a T> { +impl<'a, T> From<&'a Option> for Option<&'a T> { /// Converts from `&Option` to `Option<&T>`. /// /// # Examples @@ -2159,8 +2155,7 @@ impl<'a, T> const From<&'a Option> for Option<&'a T> { } #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl<'a, T> const From<&'a mut Option> for Option<&'a mut T> { +impl<'a, T> From<&'a mut Option> for Option<&'a mut T> { /// Converts from `&mut Option` to `Option<&mut T>` /// /// # Examples @@ -2507,8 +2502,7 @@ impl> FromIterator> for Option { } #[unstable(feature = "try_trait_v2", issue = "84277")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const ops::Try for Option { +impl ops::Try for Option { type Output = T; type Residual = Option; @@ -2527,8 +2521,7 @@ impl const ops::Try for Option { } #[unstable(feature = "try_trait_v2", issue = "84277")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const ops::FromResidual for Option { +impl ops::FromResidual for Option { #[inline] fn from_residual(residual: Option) -> Self { match residual { @@ -2546,8 +2539,7 @@ impl ops::FromResidual> for Option { } #[unstable(feature = "try_trait_v2_residual", issue = "91285")] -#[rustc_const_unstable(feature = "const_try", issue = "74935")] -impl const ops::Residual for Option { +impl ops::Residual for Option { type TryType = Option; } diff --git a/library/core/src/ptr/alignment.rs b/library/core/src/ptr/alignment.rs index efe6d4183e3ea..bbf7199fffa06 100644 --- a/library/core/src/ptr/alignment.rs +++ b/library/core/src/ptr/alignment.rs @@ -9,8 +9,7 @@ use crate::{cmp, fmt, hash, mem, num}; /// Note that particularly large alignments, while representable in this type, /// are likely not to be supported by actual allocators and linkers. #[unstable(feature = "ptr_alignment_type", issue = "102070")] -#[derive(Copy, Clone, Eq)] -#[derive_const(PartialEq)] +#[derive(Copy, Clone, PartialEq, Eq)] #[repr(transparent)] pub struct Alignment(AlignmentEnum); @@ -170,7 +169,7 @@ impl From for usize { #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")] #[unstable(feature = "ptr_alignment_type", issue = "102070")] -impl const cmp::Ord for Alignment { +impl cmp::Ord for Alignment { #[inline] fn cmp(&self, other: &Self) -> cmp::Ordering { self.as_nonzero().get().cmp(&other.as_nonzero().get()) @@ -179,7 +178,7 @@ impl const cmp::Ord for Alignment { #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")] #[unstable(feature = "ptr_alignment_type", issue = "102070")] -impl const cmp::PartialOrd for Alignment { +impl cmp::PartialOrd for Alignment { #[inline] fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) @@ -201,8 +200,7 @@ type AlignmentEnum = AlignmentEnum32; #[cfg(target_pointer_width = "64")] type AlignmentEnum = AlignmentEnum64; -#[derive(Copy, Clone, Eq)] -#[derive_const(PartialEq)] +#[derive(Copy, Clone, PartialEq, Eq)] #[repr(u16)] enum AlignmentEnum16 { _Align1Shl0 = 1 << 0, @@ -223,8 +221,7 @@ enum AlignmentEnum16 { _Align1Shl15 = 1 << 15, } -#[derive(Copy, Clone, Eq)] -#[derive_const(PartialEq)] +#[derive(Copy, Clone, PartialEq, Eq)] #[repr(u32)] enum AlignmentEnum32 { _Align1Shl0 = 1 << 0, @@ -261,8 +258,7 @@ enum AlignmentEnum32 { _Align1Shl31 = 1 << 31, } -#[derive(Copy, Clone, Eq)] -#[derive_const(PartialEq)] +#[derive(Copy, Clone, PartialEq, Eq)] #[repr(u64)] enum AlignmentEnum64 { _Align1Shl0 = 1 << 0, diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 839afc57f85d2..fe6efba600348 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -1654,7 +1654,7 @@ impl *const [T] { #[inline] pub const unsafe fn get_unchecked(self, index: I) -> *const I::Output where - I: ~const SliceIndex<[T]>, + I: SliceIndex<[T]>, { // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds. unsafe { index.get_unchecked(self) } diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index ece5244e9a99c..5af28dea472d8 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -2040,7 +2040,7 @@ impl *mut [T] { #[inline(always)] pub const unsafe fn get_unchecked_mut(self, index: I) -> *mut I::Output where - I: ~const SliceIndex<[T]>, + I: SliceIndex<[T]>, { // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds. unsafe { index.get_unchecked_mut(self) } diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index a46804c186c28..fdb428ff4e680 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -680,7 +680,7 @@ impl NonNull<[T]> { #[inline] pub const unsafe fn get_unchecked_mut(self, index: I) -> NonNull where - I: ~const SliceIndex<[T]>, + I: SliceIndex<[T]>, { // SAFETY: the caller ensures that `self` is dereferenceable and `index` in-bounds. // As a consequence, the resulting pointer cannot be null. @@ -689,8 +689,7 @@ impl NonNull<[T]> { } #[stable(feature = "nonnull", since = "1.25.0")] -#[rustc_const_unstable(feature = "const_clone", issue = "91805")] -impl const Clone for NonNull { +impl Clone for NonNull { #[inline(always)] fn clone(&self) -> Self { *self @@ -756,8 +755,7 @@ impl hash::Hash for NonNull { } #[unstable(feature = "ptr_internals", issue = "none")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From> for NonNull { +impl From> for NonNull { #[inline] fn from(unique: Unique) -> Self { // SAFETY: A Unique pointer cannot be null, so the conditions for @@ -767,8 +765,7 @@ impl const From> for NonNull { } #[stable(feature = "nonnull", since = "1.25.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From<&mut T> for NonNull { +impl From<&mut T> for NonNull { /// Converts a `&mut T` to a `NonNull`. /// /// This conversion is safe and infallible since references cannot be null. @@ -780,8 +777,7 @@ impl const From<&mut T> for NonNull { } #[stable(feature = "nonnull", since = "1.25.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From<&T> for NonNull { +impl From<&T> for NonNull { /// Converts a `&T` to a `NonNull`. /// /// This conversion is safe and infallible since references cannot be null. diff --git a/library/core/src/ptr/unique.rs b/library/core/src/ptr/unique.rs index 64616142b4188..3547897698594 100644 --- a/library/core/src/ptr/unique.rs +++ b/library/core/src/ptr/unique.rs @@ -139,8 +139,7 @@ impl Unique { } #[unstable(feature = "ptr_internals", issue = "none")] -#[rustc_const_unstable(feature = "const_clone", issue = "91805")] -impl const Clone for Unique { +impl Clone for Unique { #[inline] fn clone(&self) -> Self { *self @@ -171,7 +170,7 @@ impl fmt::Pointer for Unique { } #[unstable(feature = "ptr_internals", issue = "none")] -impl const From<&mut T> for Unique { +impl From<&mut T> for Unique { /// Converts a `&mut T` to a `Unique`. /// /// This conversion is infallible since references cannot be null. @@ -182,7 +181,7 @@ impl const From<&mut T> for Unique { } #[unstable(feature = "ptr_internals", issue = "none")] -impl const From> for Unique { +impl From> for Unique { /// Converts a `NonNull` to a `Unique`. /// /// This conversion is infallible since `NonNull` cannot be null. diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 241602c0e18f1..967fee2a6addf 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -632,13 +632,11 @@ impl Result { #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] pub const fn ok(self) -> Option where - E: ~const Destruct, + E: Destruct, { match self { Ok(x) => Some(x), - // FIXME: ~const Drop doesn't quite work right yet - #[allow(unused_variables)] - Err(x) => None, + Err(_) => None, } } @@ -661,12 +659,10 @@ impl Result { #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] pub const fn err(self) -> Option where - T: ~const Destruct, + T: Destruct, { match self { - // FIXME: ~const Drop doesn't quite work right yet - #[allow(unused_variables)] - Ok(x) => None, + Ok(_) => None, Err(x) => Some(x), } } @@ -1291,14 +1287,12 @@ impl Result { #[stable(feature = "rust1", since = "1.0.0")] pub const fn and(self, res: Result) -> Result where - T: ~const Destruct, - U: ~const Destruct, - E: ~const Destruct, + T: Destruct, + U: Destruct, + E: Destruct, { match self { - // FIXME: ~const Drop doesn't quite work right yet - #[allow(unused_variables)] - Ok(x) => res, + Ok(_) => res, Err(e) => Err(e), } } @@ -1374,15 +1368,13 @@ impl Result { #[stable(feature = "rust1", since = "1.0.0")] pub const fn or(self, res: Result) -> Result where - T: ~const Destruct, - E: ~const Destruct, - F: ~const Destruct, + T: Destruct, + E: Destruct, + F: Destruct, { match self { Ok(v) => Ok(v), - // FIXME: ~const Drop doesn't quite work right yet - #[allow(unused_variables)] - Err(e) => res, + Err(_) => res, } } @@ -1434,14 +1426,12 @@ impl Result { #[stable(feature = "rust1", since = "1.0.0")] pub const fn unwrap_or(self, default: T) -> T where - T: ~const Destruct, - E: ~const Destruct, + T: Destruct, + E: Destruct, { match self { Ok(t) => t, - // FIXME: ~const Drop doesn't quite work right yet - #[allow(unused_variables)] - Err(e) => default, + Err(_) => default, } } @@ -1704,11 +1694,10 @@ fn unwrap_failed(_msg: &str, _error: &T) -> ! { ///////////////////////////////////////////////////////////////////////////// #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_clone", issue = "91805")] -impl const Clone for Result +impl Clone for Result where - T: ~const Clone + ~const Destruct, - E: ~const Clone + ~const Destruct, + T: Clone, + E: Clone, { #[inline] fn clone(&self) -> Self { @@ -1971,8 +1960,7 @@ impl> FromIterator> for Result { } #[unstable(feature = "try_trait_v2", issue = "84277")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const ops::Try for Result { +impl ops::Try for Result { type Output = T; type Residual = Result; @@ -1991,8 +1979,7 @@ impl const ops::Try for Result { } #[unstable(feature = "try_trait_v2", issue = "84277")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl> const ops::FromResidual> +impl> ops::FromResidual> for Result { #[inline] @@ -2013,7 +2000,6 @@ impl> ops::FromResidual> for Result { } #[unstable(feature = "try_trait_v2_residual", issue = "91285")] -#[rustc_const_unstable(feature = "const_try", issue = "74935")] -impl const ops::Residual for Result { +impl ops::Residual for Result { type TryType = Result; } diff --git a/library/core/src/slice/index.rs b/library/core/src/slice/index.rs index 3539353240a9b..6ef9f9c95e843 100644 --- a/library/core/src/slice/index.rs +++ b/library/core/src/slice/index.rs @@ -7,10 +7,9 @@ use crate::ops; use crate::ptr; #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -impl const ops::Index for [T] +impl ops::Index for [T] where - I: ~const SliceIndex<[T]>, + I: SliceIndex<[T]>, { type Output = I::Output; @@ -21,10 +20,9 @@ where } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -impl const ops::IndexMut for [T] +impl ops::IndexMut for [T] where - I: ~const SliceIndex<[T]>, + I: SliceIndex<[T]>, { #[inline] fn index_mut(&mut self, index: I) -> &mut I::Output { @@ -162,7 +160,6 @@ mod private_slice_index { message = "the type `{T}` cannot be indexed by `{Self}`", label = "slice indices are of type `usize` or ranges of `usize`" )] -#[const_trait] pub unsafe trait SliceIndex: private_slice_index::Sealed { /// The output type returned by methods. #[stable(feature = "slice_get_slice", since = "1.28.0")] @@ -211,7 +208,7 @@ pub unsafe trait SliceIndex: private_slice_index::Sealed { #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex<[T]> for usize { +unsafe impl SliceIndex<[T]> for usize { type Output = T; #[inline] @@ -271,7 +268,7 @@ unsafe impl const SliceIndex<[T]> for usize { /// Because `IndexRange` guarantees `start <= end`, fewer checks are needed here /// than there are for a general `Range` (which might be `100..3`). #[rustc_const_unstable(feature = "const_index_range_slice_index", issue = "none")] -unsafe impl const SliceIndex<[T]> for ops::IndexRange { +unsafe impl SliceIndex<[T]> for ops::IndexRange { type Output = [T]; #[inline] @@ -347,7 +344,7 @@ unsafe impl const SliceIndex<[T]> for ops::IndexRange { #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex<[T]> for ops::Range { +unsafe impl SliceIndex<[T]> for ops::Range { type Output = [T]; #[inline] @@ -428,7 +425,7 @@ unsafe impl const SliceIndex<[T]> for ops::Range { #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex<[T]> for ops::RangeTo { +unsafe impl SliceIndex<[T]> for ops::RangeTo { type Output = [T]; #[inline] @@ -466,7 +463,7 @@ unsafe impl const SliceIndex<[T]> for ops::RangeTo { #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex<[T]> for ops::RangeFrom { +unsafe impl SliceIndex<[T]> for ops::RangeFrom { type Output = [T]; #[inline] @@ -512,7 +509,7 @@ unsafe impl const SliceIndex<[T]> for ops::RangeFrom { #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex<[T]> for ops::RangeFull { +unsafe impl SliceIndex<[T]> for ops::RangeFull { type Output = [T]; #[inline] @@ -548,7 +545,7 @@ unsafe impl const SliceIndex<[T]> for ops::RangeFull { #[stable(feature = "inclusive_range", since = "1.26.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex<[T]> for ops::RangeInclusive { +unsafe impl SliceIndex<[T]> for ops::RangeInclusive { type Output = [T]; #[inline] @@ -592,7 +589,7 @@ unsafe impl const SliceIndex<[T]> for ops::RangeInclusive { #[stable(feature = "inclusive_range", since = "1.26.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex<[T]> for ops::RangeToInclusive { +unsafe impl SliceIndex<[T]> for ops::RangeToInclusive { type Output = [T]; #[inline] diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index f541808a61836..992a088b91111 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -338,7 +338,7 @@ impl [T] { #[must_use] pub const fn get(&self, index: I) -> Option<&I::Output> where - I: ~const SliceIndex, + I: SliceIndex, { index.get(self) } @@ -364,7 +364,7 @@ impl [T] { #[must_use] pub const fn get_mut(&mut self, index: I) -> Option<&mut I::Output> where - I: ~const SliceIndex, + I: SliceIndex, { index.get_mut(self) } @@ -397,7 +397,7 @@ impl [T] { #[must_use] pub const unsafe fn get_unchecked(&self, index: I) -> &I::Output where - I: ~const SliceIndex, + I: SliceIndex, { // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`; // the slice is dereferenceable because `self` is a safe reference. @@ -435,7 +435,7 @@ impl [T] { #[must_use] pub const unsafe fn get_unchecked_mut(&mut self, index: I) -> &mut I::Output where - I: ~const SliceIndex, + I: SliceIndex, { // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`; // the slice is dereferenceable because `self` is a safe reference. @@ -4404,8 +4404,7 @@ where } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for &[T] { +impl Default for &[T] { /// Creates an empty slice. fn default() -> Self { &[] @@ -4413,8 +4412,7 @@ impl const Default for &[T] { } #[stable(feature = "mut_slice_default", since = "1.5.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for &mut [T] { +impl Default for &mut [T] { /// Creates a mutable empty slice. fn default() -> Self { &mut [] diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index 0416942994967..1ab27d567ca86 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -438,7 +438,7 @@ impl str { #[stable(feature = "str_checked_slicing", since = "1.20.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] - pub const fn get>(&self, i: I) -> Option<&I::Output> { + pub const fn get>(&self, i: I) -> Option<&I::Output> { i.get(self) } @@ -471,7 +471,7 @@ impl str { #[stable(feature = "str_checked_slicing", since = "1.20.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] - pub const fn get_mut>(&mut self, i: I) -> Option<&mut I::Output> { + pub const fn get_mut>(&mut self, i: I) -> Option<&mut I::Output> { i.get_mut(self) } @@ -504,7 +504,7 @@ impl str { #[stable(feature = "str_checked_slicing", since = "1.20.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] - pub const unsafe fn get_unchecked>(&self, i: I) -> &I::Output { + pub const unsafe fn get_unchecked>(&self, i: I) -> &I::Output { // SAFETY: the caller must uphold the safety contract for `get_unchecked`; // the slice is dereferenceable because `self` is a safe reference. // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is. @@ -540,7 +540,7 @@ impl str { #[stable(feature = "str_checked_slicing", since = "1.20.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] - pub const unsafe fn get_unchecked_mut>( + pub const unsafe fn get_unchecked_mut>( &mut self, i: I, ) -> &mut I::Output { @@ -2582,8 +2582,7 @@ impl AsRef<[u8]> for str { } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for &str { +impl Default for &str { /// Creates an empty str #[inline] fn default() -> Self { diff --git a/library/core/src/str/traits.rs b/library/core/src/str/traits.rs index 41c097b55eefb..1d52335f28ebf 100644 --- a/library/core/src/str/traits.rs +++ b/library/core/src/str/traits.rs @@ -50,10 +50,9 @@ impl PartialOrd for str { } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -impl const ops::Index for str +impl ops::Index for str where - I: ~const SliceIndex, + I: SliceIndex, { type Output = I::Output; @@ -64,10 +63,9 @@ where } #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -impl const ops::IndexMut for str +impl ops::IndexMut for str where - I: ~const SliceIndex, + I: SliceIndex, { #[inline] fn index_mut(&mut self, index: I) -> &mut I::Output { @@ -96,7 +94,7 @@ const fn str_index_overflow_fail() -> ! { /// Equivalent to `&self[0 .. len]` or `&mut self[0 .. len]`. #[stable(feature = "str_checked_slicing", since = "1.20.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex for ops::RangeFull { +unsafe impl SliceIndex for ops::RangeFull { type Output = str; #[inline] fn get(self, slice: &str) -> Option<&Self::Output> { @@ -161,7 +159,7 @@ unsafe impl const SliceIndex for ops::RangeFull { /// ``` #[stable(feature = "str_checked_slicing", since = "1.20.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex for ops::Range { +unsafe impl SliceIndex for ops::Range { type Output = str; #[inline] fn get(self, slice: &str) -> Option<&Self::Output> { @@ -271,7 +269,7 @@ unsafe impl const SliceIndex for ops::Range { /// character (as defined by `is_char_boundary`), or if `end > len`. #[stable(feature = "str_checked_slicing", since = "1.20.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex for ops::RangeTo { +unsafe impl SliceIndex for ops::RangeTo { type Output = str; #[inline] fn get(self, slice: &str) -> Option<&Self::Output> { @@ -340,7 +338,7 @@ unsafe impl const SliceIndex for ops::RangeTo { /// a character (as defined by `is_char_boundary`), or if `begin > len`. #[stable(feature = "str_checked_slicing", since = "1.20.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex for ops::RangeFrom { +unsafe impl SliceIndex for ops::RangeFrom { type Output = str; #[inline] fn get(self, slice: &str) -> Option<&Self::Output> { @@ -412,7 +410,7 @@ unsafe impl const SliceIndex for ops::RangeFrom { /// byte offset or equal to `len`), if `begin > end`, or if `end >= len`. #[stable(feature = "inclusive_range", since = "1.26.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex for ops::RangeInclusive { +unsafe impl SliceIndex for ops::RangeInclusive { type Output = str; #[inline] fn get(self, slice: &str) -> Option<&Self::Output> { @@ -464,7 +462,7 @@ unsafe impl const SliceIndex for ops::RangeInclusive { /// `is_char_boundary`, or equal to `len`), or if `end >= len`. #[stable(feature = "inclusive_range", since = "1.26.0")] #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] -unsafe impl const SliceIndex for ops::RangeToInclusive { +unsafe impl SliceIndex for ops::RangeToInclusive { type Output = str; #[inline] fn get(self, slice: &str) -> Option<&Self::Output> { diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 2f6b1c74da08e..b0ab634905ffe 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -147,8 +147,7 @@ pub struct AtomicBool { #[cfg(target_has_atomic_load_store = "8")] #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for AtomicBool { +impl Default for AtomicBool { /// Creates an `AtomicBool` initialized to `false`. #[inline] fn default() -> Self { @@ -179,8 +178,7 @@ pub struct AtomicPtr { #[cfg(target_has_atomic_load_store = "ptr")] #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for AtomicPtr { +impl Default for AtomicPtr { /// Creates a null `AtomicPtr`. fn default() -> AtomicPtr { AtomicPtr::new(crate::ptr::null_mut()) @@ -1916,8 +1914,7 @@ impl AtomicPtr { #[cfg(target_has_atomic_load_store = "8")] #[stable(feature = "atomic_bool_from", since = "1.24.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for AtomicBool { +impl From for AtomicBool { /// Converts a `bool` into an `AtomicBool`. /// /// # Examples @@ -1935,8 +1932,7 @@ impl const From for AtomicBool { #[cfg(target_has_atomic_load_store = "ptr")] #[stable(feature = "atomic_from", since = "1.23.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From<*mut T> for AtomicPtr { +impl From<*mut T> for AtomicPtr { /// Converts a `*mut T` into an `AtomicPtr`. #[inline] fn from(p: *mut T) -> Self { @@ -2002,8 +1998,7 @@ macro_rules! atomic_int { pub const $atomic_init: $atomic_type = $atomic_type::new(0); #[$stable] - #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] - impl const Default for $atomic_type { + impl Default for $atomic_type { #[inline] fn default() -> Self { Self::new(Default::default()) @@ -2011,8 +2006,7 @@ macro_rules! atomic_int { } #[$stable_from] - #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")] - impl const From<$int_type> for $atomic_type { + impl From<$int_type> for $atomic_type { #[doc = concat!("Converts an `", stringify!($int_type), "` into an `", stringify!($atomic_type), "`.")] #[inline] fn from(v: $int_type) -> Self { Self::new(v) } diff --git a/library/core/src/task/poll.rs b/library/core/src/task/poll.rs index af5bf441bb25f..168516263f190 100644 --- a/library/core/src/task/poll.rs +++ b/library/core/src/task/poll.rs @@ -247,8 +247,7 @@ impl Poll>> { } #[stable(feature = "futures_api", since = "1.36.0")] -#[rustc_const_unstable(feature = "const_convert", issue = "88674")] -impl const From for Poll { +impl From for Poll { /// Moves the value into a [`Poll::Ready`] to make a `Poll`. /// /// # Example diff --git a/library/core/src/tuple.rs b/library/core/src/tuple.rs index 0620e7173bc17..75d7a3f40058e 100644 --- a/library/core/src/tuple.rs +++ b/library/core/src/tuple.rs @@ -22,8 +22,7 @@ macro_rules! tuple_impls { maybe_tuple_doc! { $($T)+ @ #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl<$($T: ~const PartialEq),+> const PartialEq for ($($T,)+) + impl<$($T: PartialEq),+> PartialEq for ($($T,)+) where last_type!($($T,)+): ?Sized { @@ -50,8 +49,7 @@ macro_rules! tuple_impls { maybe_tuple_doc! { $($T)+ @ #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl<$($T: ~const PartialOrd + ~const PartialEq),+> const PartialOrd for ($($T,)+) + impl<$($T: PartialOrd),+> PartialOrd for ($($T,)+) where last_type!($($T,)+): ?Sized { @@ -81,8 +79,7 @@ macro_rules! tuple_impls { maybe_tuple_doc! { $($T)+ @ #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cmp", issue = "92391")] - impl<$($T: ~const Ord),+> const Ord for ($($T,)+) + impl<$($T: Ord),+> Ord for ($($T,)+) where last_type!($($T,)+): ?Sized { @@ -96,8 +93,7 @@ macro_rules! tuple_impls { maybe_tuple_doc! { $($T)+ @ #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] - impl<$($T: ~const Default),+> const Default for ($($T,)+) { + impl<$($T: Default),+> Default for ($($T,)+) { #[inline] fn default() -> ($($T,)+) { ($({ let x: $T = Default::default(); x},)+) diff --git a/library/core/tests/cmp.rs b/library/core/tests/cmp.rs index 8d0e59d5a4972..dc5b8a3991449 100644 --- a/library/core/tests/cmp.rs +++ b/library/core/tests/cmp.rs @@ -222,13 +222,13 @@ mod const_cmp { struct S(i32); - impl const PartialEq for S { + impl PartialEq for S { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } - impl const PartialOrd for S { + impl PartialOrd for S { fn partial_cmp(&self, other: &Self) -> Option { let ret = match (self.0, other.0) { (a, b) if a > b => Ordering::Greater, diff --git a/library/core/tests/hash/mod.rs b/library/core/tests/hash/mod.rs index 267245f05dcd2..2f4b9c7410155 100644 --- a/library/core/tests/hash/mod.rs +++ b/library/core/tests/hash/mod.rs @@ -9,13 +9,13 @@ struct MyHasher { hash: u64, } -impl const Default for MyHasher { +impl Default for MyHasher { fn default() -> MyHasher { MyHasher { hash: 0 } } } -impl const Hasher for MyHasher { +impl Hasher for MyHasher { fn write(&mut self, buf: &[u8]) { // FIXME(const_trait_impl): change to for loop let mut i = 0; @@ -35,7 +35,7 @@ impl const Hasher for MyHasher { #[test] fn test_writer_hasher() { - const fn hash(t: &T) -> u64 { + const fn hash(t: &T) -> u64 { let mut s = MyHasher { hash: 0 }; t.hash(&mut s); s.finish() @@ -113,7 +113,7 @@ struct CustomHasher { output: u64, } -impl const Hasher for CustomHasher { +impl Hasher for CustomHasher { fn finish(&self) -> u64 { self.output } @@ -125,21 +125,21 @@ impl const Hasher for CustomHasher { } } -impl const Default for CustomHasher { +impl Default for CustomHasher { fn default() -> CustomHasher { CustomHasher { output: 0 } } } -impl const Hash for Custom { - fn hash(&self, state: &mut H) { +impl Hash for Custom { + fn hash(&self, state: &mut H) { state.write_u64(self.hash); } } #[test] fn test_custom_state() { - const fn hash(t: &T) -> u64 { + const fn hash(t: &T) -> u64 { let mut c = CustomHasher { output: 0 }; t.hash(&mut c); c.finish() diff --git a/library/core/tests/hash/sip.rs b/library/core/tests/hash/sip.rs index 3abf6efcfa9ba..4b9f472625d69 100644 --- a/library/core/tests/hash/sip.rs +++ b/library/core/tests/hash/sip.rs @@ -28,7 +28,7 @@ const fn test_const_sip() { let val1 = 0x45; let val2 = 0xfeed; - const fn const_hash(x: &T) -> u64 { + const fn const_hash(x: &T) -> u64 { let mut st = SipHasher::new(); x.hash(&mut st); st.finish() diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index 3afc8287ecc00..c722bad2e4f63 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -3168,8 +3168,7 @@ impl DefaultHasher { } #[stable(feature = "hashmap_default_hasher", since = "1.13.0")] -#[rustc_const_unstable(feature = "const_hash", issue = "104061")] -impl const Default for DefaultHasher { +impl Default for DefaultHasher { /// Creates a new `DefaultHasher` using [`new`]. /// See its documentation for more. /// @@ -3181,8 +3180,7 @@ impl const Default for DefaultHasher { } #[stable(feature = "hashmap_default_hasher", since = "1.13.0")] -#[rustc_const_unstable(feature = "const_hash", issue = "104061")] -impl const Hasher for DefaultHasher { +impl Hasher for DefaultHasher { // The underlying `SipHasher13` doesn't override the other // `write_*` methods, so it's ok not to forward them here. diff --git a/library/std/src/sync/once_lock.rs b/library/std/src/sync/once_lock.rs index 8c34375ea0712..36951c4f13e9c 100644 --- a/library/std/src/sync/once_lock.rs +++ b/library/std/src/sync/once_lock.rs @@ -344,8 +344,7 @@ impl RefUnwindSafe for OnceLock {} impl UnwindSafe for OnceLock {} #[stable(feature = "once_cell", since = "CURRENT_RUSTC_VERSION")] -#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] -impl const Default for OnceLock { +impl Default for OnceLock { /// Creates a new empty cell. /// /// # Example From 8cda8df578d77ee989de9d4a44db6991d0b06cfd Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 07:00:52 +0000 Subject: [PATCH 045/228] memchr hack --- library/core/src/slice/memchr.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/library/core/src/slice/memchr.rs b/library/core/src/slice/memchr.rs index 98c8349eb6024..8ceca7f9185c6 100644 --- a/library/core/src/slice/memchr.rs +++ b/library/core/src/slice/memchr.rs @@ -83,8 +83,11 @@ const fn memchr_aligned(x: u8, text: &[u8]) -> Option { let mut offset = ptr.align_offset(USIZE_BYTES); if offset > 0 { - offset = cmp::min(offset, len); - if let Some(index) = memchr_naive(x, &text[..offset]) { + // FIXME(const-hack, fee1-dead): replace with min + offset = if offset < len { offset } else { len }; + // FIXME(const-hack, fee1-dead): replace with range slicing + let slice = unsafe { super::from_raw_parts(text.as_ptr(), offset) }; + if let Some(index) = memchr_naive(x, slice) { return Some(index); } } @@ -110,7 +113,9 @@ const fn memchr_aligned(x: u8, text: &[u8]) -> Option { // Find the byte after the point the body loop stopped. // FIXME(const-hack): Use `?` instead. - if let Some(i) = memchr_naive(x, &text[offset..]) { Some(offset + i) } else { None } + // FIXME(const-hack, fee1-dead): use range slicing + let slice = unsafe { super::from_raw_parts(text.as_ptr().add(offset), text.len() - offset) }; + if let Some(i) = memchr_naive(x, slice) { Some(offset + i) } else { None } } /// Returns the last index matching the byte `x` in `text`. From d88f979437299dfda0f5214ec14e809a10e10ff0 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 07:04:17 +0000 Subject: [PATCH 046/228] hack signum as well --- library/core/src/num/int_macros.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index aec15212d7ff7..d645e8dcbfd22 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -2603,13 +2603,16 @@ macro_rules! int_impl { #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline(always)] - #[rustc_allow_const_fn_unstable(const_cmp)] pub const fn signum(self) -> Self { // Picking the right way to phrase this is complicated // () // so delegate it to `Ord` which is already producing -1/0/+1 // exactly like we need and can be the place to deal with the complexity. - self.cmp(&0) as _ + + // FIXME(const-hack): replace with cmp + if self < 0 { -1 } + else if self == 0 { 0 } + else { 1 } } /// Returns `true` if `self` is positive and `false` if the number is zero or From ddc02b0f321da0e16e4abb4d0515440055c3bbd7 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 07:05:54 +0000 Subject: [PATCH 047/228] hack cstr is_empty --- library/core/src/ffi/c_str.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index 4a5306ccaa792..25595328c6503 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -536,7 +536,8 @@ impl CStr { pub const fn is_empty(&self) -> bool { // SAFETY: We know there is at least one byte; for empty strings it // is the NUL terminator. - (unsafe { self.inner.get_unchecked(0) }) == &0 + // FIXME(const-hack): use get_unchecked + unsafe { *self.inner.as_ptr() == 0 } } /// Converts this C string to a byte slice. From e80c0204455534c5d9ec4f92dd8bffd392513fc3 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 07:20:15 +0000 Subject: [PATCH 048/228] more hacks --- library/core/src/num/int_macros.rs | 6 ++++-- library/core/src/num/mod.rs | 1 - library/core/src/num/uint_macros.rs | 6 ++++-- library/core/src/ptr/mod.rs | 7 ++++++- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index d645e8dcbfd22..1e82d4d1ff0bb 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -785,7 +785,8 @@ macro_rules! int_impl { // SAFETY: the caller must uphold the safety contract for // `unchecked_shl`. // Any legal shift amount is losslessly representable in the self type. - unsafe { intrinsics::unchecked_shl(self, rhs.try_into().ok().unwrap_unchecked()) } + // FIXME(const-hack) replace with `.try_into().ok().unwrap_unchecked()`. + unsafe { intrinsics::unchecked_shl(self, rhs as _) } } /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is @@ -833,7 +834,8 @@ macro_rules! int_impl { // SAFETY: the caller must uphold the safety contract for // `unchecked_shr`. // Any legal shift amount is losslessly representable in the self type. - unsafe { intrinsics::unchecked_shr(self, rhs.try_into().ok().unwrap_unchecked()) } + // FIXME(const-hack) replace with `.try_into().ok().unwrap_unchecked()`. + unsafe { intrinsics::unchecked_shr(self, rhs as _) } } /// Checked absolute value. Computes `self.abs()`, returning `None` if diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index 9b812bbfc236b..b0488dc069b79 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -3,7 +3,6 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::ascii; -use crate::convert::TryInto; use crate::intrinsics; use crate::mem; use crate::ops::{Add, Mul, Sub}; diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index 114deeea38767..795645b8b7b87 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -939,7 +939,8 @@ macro_rules! uint_impl { // SAFETY: the caller must uphold the safety contract for // `unchecked_shl`. // Any legal shift amount is losslessly representable in the self type. - unsafe { intrinsics::unchecked_shl(self, rhs.try_into().ok().unwrap_unchecked()) } + // FIXME(const-hack) replace with `.try_into().ok().unwrap_unchecked()`. + unsafe { intrinsics::unchecked_shl(self, rhs as _) } } /// Checked shift right. Computes `self >> rhs`, returning `None` @@ -987,7 +988,8 @@ macro_rules! uint_impl { // SAFETY: the caller must uphold the safety contract for // `unchecked_shr`. // Any legal shift amount is losslessly representable in the self type. - unsafe { intrinsics::unchecked_shr(self, rhs.try_into().ok().unwrap_unchecked()) } + // FIXME(const-hack) replace with `.try_into().ok().unwrap_unchecked()`. + unsafe { intrinsics::unchecked_shr(self, rhs as _) } } /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 818f1a919d0d5..555d58fad8440 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -1764,7 +1764,12 @@ pub(crate) const unsafe fn align_offset(p: *const T, a: usize) -> usiz // miracles, given the situations this case has to deal with. // SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above. - let gcdpow = unsafe { cttz_nonzero(stride).min(cttz_nonzero(a)) }; + // FIXME(const-hack) replace with min + let gcdpow = unsafe { + let x = cttz_nonzero(stride); + let y = cttz_nonzero(a); + if x < y { x } else { y } + }; // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a usize. let gcd = unsafe { unchecked_shl(1usize, gcdpow) }; // SAFETY: gcd is always greater or equal to 1. From 63e0ddbf1d820ee62892eee7a50e381d964f1dec Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 07:20:26 +0000 Subject: [PATCH 049/228] core is now compilable --- library/alloc/src/lib.rs | 2 - library/core/src/alloc/layout.rs | 15 ++-- library/core/src/bool.rs | 6 +- library/core/src/clone.rs | 3 +- library/core/src/cmp.rs | 24 ++---- library/core/src/ffi/c_str.rs | 10 +-- library/core/src/hash/mod.rs | 17 +--- library/core/src/hash/sip.rs | 2 +- library/core/src/lib.rs | 3 - library/core/src/ops/range.rs | 9 +-- library/core/src/ops/try_trait.rs | 4 +- library/core/src/option.rs | 127 +++++++----------------------- library/core/src/ptr/const_ptr.rs | 3 +- library/core/src/ptr/mut_ptr.rs | 3 +- library/core/src/ptr/non_null.rs | 3 +- library/core/src/ptr/unique.rs | 7 +- library/core/src/result.rs | 40 ++-------- library/core/src/slice/memchr.rs | 1 - library/core/src/slice/mod.rs | 17 ++-- library/core/src/str/mod.rs | 18 ++--- library/core/src/time.rs | 24 ++---- 21 files changed, 85 insertions(+), 253 deletions(-) diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index aa240c37e8442..a002421aeef3a 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -106,7 +106,6 @@ #![feature(coerce_unsized)] #![feature(const_align_of_val)] #![feature(const_box)] -#![feature(const_convert)] #![feature(const_cow_is_borrowed)] #![feature(const_eval_select)] #![feature(const_maybe_uninit_as_mut_ptr)] @@ -174,7 +173,6 @@ #![feature(associated_type_bounds)] #![feature(c_unwind)] #![feature(cfg_sanitize)] -#![feature(const_deref)] #![feature(const_mut_refs)] #![feature(const_precise_live_drops)] #![feature(const_ptr_write)] diff --git a/library/core/src/alloc/layout.rs b/library/core/src/alloc/layout.rs index ac3d84718d54e..597303037345e 100644 --- a/library/core/src/alloc/layout.rs +++ b/library/core/src/alloc/layout.rs @@ -231,9 +231,8 @@ impl Layout { /// Returns an error if the combination of `self.size()` and the given /// `align` violates the conditions listed in [`Layout::from_size_align`]. #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")] - #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")] #[inline] - pub const fn align_to(&self, align: usize) -> Result { + pub fn align_to(&self, align: usize) -> Result { Layout::from_size_align(self.size(), cmp::max(self.align(), align)) } @@ -315,9 +314,8 @@ impl Layout { /// /// On arithmetic overflow, returns `LayoutError`. #[unstable(feature = "alloc_layout_extra", issue = "55724")] - #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")] #[inline] - pub const fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutError> { + pub fn repeat(&self, n: usize) -> Result<(Self, usize), LayoutError> { // This cannot overflow. Quoting from the invariant of Layout: // > `size`, when rounded up to the nearest multiple of `align`, // > must not overflow isize (i.e., the rounded value must be @@ -376,9 +374,8 @@ impl Layout { /// # assert_eq!(repr_c(&[u64, u32, u16, u32]), Ok((s, vec![0, 8, 12, 16]))); /// ``` #[stable(feature = "alloc_layout_manipulation", since = "1.44.0")] - #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")] #[inline] - pub const fn extend(&self, next: Self) -> Result<(Self, usize), LayoutError> { + pub fn extend(&self, next: Self) -> Result<(Self, usize), LayoutError> { let new_align = cmp::max(self.align, next.align); let pad = self.padding_needed_for(next.align()); @@ -403,9 +400,8 @@ impl Layout { /// /// On arithmetic overflow, returns `LayoutError`. #[unstable(feature = "alloc_layout_extra", issue = "55724")] - #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")] #[inline] - pub const fn repeat_packed(&self, n: usize) -> Result { + pub fn repeat_packed(&self, n: usize) -> Result { let size = self.size().checked_mul(n).ok_or(LayoutError)?; // The safe constructor is called here to enforce the isize size limit. Layout::from_size_alignment(size, self.align) @@ -418,9 +414,8 @@ impl Layout { /// /// On arithmetic overflow, returns `LayoutError`. #[unstable(feature = "alloc_layout_extra", issue = "55724")] - #[rustc_const_unstable(feature = "const_alloc_layout", issue = "67521")] #[inline] - pub const fn extend_packed(&self, next: Self) -> Result { + pub fn extend_packed(&self, next: Self) -> Result { let new_size = self.size().checked_add(next.size()).ok_or(LayoutError)?; // The safe constructor is called here to enforce the isize size limit. Layout::from_size_alignment(new_size, self.align) diff --git a/library/core/src/bool.rs b/library/core/src/bool.rs index 374759e38161a..03cdff9b13be1 100644 --- a/library/core/src/bool.rs +++ b/library/core/src/bool.rs @@ -30,8 +30,7 @@ impl bool { /// ``` #[stable(feature = "bool_to_option", since = "1.62.0")] #[inline] - pub fn then_some(self, t: T) -> Option - { + pub fn then_some(self, t: T) -> Option { if self { Some(t) } else { None } } @@ -57,8 +56,7 @@ impl bool { /// ``` #[stable(feature = "lazy_bool_to_option", since = "1.50.0")] #[inline] - pub fn then T>(self, f: F) -> Option - { + pub fn then T>(self, f: F) -> Option { if self { Some(f()) } else { None } } } diff --git a/library/core/src/clone.rs b/library/core/src/clone.rs index 5662ff8dfd9ae..a6d6230d3a62b 100644 --- a/library/core/src/clone.rs +++ b/library/core/src/clone.rs @@ -126,8 +126,7 @@ pub trait Clone: Sized { /// allocations. #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn clone_from(&mut self, source: &Self) - { + fn clone_from(&mut self, source: &Self) { *self = source.clone() } } diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index 5582f1be4f438..90825c4ce32e1 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -25,8 +25,6 @@ mod bytewise; pub(crate) use bytewise::BytewiseEq; -use crate::marker::Destruct; - use self::Ordering::*; /// Trait for equality comparisons. @@ -1158,9 +1156,8 @@ pub macro PartialOrd($item:item) { #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] -#[rustc_const_unstable(feature = "const_cmp", issue = "92391")] #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")] -pub const fn min(v1: T, v2: T) -> T { +pub fn min(v1: T, v2: T) -> T { v1.min(v2) } @@ -1179,8 +1176,7 @@ pub const fn min(v1: T, v2: T) -> T { #[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] -pub fn min_by Ordering>(v1: T, v2: T, compare: F) -> T -{ +pub fn min_by Ordering>(v1: T, v2: T, compare: F) -> T { match compare(&v1, &v2) { Ordering::Less | Ordering::Equal => v1, Ordering::Greater => v2, @@ -1202,8 +1198,7 @@ pub fn min_by Ordering>(v1: T, v2: T, compare: F) -> T #[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] -pub fn min_by_key K, K: Ord>(v1: T, v2: T, mut f: F) -> T -{ +pub fn min_by_key K, K: Ord>(v1: T, v2: T, mut f: F) -> T { min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2))) } @@ -1244,8 +1239,7 @@ pub fn max(v1: T, v2: T) -> T { #[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] -pub fn max_by Ordering>(v1: T, v2: T, compare: F) -> T -{ +pub fn max_by Ordering>(v1: T, v2: T, compare: F) -> T { match compare(&v1, &v2) { Ordering::Less | Ordering::Equal => v2, Ordering::Greater => v1, @@ -1267,14 +1261,8 @@ pub fn max_by Ordering>(v1: T, v2: T, compare: F) -> T #[inline] #[must_use] #[stable(feature = "cmp_min_max_by", since = "1.53.0")] -#[rustc_const_unstable(feature = "const_cmp", issue = "92391")] -pub const fn max_by_key K, K: Ord>(v1: T, v2: T, mut f: F) -> T -where - T: Destruct, - F: Destruct, - K: Destruct, -{ - max_by(v1, v2, const |v1, v2| f(v1).cmp(&f(v2))) +pub fn max_by_key K, K: Ord>(v1: T, v2: T, mut f: F) -> T { + max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2))) } // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index 25595328c6503..9b8bc8d1d21ca 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -324,14 +324,14 @@ impl CStr { /// assert_eq!(c_str.to_str().unwrap(), "AAAAAAAA"); /// ``` /// - #[rustc_allow_const_fn_unstable(const_slice_index)] #[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")] #[rustc_const_stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")] pub const fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError> { let nul_pos = memchr::memchr(0, bytes); match nul_pos { Some(nul_pos) => { - let subslice = &bytes[..nul_pos + 1]; + // FIXME(const-hack) replace with range index + let subslice = unsafe { crate::slice::from_raw_parts(bytes.as_ptr(), nul_pos + 1) }; // SAFETY: We know there is a nul byte at nul_pos, so this slice // (ending at the nul byte) is a well-formed C string. Ok(unsafe { CStr::from_bytes_with_nul_unchecked(subslice) }) @@ -561,8 +561,7 @@ impl CStr { #[must_use = "this returns the result of the operation, \ without modifying the original"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_cstr_methods", issue = "101719")] - pub const fn to_bytes(&self) -> &[u8] { + pub fn to_bytes(&self) -> &[u8] { let bytes = self.to_bytes_with_nul(); // SAFETY: to_bytes_with_nul returns slice with length at least 1 unsafe { bytes.get_unchecked(..bytes.len() - 1) } @@ -613,8 +612,7 @@ impl CStr { /// assert_eq!(cstr.to_str(), Ok("foo")); /// ``` #[stable(feature = "cstr_to_str", since = "1.4.0")] - #[rustc_const_unstable(feature = "const_cstr_methods", issue = "101719")] - pub const fn to_str(&self) -> Result<&str, str::Utf8Error> { + pub fn to_str(&self) -> Result<&str, str::Utf8Error> { // N.B., when `CStr` is changed to perform the length check in `.to_bytes()` // instead of in `from_ptr()`, it may be worth considering if this should // be rewritten to do the UTF-8 check inline with the length calculation diff --git a/library/core/src/hash/mod.rs b/library/core/src/hash/mod.rs index 4a28a6e40e830..a73b5b610a4ad 100644 --- a/library/core/src/hash/mod.rs +++ b/library/core/src/hash/mod.rs @@ -86,7 +86,6 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::fmt; -use crate::intrinsics::const_eval_select; use crate::marker; #[stable(feature = "rust1", since = "1.0.0")] @@ -239,21 +238,9 @@ pub trait Hash { where Self: Sized, { - //FIXME(const_trait_impl): revert to only a for loop - fn rt(data: &[T], state: &mut H) { - for piece in data { - piece.hash(state) - } - } - const fn ct(data: &[T], state: &mut H) { - let mut i = 0; - while i < data.len() { - data[i].hash(state); - i += 1; - } + for piece in data { + piece.hash(state) } - // SAFETY: same behavior, CT just uses while instead of for - unsafe { const_eval_select((data, state), ct, rt) }; } } diff --git a/library/core/src/hash/sip.rs b/library/core/src/hash/sip.rs index 1a87671d1d994..6b9f2e84257d1 100644 --- a/library/core/src/hash/sip.rs +++ b/library/core/src/hash/sip.rs @@ -118,7 +118,7 @@ macro_rules! load_int_le { /// Safety: this performs unchecked indexing of `buf` at `start..start+len`, so /// that must be in-bounds. #[inline] -const unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 { +unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 { debug_assert!(len < 8); let mut i = 0; // current byte index (from LSB) in the output u64 let mut out = 0; diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 8cc67c6a5260d..9ccdadcb691cd 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -112,7 +112,6 @@ #![feature(const_caller_location)] #![feature(const_cell_into_inner)] #![feature(const_char_from_u32_unchecked)] -#![feature(const_cmp)] #![feature(const_cstr_methods)] #![feature(const_discriminant)] #![feature(const_eval_select)] @@ -128,7 +127,6 @@ #![feature(const_intrinsic_forget)] #![feature(const_ipv4)] #![feature(const_ipv6)] -#![feature(const_is_char_boundary)] #![feature(const_likely)] #![feature(const_maybe_uninit_as_mut_ptr)] #![feature(const_maybe_uninit_assume_init)] @@ -146,7 +144,6 @@ #![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)] diff --git a/library/core/src/ops/range.rs b/library/core/src/ops/range.rs index 6342e40c41c90..ba5e6ddc752a4 100644 --- a/library/core/src/ops/range.rs +++ b/library/core/src/ops/range.rs @@ -116,8 +116,7 @@ impl> Range { /// assert!(!(f32::NAN..1.0).contains(&0.5)); /// ``` #[stable(feature = "range_contains", since = "1.35.0")] - #[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] - pub const fn contains(&self, item: &U) -> bool + pub fn contains(&self, item: &U) -> bool where Idx: PartialOrd, U: ?Sized + PartialOrd, @@ -143,8 +142,7 @@ impl> Range { /// assert!( (f32::NAN..5.0).is_empty()); /// ``` #[stable(feature = "range_is_empty", since = "1.47.0")] - #[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] - pub const fn is_empty(&self) -> bool { + pub fn is_empty(&self) -> bool { !(self.start < self.end) } } @@ -538,9 +536,8 @@ impl> RangeInclusive { /// assert!(r.is_empty()); /// ``` #[stable(feature = "range_is_empty", since = "1.47.0")] - #[rustc_const_unstable(feature = "const_range_bounds", issue = "108082")] #[inline] - pub const fn is_empty(&self) -> bool { + pub fn is_empty(&self) -> bool { self.exhausted || !(self.start <= self.end) } } diff --git a/library/core/src/ops/try_trait.rs b/library/core/src/ops/try_trait.rs index 58cc1a408dae1..b4f69d0b21309 100644 --- a/library/core/src/ops/try_trait.rs +++ b/library/core/src/ops/try_trait.rs @@ -386,9 +386,7 @@ impl NeverShortCircuit { } #[inline] - pub fn wrap_mut_2( - mut f: impl FnMut(A, B) -> T, - ) -> impl FnMut(A, B) -> Self { + pub fn wrap_mut_2(mut f: impl FnMut(A, B) -> T) -> impl FnMut(A, B) -> Self { move |a, b| NeverShortCircuit(f(a, b)) } } diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 6c6851d2e533d..82e7e69215edb 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -547,7 +547,6 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::iter::{self, FromIterator, FusedIterator, TrustedLen}; -use crate::marker::Destruct; use crate::panicking::{panic, panic_str}; use crate::pin::Pin; use crate::{ @@ -967,11 +966,7 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn unwrap_or(self, default: T) -> T - where - T: Destruct, - { + pub fn unwrap_or(self, default: T) -> T { match self { Some(x) => x, None => default, @@ -989,11 +984,9 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn unwrap_or_else(self, f: F) -> T + pub fn unwrap_or_else(self, f: F) -> T where F: FnOnce() -> T, - F: Destruct, { match self { Some(x) => x, @@ -1022,8 +1015,7 @@ impl Option { /// [`FromStr`]: crate::str::FromStr #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn unwrap_or_default(self) -> T + pub fn unwrap_or_default(self) -> T where T: Default, { @@ -1089,11 +1081,9 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn map(self, f: F) -> Option + pub fn map(self, f: F) -> Option where F: FnOnce(T) -> U, - F: Destruct, { match self { Some(x) => Some(f(x)), @@ -1118,11 +1108,9 @@ impl Option { /// ``` #[inline] #[unstable(feature = "result_option_inspect", issue = "91345")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn inspect(self, f: F) -> Self + pub fn inspect(self, f: F) -> Self where F: FnOnce(&T), - F: Destruct, { if let Some(ref x) = self { f(x); @@ -1151,12 +1139,9 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn map_or(self, default: U, f: F) -> U + pub fn map_or(self, default: U, f: F) -> U where F: FnOnce(T) -> U, - F: Destruct, - U: Destruct, { match self { Some(t) => f(t), @@ -1180,13 +1165,10 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn map_or_else(self, default: D, f: F) -> U + pub fn map_or_else(self, default: D, f: F) -> U where D: FnOnce() -> U, - D: Destruct, F: FnOnce(T) -> U, - F: Destruct, { match self { Some(t) => f(t), @@ -1217,11 +1199,7 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn ok_or(self, err: E) -> Result - where - E: Destruct, - { + pub fn ok_or(self, err: E) -> Result { match self { Some(v) => Ok(v), None => Err(err), @@ -1246,11 +1224,9 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn ok_or_else(self, err: F) -> Result + pub fn ok_or_else(self, err: F) -> Result where F: FnOnce() -> E, - F: Destruct, { match self { Some(v) => Ok(v), @@ -1274,8 +1250,7 @@ impl Option { /// ``` #[inline] #[stable(feature = "option_deref", since = "1.40.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn as_deref(&self) -> Option<&T::Target> + pub fn as_deref(&self) -> Option<&T::Target> where T: Deref, { @@ -1301,8 +1276,7 @@ impl Option { /// ``` #[inline] #[stable(feature = "option_deref", since = "1.40.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn as_deref_mut(&mut self) -> Option<&mut T::Target> + pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> where T: DerefMut, { @@ -1388,12 +1362,7 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn and(self, optb: Option) -> Option - where - T: Destruct, - U: Destruct, - { + pub fn and(self, optb: Option) -> Option { match self { Some(_) => optb, None => None, @@ -1430,11 +1399,9 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn and_then(self, f: F) -> Option + pub fn and_then(self, f: F) -> Option where F: FnOnce(T) -> Option, - F: Destruct, { match self { Some(x) => f(x), @@ -1468,12 +1435,9 @@ impl Option { /// [`Some(t)`]: Some #[inline] #[stable(feature = "option_filter", since = "1.27.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn filter

(self, predicate: P) -> Self + pub fn filter

(self, predicate: P) -> Self where - T: Destruct, P: FnOnce(&T) -> bool, - P: Destruct, { if let Some(x) = self { if predicate(&x) { @@ -1512,11 +1476,7 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn or(self, optb: Option) -> Option - where - T: Destruct, - { + pub fn or(self, optb: Option) -> Option { match self { Some(x) => Some(x), None => optb, @@ -1538,11 +1498,9 @@ impl Option { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn or_else(self, f: F) -> Option + pub fn or_else(self, f: F) -> Option where F: FnOnce() -> Option, - F: Destruct, { match self { Some(x) => Some(x), @@ -1573,11 +1531,7 @@ impl Option { /// ``` #[inline] #[stable(feature = "option_xor", since = "1.37.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn xor(self, optb: Option) -> Option - where - T: Destruct, - { + pub fn xor(self, optb: Option) -> Option { match (self, optb) { (Some(a), None) => Some(a), (None, Some(b)) => Some(b), @@ -1611,11 +1565,7 @@ impl Option { #[must_use = "if you intended to set a value, consider assignment instead"] #[inline] #[stable(feature = "option_insert", since = "1.53.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn insert(&mut self, value: T) -> &mut T - where - T: Destruct, - { + pub fn insert(&mut self, value: T) -> &mut T { *self = Some(value); // SAFETY: the code above just filled the option @@ -1644,11 +1594,7 @@ impl Option { /// ``` #[inline] #[stable(feature = "option_entry", since = "1.20.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn get_or_insert(&mut self, value: T) -> &mut T - where - T: Destruct, - { + pub fn get_or_insert(&mut self, value: T) -> &mut T { if let None = *self { *self = Some(value); } @@ -1679,12 +1625,11 @@ impl Option { /// ``` #[inline] #[unstable(feature = "option_get_or_insert_default", issue = "82901")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn get_or_insert_default(&mut self) -> &mut T + pub fn get_or_insert_default(&mut self) -> &mut T where T: Default, { - const fn default() -> T { + fn default() -> T { T::default() } @@ -1710,11 +1655,9 @@ impl Option { /// ``` #[inline] #[stable(feature = "option_entry", since = "1.20.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn get_or_insert_with(&mut self, f: F) -> &mut T + pub fn get_or_insert_with(&mut self, f: F) -> &mut T where F: FnOnce() -> T, - F: Destruct, { if let None = *self { // the compiler isn't smart enough to know that we are not dropping a `T` @@ -1794,12 +1737,7 @@ impl Option { /// assert_eq!(x.zip(z), None); /// ``` #[stable(feature = "option_zip_option", since = "1.46.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn zip(self, other: Option) -> Option<(T, U)> - where - T: Destruct, - U: Destruct, - { + pub fn zip(self, other: Option) -> Option<(T, U)> { match (self, other) { (Some(a), Some(b)) => Some((a, b)), _ => None, @@ -1835,13 +1773,9 @@ impl Option { /// assert_eq!(x.zip_with(None, Point::new), None); /// ``` #[unstable(feature = "option_zip", issue = "70086")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn zip_with(self, other: Option, f: F) -> Option + pub fn zip_with(self, other: Option, f: F) -> Option where F: FnOnce(T, U) -> R, - F: Destruct, - T: Destruct, - U: Destruct, { match (self, other) { (Some(a), Some(b)) => Some(f(a, b)), @@ -1867,12 +1801,7 @@ impl Option<(T, U)> { /// ``` #[inline] #[stable(feature = "unzip_option", since = "1.66.0")] - #[rustc_const_unstable(feature = "const_option", issue = "67441")] - pub const fn unzip(self) -> (Option, Option) - where - T: Destruct, - U: Destruct, - { + pub fn unzip(self) -> (Option, Option) { match self { Some((a, b)) => (Some(a), Some(b)), None => (None, None), @@ -1922,8 +1851,7 @@ impl Option<&T> { /// ``` #[must_use = "`self` will be dropped if the result is not used"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] - pub const fn cloned(self) -> Option + pub fn cloned(self) -> Option where T: Clone, { @@ -1974,8 +1902,7 @@ impl Option<&mut T> { /// ``` #[must_use = "`self` will be dropped if the result is not used"] #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")] - #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] - pub const fn cloned(self) -> Option + pub fn cloned(self) -> Option where T: Clone, { diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index fe6efba600348..1a442c8bb84e0 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -1650,9 +1650,8 @@ impl *const [T] { /// } /// ``` #[unstable(feature = "slice_ptr_get", issue = "74265")] - #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] - pub const unsafe fn get_unchecked(self, index: I) -> *const I::Output + pub unsafe fn get_unchecked(self, index: I) -> *const I::Output where I: SliceIndex<[T]>, { diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index 5af28dea472d8..9912648554bd9 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -2036,9 +2036,8 @@ impl *mut [T] { /// } /// ``` #[unstable(feature = "slice_ptr_get", issue = "74265")] - #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline(always)] - pub const unsafe fn get_unchecked_mut(self, index: I) -> *mut I::Output + pub unsafe fn get_unchecked_mut(self, index: I) -> *mut I::Output where I: SliceIndex<[T]>, { diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index fdb428ff4e680..506d891d989b1 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -676,9 +676,8 @@ impl NonNull<[T]> { /// } /// ``` #[unstable(feature = "slice_ptr_get", issue = "74265")] - #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] - pub const unsafe fn get_unchecked_mut(self, index: I) -> NonNull + pub unsafe fn get_unchecked_mut(self, index: I) -> NonNull where I: SliceIndex<[T]>, { diff --git a/library/core/src/ptr/unique.rs b/library/core/src/ptr/unique.rs index 3547897698594..a853f15edb7e0 100644 --- a/library/core/src/ptr/unique.rs +++ b/library/core/src/ptr/unique.rs @@ -70,7 +70,8 @@ impl Unique { #[must_use] #[inline] pub const fn dangling() -> Self { - Self::from(NonNull::dangling()) + // FIXME(const-hack) replace with `From` + Unique { pointer: NonNull::dangling(), _marker: PhantomData } } } @@ -134,7 +135,9 @@ impl Unique { #[must_use = "`self` will be dropped if the result is not used"] #[inline] pub const fn cast(self) -> Unique { - Unique::from(self.pointer.cast()) + // FIXME(const-hack): replace with `From` + // SAFETY: is `NonNull` + unsafe { Unique::new_unchecked(self.pointer.cast().as_ptr()) } } } diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 967fee2a6addf..28cb02989ecc0 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -489,7 +489,6 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::iter::{self, FromIterator, FusedIterator, TrustedLen}; -use crate::marker::Destruct; use crate::ops::{self, ControlFlow, Deref, DerefMut}; use crate::{convert, fmt, hint}; @@ -629,11 +628,7 @@ impl Result { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] - pub const fn ok(self) -> Option - where - E: Destruct, - { + pub fn ok(self) -> Option { match self { Ok(x) => Some(x), Err(_) => None, @@ -656,11 +651,7 @@ impl Result { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] - pub const fn err(self) -> Option - where - T: Destruct, - { + pub fn err(self) -> Option { match self { Ok(_) => None, Err(x) => Some(x), @@ -1283,14 +1274,8 @@ impl Result { /// assert_eq!(x.and(y), Ok("different result type")); /// ``` #[inline] - #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] #[stable(feature = "rust1", since = "1.0.0")] - pub const fn and(self, res: Result) -> Result - where - T: Destruct, - U: Destruct, - E: Destruct, - { + pub fn and(self, res: Result) -> Result { match self { Ok(_) => res, Err(e) => Err(e), @@ -1364,14 +1349,8 @@ impl Result { /// assert_eq!(x.or(y), Ok(2)); /// ``` #[inline] - #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] #[stable(feature = "rust1", since = "1.0.0")] - pub const fn or(self, res: Result) -> Result - where - T: Destruct, - E: Destruct, - F: Destruct, - { + pub fn or(self, res: Result) -> Result { match self { Ok(v) => Ok(v), Err(_) => res, @@ -1422,13 +1401,8 @@ impl Result { /// assert_eq!(x.unwrap_or(default), default); /// ``` #[inline] - #[rustc_const_unstable(feature = "const_result_drop", issue = "92384")] #[stable(feature = "rust1", since = "1.0.0")] - pub const fn unwrap_or(self, default: T) -> T - where - T: Destruct, - E: Destruct, - { + pub fn unwrap_or(self, default: T) -> T { match self { Ok(t) => t, Err(_) => default, @@ -1979,9 +1953,7 @@ impl ops::Try for Result { } #[unstable(feature = "try_trait_v2", issue = "84277")] -impl> ops::FromResidual> - for Result -{ +impl> ops::FromResidual> for Result { #[inline] #[track_caller] fn from_residual(residual: Result) -> Self { diff --git a/library/core/src/slice/memchr.rs b/library/core/src/slice/memchr.rs index 8ceca7f9185c6..3ae15e47bce27 100644 --- a/library/core/src/slice/memchr.rs +++ b/library/core/src/slice/memchr.rs @@ -1,7 +1,6 @@ // Original implementation taken from rust-memchr. // Copyright 2015 Andrew Gallant, bluss and Nicolas Koch -use crate::cmp; use crate::mem; const LO_USIZE: usize = usize::repeat_u8(0x01); diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 992a088b91111..d12809357a890 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -333,10 +333,9 @@ impl [T] { /// assert_eq!(None, v.get(0..4)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] #[must_use] - pub const fn get(&self, index: I) -> Option<&I::Output> + pub fn get(&self, index: I) -> Option<&I::Output> where I: SliceIndex, { @@ -359,10 +358,9 @@ impl [T] { /// assert_eq!(x, &[0, 42, 2]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] #[must_use] - pub const fn get_mut(&mut self, index: I) -> Option<&mut I::Output> + pub fn get_mut(&mut self, index: I) -> Option<&mut I::Output> where I: SliceIndex, { @@ -392,10 +390,9 @@ impl [T] { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] #[must_use] - pub const unsafe fn get_unchecked(&self, index: I) -> &I::Output + pub unsafe fn get_unchecked(&self, index: I) -> &I::Output where I: SliceIndex, { @@ -430,10 +427,9 @@ impl [T] { /// assert_eq!(x, &[1, 13, 4]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] #[must_use] - pub const unsafe fn get_unchecked_mut(&mut self, index: I) -> &mut I::Output + pub unsafe fn get_unchecked_mut(&mut self, index: I) -> &mut I::Output where I: SliceIndex, { @@ -678,9 +674,8 @@ impl [T] { /// assert!(v == [3, 2, 1]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_reverse", issue = "100784")] #[inline] - pub const fn reverse(&mut self) { + pub fn reverse(&mut self) { let half_len = self.len() / 2; let Range { start, end } = self.as_mut_ptr_range(); @@ -703,7 +698,7 @@ impl [T] { revswap(front_half, back_half, half_len); #[inline] - const fn revswap(a: &mut [T], b: &mut [T], n: usize) { + fn revswap(a: &mut [T], b: &mut [T], n: usize) { debug_assert!(a.len() == n); debug_assert!(b.len() == n); diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index 1ab27d567ca86..a13107fd0de09 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -206,9 +206,8 @@ impl str { /// ``` #[must_use] #[stable(feature = "is_char_boundary", since = "1.9.0")] - #[rustc_const_unstable(feature = "const_is_char_boundary", issue = "none")] #[inline] - pub const fn is_char_boundary(&self, index: usize) -> bool { + pub fn is_char_boundary(&self, index: usize) -> bool { // 0 is always ok. // Test for 0 explicitly so that it can optimize out the check // easily and skip reading string data for that case. @@ -436,9 +435,8 @@ impl str { /// assert!(v.get(..42).is_none()); /// ``` #[stable(feature = "str_checked_slicing", since = "1.20.0")] - #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] - pub const fn get>(&self, i: I) -> Option<&I::Output> { + pub fn get>(&self, i: I) -> Option<&I::Output> { i.get(self) } @@ -469,9 +467,8 @@ impl str { /// assert_eq!("HEllo", v); /// ``` #[stable(feature = "str_checked_slicing", since = "1.20.0")] - #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] - pub const fn get_mut>(&mut self, i: I) -> Option<&mut I::Output> { + pub fn get_mut>(&mut self, i: I) -> Option<&mut I::Output> { i.get_mut(self) } @@ -502,9 +499,8 @@ impl str { /// } /// ``` #[stable(feature = "str_checked_slicing", since = "1.20.0")] - #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] - pub const unsafe fn get_unchecked>(&self, i: I) -> &I::Output { + pub unsafe fn get_unchecked>(&self, i: I) -> &I::Output { // SAFETY: the caller must uphold the safety contract for `get_unchecked`; // the slice is dereferenceable because `self` is a safe reference. // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is. @@ -538,12 +534,8 @@ impl str { /// } /// ``` #[stable(feature = "str_checked_slicing", since = "1.20.0")] - #[rustc_const_unstable(feature = "const_slice_index", issue = "none")] #[inline] - pub const unsafe fn get_unchecked_mut>( - &mut self, - i: I, - ) -> &mut I::Output { + pub unsafe fn get_unchecked_mut>(&mut self, i: I) -> &mut I::Output { // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`; // the slice is dereferenceable because `self` is a safe reference. // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is. diff --git a/library/core/src/time.rs b/library/core/src/time.rs index ba1cb6efa04b6..b74fe01366594 100644 --- a/library/core/src/time.rs +++ b/library/core/src/time.rs @@ -735,8 +735,7 @@ impl Duration { #[stable(feature = "duration_float", since = "1.38.0")] #[must_use] #[inline] - #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")] - pub const fn from_secs_f64(secs: f64) -> Duration { + pub fn from_secs_f64(secs: f64) -> Duration { match Duration::try_from_secs_f64(secs) { Ok(v) => v, Err(e) => panic!("{}", e.description()), @@ -773,8 +772,7 @@ impl Duration { #[stable(feature = "duration_float", since = "1.38.0")] #[must_use] #[inline] - #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")] - pub const fn from_secs_f32(secs: f32) -> Duration { + pub fn from_secs_f32(secs: f32) -> Duration { match Duration::try_from_secs_f32(secs) { Ok(v) => v, Err(e) => panic!("{}", e.description()), @@ -798,8 +796,7 @@ impl Duration { #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] - #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")] - pub const fn mul_f64(self, rhs: f64) -> Duration { + pub fn mul_f64(self, rhs: f64) -> Duration { Duration::from_secs_f64(rhs * self.as_secs_f64()) } @@ -820,8 +817,7 @@ impl Duration { #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] - #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")] - pub const fn mul_f32(self, rhs: f32) -> Duration { + pub fn mul_f32(self, rhs: f32) -> Duration { Duration::from_secs_f32(rhs * self.as_secs_f32()) } @@ -842,8 +838,7 @@ impl Duration { #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] - #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")] - pub const fn div_f64(self, rhs: f64) -> Duration { + pub fn div_f64(self, rhs: f64) -> Duration { Duration::from_secs_f64(self.as_secs_f64() / rhs) } @@ -866,8 +861,7 @@ impl Duration { #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] - #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")] - pub const fn div_f32(self, rhs: f32) -> Duration { + pub fn div_f32(self, rhs: f32) -> Duration { Duration::from_secs_f32(self.as_secs_f32() / rhs) } @@ -1402,9 +1396,8 @@ impl Duration { /// assert_eq!(res, Ok(Duration::new(1, 2_929_688))); /// ``` #[stable(feature = "duration_checked_float", since = "1.66.0")] - #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")] #[inline] - pub const fn try_from_secs_f32(secs: f32) -> Result { + pub fn try_from_secs_f32(secs: f32) -> Result { try_from_secs!( secs = secs, mantissa_bits = 23, @@ -1479,9 +1472,8 @@ impl Duration { /// assert_eq!(res, Ok(Duration::new(1, 2_929_688))); /// ``` #[stable(feature = "duration_checked_float", since = "1.66.0")] - #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")] #[inline] - pub const fn try_from_secs_f64(secs: f64) -> Result { + pub fn try_from_secs_f64(secs: f64) -> Result { try_from_secs!( secs = secs, mantissa_bits = 52, From 4ecbd3be5204e896d1cbb0d28b157699bf89caa3 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 07:21:33 +0000 Subject: [PATCH 050/228] fix alloc --- library/alloc/src/boxed.rs | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 8278d400c8f27..ad86c19309831 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -576,8 +576,7 @@ impl Box { /// /// This conversion does not allocate on the heap and happens in place. #[unstable(feature = "box_into_boxed_slice", issue = "71582")] - #[rustc_const_unstable(feature = "const_box", issue = "92521")] - pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A> { + pub fn into_boxed_slice(boxed: Self) -> Box<[T], A> { let (raw, alloc) = Box::into_raw_with_allocator(boxed); unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) } } @@ -809,9 +808,8 @@ impl Box, A> { /// assert_eq!(*five, 5) /// ``` #[unstable(feature = "new_uninit", issue = "63291")] - #[rustc_const_unstable(feature = "const_box", issue = "92521")] #[inline] - pub const unsafe fn assume_init(self) -> Box { + pub unsafe fn assume_init(self) -> Box { let (raw, alloc) = Box::into_raw_with_allocator(self); unsafe { Box::from_raw_in(raw as *mut T, alloc) } } @@ -844,9 +842,8 @@ impl Box, A> { /// } /// ``` #[unstable(feature = "new_uninit", issue = "63291")] - #[rustc_const_unstable(feature = "const_box", issue = "92521")] #[inline] - pub const fn write(mut boxed: Self, value: T) -> Box { + pub fn write(mut boxed: Self, value: T) -> Box { unsafe { (*boxed).write(value); boxed.assume_init() @@ -1090,9 +1087,8 @@ impl Box { /// /// [memory layout]: self#memory-layout #[unstable(feature = "allocator_api", issue = "32838")] - #[rustc_const_unstable(feature = "const_box", issue = "92521")] #[inline] - pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) { + pub fn into_raw_with_allocator(b: Self) -> (*mut T, A) { let (leaked, alloc) = Box::into_unique(b); (leaked.as_ptr(), alloc) } @@ -1102,10 +1098,9 @@ impl Box { issue = "none", reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead" )] - #[rustc_const_unstable(feature = "const_box", issue = "92521")] #[inline] #[doc(hidden)] - pub const fn into_unique(b: Self) -> (Unique, A) { + pub fn into_unique(b: Self) -> (Unique, A) { // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a // raw pointer for the type system. Turning it directly into a raw pointer would not be // recognized as "releasing" the unique pointer to permit aliased raw accesses, @@ -1163,9 +1158,8 @@ impl Box { /// assert_eq!(*static_ref, [4, 2, 3]); /// ``` #[stable(feature = "box_leak", since = "1.26.0")] - #[rustc_const_unstable(feature = "const_box", issue = "92521")] #[inline] - pub const fn leak<'a>(b: Self) -> &'a mut T + pub fn leak<'a>(b: Self) -> &'a mut T where A: 'a, { From ede7bc032a7a447ffce7a4c3fc1b1fc72842386b Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 07:25:13 +0000 Subject: [PATCH 051/228] make rustc compilable --- compiler/rustc_ast/src/lib.rs | 1 - compiler/rustc_ast/src/ptr.rs | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs index 23c32fa96ca44..b07ed1d1c741e 100644 --- a/compiler/rustc_ast/src/lib.rs +++ b/compiler/rustc_ast/src/lib.rs @@ -10,7 +10,6 @@ )] #![feature(associated_type_bounds)] #![feature(box_patterns)] -#![feature(const_default_impls)] #![feature(const_trait_impl)] #![feature(if_let_guard)] #![feature(let_chains)] diff --git a/compiler/rustc_ast/src/ptr.rs b/compiler/rustc_ast/src/ptr.rs index 4b2850336a03d..0140fb752bf92 100644 --- a/compiler/rustc_ast/src/ptr.rs +++ b/compiler/rustc_ast/src/ptr.rs @@ -126,7 +126,8 @@ impl> Encodable for P { } impl P<[T]> { - pub const fn new() -> P<[T]> { + // FIXME(const-hack) make this const again + pub fn new() -> P<[T]> { P { ptr: Box::default() } } From 34097b2f33aa16bbd4f71f6843b26c9ddfa1a471 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 07:27:28 +0000 Subject: [PATCH 052/228] fix tidy --- library/core/src/ffi/c_str.rs | 1 + library/core/src/slice/memchr.rs | 2 ++ 2 files changed, 3 insertions(+) diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index 9b8bc8d1d21ca..bd2b2c36c4315 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -331,6 +331,7 @@ impl CStr { match nul_pos { Some(nul_pos) => { // FIXME(const-hack) replace with range index + // SAFETY: nul_pos + 1 <= bytes.len() let subslice = unsafe { crate::slice::from_raw_parts(bytes.as_ptr(), nul_pos + 1) }; // SAFETY: We know there is a nul byte at nul_pos, so this slice // (ending at the nul byte) is a well-formed C string. diff --git a/library/core/src/slice/memchr.rs b/library/core/src/slice/memchr.rs index 3ae15e47bce27..3a8b59d727b4a 100644 --- a/library/core/src/slice/memchr.rs +++ b/library/core/src/slice/memchr.rs @@ -85,6 +85,7 @@ const fn memchr_aligned(x: u8, text: &[u8]) -> Option { // FIXME(const-hack, fee1-dead): replace with min offset = if offset < len { offset } else { len }; // FIXME(const-hack, fee1-dead): replace with range slicing + // SAFETY: offset is within bounds let slice = unsafe { super::from_raw_parts(text.as_ptr(), offset) }; if let Some(index) = memchr_naive(x, slice) { return Some(index); @@ -113,6 +114,7 @@ const fn memchr_aligned(x: u8, text: &[u8]) -> Option { // Find the byte after the point the body loop stopped. // FIXME(const-hack): Use `?` instead. // FIXME(const-hack, fee1-dead): use range slicing + // SAFETY: offset is within bounds let slice = unsafe { super::from_raw_parts(text.as_ptr().add(offset), text.len() - offset) }; if let Some(i) = memchr_naive(x, slice) { Some(offset + i) } else { None } } From eac922e721b8d46ed699d2e57cecf3dbf8226802 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 09:16:22 +0000 Subject: [PATCH 053/228] readd `const_trait` to `Drop`, `Destruct`, and `Fn*` --- library/core/src/lib.rs | 1 + library/core/src/marker.rs | 1 + library/core/src/ops/drop.rs | 1 + library/core/src/ops/function.rs | 3 +++ 4 files changed, 6 insertions(+) diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 9ccdadcb691cd..24a9d81d03784 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -198,6 +198,7 @@ #![feature(const_mut_refs)] #![feature(const_precise_live_drops)] #![feature(const_refs_to_cell)] +#![feature(const_trait_impl)] #![feature(decl_macro)] #![feature(deprecated_suggestion)] #![feature(doc_cfg)] diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index d149ea0320993..e85c0c0a68890 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -858,6 +858,7 @@ impl Unpin for *mut T {} #[lang = "destruct"] #[rustc_on_unimplemented(message = "can't drop `{Self}`", append_const_msg)] #[rustc_deny_explicit_impl] +#[const_trait] pub trait Destruct {} /// A marker for tuple types. diff --git a/library/core/src/ops/drop.rs b/library/core/src/ops/drop.rs index de9ddb852df31..a2c3d978cc4fa 100644 --- a/library/core/src/ops/drop.rs +++ b/library/core/src/ops/drop.rs @@ -134,6 +134,7 @@ /// these types cannot have destructors. #[lang = "drop"] #[stable(feature = "rust1", since = "1.0.0")] +#[const_trait] pub trait Drop { /// Executes the destructor for this type. /// diff --git a/library/core/src/ops/function.rs b/library/core/src/ops/function.rs index 6c16776b2c209..67c8245f0bfe0 100644 --- a/library/core/src/ops/function.rs +++ b/library/core/src/ops/function.rs @@ -72,6 +72,7 @@ use crate::marker::Tuple; )] #[fundamental] // so that regex can rely that `&str: !FnMut` #[must_use = "closures are lazy and do nothing unless called"] +#[const_trait] pub trait Fn: FnMut { /// Performs the call operation. #[unstable(feature = "fn_traits", issue = "29625")] @@ -158,6 +159,7 @@ pub trait Fn: FnMut { )] #[fundamental] // so that regex can rely that `&str: !FnMut` #[must_use = "closures are lazy and do nothing unless called"] +#[const_trait] pub trait FnMut: FnOnce { /// Performs the call operation. #[unstable(feature = "fn_traits", issue = "29625")] @@ -236,6 +238,7 @@ pub trait FnMut: FnOnce { )] #[fundamental] // so that regex can rely that `&str: !FnMut` #[must_use = "closures are lazy and do nothing unless called"] +#[const_trait] pub trait FnOnce { /// The returned type after the call operator is used. #[lang = "fn_once_output"] From 147e850691b60b273643f1e4d3b53cad620b80b7 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 09:25:48 +0000 Subject: [PATCH 054/228] revive raw pointer comp error --- compiler/rustc_const_eval/src/transform/check_consts/ops.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 c0f5b3725b36d..f610d9e3a0345 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs @@ -610,10 +610,11 @@ pub struct RawPtrComparison; impl<'tcx> NonConstOp<'tcx> for RawPtrComparison { fn build_error( &self, - _: &ConstCx<'_, 'tcx>, + ccx: &ConstCx<'_, 'tcx>, span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - span_bug!(span, "raw ptr comparison should already be caught in the trait system"); + // FIXME(const_trait_impl): revert to span_bug? + ccx.tcx.sess.create_err(errors::RawPtrComparisonErr { span }) } } From c98895d9f20eec10993bf2c3f07a2f2945228e49 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sun, 16 Apr 2023 01:06:55 -0700 Subject: [PATCH 055/228] Various minor Idx-related tweaks Nothing particularly exciting here, but a couple of things I noticed as I was looking for more index conversions to simplify. --- compiler/rustc_abi/src/layout.rs | 7 +++---- compiler/rustc_abi/src/lib.rs | 2 +- compiler/rustc_ast/src/node_id.rs | 8 ++++---- .../rustc_borrowck/src/diagnostics/var_name.rs | 4 ++-- compiler/rustc_borrowck/src/facts.rs | 5 ++--- compiler/rustc_borrowck/src/location.rs | 8 ++++---- compiler/rustc_borrowck/src/nll.rs | 8 ++++---- .../src/type_check/input_output.rs | 3 +-- .../rustc_borrowck/src/universal_regions.rs | 4 ++-- compiler/rustc_codegen_ssa/src/mir/block.rs | 3 +-- .../src/interpret/discriminant.rs | 17 +++++++++-------- compiler/rustc_hir_typeck/src/demand.rs | 3 +-- compiler/rustc_hir_typeck/src/intrinsicck.rs | 4 ++-- .../src/infer/error_reporting/suggest.rs | 3 +-- compiler/rustc_middle/src/ty/mod.rs | 10 ++++++++++ .../rustc_query_system/src/dep_graph/query.rs | 5 +---- .../src/solve/eval_ctxt/canonical.rs | 13 +++++++------ 17 files changed, 55 insertions(+), 52 deletions(-) diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index c863acde7b03d..2b01aca2ee482 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -461,8 +461,8 @@ pub trait LayoutCalculator { let all_indices = variants.indices(); let needs_disc = |index: VariantIdx| index != largest_variant_index && !absent(&variants[index]); - let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap().index() - ..=all_indices.rev().find(|v| needs_disc(*v)).unwrap().index(); + let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap() + ..=all_indices.rev().find(|v| needs_disc(*v)).unwrap(); let count = niche_variants.size_hint().1.unwrap() as u128; @@ -560,8 +560,7 @@ pub trait LayoutCalculator { tag: niche_scalar, tag_encoding: TagEncoding::Niche { untagged_variant: largest_variant_index, - niche_variants: (VariantIdx::new(*niche_variants.start()) - ..=VariantIdx::new(*niche_variants.end())), + niche_variants, niche_start, }, tag_field: 0, diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index b0c0ee942ea8f..9f96575e2f1d2 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -11,7 +11,7 @@ use bitflags::bitflags; use rustc_data_structures::intern::Interned; #[cfg(feature = "nightly")] use rustc_data_structures::stable_hasher::StableOrd; -use rustc_index::vec::{Idx, IndexSlice, IndexVec}; +use rustc_index::vec::{IndexSlice, IndexVec}; #[cfg(feature = "nightly")] use rustc_macros::HashStable_Generic; #[cfg(feature = "nightly")] diff --git a/compiler/rustc_ast/src/node_id.rs b/compiler/rustc_ast/src/node_id.rs index daa82996b3d11..d16741757d1f1 100644 --- a/compiler/rustc_ast/src/node_id.rs +++ b/compiler/rustc_ast/src/node_id.rs @@ -9,14 +9,14 @@ rustc_index::newtype_index! { /// /// [`DefId`]: rustc_span::def_id::DefId #[debug_format = "NodeId({})"] - pub struct NodeId {} + pub struct NodeId { + /// The [`NodeId`] used to represent the root of the crate. + const CRATE_NODE_ID = 0; + } } rustc_data_structures::define_id_collections!(NodeMap, NodeSet, NodeMapEntry, NodeId); -/// The [`NodeId`] used to represent the root of the crate. -pub const CRATE_NODE_ID: NodeId = NodeId::from_u32(0); - /// When parsing and at the beginning of doing expansions, we initially give all AST nodes /// this dummy AST [`NodeId`]. Then, during a later phase of expansion, we renumber them /// to have small, positive IDs. diff --git a/compiler/rustc_borrowck/src/diagnostics/var_name.rs b/compiler/rustc_borrowck/src/diagnostics/var_name.rs index 376415e3d3208..aa7cf3578ea82 100644 --- a/compiler/rustc_borrowck/src/diagnostics/var_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/var_name.rs @@ -3,7 +3,7 @@ use crate::region_infer::RegionInferenceContext; use crate::Upvar; -use rustc_index::vec::{Idx, IndexSlice}; +use rustc_index::vec::IndexSlice; use rustc_middle::mir::{Body, Local}; use rustc_middle::ty::{RegionVid, TyCtxt}; use rustc_span::source_map::Span; @@ -117,7 +117,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { argument_index: usize, ) -> (Option, Span) { let implicit_inputs = self.universal_regions().defining_ty.implicit_inputs(); - let argument_local = Local::new(implicit_inputs + argument_index + 1); + let argument_local = Local::from_usize(implicit_inputs + argument_index + 1); debug!("get_argument_name_and_span_for_region: argument_local={argument_local:?}"); let argument_name = local_names[argument_local]; diff --git a/compiler/rustc_borrowck/src/facts.rs b/compiler/rustc_borrowck/src/facts.rs index 02ffb51fbb7e3..87fad9a355d3d 100644 --- a/compiler/rustc_borrowck/src/facts.rs +++ b/compiler/rustc_borrowck/src/facts.rs @@ -4,7 +4,6 @@ use crate::location::{LocationIndex, LocationTable}; use crate::BorrowIndex; use polonius_engine::AllFacts as PoloniusFacts; use polonius_engine::Atom; -use rustc_index::vec::Idx; use rustc_middle::mir::Local; use rustc_middle::ty::{RegionVid, TyCtxt}; use rustc_mir_dataflow::move_paths::MovePathIndex; @@ -93,13 +92,13 @@ impl AllFactsExt for AllFacts { impl Atom for BorrowIndex { fn index(self) -> usize { - Idx::index(self) + self.as_usize() } } impl Atom for LocationIndex { fn index(self) -> usize { - Idx::index(self) + self.as_usize() } } diff --git a/compiler/rustc_borrowck/src/location.rs b/compiler/rustc_borrowck/src/location.rs index 288b7d85be2d4..08fa912f3682a 100644 --- a/compiler/rustc_borrowck/src/location.rs +++ b/compiler/rustc_borrowck/src/location.rs @@ -1,6 +1,6 @@ #![deny(rustc::untranslatable_diagnostic)] #![deny(rustc::diagnostic_outside_of_impl)] -use rustc_index::vec::{Idx, IndexVec}; +use rustc_index::vec::IndexVec; use rustc_middle::mir::{BasicBlock, Body, Location}; /// Maps between a MIR Location, which identifies a particular @@ -50,19 +50,19 @@ impl LocationTable { } pub fn all_points(&self) -> impl Iterator { - (0..self.num_points).map(LocationIndex::new) + (0..self.num_points).map(LocationIndex::from_usize) } pub fn start_index(&self, location: Location) -> LocationIndex { let Location { block, statement_index } = location; let start_index = self.statements_before_block[block]; - LocationIndex::new(start_index + statement_index * 2) + LocationIndex::from_usize(start_index + statement_index * 2) } pub fn mid_index(&self, location: Location) -> LocationIndex { let Location { block, statement_index } = location; let start_index = self.statements_before_block[block]; - LocationIndex::new(start_index + statement_index * 2 + 1) + LocationIndex::from_usize(start_index + statement_index * 2 + 1) } pub fn to_location(&self, index: LocationIndex) -> RichLocation { diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs index 59a3ab3189d75..73b8765e57d1a 100644 --- a/compiler/rustc_borrowck/src/nll.rs +++ b/compiler/rustc_borrowck/src/nll.rs @@ -7,8 +7,8 @@ use rustc_hir::def_id::LocalDefId; use rustc_index::vec::IndexSlice; use rustc_middle::mir::{create_dump_file, dump_enabled, dump_mir, PassWhere}; use rustc_middle::mir::{ - BasicBlock, Body, ClosureOutlivesSubject, ClosureRegionRequirements, LocalKind, Location, - Promoted, + Body, ClosureOutlivesSubject, ClosureRegionRequirements, LocalKind, Location, Promoted, + START_BLOCK, }; use rustc_middle::ty::{self, OpaqueHiddenType, TyCtxt}; use rustc_span::symbol::sym; @@ -94,8 +94,8 @@ fn populate_polonius_move_facts( } } - let fn_entry_start = location_table - .start_index(Location { block: BasicBlock::from_u32(0u32), statement_index: 0 }); + let fn_entry_start = + location_table.start_index(Location { block: START_BLOCK, statement_index: 0 }); // initialized_at for init in move_data.inits.iter() { diff --git a/compiler/rustc_borrowck/src/type_check/input_output.rs b/compiler/rustc_borrowck/src/type_check/input_output.rs index 17e702eb8c528..9250b8d3eaf2a 100644 --- a/compiler/rustc_borrowck/src/type_check/input_output.rs +++ b/compiler/rustc_borrowck/src/type_check/input_output.rs @@ -7,7 +7,6 @@ //! `RETURN_PLACE` the MIR arguments) are always fully normalized (and //! contain revealed `impl Trait` values). -use rustc_index::vec::Idx; use rustc_infer::infer::LateBoundRegionConversionTime; use rustc_middle::mir::*; use rustc_middle::ty::{self, Ty}; @@ -83,7 +82,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } // In MIR, argument N is stored in local N+1. - let local = Local::new(argument_index + 1); + let local = Local::from_usize(argument_index + 1); let mir_input_ty = body.local_decls[local].ty; diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index 70fddb1057c09..74241f722a67e 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -19,7 +19,7 @@ use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::LangItem; use rustc_hir::BodyOwnerKind; -use rustc_index::vec::{Idx, IndexVec}; +use rustc_index::vec::IndexVec; use rustc_infer::infer::NllRegionVariableOrigin; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{self, InlineConstSubsts, InlineConstSubstsParts, RegionVid, Ty, TyCtxt}; @@ -289,7 +289,7 @@ impl<'tcx> UniversalRegions<'tcx> { /// Returns an iterator over all the RegionVids corresponding to /// universally quantified free regions. pub fn universal_regions(&self) -> impl Iterator { - (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::new) + (FIRST_GLOBAL_INDEX..self.num_universals).map(RegionVid::from_usize) } /// Returns `true` if `r` is classified as an local region. diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index dd86977817fbc..a0a8246be1524 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -12,7 +12,6 @@ use crate::MemFlags; use rustc_ast as ast; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_hir::lang_items::LangItem; -use rustc_index::vec::Idx; use rustc_middle::mir::{self, AssertKind, SwitchTargets}; use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement}; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; @@ -369,7 +368,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { if self.fn_abi.c_variadic { // The `VaList` "spoofed" argument is just after all the real arguments. let va_list_arg_idx = self.fn_abi.args.len(); - match self.locals[mir::Local::new(1 + va_list_arg_idx)] { + match self.locals[mir::Local::from_usize(1 + va_list_arg_idx)] { LocalRef::Place(va_list) => { bx.va_end(va_list.llval); } diff --git a/compiler/rustc_const_eval/src/interpret/discriminant.rs b/compiler/rustc_const_eval/src/interpret/discriminant.rs index 557e721249d7f..015a9beab832d 100644 --- a/compiler/rustc_const_eval/src/interpret/discriminant.rs +++ b/compiler/rustc_const_eval/src/interpret/discriminant.rs @@ -211,18 +211,19 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let variant_index_relative = u32::try_from(variant_index_relative) .expect("we checked that this fits into a u32"); // Then computing the absolute variant idx should not overflow any more. - let variant_index = variants_start - .checked_add(variant_index_relative) - .expect("overflow computing absolute variant idx"); - let variants_len = op + let variant_index = VariantIdx::from_u32( + variants_start + .checked_add(variant_index_relative) + .expect("overflow computing absolute variant idx"), + ); + let variants = op .layout .ty .ty_adt_def() .expect("tagged layout for non adt") - .variants() - .len(); - assert!(usize::try_from(variant_index).unwrap() < variants_len); - VariantIdx::from_u32(variant_index) + .variants(); + assert!(variant_index < variants.next_index()); + variant_index } else { untagged_variant } diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 13442c3164928..525acfdaa8124 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -17,7 +17,6 @@ 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, DUMMY_SP}; -use rustc_target::abi::FieldIdx; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::traits::ObligationCause; @@ -875,7 +874,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { variant.fields.len() == 1 }) .filter_map(|variant| { - let sole_field = &variant.fields[FieldIdx::from_u32(0)]; + let sole_field = &variant.single_field(); let field_is_local = sole_field.did.is_local(); let field_is_accessible = diff --git a/compiler/rustc_hir_typeck/src/intrinsicck.rs b/compiler/rustc_hir_typeck/src/intrinsicck.rs index 106f5bcd75587..0fdb29a5e4846 100644 --- a/compiler/rustc_hir_typeck/src/intrinsicck.rs +++ b/compiler/rustc_hir_typeck/src/intrinsicck.rs @@ -4,7 +4,7 @@ use rustc_hir as hir; use rustc_index::vec::Idx; use rustc_middle::ty::layout::{LayoutError, SizeSkeleton}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; -use rustc_target::abi::{FieldIdx, Pointer, VariantIdx}; +use rustc_target::abi::{Pointer, VariantIdx}; use super::FnCtxt; @@ -28,7 +28,7 @@ fn unpack_option_like<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { } if def.variant(data_idx).fields.len() == 1 { - return def.variant(data_idx).fields[FieldIdx::from_u32(0)].ty(tcx, substs); + return def.variant(data_idx).single_field().ty(tcx, substs); } } diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index 4dc5fc451ddd4..d885d040707e4 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -10,7 +10,6 @@ use rustc_middle::traits::{ use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self as ty, GenericArgKind, IsSuggestable, Ty, TypeVisitableExt}; use rustc_span::{sym, BytePos, Span}; -use rustc_target::abi::FieldIdx; use crate::errors::{ ConsiderAddingAwait, FnConsiderCasting, FnItemsAreDistinct, FnUniqTypes, @@ -114,7 +113,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { variant.fields.len() == 1 && variant.ctor_kind() == Some(CtorKind::Fn) }) .filter_map(|variant| { - let sole_field = &variant.fields[FieldIdx::from_u32(0)]; + let sole_field = &variant.single_field(); let sole_field_ty = sole_field.ty(self.tcx, substs); if self.same_type_modulo_infer(sole_field_ty, exp_found.found) { let variant_path = diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 2e516f291bc0d..18a397c9abb96 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1969,6 +1969,16 @@ impl VariantDef { pub fn ctor_def_id(&self) -> Option { self.ctor.map(|(_, def_id)| def_id) } + + /// Returns the one field in this variant. + /// + /// `panic!`s if there are no fields or multiple fields. + #[inline] + pub fn single_field(&self) -> &FieldDef { + assert!(self.fields.len() == 1); + + &self.fields[FieldIdx::from_u32(0)] + } } impl PartialEq for VariantDef { diff --git a/compiler/rustc_query_system/src/dep_graph/query.rs b/compiler/rustc_query_system/src/dep_graph/query.rs index 27b3b5e13667e..9dcc41e27269f 100644 --- a/compiler/rustc_query_system/src/dep_graph/query.rs +++ b/compiler/rustc_query_system/src/dep_graph/query.rs @@ -24,10 +24,7 @@ impl DepGraphQuery { pub fn push(&mut self, index: DepNodeIndex, node: DepNode, edges: &[DepNodeIndex]) { let source = self.graph.add_node(node); - if index.index() >= self.dep_index_to_index.len() { - self.dep_index_to_index.resize(index.index() + 1, None); - } - self.dep_index_to_index[index] = Some(source); + self.dep_index_to_index.insert(index, source); self.indices.insert(node, source); for &target in edges.iter() { diff --git a/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs b/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs index ada868705c7c3..dfdd52720a052 100644 --- a/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs +++ b/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs @@ -11,12 +11,13 @@ use super::{CanonicalGoal, Certainty, EvalCtxt, Goal}; use crate::solve::canonicalize::{CanonicalizeMode, Canonicalizer}; use crate::solve::{CanonicalResponse, QueryResult, Response}; +use rustc_index::vec::IndexVec; use rustc_infer::infer::canonical::query_response::make_query_region_constraints; use rustc_infer::infer::canonical::CanonicalVarValues; use rustc_infer::infer::canonical::{CanonicalExt, QueryRegionConstraints}; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::solve::{ExternalConstraints, ExternalConstraintsData}; -use rustc_middle::ty::{self, GenericArgKind}; +use rustc_middle::ty::{self, BoundVar, GenericArgKind}; use rustc_span::DUMMY_SP; use std::iter; use std::ops::Deref; @@ -139,25 +140,25 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { // // We therefore instantiate the existential variable in the canonical response with the // inference variable of the input right away, which is more performant. - let mut opt_values = vec![None; response.variables.len()]; + let mut opt_values = IndexVec::from_elem_n(None, response.variables.len()); for (original_value, result_value) in iter::zip(original_values, var_values.var_values) { match result_value.unpack() { GenericArgKind::Type(t) => { if let &ty::Bound(debruijn, b) = t.kind() { assert_eq!(debruijn, ty::INNERMOST); - opt_values[b.var.index()] = Some(*original_value); + opt_values[b.var] = Some(*original_value); } } GenericArgKind::Lifetime(r) => { if let ty::ReLateBound(debruijn, br) = *r { assert_eq!(debruijn, ty::INNERMOST); - opt_values[br.var.index()] = Some(*original_value); + opt_values[br.var] = Some(*original_value); } } GenericArgKind::Const(c) => { if let ty::ConstKind::Bound(debrujin, b) = c.kind() { assert_eq!(debrujin, ty::INNERMOST); - opt_values[b.index()] = Some(*original_value); + opt_values[b] = Some(*original_value); } } } @@ -180,7 +181,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { // more placeholders then they should be able to. However the inference variables have // to "come from somewhere", so by equating them with the original values of the caller // later on, we pull them down into their correct universe again. - if let Some(v) = opt_values[index] { + if let Some(v) = opt_values[BoundVar::from_usize(index)] { v } else { self.infcx.instantiate_canonical_var(DUMMY_SP, info, |_| prev_universe) From 4e7edf3684ac96f57f918afdb560c4af7afafb60 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 16 Apr 2023 09:56:37 +0000 Subject: [PATCH 056/228] Add tests. --- tests/ui/impl-trait/issue-108591.rs | 30 +++++++++++++++++++++++++ tests/ui/impl-trait/issue-108592.rs | 21 +++++++++++++++++ tests/ui/impl-trait/issue-108592.stderr | 21 +++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 tests/ui/impl-trait/issue-108591.rs create mode 100644 tests/ui/impl-trait/issue-108592.rs create mode 100644 tests/ui/impl-trait/issue-108592.stderr diff --git a/tests/ui/impl-trait/issue-108591.rs b/tests/ui/impl-trait/issue-108591.rs new file mode 100644 index 0000000000000..6b9d14941f237 --- /dev/null +++ b/tests/ui/impl-trait/issue-108591.rs @@ -0,0 +1,30 @@ +// check-pass + +#![feature(type_alias_impl_trait)] + +struct MyTy<'a>(Vec, &'a ()); + +impl MyTy<'_> { + fn one(&mut self) -> &mut impl Sized { + &mut self.0 + } + fn two(&mut self) -> &mut (impl Sized + 'static) { + self.one() + } +} + +type Opaque<'a> = impl Sized; +fn define<'a>() -> Opaque<'a> {} + +fn test<'a>() { + None::<&'static Opaque<'a>>; +} + +fn one<'a, 'b: 'b>() -> &'a impl Sized { + &() +} +fn two<'a, 'b>() { + one::<'a, 'b>(); +} + +fn main() {} diff --git a/tests/ui/impl-trait/issue-108592.rs b/tests/ui/impl-trait/issue-108592.rs new file mode 100644 index 0000000000000..58a0ed9bf1a18 --- /dev/null +++ b/tests/ui/impl-trait/issue-108592.rs @@ -0,0 +1,21 @@ +// check-pass +#![feature(type_alias_impl_trait)] + +fn opaque<'a: 'a>() -> impl Sized {} +fn assert_static(_: T) {} + +fn test_closure() { + let closure = |_| { + assert_static(opaque()); + }; + closure(&opaque()); +} + +type Opaque<'a> = impl Sized; +fn define<'a>() -> Opaque<'a> {} + +fn test_tait(_: &Opaque<'_>) { + None::<&'static Opaque<'_>>; +} + +fn main() {} diff --git a/tests/ui/impl-trait/issue-108592.stderr b/tests/ui/impl-trait/issue-108592.stderr new file mode 100644 index 0000000000000..3fbf0b266c3e3 --- /dev/null +++ b/tests/ui/impl-trait/issue-108592.stderr @@ -0,0 +1,21 @@ +error[E0428]: the name `test` is defined multiple times + --> $DIR/issue-108592.rs:17:1 + | +LL | fn test() { + | --------- previous definition of the value `test` here +... +LL | fn test(_: &Opaque<'_>) { + | ^^^^^^^^^^^^^^^^^^^^^^^ `test` redefined here + | + = note: `test` must be defined only once in the value namespace of this module + +error[E0601]: `main` function not found in crate `issue_108592` + --> $DIR/issue-108592.rs:20:2 + | +LL | } + | ^ consider adding a `main` function to `$DIR/issue-108592.rs` + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0428, E0601. +For more information about an error, try `rustc --explain E0428`. From 8889c6fa0ea8b2045205bc1a4550260c34be98c6 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 16 Apr 2023 10:01:15 +0000 Subject: [PATCH 057/228] Account for variance in outlives obligations. --- .../src/infer/outlives/obligations.rs | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index ccf11c61b573b..2f5e2e417a6fd 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -344,12 +344,14 @@ where // the problem is to add `T: 'r`, which isn't true. So, if there are no // inference variables, we use a verify constraint instead of adding // edges, which winds up enforcing the same condition. + let is_opaque = alias_ty.kind(self.tcx) == ty::Opaque; if approx_env_bounds.is_empty() && trait_bounds.is_empty() - && (alias_ty.needs_infer() || alias_ty.kind(self.tcx) == ty::Opaque) + && (alias_ty.needs_infer() || is_opaque) { debug!("no declared bounds"); - self.substs_must_outlive(alias_ty.substs, origin, region); + let opt_variances = is_opaque.then(|| self.tcx.variances_of(alias_ty.def_id)); + self.substs_must_outlive(alias_ty.substs, origin, region, opt_variances); return; } @@ -395,22 +397,31 @@ where self.delegate.push_verify(origin, GenericKind::Alias(alias_ty), region, verify_bound); } + #[instrument(level = "debug", skip(self))] fn substs_must_outlive( &mut self, substs: SubstsRef<'tcx>, origin: infer::SubregionOrigin<'tcx>, region: ty::Region<'tcx>, + opt_variances: Option<&[ty::Variance]>, ) { let constraint = origin.to_constraint_category(); - for k in substs { + for (index, k) in substs.iter().enumerate() { match k.unpack() { GenericArgKind::Lifetime(lt) => { - self.delegate.push_sub_region_constraint( - origin.clone(), - region, - lt, - constraint, - ); + let variance = if let Some(variances) = opt_variances { + variances[index] + } else { + ty::Invariant + }; + if variance == ty::Invariant { + self.delegate.push_sub_region_constraint( + origin.clone(), + region, + lt, + constraint, + ); + } } GenericArgKind::Type(ty) => { self.type_must_outlive(origin.clone(), ty, region, constraint); From 28d27fd1644b75a6bbd3f7ff85169cfd374e8022 Mon Sep 17 00:00:00 2001 From: Erik Hofmayer Date: Wed, 5 Apr 2023 21:37:15 +0200 Subject: [PATCH 058/228] Set git info env variables when building tools This should fix issue #107094. --- src/bootstrap/tool.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index d1fd2e8c42cb0..9736256f91122 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -319,6 +319,12 @@ pub fn prepare_tool_cargo( cargo.env("CFG_VERSION", builder.rust_version()); cargo.env("CFG_RELEASE_NUM", &builder.version); cargo.env("DOC_RUST_LANG_ORG_CHANNEL", builder.doc_rust_lang_org_channel()); + if let Some(ref ver_date) = builder.rust_info().commit_date() { + cargo.env("CFG_VER_DATE", ver_date); + } + if let Some(ref ver_hash) = builder.rust_info().sha() { + cargo.env("CFG_VER_HASH", ver_hash); + } let info = GitInfo::new(builder.config.omit_git_hash, &dir); if let Some(sha) = info.sha() { From d535af36258f81e542d963aac49ed2f9e5323dcd Mon Sep 17 00:00:00 2001 From: Erik Hofmayer Date: Thu, 6 Apr 2023 22:48:52 +0200 Subject: [PATCH 059/228] Add needs-git-hash header to compiletest This header can be used for tests which check the output of `--version --verbose` commands. --- src/bootstrap/test.rs | 4 ++++ src/tools/compiletest/src/common.rs | 3 +++ src/tools/compiletest/src/header/needs.rs | 5 +++++ src/tools/compiletest/src/header/tests.rs | 10 ++++++++++ src/tools/compiletest/src/main.rs | 2 ++ 5 files changed, 24 insertions(+) diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index aedf1ecab13c4..cbdacfc5f80be 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -1804,6 +1804,10 @@ note: if you're sure you want to do this, please open an issue as to why. In the cmd.arg("--channel").arg(&builder.config.channel); + if !builder.config.ignore_git { + cmd.arg("--git-hash"); + } + if let Some(commit) = builder.config.download_rustc_commit() { cmd.env("FAKE_DOWNLOAD_RUSTC_PREFIX", format!("/rustc/{commit}")); } diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index d2f494942cf9b..3f36cc5bbcc91 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -303,6 +303,9 @@ pub struct Config { /// The current Rust channel pub channel: String, + /// Whether adding git commit information such as the commit hash has been enabled for building + pub git_hash: bool, + /// The default Rust edition pub edition: Option, diff --git a/src/tools/compiletest/src/header/needs.rs b/src/tools/compiletest/src/header/needs.rs index 35d6179abaa6b..81179480ed810 100644 --- a/src/tools/compiletest/src/header/needs.rs +++ b/src/tools/compiletest/src/header/needs.rs @@ -115,6 +115,11 @@ pub(super) fn handle_needs( condition: cache.x86_64_dlltool, ignore_reason: "ignored when dlltool for x86_64 is not present", }, + Need { + name: "needs-git-hash", + condition: config.git_hash, + ignore_reason: "ignored when git hashes have been omitted for building", + }, ]; let (name, comment) = match ln.split_once([':', ' ']) { diff --git a/src/tools/compiletest/src/header/tests.rs b/src/tools/compiletest/src/header/tests.rs index 9af7bd5e20145..362fba11697be 100644 --- a/src/tools/compiletest/src/header/tests.rs +++ b/src/tools/compiletest/src/header/tests.rs @@ -251,6 +251,16 @@ fn debugger() { assert!(check_ignore(&config, "// ignore-lldb")); } +#[test] +fn git_hash() { + let mut config = config(); + config.git_hash = false; + assert!(check_ignore(&config, "// needs-git-hash")); + + config.git_hash = true; + assert!(!check_ignore(&config, "// needs-git-hash")); +} + #[test] fn sanitizers() { let mut config = config(); diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index 4a2b9de8aee6b..c4bef998f3171 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -159,6 +159,7 @@ pub fn parse_config(args: Vec) -> Config { .optflag("", "nocapture", "") .optflag("h", "help", "show this message") .reqopt("", "channel", "current Rust channel", "CHANNEL") + .optflag("", "git-hash", "run tests which rely on commit version being compiled into the binaries") .optopt("", "edition", "default Rust edition", "EDITION"); let (argv0, args_) = args.split_first().unwrap(); @@ -302,6 +303,7 @@ pub fn parse_config(args: Vec) -> Config { rustfix_coverage: matches.opt_present("rustfix-coverage"), has_tidy, channel: matches.opt_str("channel").unwrap(), + git_hash: matches.opt_present("git-hash"), edition: matches.opt_str("edition"), cc: matches.opt_str("cc").unwrap(), From 135e6201fc3dc61bcee1d4186f233570edbbbb8c Mon Sep 17 00:00:00 2001 From: Erik Hofmayer Date: Fri, 7 Apr 2023 19:45:37 +0200 Subject: [PATCH 060/228] Add regression test for issue 107094 --- tests/run-make/issue-107094/Makefile | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100755 tests/run-make/issue-107094/Makefile diff --git a/tests/run-make/issue-107094/Makefile b/tests/run-make/issue-107094/Makefile new file mode 100755 index 0000000000000..7bbaf31a7771d --- /dev/null +++ b/tests/run-make/issue-107094/Makefile @@ -0,0 +1,7 @@ +# needs-git-hash + +include ../tools.mk + +all: + $(BARE_RUSTC) --version --verbose | $(CGREP) -i -e "commit-hash: [0-9a-f]{40}" "commit-date: [0-9\-]+" + $(BARE_RUSTDOC) --version --verbose | $(CGREP) -i -e "commit-hash: [0-9a-f]{40}" "commit-date: [0-9\-]+" From 550df4d34b4398a232058641980c1a5619fe152e Mon Sep 17 00:00:00 2001 From: Erik Hofmayer Date: Fri, 7 Apr 2023 20:58:07 +0200 Subject: [PATCH 061/228] Change mode of Makefile of test for issue 107094 --- tests/run-make/issue-107094/Makefile | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 tests/run-make/issue-107094/Makefile diff --git a/tests/run-make/issue-107094/Makefile b/tests/run-make/issue-107094/Makefile old mode 100755 new mode 100644 From bfa87984d272f06b5a3af6ed3030dcdaa53d9cab Mon Sep 17 00:00:00 2001 From: Erik Hofmayer Date: Sun, 9 Apr 2023 12:27:41 +0200 Subject: [PATCH 062/228] Fix error due to renaming of ignore_git --- src/bootstrap/test.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index cbdacfc5f80be..3814dc63ed4dc 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -1804,7 +1804,7 @@ note: if you're sure you want to do this, please open an issue as to why. In the cmd.arg("--channel").arg(&builder.config.channel); - if !builder.config.ignore_git { + if !builder.config.omit_git_hash { cmd.arg("--git-hash"); } From e4a9d137d0c29d3625672f137dadb57149fc8a30 Mon Sep 17 00:00:00 2001 From: klensy Date: Sun, 16 Apr 2023 14:13:14 +0300 Subject: [PATCH 063/228] bolt: remove deprecated option value --- src/bootstrap/bolt.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/bolt.rs b/src/bootstrap/bolt.rs index 10e6d2e7d6d08..5384181ea687d 100644 --- a/src/bootstrap/bolt.rs +++ b/src/bootstrap/bolt.rs @@ -40,7 +40,7 @@ pub fn optimize_with_bolt(path: &Path, profile_path: &Path, output_path: &Path) // Reorder functions within the binary .arg("-reorder-functions=hfsort+") // Split function code into hot and code regions - .arg("-split-functions=2") + .arg("-split-functions") // Split as many basic blocks as possible .arg("-split-all-cold") // Move jump tables to a separate section From 4c6ddc036b13cc9fa06e437295476231a7c11435 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Sun, 16 Apr 2023 11:12:37 +0000 Subject: [PATCH 064/228] fix library and rustdoc tests --- library/alloc/tests/const_fns.rs | 19 +++-- library/alloc/tests/lib.rs | 2 - library/core/tests/atomic.rs | 2 + library/core/tests/bool.rs | 2 + library/core/tests/cell.rs | 2 + library/core/tests/char.rs | 2 + library/core/tests/cmp.rs | 2 + library/core/tests/convert.rs | 2 + library/core/tests/hash/mod.rs | 12 +-- library/core/tests/hash/sip.rs | 2 + library/core/tests/lazy.rs | 2 + library/core/tests/lib.rs | 3 - library/core/tests/nonzero.rs | 2 + library/core/tests/num/const_from.rs | 2 + library/core/tests/option.rs | 24 ++++-- library/core/tests/time.rs | 12 ++- ...ide-complex-unevaluated-const-arguments.rs | 8 +- tests/rustdoc/rfc-2632-const-trait-impl.rs | 40 +++++----- .../unify-op-with-fn-call.rs | 3 +- .../unify-op-with-fn-call.stderr | 11 +-- .../const-eval/const-eval-overflow-3b.stderr | 4 +- .../const-eval/const-eval-overflow-4b.stderr | 4 +- .../ui/consts/const-eval/const_raw_ptr_ops.rs | 4 +- .../const-eval/const_raw_ptr_ops.stderr | 27 ++----- .../const-eval/ub-slice-get-unchecked.rs | 2 + .../const-eval/ub-slice-get-unchecked.stderr | 19 ++--- tests/ui/consts/const-float-classify.rs | 35 ++++++--- tests/ui/consts/const-fn-error.rs | 1 - tests/ui/consts/const-fn-error.stderr | 19 +---- tests/ui/consts/const-for.rs | 1 - tests/ui/consts/const-for.stderr | 18 +---- tests/ui/consts/const-try.rs | 2 +- tests/ui/consts/const-try.stderr | 20 +++++ tests/ui/consts/const_cmp_type_id.rs | 2 +- tests/ui/consts/const_cmp_type_id.stderr | 76 +++++++++++++++++++ tests/ui/consts/fn_trait_refs.rs | 2 +- tests/ui/consts/fn_trait_refs.stderr | 15 ++++ tests/ui/consts/issue-25826.rs | 2 +- tests/ui/consts/issue-25826.stderr | 14 +--- tests/ui/consts/issue-73976-monomorphic.rs | 2 +- .../ui/consts/issue-73976-monomorphic.stderr | 28 +++++++ tests/ui/consts/issue-94675.rs | 5 +- tests/ui/consts/issue-94675.stderr | 28 ++++--- .../ui/consts/min_const_fn/cmp_fn_pointers.rs | 2 +- .../min_const_fn/cmp_fn_pointers.stderr | 14 +--- tests/ui/consts/promoted_const_call.rs | 2 + tests/ui/consts/promoted_const_call.stderr | 12 +-- tests/ui/consts/rustc-impl-const-stability.rs | 2 +- .../consts/rustc-impl-const-stability.stderr | 11 +++ tests/ui/consts/try-operator.rs | 2 +- tests/ui/consts/try-operator.stderr | 9 +++ ...de-confusable-in-float-literal-expt.stderr | 4 +- tests/ui/issues/issue-25901.rs | 2 +- tests/ui/issues/issue-25901.stderr | 23 ++++-- tests/ui/issues/issue-50582.stderr | 4 +- tests/ui/never_type/issue-52443.rs | 1 - tests/ui/never_type/issue-52443.stderr | 17 +---- .../rfc-2632-const-trait-impl/assoc-type.rs | 3 +- .../assoc-type.stderr | 19 +---- .../call-const-trait-method-pass.rs | 2 +- .../call-const-trait-method-pass.stderr | 20 +++++ .../call-generic-in-impl.rs | 2 +- .../call-generic-in-impl.stderr | 8 ++ .../call-generic-method-chain.rs | 2 +- .../call-generic-method-chain.stderr | 23 ++++++ .../call-generic-method-dup-bound.rs | 2 +- .../call-generic-method-dup-bound.stderr | 23 ++++++ .../call-generic-method-fail.rs | 3 +- .../call-generic-method-fail.stderr | 29 +++++-- .../call-generic-method-pass.rs | 2 +- .../call-generic-method-pass.stderr | 17 +++++ .../const-and-non-const-impl.rs | 4 +- .../const-and-non-const-impl.stderr | 27 +++---- .../const-closure-trait-method-fail.rs | 3 +- .../const-closure-trait-method-fail.stderr | 4 +- .../const-closures.rs | 2 +- .../const-drop-fail-2.precise.stderr | 54 ++++--------- .../const-drop-fail-2.rs | 5 +- .../const-drop-fail-2.stderr | 50 ++++++++++++ .../const-drop-fail-2.stock.stderr | 54 ++++--------- .../const-drop-fail.precise.stderr | 10 +-- .../const-drop-fail.rs | 4 +- .../const-drop-fail.stock.stderr | 10 +-- .../const-impl-trait.rs | 2 +- .../const-impl-trait.stderr | 39 ++++++++++ .../const_derives/derive-const-gate.rs | 1 + .../const_derives/derive-const-gate.stderr | 12 ++- .../derive-const-non-const-type.rs | 3 +- .../derive-const-non-const-type.stderr | 38 ++-------- .../const_derives/derive-const-use.rs | 2 +- .../const_derives/derive-const-use.stderr | 53 +++++++++++++ .../const_derives/derive-const-with-params.rs | 2 +- .../derive-const-with-params.stderr | 20 +++++ .../generic-bound.rs | 2 +- .../generic-bound.stderr | 11 +++ .../non-const-op-in-closure-in-const.rs | 2 +- .../non-const-op-in-closure-in-const.stderr | 8 ++ .../specializing-constness.rs | 7 +- .../specializing-constness.stderr | 12 +-- .../std-impl-gate.gated.stderr | 9 +++ .../std-impl-gate.rs | 2 +- .../trait-default-body-stability.rs | 2 +- .../trait-default-body-stability.stderr | 20 +++++ tests/ui/specialization/const_trait_impl.rs | 3 +- .../ui/specialization/const_trait_impl.stderr | 20 +++++ tests/ui/suggestions/issue-109436.stderr | 2 +- .../ui/typeck/typeck_type_placeholder_item.rs | 4 +- .../typeck_type_placeholder_item.stderr | 34 ++------- 108 files changed, 839 insertions(+), 442 deletions(-) create mode 100644 tests/ui/consts/const-try.stderr create mode 100644 tests/ui/consts/const_cmp_type_id.stderr create mode 100644 tests/ui/consts/fn_trait_refs.stderr create mode 100644 tests/ui/consts/issue-73976-monomorphic.stderr create mode 100644 tests/ui/consts/rustc-impl-const-stability.stderr create mode 100644 tests/ui/consts/try-operator.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/call-const-trait-method-pass.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/call-generic-in-impl.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/call-generic-method-chain.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/call-generic-method-dup-bound.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/call-generic-method-pass.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/const-impl-trait.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-use.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/generic-bound.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/std-impl-gate.gated.stderr create mode 100644 tests/ui/rfc-2632-const-trait-impl/trait-default-body-stability.stderr create mode 100644 tests/ui/specialization/const_trait_impl.stderr diff --git a/library/alloc/tests/const_fns.rs b/library/alloc/tests/const_fns.rs index 49b837becbcd8..4e7d7fc833ea1 100644 --- a/library/alloc/tests/const_fns.rs +++ b/library/alloc/tests/const_fns.rs @@ -1,13 +1,16 @@ // Test const functions in the library pub const MY_VEC: Vec = Vec::new(); -pub const MY_VEC2: Vec = Default::default(); + +// FIXME(#110395) +// pub const MY_VEC2: Vec = Default::default(); pub const MY_STRING: String = String::new(); -pub const MY_STRING2: String = Default::default(); -pub const MY_BOXED_SLICE: Box<[usize]> = Default::default(); -pub const MY_BOXED_STR: Box = Default::default(); +// pub const MY_STRING2: String = Default::default(); + +// pub const MY_BOXED_SLICE: Box<[usize]> = Default::default(); +// pub const MY_BOXED_STR: Box = Default::default(); use std::collections::{BTreeMap, BTreeSet}; @@ -23,11 +26,11 @@ pub const SET_IS_EMPTY: bool = SET.is_empty(); #[test] fn test_const() { - assert_eq!(MY_VEC, MY_VEC2); - assert_eq!(MY_STRING, MY_STRING2); + assert_eq!(MY_VEC, /* MY_VEC */ vec![]); + assert_eq!(MY_STRING, /* MY_STRING2 */ String::default()); - assert_eq!(MY_VEC, *MY_BOXED_SLICE); - assert_eq!(MY_STRING, *MY_BOXED_STR); + // assert_eq!(MY_VEC, *MY_BOXED_SLICE); + // assert_eq!(MY_STRING, *MY_BOXED_STR); assert_eq!(MAP_LEN, 0); assert_eq!(SET_LEN, 0); diff --git a/library/alloc/tests/lib.rs b/library/alloc/tests/lib.rs index 0667cd7bc07e1..0eca4c9bb07aa 100644 --- a/library/alloc/tests/lib.rs +++ b/library/alloc/tests/lib.rs @@ -3,7 +3,6 @@ #![feature(assert_matches)] #![feature(btree_drain_filter)] #![feature(cow_is_borrowed)] -#![feature(const_convert)] #![feature(const_cow_is_borrowed)] #![feature(const_heap)] #![feature(const_mut_refs)] @@ -33,7 +32,6 @@ #![feature(slice_partition_dedup)] #![feature(string_remove_matches)] #![feature(const_btree_len)] -#![feature(const_default_impls)] #![feature(const_trait_impl)] #![feature(const_str_from_utf8)] #![feature(panic_update_hook)] diff --git a/library/core/tests/atomic.rs b/library/core/tests/atomic.rs index 94b0310603bf4..a67a842d3407f 100644 --- a/library/core/tests/atomic.rs +++ b/library/core/tests/atomic.rs @@ -306,9 +306,11 @@ fn atomic_compare_exchange() { ATOMIC.compare_exchange_weak(0, 1, SeqCst, SeqCst).ok(); } +/* FIXME(#110395) #[test] fn atomic_const_from() { const _ATOMIC_U8: AtomicU8 = AtomicU8::from(1); const _ATOMIC_BOOL: AtomicBool = AtomicBool::from(true); const _ATOMIC_PTR: AtomicPtr = AtomicPtr::from(core::ptr::null_mut()); } +*/ diff --git a/library/core/tests/bool.rs b/library/core/tests/bool.rs index 4819ce911d618..47f6459915b3e 100644 --- a/library/core/tests/bool.rs +++ b/library/core/tests/bool.rs @@ -89,6 +89,7 @@ fn test_bool_to_option() { assert_eq!(false.then(|| 0), None); assert_eq!(true.then(|| 0), Some(0)); + /* FIXME(#110395) const fn zero() -> i32 { 0 } @@ -102,4 +103,5 @@ fn test_bool_to_option() { assert_eq!(B, Some(0)); assert_eq!(C, None); assert_eq!(D, Some(0)); + */ } diff --git a/library/core/tests/cell.rs b/library/core/tests/cell.rs index 7b77b2134ccd7..e084f867943d3 100644 --- a/library/core/tests/cell.rs +++ b/library/core/tests/cell.rs @@ -468,6 +468,7 @@ fn const_cells() { const CELL: Cell = Cell::new(3); const _: i32 = CELL.into_inner(); +/* FIXME(#110395) const UNSAFE_CELL_FROM: UnsafeCell = UnsafeCell::from(3); const _: i32 = UNSAFE_CELL.into_inner(); @@ -476,4 +477,5 @@ fn const_cells() { const CELL_FROM: Cell = Cell::from(3); const _: i32 = CELL.into_inner(); +*/ } diff --git a/library/core/tests/char.rs b/library/core/tests/char.rs index ac0b2ca168b23..85ba51c9228e3 100644 --- a/library/core/tests/char.rs +++ b/library/core/tests/char.rs @@ -21,6 +21,7 @@ fn test_convert() { assert!(char::try_from(0xFFFF_FFFF_u32).is_err()); } +/* FIXME(#110395) #[test] const fn test_convert_const() { assert!(u32::from('a') == 0x61); @@ -30,6 +31,7 @@ const fn test_convert_const() { assert!(char::from(b'a') == 'a'); assert!(char::from(b'\xFF') == '\u{FF}'); } +*/ #[test] fn test_from_str() { diff --git a/library/core/tests/cmp.rs b/library/core/tests/cmp.rs index dc5b8a3991449..72fdd490da152 100644 --- a/library/core/tests/cmp.rs +++ b/library/core/tests/cmp.rs @@ -217,6 +217,7 @@ fn cmp_default() { assert_eq!(Fool(false), Fool(true)); } +/* FIXME(#110395) mod const_cmp { use super::*; @@ -248,3 +249,4 @@ mod const_cmp { const _: () = assert!(S(0) < S(1)); const _: () = assert!(S(1) > S(0)); } +*/ diff --git a/library/core/tests/convert.rs b/library/core/tests/convert.rs index f1048f4cf09cb..f76dd277884e2 100644 --- a/library/core/tests/convert.rs +++ b/library/core/tests/convert.rs @@ -1,3 +1,4 @@ +/* FIXME(#110395) #[test] fn convert() { const fn from(x: i32) -> i32 { @@ -14,3 +15,4 @@ fn convert() { const BAR: Vec = into(Vec::new()); assert_eq!(BAR, Vec::::new()); } +*/ diff --git a/library/core/tests/hash/mod.rs b/library/core/tests/hash/mod.rs index 2f4b9c7410155..033bd1ed6ed9e 100644 --- a/library/core/tests/hash/mod.rs +++ b/library/core/tests/hash/mod.rs @@ -35,13 +35,14 @@ impl Hasher for MyHasher { #[test] fn test_writer_hasher() { - const fn hash(t: &T) -> u64 { + // FIXME(#110395) + /* const */ fn hash(t: &T) -> u64 { let mut s = MyHasher { hash: 0 }; t.hash(&mut s); s.finish() } - const { + /* const { // FIXME(fee1-dead): assert_eq assert!(hash(&()) == 0); assert!(hash(&5_u8) == 5); @@ -52,7 +53,7 @@ fn test_writer_hasher() { let s: &str = "a"; assert!(hash(&s) == 97 + 0xFF); - }; + }; */ assert_eq!(hash(&()), 0); @@ -139,7 +140,8 @@ impl Hash for Custom { #[test] fn test_custom_state() { - const fn hash(t: &T) -> u64 { + // FIXME(#110395) + /* const */ fn hash(t: &T) -> u64 { let mut c = CustomHasher { output: 0 }; t.hash(&mut c); c.finish() @@ -147,7 +149,7 @@ fn test_custom_state() { assert_eq!(hash(&Custom { hash: 5 }), 5); - const { assert!(hash(&Custom { hash: 6 }) == 6) }; + // const { assert!(hash(&Custom { hash: 6 }) == 6) }; } // FIXME: Instantiated functions with i128 in the signature is not supported in Emscripten. diff --git a/library/core/tests/hash/sip.rs b/library/core/tests/hash/sip.rs index 4b9f472625d69..0a67c485c98bb 100644 --- a/library/core/tests/hash/sip.rs +++ b/library/core/tests/hash/sip.rs @@ -23,6 +23,7 @@ fn hash(x: &T) -> u64 { hash_with(SipHasher::new(), x) } +/* FIXME(#110395) #[test] const fn test_const_sip() { let val1 = 0x45; @@ -36,6 +37,7 @@ const fn test_const_sip() { assert!(const_hash(&(val1)) != const_hash(&(val2))); } +*/ #[test] #[allow(unused_must_use)] diff --git a/library/core/tests/lazy.rs b/library/core/tests/lazy.rs index c7c3c479b71db..e2f526d155e87 100644 --- a/library/core/tests/lazy.rs +++ b/library/core/tests/lazy.rs @@ -46,11 +46,13 @@ fn unsync_once_cell_drop_empty() { drop(x); } +/* FIXME(#110395) #[test] const fn once_cell_const() { let _once_cell: OnceCell = OnceCell::new(); let _once_cell: OnceCell = OnceCell::from(32); } +*/ #[test] fn clone() { diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index 6cdafa411d003..f460da35dd3e6 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -8,16 +8,13 @@ #![feature(const_assume)] #![feature(const_align_of_val_raw)] #![feature(const_black_box)] -#![feature(const_bool_to_option)] #![feature(const_caller_location)] #![feature(const_cell_into_inner)] -#![feature(const_convert)] #![feature(const_hash)] #![feature(const_heap)] #![feature(const_maybe_uninit_as_mut_ptr)] #![feature(const_maybe_uninit_assume_init_read)] #![feature(const_nonnull_new)] -#![feature(const_num_from_num)] #![feature(const_pointer_byte_offsets)] #![feature(const_pointer_is_aligned)] #![feature(const_ptr_as_ref)] diff --git a/library/core/tests/nonzero.rs b/library/core/tests/nonzero.rs index a0ca919a851c3..96356b728e926 100644 --- a/library/core/tests/nonzero.rs +++ b/library/core/tests/nonzero.rs @@ -215,11 +215,13 @@ fn nonzero_const() { const ONE: Option = NonZeroU8::new(1); assert!(ONE.is_some()); + /* FIXME(#110395) const FROM_NONZERO_U8: u8 = u8::from(NONZERO_U8); assert_eq!(FROM_NONZERO_U8, 5); const NONZERO_CONVERT: NonZeroU32 = NonZeroU32::from(NONZERO_U8); assert_eq!(NONZERO_CONVERT.get(), 5); + */ } #[test] diff --git a/library/core/tests/num/const_from.rs b/library/core/tests/num/const_from.rs index aca18ef39de1a..fa58e77187915 100644 --- a/library/core/tests/num/const_from.rs +++ b/library/core/tests/num/const_from.rs @@ -1,3 +1,4 @@ +/* FIXME(#110395) #[test] fn from() { use core::convert::TryFrom; @@ -23,3 +24,4 @@ fn from() { const I16_FROM_U16: Result = i16::try_from(1u16); assert_eq!(I16_FROM_U16, Ok(1i16)); } +*/ diff --git a/library/core/tests/option.rs b/library/core/tests/option.rs index dca6321cf62fd..5defeb50d40f9 100644 --- a/library/core/tests/option.rs +++ b/library/core/tests/option.rs @@ -88,6 +88,7 @@ fn test_and() { assert_eq!(x.and(Some(2)), None); assert_eq!(x.and(None::), None); + /* FIXME(#110395) const FOO: Option = Some(1); const A: Option = FOO.and(Some(2)); const B: Option = FOO.and(None); @@ -99,6 +100,7 @@ fn test_and() { const D: Option = BAR.and(None); assert_eq!(C, None); assert_eq!(D, None); + */ } #[test] @@ -119,6 +121,7 @@ fn test_and_then() { assert_eq!(x.and_then(plus_one), None); assert_eq!(x.and_then(none), None); + /* FIXME(#110395) const FOO: Option = Some(1); const A: Option = FOO.and_then(plus_one); const B: Option = FOO.and_then(none); @@ -130,6 +133,7 @@ fn test_and_then() { const D: Option = BAR.and_then(none); assert_eq!(C, None); assert_eq!(D, None); + */ } #[test] @@ -142,6 +146,7 @@ fn test_or() { assert_eq!(x.or(Some(2)), Some(2)); assert_eq!(x.or(None), None); + /* FIXME(#110395) const FOO: Option = Some(1); const A: Option = FOO.or(Some(2)); const B: Option = FOO.or(None); @@ -153,6 +158,7 @@ fn test_or() { const D: Option = BAR.or(None); assert_eq!(C, Some(2)); assert_eq!(D, None); + */ } #[test] @@ -173,6 +179,7 @@ fn test_or_else() { assert_eq!(x.or_else(two), Some(2)); assert_eq!(x.or_else(none), None); +/* FIXME(#110395) const FOO: Option = Some(1); const A: Option = FOO.or_else(two); const B: Option = FOO.or_else(none); @@ -184,6 +191,7 @@ fn test_or_else() { const D: Option = BAR.or_else(none); assert_eq!(C, Some(2)); assert_eq!(D, None); +*/ } #[test] @@ -215,10 +223,12 @@ fn test_unwrap_or() { let x: Option = None; assert_eq!(x.unwrap_or(2), 2); + /* FIXME(#110395) const A: isize = Some(1).unwrap_or(2); const B: isize = None.unwrap_or(2); assert_eq!(A, 1); assert_eq!(B, 2); + */ } #[test] @@ -233,10 +243,12 @@ fn test_unwrap_or_else() { let x: Option = None; assert_eq!(x.unwrap_or_else(two), 2); + /* FIXME(#110395) const A: isize = Some(1).unwrap_or_else(two); const B: isize = None.unwrap_or_else(two); assert_eq!(A, 1); assert_eq!(B, 2); + */ } #[test] @@ -439,14 +451,15 @@ fn option_const() { const OPTION: Option = Some(32); assert_eq!(OPTION, Some(32)); - const OPTION_FROM: Option = Option::from(32); - assert_eq!(OPTION_FROM, Some(32)); + // FIXME(#110395) + // const OPTION_FROM: Option = Option::from(32); + // assert_eq!(OPTION_FROM, Some(32)); const REF: Option<&usize> = OPTION.as_ref(); assert_eq!(REF, Some(&32)); - const REF_FROM: Option<&usize> = Option::from(&OPTION); - assert_eq!(REF_FROM, Some(&32)); + // const REF_FROM: Option<&usize> = Option::from(&OPTION); + // assert_eq!(REF_FROM, Some(&32)); const IS_SOME: bool = OPTION.is_some(); assert!(IS_SOME); @@ -474,7 +487,7 @@ const fn option_const_mut() { None => unreachable!(), } } - +/* FIXME(const-hack) { let as_mut: Option<&mut usize> = Option::from(&mut option); match as_mut { @@ -482,6 +495,7 @@ const fn option_const_mut() { None => unreachable!(), } } +*/ } #[test] diff --git a/library/core/tests/time.rs b/library/core/tests/time.rs index 2975c81f8fec9..872611937cc08 100644 --- a/library/core/tests/time.rs +++ b/library/core/tests/time.rs @@ -425,14 +425,16 @@ fn duration_const() { const SECONDS_F32: f32 = Duration::SECOND.as_secs_f32(); assert_eq!(SECONDS_F32, 1.0); - const FROM_SECONDS_F32: Duration = Duration::from_secs_f32(1.0); - assert_eq!(FROM_SECONDS_F32, Duration::SECOND); + // FIXME(#110395) + // const FROM_SECONDS_F32: Duration = Duration::from_secs_f32(1.0); + // assert_eq!(FROM_SECONDS_F32, Duration::SECOND); const SECONDS_F64: f64 = Duration::SECOND.as_secs_f64(); assert_eq!(SECONDS_F64, 1.0); - const FROM_SECONDS_F64: Duration = Duration::from_secs_f64(1.0); - assert_eq!(FROM_SECONDS_F64, Duration::SECOND); + // FIXME(#110395) + // const FROM_SECONDS_F64: Duration = Duration::from_secs_f64(1.0); + // assert_eq!(FROM_SECONDS_F64, Duration::SECOND); const MILLIS: u128 = Duration::SECOND.as_millis(); assert_eq!(MILLIS, 1_000); @@ -463,6 +465,7 @@ fn duration_const() { const CHECKED_MUL: Option = Duration::SECOND.checked_mul(1); assert_eq!(CHECKED_MUL, Some(Duration::SECOND)); +/* FIXME(#110395) const MUL_F32: Duration = Duration::SECOND.mul_f32(1.0); assert_eq!(MUL_F32, Duration::SECOND); @@ -477,6 +480,7 @@ fn duration_const() { const DIV_F64: Duration = Duration::SECOND.div_f64(1.0); assert_eq!(DIV_F64, Duration::SECOND); +*/ const DIV_DURATION_F32: f32 = Duration::SECOND.div_duration_f32(Duration::SECOND); assert_eq!(DIV_DURATION_F32, 1.0); diff --git a/tests/rustdoc/hide-complex-unevaluated-const-arguments.rs b/tests/rustdoc/hide-complex-unevaluated-const-arguments.rs index d368db909fa01..6006354eba4e5 100644 --- a/tests/rustdoc/hide-complex-unevaluated-const-arguments.rs +++ b/tests/rustdoc/hide-complex-unevaluated-const-arguments.rs @@ -29,7 +29,7 @@ pub trait Stage { // // @has - '//*[@id="associatedconstant.ARRAY1"]' \ // 'const ARRAY1: [u8; { _ }]' - const ARRAY1: [u8; Struct::new(/* ... */) + Self::ABSTRACT * 1_000]; + const ARRAY1: [u8; Struct::new(/* ... */).do_something(Self::ABSTRACT * 1_000)]; // @has - '//*[@id="associatedconstant.VERBOSE"]' \ // 'const VERBOSE: [u16; { _ }]' @@ -73,10 +73,14 @@ pub struct Struct { private: () } impl Struct { const fn new() -> Self { Self { private: () } } + const fn do_something(self, x: usize) -> usize { + x + } } - +/* FIXME(const-trait): readd this impl const std::ops::Add for Struct { type Output = usize; fn add(self, _: usize) -> usize { 0 } } +*/ diff --git a/tests/rustdoc/rfc-2632-const-trait-impl.rs b/tests/rustdoc/rfc-2632-const-trait-impl.rs index 1120302ac7ea9..5d742dc391a53 100644 --- a/tests/rustdoc/rfc-2632-const-trait-impl.rs +++ b/tests/rustdoc/rfc-2632-const-trait-impl.rs @@ -13,57 +13,57 @@ use std::marker::Destruct; pub struct S(T); // @!has foo/trait.Tr.html '//pre[@class="rust item-decl"]/code/a[@class="trait"]' '~const' -// @has - '//pre[@class="rust item-decl"]/code/a[@class="trait"]' 'Clone' +// @has - '//pre[@class="rust item-decl"]/code/a[@class="trait"]' 'Fn' // @!has - '//pre[@class="rust item-decl"]/code/span[@class="where"]' '~const' -// @has - '//pre[@class="rust item-decl"]/code/span[@class="where"]' ': Clone' +// @has - '//pre[@class="rust item-decl"]/code/span[@class="where"]' ': Fn' #[const_trait] pub trait Tr { // @!has - '//section[@id="method.a"]/h4[@class="code-header"]' '~const' - // @has - '//section[@id="method.a"]/h4[@class="code-header"]/a[@class="trait"]' 'Clone' + // @has - '//section[@id="method.a"]/h4[@class="code-header"]/a[@class="trait"]' 'Fn' // @!has - '//section[@id="method.a"]/h4[@class="code-header"]/span[@class="where"]' '~const' - // @has - '//section[@id="method.a"]/h4[@class="code-header"]/span[@class="where fmt-newline"]' ': Clone' - fn a() + // @has - '//section[@id="method.a"]/h4[@class="code-header"]/span[@class="where fmt-newline"]' ': Fn' + fn a() where - Option: ~const Clone + ~const Destruct, + Option: ~const Fn() + ~const Destruct, { } } // @has - '//section[@id="impl-Tr%3CT%3E-for-T"]' '' // @!has - '//section[@id="impl-Tr%3CT%3E-for-T"]/h3[@class="code-header"]' '~const' -// @has - '//section[@id="impl-Tr%3CT%3E-for-T"]/h3[@class="code-header"]/a[@class="trait"]' 'Clone' +// @has - '//section[@id="impl-Tr%3CT%3E-for-T"]/h3[@class="code-header"]/a[@class="trait"]' 'Fn' // @!has - '//section[@id="impl-Tr%3CT%3E-for-T"]/h3[@class="code-header"]/span[@class="where"]' '~const' -// @has - '//section[@id="impl-Tr%3CT%3E-for-T"]/h3[@class="code-header"]/span[@class="where fmt-newline"]' ': Clone' -impl const Tr for T +// @has - '//section[@id="impl-Tr%3CT%3E-for-T"]/h3[@class="code-header"]/span[@class="where fmt-newline"]' ': Fn' +impl const Tr for T where - Option: ~const Clone + ~const Destruct, + Option: ~const Fn() + ~const Destruct, { - fn a() + fn a() where - Option: ~const Clone + ~const Destruct, + Option: ~const Fn() + ~const Destruct, { } } // @!has foo/fn.foo.html '//pre[@class="rust item-decl"]/code/a[@class="trait"]' '~const' -// @has - '//pre[@class="rust item-decl"]/code/a[@class="trait"]' 'Clone' +// @has - '//pre[@class="rust item-decl"]/code/a[@class="trait"]' 'Fn' // @!has - '//pre[@class="rust item-decl"]/code/span[@class="where fmt-newline"]' '~const' -// @has - '//pre[@class="rust item-decl"]/code/span[@class="where fmt-newline"]' ': Clone' -pub const fn foo() +// @has - '//pre[@class="rust item-decl"]/code/span[@class="where fmt-newline"]' ': Fn' +pub const fn foo() where - Option: ~const Clone + ~const Destruct, + Option: ~const Fn() + ~const Destruct, { F::a() } impl S { // @!has foo/struct.S.html '//section[@id="method.foo"]/h4[@class="code-header"]' '~const' - // @has - '//section[@id="method.foo"]/h4[@class="code-header"]/a[@class="trait"]' 'Clone' + // @has - '//section[@id="method.foo"]/h4[@class="code-header"]/a[@class="trait"]' 'Fn' // @!has - '//section[@id="method.foo"]/h4[@class="code-header"]/span[@class="where"]' '~const' - // @has - '//section[@id="method.foo"]/h4[@class="code-header"]/span[@class="where fmt-newline"]' ': Clone' - pub const fn foo() + // @has - '//section[@id="method.foo"]/h4[@class="code-header"]/span[@class="where fmt-newline"]' ': Fn' + pub const fn foo() where - B: ~const Clone + ~const Destruct, + B: ~const Fn() + ~const Destruct, { B::a() } diff --git a/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.rs b/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.rs index c0404d35b0887..ae9207cf8555b 100644 --- a/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.rs +++ b/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.rs @@ -1,3 +1,5 @@ +// known-bug: #110395 + #![feature(generic_const_exprs, adt_const_params, const_trait_impl)] #![allow(incomplete_features)] @@ -26,7 +28,6 @@ struct Evaluatable2; fn foo2(a: Evaluatable2<{ N + N }>) { bar2::<{ std::ops::Add::add(N, N) }>(); - //~^ error: unconstrained generic constant // FIXME(generic_const_exprs) make this not an error } diff --git a/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.stderr b/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.stderr index d18c7916f5f6f..7f28771cee83f 100644 --- a/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.stderr +++ b/tests/ui/const-generics/generic_const_exprs/unify-op-with-fn-call.stderr @@ -1,10 +1,11 @@ -error: unconstrained generic constant - --> $DIR/unify-op-with-fn-call.rs:28:12 +error: const `impl` for trait `Add` which is not marked with `#[const_trait]` + --> $DIR/unify-op-with-fn-call.rs:10:12 | -LL | bar2::<{ std::ops::Add::add(N, N) }>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | impl const std::ops::Add for Foo { + | ^^^^^^^^^^^^^ | - = help: try adding a `where` bound using this expression: `where [(); { std::ops::Add::add(N, N) }]:` + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change error: aborting due to previous error diff --git a/tests/ui/consts/const-eval/const-eval-overflow-3b.stderr b/tests/ui/consts/const-eval/const-eval-overflow-3b.stderr index f199170018f20..05f33c33946a8 100644 --- a/tests/ui/consts/const-eval/const-eval-overflow-3b.stderr +++ b/tests/ui/consts/const-eval/const-eval-overflow-3b.stderr @@ -4,13 +4,13 @@ error[E0308]: mismatched types LL | = [0; (i8::MAX + 1u8) as usize]; | ^^^ expected `i8`, found `u8` -error[E0277]: cannot add `u8` to `i8` in const contexts +error[E0277]: cannot add `u8` to `i8` --> $DIR/const-eval-overflow-3b.rs:16:20 | LL | = [0; (i8::MAX + 1u8) as usize]; | ^ no implementation for `i8 + u8` | - = help: the trait `~const Add` is not implemented for `i8` + = help: the trait `Add` is not implemented for `i8` = help: the following other types implement trait `Add`: <&'a i8 as Add> <&i8 as Add<&i8>> diff --git a/tests/ui/consts/const-eval/const-eval-overflow-4b.stderr b/tests/ui/consts/const-eval/const-eval-overflow-4b.stderr index 1f8e402317aa8..d019f5920b517 100644 --- a/tests/ui/consts/const-eval/const-eval-overflow-4b.stderr +++ b/tests/ui/consts/const-eval/const-eval-overflow-4b.stderr @@ -4,13 +4,13 @@ error[E0308]: mismatched types LL | : [u32; (i8::MAX as i8 + 1u8) as usize] | ^^^ expected `i8`, found `u8` -error[E0277]: cannot add `u8` to `i8` in const contexts +error[E0277]: cannot add `u8` to `i8` --> $DIR/const-eval-overflow-4b.rs:9:28 | LL | : [u32; (i8::MAX as i8 + 1u8) as usize] | ^ no implementation for `i8 + u8` | - = help: the trait `~const Add` is not implemented for `i8` + = help: the trait `Add` is not implemented for `i8` = help: the following other types implement trait `Add`: <&'a i8 as Add> <&i8 as Add<&i8>> diff --git a/tests/ui/consts/const-eval/const_raw_ptr_ops.rs b/tests/ui/consts/const-eval/const_raw_ptr_ops.rs index cd7c980077533..432a05756d305 100644 --- a/tests/ui/consts/const-eval/const_raw_ptr_ops.rs +++ b/tests/ui/consts/const-eval/const_raw_ptr_ops.rs @@ -1,6 +1,6 @@ fn main() {} // unconst and bad, will thus error in miri -const X: bool = unsafe { &1 as *const i32 == &2 as *const i32 }; //~ ERROR can't compare +const X: bool = unsafe { &1 as *const i32 == &2 as *const i32 }; //~ ERROR pointers cannot // unconst and bad, will thus error in miri -const X2: bool = unsafe { 42 as *const i32 == 43 as *const i32 }; //~ ERROR can't compare +const X2: bool = unsafe { 42 as *const i32 == 43 as *const i32 }; //~ ERROR pointers cannot diff --git a/tests/ui/consts/const-eval/const_raw_ptr_ops.stderr b/tests/ui/consts/const-eval/const_raw_ptr_ops.stderr index 12244450e7f8f..1f5bca273d3b0 100644 --- a/tests/ui/consts/const-eval/const_raw_ptr_ops.stderr +++ b/tests/ui/consts/const-eval/const_raw_ptr_ops.stderr @@ -1,29 +1,18 @@ -error[E0277]: can't compare `*const i32` with `_` in const contexts - --> $DIR/const_raw_ptr_ops.rs:4:43 +error: pointers cannot be reliably compared during const eval + --> $DIR/const_raw_ptr_ops.rs:4:26 | LL | const X: bool = unsafe { &1 as *const i32 == &2 as *const i32 }; - | ^^ no implementation for `*const i32 == _` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = help: the trait `~const PartialEq<_>` is not implemented for `*const i32` -note: the trait `PartialEq<_>` is implemented for `*const i32`, but that implementation is not `const` - --> $DIR/const_raw_ptr_ops.rs:4:43 - | -LL | const X: bool = unsafe { &1 as *const i32 == &2 as *const i32 }; - | ^^ + = note: see issue #53020 for more information -error[E0277]: can't compare `*const i32` with `_` in const contexts - --> $DIR/const_raw_ptr_ops.rs:6:44 +error: pointers cannot be reliably compared during const eval + --> $DIR/const_raw_ptr_ops.rs:6:27 | LL | const X2: bool = unsafe { 42 as *const i32 == 43 as *const i32 }; - | ^^ no implementation for `*const i32 == _` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = help: the trait `~const PartialEq<_>` is not implemented for `*const i32` -note: the trait `PartialEq<_>` is implemented for `*const i32`, but that implementation is not `const` - --> $DIR/const_raw_ptr_ops.rs:6:44 - | -LL | const X2: bool = unsafe { 42 as *const i32 == 43 as *const i32 }; - | ^^ + = note: see issue #53020 for more information error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/consts/const-eval/ub-slice-get-unchecked.rs b/tests/ui/consts/const-eval/ub-slice-get-unchecked.rs index d9a74b4f3e24c..ebc5543b380a5 100644 --- a/tests/ui/consts/const-eval/ub-slice-get-unchecked.rs +++ b/tests/ui/consts/const-eval/ub-slice-get-unchecked.rs @@ -1,3 +1,5 @@ +// known-bug: #110395 + #![feature(const_slice_index)] const A: [(); 5] = [(), (), (), (), ()]; diff --git a/tests/ui/consts/const-eval/ub-slice-get-unchecked.stderr b/tests/ui/consts/const-eval/ub-slice-get-unchecked.stderr index 775e475dfeb41..403fb5e09404d 100644 --- a/tests/ui/consts/const-eval/ub-slice-get-unchecked.stderr +++ b/tests/ui/consts/const-eval/ub-slice-get-unchecked.stderr @@ -1,18 +1,11 @@ -error[E0080]: evaluation of constant value failed - --> $SRC_DIR/core/src/slice/index.rs:LL:COL - | - = note: overflow executing `unchecked_sub` - | -note: inside ` as SliceIndex<[()]>>::get_unchecked` - --> $SRC_DIR/core/src/slice/index.rs:LL:COL -note: inside `core::slice::::get_unchecked::>` - --> $SRC_DIR/core/src/slice/mod.rs:LL:COL -note: inside `B` - --> $DIR/ub-slice-get-unchecked.rs:7:27 +error[E0015]: cannot call non-const fn `core::slice::::get_unchecked::>` in constants + --> $DIR/ub-slice-get-unchecked.rs:9:29 | LL | const B: &[()] = unsafe { A.get_unchecked(3..1) }; - | ^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^ + | + = note: calls in constants are limited to constant functions, tuple structs and tuple variants error: aborting due to previous error -For more information about this error, try `rustc --explain E0080`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/const-float-classify.rs b/tests/ui/consts/const-float-classify.rs index 74238d0dd9231..3a5d5bb46e912 100644 --- a/tests/ui/consts/const-float-classify.rs +++ b/tests/ui/consts/const-float-classify.rs @@ -8,11 +8,33 @@ // Don't promote const fn nop(x: T) -> T { x } +// FIXME(const-hack): replace with PartialEq +#[const_trait] +trait MyEq { + fn eq(self, b: T) -> bool; +} + +impl const MyEq for bool { + fn eq(self, b: bool) -> bool { + self == b + } +} + +impl const MyEq for bool { + fn eq(self, _: NonDet) -> bool { + true + } +} + +const fn eq, B>(x: A, y: B) -> bool { + x.eq(y) +} + macro_rules! const_assert { ($a:expr, $b:expr) => { { - const _: () = assert!($a == $b); - assert_eq!(nop($a), nop($b)); + const _: () = assert!(eq($a, $b)); + assert!(eq(nop($a), nop($b))); } }; } @@ -47,15 +69,6 @@ macro_rules! suite_inner { #[derive(Debug)] struct NonDet; -impl const PartialEq for bool { - fn eq(&self, _: &NonDet) -> bool { - true - } - fn ne(&self, _: &NonDet) -> bool { - false - } -} - // The result of the `is_sign` methods are not checked for correctness, since LLVM does not // guarantee anything about the signedness of NaNs. See // https://github.com/rust-lang/rust/issues/55131. diff --git a/tests/ui/consts/const-fn-error.rs b/tests/ui/consts/const-fn-error.rs index dabbd58dbe0ac..50b7ce1f8c01d 100644 --- a/tests/ui/consts/const-fn-error.rs +++ b/tests/ui/consts/const-fn-error.rs @@ -7,7 +7,6 @@ const fn f(x: usize) -> usize { //~| ERROR `for` is not allowed in a `const fn` //~| ERROR mutable references are not allowed in constant functions //~| ERROR cannot call non-const fn - //~| ERROR the trait bound sum += i; } sum diff --git a/tests/ui/consts/const-fn-error.stderr b/tests/ui/consts/const-fn-error.stderr index 73d235d6aec5f..f735b3d53ce43 100644 --- a/tests/ui/consts/const-fn-error.stderr +++ b/tests/ui/consts/const-fn-error.stderr @@ -5,7 +5,7 @@ LL | / for i in 0..x { LL | | LL | | LL | | -... | +LL | | LL | | sum += i; LL | | } | |_____^ @@ -33,19 +33,6 @@ LL | for i in 0..x { = note: see issue #57349 for more information = help: add `#![feature(const_mut_refs)]` to the crate attributes to enable -error[E0277]: the trait bound `std::ops::Range: Iterator` is not satisfied - --> $DIR/const-fn-error.rs:5:14 - | -LL | for i in 0..x { - | ^^^^ `std::ops::Range` is not an iterator - | - = help: the trait `~const Iterator` is not implemented for `std::ops::Range` -note: the trait `Iterator` is implemented for `std::ops::Range`, but that implementation is not `const` - --> $DIR/const-fn-error.rs:5:14 - | -LL | for i in 0..x { - | ^^^^ - error[E0015]: cannot call non-const fn ` as Iterator>::next` in constant functions --> $DIR/const-fn-error.rs:5:14 | @@ -55,7 +42,7 @@ LL | for i in 0..x { = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable -error: aborting due to 5 previous errors +error: aborting due to 4 previous errors -Some errors have detailed explanations: E0015, E0277, E0658. +Some errors have detailed explanations: E0015, E0658. For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/const-for.rs b/tests/ui/consts/const-for.rs index ff9c977f79481..8db2485355833 100644 --- a/tests/ui/consts/const-for.rs +++ b/tests/ui/consts/const-for.rs @@ -5,7 +5,6 @@ const _: () = { for _ in 0..5 {} //~^ error: cannot call //~| error: cannot convert - //~| error: the trait bound }; fn main() {} diff --git a/tests/ui/consts/const-for.stderr b/tests/ui/consts/const-for.stderr index 64f2f603b943b..3fb9787c0d868 100644 --- a/tests/ui/consts/const-for.stderr +++ b/tests/ui/consts/const-for.stderr @@ -9,19 +9,6 @@ note: impl defined here, but it is not `const` = note: calls in constants are limited to constant functions, tuple structs and tuple variants = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable -error[E0277]: the trait bound `std::ops::Range: Iterator` is not satisfied - --> $DIR/const-for.rs:5:14 - | -LL | for _ in 0..5 {} - | ^^^^ `std::ops::Range` is not an iterator - | - = help: the trait `~const Iterator` is not implemented for `std::ops::Range` -note: the trait `Iterator` is implemented for `std::ops::Range`, but that implementation is not `const` - --> $DIR/const-for.rs:5:14 - | -LL | for _ in 0..5 {} - | ^^^^ - error[E0015]: cannot call non-const fn ` as Iterator>::next` in constants --> $DIR/const-for.rs:5:14 | @@ -31,7 +18,6 @@ LL | for _ in 0..5 {} = note: calls in constants are limited to constant functions, tuple structs and tuple variants = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors -Some errors have detailed explanations: E0015, E0277. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/const-try.rs b/tests/ui/consts/const-try.rs index e199fd9ff8a1a..6b7ba8f1e32b4 100644 --- a/tests/ui/consts/const-try.rs +++ b/tests/ui/consts/const-try.rs @@ -1,4 +1,4 @@ -// check-pass +// known-bug: #110395 // Demonstrates what's needed to make use of `?` in const contexts. diff --git a/tests/ui/consts/const-try.stderr b/tests/ui/consts/const-try.stderr new file mode 100644 index 0000000000000..37014f9b83f69 --- /dev/null +++ b/tests/ui/consts/const-try.stderr @@ -0,0 +1,20 @@ +error: const `impl` for trait `FromResidual` which is not marked with `#[const_trait]` + --> $DIR/const-try.rs:15:12 + | +LL | impl const FromResidual for TryMe { + | ^^^^^^^^^^^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: const `impl` for trait `Try` which is not marked with `#[const_trait]` + --> $DIR/const-try.rs:21:12 + | +LL | impl const Try for TryMe { + | ^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: aborting due to 2 previous errors + diff --git a/tests/ui/consts/const_cmp_type_id.rs b/tests/ui/consts/const_cmp_type_id.rs index f10d1c24f7ded..19cee2022ac07 100644 --- a/tests/ui/consts/const_cmp_type_id.rs +++ b/tests/ui/consts/const_cmp_type_id.rs @@ -1,4 +1,4 @@ -// run-pass +// known-bug: #110395 #![feature(const_type_id)] #![feature(const_trait_impl)] diff --git a/tests/ui/consts/const_cmp_type_id.stderr b/tests/ui/consts/const_cmp_type_id.stderr new file mode 100644 index 0000000000000..319d2b924a88c --- /dev/null +++ b/tests/ui/consts/const_cmp_type_id.stderr @@ -0,0 +1,76 @@ +error[E0277]: can't compare `TypeId` with `TypeId` in const contexts + --> $DIR/const_cmp_type_id.rs:8:13 + | +LL | assert!(TypeId::of::() == TypeId::of::()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `TypeId == TypeId` + | + = help: the trait `~const PartialEq` is not implemented for `TypeId` +note: the trait `PartialEq` is implemented for `TypeId`, but that implementation is not `const` + --> $DIR/const_cmp_type_id.rs:8:13 + | +LL | assert!(TypeId::of::() == TypeId::of::()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/const_cmp_type_id.rs:8:13 + | +LL | assert!(TypeId::of::() == TypeId::of::()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: impl defined here, but it is not `const` + --> $SRC_DIR/core/src/any.rs:LL:COL + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: can't compare `TypeId` with `TypeId` in const contexts + --> $DIR/const_cmp_type_id.rs:9:13 + | +LL | assert!(TypeId::of::<()>() != TypeId::of::()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `TypeId == TypeId` + | + = help: the trait `~const PartialEq` is not implemented for `TypeId` +note: the trait `PartialEq` is implemented for `TypeId`, but that implementation is not `const` + --> $DIR/const_cmp_type_id.rs:9:13 + | +LL | assert!(TypeId::of::<()>() != TypeId::of::()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/const_cmp_type_id.rs:9:13 + | +LL | assert!(TypeId::of::<()>() != TypeId::of::()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: impl defined here, but it is not `const` + --> $SRC_DIR/core/src/any.rs:LL:COL + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: can't compare `TypeId` with `TypeId` in const contexts + --> $DIR/const_cmp_type_id.rs:10:22 + | +LL | const _A: bool = TypeId::of::() < TypeId::of::(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `TypeId < TypeId` and `TypeId > TypeId` + | + = help: the trait `~const PartialOrd` is not implemented for `TypeId` +note: the trait `PartialOrd` is implemented for `TypeId`, but that implementation is not `const` + --> $DIR/const_cmp_type_id.rs:10:22 + | +LL | const _A: bool = TypeId::of::() < TypeId::of::(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error[E0015]: cannot call non-const operator in constants + --> $DIR/const_cmp_type_id.rs:10:22 + | +LL | const _A: bool = TypeId::of::() < TypeId::of::(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: impl defined here, but it is not `const` + --> $SRC_DIR/core/src/any.rs:LL:COL + = note: calls in constants are limited to constant functions, tuple structs and tuple variants + = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 6 previous errors + +Some errors have detailed explanations: E0015, E0277. +For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/fn_trait_refs.rs b/tests/ui/consts/fn_trait_refs.rs index b507492970ab3..be11ac7264a1a 100644 --- a/tests/ui/consts/fn_trait_refs.rs +++ b/tests/ui/consts/fn_trait_refs.rs @@ -1,4 +1,4 @@ -// check-pass +// known-bug: #110395 #![feature(const_fn_trait_ref_impls)] #![feature(fn_traits)] diff --git a/tests/ui/consts/fn_trait_refs.stderr b/tests/ui/consts/fn_trait_refs.stderr new file mode 100644 index 0000000000000..bfebf66701bd9 --- /dev/null +++ b/tests/ui/consts/fn_trait_refs.stderr @@ -0,0 +1,15 @@ +error[E0635]: unknown feature `const_fn_trait_ref_impls` + --> $DIR/fn_trait_refs.rs:3:12 + | +LL | #![feature(const_fn_trait_ref_impls)] + | ^^^^^^^^^^^^^^^^^^^^^^^^ + +error[E0635]: unknown feature `const_cmp` + --> $DIR/fn_trait_refs.rs:8:12 + | +LL | #![feature(const_cmp)] + | ^^^^^^^^^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0635`. diff --git a/tests/ui/consts/issue-25826.rs b/tests/ui/consts/issue-25826.rs index c340c30a113b5..f5ed5aeedc39c 100644 --- a/tests/ui/consts/issue-25826.rs +++ b/tests/ui/consts/issue-25826.rs @@ -1,6 +1,6 @@ fn id(t: T) -> T { t } fn main() { const A: bool = unsafe { id:: as *const () < id:: as *const () }; - //~^ ERROR can't compare + //~^ ERROR pointers cannot println!("{}", A); } diff --git a/tests/ui/consts/issue-25826.stderr b/tests/ui/consts/issue-25826.stderr index 905c5ee6eb4a0..780edd2149fe1 100644 --- a/tests/ui/consts/issue-25826.stderr +++ b/tests/ui/consts/issue-25826.stderr @@ -1,16 +1,10 @@ -error[E0277]: can't compare `*const ()` with `*const ()` in const contexts - --> $DIR/issue-25826.rs:3:52 +error: pointers cannot be reliably compared during const eval + --> $DIR/issue-25826.rs:3:30 | LL | const A: bool = unsafe { id:: as *const () < id:: as *const () }; - | ^ no implementation for `*const () < *const ()` and `*const () > *const ()` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = help: the trait `~const PartialOrd` is not implemented for `*const ()` -note: the trait `PartialOrd` is implemented for `*const ()`, but that implementation is not `const` - --> $DIR/issue-25826.rs:3:52 - | -LL | const A: bool = unsafe { id:: as *const () < id:: as *const () }; - | ^ + = note: see issue #53020 for more information error: aborting due to previous error -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/consts/issue-73976-monomorphic.rs b/tests/ui/consts/issue-73976-monomorphic.rs index addcc1eaab60b..a3b9510036d0f 100644 --- a/tests/ui/consts/issue-73976-monomorphic.rs +++ b/tests/ui/consts/issue-73976-monomorphic.rs @@ -1,4 +1,4 @@ -// check-pass +// known-bug: #110395 // // This test is complement to the test in issue-73976-polymorphic.rs. // In that test we ensure that polymorphic use of type_id and type_name in patterns diff --git a/tests/ui/consts/issue-73976-monomorphic.stderr b/tests/ui/consts/issue-73976-monomorphic.stderr new file mode 100644 index 0000000000000..95ab78b1b23b3 --- /dev/null +++ b/tests/ui/consts/issue-73976-monomorphic.stderr @@ -0,0 +1,28 @@ +error[E0277]: can't compare `TypeId` with `TypeId` in const contexts + --> $DIR/issue-73976-monomorphic.rs:21:5 + | +LL | GetTypeId::::VALUE == GetTypeId::::VALUE + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `TypeId == TypeId` + | + = help: the trait `~const PartialEq` is not implemented for `TypeId` +note: the trait `PartialEq` is implemented for `TypeId`, but that implementation is not `const` + --> $DIR/issue-73976-monomorphic.rs:21:5 + | +LL | GetTypeId::::VALUE == GetTypeId::::VALUE + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/issue-73976-monomorphic.rs:21:5 + | +LL | GetTypeId::::VALUE == GetTypeId::::VALUE + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: impl defined here, but it is not `const` + --> $SRC_DIR/core/src/any.rs:LL:COL + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0015, E0277. +For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/issue-94675.rs b/tests/ui/consts/issue-94675.rs index ce21ebdb9ac99..38c8129b8cfd9 100644 --- a/tests/ui/consts/issue-94675.rs +++ b/tests/ui/consts/issue-94675.rs @@ -7,8 +7,9 @@ struct Foo<'a> { impl<'a> Foo<'a> { const fn spam(&mut self, baz: &mut Vec) { self.bar[0] = baz.len(); - //~^ the trait bound `Vec: ~const Index<_>` is not satisfied - //~| the trait bound `Vec: ~const IndexMut` is not satisfied + //~^ ERROR: cannot call + //~| ERROR: cannot call + //~| ERROR: the trait bound } } diff --git a/tests/ui/consts/issue-94675.stderr b/tests/ui/consts/issue-94675.stderr index f4683f7f5361d..b4e5db44e7105 100644 --- a/tests/ui/consts/issue-94675.stderr +++ b/tests/ui/consts/issue-94675.stderr @@ -1,15 +1,10 @@ -error[E0277]: the trait bound `Vec: ~const Index<_>` is not satisfied - --> $DIR/issue-94675.rs:9:9 +error[E0015]: cannot call non-const fn `Vec::::len` in constant functions + --> $DIR/issue-94675.rs:9:27 | LL | self.bar[0] = baz.len(); - | ^^^^^^^^^^^ vector indices are of type `usize` or ranges of `usize` - | - = help: the trait `~const Index<_>` is not implemented for `Vec` -note: the trait `Index<_>` is implemented for `Vec`, but that implementation is not `const` - --> $DIR/issue-94675.rs:9:9 + | ^^^^^ | -LL | self.bar[0] = baz.len(); - | ^^^^^^^^^^^ + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants error[E0277]: the trait bound `Vec: ~const IndexMut` is not satisfied --> $DIR/issue-94675.rs:9:9 @@ -24,6 +19,17 @@ note: the trait `IndexMut` is implemented for `Vec`, but that impl LL | self.bar[0] = baz.len(); | ^^^^^^^^^^^ -error: aborting due to 2 previous errors +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/issue-94675.rs:9:9 + | +LL | self.bar[0] = baz.len(); + | ^^^^^^^^^^^ + | +note: impl defined here, but it is not `const` + --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + +error: aborting due to 3 previous errors -For more information about this error, try `rustc --explain E0277`. +Some errors have detailed explanations: E0015, E0277. +For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/min_const_fn/cmp_fn_pointers.rs b/tests/ui/consts/min_const_fn/cmp_fn_pointers.rs index 9a2775688c6fa..c5990a7f5155f 100644 --- a/tests/ui/consts/min_const_fn/cmp_fn_pointers.rs +++ b/tests/ui/consts/min_const_fn/cmp_fn_pointers.rs @@ -1,6 +1,6 @@ const fn cmp(x: fn(), y: fn()) -> bool { unsafe { x == y } - //~^ ERROR can't compare + //~^ ERROR pointers cannot } fn main() {} diff --git a/tests/ui/consts/min_const_fn/cmp_fn_pointers.stderr b/tests/ui/consts/min_const_fn/cmp_fn_pointers.stderr index 8a1b20a334567..3845068d8411c 100644 --- a/tests/ui/consts/min_const_fn/cmp_fn_pointers.stderr +++ b/tests/ui/consts/min_const_fn/cmp_fn_pointers.stderr @@ -1,16 +1,10 @@ -error[E0277]: can't compare `fn()` with `_` in const contexts - --> $DIR/cmp_fn_pointers.rs:2:16 +error: pointers cannot be reliably compared during const eval + --> $DIR/cmp_fn_pointers.rs:2:14 | LL | unsafe { x == y } - | ^^ no implementation for `fn() == _` + | ^^^^^^ | - = help: the trait `~const PartialEq<_>` is not implemented for `fn()` -note: the trait `PartialEq<_>` is implemented for `fn()`, but that implementation is not `const` - --> $DIR/cmp_fn_pointers.rs:2:16 - | -LL | unsafe { x == y } - | ^^ + = note: see issue #53020 for more information error: aborting due to previous error -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/consts/promoted_const_call.rs b/tests/ui/consts/promoted_const_call.rs index 30ae730535ca6..dae6cafaebb34 100644 --- a/tests/ui/consts/promoted_const_call.rs +++ b/tests/ui/consts/promoted_const_call.rs @@ -1,7 +1,9 @@ #![feature(const_mut_refs)] #![feature(const_trait_impl)] + struct Panic; impl const Drop for Panic { fn drop(&mut self) { panic!(); } } + pub const fn id(x: T) -> T { x } pub const C: () = { let _: &'static _ = &id(&Panic); diff --git a/tests/ui/consts/promoted_const_call.stderr b/tests/ui/consts/promoted_const_call.stderr index 83cc16f6f94d6..1cbd8cbe6999c 100644 --- a/tests/ui/consts/promoted_const_call.stderr +++ b/tests/ui/consts/promoted_const_call.stderr @@ -1,5 +1,5 @@ error[E0716]: temporary value dropped while borrowed - --> $DIR/promoted_const_call.rs:7:26 + --> $DIR/promoted_const_call.rs:9:26 | LL | let _: &'static _ = &id(&Panic); | ---------- ^^^^^^^^^^ creates a temporary value which is freed while still in use @@ -10,7 +10,7 @@ LL | }; | - temporary value is freed at the end of this statement error[E0716]: temporary value dropped while borrowed - --> $DIR/promoted_const_call.rs:7:30 + --> $DIR/promoted_const_call.rs:9:30 | LL | let _: &'static _ = &id(&Panic); | ---------- ^^^^^ - temporary value is freed at the end of this statement @@ -19,7 +19,7 @@ LL | let _: &'static _ = &id(&Panic); | type annotation requires that borrow lasts for `'static` error[E0716]: temporary value dropped while borrowed - --> $DIR/promoted_const_call.rs:13:26 + --> $DIR/promoted_const_call.rs:15:26 | LL | let _: &'static _ = &id(&Panic); | ---------- ^^^^^^^^^^ creates a temporary value which is freed while still in use @@ -30,7 +30,7 @@ LL | } | - temporary value is freed at the end of this statement error[E0716]: temporary value dropped while borrowed - --> $DIR/promoted_const_call.rs:13:30 + --> $DIR/promoted_const_call.rs:15:30 | LL | let _: &'static _ = &id(&Panic); | ---------- ^^^^^ - temporary value is freed at the end of this statement @@ -39,7 +39,7 @@ LL | let _: &'static _ = &id(&Panic); | type annotation requires that borrow lasts for `'static` error[E0716]: temporary value dropped while borrowed - --> $DIR/promoted_const_call.rs:16:26 + --> $DIR/promoted_const_call.rs:18:26 | LL | let _: &'static _ = &&(Panic, 0).1; | ---------- ^^^^^^^^^^^^^ creates a temporary value which is freed while still in use @@ -50,7 +50,7 @@ LL | } | - temporary value is freed at the end of this statement error[E0716]: temporary value dropped while borrowed - --> $DIR/promoted_const_call.rs:16:27 + --> $DIR/promoted_const_call.rs:18:27 | LL | let _: &'static _ = &&(Panic, 0).1; | ---------- ^^^^^^^^^^ creates a temporary value which is freed while still in use diff --git a/tests/ui/consts/rustc-impl-const-stability.rs b/tests/ui/consts/rustc-impl-const-stability.rs index 0c18efa0a0235..a1a741e80e55e 100644 --- a/tests/ui/consts/rustc-impl-const-stability.rs +++ b/tests/ui/consts/rustc-impl-const-stability.rs @@ -1,4 +1,4 @@ -// check-pass +// known-bug: #110395 #![crate_type = "lib"] #![feature(staged_api)] diff --git a/tests/ui/consts/rustc-impl-const-stability.stderr b/tests/ui/consts/rustc-impl-const-stability.stderr new file mode 100644 index 0000000000000..e6930da71ec78 --- /dev/null +++ b/tests/ui/consts/rustc-impl-const-stability.stderr @@ -0,0 +1,11 @@ +error: const `impl` for trait `Default` which is not marked with `#[const_trait]` + --> $DIR/rustc-impl-const-stability.rs:15:12 + | +LL | impl const Default for Data { + | ^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: aborting due to previous error + diff --git a/tests/ui/consts/try-operator.rs b/tests/ui/consts/try-operator.rs index fe43b132cbd7f..ed69f492fb969 100644 --- a/tests/ui/consts/try-operator.rs +++ b/tests/ui/consts/try-operator.rs @@ -1,4 +1,4 @@ -// run-pass +// known-bug: #110395 #![feature(try_trait_v2)] #![feature(const_trait_impl)] diff --git a/tests/ui/consts/try-operator.stderr b/tests/ui/consts/try-operator.stderr new file mode 100644 index 0000000000000..f6a651c5e663c --- /dev/null +++ b/tests/ui/consts/try-operator.stderr @@ -0,0 +1,9 @@ +error[E0635]: unknown feature `const_convert` + --> $DIR/try-operator.rs:6:12 + | +LL | #![feature(const_convert)] + | ^^^^^^^^^^^^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0635`. diff --git a/tests/ui/did_you_mean/issue-49746-unicode-confusable-in-float-literal-expt.stderr b/tests/ui/did_you_mean/issue-49746-unicode-confusable-in-float-literal-expt.stderr index 81f3f26943255..26986684f0c0a 100644 --- a/tests/ui/did_you_mean/issue-49746-unicode-confusable-in-float-literal-expt.stderr +++ b/tests/ui/did_you_mean/issue-49746-unicode-confusable-in-float-literal-expt.stderr @@ -15,13 +15,13 @@ help: Unicode character '−' (Minus Sign) looks like '-' (Minus/Hyphen), but it LL | const UNIVERSAL_GRAVITATIONAL_CONSTANT: f64 = 6.674e-11; // m³⋅kg⁻¹⋅s⁻² | ~ -error[E0277]: cannot subtract `{integer}` from `{float}` in const contexts +error[E0277]: cannot subtract `{integer}` from `{float}` --> $DIR/issue-49746-unicode-confusable-in-float-literal-expt.rs:1:53 | LL | const UNIVERSAL_GRAVITATIONAL_CONSTANT: f64 = 6.674e−11; // m³⋅kg⁻¹⋅s⁻² | ^ no implementation for `{float} - {integer}` | - = help: the trait `~const Sub<{integer}>` is not implemented for `{float}` + = help: the trait `Sub<{integer}>` is not implemented for `{float}` = help: the following other types implement trait `Sub`: <&'a f32 as Sub> <&'a f64 as Sub> diff --git a/tests/ui/issues/issue-25901.rs b/tests/ui/issues/issue-25901.rs index 1f7b341a97efc..85e12463a903d 100644 --- a/tests/ui/issues/issue-25901.rs +++ b/tests/ui/issues/issue-25901.rs @@ -2,7 +2,7 @@ struct A; struct B; static S: &'static B = &A; -//~^ ERROR the trait bound +//~^ ERROR cannot perform deref coercion use std::ops::Deref; diff --git a/tests/ui/issues/issue-25901.stderr b/tests/ui/issues/issue-25901.stderr index b9cac32229a1e..1427e43854f57 100644 --- a/tests/ui/issues/issue-25901.stderr +++ b/tests/ui/issues/issue-25901.stderr @@ -1,15 +1,24 @@ -error[E0277]: the trait bound `A: Deref` is not satisfied +error[E0015]: cannot perform deref coercion on `A` in statics --> $DIR/issue-25901.rs:4:24 | LL | static S: &'static B = &A; - | ^^ the trait `~const Deref` is not implemented for `A` + | ^^ | -note: the trait `Deref` is implemented for `A`, but that implementation is not `const` - --> $DIR/issue-25901.rs:4:24 + = note: attempting to deref into `B` +note: deref defined here + --> $DIR/issue-25901.rs:10:5 | -LL | static S: &'static B = &A; - | ^^ +LL | type Target = B; + | ^^^^^^^^^^^ +note: impl defined here, but it is not `const` + --> $DIR/issue-25901.rs:9:1 + | +LL | impl Deref for A { + | ^^^^^^^^^^^^^^^^ + = note: calls in statics are limited to constant functions, tuple structs and tuple variants + = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable + = note: consider wrapping this expression in `Lazy::new(|| ...)` from the `once_cell` crate: https://crates.io/crates/once_cell error: aborting due to previous error -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/issues/issue-50582.stderr b/tests/ui/issues/issue-50582.stderr index 53ecc6112ffee..3d527eb6b4e4a 100644 --- a/tests/ui/issues/issue-50582.stderr +++ b/tests/ui/issues/issue-50582.stderr @@ -7,13 +7,13 @@ LL | Vec::<[(); 1 + for x in 0..1 {}]>::new(); = note: see issue #87575 for more information = help: add `#![feature(const_for)]` to the crate attributes to enable -error[E0277]: cannot add `()` to `{integer}` in const contexts +error[E0277]: cannot add `()` to `{integer}` --> $DIR/issue-50582.rs:2:18 | LL | Vec::<[(); 1 + for x in 0..1 {}]>::new(); | ^ no implementation for `{integer} + ()` | - = help: the trait `~const Add<()>` is not implemented for `{integer}` + = help: the trait `Add<()>` is not implemented for `{integer}` = help: the following other types implement trait `Add`: <&'a f32 as Add> <&'a f64 as Add> diff --git a/tests/ui/never_type/issue-52443.rs b/tests/ui/never_type/issue-52443.rs index 4669d7c1a35d6..0498a8a162590 100644 --- a/tests/ui/never_type/issue-52443.rs +++ b/tests/ui/never_type/issue-52443.rs @@ -11,5 +11,4 @@ fn main() { //~| ERROR cannot convert //~| ERROR mutable references //~| ERROR cannot call - //~| ERROR the trait bound } diff --git a/tests/ui/never_type/issue-52443.stderr b/tests/ui/never_type/issue-52443.stderr index 1233bdc5d1f8c..99dfce8690343 100644 --- a/tests/ui/never_type/issue-52443.stderr +++ b/tests/ui/never_type/issue-52443.stderr @@ -58,19 +58,6 @@ LL | [(); { for _ in 0usize.. {}; 0}]; = note: see issue #57349 for more information = help: add `#![feature(const_mut_refs)]` to the crate attributes to enable -error[E0277]: the trait bound `RangeFrom: Iterator` is not satisfied - --> $DIR/issue-52443.rs:9:21 - | -LL | [(); { for _ in 0usize.. {}; 0}]; - | ^^^^^^^^ `RangeFrom` is not an iterator - | - = help: the trait `~const Iterator` is not implemented for `RangeFrom` -note: the trait `Iterator` is implemented for `RangeFrom`, but that implementation is not `const` - --> $DIR/issue-52443.rs:9:21 - | -LL | [(); { for _ in 0usize.. {}; 0}]; - | ^^^^^^^^ - error[E0015]: cannot call non-const fn ` as Iterator>::next` in constants --> $DIR/issue-52443.rs:9:21 | @@ -80,7 +67,7 @@ LL | [(); { for _ in 0usize.. {}; 0}]; = note: calls in constants are limited to constant functions, tuple structs and tuple variants = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable -error: aborting due to 7 previous errors; 1 warning emitted +error: aborting due to 6 previous errors; 1 warning emitted -Some errors have detailed explanations: E0015, E0277, E0308, E0658. +Some errors have detailed explanations: E0015, E0308, E0658. For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/rfc-2632-const-trait-impl/assoc-type.rs b/tests/ui/rfc-2632-const-trait-impl/assoc-type.rs index 7d9dae52cf10e..96790a87311dd 100644 --- a/tests/ui/rfc-2632-const-trait-impl/assoc-type.rs +++ b/tests/ui/rfc-2632-const-trait-impl/assoc-type.rs @@ -1,3 +1,5 @@ +// known-bug: #110395 + #![feature(const_trait_impl)] struct NonConstAdd(i32); @@ -17,7 +19,6 @@ trait Foo { impl const Foo for NonConstAdd { type Bar = NonConstAdd; - //~^ ERROR: cannot add `NonConstAdd` to `NonConstAdd` in const contexts } #[const_trait] diff --git a/tests/ui/rfc-2632-const-trait-impl/assoc-type.stderr b/tests/ui/rfc-2632-const-trait-impl/assoc-type.stderr index 89177b0f1ac1c..0cffae1da8d97 100644 --- a/tests/ui/rfc-2632-const-trait-impl/assoc-type.stderr +++ b/tests/ui/rfc-2632-const-trait-impl/assoc-type.stderr @@ -1,21 +1,8 @@ -error[E0277]: cannot add `NonConstAdd` to `NonConstAdd` in const contexts - --> $DIR/assoc-type.rs:19:16 - | -LL | type Bar = NonConstAdd; - | ^^^^^^^^^^^ no implementation for `NonConstAdd + NonConstAdd` - | - = help: the trait `~const Add` is not implemented for `NonConstAdd` -note: the trait `Add` is implemented for `NonConstAdd`, but that implementation is not `const` - --> $DIR/assoc-type.rs:19:16 - | -LL | type Bar = NonConstAdd; - | ^^^^^^^^^^^ -note: required by a bound in `Foo::Bar` - --> $DIR/assoc-type.rs:15:15 +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/assoc-type.rs:17:22 | LL | type Bar: ~const std::ops::Add; - | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `Foo::Bar` + | ^^^^^^^^^^^^^ error: aborting due to previous error -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/rfc-2632-const-trait-impl/call-const-trait-method-pass.rs b/tests/ui/rfc-2632-const-trait-impl/call-const-trait-method-pass.rs index b64161b6aa014..ae0c2e6bcfa41 100644 --- a/tests/ui/rfc-2632-const-trait-impl/call-const-trait-method-pass.rs +++ b/tests/ui/rfc-2632-const-trait-impl/call-const-trait-method-pass.rs @@ -1,4 +1,4 @@ -// run-pass +// known-bug: #110395 #![feature(const_trait_impl)] diff --git a/tests/ui/rfc-2632-const-trait-impl/call-const-trait-method-pass.stderr b/tests/ui/rfc-2632-const-trait-impl/call-const-trait-method-pass.stderr new file mode 100644 index 0000000000000..ff53eea1110c0 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/call-const-trait-method-pass.stderr @@ -0,0 +1,20 @@ +error: const `impl` for trait `Add` which is not marked with `#[const_trait]` + --> $DIR/call-const-trait-method-pass.rs:7:12 + | +LL | impl const std::ops::Add for Int { + | ^^^^^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: const `impl` for trait `PartialEq` which is not marked with `#[const_trait]` + --> $DIR/call-const-trait-method-pass.rs:15:12 + | +LL | impl const PartialEq for Int { + | ^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: aborting due to 2 previous errors + diff --git a/tests/ui/rfc-2632-const-trait-impl/call-generic-in-impl.rs b/tests/ui/rfc-2632-const-trait-impl/call-generic-in-impl.rs index 50c46579086c6..5120e6bfb4117 100644 --- a/tests/ui/rfc-2632-const-trait-impl/call-generic-in-impl.rs +++ b/tests/ui/rfc-2632-const-trait-impl/call-generic-in-impl.rs @@ -1,4 +1,4 @@ -// check-pass +// known-bug: #110395 #![feature(const_trait_impl)] #[const_trait] diff --git a/tests/ui/rfc-2632-const-trait-impl/call-generic-in-impl.stderr b/tests/ui/rfc-2632-const-trait-impl/call-generic-in-impl.stderr new file mode 100644 index 0000000000000..02d53cc78ee56 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/call-generic-in-impl.stderr @@ -0,0 +1,8 @@ +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-in-impl.rs:9:16 + | +LL | impl const MyPartialEq for T { + | ^^^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-chain.rs b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-chain.rs index b00ff1f2fac2a..3febb328a83ca 100644 --- a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-chain.rs +++ b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-chain.rs @@ -1,6 +1,6 @@ //! Basic test for calling methods on generic type parameters in `const fn`. -// check-pass +// known-bug: #110395 #![feature(const_trait_impl)] diff --git a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-chain.stderr b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-chain.stderr new file mode 100644 index 0000000000000..529a472e0bda5 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-chain.stderr @@ -0,0 +1,23 @@ +error: const `impl` for trait `PartialEq` which is not marked with `#[const_trait]` + --> $DIR/call-generic-method-chain.rs:9:12 + | +LL | impl const PartialEq for S { + | ^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-method-chain.rs:18:32 + | +LL | const fn equals_self(t: &T) -> bool { + | ^^^^^^^^^ + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-method-chain.rs:22:40 + | +LL | const fn equals_self_wrapper(t: &T) -> bool { + | ^^^^^^^^^ + +error: aborting due to 3 previous errors + diff --git a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-dup-bound.rs b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-dup-bound.rs index c8ded0fa7ea32..e618160d3b6f0 100644 --- a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-dup-bound.rs +++ b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-dup-bound.rs @@ -1,4 +1,4 @@ -// check-pass +// known-bug: #110395 #![feature(const_trait_impl)] diff --git a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-dup-bound.stderr b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-dup-bound.stderr new file mode 100644 index 0000000000000..bdc6ccc8aec23 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-dup-bound.stderr @@ -0,0 +1,23 @@ +error: const `impl` for trait `PartialEq` which is not marked with `#[const_trait]` + --> $DIR/call-generic-method-dup-bound.rs:7:12 + | +LL | impl const PartialEq for S { + | ^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-method-dup-bound.rs:18:44 + | +LL | const fn equals_self(t: &T) -> bool { + | ^^^^^^^^^ + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-method-dup-bound.rs:25:37 + | +LL | const fn equals_self2(t: &T) -> bool { + | ^^^^^^^^^ + +error: aborting due to 3 previous errors + diff --git a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-fail.rs b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-fail.rs index 2bc5ee512c52f..fe1abbf420715 100644 --- a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-fail.rs +++ b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-fail.rs @@ -1,8 +1,9 @@ +// known-bug: #110395 #![feature(const_trait_impl)] pub const fn equals_self(t: &T) -> bool { *t == *t - //~^ ERROR can't compare + // (remove this) ~^ ERROR can't compare } fn main() {} diff --git a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-fail.stderr b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-fail.stderr index 31e6dbdab2258..3963f64ad32b3 100644 --- a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-fail.stderr +++ b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-fail.stderr @@ -1,15 +1,28 @@ -error[E0277]: can't compare `T` with `_` in const contexts - --> $DIR/call-generic-method-fail.rs:4:8 +error[E0277]: can't compare `T` with `T` in const contexts + --> $DIR/call-generic-method-fail.rs:5:5 | LL | *t == *t - | ^^ no implementation for `T == _` + | ^^^^^^^^ no implementation for `T == T` | -note: the trait `PartialEq<_>` is implemented for `T`, but that implementation is not `const` - --> $DIR/call-generic-method-fail.rs:4:8 +note: the trait `PartialEq` is implemented for `T`, but that implementation is not `const` + --> $DIR/call-generic-method-fail.rs:5:5 | LL | *t == *t - | ^^ + | ^^^^^^^^ -error: aborting due to previous error +error[E0015]: cannot call non-const operator in constant functions + --> $DIR/call-generic-method-fail.rs:5:5 + | +LL | *t == *t + | ^^^^^^^^ + | + = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants +help: consider further restricting this bound + | +LL | pub const fn equals_self(t: &T) -> bool { + | ++++++++++++++++++++++++++++ + +error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0277`. +Some errors have detailed explanations: E0015, E0277. +For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-pass.rs b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-pass.rs index 40565d1b76a9c..09f35a277371e 100644 --- a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-pass.rs +++ b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-pass.rs @@ -1,6 +1,6 @@ //! Basic test for calling methods on generic type parameters in `const fn`. -// check-pass +// known-bug: #110395 #![feature(const_trait_impl)] diff --git a/tests/ui/rfc-2632-const-trait-impl/call-generic-method-pass.stderr b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-pass.stderr new file mode 100644 index 0000000000000..7fbe89dba3cb3 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/call-generic-method-pass.stderr @@ -0,0 +1,17 @@ +error: const `impl` for trait `PartialEq` which is not marked with `#[const_trait]` + --> $DIR/call-generic-method-pass.rs:9:12 + | +LL | impl const PartialEq for S { + | ^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/call-generic-method-pass.rs:18:32 + | +LL | const fn equals_self(t: &T) -> bool { + | ^^^^^^^^^ + +error: aborting due to 2 previous errors + diff --git a/tests/ui/rfc-2632-const-trait-impl/const-and-non-const-impl.rs b/tests/ui/rfc-2632-const-trait-impl/const-and-non-const-impl.rs index f66d63da69314..9ba19e800dd65 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-and-non-const-impl.rs +++ b/tests/ui/rfc-2632-const-trait-impl/const-and-non-const-impl.rs @@ -1,9 +1,10 @@ +// known-bug: #110395 + #![feature(const_trait_impl)] pub struct Int(i32); impl const std::ops::Add for i32 { - //~^ ERROR only traits defined in the current crate can be implemented for primitive types type Output = Self; fn add(self, rhs: Self) -> Self { @@ -20,7 +21,6 @@ impl std::ops::Add for Int { } impl const std::ops::Add for Int { - //~^ ERROR conflicting implementations of trait type Output = Self; fn add(self, rhs: Self) -> Self { diff --git a/tests/ui/rfc-2632-const-trait-impl/const-and-non-const-impl.stderr b/tests/ui/rfc-2632-const-trait-impl/const-and-non-const-impl.stderr index 36a09add4d3bb..4f858d61eebaa 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-and-non-const-impl.stderr +++ b/tests/ui/rfc-2632-const-trait-impl/const-and-non-const-impl.stderr @@ -1,25 +1,20 @@ -error[E0117]: only traits defined in the current crate can be implemented for primitive types - --> $DIR/const-and-non-const-impl.rs:5:1 +error: const `impl` for trait `Add` which is not marked with `#[const_trait]` + --> $DIR/const-and-non-const-impl.rs:7:12 | LL | impl const std::ops::Add for i32 { - | ^^^^^^^^^^^-------------^^^^^--- - | | | | - | | | `i32` is not defined in the current crate - | | `i32` is not defined in the current crate - | impl doesn't use only types from inside the current crate + | ^^^^^^^^^^^^^ | - = note: define and implement a trait or new type instead + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change -error[E0119]: conflicting implementations of trait `Add` for type `Int` - --> $DIR/const-and-non-const-impl.rs:22:1 +error: const `impl` for trait `Add` which is not marked with `#[const_trait]` + --> $DIR/const-and-non-const-impl.rs:23:12 | -LL | impl std::ops::Add for Int { - | -------------------------- first implementation here -... LL | impl const std::ops::Add for Int { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Int` + | ^^^^^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change error: aborting due to 2 previous errors -Some errors have detailed explanations: E0117, E0119. -For more information about an error, try `rustc --explain E0117`. diff --git a/tests/ui/rfc-2632-const-trait-impl/const-closure-trait-method-fail.rs b/tests/ui/rfc-2632-const-trait-impl/const-closure-trait-method-fail.rs index b5f19e40c0334..b4cc7a9e17e64 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-closure-trait-method-fail.rs +++ b/tests/ui/rfc-2632-const-trait-impl/const-closure-trait-method-fail.rs @@ -1,3 +1,5 @@ +// known-bug: #110395 + #![feature(const_trait_impl)] #[const_trait] @@ -14,6 +16,5 @@ const fn need_const_closure i32>(x: T) -> i32 { } const _: () = assert!(need_const_closure(Tr::a) == 42); -//~^ ERROR: the trait bound fn main() {} diff --git a/tests/ui/rfc-2632-const-trait-impl/const-closure-trait-method-fail.stderr b/tests/ui/rfc-2632-const-trait-impl/const-closure-trait-method-fail.stderr index ffc24ec6e9207..112416a354343 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-closure-trait-method-fail.stderr +++ b/tests/ui/rfc-2632-const-trait-impl/const-closure-trait-method-fail.stderr @@ -1,11 +1,11 @@ error[E0277]: the trait bound `(): ~const Tr` is not satisfied in `fn(()) -> i32 {<() as Tr>::a}` - --> $DIR/const-closure-trait-method-fail.rs:16:23 + --> $DIR/const-closure-trait-method-fail.rs:18:23 | LL | const _: () = assert!(need_const_closure(Tr::a) == 42); | ^^^^^^^^^^^^^^^^^^^^^^^^^ within `fn(()) -> i32 {<() as Tr>::a}`, the trait `~const Tr` is not implemented for `()` | note: the trait `Tr` is implemented for `()`, but that implementation is not `const` - --> $DIR/const-closure-trait-method-fail.rs:16:23 + --> $DIR/const-closure-trait-method-fail.rs:18:23 | LL | const _: () = assert!(need_const_closure(Tr::a) == 42); | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/rfc-2632-const-trait-impl/const-closures.rs b/tests/ui/rfc-2632-const-trait-impl/const-closures.rs index 755d853983949..7c55b51c8f5f0 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-closures.rs +++ b/tests/ui/rfc-2632-const-trait-impl/const-closures.rs @@ -1,4 +1,4 @@ -// run-pass +// check-pass #![feature(const_trait_impl)] diff --git a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.precise.stderr b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.precise.stderr index bcdc80f82f82e..13350a6d14a42 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.precise.stderr +++ b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.precise.stderr @@ -1,50 +1,26 @@ -error[E0277]: the trait bound `NonTrivialDrop: ~const A` is not satisfied - --> $DIR/const-drop-fail-2.rs:31:23 +error: const `impl` for trait `Drop` which is not marked with `#[const_trait]` + --> $DIR/const-drop-fail-2.rs:23:25 | -LL | const _: () = check::>( - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `~const A` is not implemented for `NonTrivialDrop` +LL | impl const Drop for ConstDropImplWithBounds { + | ^^^^ | -note: the trait `A` is implemented for `NonTrivialDrop`, but that implementation is not `const` - --> $DIR/const-drop-fail-2.rs:31:23 - | -LL | const _: () = check::>( - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required by a bound in `ConstDropImplWithBounds` - --> $DIR/const-drop-fail-2.rs:21:35 - | -LL | struct ConstDropImplWithBounds(PhantomData); - | ^^^^^^^^ required by this bound in `ConstDropImplWithBounds` + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change -error[E0277]: the trait bound `NonTrivialDrop: ~const A` is not satisfied - --> $DIR/const-drop-fail-2.rs:33:5 - | -LL | ConstDropImplWithBounds(PhantomData) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `~const A` is not implemented for `NonTrivialDrop` +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/const-drop-fail-2.rs:29:26 | -note: the trait `A` is implemented for `NonTrivialDrop`, but that implementation is not `const` - --> $DIR/const-drop-fail-2.rs:33:5 - | -LL | ConstDropImplWithBounds(PhantomData) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required by a bound in `ConstDropImplWithBounds` - --> $DIR/const-drop-fail-2.rs:21:35 - | -LL | struct ConstDropImplWithBounds(PhantomData); - | ^^^^^^^^ required by this bound in `ConstDropImplWithBounds` +LL | const fn check(_: T) {} + | ^^^^^^^^ -error[E0367]: `Drop` impl requires `T: ~const A` but the struct it is implemented for does not - --> $DIR/const-drop-fail-2.rs:39:9 +error: const `impl` for trait `Drop` which is not marked with `#[const_trait]` + --> $DIR/const-drop-fail-2.rs:39:25 | LL | impl const Drop for ConstDropImplWithNonConstBounds { - | ^^^^^^^^ - | -note: the implementor must specify the same requirement - --> $DIR/const-drop-fail-2.rs:37:1 + | ^^^^ | -LL | struct ConstDropImplWithNonConstBounds(PhantomData); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change error: aborting due to 3 previous errors -Some errors have detailed explanations: E0277, E0367. -For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.rs b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.rs index 6a252c5d37bac..3de9d37d49337 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.rs +++ b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.rs @@ -1,4 +1,4 @@ -// revisions: stock precise +// known-bug: #110395 #![feature(const_trait_impl)] #![feature(const_mut_refs)] #![cfg_attr(precise, feature(const_precise_live_drops))] @@ -29,15 +29,12 @@ impl const Drop for ConstDropImplWithBounds { const fn check(_: T) {} const _: () = check::>( - //~^ ERROR the trait bound ConstDropImplWithBounds(PhantomData) - //~^ ERROR the trait bound ); struct ConstDropImplWithNonConstBounds(PhantomData); impl const Drop for ConstDropImplWithNonConstBounds { -//~^ ERROR `Drop` impl requires `T: ~const A` but the struct it is implemented for does not fn drop(&mut self) { T::a(); } diff --git a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.stderr b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.stderr new file mode 100644 index 0000000000000..375f5d2c52d64 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.stderr @@ -0,0 +1,50 @@ +error[E0277]: the trait bound `NonTrivialDrop: ~const A` is not satisfied + --> $DIR/const-drop-fail-2.rs:31:23 + | +LL | const _: () = check::>( + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `~const A` is not implemented for `NonTrivialDrop` + | +note: the trait `A` is implemented for `NonTrivialDrop`, but that implementation is not `const` + --> $DIR/const-drop-fail-2.rs:31:23 + | +LL | const _: () = check::>( + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `ConstDropImplWithBounds` + --> $DIR/const-drop-fail-2.rs:21:35 + | +LL | struct ConstDropImplWithBounds(PhantomData); + | ^^^^^^^^ required by this bound in `ConstDropImplWithBounds` + +error[E0277]: the trait bound `NonTrivialDrop: ~const A` is not satisfied + --> $DIR/const-drop-fail-2.rs:32:5 + | +LL | ConstDropImplWithBounds(PhantomData) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `~const A` is not implemented for `NonTrivialDrop` + | +note: the trait `A` is implemented for `NonTrivialDrop`, but that implementation is not `const` + --> $DIR/const-drop-fail-2.rs:32:5 + | +LL | ConstDropImplWithBounds(PhantomData) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `ConstDropImplWithBounds` + --> $DIR/const-drop-fail-2.rs:21:35 + | +LL | struct ConstDropImplWithBounds(PhantomData); + | ^^^^^^^^ required by this bound in `ConstDropImplWithBounds` + +error[E0367]: `Drop` impl requires `T: ~const A` but the struct it is implemented for does not + --> $DIR/const-drop-fail-2.rs:37:9 + | +LL | impl const Drop for ConstDropImplWithNonConstBounds { + | ^^^^^^^^ + | +note: the implementor must specify the same requirement + --> $DIR/const-drop-fail-2.rs:35:1 + | +LL | struct ConstDropImplWithNonConstBounds(PhantomData); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 3 previous errors + +Some errors have detailed explanations: E0277, E0367. +For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.stock.stderr b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.stock.stderr index bcdc80f82f82e..13350a6d14a42 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.stock.stderr +++ b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail-2.stock.stderr @@ -1,50 +1,26 @@ -error[E0277]: the trait bound `NonTrivialDrop: ~const A` is not satisfied - --> $DIR/const-drop-fail-2.rs:31:23 +error: const `impl` for trait `Drop` which is not marked with `#[const_trait]` + --> $DIR/const-drop-fail-2.rs:23:25 | -LL | const _: () = check::>( - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `~const A` is not implemented for `NonTrivialDrop` +LL | impl const Drop for ConstDropImplWithBounds { + | ^^^^ | -note: the trait `A` is implemented for `NonTrivialDrop`, but that implementation is not `const` - --> $DIR/const-drop-fail-2.rs:31:23 - | -LL | const _: () = check::>( - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required by a bound in `ConstDropImplWithBounds` - --> $DIR/const-drop-fail-2.rs:21:35 - | -LL | struct ConstDropImplWithBounds(PhantomData); - | ^^^^^^^^ required by this bound in `ConstDropImplWithBounds` + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change -error[E0277]: the trait bound `NonTrivialDrop: ~const A` is not satisfied - --> $DIR/const-drop-fail-2.rs:33:5 - | -LL | ConstDropImplWithBounds(PhantomData) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `~const A` is not implemented for `NonTrivialDrop` +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/const-drop-fail-2.rs:29:26 | -note: the trait `A` is implemented for `NonTrivialDrop`, but that implementation is not `const` - --> $DIR/const-drop-fail-2.rs:33:5 - | -LL | ConstDropImplWithBounds(PhantomData) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -note: required by a bound in `ConstDropImplWithBounds` - --> $DIR/const-drop-fail-2.rs:21:35 - | -LL | struct ConstDropImplWithBounds(PhantomData); - | ^^^^^^^^ required by this bound in `ConstDropImplWithBounds` +LL | const fn check(_: T) {} + | ^^^^^^^^ -error[E0367]: `Drop` impl requires `T: ~const A` but the struct it is implemented for does not - --> $DIR/const-drop-fail-2.rs:39:9 +error: const `impl` for trait `Drop` which is not marked with `#[const_trait]` + --> $DIR/const-drop-fail-2.rs:39:25 | LL | impl const Drop for ConstDropImplWithNonConstBounds { - | ^^^^^^^^ - | -note: the implementor must specify the same requirement - --> $DIR/const-drop-fail-2.rs:37:1 + | ^^^^ | -LL | struct ConstDropImplWithNonConstBounds(PhantomData); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change error: aborting due to 3 previous errors -Some errors have detailed explanations: E0277, E0367. -For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.precise.stderr b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.precise.stderr index 40caada51d740..e745cbd244292 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.precise.stderr +++ b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.precise.stderr @@ -1,5 +1,5 @@ error[E0277]: can't drop `NonTrivialDrop` in const contexts - --> $DIR/const-drop-fail.rs:26:23 + --> $DIR/const-drop-fail.rs:28:23 | LL | const _: () = check($exp); | ^^^^^^^^^^^ the trait `~const Destruct` is not implemented for `NonTrivialDrop` @@ -11,7 +11,7 @@ LL | | } | |_- in this macro invocation | note: the trait `Destruct` is implemented for `NonTrivialDrop`, but that implementation is not `const` - --> $DIR/const-drop-fail.rs:26:23 + --> $DIR/const-drop-fail.rs:28:23 | LL | const _: () = check($exp); | ^^^^^^^^^^^ @@ -24,7 +24,7 @@ LL | | } = note: this error originates in the macro `check_all` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't drop `NonTrivialDrop` in const contexts - --> $DIR/const-drop-fail.rs:26:23 + --> $DIR/const-drop-fail.rs:28:23 | LL | const _: () = check($exp); | ^^^^^^^^^^^ within `ConstImplWithDropGlue`, the trait `~const Destruct` is not implemented for `NonTrivialDrop` @@ -36,7 +36,7 @@ LL | | } | |_- in this macro invocation | note: the trait `Destruct` is implemented for `NonTrivialDrop`, but that implementation is not `const` - --> $DIR/const-drop-fail.rs:26:23 + --> $DIR/const-drop-fail.rs:28:23 | LL | const _: () = check($exp); | ^^^^^^^^^^^ @@ -47,7 +47,7 @@ LL | | ConstImplWithDropGlue(NonTrivialDrop), LL | | } | |_- in this macro invocation note: required because it appears within the type `ConstImplWithDropGlue` - --> $DIR/const-drop-fail.rs:16:8 + --> $DIR/const-drop-fail.rs:18:8 | LL | struct ConstImplWithDropGlue(NonTrivialDrop); | ^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.rs b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.rs index c4bdb9ef5e569..1c37648ff1cba 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.rs +++ b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.rs @@ -1,3 +1,5 @@ +// known-bug: #110395 + // revisions: stock precise #![feature(const_trait_impl)] #![feature(const_mut_refs)] @@ -24,8 +26,6 @@ const fn check(_: T) {} macro_rules! check_all { ($($exp:expr),*$(,)?) => {$( const _: () = check($exp); - //~^ ERROR can't drop - //~| ERROR can't drop )*}; } diff --git a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.stock.stderr b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.stock.stderr index 40caada51d740..e745cbd244292 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.stock.stderr +++ b/tests/ui/rfc-2632-const-trait-impl/const-drop-fail.stock.stderr @@ -1,5 +1,5 @@ error[E0277]: can't drop `NonTrivialDrop` in const contexts - --> $DIR/const-drop-fail.rs:26:23 + --> $DIR/const-drop-fail.rs:28:23 | LL | const _: () = check($exp); | ^^^^^^^^^^^ the trait `~const Destruct` is not implemented for `NonTrivialDrop` @@ -11,7 +11,7 @@ LL | | } | |_- in this macro invocation | note: the trait `Destruct` is implemented for `NonTrivialDrop`, but that implementation is not `const` - --> $DIR/const-drop-fail.rs:26:23 + --> $DIR/const-drop-fail.rs:28:23 | LL | const _: () = check($exp); | ^^^^^^^^^^^ @@ -24,7 +24,7 @@ LL | | } = note: this error originates in the macro `check_all` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't drop `NonTrivialDrop` in const contexts - --> $DIR/const-drop-fail.rs:26:23 + --> $DIR/const-drop-fail.rs:28:23 | LL | const _: () = check($exp); | ^^^^^^^^^^^ within `ConstImplWithDropGlue`, the trait `~const Destruct` is not implemented for `NonTrivialDrop` @@ -36,7 +36,7 @@ LL | | } | |_- in this macro invocation | note: the trait `Destruct` is implemented for `NonTrivialDrop`, but that implementation is not `const` - --> $DIR/const-drop-fail.rs:26:23 + --> $DIR/const-drop-fail.rs:28:23 | LL | const _: () = check($exp); | ^^^^^^^^^^^ @@ -47,7 +47,7 @@ LL | | ConstImplWithDropGlue(NonTrivialDrop), LL | | } | |_- in this macro invocation note: required because it appears within the type `ConstImplWithDropGlue` - --> $DIR/const-drop-fail.rs:16:8 + --> $DIR/const-drop-fail.rs:18:8 | LL | struct ConstImplWithDropGlue(NonTrivialDrop); | ^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/rfc-2632-const-trait-impl/const-impl-trait.rs b/tests/ui/rfc-2632-const-trait-impl/const-impl-trait.rs index 0622f96e70d81..f396deff4fe89 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const-impl-trait.rs +++ b/tests/ui/rfc-2632-const-trait-impl/const-impl-trait.rs @@ -1,4 +1,4 @@ -// check-pass +// known-bug: #110395 #![allow(incomplete_features)] #![feature( associated_type_bounds, diff --git a/tests/ui/rfc-2632-const-trait-impl/const-impl-trait.stderr b/tests/ui/rfc-2632-const-trait-impl/const-impl-trait.stderr new file mode 100644 index 0000000000000..f9078e227910d --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/const-impl-trait.stderr @@ -0,0 +1,39 @@ +error[E0635]: unknown feature `const_cmp` + --> $DIR/const-impl-trait.rs:6:5 + | +LL | const_cmp, + | ^^^^^^^^^ + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/const-impl-trait.rs:12:30 + | +LL | const fn cmp(a: &impl ~const PartialEq) -> bool { + | ^^^^^^^^^ + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/const-impl-trait.rs:16:30 + | +LL | const fn wrap(x: impl ~const PartialEq + ~const Destruct) + | ^^^^^^^^^ + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/const-impl-trait.rs:17:20 + | +LL | -> impl ~const PartialEq + ~const Destruct + | ^^^^^^^^^ + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/const-impl-trait.rs:24:29 + | +LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy; + | ^^^^^^^^^ + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/const-impl-trait.rs:28:29 + | +LL | fn huh() -> impl ~const PartialEq + ~const Destruct + Copy { + | ^^^^^^^^^ + +error: aborting due to 6 previous errors + +For more information about this error, try `rustc --explain E0635`. diff --git a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-gate.rs b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-gate.rs index 348ca0ab1906b..dba3ad7f8701e 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-gate.rs +++ b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-gate.rs @@ -1,4 +1,5 @@ #[derive_const(Default)] //~ ERROR use of unstable library feature +//~^ ERROR not marked with `#[const_trait]` pub struct S; fn main() {} diff --git a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-gate.stderr b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-gate.stderr index cc9bdd2715f70..6a81f96d88d2e 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-gate.stderr +++ b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-gate.stderr @@ -6,6 +6,16 @@ LL | #[derive_const(Default)] | = help: add `#![feature(derive_const)]` to the crate attributes to enable -error: aborting due to previous error +error: const `impl` for trait `Default` which is not marked with `#[const_trait]` + --> $DIR/derive-const-gate.rs:1:16 + | +LL | #[derive_const(Default)] + | ^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.rs b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.rs index ed6699f372420..b575ea8dae298 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.rs +++ b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.rs @@ -1,3 +1,4 @@ +// known-bug: #110395 #![feature(derive_const)] pub struct A; @@ -8,7 +9,5 @@ impl Default for A { #[derive_const(Default)] pub struct S(A); -//~^ cannot call non-const fn -//~| the trait bound fn main() {} diff --git a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.stderr b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.stderr index 653037ef39895..1c69ad4317142 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.stderr +++ b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-non-const-type.stderr @@ -1,38 +1,12 @@ -error[E0277]: the trait bound `A: Default` is not satisfied - --> $DIR/derive-const-non-const-type.rs:10:14 +error: const `impl` for trait `Default` which is not marked with `#[const_trait]` + --> $DIR/derive-const-non-const-type.rs:10:16 | LL | #[derive_const(Default)] - | ------- in this derive macro expansion -LL | pub struct S(A); - | ^ the trait `~const Default` is not implemented for `A` + | ^^^^^^^ | -note: the trait `Default` is implemented for `A`, but that implementation is not `const` - --> $DIR/derive-const-non-const-type.rs:10:14 - | -LL | #[derive_const(Default)] - | ------- in this derive macro expansion -LL | pub struct S(A); - | ^ - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider annotating `A` with `#[derive(Default)]` - | -LL + #[derive(Default)] -LL | pub struct A; - | - -error[E0015]: cannot call non-const fn `::default` in constant functions - --> $DIR/derive-const-non-const-type.rs:10:14 - | -LL | #[derive_const(Default)] - | ------- in this derive macro expansion -LL | pub struct S(A); - | ^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 2 previous errors +error: aborting due to previous error -Some errors have detailed explanations: E0015, E0277. -For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-use.rs b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-use.rs index d1fbeac8598e4..69098542b7e36 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-use.rs +++ b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-use.rs @@ -1,4 +1,4 @@ -// check-pass +// known-bug: #110395 #![feature(const_trait_impl, const_cmp, const_default_impls, derive_const)] pub struct A; diff --git a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-use.stderr b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-use.stderr new file mode 100644 index 0000000000000..88054096e630b --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-use.stderr @@ -0,0 +1,53 @@ +error[E0635]: unknown feature `const_cmp` + --> $DIR/derive-const-use.rs:2:30 + | +LL | #![feature(const_trait_impl, const_cmp, const_default_impls, derive_const)] + | ^^^^^^^^^ + +error[E0635]: unknown feature `const_default_impls` + --> $DIR/derive-const-use.rs:2:41 + | +LL | #![feature(const_trait_impl, const_cmp, const_default_impls, derive_const)] + | ^^^^^^^^^^^^^^^^^^^ + +error: const `impl` for trait `Default` which is not marked with `#[const_trait]` + --> $DIR/derive-const-use.rs:6:12 + | +LL | impl const Default for A { + | ^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: const `impl` for trait `PartialEq` which is not marked with `#[const_trait]` + --> $DIR/derive-const-use.rs:10:12 + | +LL | impl const PartialEq for A { + | ^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: const `impl` for trait `Default` which is not marked with `#[const_trait]` + --> $DIR/derive-const-use.rs:14:16 + | +LL | #[derive_const(Default, PartialEq)] + | ^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: const `impl` for trait `PartialEq` which is not marked with `#[const_trait]` + --> $DIR/derive-const-use.rs:14:25 + | +LL | #[derive_const(Default, PartialEq)] + | ^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 6 previous errors + +For more information about this error, try `rustc --explain E0635`. diff --git a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.rs b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.rs index 72edfbc97e48f..2a5d0176ba004 100644 --- a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.rs +++ b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.rs @@ -1,4 +1,4 @@ -// check-pass +// known-bug: #110395 #![feature(derive_const)] #![feature(const_trait_impl)] diff --git a/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.stderr b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.stderr new file mode 100644 index 0000000000000..fa78326587c71 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/const_derives/derive-const-with-params.stderr @@ -0,0 +1,20 @@ +error: const `impl` for trait `PartialEq` which is not marked with `#[const_trait]` + --> $DIR/derive-const-with-params.rs:6:16 + | +LL | #[derive_const(PartialEq)] + | ^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/derive-const-with-params.rs:6:16 + | +LL | #[derive_const(PartialEq)] + | ^^^^^^^^^ + | + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 2 previous errors + diff --git a/tests/ui/rfc-2632-const-trait-impl/generic-bound.rs b/tests/ui/rfc-2632-const-trait-impl/generic-bound.rs index 5495b531cff56..d665c4479c9ab 100644 --- a/tests/ui/rfc-2632-const-trait-impl/generic-bound.rs +++ b/tests/ui/rfc-2632-const-trait-impl/generic-bound.rs @@ -1,4 +1,4 @@ -// run-pass +// known-bug: #110395 #![feature(const_trait_impl)] diff --git a/tests/ui/rfc-2632-const-trait-impl/generic-bound.stderr b/tests/ui/rfc-2632-const-trait-impl/generic-bound.stderr new file mode 100644 index 0000000000000..1b21d7c0e0e60 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/generic-bound.stderr @@ -0,0 +1,11 @@ +error: const `impl` for trait `Add` which is not marked with `#[const_trait]` + --> $DIR/generic-bound.rs:16:15 + | +LL | impl const std::ops::Add for S { + | ^^^^^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: aborting due to previous error + diff --git a/tests/ui/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.rs b/tests/ui/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.rs index 1a4509b18695a..dff8a244453af 100644 --- a/tests/ui/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.rs +++ b/tests/ui/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.rs @@ -1,4 +1,4 @@ -// check-pass +// known-bug: #110395 #![feature(const_trait_impl)] diff --git a/tests/ui/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.stderr b/tests/ui/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.stderr new file mode 100644 index 0000000000000..cfdda4713a793 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/non-const-op-in-closure-in-const.stderr @@ -0,0 +1,8 @@ +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/non-const-op-in-closure-in-const.rs:10:51 + | +LL | impl const Convert for A where B: ~const From { + | ^^^^^^^ + +error: aborting due to previous error + diff --git a/tests/ui/rfc-2632-const-trait-impl/specializing-constness.rs b/tests/ui/rfc-2632-const-trait-impl/specializing-constness.rs index 9ab170f092006..5c2a3f80170ea 100644 --- a/tests/ui/rfc-2632-const-trait-impl/specializing-constness.rs +++ b/tests/ui/rfc-2632-const-trait-impl/specializing-constness.rs @@ -11,13 +11,16 @@ pub trait A { fn a() -> u32; } -impl const A for T { +#[const_trait] +pub trait Spec {} + +impl const A for T { default fn a() -> u32 { 2 } } -impl A for T { +impl A for T { //~^ ERROR: cannot specialize //~| ERROR: missing `~const` qualifier fn a() -> u32 { diff --git a/tests/ui/rfc-2632-const-trait-impl/specializing-constness.stderr b/tests/ui/rfc-2632-const-trait-impl/specializing-constness.stderr index 843fc6ce84d45..1ffdc50e58932 100644 --- a/tests/ui/rfc-2632-const-trait-impl/specializing-constness.stderr +++ b/tests/ui/rfc-2632-const-trait-impl/specializing-constness.stderr @@ -1,14 +1,14 @@ error: cannot specialize on const impl with non-const impl - --> $DIR/specializing-constness.rs:20:1 + --> $DIR/specializing-constness.rs:23:1 | -LL | impl A for T { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | impl A for T { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: missing `~const` qualifier for specialization - --> $DIR/specializing-constness.rs:20:9 + --> $DIR/specializing-constness.rs:23:9 | -LL | impl A for T { - | ^^^^^^^ +LL | impl A for T { + | ^^^^ error: aborting due to 2 previous errors diff --git a/tests/ui/rfc-2632-const-trait-impl/std-impl-gate.gated.stderr b/tests/ui/rfc-2632-const-trait-impl/std-impl-gate.gated.stderr new file mode 100644 index 0000000000000..78aab9469e822 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/std-impl-gate.gated.stderr @@ -0,0 +1,9 @@ +error[E0635]: unknown feature `const_default_impls` + --> $DIR/std-impl-gate.rs:6:46 + | +LL | #![cfg_attr(gated, feature(const_trait_impl, const_default_impls))] + | ^^^^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0635`. diff --git a/tests/ui/rfc-2632-const-trait-impl/std-impl-gate.rs b/tests/ui/rfc-2632-const-trait-impl/std-impl-gate.rs index 2f54c09e31c9e..e9e5e0235df33 100644 --- a/tests/ui/rfc-2632-const-trait-impl/std-impl-gate.rs +++ b/tests/ui/rfc-2632-const-trait-impl/std-impl-gate.rs @@ -1,7 +1,7 @@ // This tests feature gates for const impls in the standard library. // revisions: stock gated -//[gated] run-pass +//[gated] known-bug: #110395 #![cfg_attr(gated, feature(const_trait_impl, const_default_impls))] diff --git a/tests/ui/rfc-2632-const-trait-impl/trait-default-body-stability.rs b/tests/ui/rfc-2632-const-trait-impl/trait-default-body-stability.rs index 334fc4cb8473d..8d56295e73837 100644 --- a/tests/ui/rfc-2632-const-trait-impl/trait-default-body-stability.rs +++ b/tests/ui/rfc-2632-const-trait-impl/trait-default-body-stability.rs @@ -1,4 +1,4 @@ -// check-pass +// known-bug: #110395 #![feature(staged_api)] #![feature(const_trait_impl)] diff --git a/tests/ui/rfc-2632-const-trait-impl/trait-default-body-stability.stderr b/tests/ui/rfc-2632-const-trait-impl/trait-default-body-stability.stderr new file mode 100644 index 0000000000000..35dc1ca129b12 --- /dev/null +++ b/tests/ui/rfc-2632-const-trait-impl/trait-default-body-stability.stderr @@ -0,0 +1,20 @@ +error: const `impl` for trait `Try` which is not marked with `#[const_trait]` + --> $DIR/trait-default-body-stability.rs:18:12 + | +LL | impl const Try for T { + | ^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: const `impl` for trait `FromResidual` which is not marked with `#[const_trait]` + --> $DIR/trait-default-body-stability.rs:33:12 + | +LL | impl const FromResidual for T { + | ^^^^^^^^^^^^ + | + = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` + = note: adding a non-const method body in the future would be a breaking change + +error: aborting due to 2 previous errors + diff --git a/tests/ui/specialization/const_trait_impl.rs b/tests/ui/specialization/const_trait_impl.rs index 05ba4c8d45d5b..b1ec58c3df31b 100644 --- a/tests/ui/specialization/const_trait_impl.rs +++ b/tests/ui/specialization/const_trait_impl.rs @@ -1,4 +1,5 @@ -// check-pass +// known-bug: #110395 + #![feature(const_trait_impl, min_specialization, rustc_attrs)] #[rustc_specialization_trait] diff --git a/tests/ui/specialization/const_trait_impl.stderr b/tests/ui/specialization/const_trait_impl.stderr new file mode 100644 index 0000000000000..d13cd8f55553d --- /dev/null +++ b/tests/ui/specialization/const_trait_impl.stderr @@ -0,0 +1,20 @@ +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/const_trait_impl.rs:34:16 + | +LL | impl const A for T { + | ^^^^^^^ + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/const_trait_impl.rs:40:16 + | +LL | impl const A for T { + | ^^^^^^^ + +error: ~const can only be applied to `#[const_trait]` traits + --> $DIR/const_trait_impl.rs:46:16 + | +LL | impl const A for T { + | ^^^^^^^ + +error: aborting due to 3 previous errors + diff --git a/tests/ui/suggestions/issue-109436.stderr b/tests/ui/suggestions/issue-109436.stderr index 48518b33d12ac..c479326f93534 100644 --- a/tests/ui/suggestions/issue-109436.stderr +++ b/tests/ui/suggestions/issue-109436.stderr @@ -2,7 +2,7 @@ error[E0277]: the trait bound `Foo: Into<_>` is not satisfied --> $DIR/issue-109436.rs:12:22 | LL | let b: Bar = foo.into(); - | ^^^^ the trait `~const Into<_>` is not implemented for `Foo` + | ^^^^ the trait `Into<_>` is not implemented for `Foo` | = note: required for `Foo` to implement `Into` help: consider borrowing here diff --git a/tests/ui/typeck/typeck_type_placeholder_item.rs b/tests/ui/typeck/typeck_type_placeholder_item.rs index a450dbb82d1bd..46aed0f603e87 100644 --- a/tests/ui/typeck/typeck_type_placeholder_item.rs +++ b/tests/ui/typeck/typeck_type_placeholder_item.rs @@ -227,6 +227,4 @@ fn evens_squared(n: usize) -> _ { } const _: _ = (1..10).filter(|x| x % 2 == 0).map(|x| x * x); -//~^ ERROR the trait bound -//~| ERROR the trait bound -//~| ERROR the placeholder +//~^ ERROR the placeholder diff --git a/tests/ui/typeck/typeck_type_placeholder_item.stderr b/tests/ui/typeck/typeck_type_placeholder_item.stderr index bc6c9fd077993..bc02547c65eb8 100644 --- a/tests/ui/typeck/typeck_type_placeholder_item.stderr +++ b/tests/ui/typeck/typeck_type_placeholder_item.stderr @@ -437,37 +437,17 @@ LL | fn evens_squared(n: usize) -> _ { | not allowed in type signatures | help: replace with an appropriate return type: `impl Iterator` -error[E0277]: the trait bound `std::ops::Range<{integer}>: Iterator` is not satisfied - --> $DIR/typeck_type_placeholder_item.rs:229:22 - | -LL | const _: _ = (1..10).filter(|x| x % 2 == 0).map(|x| x * x); - | ^^^^^^ `std::ops::Range<{integer}>` is not an iterator - | - = help: the trait `~const Iterator` is not implemented for `std::ops::Range<{integer}>` -note: the trait `Iterator` is implemented for `std::ops::Range<{integer}>`, but that implementation is not `const` - --> $DIR/typeck_type_placeholder_item.rs:229:14 - | -LL | const _: _ = (1..10).filter(|x| x % 2 == 0).map(|x| x * x); - | ^^^^^^^ - -error[E0277]: the trait bound `Filter, [closure@$DIR/typeck_type_placeholder_item.rs:229:29: 229:32]>: Iterator` is not satisfied - --> $DIR/typeck_type_placeholder_item.rs:229:45 +error[E0121]: the placeholder `_` is not allowed within types on item signatures for constants + --> $DIR/typeck_type_placeholder_item.rs:229:10 | LL | const _: _ = (1..10).filter(|x| x % 2 == 0).map(|x| x * x); - | ^^^ `Filter, [closure@$DIR/typeck_type_placeholder_item.rs:229:29: 229:32]>` is not an iterator + | ^ not allowed in type signatures | - = help: the trait `~const Iterator` is not implemented for `Filter, [closure@$DIR/typeck_type_placeholder_item.rs:229:29: 229:32]>` -note: the trait `Iterator` is implemented for `Filter, [closure@$DIR/typeck_type_placeholder_item.rs:229:29: 229:32]>`, but that implementation is not `const` +note: however, the inferred type `Map, [closure@typeck_type_placeholder_item.rs:229:29]>, [closure@typeck_type_placeholder_item.rs:229:49]>` cannot be named --> $DIR/typeck_type_placeholder_item.rs:229:14 | LL | const _: _ = (1..10).filter(|x| x % 2 == 0).map(|x| x * x); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error[E0121]: the placeholder `_` is not allowed within types on item signatures for constants - --> $DIR/typeck_type_placeholder_item.rs:229:10 - | -LL | const _: _ = (1..10).filter(|x| x % 2 == 0).map(|x| x * x); - | ^ not allowed in type signatures + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0121]: the placeholder `_` is not allowed within types on item signatures for functions --> $DIR/typeck_type_placeholder_item.rs:140:31 @@ -677,7 +657,7 @@ LL | const D: _ = 42; | not allowed in type signatures | help: replace with the correct type: `i32` -error: aborting due to 73 previous errors +error: aborting due to 71 previous errors -Some errors have detailed explanations: E0121, E0277, E0282, E0403. +Some errors have detailed explanations: E0121, E0282, E0403. For more information about an error, try `rustc --explain E0121`. From 7859a8e9a55725bd19636baa8d2a1a99b76689bf Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Sun, 16 Apr 2023 14:58:56 +0200 Subject: [PATCH 065/228] Don't use `serde_json` to serialize a simple JSON object This avoids `rustc_data_structures` depending on `serde_json` which allows it to be compiled much earlier, unlocking most of rustc. --- Cargo.lock | 1 - compiler/rustc_data_structures/Cargo.toml | 1 - .../rustc_data_structures/src/profiling.rs | 41 +++++++++++++++---- .../src/profiling/tests.rs | 19 +++++++++ 4 files changed, 52 insertions(+), 10 deletions(-) create mode 100644 compiler/rustc_data_structures/src/profiling/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 12be36ef86126..df6f04259549f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4587,7 +4587,6 @@ dependencies = [ "rustc_index", "rustc_macros", "rustc_serialize", - "serde_json", "smallvec", "stable_deref_trait", "stacker", diff --git a/compiler/rustc_data_structures/Cargo.toml b/compiler/rustc_data_structures/Cargo.toml index 2102f09c56a03..39f4bc63c88d1 100644 --- a/compiler/rustc_data_structures/Cargo.toml +++ b/compiler/rustc_data_structures/Cargo.toml @@ -21,7 +21,6 @@ rustc-hash = "1.1.0" rustc_index = { path = "../rustc_index", package = "rustc_index" } rustc_macros = { path = "../rustc_macros" } rustc_serialize = { path = "../rustc_serialize" } -serde_json = "1.0.59" smallvec = { version = "1.8.1", features = [ "const_generics", "union", diff --git a/compiler/rustc_data_structures/src/profiling.rs b/compiler/rustc_data_structures/src/profiling.rs index 1ed584eafad30..8fa1ac70a78c0 100644 --- a/compiler/rustc_data_structures/src/profiling.rs +++ b/compiler/rustc_data_structures/src/profiling.rs @@ -87,6 +87,7 @@ use crate::fx::FxHashMap; use std::borrow::Borrow; use std::collections::hash_map::Entry; use std::error::Error; +use std::fmt::Display; use std::fs; use std::intrinsics::unlikely; use std::path::Path; @@ -97,7 +98,6 @@ use std::time::{Duration, Instant}; pub use measureme::EventId; use measureme::{EventIdBuilder, Profiler, SerializableString, StringId}; use parking_lot::RwLock; -use serde_json::json; use smallvec::SmallVec; bitflags::bitflags! { @@ -763,6 +763,31 @@ impl Drop for VerboseTimingGuard<'_> { } } +struct JsonTimePassesEntry<'a> { + pass: &'a str, + time: f64, + start_rss: Option, + end_rss: Option, +} + +impl Display for JsonTimePassesEntry<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let Self { pass: what, time, start_rss, end_rss } = self; + write!(f, r#"{{"pass":"{what}","time":{time},"rss_start":"#).unwrap(); + match start_rss { + Some(rss) => write!(f, "{rss}")?, + None => write!(f, "null")?, + } + write!(f, r#","rss_end":"#)?; + match end_rss { + Some(rss) => write!(f, "{rss}")?, + None => write!(f, "null")?, + } + write!(f, "}}")?; + Ok(()) + } +} + pub fn print_time_passes_entry( what: &str, dur: Duration, @@ -772,13 +797,10 @@ pub fn print_time_passes_entry( ) { match format { TimePassesFormat::Json => { - let json = json!({ - "pass": what, - "time": dur.as_secs_f64(), - "rss_start": start_rss, - "rss_end": end_rss, - }); - eprintln!("time: {json}"); + let entry = + JsonTimePassesEntry { pass: what, time: dur.as_secs_f64(), start_rss, end_rss }; + + eprintln!(r#"time: {entry}"#); return; } TimePassesFormat::Text => (), @@ -894,3 +916,6 @@ cfg_if! { } } } + +#[cfg(test)] +mod tests; diff --git a/compiler/rustc_data_structures/src/profiling/tests.rs b/compiler/rustc_data_structures/src/profiling/tests.rs new file mode 100644 index 0000000000000..2b09de085da06 --- /dev/null +++ b/compiler/rustc_data_structures/src/profiling/tests.rs @@ -0,0 +1,19 @@ +use super::JsonTimePassesEntry; + +#[test] +fn with_rss() { + let entry = + JsonTimePassesEntry { pass: "typeck", time: 56.1, start_rss: Some(10), end_rss: Some(20) }; + + assert_eq!(entry.to_string(), r#"{"pass":"typeck","time":56.1,"rss_start":10,"rss_end":20}"#) +} + +#[test] +fn no_rss() { + let entry = JsonTimePassesEntry { pass: "typeck", time: 56.1, start_rss: None, end_rss: None }; + + assert_eq!( + entry.to_string(), + r#"{"pass":"typeck","time":56.1,"rss_start":null,"rss_end":null}"# + ) +} From ad8d304163a8c0e8a20d4a1d9783734586273f4a Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Sun, 16 Apr 2023 09:44:03 -0400 Subject: [PATCH 066/228] Implement StableHasher::write_u128 via write_u64 --- compiler/rustc_data_structures/src/stable_hasher.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_data_structures/src/stable_hasher.rs b/compiler/rustc_data_structures/src/stable_hasher.rs index 3ed1de1bc3ca1..1608009809f4c 100644 --- a/compiler/rustc_data_structures/src/stable_hasher.rs +++ b/compiler/rustc_data_structures/src/stable_hasher.rs @@ -107,7 +107,8 @@ impl Hasher for StableHasher { #[inline] fn write_u128(&mut self, i: u128) { - self.state.write(&i.to_le_bytes()); + self.write_u64(i as u64); + self.write_u64((i >> 64) as u64); } #[inline] From 8fc1d68413b98cd50e6e55b6e33145ccd584b6a1 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 16 Apr 2023 10:14:27 +0000 Subject: [PATCH 067/228] Account for variance in outlives verification. --- .../src/infer/outlives/components.rs | 40 ++++++++++++++++++- .../rustc_infer/src/infer/outlives/verify.rs | 9 ++++- tests/ui/impl-trait/issue-108592.stderr | 21 ---------- 3 files changed, 45 insertions(+), 25 deletions(-) delete mode 100644 tests/ui/impl-trait/issue-108592.stderr diff --git a/compiler/rustc_infer/src/infer/outlives/components.rs b/compiler/rustc_infer/src/infer/outlives/components.rs index ff23087fe8d8a..cb63d2f18b634 100644 --- a/compiler/rustc_infer/src/infer/outlives/components.rs +++ b/compiler/rustc_infer/src/infer/outlives/components.rs @@ -143,7 +143,7 @@ fn compute_components<'tcx>( // through and constrain Pi. let mut subcomponents = smallvec![]; let mut subvisited = SsoHashSet::new(); - compute_components_recursive(tcx, ty.into(), &mut subcomponents, &mut subvisited); + compute_alias_components_recursive(tcx, ty, &mut subcomponents, &mut subvisited); out.push(Component::EscapingAlias(subcomponents.into_iter().collect())); } } @@ -193,7 +193,43 @@ fn compute_components<'tcx>( /// /// This should not be used to get the components of `parent` itself. /// Use [push_outlives_components] instead. -pub(super) fn compute_components_recursive<'tcx>( +pub(super) fn compute_alias_components_recursive<'tcx>( + tcx: TyCtxt<'tcx>, + alias_ty: Ty<'tcx>, + out: &mut SmallVec<[Component<'tcx>; 4]>, + visited: &mut SsoHashSet>, +) { + let ty::Alias(kind, alias_ty) = alias_ty.kind() else { bug!() }; + let opt_variances = if *kind == ty::Opaque { tcx.variances_of(alias_ty.def_id) } else { &[] }; + for (index, child) in alias_ty.substs.iter().enumerate() { + if opt_variances.get(index) == Some(&ty::Bivariant) { + continue; + } + if !visited.insert(child) { + continue; + } + match child.unpack() { + GenericArgKind::Type(ty) => { + compute_components(tcx, ty, out, visited); + } + GenericArgKind::Lifetime(lt) => { + // Ignore late-bound regions. + if !lt.is_late_bound() { + out.push(Component::Region(lt)); + } + } + GenericArgKind::Const(_) => { + compute_components_recursive(tcx, child, out, visited); + } + } + } +} + +/// Collect [Component]s for *all* the substs of `parent`. +/// +/// This should not be used to get the components of `parent` itself. +/// Use [push_outlives_components] instead. +fn compute_components_recursive<'tcx>( tcx: TyCtxt<'tcx>, parent: GenericArg<'tcx>, out: &mut SmallVec<[Component<'tcx>; 4]>, diff --git a/compiler/rustc_infer/src/infer/outlives/verify.rs b/compiler/rustc_infer/src/infer/outlives/verify.rs index bae246418b05a..e1cb53bc71d33 100644 --- a/compiler/rustc_infer/src/infer/outlives/verify.rs +++ b/compiler/rustc_infer/src/infer/outlives/verify.rs @@ -1,4 +1,4 @@ -use crate::infer::outlives::components::{compute_components_recursive, Component}; +use crate::infer::outlives::components::{compute_alias_components_recursive, Component}; use crate::infer::outlives::env::RegionBoundPairs; use crate::infer::region_constraints::VerifyIfEq; use crate::infer::VerifyBound; @@ -130,7 +130,12 @@ impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> { // see the extensive comment in projection_must_outlive let recursive_bound = { let mut components = smallvec![]; - compute_components_recursive(self.tcx, alias_ty_as_ty.into(), &mut components, visited); + compute_alias_components_recursive( + self.tcx, + alias_ty_as_ty.into(), + &mut components, + visited, + ); self.bound_from_components(&components, visited) }; diff --git a/tests/ui/impl-trait/issue-108592.stderr b/tests/ui/impl-trait/issue-108592.stderr deleted file mode 100644 index 3fbf0b266c3e3..0000000000000 --- a/tests/ui/impl-trait/issue-108592.stderr +++ /dev/null @@ -1,21 +0,0 @@ -error[E0428]: the name `test` is defined multiple times - --> $DIR/issue-108592.rs:17:1 - | -LL | fn test() { - | --------- previous definition of the value `test` here -... -LL | fn test(_: &Opaque<'_>) { - | ^^^^^^^^^^^^^^^^^^^^^^^ `test` redefined here - | - = note: `test` must be defined only once in the value namespace of this module - -error[E0601]: `main` function not found in crate `issue_108592` - --> $DIR/issue-108592.rs:20:2 - | -LL | } - | ^ consider adding a `main` function to `$DIR/issue-108592.rs` - -error: aborting due to 2 previous errors - -Some errors have detailed explanations: E0428, E0601. -For more information about an error, try `rustc --explain E0428`. From 33036159a4cf4972c8f8f149c9088c581da89f85 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Mon, 10 Apr 2023 16:45:31 -0700 Subject: [PATCH 068/228] ci: add a runner for vanilla LLVM 16 Like #107044, this will let us track compatibility with LLVM 16 going forward, especially after we eventually upgrade our own to the next. This also drops `tidy` here and in `x86_64-gnu-llvm-15`, syncing with that change in #106085. --- .github/workflows/ci.yml | 4 ++ .../host-x86_64/x86_64-gnu-llvm-15/Dockerfile | 6 +- .../host-x86_64/x86_64-gnu-llvm-16/Dockerfile | 64 +++++++++++++++++++ src/ci/github-actions/ci.yml | 5 ++ tests/codegen/option-as-slice.rs | 2 + tests/debuginfo/unsized.rs | 2 + 6 files changed, 78 insertions(+), 5 deletions(-) create mode 100644 src/ci/docker/host-x86_64/x86_64-gnu-llvm-16/Dockerfile diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bce88472f96f9..dacf929278ab9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -292,6 +292,10 @@ jobs: - name: x86_64-gnu-distcheck os: ubuntu-20.04-8core-32gb env: {} + - name: x86_64-gnu-llvm-16 + env: + RUST_BACKTRACE: 1 + os: ubuntu-20.04-8core-32gb - name: x86_64-gnu-llvm-15 env: RUST_BACKTRACE: 1 diff --git a/src/ci/docker/host-x86_64/x86_64-gnu-llvm-15/Dockerfile b/src/ci/docker/host-x86_64/x86_64-gnu-llvm-15/Dockerfile index fb5037e3b973d..c471843b8533f 100644 --- a/src/ci/docker/host-x86_64/x86_64-gnu-llvm-15/Dockerfile +++ b/src/ci/docker/host-x86_64/x86_64-gnu-llvm-15/Dockerfile @@ -2,7 +2,6 @@ FROM ubuntu:22.10 ARG DEBIAN_FRONTEND=noninteractive -# NOTE: intentionally installs both python2 and python3 so we can test support for both. RUN apt-get update && apt-get install -y --no-install-recommends \ g++ \ gcc-multilib \ @@ -11,7 +10,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ file \ curl \ ca-certificates \ - python2.7 \ python3 \ git \ cmake \ @@ -63,6 +61,4 @@ ENV SCRIPT ../x.py --stage 2 test --exclude src/tools/tidy && \ # work. # ../x.ps1 --stage 2 test tests/ui --pass=check \ - --host='' --target=i686-unknown-linux-gnu && \ - # Run tidy at the very end, after all the other tests. - python2.7 ../x.py --stage 2 test src/tools/tidy + --host='' --target=i686-unknown-linux-gnu diff --git a/src/ci/docker/host-x86_64/x86_64-gnu-llvm-16/Dockerfile b/src/ci/docker/host-x86_64/x86_64-gnu-llvm-16/Dockerfile new file mode 100644 index 0000000000000..7c75d0df59083 --- /dev/null +++ b/src/ci/docker/host-x86_64/x86_64-gnu-llvm-16/Dockerfile @@ -0,0 +1,64 @@ +FROM ubuntu:23.04 + +ARG DEBIAN_FRONTEND=noninteractive + +RUN apt-get update && apt-get install -y --no-install-recommends \ + g++ \ + gcc-multilib \ + make \ + ninja-build \ + file \ + curl \ + ca-certificates \ + python3 \ + git \ + cmake \ + sudo \ + gdb \ + llvm-16-tools \ + llvm-16-dev \ + libedit-dev \ + libssl-dev \ + pkg-config \ + zlib1g-dev \ + xz-utils \ + nodejs \ + mingw-w64 \ + && rm -rf /var/lib/apt/lists/* + +# Install powershell (universal package) so we can test x.ps1 on Linux +RUN curl -sL "https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell_7.3.1-1.deb_amd64.deb" > powershell.deb && \ + dpkg -i powershell.deb && \ + rm -f powershell.deb + +COPY scripts/sccache.sh /scripts/ +RUN sh /scripts/sccache.sh + +# We are disabling CI LLVM since this builder is intentionally using a host +# LLVM, rather than the typical src/llvm-project LLVM. +ENV NO_DOWNLOAD_CI_LLVM 1 + +# Using llvm-link-shared due to libffi issues -- see #34486 +ENV RUST_CONFIGURE_ARGS \ + --build=x86_64-unknown-linux-gnu \ + --llvm-root=/usr/lib/llvm-16 \ + --enable-llvm-link-shared \ + --set rust.thin-lto-import-instr-limit=10 + +# NOTE: intentionally uses all of `x.py`, `x`, and `x.ps1` to make sure they all work on Linux. +ENV SCRIPT ../x.py --stage 2 test --exclude src/tools/tidy && \ + # Run the `mir-opt` tests again but this time for a 32-bit target. + # This enforces that tests using `// EMIT_MIR_FOR_EACH_BIT_WIDTH` have + # both 32-bit and 64-bit outputs updated by the PR author, before + # the PR is approved and tested for merging. + # It will also detect tests lacking `// EMIT_MIR_FOR_EACH_BIT_WIDTH`, + # despite having different output on 32-bit vs 64-bit targets. + ../x --stage 2 test tests/mir-opt \ + --host='' --target=i686-unknown-linux-gnu && \ + # Run the UI test suite again, but in `--pass=check` mode + # + # This is intended to make sure that both `--pass=check` continues to + # work. + # + ../x.ps1 --stage 2 test tests/ui --pass=check \ + --host='' --target=i686-unknown-linux-gnu diff --git a/src/ci/github-actions/ci.yml b/src/ci/github-actions/ci.yml index dbf4be4be24e9..8c7798aad8bdf 100644 --- a/src/ci/github-actions/ci.yml +++ b/src/ci/github-actions/ci.yml @@ -457,6 +457,11 @@ jobs: - name: x86_64-gnu-distcheck <<: *job-linux-8c + - name: x86_64-gnu-llvm-16 + env: + RUST_BACKTRACE: 1 + <<: *job-linux-8c + - name: x86_64-gnu-llvm-15 env: RUST_BACKTRACE: 1 diff --git a/tests/codegen/option-as-slice.rs b/tests/codegen/option-as-slice.rs index d735d55837408..1edd9ba9f7da6 100644 --- a/tests/codegen/option-as-slice.rs +++ b/tests/codegen/option-as-slice.rs @@ -1,5 +1,7 @@ // compile-flags: -O -Z randomize-layout=no // only-x86_64 +// ignore-llvm-version: 16.0.0 +// ^ needs https://reviews.llvm.org/D146149 in 16.0.1 #![crate_type = "lib"] #![feature(option_as_slice)] diff --git a/tests/debuginfo/unsized.rs b/tests/debuginfo/unsized.rs index b1ec9b0683059..3b8280bc4a9ef 100644 --- a/tests/debuginfo/unsized.rs +++ b/tests/debuginfo/unsized.rs @@ -1,4 +1,6 @@ // compile-flags:-g +// ignore-gdb-version: 13.1 - 99.0 +// ^ https://sourceware.org/bugzilla/show_bug.cgi?id=30330 // === GDB TESTS =================================================================================== From 6fe2406155183f0b46022b60a997adc67f9d1c2a Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Sun, 16 Apr 2023 11:49:41 -0700 Subject: [PATCH 069/228] Test python2.7 in dist-x86_64-illumos --- src/ci/docker/host-x86_64/dist-x86_64-illumos/Dockerfile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ci/docker/host-x86_64/dist-x86_64-illumos/Dockerfile b/src/ci/docker/host-x86_64/dist-x86_64-illumos/Dockerfile index 2089bf3871626..55fefd2b725b5 100644 --- a/src/ci/docker/host-x86_64/dist-x86_64-illumos/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-x86_64-illumos/Dockerfile @@ -6,12 +6,13 @@ RUN sed -i 's/^# deb-src/deb-src/' /etc/apt/sources.list COPY scripts/cross-apt-packages.sh /tmp/ RUN bash /tmp/cross-apt-packages.sh -# Required for cross-build gcc +# Required for cross-build gcc, and we install python2 to test general compatibility. RUN apt-get update && \ apt-get install -y --no-install-recommends \ libgmp-dev \ libmpfr-dev \ libmpc-dev \ + python2.7 \ && rm -rf /var/lib/apt/lists/* COPY scripts/illumos-toolchain.sh /tmp/ @@ -35,4 +36,4 @@ ENV \ ENV HOSTS=x86_64-unknown-illumos ENV RUST_CONFIGURE_ARGS --enable-extended --disable-docs -ENV SCRIPT python3 ../x.py dist --host $HOSTS --target $HOSTS +ENV SCRIPT python2.7 ../x.py dist --host $HOSTS --target $HOSTS From e28e19034ffd49a50499e96da884be3ea9a950aa Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 16 Apr 2023 23:07:18 +0000 Subject: [PATCH 070/228] Check freeze with right param-env --- .../src/deduce_param_attrs.rs | 5 +++-- .../freeze-on-polymorphic-projection.rs | 19 +++++++++++++++++++ .../freeze-on-polymorphic-projection.stderr | 12 ++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 tests/ui/codegen/freeze-on-polymorphic-projection.rs create mode 100644 tests/ui/codegen/freeze-on-polymorphic-projection.stderr diff --git a/compiler/rustc_mir_transform/src/deduce_param_attrs.rs b/compiler/rustc_mir_transform/src/deduce_param_attrs.rs index e5c3fa5646a73..8ee08c5be3419 100644 --- a/compiler/rustc_mir_transform/src/deduce_param_attrs.rs +++ b/compiler/rustc_mir_transform/src/deduce_param_attrs.rs @@ -9,7 +9,7 @@ use rustc_hir::def_id::LocalDefId; use rustc_index::bit_set::BitSet; use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::{Body, Local, Location, Operand, Terminator, TerminatorKind, RETURN_PLACE}; -use rustc_middle::ty::{self, DeducedParamAttrs, ParamEnv, Ty, TyCtxt}; +use rustc_middle::ty::{self, DeducedParamAttrs, Ty, TyCtxt}; use rustc_session::config::OptLevel; /// A visitor that determines which arguments have been mutated. We can't use the mutability field @@ -198,11 +198,12 @@ pub fn deduced_param_attrs<'tcx>( // see [1]. // // [1]: https://github.com/rust-lang/rust/pull/103172#discussion_r999139997 + let param_env = tcx.param_env_reveal_all_normalized(def_id); let mut deduced_param_attrs = tcx.arena.alloc_from_iter( body.local_decls.iter().skip(1).take(body.arg_count).enumerate().map( |(arg_index, local_decl)| DeducedParamAttrs { read_only: !deduce_read_only.mutable_args.contains(arg_index) - && local_decl.ty.is_freeze(tcx, ParamEnv::reveal_all()), + && local_decl.ty.is_freeze(tcx, param_env), }, ), ); diff --git a/tests/ui/codegen/freeze-on-polymorphic-projection.rs b/tests/ui/codegen/freeze-on-polymorphic-projection.rs new file mode 100644 index 0000000000000..edc79f8fd94bd --- /dev/null +++ b/tests/ui/codegen/freeze-on-polymorphic-projection.rs @@ -0,0 +1,19 @@ +// build-pass +// compile-flags: -Copt-level=1 --crate-type=lib + +#![feature(specialization)] +//~^ WARN the feature `specialization` is incomplete + +pub unsafe trait Storage { + type Handle; +} + +pub unsafe trait MultipleStorage: Storage {} + +default unsafe impl Storage for S where S: MultipleStorage {} + +// Make sure that we call is_freeze on `(S::Handle,)` in the param-env of `ice`, +// instead of in an empty, reveal-all param-env. +pub fn ice(boxed: (S::Handle,)) -> (S::Handle,) { + boxed +} diff --git a/tests/ui/codegen/freeze-on-polymorphic-projection.stderr b/tests/ui/codegen/freeze-on-polymorphic-projection.stderr new file mode 100644 index 0000000000000..903cb2ff6aa98 --- /dev/null +++ b/tests/ui/codegen/freeze-on-polymorphic-projection.stderr @@ -0,0 +1,12 @@ +warning: the feature `specialization` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/freeze-on-polymorphic-projection.rs:4:12 + | +LL | #![feature(specialization)] + | ^^^^^^^^^^^^^^ + | + = note: see issue #31844 for more information + = help: consider using `min_specialization` instead, which is more stable and complete + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + From 84facac97a3a13a1ea29b227d55513b58ffe7692 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Sat, 15 Apr 2023 13:53:50 -0400 Subject: [PATCH 071/228] Remove some unnecessary hash truncations --- compiler/rustc_data_structures/src/svh.rs | 34 ++++--------------- compiler/rustc_middle/src/hir/map/mod.rs | 2 +- .../src/ich/impls_syntax.rs | 2 +- compiler/rustc_span/src/lib.rs | 4 +-- 4 files changed, 9 insertions(+), 33 deletions(-) diff --git a/compiler/rustc_data_structures/src/svh.rs b/compiler/rustc_data_structures/src/svh.rs index 61654b9e8f5f5..b955df94f1633 100644 --- a/compiler/rustc_data_structures/src/svh.rs +++ b/compiler/rustc_data_structures/src/svh.rs @@ -5,40 +5,30 @@ //! mismatches where we have two versions of the same crate that were //! compiled from distinct sources. -use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; +use crate::fingerprint::Fingerprint; use std::fmt; -use std::hash::{Hash, Hasher}; use crate::stable_hasher; -#[derive(Copy, Clone, PartialEq, Eq, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, Hash)] pub struct Svh { - hash: u64, + hash: Fingerprint, } impl Svh { /// Creates a new `Svh` given the hash. If you actually want to /// compute the SVH from some HIR, you want the `calculate_svh` /// function found in `rustc_incremental`. - pub fn new(hash: u64) -> Svh { + pub fn new(hash: Fingerprint) -> Svh { Svh { hash } } pub fn as_u64(&self) -> u64 { - self.hash + self.hash.to_smaller_hash() } pub fn to_string(&self) -> String { - format!("{:016x}", self.hash) - } -} - -impl Hash for Svh { - fn hash(&self, state: &mut H) - where - H: Hasher, - { - self.hash.to_le().hash(state); + format!("{:016x}", self.hash.to_smaller_hash()) } } @@ -48,18 +38,6 @@ impl fmt::Display for Svh { } } -impl Encodable for Svh { - fn encode(&self, s: &mut S) { - s.emit_u64(self.as_u64().to_le()); - } -} - -impl Decodable for Svh { - fn decode(d: &mut D) -> Svh { - Svh::new(u64::from_le(d.read_u64())) - } -} - impl stable_hasher::HashStable for Svh { #[inline] fn hash_stable(&self, ctx: &mut T, hasher: &mut stable_hasher::StableHasher) { diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index e551c76f8db38..64aff27744fd1 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -1199,7 +1199,7 @@ pub(super) fn crate_hash(tcx: TyCtxt<'_>, _: LocalCrate) -> Svh { stable_hasher.finish() }); - Svh::new(crate_hash.to_smaller_hash()) + Svh::new(crate_hash) } fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> { diff --git a/compiler/rustc_query_system/src/ich/impls_syntax.rs b/compiler/rustc_query_system/src/ich/impls_syntax.rs index 0bc811eb04412..8865ecf3e054a 100644 --- a/compiler/rustc_query_system/src/ich/impls_syntax.rs +++ b/compiler/rustc_query_system/src/ich/impls_syntax.rs @@ -75,7 +75,7 @@ impl<'a> HashStable> for SourceFile { ref normalized_pos, } = *self; - (name_hash as u64).hash_stable(hcx, hasher); + name_hash.hash_stable(hcx, hasher); src_hash.hash_stable(hcx, hasher); diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index aa8859ed1a358..16583582933da 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -2159,9 +2159,7 @@ where }; Hash::hash(&TAG_VALID_SPAN, hasher); - // We truncate the stable ID hash and line and column numbers. The chances - // of causing a collision this way should be minimal. - Hash::hash(&(file.name_hash as u64), hasher); + Hash::hash(&file.name_hash, hasher); // Hash both the length and the end location (line/column) of a span. If we // hash only the length, for example, then two otherwise equal spans with From 99851c48cf0f1942d9c4d0c22df1d83fc3a61814 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 17 Apr 2023 01:19:29 +0000 Subject: [PATCH 072/228] bless mir-opt --- ...unchecked_shl_unsigned_smaller.Inline.diff | 117 ++---------------- ..._shl_unsigned_smaller.PreCodegen.after.mir | 116 ++--------------- ...s.unchecked_shr_signed_smaller.Inline.diff | 117 ++---------------- ...ed_shr_signed_smaller.PreCodegen.after.mir | 116 ++--------------- 4 files changed, 28 insertions(+), 438 deletions(-) diff --git a/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.Inline.diff b/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.Inline.diff index 6184a0acd1879..082e3884d9e64 100644 --- a/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.Inline.diff +++ b/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.Inline.diff @@ -11,50 +11,7 @@ + debug self => _3; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + debug rhs => _4; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + let mut _5: u16; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ let mut _6: std::option::Option; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ let mut _7: std::result::Result; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + scope 2 { -+ scope 3 (inlined >::try_into) { // at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ debug self => _4; // in scope 3 at $SRC_DIR/core/src/convert/mod.rs:LL:COL -+ scope 4 (inlined convert::num:: for u16>::try_from) { // at $SRC_DIR/core/src/convert/mod.rs:LL:COL -+ debug u => _4; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ let mut _8: bool; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ let mut _9: u32; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ let mut _10: u16; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ } -+ } -+ scope 5 (inlined Result::::ok) { // at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ debug self => _7; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ let mut _11: isize; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ let _12: u16; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ scope 6 { -+ debug x => _12; // in scope 6 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ scope 7 { -+ scope 8 { -+ debug x => const TryFromIntError(()); // in scope 8 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ } -+ } -+ scope 9 (inlined #[track_caller] Option::::unwrap_unchecked) { // at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ debug self => _6; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ let mut _13: &std::option::Option; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ let mut _14: isize; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ scope 10 { -+ debug val => _5; // in scope 10 at $SRC_DIR/core/src/option.rs:LL:COL -+ } -+ scope 11 { -+ scope 13 (inlined unreachable_unchecked) { // at $SRC_DIR/core/src/option.rs:LL:COL -+ scope 14 { -+ scope 15 (inlined unreachable_unchecked::runtime) { // at $SRC_DIR/core/src/intrinsics.rs:LL:COL -+ } -+ } -+ } -+ } -+ scope 12 (inlined Option::::is_some) { // at $SRC_DIR/core/src/option.rs:LL:COL -+ debug self => _13; // in scope 12 at $SRC_DIR/core/src/option.rs:LL:COL -+ } -+ } + } + } @@ -64,81 +21,21 @@ StorageLive(_4); // scope 0 at $DIR/unchecked_shifts.rs:+1:21: +1:22 _4 = _2; // scope 0 at $DIR/unchecked_shifts.rs:+1:21: +1:22 - _0 = core::num::::unchecked_shl(move _3, move _4) -> bb1; // scope 0 at $DIR/unchecked_shifts.rs:+1:5: +1:23 -- // mir::Constant ++ StorageLive(_5); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 ++ _5 = _4 as u16 (IntToInt); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL ++ _0 = unchecked_shl::(_3, _5) -> [return: bb1, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + // mir::Constant - // + span: $DIR/unchecked_shifts.rs:11:7: 11:20 - // + literal: Const { ty: unsafe fn(u16, u32) -> u16 {core::num::::unchecked_shl}, val: Value() } -+ StorageLive(_5); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ StorageLive(_6); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ StorageLive(_7); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ StorageLive(_8); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ StorageLive(_9); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ _9 = const 65535_u32; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ _8 = Gt(_4, move _9); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ StorageDead(_9); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ switchInt(move _8) -> [0: bb4, otherwise: bb3]; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL ++ // + span: $SRC_DIR/core/src/num/uint_macros.rs:LL:COL ++ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(u16, u16) -> u16 {unchecked_shl::}, val: Value() } } bb1: { -+ StorageDead(_12); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ StorageDead(_7); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ StorageLive(_13); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ _14 = discriminant(_6); // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ switchInt(move _14) -> [1: bb9, otherwise: bb7]; // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ } -+ -+ bb2: { -+ StorageDead(_5); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL ++ StorageDead(_5); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 StorageDead(_4); // scope 0 at $DIR/unchecked_shifts.rs:+1:22: +1:23 StorageDead(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:22: +1:23 return; // scope 0 at $DIR/unchecked_shifts.rs:+2:2: +2:2 -+ } -+ -+ bb3: { -+ _7 = Result::::Err(const TryFromIntError(())); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ // mir::Constant -+ // + span: no-location -+ // + literal: Const { ty: TryFromIntError, val: Value() } -+ goto -> bb5; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ } -+ -+ bb4: { -+ StorageLive(_10); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ _10 = _4 as u16 (IntToInt); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ _7 = Result::::Ok(move _10); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ StorageDead(_10); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ goto -> bb5; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ } -+ -+ bb5: { -+ StorageDead(_8); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ StorageLive(_12); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ _11 = discriminant(_7); // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ switchInt(move _11) -> [0: bb8, 1: bb6, otherwise: bb7]; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ -+ bb6: { -+ _6 = Option::::None; // scope 8 at $SRC_DIR/core/src/result.rs:LL:COL -+ goto -> bb1; // scope 7 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ -+ bb7: { -+ unreachable; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ -+ bb8: { -+ _12 = move ((_7 as Ok).0: u16); // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ _6 = Option::::Some(move _12); // scope 6 at $SRC_DIR/core/src/result.rs:LL:COL -+ goto -> bb1; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ -+ bb9: { -+ _5 = move ((_6 as Some).0: u16); // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ StorageDead(_13); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ StorageDead(_6); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ _0 = unchecked_shl::(_3, move _5) -> [return: bb2, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ // mir::Constant -+ // + span: $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(u16, u16) -> u16 {unchecked_shl::}, val: Value() } } } diff --git a/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.PreCodegen.after.mir b/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.PreCodegen.after.mir index 726b6bbf93b5c..e12ca38e2cf2f 100644 --- a/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.PreCodegen.after.mir +++ b/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.PreCodegen.after.mir @@ -8,123 +8,21 @@ fn unchecked_shl_unsigned_smaller(_1: u16, _2: u32) -> u16 { debug self => _1; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL debug rhs => _2; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL let mut _3: u16; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - let mut _4: std::option::Option; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - let mut _5: std::result::Result; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL scope 2 { - scope 3 (inlined >::try_into) { // at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - debug self => _2; // in scope 3 at $SRC_DIR/core/src/convert/mod.rs:LL:COL - scope 4 (inlined convert::num:: for u16>::try_from) { // at $SRC_DIR/core/src/convert/mod.rs:LL:COL - debug u => _2; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - let mut _6: bool; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - let mut _7: u32; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - let mut _8: u16; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - } - } - scope 5 (inlined Result::::ok) { // at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - debug self => _5; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - let mut _9: isize; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - let _10: u16; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - scope 6 { - debug x => _10; // in scope 6 at $SRC_DIR/core/src/result.rs:LL:COL - } - scope 7 { - scope 8 { - debug x => const TryFromIntError(()); // in scope 8 at $SRC_DIR/core/src/result.rs:LL:COL - } - } - } - scope 9 (inlined #[track_caller] Option::::unwrap_unchecked) { // at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - debug self => _4; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - let mut _11: &std::option::Option; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - let mut _12: isize; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - scope 10 { - debug val => _3; // in scope 10 at $SRC_DIR/core/src/option.rs:LL:COL - } - scope 11 { - scope 13 (inlined unreachable_unchecked) { // at $SRC_DIR/core/src/option.rs:LL:COL - scope 14 { - scope 15 (inlined unreachable_unchecked::runtime) { // at $SRC_DIR/core/src/intrinsics.rs:LL:COL - } - } - } - } - scope 12 (inlined Option::::is_some) { // at $SRC_DIR/core/src/option.rs:LL:COL - debug self => _11; // in scope 12 at $SRC_DIR/core/src/option.rs:LL:COL - } - } } } bb0: { - StorageLive(_3); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - StorageLive(_4); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - StorageLive(_5); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - StorageLive(_6); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - StorageLive(_7); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - _7 = const 65535_u32; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - _6 = Gt(_2, move _7); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - StorageDead(_7); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - switchInt(move _6) -> [0: bb4, otherwise: bb3]; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL + StorageLive(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 + _3 = _2 as u16 (IntToInt); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + _0 = unchecked_shl::(_1, _3) -> [return: bb1, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + // mir::Constant + // + span: $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(u16, u16) -> u16 {unchecked_shl::}, val: Value() } } bb1: { - StorageDead(_10); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - StorageDead(_5); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - StorageLive(_11); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - _12 = discriminant(_4); // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - switchInt(move _12) -> [1: bb9, otherwise: bb7]; // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - } - - bb2: { - StorageDead(_3); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + StorageDead(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 return; // scope 0 at $DIR/unchecked_shifts.rs:+2:2: +2:2 } - - bb3: { - _5 = Result::::Err(const TryFromIntError(())); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - // mir::Constant - // + span: no-location - // + literal: Const { ty: TryFromIntError, val: Value() } - goto -> bb5; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - } - - bb4: { - StorageLive(_8); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - _8 = _2 as u16 (IntToInt); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - _5 = Result::::Ok(move _8); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - StorageDead(_8); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - goto -> bb5; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - } - - bb5: { - StorageDead(_6); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - StorageLive(_10); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - _9 = discriminant(_5); // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - switchInt(move _9) -> [0: bb8, 1: bb6, otherwise: bb7]; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - } - - bb6: { - _4 = Option::::None; // scope 8 at $SRC_DIR/core/src/result.rs:LL:COL - goto -> bb1; // scope 7 at $SRC_DIR/core/src/result.rs:LL:COL - } - - bb7: { - unreachable; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - } - - bb8: { - _10 = move ((_5 as Ok).0: u16); // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - _4 = Option::::Some(move _10); // scope 6 at $SRC_DIR/core/src/result.rs:LL:COL - goto -> bb1; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - } - - bb9: { - _3 = move ((_4 as Some).0: u16); // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - StorageDead(_11); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - StorageDead(_4); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - _0 = unchecked_shl::(_1, move _3) -> [return: bb2, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - // mir::Constant - // + span: $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(u16, u16) -> u16 {unchecked_shl::}, val: Value() } - } } diff --git a/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.Inline.diff b/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.Inline.diff index 35d5b6e72f28f..ca9f4c96eb267 100644 --- a/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.Inline.diff +++ b/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.Inline.diff @@ -11,50 +11,7 @@ + debug self => _3; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL + debug rhs => _4; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL + let mut _5: i16; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ let mut _6: std::option::Option; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ let mut _7: std::result::Result; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL + scope 2 { -+ scope 3 (inlined >::try_into) { // at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ debug self => _4; // in scope 3 at $SRC_DIR/core/src/convert/mod.rs:LL:COL -+ scope 4 (inlined convert::num:: for i16>::try_from) { // at $SRC_DIR/core/src/convert/mod.rs:LL:COL -+ debug u => _4; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ let mut _8: bool; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ let mut _9: u32; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ let mut _10: i16; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ } -+ } -+ scope 5 (inlined Result::::ok) { // at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ debug self => _7; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ let mut _11: isize; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ let _12: i16; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ scope 6 { -+ debug x => _12; // in scope 6 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ scope 7 { -+ scope 8 { -+ debug x => const TryFromIntError(()); // in scope 8 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ } -+ } -+ scope 9 (inlined #[track_caller] Option::::unwrap_unchecked) { // at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ debug self => _6; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ let mut _13: &std::option::Option; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ let mut _14: isize; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ scope 10 { -+ debug val => _5; // in scope 10 at $SRC_DIR/core/src/option.rs:LL:COL -+ } -+ scope 11 { -+ scope 13 (inlined unreachable_unchecked) { // at $SRC_DIR/core/src/option.rs:LL:COL -+ scope 14 { -+ scope 15 (inlined unreachable_unchecked::runtime) { // at $SRC_DIR/core/src/intrinsics.rs:LL:COL -+ } -+ } -+ } -+ } -+ scope 12 (inlined Option::::is_some) { // at $SRC_DIR/core/src/option.rs:LL:COL -+ debug self => _13; // in scope 12 at $SRC_DIR/core/src/option.rs:LL:COL -+ } -+ } + } + } @@ -64,81 +21,21 @@ StorageLive(_4); // scope 0 at $DIR/unchecked_shifts.rs:+1:21: +1:22 _4 = _2; // scope 0 at $DIR/unchecked_shifts.rs:+1:21: +1:22 - _0 = core::num::::unchecked_shr(move _3, move _4) -> bb1; // scope 0 at $DIR/unchecked_shifts.rs:+1:5: +1:23 -- // mir::Constant ++ StorageLive(_5); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 ++ _5 = _4 as i16 (IntToInt); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL ++ _0 = unchecked_shr::(_3, _5) -> [return: bb1, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL + // mir::Constant - // + span: $DIR/unchecked_shifts.rs:17:7: 17:20 - // + literal: Const { ty: unsafe fn(i16, u32) -> i16 {core::num::::unchecked_shr}, val: Value() } -+ StorageLive(_5); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ StorageLive(_6); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ StorageLive(_7); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ StorageLive(_8); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ StorageLive(_9); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ _9 = const 32767_u32; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ _8 = Gt(_4, move _9); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ StorageDead(_9); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ switchInt(move _8) -> [0: bb4, otherwise: bb3]; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL ++ // + span: $SRC_DIR/core/src/num/int_macros.rs:LL:COL ++ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(i16, i16) -> i16 {unchecked_shr::}, val: Value() } } bb1: { -+ StorageDead(_12); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ StorageDead(_7); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ StorageLive(_13); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ _14 = discriminant(_6); // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ switchInt(move _14) -> [1: bb9, otherwise: bb7]; // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ } -+ -+ bb2: { -+ StorageDead(_5); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL ++ StorageDead(_5); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 StorageDead(_4); // scope 0 at $DIR/unchecked_shifts.rs:+1:22: +1:23 StorageDead(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:22: +1:23 return; // scope 0 at $DIR/unchecked_shifts.rs:+2:2: +2:2 -+ } -+ -+ bb3: { -+ _7 = Result::::Err(const TryFromIntError(())); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ // mir::Constant -+ // + span: no-location -+ // + literal: Const { ty: TryFromIntError, val: Value() } -+ goto -> bb5; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ } -+ -+ bb4: { -+ StorageLive(_10); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ _10 = _4 as i16 (IntToInt); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ _7 = Result::::Ok(move _10); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ StorageDead(_10); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ goto -> bb5; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ } -+ -+ bb5: { -+ StorageDead(_8); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL -+ StorageLive(_12); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ _11 = discriminant(_7); // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ switchInt(move _11) -> [0: bb8, 1: bb6, otherwise: bb7]; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ -+ bb6: { -+ _6 = Option::::None; // scope 8 at $SRC_DIR/core/src/result.rs:LL:COL -+ goto -> bb1; // scope 7 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ -+ bb7: { -+ unreachable; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ -+ bb8: { -+ _12 = move ((_7 as Ok).0: i16); // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ _6 = Option::::Some(move _12); // scope 6 at $SRC_DIR/core/src/result.rs:LL:COL -+ goto -> bb1; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL -+ } -+ -+ bb9: { -+ _5 = move ((_6 as Some).0: i16); // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL -+ StorageDead(_13); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ StorageDead(_6); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ _0 = unchecked_shr::(_3, move _5) -> [return: bb2, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ // mir::Constant -+ // + span: $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(i16, i16) -> i16 {unchecked_shr::}, val: Value() } } } diff --git a/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.PreCodegen.after.mir b/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.PreCodegen.after.mir index b006085b54c58..42c2c255781fe 100644 --- a/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.PreCodegen.after.mir +++ b/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.PreCodegen.after.mir @@ -8,123 +8,21 @@ fn unchecked_shr_signed_smaller(_1: i16, _2: u32) -> i16 { debug self => _1; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL debug rhs => _2; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL let mut _3: i16; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - let mut _4: std::option::Option; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - let mut _5: std::result::Result; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL scope 2 { - scope 3 (inlined >::try_into) { // at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - debug self => _2; // in scope 3 at $SRC_DIR/core/src/convert/mod.rs:LL:COL - scope 4 (inlined convert::num:: for i16>::try_from) { // at $SRC_DIR/core/src/convert/mod.rs:LL:COL - debug u => _2; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - let mut _6: bool; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - let mut _7: u32; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - let mut _8: i16; // in scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - } - } - scope 5 (inlined Result::::ok) { // at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - debug self => _5; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - let mut _9: isize; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - let _10: i16; // in scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - scope 6 { - debug x => _10; // in scope 6 at $SRC_DIR/core/src/result.rs:LL:COL - } - scope 7 { - scope 8 { - debug x => const TryFromIntError(()); // in scope 8 at $SRC_DIR/core/src/result.rs:LL:COL - } - } - } - scope 9 (inlined #[track_caller] Option::::unwrap_unchecked) { // at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - debug self => _4; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - let mut _11: &std::option::Option; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - let mut _12: isize; // in scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - scope 10 { - debug val => _3; // in scope 10 at $SRC_DIR/core/src/option.rs:LL:COL - } - scope 11 { - scope 13 (inlined unreachable_unchecked) { // at $SRC_DIR/core/src/option.rs:LL:COL - scope 14 { - scope 15 (inlined unreachable_unchecked::runtime) { // at $SRC_DIR/core/src/intrinsics.rs:LL:COL - } - } - } - } - scope 12 (inlined Option::::is_some) { // at $SRC_DIR/core/src/option.rs:LL:COL - debug self => _11; // in scope 12 at $SRC_DIR/core/src/option.rs:LL:COL - } - } } } bb0: { - StorageLive(_3); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - StorageLive(_4); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - StorageLive(_5); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - StorageLive(_6); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - StorageLive(_7); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - _7 = const 32767_u32; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - _6 = Gt(_2, move _7); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - StorageDead(_7); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - switchInt(move _6) -> [0: bb4, otherwise: bb3]; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL + StorageLive(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 + _3 = _2 as i16 (IntToInt); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL + _0 = unchecked_shr::(_1, _3) -> [return: bb1, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL + // mir::Constant + // + span: $SRC_DIR/core/src/num/int_macros.rs:LL:COL + // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(i16, i16) -> i16 {unchecked_shr::}, val: Value() } } bb1: { - StorageDead(_10); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - StorageDead(_5); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - StorageLive(_11); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - _12 = discriminant(_4); // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - switchInt(move _12) -> [1: bb9, otherwise: bb7]; // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - } - - bb2: { - StorageDead(_3); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL + StorageDead(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 return; // scope 0 at $DIR/unchecked_shifts.rs:+2:2: +2:2 } - - bb3: { - _5 = Result::::Err(const TryFromIntError(())); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - // mir::Constant - // + span: no-location - // + literal: Const { ty: TryFromIntError, val: Value() } - goto -> bb5; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - } - - bb4: { - StorageLive(_8); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - _8 = _2 as i16 (IntToInt); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - _5 = Result::::Ok(move _8); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - StorageDead(_8); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - goto -> bb5; // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - } - - bb5: { - StorageDead(_6); // scope 4 at $SRC_DIR/core/src/convert/num.rs:LL:COL - StorageLive(_10); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - _9 = discriminant(_5); // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - switchInt(move _9) -> [0: bb8, 1: bb6, otherwise: bb7]; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - } - - bb6: { - _4 = Option::::None; // scope 8 at $SRC_DIR/core/src/result.rs:LL:COL - goto -> bb1; // scope 7 at $SRC_DIR/core/src/result.rs:LL:COL - } - - bb7: { - unreachable; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - } - - bb8: { - _10 = move ((_5 as Ok).0: i16); // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - _4 = Option::::Some(move _10); // scope 6 at $SRC_DIR/core/src/result.rs:LL:COL - goto -> bb1; // scope 5 at $SRC_DIR/core/src/result.rs:LL:COL - } - - bb9: { - _3 = move ((_4 as Some).0: i16); // scope 9 at $SRC_DIR/core/src/option.rs:LL:COL - StorageDead(_11); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - StorageDead(_4); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - _0 = unchecked_shr::(_1, move _3) -> [return: bb2, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - // mir::Constant - // + span: $SRC_DIR/core/src/num/int_macros.rs:LL:COL - // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(i16, i16) -> i16 {unchecked_shr::}, val: Value() } - } } From 1ee189cde53a4cecd3e8811d6ffe983676a70c7b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 16 Apr 2023 19:36:50 +0000 Subject: [PATCH 073/228] Encode def span for ConstParam --- compiler/rustc_metadata/src/rmeta/encoder.rs | 4 ++-- ...foreign-generic-mismatch-with-const-arg.rs | 1 + ...foreign-generic-mismatch-with-const-arg.rs | 8 +++++++ ...ign-generic-mismatch-with-const-arg.stderr | 21 +++++++++++++++++++ 4 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 tests/ui/consts/auxiliary/foreign-generic-mismatch-with-const-arg.rs create mode 100644 tests/ui/consts/foreign-generic-mismatch-with-const-arg.rs create mode 100644 tests/ui/consts/foreign-generic-mismatch-with-const-arg.stderr diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 657b903e0a8af..1109e308cf0bf 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -823,6 +823,7 @@ fn should_encode_span(def_kind: DefKind) -> bool { | DefKind::TraitAlias | DefKind::AssocTy | DefKind::TyParam + | DefKind::ConstParam | DefKind::Fn | DefKind::Const | DefKind::Static(_) @@ -837,8 +838,7 @@ fn should_encode_span(def_kind: DefKind) -> bool { | DefKind::Impl { .. } | DefKind::Closure | DefKind::Generator => true, - DefKind::ConstParam - | DefKind::ExternCrate + DefKind::ExternCrate | DefKind::Use | DefKind::ForeignMod | DefKind::ImplTraitPlaceholder diff --git a/tests/ui/consts/auxiliary/foreign-generic-mismatch-with-const-arg.rs b/tests/ui/consts/auxiliary/foreign-generic-mismatch-with-const-arg.rs new file mode 100644 index 0000000000000..85b0c6c9df8b1 --- /dev/null +++ b/tests/ui/consts/auxiliary/foreign-generic-mismatch-with-const-arg.rs @@ -0,0 +1 @@ +pub fn test() {} diff --git a/tests/ui/consts/foreign-generic-mismatch-with-const-arg.rs b/tests/ui/consts/foreign-generic-mismatch-with-const-arg.rs new file mode 100644 index 0000000000000..7590abbd827b1 --- /dev/null +++ b/tests/ui/consts/foreign-generic-mismatch-with-const-arg.rs @@ -0,0 +1,8 @@ +// aux-build: foreign-generic-mismatch-with-const-arg.rs + +extern crate foreign_generic_mismatch_with_const_arg; + +fn main() { + foreign_generic_mismatch_with_const_arg::test::<1>(); + //~^ ERROR function takes 2 generic arguments but 1 generic argument was supplied +} diff --git a/tests/ui/consts/foreign-generic-mismatch-with-const-arg.stderr b/tests/ui/consts/foreign-generic-mismatch-with-const-arg.stderr new file mode 100644 index 0000000000000..4cc03a20514aa --- /dev/null +++ b/tests/ui/consts/foreign-generic-mismatch-with-const-arg.stderr @@ -0,0 +1,21 @@ +error[E0107]: function takes 2 generic arguments but 1 generic argument was supplied + --> $DIR/foreign-generic-mismatch-with-const-arg.rs:6:46 + | +LL | foreign_generic_mismatch_with_const_arg::test::<1>(); + | ^^^^ - supplied 1 generic argument + | | + | expected 2 generic arguments + | +note: function defined here, with 2 generic parameters: `N`, `T` + --> $DIR/auxiliary/foreign-generic-mismatch-with-const-arg.rs:1:8 + | +LL | pub fn test() {} + | ^^^^ -------------- - +help: add missing generic argument + | +LL | foreign_generic_mismatch_with_const_arg::test::<1, T>(); + | +++ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0107`. From 010067818848e57506a712e4d5595c9f8330a313 Mon Sep 17 00:00:00 2001 From: Josh Soref <2119212+jsoref@users.noreply.github.com> Date: Sun, 9 Apr 2023 19:18:15 -0400 Subject: [PATCH 074/228] Spelling misc * environment * nonexistent * potential * prefixes * stabilization * suffixes * use Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> --- .github/ISSUE_TEMPLATE/library_tracking_issue.md | 4 ++-- RELEASES.md | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/library_tracking_issue.md b/.github/ISSUE_TEMPLATE/library_tracking_issue.md index 91c06402ca10a..934312662beb6 100644 --- a/.github/ISSUE_TEMPLATE/library_tracking_issue.md +++ b/.github/ISSUE_TEMPLATE/library_tracking_issue.md @@ -12,7 +12,7 @@ Tracking issues are for tracking a feature from implementation to stabilization. Make sure to include the relevant RFC for the feature if it has one. If the new feature is small, it may be fine to skip the RFC process. In that -case, you can use use `issue = "none"` in your initial implementation PR. The +case, you can use `issue = "none"` in your initial implementation PR. The reviewer will ask you to open a tracking issue if they agree your feature can be added without an RFC. --> @@ -65,7 +65,7 @@ the rfcbot will ask all the team members to verify they agree with stabilization. Once enough members agree and there are no concerns, the final comment period begins: this issue will be marked as such and will be listed in the next This Week in Rust newsletter. If no blocking concerns are raised in -that period of 10 days, a stabilzation PR can be opened by anyone. +that period of 10 days, a stabilization PR can be opened by anyone. --> ### Unresolved Questions diff --git a/RELEASES.md b/RELEASES.md index b89178a6f68fe..699735de6fb4d 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -963,7 +963,7 @@ Compatibility Notes - [rustdoc: doctests are now run on unexported `macro_rules!` macros, matching other private items][96630] - [rustdoc: Remove .woff font files][96279] - [Enforce Copy bounds for repeat elements while considering lifetimes][95819] -- [Windows: Fix potentinal unsoundness by aborting if `File` reads or writes cannot +- [Windows: Fix potential unsoundness by aborting if `File` reads or writes cannot complete synchronously][95469]. Internal Changes @@ -1794,10 +1794,10 @@ Libraries - [impl Default, Copy, Clone for std::io::Sink and std::io::Empty][rust#86744] - [`impl From<[(K, V); N]>` for all collections.][rust#84111] - [Remove `P: Unpin` bound on impl Future for Pin.][rust#81363] -- [Treat invalid environment variable names as non-existent.][rust#86183] +- [Treat invalid environment variable names as nonexistent.][rust#86183] Previously, the environment functions would panic if given a variable name with an internal null character or equal sign (`=`). Now, these functions will - just treat such names as non-existent variables, since the OS cannot represent + just treat such names as nonexistent variables, since the OS cannot represent the existence of a variable with such a name. Stabilised APIs @@ -1990,7 +1990,7 @@ Compatibility Notes kinds of errors could be categorised [into newer more specific `ErrorKind` variants][79965], and that they do not represent a user error. - [Using environment variable names with `process::Command` on Windows now - behaves as expected.][85270] Previously using envionment variables with + behaves as expected.][85270] Previously using environment variables with `Command` would cause them to be ASCII-uppercased. - [Rustdoc will now warn on using rustdoc lints that aren't prefixed with `rustdoc::`][86849] @@ -6367,7 +6367,7 @@ eg. `static MINUTE: Duration = Duration::from_secs(60);` Cargo ----- -- [`cargo new` no longer removes `rust` or `rs` prefixs/suffixs.][cargo/5013] +- [`cargo new` no longer removes `rust` or `rs` prefixes/suffixes.][cargo/5013] - [`cargo new` now defaults to creating a binary crate, instead of a library crate.][cargo/5029] From 85653831f7b11b969a099b61e3736a85ea26ce66 Mon Sep 17 00:00:00 2001 From: kadiwa Date: Mon, 17 Apr 2023 09:16:07 +0200 Subject: [PATCH 075/228] typos --- compiler/rustc_lint/messages.ftl | 2 +- compiler/rustc_lint/src/builtin.rs | 2 +- library/core/src/ptr/const_ptr.rs | 6 +++--- library/core/src/ptr/mut_ptr.rs | 6 +++--- tests/codegen/optimize-attr-1.rs | 2 +- .../{borrowck-block-unint.rs => borrowck-block-uninit.rs} | 0 ...owck-block-unint.stderr => borrowck-block-uninit.stderr} | 2 +- 7 files changed, 10 insertions(+), 10 deletions(-) rename tests/ui/borrowck/{borrowck-block-unint.rs => borrowck-block-uninit.rs} (100%) rename tests/ui/borrowck/{borrowck-block-unint.stderr => borrowck-block-uninit.stderr} (92%) diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index db15b176df001..3d1b8f8ed95ac 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -445,7 +445,7 @@ lint_builtin_incomplete_features = the feature `{$name}` is incomplete and may n .help = consider using `min_{$name}` instead, which is more stable and complete lint_builtin_unpermitted_type_init_zeroed = the type `{$ty}` does not permit zero-initialization -lint_builtin_unpermitted_type_init_unint = the type `{$ty}` does not permit being left uninitialized +lint_builtin_unpermitted_type_init_uninit = the type `{$ty}` does not permit being left uninitialized lint_builtin_unpermitted_type_init_label = this code causes undefined behavior when executed lint_builtin_unpermitted_type_init_label_suggestion = help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 6b387df785e7d..09c05cdfa8100 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2628,7 +2628,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { if let Some(err) = with_no_trimmed_paths!(ty_find_init_error(cx, conjured_ty, init)) { let msg = match init { InitKind::Zeroed => fluent::lint_builtin_unpermitted_type_init_zeroed, - InitKind::Uninit => fluent::lint_builtin_unpermitted_type_init_unint, + InitKind::Uninit => fluent::lint_builtin_unpermitted_type_init_uninit, }; let sub = BuiltinUnpermittedTypeInitSub { err }; cx.emit_spanned_lint( diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 839afc57f85d2..3838c39cc6a60 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -132,8 +132,8 @@ impl *const T { /// ``` #[unstable(feature = "ptr_to_from_bits", issue = "91126")] #[deprecated( - since = "1.67", - note = "replaced by the `exposed_addr` method, or update your code \ + since = "1.67.0", + note = "replaced by the `expose_addr` method, or update your code \ to follow the strict provenance rules using its APIs" )] #[inline(always)] @@ -161,7 +161,7 @@ impl *const T { /// ``` #[unstable(feature = "ptr_to_from_bits", issue = "91126")] #[deprecated( - since = "1.67", + since = "1.67.0", note = "replaced by the `ptr::from_exposed_addr` function, or update \ your code to follow the strict provenance rules using its APIs" )] diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index ece5244e9a99c..e522b6dc15cc6 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -138,8 +138,8 @@ impl *mut T { /// ``` #[unstable(feature = "ptr_to_from_bits", issue = "91126")] #[deprecated( - since = "1.67", - note = "replaced by the `exposed_addr` method, or update your code \ + since = "1.67.0", + note = "replaced by the `expose_addr` method, or update your code \ to follow the strict provenance rules using its APIs" )] #[inline(always)] @@ -167,7 +167,7 @@ impl *mut T { /// ``` #[unstable(feature = "ptr_to_from_bits", issue = "91126")] #[deprecated( - since = "1.67", + since = "1.67.0", note = "replaced by the `ptr::from_exposed_addr_mut` function, or \ update your code to follow the strict provenance rules using its APIs" )] diff --git a/tests/codegen/optimize-attr-1.rs b/tests/codegen/optimize-attr-1.rs index 1d1f0a38657f3..d95ba853030ff 100644 --- a/tests/codegen/optimize-attr-1.rs +++ b/tests/codegen/optimize-attr-1.rs @@ -9,7 +9,7 @@ // CHECK-LABEL: define{{.*}}i32 @nothing // CHECK-SAME: [[NOTHING_ATTRS:#[0-9]+]] // SIZE-OPT: ret i32 4 -// SPEEC-OPT: ret i32 4 +// SPEED-OPT: ret i32 4 #[no_mangle] pub fn nothing() -> i32 { 2 + 2 diff --git a/tests/ui/borrowck/borrowck-block-unint.rs b/tests/ui/borrowck/borrowck-block-uninit.rs similarity index 100% rename from tests/ui/borrowck/borrowck-block-unint.rs rename to tests/ui/borrowck/borrowck-block-uninit.rs diff --git a/tests/ui/borrowck/borrowck-block-unint.stderr b/tests/ui/borrowck/borrowck-block-uninit.stderr similarity index 92% rename from tests/ui/borrowck/borrowck-block-unint.stderr rename to tests/ui/borrowck/borrowck-block-uninit.stderr index f47921a975269..1a5969586f239 100644 --- a/tests/ui/borrowck/borrowck-block-unint.stderr +++ b/tests/ui/borrowck/borrowck-block-uninit.stderr @@ -1,5 +1,5 @@ error[E0381]: used binding `x` isn't initialized - --> $DIR/borrowck-block-unint.rs:4:11 + --> $DIR/borrowck-block-uninit.rs:4:11 | LL | let x: isize; | - binding declared here but left uninitialized From 4cd0e00655ccb88605c3bc4124edd1d6a5b3f011 Mon Sep 17 00:00:00 2001 From: Pietro Albini Date: Mon, 17 Apr 2023 09:42:45 +0200 Subject: [PATCH 076/228] avoid including dry run steps in the build metrics Including steps executed during the dry run will result in a duplication of all the steps in the build metrics, which just adds noise. --- src/bootstrap/builder.rs | 4 ++-- src/bootstrap/metrics.rs | 23 +++++++++++++++++++---- src/bootstrap/render_tests.rs | 1 + 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index ade8fa4c74dcb..3a50bf5c4dbaf 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -2010,7 +2010,7 @@ impl<'a> Builder<'a> { } #[cfg(feature = "build-metrics")] - self.metrics.enter_step(&step); + self.metrics.enter_step(&step, self); let (out, dur) = { let start = Instant::now(); @@ -2036,7 +2036,7 @@ impl<'a> Builder<'a> { } #[cfg(feature = "build-metrics")] - self.metrics.exit_step(); + self.metrics.exit_step(self); { let mut stack = self.stack.borrow_mut(); diff --git a/src/bootstrap/metrics.rs b/src/bootstrap/metrics.rs index 82b123ec8a5e1..e19d56ccd6adc 100644 --- a/src/bootstrap/metrics.rs +++ b/src/bootstrap/metrics.rs @@ -4,7 +4,7 @@ //! As this module requires additional dependencies not present during local builds, it's cfg'd //! away whenever the `build.metrics` config option is not set to `true`. -use crate::builder::Step; +use crate::builder::{Builder, Step}; use crate::util::t; use crate::Build; use serde_derive::{Deserialize, Serialize}; @@ -33,7 +33,12 @@ impl BuildMetrics { BuildMetrics { state } } - pub(crate) fn enter_step(&self, step: &S) { + pub(crate) fn enter_step(&self, step: &S, builder: &Builder<'_>) { + // Do not record dry runs, as they'd be duplicates of the actual steps. + if builder.config.dry_run() { + return; + } + let mut state = self.state.borrow_mut(); // Consider all the stats gathered so far as the parent's. @@ -56,7 +61,12 @@ impl BuildMetrics { }); } - pub(crate) fn exit_step(&self) { + pub(crate) fn exit_step(&self, builder: &Builder<'_>) { + // Do not record dry runs, as they'd be duplicates of the actual steps. + if builder.config.dry_run() { + return; + } + let mut state = self.state.borrow_mut(); self.collect_stats(&mut *state); @@ -74,7 +84,12 @@ impl BuildMetrics { } } - pub(crate) fn record_test(&self, name: &str, outcome: TestOutcome) { + pub(crate) fn record_test(&self, name: &str, outcome: TestOutcome, builder: &Builder<'_>) { + // Do not record dry runs, as they'd be duplicates of the actual steps. + if builder.config.dry_run() { + return; + } + let mut state = self.state.borrow_mut(); state .running_steps diff --git a/src/bootstrap/render_tests.rs b/src/bootstrap/render_tests.rs index 19019ad2c089d..a56db9cccfe5b 100644 --- a/src/bootstrap/render_tests.rs +++ b/src/bootstrap/render_tests.rs @@ -124,6 +124,7 @@ impl<'a> Renderer<'a> { ignore_reason: reason.map(|s| s.to_string()), }, }, + self.builder, ); if self.builder.config.verbose_tests { From a091fd25cae34ebdc3f158e623743d51428952ff Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sat, 15 Apr 2023 12:07:30 +0200 Subject: [PATCH 077/228] Add list of supported disambiguators and suffixes for intra-doc links in the rustdoc book --- .../src/write-documentation/linking-to-items-by-name.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) 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 eb2285ef90646..72157b5cd9bce 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 @@ -88,13 +88,16 @@ fn Foo() {} ``` These prefixes will be stripped when displayed in the documentation, so `[struct@Foo]` will be -rendered as `Foo`. +rendered as `Foo`. The following prefixes are available: `struct`, `enum`, `trait`, `union`, +`mod`, `module`, `const`, `constant`, `fn`, `function`, `method`, `derive`, `type`, `value`, +`macro`, `prim` or `primitive`. You can also disambiguate for functions by adding `()` after the function name, -or for macros by adding `!` after the macro name: +or for macros by adding `!` after the macro name. The macro `!` can be followed by `()`, `{}`, +or `[]`. Example: ```rust -/// This is different from [`foo!`] +/// This is different from [`foo!()`]. fn foo() {} /// This is different from [`foo()`] From 1531c95c5d3f4e9ef4cfc122c35947e7b9cca53e Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sat, 15 Apr 2023 15:52:27 +0200 Subject: [PATCH 078/228] Add code comment to remind contributors to update rustdoc book if they update the disambiguators list --- src/librustdoc/passes/collect_intra_doc_links.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 2cd9c8a878187..3b7226df65a3d 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -1419,6 +1419,7 @@ impl Disambiguator { if let Some(idx) = link.find('@') { let (prefix, rest) = link.split_at(idx); let d = match prefix { + // If you update this list, please also update the relevant rustdoc book section! "struct" => Kind(DefKind::Struct), "enum" => Kind(DefKind::Enum), "trait" => Kind(DefKind::Trait), @@ -1437,6 +1438,7 @@ impl Disambiguator { Ok(Some((d, &rest[1..], &rest[1..]))) } else { let suffixes = [ + // If you update this list, please also update the relevant rustdoc book section! ("!()", DefKind::Macro(MacroKind::Bang)), ("!{}", DefKind::Macro(MacroKind::Bang)), ("![]", DefKind::Macro(MacroKind::Bang)), From f91d02b153a357b9937d6a5193db931076795deb Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 17 Apr 2023 11:13:29 +0200 Subject: [PATCH 079/228] Remove unused RustdocVisitor::visit_item_inner return type --- src/librustdoc/visit_ast.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 393d51fe09069..5ac68da150a9a 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -331,7 +331,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { item: &'tcx hir::Item<'_>, renamed: Option, import_id: Option, - ) -> bool { + ) { debug!("visiting item {:?}", item); let name = renamed.unwrap_or(item.ident.name); let tcx = self.cx.tcx; @@ -448,7 +448,6 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { } } } - true } fn visit_foreign_item_inner( @@ -485,9 +484,8 @@ impl<'a, 'tcx> Visitor<'tcx> for RustdocVisitor<'a, 'tcx> { } fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) { - if self.visit_item_inner(i, None, None) { - walk_item(self, i); - } + self.visit_item_inner(i, None, None); + walk_item(self, i); } fn visit_mod(&mut self, _: &hir::Mod<'tcx>, _: Span, _: hir::HirId) { From dd025c3b562bf00aae462b0c77b7d2ba1f8fad93 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 17 Apr 2023 08:22:16 +0000 Subject: [PATCH 080/228] fix codegen difference --- library/core/src/num/int_macros.rs | 6 ++--- library/core/src/num/mod.rs | 18 ++++++++++++++ library/core/src/num/uint_macros.rs | 6 ++--- ...unchecked_shl_unsigned_smaller.Inline.diff | 24 +++++++++++++------ ..._shl_unsigned_smaller.PreCodegen.after.mir | 22 ++++++++++++----- ...s.unchecked_shr_signed_smaller.Inline.diff | 24 +++++++++++++------ ...ed_shr_signed_smaller.PreCodegen.after.mir | 22 ++++++++++++----- 7 files changed, 88 insertions(+), 34 deletions(-) diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index 1e82d4d1ff0bb..17715c9291fee 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -785,8 +785,7 @@ macro_rules! int_impl { // SAFETY: the caller must uphold the safety contract for // `unchecked_shl`. // Any legal shift amount is losslessly representable in the self type. - // FIXME(const-hack) replace with `.try_into().ok().unwrap_unchecked()`. - unsafe { intrinsics::unchecked_shl(self, rhs as _) } + unsafe { intrinsics::unchecked_shl(self, conv_rhs_for_unchecked_shift!($SelfT, rhs)) } } /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is @@ -834,8 +833,7 @@ macro_rules! int_impl { // SAFETY: the caller must uphold the safety contract for // `unchecked_shr`. // Any legal shift amount is losslessly representable in the self type. - // FIXME(const-hack) replace with `.try_into().ok().unwrap_unchecked()`. - unsafe { intrinsics::unchecked_shr(self, rhs as _) } + unsafe { intrinsics::unchecked_shr(self, conv_rhs_for_unchecked_shift!($SelfT, rhs)) } } /// Checked absolute value. Computes `self.abs()`, returning `None` if diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index b0488dc069b79..fdd7be625ed93 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -3,6 +3,7 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::ascii; +use crate::convert::TryInto; use crate::intrinsics; use crate::mem; use crate::ops::{Add, Mul, Sub}; @@ -224,6 +225,23 @@ macro_rules! widening_impl { }; } +macro_rules! conv_rhs_for_unchecked_shift { + ($SelfT:ty, $x:expr) => {{ + #[inline] + fn conv(x: u32) -> $SelfT { + // FIXME(const-hack) replace with `.try_into().ok().unwrap_unchecked()`. + // SAFETY: Any legal shift amount must be losslessly representable in the self type. + unsafe { x.try_into().ok().unwrap_unchecked() } + } + #[inline] + const fn const_conv(x: u32) -> $SelfT { + x as _ + } + + intrinsics::const_eval_select(($x,), const_conv, conv) + }}; +} + impl i8 { int_impl! { Self = i8, diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index 795645b8b7b87..6f6b6dbb80b3f 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -939,8 +939,7 @@ macro_rules! uint_impl { // SAFETY: the caller must uphold the safety contract for // `unchecked_shl`. // Any legal shift amount is losslessly representable in the self type. - // FIXME(const-hack) replace with `.try_into().ok().unwrap_unchecked()`. - unsafe { intrinsics::unchecked_shl(self, rhs as _) } + unsafe { intrinsics::unchecked_shl(self, conv_rhs_for_unchecked_shift!($SelfT, rhs)) } } /// Checked shift right. Computes `self >> rhs`, returning `None` @@ -988,8 +987,7 @@ macro_rules! uint_impl { // SAFETY: the caller must uphold the safety contract for // `unchecked_shr`. // Any legal shift amount is losslessly representable in the self type. - // FIXME(const-hack) replace with `.try_into().ok().unwrap_unchecked()`. - unsafe { intrinsics::unchecked_shr(self, rhs as _) } + unsafe { intrinsics::unchecked_shr(self, conv_rhs_for_unchecked_shift!($SelfT, rhs)) } } /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if diff --git a/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.Inline.diff b/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.Inline.diff index 082e3884d9e64..473e02f1cb1c8 100644 --- a/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.Inline.diff +++ b/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.Inline.diff @@ -10,7 +10,8 @@ + scope 1 (inlined core::num::::unchecked_shl) { // at $DIR/unchecked_shifts.rs:11:7: 11:23 + debug self => _3; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + debug rhs => _4; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ let mut _5: u16; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL ++ let mut _5: u16; // in scope 1 at $SRC_DIR/core/src/num/mod.rs:LL:COL ++ let mut _6: (u32,); // in scope 1 at $SRC_DIR/core/src/num/mod.rs:LL:COL + scope 2 { + } + } @@ -21,18 +22,27 @@ StorageLive(_4); // scope 0 at $DIR/unchecked_shifts.rs:+1:21: +1:22 _4 = _2; // scope 0 at $DIR/unchecked_shifts.rs:+1:21: +1:22 - _0 = core::num::::unchecked_shl(move _3, move _4) -> bb1; // scope 0 at $DIR/unchecked_shifts.rs:+1:5: +1:23 -+ StorageLive(_5); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 -+ _5 = _4 as u16 (IntToInt); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ _0 = unchecked_shl::(_3, _5) -> [return: bb1, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL ++ StorageLive(_5); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL ++ StorageLive(_6); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL ++ _6 = (_4,); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL ++ _5 = core::num::::unchecked_shl::conv(move (_6.0: u32)) -> bb1; // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL // mir::Constant - // + span: $DIR/unchecked_shifts.rs:11:7: 11:20 - // + literal: Const { ty: unsafe fn(u16, u32) -> u16 {core::num::::unchecked_shl}, val: Value() } -+ // + span: $SRC_DIR/core/src/num/uint_macros.rs:LL:COL -+ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(u16, u16) -> u16 {unchecked_shl::}, val: Value() } ++ // + span: $SRC_DIR/core/src/num/mod.rs:LL:COL ++ // + literal: Const { ty: fn(u32) -> u16 {core::num::::unchecked_shl::conv}, val: Value() } } bb1: { -+ StorageDead(_5); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 ++ StorageDead(_6); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL ++ _0 = unchecked_shl::(_3, move _5) -> [return: bb2, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL ++ // mir::Constant ++ // + span: $SRC_DIR/core/src/num/uint_macros.rs:LL:COL ++ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(u16, u16) -> u16 {unchecked_shl::}, val: Value() } ++ } ++ ++ bb2: { ++ StorageDead(_5); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL StorageDead(_4); // scope 0 at $DIR/unchecked_shifts.rs:+1:22: +1:23 StorageDead(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:22: +1:23 return; // scope 0 at $DIR/unchecked_shifts.rs:+2:2: +2:2 diff --git a/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.PreCodegen.after.mir b/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.PreCodegen.after.mir index e12ca38e2cf2f..9b7b11ef659aa 100644 --- a/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.PreCodegen.after.mir +++ b/tests/mir-opt/inline/unchecked_shifts.unchecked_shl_unsigned_smaller.PreCodegen.after.mir @@ -7,22 +7,32 @@ fn unchecked_shl_unsigned_smaller(_1: u16, _2: u32) -> u16 { scope 1 (inlined core::num::::unchecked_shl) { // at $DIR/unchecked_shifts.rs:11:7: 11:23 debug self => _1; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL debug rhs => _2; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - let mut _3: u16; // in scope 1 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + let mut _3: u16; // in scope 1 at $SRC_DIR/core/src/num/mod.rs:LL:COL + let mut _4: (u32,); // in scope 1 at $SRC_DIR/core/src/num/mod.rs:LL:COL scope 2 { } } bb0: { - StorageLive(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 - _3 = _2 as u16 (IntToInt); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL - _0 = unchecked_shl::(_1, _3) -> [return: bb1, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL + StorageLive(_3); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL + StorageLive(_4); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL + _4 = (_2,); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL + _3 = core::num::::unchecked_shl::conv(move (_4.0: u32)) -> bb1; // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL + // mir::Constant + // + span: $SRC_DIR/core/src/num/mod.rs:LL:COL + // + literal: Const { ty: fn(u32) -> u16 {core::num::::unchecked_shl::conv}, val: Value() } + } + + bb1: { + StorageDead(_4); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL + _0 = unchecked_shl::(_1, move _3) -> [return: bb2, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL // mir::Constant // + span: $SRC_DIR/core/src/num/uint_macros.rs:LL:COL // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(u16, u16) -> u16 {unchecked_shl::}, val: Value() } } - bb1: { - StorageDead(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 + bb2: { + StorageDead(_3); // scope 2 at $SRC_DIR/core/src/num/uint_macros.rs:LL:COL return; // scope 0 at $DIR/unchecked_shifts.rs:+2:2: +2:2 } } diff --git a/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.Inline.diff b/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.Inline.diff index ca9f4c96eb267..9638ddda46b71 100644 --- a/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.Inline.diff +++ b/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.Inline.diff @@ -10,7 +10,8 @@ + scope 1 (inlined core::num::::unchecked_shr) { // at $DIR/unchecked_shifts.rs:17:7: 17:23 + debug self => _3; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL + debug rhs => _4; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ let mut _5: i16; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL ++ let mut _5: i16; // in scope 1 at $SRC_DIR/core/src/num/mod.rs:LL:COL ++ let mut _6: (u32,); // in scope 1 at $SRC_DIR/core/src/num/mod.rs:LL:COL + scope 2 { + } + } @@ -21,18 +22,27 @@ StorageLive(_4); // scope 0 at $DIR/unchecked_shifts.rs:+1:21: +1:22 _4 = _2; // scope 0 at $DIR/unchecked_shifts.rs:+1:21: +1:22 - _0 = core::num::::unchecked_shr(move _3, move _4) -> bb1; // scope 0 at $DIR/unchecked_shifts.rs:+1:5: +1:23 -+ StorageLive(_5); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 -+ _5 = _4 as i16 (IntToInt); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ _0 = unchecked_shr::(_3, _5) -> [return: bb1, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL ++ StorageLive(_5); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL ++ StorageLive(_6); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL ++ _6 = (_4,); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL ++ _5 = core::num::::unchecked_shr::conv(move (_6.0: u32)) -> bb1; // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL // mir::Constant - // + span: $DIR/unchecked_shifts.rs:17:7: 17:20 - // + literal: Const { ty: unsafe fn(i16, u32) -> i16 {core::num::::unchecked_shr}, val: Value() } -+ // + span: $SRC_DIR/core/src/num/int_macros.rs:LL:COL -+ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(i16, i16) -> i16 {unchecked_shr::}, val: Value() } ++ // + span: $SRC_DIR/core/src/num/mod.rs:LL:COL ++ // + literal: Const { ty: fn(u32) -> i16 {core::num::::unchecked_shr::conv}, val: Value() } } bb1: { -+ StorageDead(_5); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 ++ StorageDead(_6); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL ++ _0 = unchecked_shr::(_3, move _5) -> [return: bb2, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL ++ // mir::Constant ++ // + span: $SRC_DIR/core/src/num/int_macros.rs:LL:COL ++ // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(i16, i16) -> i16 {unchecked_shr::}, val: Value() } ++ } ++ ++ bb2: { ++ StorageDead(_5); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL StorageDead(_4); // scope 0 at $DIR/unchecked_shifts.rs:+1:22: +1:23 StorageDead(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:22: +1:23 return; // scope 0 at $DIR/unchecked_shifts.rs:+2:2: +2:2 diff --git a/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.PreCodegen.after.mir b/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.PreCodegen.after.mir index 42c2c255781fe..afe6d08741b47 100644 --- a/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.PreCodegen.after.mir +++ b/tests/mir-opt/inline/unchecked_shifts.unchecked_shr_signed_smaller.PreCodegen.after.mir @@ -7,22 +7,32 @@ fn unchecked_shr_signed_smaller(_1: i16, _2: u32) -> i16 { scope 1 (inlined core::num::::unchecked_shr) { // at $DIR/unchecked_shifts.rs:17:7: 17:23 debug self => _1; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL debug rhs => _2; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - let mut _3: i16; // in scope 1 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL + let mut _3: i16; // in scope 1 at $SRC_DIR/core/src/num/mod.rs:LL:COL + let mut _4: (u32,); // in scope 1 at $SRC_DIR/core/src/num/mod.rs:LL:COL scope 2 { } } bb0: { - StorageLive(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 - _3 = _2 as i16 (IntToInt); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL - _0 = unchecked_shr::(_1, _3) -> [return: bb1, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL + StorageLive(_3); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL + StorageLive(_4); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL + _4 = (_2,); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL + _3 = core::num::::unchecked_shr::conv(move (_4.0: u32)) -> bb1; // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL + // mir::Constant + // + span: $SRC_DIR/core/src/num/mod.rs:LL:COL + // + literal: Const { ty: fn(u32) -> i16 {core::num::::unchecked_shr::conv}, val: Value() } + } + + bb1: { + StorageDead(_4); // scope 2 at $SRC_DIR/core/src/num/mod.rs:LL:COL + _0 = unchecked_shr::(_1, move _3) -> [return: bb2, unwind unreachable]; // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL // mir::Constant // + span: $SRC_DIR/core/src/num/int_macros.rs:LL:COL // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(i16, i16) -> i16 {unchecked_shr::}, val: Value() } } - bb1: { - StorageDead(_3); // scope 0 at $DIR/unchecked_shifts.rs:+1:7: +1:23 + bb2: { + StorageDead(_3); // scope 2 at $SRC_DIR/core/src/num/int_macros.rs:LL:COL return; // scope 0 at $DIR/unchecked_shifts.rs:+2:2: +2:2 } } From 63d8758d35516d77dc53b5acaf0dc405f2297166 Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Mon, 17 Apr 2023 13:45:11 +0200 Subject: [PATCH 081/228] Force -Zflatten-format-args=no in Clippy. --- src/tools/clippy/src/driver.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/tools/clippy/src/driver.rs b/src/tools/clippy/src/driver.rs index 718bc41fb9924..205905d509135 100644 --- a/src/tools/clippy/src/driver.rs +++ b/src/tools/clippy/src/driver.rs @@ -160,6 +160,9 @@ impl rustc_driver::Callbacks for ClippyCallbacks { // MIR passes can be enabled / disabled separately, we should figure out, what passes to // use for Clippy. config.opts.unstable_opts.mir_opt_level = Some(0); + + // Disable flattening and inlining of format_args!(), so the HIR matches with the AST. + config.opts.unstable_opts.flatten_format_args = false; } } From 2cd5ce08ba2a52da052c8372737245eb6c3c78bd Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Mon, 17 Apr 2023 14:13:37 +0200 Subject: [PATCH 082/228] Update test. --- compiler/rustc_interface/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index 10dfd32d418a2..f5d44d239e034 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -747,7 +747,7 @@ fn test_unstable_options_tracking_hash() { tracked!(emit_thin_lto, false); tracked!(export_executable_symbols, true); tracked!(fewer_names, Some(true)); - tracked!(flatten_format_args, true); + tracked!(flatten_format_args, false); tracked!(force_unstable_if_unmarked, true); tracked!(fuel, Some(("abc".to_string(), 99))); tracked!(function_sections, Some(false)); From c3c9f8f5f8cb96e0536bc8d4e76e66c5e7caba56 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 17 Apr 2023 14:34:50 +0200 Subject: [PATCH 083/228] Fix invalid handling of nested items with `--document-private-items` --- src/librustdoc/visit_ast.rs | 40 ++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index 5ac68da150a9a..071a85f4da6ea 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -10,6 +10,7 @@ use rustc_hir::{Node, CRATE_HIR_ID}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_span::hygiene::MacroKind; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; @@ -87,6 +88,7 @@ pub(crate) struct RustdocVisitor<'a, 'tcx> { inside_public_path: bool, exact_paths: DefIdMap>, modules: Vec>, + is_importable_from_parent: bool, } impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { @@ -107,6 +109,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { inside_public_path: true, exact_paths: Default::default(), modules: vec![om], + is_importable_from_parent: true, } } @@ -319,11 +322,23 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { renamed: Option, parent_id: Option, ) { - self.modules - .last_mut() - .unwrap() - .items - .insert((item.owner_id.def_id, renamed), (item, renamed, parent_id)); + if self.is_importable_from_parent + // If we're inside an item, only impl blocks and `macro_rules!` with the `macro_export` + // attribute can still be visible. + || match item.kind { + hir::ItemKind::Impl(..) => true, + hir::ItemKind::Macro(_, MacroKind::Bang) => { + self.cx.tcx.has_attr(item.owner_id.def_id, sym::macro_export) + } + _ => false, + } + { + self.modules + .last_mut() + .unwrap() + .items + .insert((item.owner_id.def_id, renamed), (item, renamed, parent_id)); + } } fn visit_item_inner( @@ -485,7 +500,22 @@ impl<'a, 'tcx> Visitor<'tcx> for RustdocVisitor<'a, 'tcx> { fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) { self.visit_item_inner(i, None, None); + let new_value = if self.is_importable_from_parent { + matches!( + i.kind, + hir::ItemKind::Mod(..) + | hir::ItemKind::ForeignMod { .. } + | hir::ItemKind::Impl(..) + | hir::ItemKind::Trait(..) + ) + } else { + // Whatever the context, if it's an impl block, the items inside it can be used so they + // should be visible. + matches!(i.kind, hir::ItemKind::Impl(..)) + }; + let prev = mem::replace(&mut self.is_importable_from_parent, new_value); walk_item(self, i); + self.is_importable_from_parent = prev; } fn visit_mod(&mut self, _: &hir::Mod<'tcx>, _: Span, _: hir::HirId) { From 84de04155c3a1d5e9f71c53bc0d93b46e0417b25 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Mon, 17 Apr 2023 12:42:02 +0000 Subject: [PATCH 084/228] add test for invalid places of repr align --- tests/ui/attributes/invalid-repr.rs | 5 +++++ tests/ui/attributes/invalid-repr.stderr | 12 ++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 tests/ui/attributes/invalid-repr.rs create mode 100644 tests/ui/attributes/invalid-repr.stderr diff --git a/tests/ui/attributes/invalid-repr.rs b/tests/ui/attributes/invalid-repr.rs new file mode 100644 index 0000000000000..10a487c127ec8 --- /dev/null +++ b/tests/ui/attributes/invalid-repr.rs @@ -0,0 +1,5 @@ +#[repr(align(16))] +//~^ ERROR attribute should be applied to a struct, enum, function, associated function, or union +pub type Foo = i32; + +fn main() {} diff --git a/tests/ui/attributes/invalid-repr.stderr b/tests/ui/attributes/invalid-repr.stderr new file mode 100644 index 0000000000000..98a6a24b3c42c --- /dev/null +++ b/tests/ui/attributes/invalid-repr.stderr @@ -0,0 +1,12 @@ +error[E0517]: attribute should be applied to a struct, enum, function, associated function, or union + --> $DIR/invalid-repr.rs:1:8 + | +LL | #[repr(align(16))] + | ^^^^^^^^^ +LL | +LL | pub type Foo = i32; + | ------------------- not a struct, enum, function, associated function, or union + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0517`. From 69279c0584a1ee78100678062fd5a12ed1beaec3 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Fri, 14 Apr 2023 19:55:25 -0400 Subject: [PATCH 085/228] Bypass the varint path when encoding InitMask --- .../src/mir/interpret/allocation/init_mask.rs | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs b/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs index dcb56a1755e45..d4dd56a42c1ed 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs @@ -5,7 +5,9 @@ use std::hash; use std::iter; use std::ops::Range; +use rustc_serialize::{Decodable, Encodable}; use rustc_target::abi::Size; +use rustc_type_ir::{TyDecoder, TyEncoder}; use super::AllocRange; @@ -182,11 +184,39 @@ impl InitMask { /// The actual materialized blocks of the bitmask, when we can't keep the `InitMask` lazy. // Note: for performance reasons when interning, some of the fields can be partially // hashed. (see the `Hash` impl below for more details), so the impl is not derived. -#[derive(Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, HashStable)] +#[derive(Clone, Debug, Eq, PartialEq, HashStable)] struct InitMaskMaterialized { blocks: Vec, } +// `Block` is a `u64`, but it is a bitmask not a numeric value. If we were to just derive +// Encodable and Decodable we would apply varint encoding to the bitmasks, which is slower +// and also produces more output when the high bits of each `u64` are occupied. +// Note: There is probably a remaining optimization for masks that do not use an entire +// `Block`. +impl Encodable for InitMaskMaterialized { + fn encode(&self, encoder: &mut E) { + encoder.emit_usize(self.blocks.len()); + for block in &self.blocks { + encoder.emit_raw_bytes(&block.to_le_bytes()); + } + } +} + +// This implementation is deliberately not derived, see the matching `Encodable` impl. +impl Decodable for InitMaskMaterialized { + fn decode(decoder: &mut D) -> Self { + let num_blocks = decoder.read_usize(); + let mut blocks = Vec::with_capacity(num_blocks); + for _ in 0..num_blocks { + let bytes = decoder.read_raw_bytes(8); + let block = u64::from_le_bytes(bytes.try_into().unwrap()); + blocks.push(block); + } + InitMaskMaterialized { blocks } + } +} + // Const allocations are only hashed for interning. However, they can be large, making the hashing // expensive especially since it uses `FxHash`: it's better suited to short keys, not potentially // big buffers like the allocation's init mask. We can partially hash some fields when they're From e1cd99f6ff2bc2aecec530801b8a71d898bff309 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Mon, 17 Apr 2023 13:14:03 +0000 Subject: [PATCH 086/228] Make `IndexVec::ensure_contains_elem` return a reference to the element --- compiler/rustc_ast_lowering/src/item.rs | 10 +++++----- compiler/rustc_ast_lowering/src/lib.rs | 15 +++++++-------- .../src/generator_interior/drop_ranges/mod.rs | 3 +-- compiler/rustc_index/src/interval.rs | 3 +-- compiler/rustc_index/src/vec.rs | 15 ++++++++------- compiler/rustc_metadata/src/rmeta/table.rs | 4 ++-- 6 files changed, 24 insertions(+), 26 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index f89e254a2f54d..c061a244cf50a 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -89,9 +89,9 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { lctx.with_hir_id_owner(owner, |lctx| f(lctx)); for (def_id, info) in lctx.children { - self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom); - debug_assert!(matches!(self.owners[def_id], hir::MaybeOwner::Phantom)); - self.owners[def_id] = info; + let owner = self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom); + debug_assert!(matches!(owner, hir::MaybeOwner::Phantom)); + *owner = info; } } @@ -99,8 +99,8 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { &mut self, def_id: LocalDefId, ) -> hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>> { - self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom); - if let hir::MaybeOwner::Phantom = self.owners[def_id] { + let owner = self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom); + if let hir::MaybeOwner::Phantom = owner { let node = self.ast_index[def_id]; match node { AstOwner::NonOwner => {} diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 2af47e11637c5..537c2a0618348 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -368,8 +368,8 @@ fn index_crate<'a>( krate: &'a Crate, ) -> IndexVec> { let mut indexer = Indexer { node_id_to_def_id, index: IndexVec::new() }; - indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner); - indexer.index[CRATE_DEF_ID] = AstOwner::Crate(krate); + *indexer.index.ensure_contains_elem(CRATE_DEF_ID, || AstOwner::NonOwner) = + AstOwner::Crate(krate); visit::walk_crate(&mut indexer, krate); return indexer.index; @@ -386,22 +386,21 @@ fn index_crate<'a>( fn visit_item(&mut self, item: &'a ast::Item) { let def_id = self.node_id_to_def_id[&item.id]; - self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner); - self.index[def_id] = AstOwner::Item(item); + *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = AstOwner::Item(item); visit::walk_item(self, item) } fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: visit::AssocCtxt) { let def_id = self.node_id_to_def_id[&item.id]; - self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner); - self.index[def_id] = AstOwner::AssocItem(item, ctxt); + *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = + AstOwner::AssocItem(item, ctxt); visit::walk_assoc_item(self, item, ctxt); } fn visit_foreign_item(&mut self, item: &'a ast::ForeignItem) { let def_id = self.node_id_to_def_id[&item.id]; - self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner); - self.index[def_id] = AstOwner::ForeignItem(item); + *self.index.ensure_contains_elem(def_id, || AstOwner::NonOwner) = + AstOwner::ForeignItem(item); visit::walk_foreign_item(self, item); } } diff --git a/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs b/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs index f7b493bc2242b..d3685d21f2521 100644 --- a/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs +++ b/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs @@ -268,8 +268,7 @@ impl DropRangesBuilder { fn node_mut(&mut self, id: PostOrderId) -> &mut NodeInfo { let size = self.num_values(); - self.nodes.ensure_contains_elem(id, || NodeInfo::new(size)); - &mut self.nodes[id] + self.nodes.ensure_contains_elem(id, || NodeInfo::new(size)) } fn add_control_edge(&mut self, from: PostOrderId, to: PostOrderId) { diff --git a/compiler/rustc_index/src/interval.rs b/compiler/rustc_index/src/interval.rs index d809740c6ab31..4605d42a15b7d 100644 --- a/compiler/rustc_index/src/interval.rs +++ b/compiler/rustc_index/src/interval.rs @@ -261,8 +261,7 @@ impl SparseIntervalMatrix { } fn ensure_row(&mut self, row: R) -> &mut IntervalSet { - self.rows.ensure_contains_elem(row, || IntervalSet::new(self.column_size)); - &mut self.rows[row] + self.rows.ensure_contains_elem(row, || IntervalSet::new(self.column_size)) } pub fn union_row(&mut self, row: R, from: &IntervalSet) -> bool diff --git a/compiler/rustc_index/src/vec.rs b/compiler/rustc_index/src/vec.rs index ae2f52c513e9f..95600f7bcf16f 100644 --- a/compiler/rustc_index/src/vec.rs +++ b/compiler/rustc_index/src/vec.rs @@ -236,12 +236,16 @@ impl IndexVec { /// `elem`; if that is already true, then has no /// effect. Otherwise, inserts new values as needed by invoking /// `fill_value`. + /// + /// Returns a reference to the `elem` entry. #[inline] - pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) { + pub fn ensure_contains_elem(&mut self, elem: I, fill_value: impl FnMut() -> T) -> &mut T { let min_new_len = elem.index() + 1; if self.len() < min_new_len { self.raw.resize_with(min_new_len, fill_value); } + + &mut self[elem] } #[inline] @@ -446,20 +450,17 @@ impl IndexSlice { impl IndexVec> { #[inline] pub fn insert(&mut self, index: I, value: T) -> Option { - self.ensure_contains_elem(index, || None); - self[index].replace(value) + self.ensure_contains_elem(index, || None).replace(value) } #[inline] pub fn get_or_insert_with(&mut self, index: I, value: impl FnOnce() -> T) -> &mut T { - self.ensure_contains_elem(index, || None); - self[index].get_or_insert_with(value) + self.ensure_contains_elem(index, || None).get_or_insert_with(value) } #[inline] pub fn remove(&mut self, index: I) -> Option { - self.ensure_contains_elem(index, || None); - self[index].take() + self.ensure_contains_elem(index, || None).take() } } diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs index 364fa74ab7b45..66e2518fa56e5 100644 --- a/compiler/rustc_metadata/src/rmeta/table.rs +++ b/compiler/rustc_metadata/src/rmeta/table.rs @@ -413,8 +413,8 @@ impl> TableBui // > Space requirements could perhaps be optimized by using the HAMT `popcnt` // > trick (i.e. divide things into buckets of 32 or 64 items and then // > store bit-masks of which item in each bucket is actually serialized). - self.blocks.ensure_contains_elem(i, || [0; N]); - value.write_to_bytes(&mut self.blocks[i]); + let block = self.blocks.ensure_contains_elem(i, || [0; N]); + value.write_to_bytes(block); } } From bef3502dbae607fba8d3a7ea209191f9b80b9e91 Mon Sep 17 00:00:00 2001 From: Augie Fackler Date: Mon, 17 Apr 2023 10:53:18 -0400 Subject: [PATCH 087/228] tests: adapt for LLVM change 5b386b864c7619897c51a1da97d78f1cf6f3eff6 The above-mentioned change modified the output of thread-local.rs by changing some variable names. Rather than assume things get put in %0, we capture the variable so the test passes in both the old and new version. --- tests/codegen/thread-local.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/codegen/thread-local.rs b/tests/codegen/thread-local.rs index aa7fab7fb1795..caf0366d2c144 100644 --- a/tests/codegen/thread-local.rs +++ b/tests/codegen/thread-local.rs @@ -20,8 +20,8 @@ thread_local!(static A: Cell = const { Cell::new(1) }); // CHECK-LABEL: @get #[no_mangle] fn get() -> u32 { - // CHECK: %0 = load i32, {{.*}}[[TLS]]{{.*}} - // CHECK-NEXT: ret i32 %0 + // CHECK: [[RET_0:%.+]] = load i32, {{.*}}[[TLS]]{{.*}} + // CHECK-NEXT: ret i32 [[RET_0]] A.with(|a| a.get()) } @@ -36,8 +36,8 @@ fn set(v: u32) { // CHECK-LABEL: @get_aux #[no_mangle] fn get_aux() -> u64 { - // CHECK: %0 = load i64, {{.*}}[[TLS_AUX]] - // CHECK-NEXT: ret i64 %0 + // CHECK: [[RET_1:%.+]] = load i64, {{.*}}[[TLS_AUX]] + // CHECK-NEXT: ret i64 [[RET_1]] aux::A.with(|a| a.get()) } From 70ce74e1e25715127b8d2ba0806c8670c295de10 Mon Sep 17 00:00:00 2001 From: Josh Soref <2119212+jsoref@users.noreply.github.com> Date: Sun, 9 Apr 2023 17:35:23 -0400 Subject: [PATCH 088/228] Spelling src/bootstrap * although * correct * granular * libunwind * repository * section Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> --- src/bootstrap/bootstrap.py | 2 +- src/bootstrap/builder.rs | 2 +- src/bootstrap/channel.rs | 2 +- src/bootstrap/llvm.rs | 2 +- src/bootstrap/render_tests.rs | 2 +- src/bootstrap/sanity.rs | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index 025145244c491..a0b492ac3423a 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -575,7 +575,7 @@ def fix_bin_or_dylib(self, fname): ] patchelf_args = ["--set-rpath", ":".join(rpath_entries)] if not fname.endswith(".so"): - # Finally, set the corret .interp for binaries + # Finally, set the correct .interp for binaries with open("{}/nix-support/dynamic-linker".format(nix_deps_dir)) as dynamic_linker: patchelf_args += ["--set-interpreter", dynamic_linker.read().rstrip()] diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index e959ea06f8b69..6fd9eb7a74f16 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -1384,7 +1384,7 @@ impl<'a> Builder<'a> { // Add extra cfg not defined in/by rustc // - // Note: Altrough it would seems that "-Zunstable-options" to `rustflags` is useless as + // Note: Although it would seems that "-Zunstable-options" to `rustflags` is useless as // cargo would implicitly add it, it was discover that sometimes bootstrap only use // `rustflags` without `cargo` making it required. rustflags.arg("-Zunstable-options"); diff --git a/src/bootstrap/channel.rs b/src/bootstrap/channel.rs index c3e3fa009a677..87018574048a0 100644 --- a/src/bootstrap/channel.rs +++ b/src/bootstrap/channel.rs @@ -22,7 +22,7 @@ pub enum GitInfo { /// If the info should be used (`omit_git_hash` is false), this will be /// `Some`, otherwise it will be `None`. Present(Option), - /// This is not a git repostory, but the info can be fetched from the + /// This is not a git repository, but the info can be fetched from the /// `git-commit-info` file. RecordedForTarball(Info), } diff --git a/src/bootstrap/llvm.rs b/src/bootstrap/llvm.rs index a893c3a47c9fd..cfc7418631368 100644 --- a/src/bootstrap/llvm.rs +++ b/src/bootstrap/llvm.rs @@ -1153,7 +1153,7 @@ impl Step for Libunwind { run.builder.ensure(Libunwind { target: run.target }); } - /// Build linunwind.a + /// Build libunwind.a fn run(self, builder: &Builder<'_>) -> Self::Output { builder.update_submodule(&Path::new("src/llvm-project")); diff --git a/src/bootstrap/render_tests.rs b/src/bootstrap/render_tests.rs index 19019ad2c089d..59fdfda71fff8 100644 --- a/src/bootstrap/render_tests.rs +++ b/src/bootstrap/render_tests.rs @@ -1,7 +1,7 @@ //! This module renders the JSON output of libtest into a human-readable form, trying to be as //! similar to libtest's native output as possible. //! -//! This is needed because we need to use libtest in JSON mode to extract granluar information +//! This is needed because we need to use libtest in JSON mode to extract granular information //! about the executed tests. Doing so suppresses the human-readable output, and (compared to Cargo //! and rustc) libtest doesn't include the rendered human-readable output as a JSON field. We had //! to reimplement all the rendering logic in this module because of that. diff --git a/src/bootstrap/sanity.rs b/src/bootstrap/sanity.rs index 8a40b0f64f4b6..140259b02135f 100644 --- a/src/bootstrap/sanity.rs +++ b/src/bootstrap/sanity.rs @@ -100,7 +100,7 @@ pub fn check(build: &mut Build) { Couldn't find required command: cmake You should install cmake, or set `download-ci-llvm = true` in the -`[llvm]` section section of `config.toml` to download LLVM rather +`[llvm]` section of `config.toml` to download LLVM rather than building it. " ); From 0a763c92f214501ccd0460fdddfbb49d21fe9b2e Mon Sep 17 00:00:00 2001 From: Erik Hofmayer Date: Mon, 17 Apr 2023 18:53:52 +0200 Subject: [PATCH 089/228] Make commit-date pattern more specific in test for issue 107094 --- tests/run-make/issue-107094/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/run-make/issue-107094/Makefile b/tests/run-make/issue-107094/Makefile index 7bbaf31a7771d..d614e3e1055c0 100644 --- a/tests/run-make/issue-107094/Makefile +++ b/tests/run-make/issue-107094/Makefile @@ -3,5 +3,5 @@ include ../tools.mk all: - $(BARE_RUSTC) --version --verbose | $(CGREP) -i -e "commit-hash: [0-9a-f]{40}" "commit-date: [0-9\-]+" - $(BARE_RUSTDOC) --version --verbose | $(CGREP) -i -e "commit-hash: [0-9a-f]{40}" "commit-date: [0-9\-]+" + $(BARE_RUSTC) --version --verbose | $(CGREP) -i -e "commit-hash: [0-9a-f]{40}" "commit-date: [0-9]{4}-[0-9]{2}-[0-9]{2}" + $(BARE_RUSTDOC) --version --verbose | $(CGREP) -i -e "commit-hash: [0-9a-f]{40}" "commit-date: [0-9]{4}-[0-9]{2}-[0-9]{2}" From 9c8d10a9f32bb87c7e665bc51e9cc6bb5f3b1800 Mon Sep 17 00:00:00 2001 From: Josh Soref <2119212+jsoref@users.noreply.github.com> Date: Sun, 9 Apr 2023 17:35:58 -0400 Subject: [PATCH 090/228] Spelling src/ci * architecture * configures * preparation * toolstate * unknown Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> --- src/ci/docker/README.md | 2 +- .../riscv64gc-linux/0001-Remove-stime-function-calls.patch | 2 +- src/ci/docker/host-x86_64/dist-mips-linux/mips-linux-gnu.config | 2 +- .../host-x86_64/dist-mips64-linux/mips64-linux-gnu.config | 2 +- .../host-x86_64/dist-mips64el-linux/mips64el-linux-gnu.config | 2 +- .../host-x86_64/dist-mipsel-linux/mipsel-linux-gnu.config | 2 +- src/ci/docker/host-x86_64/mingw-check/validate-toolstate.sh | 2 +- src/ci/docker/scripts/qemu-bare-bones-rcS | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/ci/docker/README.md b/src/ci/docker/README.md index ea236bee56302..9f7259f883a59 100644 --- a/src/ci/docker/README.md +++ b/src/ci/docker/README.md @@ -211,7 +211,7 @@ For targets: `armv7-unknown-linux-gnueabihf` (\*) These options have been selected to match the configuration of the arm toolchains shipped with Ubuntu 15.10 (+) These options have been selected to match the gcc flags we use to compile C - libraries like jemalloc. See the mk/cfg/arm(v7)-uknown-linux-gnueabi{,hf}.mk + libraries like jemalloc. See the mk/cfg/arm(v7)-unknown-linux-gnueabi{,hf}.mk file in Rust's source code. ### `aarch64-linux-gnu.config` diff --git a/src/ci/docker/host-x86_64/disabled/riscv64gc-linux/0001-Remove-stime-function-calls.patch b/src/ci/docker/host-x86_64/disabled/riscv64gc-linux/0001-Remove-stime-function-calls.patch index 08d0c5b2cac1e..4437a870b207e 100644 --- a/src/ci/docker/host-x86_64/disabled/riscv64gc-linux/0001-Remove-stime-function-calls.patch +++ b/src/ci/docker/host-x86_64/disabled/riscv64gc-linux/0001-Remove-stime-function-calls.patch @@ -5,7 +5,7 @@ Subject: [PATCH] Remove stime() function calls stime() has been deprecated in glibc 2.31 and replaced with clock_settime(). Let's replace the stime() function calls with -clock_settime() in preperation. +clock_settime() in preparation. function old new delta rdate_main 197 224 +27 diff --git a/src/ci/docker/host-x86_64/dist-mips-linux/mips-linux-gnu.config b/src/ci/docker/host-x86_64/dist-mips-linux/mips-linux-gnu.config index 575584ef0cf66..5bfbbae206b41 100644 --- a/src/ci/docker/host-x86_64/dist-mips-linux/mips-linux-gnu.config +++ b/src/ci/docker/host-x86_64/dist-mips-linux/mips-linux-gnu.config @@ -528,7 +528,7 @@ CT_CC_GCC_DEC_FLOAT_AUTO=y CT_CC_GCC_HAS_ARCH_OPTIONS=y # -# archictecture-specific options +# architecture-specific options # CT_CC_GCC_mips_llsc=m CT_CC_GCC_mips_synci=m diff --git a/src/ci/docker/host-x86_64/dist-mips64-linux/mips64-linux-gnu.config b/src/ci/docker/host-x86_64/dist-mips64-linux/mips64-linux-gnu.config index 4b1efe24aed8a..c28d655427e3c 100644 --- a/src/ci/docker/host-x86_64/dist-mips64-linux/mips64-linux-gnu.config +++ b/src/ci/docker/host-x86_64/dist-mips64-linux/mips64-linux-gnu.config @@ -529,7 +529,7 @@ CT_CC_GCC_DEC_FLOAT_AUTO=y CT_CC_GCC_HAS_ARCH_OPTIONS=y # -# archictecture-specific options +# architecture-specific options # CT_CC_GCC_mips_llsc=m CT_CC_GCC_mips_synci=m diff --git a/src/ci/docker/host-x86_64/dist-mips64el-linux/mips64el-linux-gnu.config b/src/ci/docker/host-x86_64/dist-mips64el-linux/mips64el-linux-gnu.config index baff944cf972a..50dfe7b2dd1a6 100644 --- a/src/ci/docker/host-x86_64/dist-mips64el-linux/mips64el-linux-gnu.config +++ b/src/ci/docker/host-x86_64/dist-mips64el-linux/mips64el-linux-gnu.config @@ -529,7 +529,7 @@ CT_CC_GCC_DEC_FLOAT_AUTO=y CT_CC_GCC_HAS_ARCH_OPTIONS=y # -# archictecture-specific options +# architecture-specific options # CT_CC_GCC_mips_llsc=m CT_CC_GCC_mips_synci=m diff --git a/src/ci/docker/host-x86_64/dist-mipsel-linux/mipsel-linux-gnu.config b/src/ci/docker/host-x86_64/dist-mipsel-linux/mipsel-linux-gnu.config index adb2da7ddeedd..3566c7c8593e2 100644 --- a/src/ci/docker/host-x86_64/dist-mipsel-linux/mipsel-linux-gnu.config +++ b/src/ci/docker/host-x86_64/dist-mipsel-linux/mipsel-linux-gnu.config @@ -528,7 +528,7 @@ CT_CC_GCC_DEC_FLOAT_AUTO=y CT_CC_GCC_HAS_ARCH_OPTIONS=y # -# archictecture-specific options +# architecture-specific options # CT_CC_GCC_mips_llsc=m CT_CC_GCC_mips_synci=m diff --git a/src/ci/docker/host-x86_64/mingw-check/validate-toolstate.sh b/src/ci/docker/host-x86_64/mingw-check/validate-toolstate.sh index 0b06f5e3623e3..a5691da8cda2d 100755 --- a/src/ci/docker/host-x86_64/mingw-check/validate-toolstate.sh +++ b/src/ci/docker/host-x86_64/mingw-check/validate-toolstate.sh @@ -1,5 +1,5 @@ #!/bin/bash -# A quick smoke test to make sure publish_tooolstate.py works. +# A quick smoke test to make sure publish_toolstate.py works. set -euo pipefail IFS=$'\n\t' diff --git a/src/ci/docker/scripts/qemu-bare-bones-rcS b/src/ci/docker/scripts/qemu-bare-bones-rcS index 3c29bedc13c99..c5d807b2d7d90 100644 --- a/src/ci/docker/scripts/qemu-bare-bones-rcS +++ b/src/ci/docker/scripts/qemu-bare-bones-rcS @@ -9,7 +9,7 @@ mount -t sysfs none /sys /addentropy < /addentropy cat /dev/urandom | head -n 2048 | /addentropy -# Set up IP that qemu expects. This confgures eth0 with the public IP that QEMU +# Set up IP that qemu expects. This configures eth0 with the public IP that QEMU # will communicate to as well as the loopback 127.0.0.1 address. ifconfig eth0 10.0.2.15 ifconfig lo up From 9534541dd48ec52bcd9a60094155dffaa8f0a87f Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Mon, 17 Apr 2023 17:16:49 +0000 Subject: [PATCH 091/228] Use `Item::expect_*` and `ImplItem::expect_*` more --- compiler/rustc_ast_lowering/src/item.rs | 10 ++++------ compiler/rustc_hir_analysis/src/coherence/builtin.rs | 7 +++---- .../src/infer/error_reporting/note_and_explain.rs | 5 +---- compiler/rustc_infer/src/infer/opaque_types.rs | 7 +------ compiler/rustc_metadata/src/rmeta/encoder.rs | 4 ++-- 5 files changed, 11 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index f89e254a2f54d..7b94f6edf7039 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -138,12 +138,10 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { // Evaluate with the lifetimes in `params` in-scope. // This is used to track which lifetimes have already been defined, // and which need to be replicated when lowering an async fn. - match parent_hir.node().expect_item().kind { - hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => { - lctx.is_in_trait_impl = of_trait.is_some(); - } - _ => {} - }; + + if let hir::ItemKind::Impl(impl_) = parent_hir.node().expect_item().kind { + lctx.is_in_trait_impl = impl_.of_trait.is_some(); + } match ctxt { AssocCtxt::Trait => hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)), diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 0f40cca9427b4..c2dc2a0f058f3 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -74,10 +74,9 @@ fn visit_implementation_of_copy(tcx: TyCtxt<'_>, impl_did: LocalDefId) { debug!("visit_implementation_of_copy: self_type={:?} (free)", self_type); - let span = match tcx.hir().expect_item(impl_did).kind { - ItemKind::Impl(hir::Impl { polarity: hir::ImplPolarity::Negative(_), .. }) => return, - ItemKind::Impl(impl_) => impl_.self_ty.span, - _ => bug!("expected Copy impl item"), + let span = match tcx.hir().expect_item(impl_did).expect_impl() { + hir::Impl { polarity: hir::ImplPolarity::Negative(_), .. } => return, + hir::Impl { self_ty, .. } => self_ty.span, }; let cause = traits::ObligationCause::misc(span, impl_did); diff --git a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs index b38bbdfe7bb8b..e410172c8c8d1 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs @@ -462,10 +462,7 @@ fn foo(&self) -> Self::T { String::new() } if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *proj_ty.self_ty().kind() { let opaque_local_def_id = def_id.as_local(); let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id { - match &tcx.hir().expect_item(opaque_local_def_id).kind { - hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty, - _ => bug!("The HirId comes from a `ty::Opaque`"), - } + tcx.hir().expect_item(opaque_local_def_id).expect_opaque_ty() } else { return false; }; diff --git a/compiler/rustc_infer/src/infer/opaque_types.rs b/compiler/rustc_infer/src/infer/opaque_types.rs index 3a0a0494a7ed3..680465bdab690 100644 --- a/compiler/rustc_infer/src/infer/opaque_types.rs +++ b/compiler/rustc_infer/src/infer/opaque_types.rs @@ -392,12 +392,7 @@ impl<'tcx> InferCtxt<'tcx> { /// defining scope. #[instrument(skip(self), level = "trace", ret)] fn opaque_type_origin_unchecked(&self, def_id: LocalDefId) -> OpaqueTyOrigin { - match self.tcx.hir().expect_item(def_id).kind { - hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => origin, - ref itemkind => { - bug!("weird opaque type: {:?}, {:#?}", def_id, itemkind) - } - } + self.tcx.hir().expect_item(def_id).expect_opaque_ty().origin } } diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 657b903e0a8af..c73d6b5e9316e 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1469,8 +1469,8 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { match impl_item.kind { ty::AssocKind::Fn => { - let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local()); - let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind else { bug!() }; + let (sig, body) = + self.tcx.hir().expect_impl_item(def_id.expect_local()).expect_fn(); self.tables.asyncness.set_some(def_id.index, sig.header.asyncness); record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body)); // Can be inside `impl const Trait`, so using sig.header.constness is not reliable From 880da9fca96f59e2503c2ad0343177265e788ec4 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Mon, 17 Apr 2023 17:17:42 +0000 Subject: [PATCH 092/228] doc fix I think those don't make sense here, ig they were left from me copying the defs. --- compiler/rustc_hir/src/hir.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index b274e62807988..fb0c087bfb471 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -3146,7 +3146,6 @@ impl<'hir> Item<'hir> { (ty, gen) } - /// An opaque `impl Trait` type alias, e.g., `type Foo = impl Bar;`. /// Expect an [`ItemKind::OpaqueTy`] or panic. #[track_caller] pub fn expect_opaque_ty(&self) -> &OpaqueTy<'hir> { @@ -3168,7 +3167,6 @@ impl<'hir> Item<'hir> { (data, gen) } - /// A union definition, e.g., `union Foo {x: A, y: B}`. /// Expect an [`ItemKind::Union`] or panic. #[track_caller] pub fn expect_union(&self) -> (&VariantData<'hir>, &'hir Generics<'hir>) { From c456e15855b538aecff7b088dda6144dcde9d6ca Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 17 Apr 2023 14:35:33 +0200 Subject: [PATCH 093/228] Add regression tests for #110422 --- .../infinite-recursive-type-impl-trait.rs | 5 +- .../infinite-recursive-type-impl-trait.stderr | 16 ----- tests/rustdoc/issue-110422-inner-private.rs | 64 +++++++++++++++++++ 3 files changed, 68 insertions(+), 17 deletions(-) delete mode 100644 tests/rustdoc-ui/infinite-recursive-type-impl-trait.stderr create mode 100644 tests/rustdoc/issue-110422-inner-private.rs diff --git a/tests/rustdoc-ui/infinite-recursive-type-impl-trait.rs b/tests/rustdoc-ui/infinite-recursive-type-impl-trait.rs index ac51725749867..096130d776828 100644 --- a/tests/rustdoc-ui/infinite-recursive-type-impl-trait.rs +++ b/tests/rustdoc-ui/infinite-recursive-type-impl-trait.rs @@ -1,6 +1,9 @@ +// check-pass + fn f() -> impl Sized { - enum E { //~ ERROR + enum E { V(E), } + unimplemented!() } diff --git a/tests/rustdoc-ui/infinite-recursive-type-impl-trait.stderr b/tests/rustdoc-ui/infinite-recursive-type-impl-trait.stderr deleted file mode 100644 index a61577bd14afc..0000000000000 --- a/tests/rustdoc-ui/infinite-recursive-type-impl-trait.stderr +++ /dev/null @@ -1,16 +0,0 @@ -error[E0072]: recursive type `f::E` has infinite size - --> $DIR/infinite-recursive-type-impl-trait.rs:2:5 - | -LL | enum E { - | ^^^^^^ -LL | V(E), - | - recursive without indirection - | -help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle - | -LL | V(Box), - | ++++ + - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0072`. diff --git a/tests/rustdoc/issue-110422-inner-private.rs b/tests/rustdoc/issue-110422-inner-private.rs new file mode 100644 index 0000000000000..ee8ed5cc6e17f --- /dev/null +++ b/tests/rustdoc/issue-110422-inner-private.rs @@ -0,0 +1,64 @@ +// Regression test for . +// This test ensures that inner items (except for implementations and macros) +// don't appear in documentation. + +// compile-flags: --document-private-items + +#![crate_name = "foo"] + +// @has 'foo/index.html' +// Checking there is no "trait" entry. +// @count - '//*[@id="main-content"]/*[@class="small-section-header"]' 4 +// @has - '//*[@id="main-content"]/*[@class="small-section-header"]' 'Structs' +// @has - '//*[@id="main-content"]/*[@class="small-section-header"]' 'Constants' +// @has - '//*[@id="main-content"]/*[@class="small-section-header"]' 'Functions' +// @has - '//*[@id="main-content"]/*[@class="small-section-header"]' 'Macros' + +// @has - '//a[@href="fn.foo.html"]' 'foo' +fn foo() { + fn bar() {} + + // @has - '//a[@class="macro"]' 'visible_macro' + // @!has - '//a[@class="macro"]' 'non_visible_macro' + // @has 'foo/macro.visible_macro.html' + // @!has 'foo/macro.non_visible_macro.html' + #[macro_export] + macro_rules! visible_macro { + () => {} + } + + macro_rules! non_visible_macro { + () => {} + } +} + +// @has 'foo/index.html' +// @has - '//a[@href="struct.Bar.html"]' 'Bar' +struct Bar; + +const BAR: i32 = { + // @!has - '//a[@href="fn.yo.html"]' 'yo' + // @!has 'foo/fn.yo.html' + fn yo() {} + + // @!has 'foo/index.html' '//a[@href="trait.Foo.html"]' 'Foo' + // @!has 'foo/trait.Foo.html' + trait Foo { + fn babar() {} + } + impl Foo for Bar {} + + // @has 'foo/struct.Bar.html' + // @has - '//*[@id="method.foo"]/*[@class="code-header"]' 'pub(crate) fn foo()' + // @count - '//*[@id="main-content"]/*[@class="small-section-header"]' 3 + // We now check that the `Foo` trait is not documented nor visible on `Bar` page. + // @has - '//*[@id="main-content"]/*[@class="small-section-header"]' 'Implementations' + // @has - '//*[@id="main-content"]/*[@class="small-section-header"]' 'Auto Trait Implementations' + // @has - '//*[@id="main-content"]/*[@class="small-section-header"]' 'Blanket Implementations' + // @!has - '//*[@href="trait.Foo.html#method.babar"]/*[@class="code-header"]' 'fn babar()' + impl Bar { + fn foo() {} + } + + 1 +}; From c960a043e368c1e89974dbed244a3fdae222109a Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Mon, 17 Apr 2023 19:19:59 +0000 Subject: [PATCH 094/228] Assure everyone that `has_type_flags` is fast --- compiler/rustc_middle/src/ty/visit.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/compiler/rustc_middle/src/ty/visit.rs b/compiler/rustc_middle/src/ty/visit.rs index 24a1f04c7e388..1b07f52afca92 100644 --- a/compiler/rustc_middle/src/ty/visit.rs +++ b/compiler/rustc_middle/src/ty/visit.rs @@ -33,6 +33,14 @@ pub trait TypeVisitableExt<'tcx>: TypeVisitable> { } fn has_type_flags(&self, flags: TypeFlags) -> bool { + // N.B. Even though this uses a visitor, the visitor does not actually + // recurse through the whole `TypeVisitable` implementor type. + // + // Instead it stops on the first "level", visiting types, regions, + // consts and predicates just fetches their type flags. + // + // Thus this is a lot faster than it might seem and should be + // optimized to a simple field access. let res = self.visit_with(&mut HasTypeFlagsVisitor { flags }).break_value() == Some(FoundFlags); trace!(?self, ?flags, ?res, "has_type_flags"); From e09d0d2a29e81972563a52dc28f867499ffc9315 Mon Sep 17 00:00:00 2001 From: Josh Soref <2119212+jsoref@users.noreply.github.com> Date: Sun, 9 Apr 2023 17:35:02 -0400 Subject: [PATCH 095/228] Spelling - compiler * account * achieved * advising * always * ambiguous * analysis * annotations * appropriate * build * candidates * cascading * category * character * clarification * compound * conceptually * constituent * consts * convenience * corresponds * debruijn * debug * debugable * debuggable * deterministic * discriminant * display * documentation * doesn't * ellipsis * erroneous * evaluability * evaluate * evaluation * explicitly * fallible * fulfill * getting * has * highlighting * illustrative * imported * incompatible * infringing * initialized * into * intrinsic * introduced * javascript * liveness * metadata * monomorphization * nonexistent * nontrivial * obligation * obligations * offset * opaque * opportunities * opt-in * outlive * overlapping * paragraph * parentheses * poisson * precisely * predecessors * predicates * preexisting * propagated * really * reentrant * referent * responsibility * rustonomicon * shortcircuit * simplifiable * simplifications * specify * stabilized * structurally * suggestibility * translatable * transmuting * two * unclosed * uninhabited * visibility * volatile * workaround Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com> --- compiler/rustc_ast_passes/messages.ftl | 2 +- compiler/rustc_ast_passes/src/errors.rs | 2 +- .../src/diagnostics/mutability_errors.rs | 6 +++--- compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs | 4 ++-- .../src/debuginfo/metadata/enums/cpp_like.rs | 2 +- compiler/rustc_codegen_llvm/src/lib.rs | 2 +- compiler/rustc_codegen_ssa/messages.ftl | 2 +- compiler/rustc_codegen_ssa/src/back/write.rs | 2 +- compiler/rustc_codegen_ssa/src/codegen_attrs.rs | 2 +- compiler/rustc_codegen_ssa/src/errors.rs | 2 +- .../rustc_const_eval/src/interpret/validity.rs | 4 ++-- .../rustc_const_eval/src/transform/validate.rs | 2 +- compiler/rustc_data_structures/src/profiling.rs | 2 +- .../rustc_error_codes/src/error_codes/E0026.md | 2 +- .../rustc_error_codes/src/error_codes/E0208.md | 4 ++-- .../rustc_error_codes/src/error_codes/E0311.md | 2 +- .../rustc_error_codes/src/error_codes/E0457.md | 2 +- .../rustc_error_codes/src/error_codes/E0576.md | 2 +- .../rustc_error_codes/src/error_codes/E0609.md | 2 +- compiler/rustc_errors/src/emitter.rs | 2 +- compiler/rustc_expand/src/mbe/macro_rules.rs | 4 ++-- compiler/rustc_expand/src/tests.rs | 4 ++-- compiler/rustc_feature/src/removed.rs | 2 +- compiler/rustc_hir_analysis/src/astconv/mod.rs | 2 +- .../rustc_hir_analysis/src/coherence/builtin.rs | 2 +- .../src/collect/resolve_bound_vars.rs | 2 +- compiler/rustc_hir_typeck/src/coercion.rs | 4 ++-- compiler/rustc_hir_typeck/src/errors.rs | 2 +- compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs | 2 +- .../src/fn_ctxt/adjust_fulfillment_errors.rs | 2 +- .../rustc_hir_typeck/src/fn_ctxt/suggestions.rs | 2 +- .../rustc_hir_typeck/src/generator_interior/mod.rs | 2 +- compiler/rustc_hir_typeck/src/method/suggest.rs | 2 +- compiler/rustc_hir_typeck/src/pat.rs | 2 +- compiler/rustc_hir_typeck/src/upvar.rs | 4 ++-- .../rustc_incremental/src/persist/dirty_clean.rs | 2 +- compiler/rustc_infer/messages.ftl | 10 +++++----- compiler/rustc_infer/src/errors/mod.rs | 14 +++++++------- .../src/infer/canonical/query_response.rs | 4 ++-- compiler/rustc_infer/src/infer/combine.rs | 2 +- compiler/rustc_infer/src/infer/equate.rs | 2 +- .../rustc_infer/src/infer/error_reporting/mod.rs | 4 ++-- .../src/infer/error_reporting/need_type_info.rs | 6 +++--- .../rustc_infer/src/infer/higher_ranked/mod.rs | 2 +- compiler/rustc_infer/src/infer/sub.rs | 2 +- compiler/rustc_infer/src/traits/project.rs | 2 +- compiler/rustc_lint/src/builtin.rs | 12 ++++++------ compiler/rustc_lint/src/errors.rs | 2 +- compiler/rustc_lint_defs/src/builtin.rs | 4 ++-- compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp | 2 +- compiler/rustc_metadata/src/rmeta/decoder.rs | 4 ++-- compiler/rustc_middle/src/mir/interpret/pointer.rs | 2 +- compiler/rustc_middle/src/mir/syntax.rs | 4 ++-- compiler/rustc_middle/src/ty/abstract_const.rs | 2 +- compiler/rustc_middle/src/ty/fast_reject.rs | 2 +- compiler/rustc_middle/src/ty/layout.rs | 6 +++--- compiler/rustc_middle/src/ty/structural_impls.rs | 2 +- compiler/rustc_middle/src/ty/util.rs | 4 ++-- compiler/rustc_mir_build/src/build/expr/into.rs | 4 ++-- compiler/rustc_mir_build/src/build/matches/test.rs | 12 ++++++------ .../src/thir/pattern/const_to_pat.rs | 2 +- compiler/rustc_mir_dataflow/src/value_analysis.rs | 2 +- .../src/add_moves_for_packed_drops.rs | 4 ++-- compiler/rustc_mir_transform/src/add_retag.rs | 2 +- .../rustc_mir_transform/src/const_debuginfo.rs | 4 ++-- compiler/rustc_mir_transform/src/const_prop.rs | 2 +- compiler/rustc_mir_transform/src/coverage/graph.rs | 2 +- .../rustc_mir_transform/src/dataflow_const_prop.rs | 2 +- compiler/rustc_mir_transform/src/dest_prop.rs | 4 ++-- .../rustc_mir_transform/src/elaborate_drops.rs | 2 +- compiler/rustc_mir_transform/src/generator.rs | 2 +- compiler/rustc_mir_transform/src/ssa.rs | 2 +- compiler/rustc_monomorphize/src/collector.rs | 2 +- .../rustc_monomorphize/src/partitioning/default.rs | 2 +- compiler/rustc_parse/src/lexer/mod.rs | 2 +- compiler/rustc_parse/src/validate_attr.rs | 2 +- compiler/rustc_query_impl/src/on_disk_cache.rs | 2 +- compiler/rustc_query_system/messages.ftl | 2 +- compiler/rustc_query_system/src/dep_graph/graph.rs | 2 +- compiler/rustc_query_system/src/query/config.rs | 2 +- compiler/rustc_query_system/src/query/plumbing.rs | 2 +- .../rustc_resolve/src/effective_visibilities.rs | 2 +- compiler/rustc_resolve/src/errors.rs | 2 +- compiler/rustc_resolve/src/late.rs | 4 ++-- compiler/rustc_resolve/src/late/diagnostics.rs | 4 ++-- compiler/rustc_span/src/source_map.rs | 4 ++-- compiler/rustc_target/src/abi/call/avr.rs | 2 +- compiler/rustc_target/src/spec/mod.rs | 6 +++--- compiler/rustc_target/src/spec/thumb_base.rs | 2 +- .../src/solve/assembly/mod.rs | 4 ++-- .../src/solve/eval_ctxt/canonical.rs | 6 +++--- .../rustc_trait_selection/src/solve/trait_goals.rs | 2 +- .../src/traits/error_reporting/mod.rs | 4 ++-- .../src/traits/error_reporting/suggestions.rs | 2 +- compiler/rustc_trait_selection/src/traits/misc.rs | 4 ++-- compiler/rustc_trait_selection/src/traits/mod.rs | 2 +- .../rustc_trait_selection/src/traits/select/mod.rs | 2 +- compiler/rustc_ty_utils/src/layout_sanity_check.rs | 2 +- compiler/rustc_ty_utils/src/needs_drop.rs | 2 +- tests/ui/error-codes/E0026-teach.stderr | 2 +- .../enum-variant-generic-args.stderr | 12 ++++++------ 101 files changed, 159 insertions(+), 159 deletions(-) diff --git a/compiler/rustc_ast_passes/messages.ftl b/compiler/rustc_ast_passes/messages.ftl index a349fe6a3c44b..ffca37ae9d5f6 100644 --- a/compiler/rustc_ast_passes/messages.ftl +++ b/compiler/rustc_ast_passes/messages.ftl @@ -231,7 +231,7 @@ ast_passes_feature_on_non_nightly = `#![feature]` may not be used on the {$chann .suggestion = remove the attribute .stable_since = the feature `{$name}` has been stable since `{$since}` and no longer requires an attribute to enable -ast_passes_incompatbile_features = `{$f1}` and `{$f2}` are incompatible, using them at the same time is not allowed +ast_passes_incompatible_features = `{$f1}` and `{$f2}` are incompatible, using them at the same time is not allowed .help = remove one of these features ast_passes_show_span = {$msg} diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 27bbd237961a9..1732865f0bb64 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -677,7 +677,7 @@ impl AddToDiagnostic for StableFeature { } #[derive(Diagnostic)] -#[diag(ast_passes_incompatbile_features)] +#[diag(ast_passes_incompatible_features)] #[help] pub struct IncompatibleFeatures { #[primary_span] diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index eb5f166548d9c..e3d81194ac817 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -1147,7 +1147,7 @@ pub fn mut_borrow_of_mutable_ref(local_decl: &LocalDecl<'_>, local_name: Option< // suggest removing the `&mut`. // // Deliberately fall into this case for all implicit self types, - // so that we don't fall in to the next case with them. + // so that we don't fall into the next case with them. kind == hir::ImplicitSelfKind::MutRef } _ if Some(kw::SelfLower) == local_name => { @@ -1235,7 +1235,7 @@ fn suggest_ampmut<'tcx>( } } - let (suggestability, highlight_span) = match opt_ty_info { + let (suggestibility, highlight_span) = match opt_ty_info { // if this is a variable binding with an explicit type, // try to highlight that for the suggestion. Some(ty_span) => (true, ty_span), @@ -1256,7 +1256,7 @@ fn suggest_ampmut<'tcx>( let ty_mut = local_decl.ty.builtin_deref(true).unwrap(); assert_eq!(ty_mut.mutbl, hir::Mutability::Not); ( - suggestability, + suggestibility, highlight_span, if local_decl.ty.is_ref() { format!("&mut {}", ty_mut.ty) diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs index ff2b005d75767..aaf5dbd9930c7 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/gdb.rs @@ -22,9 +22,9 @@ pub fn insert_reference_to_gdb_debug_scripts_section_global(bx: &mut Builder<'_, bx.const_bitcast(get_or_insert_gdb_debug_scripts_section_global(bx), bx.type_i8p()); // Load just the first byte as that's all that's necessary to force // LLVM to keep around the reference to the global. - let volative_load_instruction = bx.volatile_load(bx.type_i8(), gdb_debug_scripts_section); + let volatile_load_instruction = bx.volatile_load(bx.type_i8(), gdb_debug_scripts_section); unsafe { - llvm::LLVMSetAlignment(volative_load_instruction, 1); + llvm::LLVMSetAlignment(volatile_load_instruction, 1); } } } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs index 69443b9b828e2..38ad42370d3fe 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs @@ -62,7 +62,7 @@ const SINGLE_VARIANT_VIRTUAL_DISR: u64 = 0; /// In CPP-like mode, we generate a union with a field for each variant and an /// explicit tag field. The field of each variant has a struct type -/// that encodes the discrimiant of the variant and it's data layout. +/// that encodes the discriminant of the variant and it's data layout. /// The union also has a nested enumeration type that is only used for encoding /// variant names in an efficient way. Its enumerator values do _not_ correspond /// to the enum's discriminant values. diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 3f77ea77effe3..4926f4e50c417 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -69,7 +69,7 @@ mod declare; mod errors; mod intrinsic; -// The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912. +// The following is a workaround that replaces `pub mod llvm;` and that fixes issue 53912. #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { diff --git a/compiler/rustc_codegen_ssa/messages.ftl b/compiler/rustc_codegen_ssa/messages.ftl index 243be0e1f70e7..85a96e3e89c05 100644 --- a/compiler/rustc_codegen_ssa/messages.ftl +++ b/compiler/rustc_codegen_ssa/messages.ftl @@ -148,7 +148,7 @@ codegen_ssa_processing_dymutil_failed = processing debug info with `dsymutil` fa codegen_ssa_unable_to_run_dsymutil = unable to run `dsymutil`: {$error} -codegen_ssa_stripping_debu_info_failed = stripping debug info with `{$util}` failed: {$status} +codegen_ssa_stripping_debug_info_failed = stripping debug info with `{$util}` failed: {$status} .note = {$output} codegen_ssa_unable_to_run = unable to run `{$util}`: {$error} diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 2dda4cd169410..c80347448cbb2 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -872,7 +872,7 @@ fn execute_copy_from_cache_work_item( let load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| { let source_file = in_incr_comp_dir(&incr_comp_session_dir, saved_path); debug!( - "copying pre-existing module `{}` from {:?} to {}", + "copying preexisting module `{}` from {:?} to {}", module.name, source_file, output_path.display() diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 8542bab689d6d..9bfe426c00766 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -156,7 +156,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { None => { // Unfortunately, unconditionally using `llvm.used` causes // issues in handling `.init_array` with the gold linker, - // but using `llvm.compiler.used` caused a nontrival amount + // but using `llvm.compiler.used` caused a nontrivial amount // of unintentional ecosystem breakage -- particularly on // Mach-O targets. // diff --git a/compiler/rustc_codegen_ssa/src/errors.rs b/compiler/rustc_codegen_ssa/src/errors.rs index 66e7e314f79d8..4493176667867 100644 --- a/compiler/rustc_codegen_ssa/src/errors.rs +++ b/compiler/rustc_codegen_ssa/src/errors.rs @@ -424,7 +424,7 @@ pub struct UnableToRunDsymutil { } #[derive(Diagnostic)] -#[diag(codegen_ssa_stripping_debu_info_failed)] +#[diag(codegen_ssa_stripping_debug_info_failed)] #[note] pub struct StrippingDebugInfoFailed<'a> { pub util: &'a str, diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 93b5273e1b146..e06b634cdc330 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -784,7 +784,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> Abi::Scalar(scalar_layout) => { if !scalar_layout.is_uninit_valid() { // There is something to check here. - let scalar = self.read_scalar(op, "initiailized scalar value")?; + let scalar = self.read_scalar(op, "initialized scalar value")?; self.visit_scalar(scalar, scalar_layout)?; } } @@ -794,7 +794,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> // the other must be init. if !a_layout.is_uninit_valid() && !b_layout.is_uninit_valid() { let (a, b) = - self.read_immediate(op, "initiailized scalar value")?.to_scalar_pair(); + self.read_immediate(op, "initialized scalar value")?.to_scalar_pair(); self.visit_scalar(a, a_layout)?; self.visit_scalar(b, b_layout)?; } diff --git a/compiler/rustc_const_eval/src/transform/validate.rs b/compiler/rustc_const_eval/src/transform/validate.rs index d4bed97380ba1..8aee019e99494 100644 --- a/compiler/rustc_const_eval/src/transform/validate.rs +++ b/compiler/rustc_const_eval/src/transform/validate.rs @@ -262,7 +262,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // We sometimes have to use `defining_opaque_types` for subtyping // to succeed here and figuring out how exactly that should work // is annoying. It is harmless enough to just not validate anything - // in that case. We still check this after analysis as all opque + // in that case. We still check this after analysis as all opaque // types have been revealed at this point. if (src, dest).has_opaque_types() { return true; diff --git a/compiler/rustc_data_structures/src/profiling.rs b/compiler/rustc_data_structures/src/profiling.rs index 1ed584eafad30..2ab7757638aef 100644 --- a/compiler/rustc_data_structures/src/profiling.rs +++ b/compiler/rustc_data_structures/src/profiling.rs @@ -557,7 +557,7 @@ impl SelfProfiler { let crate_name = crate_name.unwrap_or("unknown-crate"); // HACK(eddyb) we need to pad the PID, strange as it may seem, as its // length can behave as a source of entropy for heap addresses, when - // ASLR is disabled and the heap is otherwise determinic. + // ASLR is disabled and the heap is otherwise deterministic. let pid: u32 = process::id(); let filename = format!("{crate_name}-{pid:07}.rustc_profile"); let path = output_directory.join(&filename); diff --git a/compiler/rustc_error_codes/src/error_codes/E0026.md b/compiler/rustc_error_codes/src/error_codes/E0026.md index 72c575aabb643..f485112cca29f 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0026.md +++ b/compiler/rustc_error_codes/src/error_codes/E0026.md @@ -1,4 +1,4 @@ -A struct pattern attempted to extract a non-existent field from a struct. +A struct pattern attempted to extract a nonexistent field from a struct. Erroneous code example: diff --git a/compiler/rustc_error_codes/src/error_codes/E0208.md b/compiler/rustc_error_codes/src/error_codes/E0208.md index 1ae01106f2014..c6db9b5d61bea 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0208.md +++ b/compiler/rustc_error_codes/src/error_codes/E0208.md @@ -32,7 +32,7 @@ error: [-, o] This error is deliberately triggered with the `#[rustc_variance]` attribute (`#![feature(rustc_attrs)]` must be enabled) and helps to show you the variance of the type's generic parameters. You can read more about variance and -subtyping in [this section of the Rustnomicon]. For a more in depth look at +subtyping in [this section of the Rustonomicon]. For a more in depth look at variance (including a more complete list of common variances) see [this section of the Reference]. For information on how variance is implemented in the compiler, see [this section of `rustc-dev-guide`]. @@ -41,6 +41,6 @@ This error can be easily fixed by removing the `#[rustc_variance]` attribute, the compiler's suggestion to comment it out can be applied automatically with `rustfix`. -[this section of the Rustnomicon]: https://doc.rust-lang.org/nomicon/subtyping.html +[this section of the Rustonomicon]: https://doc.rust-lang.org/nomicon/subtyping.html [this section of the Reference]: https://doc.rust-lang.org/reference/subtyping.html#variance [this section of `rustc-dev-guide`]: https://rustc-dev-guide.rust-lang.org/variance.html diff --git a/compiler/rustc_error_codes/src/error_codes/E0311.md b/compiler/rustc_error_codes/src/error_codes/E0311.md index 08159d3f469ac..c1104a88a7676 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0311.md +++ b/compiler/rustc_error_codes/src/error_codes/E0311.md @@ -29,7 +29,7 @@ If `no_restriction()` were to use `&T` instead of `&()` as an argument, the compiler would have added an implied bound, causing this to compile. This error can be resolved by explicitly naming the elided lifetime for `x` and -then explicily requiring that the generic parameter `T` outlives that lifetime: +then explicitly requiring that the generic parameter `T` outlives that lifetime: ``` fn no_restriction<'a, T: 'a>(x: &'a ()) -> &'a () { diff --git a/compiler/rustc_error_codes/src/error_codes/E0457.md b/compiler/rustc_error_codes/src/error_codes/E0457.md index 53d384d36c426..2c33d1e6a2419 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0457.md +++ b/compiler/rustc_error_codes/src/error_codes/E0457.md @@ -1,6 +1,6 @@ Plugin `..` only found in rlib format, but must be available in dylib format. -Erroronous code example: +Erroneous code example: `rlib-plugin.rs` ```ignore (needs-linkage-with-other-tests) diff --git a/compiler/rustc_error_codes/src/error_codes/E0576.md b/compiler/rustc_error_codes/src/error_codes/E0576.md index 8eead4e7e3b51..300a57a1985f5 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0576.md +++ b/compiler/rustc_error_codes/src/error_codes/E0576.md @@ -10,7 +10,7 @@ trait Hello { } ``` -In this example, we tried to use the non-existent associated type `You` of the +In this example, we tried to use the nonexistent associated type `You` of the `Hello` trait. To fix this error, use an existing associated type: ``` diff --git a/compiler/rustc_error_codes/src/error_codes/E0609.md b/compiler/rustc_error_codes/src/error_codes/E0609.md index a9db34f474e25..0f5ac94e6d589 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0609.md +++ b/compiler/rustc_error_codes/src/error_codes/E0609.md @@ -1,4 +1,4 @@ -Attempted to access a non-existent field in a struct. +Attempted to access a nonexistent field in a struct. Erroneous code example: diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index fe44799efdb6a..8c76d5e010ff9 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -1980,7 +1980,7 @@ impl EmitterWriter { } if let DisplaySuggestion::Add = show_code_change && is_item_attribute { // The suggestion adds an entire line of code, ending on a newline, so we'll also - // print the *following* line, to provide context of what we're advicing people to + // print the *following* line, to provide context of what we're advising people to // do. Otherwise you would only see contextless code that can be confused for // already existing code, despite the colors and UI elements. // We special case `#[derive(_)]\n` and other attribute suggestions, because those diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 5679cdcbbd062..3aeb2edb54ca0 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -341,7 +341,7 @@ pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>( Success(named_matches) => { debug!("Parsed arm successfully"); // The matcher was `Success(..)`ful. - // Merge the gated spans from parsing the matcher with the pre-existing ones. + // Merge the gated spans from parsing the matcher with the preexisting ones. sess.gated_spans.merge(gated_spans_snapshot); return Ok((i, named_matches)); @@ -873,7 +873,7 @@ impl<'tt> FirstSets<'tt> { } } -// Most `mbe::TokenTree`s are pre-existing in the matcher, but some are defined +// Most `mbe::TokenTree`s are preexisting in the matcher, but some are defined // implicitly, such as opening/closing delimiters and sequence repetition ops. // This type encapsulates both kinds. It implements `Clone` while avoiding the // need for `mbe::TokenTree` to implement `Clone`. diff --git a/compiler/rustc_expand/src/tests.rs b/compiler/rustc_expand/src/tests.rs index 480d95b77e901..8a5e09475ff13 100644 --- a/compiler/rustc_expand/src/tests.rs +++ b/compiler/rustc_expand/src/tests.rs @@ -513,7 +513,7 @@ error: foo } #[test] -fn non_overlaping() { +fn non_overlapping() { test_harness( r#" fn foo() { @@ -552,7 +552,7 @@ error: foo } #[test] -fn overlaping_start_and_end() { +fn overlapping_start_and_end() { test_harness( r#" fn foo() { diff --git a/compiler/rustc_feature/src/removed.rs b/compiler/rustc_feature/src/removed.rs index 48d9fbfa6d261..876a31abdf882 100644 --- a/compiler/rustc_feature/src/removed.rs +++ b/compiler/rustc_feature/src/removed.rs @@ -139,7 +139,7 @@ declare_features! ( /// Allows using `#[on_unimplemented(..)]` on traits. /// (Moved to `rustc_attrs`.) (removed, on_unimplemented, "1.40.0", None, None, None), - /// A way to temporarily opt out of opt in copy. This will *never* be accepted. + /// A way to temporarily opt out of opt-in copy. This will *never* be accepted. (removed, opt_out_copy, "1.0.0", None, None, None), /// Allows features specific to OIBIT (now called auto traits). /// Renamed to `auto_traits`. diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index 8d1156c1771e9..7eb12d380a769 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -2061,7 +2061,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { err.note("enum variants can't have type parameters"); let type_name = tcx.item_name(adt_def.did()); let msg = format!( - "you might have meant to specity type parameters on enum \ + "you might have meant to specify type parameters on enum \ `{type_name}`" ); let Some(args) = assoc_segment.args else { return; }; diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 0f40cca9427b4..d7443ea6998e2 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -83,7 +83,7 @@ fn visit_implementation_of_copy(tcx: TyCtxt<'_>, impl_did: LocalDefId) { let cause = traits::ObligationCause::misc(span, impl_did); match type_allowed_to_implement_copy(tcx, param_env, self_type, cause) { Ok(()) => {} - Err(CopyImplementationError::InfrigingFields(fields)) => { + Err(CopyImplementationError::InfringingFields(fields)) => { let mut err = struct_span_err!( tcx.sess, span, diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index e758fe95d9c29..3cb217335bda0 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -1333,7 +1333,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { // We may fail to resolve higher-ranked lifetimes that are mentioned by APIT. // AST-based resolution does not care for impl-trait desugaring, which are the - // responibility of lowering. This may create a mismatch between the resolution + // responsibility of lowering. This may create a mismatch between the resolution // AST found (`region_def_id`) which points to HRTB, and what HIR allows. // ``` // fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {} diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 8fa3bcd68c3d3..507c24d540cc5 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -976,7 +976,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Attempt to coerce an expression to a type, and return the /// adjusted type of the expression, if successful. /// Adjustments are only recorded if the coercion succeeded. - /// The expressions *must not* have any pre-existing adjustments. + /// The expressions *must not* have any preexisting adjustments. pub fn try_coerce( &self, expr: &hir::Expr<'_>, @@ -1340,7 +1340,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { } /// As an optimization, you can create a `CoerceMany` with a - /// pre-existing slice of expressions. In this case, you are + /// preexisting slice of expressions. In this case, you are /// expected to pass each element in the slice to `coerce(...)` in /// order. This is used with arrays in particular to avoid /// needlessly cloning the slice. diff --git a/compiler/rustc_hir_typeck/src/errors.rs b/compiler/rustc_hir_typeck/src/errors.rs index 3eee2278dcadd..5be78416e6128 100644 --- a/compiler/rustc_hir_typeck/src/errors.rs +++ b/compiler/rustc_hir_typeck/src/errors.rs @@ -108,7 +108,7 @@ pub enum ExpectedReturnTypeLabel<'tcx> { #[derive(Diagnostic)] #[diag(hir_typeck_missing_parentheses_in_range, code = "E0689")] -pub struct MissingParentheseInRange { +pub struct MissingParenthesesInRange { #[primary_span] #[label(hir_typeck_missing_parentheses_in_range)] pub span: Span, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index f736f7a96207e..13a869caa8fa6 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -827,7 +827,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } QPath::TypeRelative(ref qself, ref segment) => { // Don't use `self.to_ty`, since this will register a WF obligation. - // If we're trying to call a non-existent method on a trait + // If we're trying to call a nonexistent method on a trait // (e.g. `MyTrait::missing_method`), then resolution will // give us a `QPath::TypeRelative` with a trait object as // `qself`. In that case, we want to avoid registering a WF obligation 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 c3e5f9cb745fc..56c94505727e8 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 @@ -330,7 +330,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// expression mentioned. /// /// `blame_specific_arg_if_possible` will find the most-specific expression anywhere inside - /// the provided function call expression, and mark it as responsible for the fullfillment + /// the provided function call expression, and mark it as responsible for the fulfillment /// error. fn blame_specific_arg_if_possible( &self, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index e82821850d62e..eef2b5009c82d 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -794,7 +794,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; }; - // get all where BoundPredicates here, because they are used in to cases below + // get all where BoundPredicates here, because they are used in two cases below let where_predicates = predicates .iter() .filter_map(|p| match p { diff --git a/compiler/rustc_hir_typeck/src/generator_interior/mod.rs b/compiler/rustc_hir_typeck/src/generator_interior/mod.rs index f397108044333..8feef332de8a7 100644 --- a/compiler/rustc_hir_typeck/src/generator_interior/mod.rs +++ b/compiler/rustc_hir_typeck/src/generator_interior/mod.rs @@ -650,7 +650,7 @@ fn check_must_not_suspend_ty<'tcx>( }, ) } - // If drop tracking is enabled, we want to look through references, since the referrent + // If drop tracking is enabled, we want to look through references, since the referent // may not be considered live across the await point. ty::Ref(_region, ty, _mutability) if fcx.sess().opts.unstable_opts.drop_tracking => { let descr_pre = &format!("{}reference{} to ", data.descr_pre, plural_suffix); diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 900a6fa0d8db3..db1f10f645fd4 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -1530,7 +1530,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); if pick.is_ok() { let range_span = parent_expr.span.with_hi(expr.span.hi()); - tcx.sess.emit_err(errors::MissingParentheseInRange { + tcx.sess.emit_err(errors::MissingParenthesesInRange { span, ty_str: ty_str.to_string(), method_name: item_name.as_str().to_string(), diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index af0bd26dec5f9..7160d1c67b251 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -1659,7 +1659,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if tcx.sess.teach(&err.get_code().unwrap()) { err.note( "This error indicates that a struct pattern attempted to \ - extract a non-existent field from a struct. Struct fields \ + extract a nonexistent field from a struct. Struct fields \ are identified by the name used before the colon : so struct \ patterns should resemble the declaration of the struct type \ being matched.\n\n\ diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 41a6ad80b65a3..147b3e74d0f8a 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -223,7 +223,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_def_id); if should_do_rust_2021_incompatible_closure_captures_analysis(self.tcx, closure_hir_id) { - self.perform_2229_migration_anaysis(closure_def_id, body_id, capture_clause, span); + self.perform_2229_migration_analysis(closure_def_id, body_id, capture_clause, span); } let after_feature_tys = self.final_upvar_tys(closure_def_id); @@ -731,7 +731,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Perform the migration analysis for RFC 2229, and emit lint /// `disjoint_capture_drop_reorder` if needed. - fn perform_2229_migration_anaysis( + fn perform_2229_migration_analysis( &self, closure_def_id: LocalDefId, body_id: hir::BodyId, diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 1d88dfd20c8cd..43274091cb873 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -139,7 +139,7 @@ pub fn check_dirty_clean_annotations(tcx: TyCtxt<'_>) { return; } - // can't add `#[rustc_clean]` etc without opting in to this feature + // can't add `#[rustc_clean]` etc without opting into this feature if !tcx.features().rustc_attrs { return; } diff --git a/compiler/rustc_infer/messages.ftl b/compiler/rustc_infer/messages.ftl index c8998ea91bfe1..fdc4ff0896f5b 100644 --- a/compiler/rustc_infer/messages.ftl +++ b/compiler/rustc_infer/messages.ftl @@ -80,7 +80,7 @@ infer_subtype = ...so that the {$requirement -> [no_else] `if` missing an `else` returns `()` [fn_main_correct_type] `main` function has the correct type [fn_start_correct_type] `#[start]` function has the correct type - [intristic_correct_type] intrinsic has the correct type + [intrinsic_correct_type] intrinsic has the correct type [method_correct_type] method receiver has the correct type *[other] types are compatible } @@ -93,7 +93,7 @@ infer_subtype_2 = ...so that {$requirement -> [no_else] `if` missing an `else` returns `()` [fn_main_correct_type] `main` function has the correct type [fn_start_correct_type] `#[start]` function has the correct type - [intristic_correct_type] intrinsic has the correct type + [intrinsic_correct_type] intrinsic has the correct type [method_correct_type] method receiver has the correct type *[other] types are compatible } @@ -341,8 +341,8 @@ infer_await_note = calling an async function returns a future infer_prlf_defined_with_sub = the lifetime `{$sub_symbol}` defined here... infer_prlf_defined_without_sub = the lifetime defined here... -infer_prlf_must_oultive_with_sup = ...must outlive the lifetime `{$sup_symbol}` defined here -infer_prlf_must_oultive_without_sup = ...must outlive the lifetime defined here +infer_prlf_must_outlive_with_sup = ...must outlive the lifetime `{$sup_symbol}` defined here +infer_prlf_must_outlive_without_sup = ...must outlive the lifetime defined here infer_prlf_known_limitation = this is a known limitation that will be removed in the future (see issue #100013 for more information) infer_opaque_captures_lifetime = hidden type for `{$opaque_ty}` captures lifetime that does not appear in bounds @@ -380,7 +380,7 @@ infer_oc_no_else = `if` may be missing an `else` clause infer_oc_no_diverge = `else` clause of `let...else` does not diverge infer_oc_fn_main_correct_type = `main` function has wrong type infer_oc_fn_start_correct_type = `#[start]` function has wrong type -infer_oc_intristic_correct_type = intrinsic has wrong type +infer_oc_intrinsic_correct_type = intrinsic has wrong type infer_oc_method_correct_type = mismatched `self` parameter type infer_oc_closure_selfref = closure/generator type that references itself infer_oc_cant_coerce = cannot coerce intrinsics to function pointers diff --git a/compiler/rustc_infer/src/errors/mod.rs b/compiler/rustc_infer/src/errors/mod.rs index 65b3dd1a892b8..b1e819e83f19b 100644 --- a/compiler/rustc_infer/src/errors/mod.rs +++ b/compiler/rustc_infer/src/errors/mod.rs @@ -71,7 +71,7 @@ pub struct AmbiguousImpl<'a> { // Copy of `AnnotationRequired` for E0284 #[derive(Diagnostic)] #[diag(infer_type_annotations_needed, code = "E0284")] -pub struct AmbigousReturn<'a> { +pub struct AmbiguousReturn<'a> { #[primary_span] pub span: Span, pub source_kind: &'static str, @@ -1085,7 +1085,7 @@ pub enum PlaceholderRelationLfNotSatisfied { span: Span, #[note(infer_prlf_defined_with_sub)] sub_span: Span, - #[note(infer_prlf_must_oultive_with_sup)] + #[note(infer_prlf_must_outlive_with_sup)] sup_span: Span, sub_symbol: Symbol, sup_symbol: Symbol, @@ -1098,7 +1098,7 @@ pub enum PlaceholderRelationLfNotSatisfied { span: Span, #[note(infer_prlf_defined_with_sub)] sub_span: Span, - #[note(infer_prlf_must_oultive_without_sup)] + #[note(infer_prlf_must_outlive_without_sup)] sup_span: Span, sub_symbol: Symbol, #[note(infer_prlf_known_limitation)] @@ -1110,7 +1110,7 @@ pub enum PlaceholderRelationLfNotSatisfied { span: Span, #[note(infer_prlf_defined_without_sub)] sub_span: Span, - #[note(infer_prlf_must_oultive_with_sup)] + #[note(infer_prlf_must_outlive_with_sup)] sup_span: Span, sup_symbol: Symbol, #[note(infer_prlf_known_limitation)] @@ -1122,7 +1122,7 @@ pub enum PlaceholderRelationLfNotSatisfied { span: Span, #[note(infer_prlf_defined_without_sub)] sub_span: Span, - #[note(infer_prlf_must_oultive_without_sup)] + #[note(infer_prlf_must_outlive_without_sup)] sup_span: Span, #[note(infer_prlf_known_limitation)] note: (), @@ -1488,8 +1488,8 @@ pub enum ObligationCauseFailureCode { #[subdiagnostic] subdiags: Vec, }, - #[diag(infer_oc_intristic_correct_type, code = "E0308")] - IntristicCorrectType { + #[diag(infer_oc_intrinsic_correct_type, code = "E0308")] + IntrinsicCorrectType { #[primary_span] span: Span, #[subdiagnostic] diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index e98f68ae5a851..257d36259291e 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -467,11 +467,11 @@ impl<'tcx> InferCtxt<'tcx> { } } GenericArgKind::Const(result_value) => { - if let ty::ConstKind::Bound(debrujin, b) = result_value.kind() { + if let ty::ConstKind::Bound(debruijn, b) = result_value.kind() { // ...in which case we would set `canonical_vars[0]` to `Some(const X)`. // We only allow a `ty::INNERMOST` index in substitutions. - assert_eq!(debrujin, ty::INNERMOST); + assert_eq!(debruijn, ty::INNERMOST); opt_values[b] = Some(*original_value); } } diff --git a/compiler/rustc_infer/src/infer/combine.rs b/compiler/rustc_infer/src/infer/combine.rs index fe45b5ebe61b1..9b670c76a1822 100644 --- a/compiler/rustc_infer/src/infer/combine.rs +++ b/compiler/rustc_infer/src/infer/combine.rs @@ -832,7 +832,7 @@ pub trait ObligationEmittingRelation<'tcx>: TypeRelation<'tcx> { /// Register predicates that must hold in order for this relation to hold. Uses /// a default obligation cause, [`ObligationEmittingRelation::register_obligations`] should - /// be used if control over the obligaton causes is required. + /// be used if control over the obligation causes is required. fn register_predicates(&mut self, obligations: impl IntoIterator>); /// Register an obligation that both constants must be equal to each other. diff --git a/compiler/rustc_infer/src/infer/equate.rs b/compiler/rustc_infer/src/infer/equate.rs index fe4a2dd380073..f90f7674b55b1 100644 --- a/compiler/rustc_infer/src/infer/equate.rs +++ b/compiler/rustc_infer/src/infer/equate.rs @@ -178,7 +178,7 @@ impl<'tcx> TypeRelation<'tcx> for Equate<'_, '_, 'tcx> { where T: Relate<'tcx>, { - // A binder is equal to itself if it's structually equal to itself + // A binder is equal to itself if it's structurally equal to itself if a == b { return Ok(a); } diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 992b07db1543d..f6a4ddd7855ca 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -2886,7 +2886,7 @@ impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> { LetElse => ObligationCauseFailureCode::NoDiverge { span, subdiags }, MainFunctionType => ObligationCauseFailureCode::FnMainCorrectType { span }, StartFunctionType => ObligationCauseFailureCode::FnStartCorrectType { span, subdiags }, - IntrinsicType => ObligationCauseFailureCode::IntristicCorrectType { span, subdiags }, + IntrinsicType => ObligationCauseFailureCode::IntrinsicCorrectType { span, subdiags }, MethodReceiver => ObligationCauseFailureCode::MethodCorrectType { span, subdiags }, // In the case where we have no more specific thing to @@ -2943,7 +2943,7 @@ impl IntoDiagnosticArg for ObligationCauseAsDiagArg<'_> { IfExpressionWithNoElse => "no_else", MainFunctionType => "fn_main_correct_type", StartFunctionType => "fn_start_correct_type", - IntrinsicType => "intristic_correct_type", + IntrinsicType => "intrinsic_correct_type", MethodReceiver => "method_correct_type", _ => "other", } diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index 75cc4e257bd83..58e3159a4e217 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -1,5 +1,5 @@ use crate::errors::{ - AmbigousReturn, AmbiguousImpl, AnnotationRequired, InferenceBadError, NeedTypeInfoInGenerator, + AmbiguousImpl, AmbiguousReturn, AnnotationRequired, InferenceBadError, NeedTypeInfoInGenerator, SourceKindMultiSuggestion, SourceKindSubdiag, }; use crate::infer::error_reporting::TypeErrCtxt; @@ -368,7 +368,7 @@ impl<'tcx> InferCtxt<'tcx> { bad_label, } .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic), - TypeAnnotationNeeded::E0284 => AmbigousReturn { + TypeAnnotationNeeded::E0284 => AmbiguousReturn { span, source_kind, source_name, @@ -573,7 +573,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { bad_label: None, } .into_diagnostic(&self.tcx.sess.parse_sess.span_diagnostic), - TypeAnnotationNeeded::E0284 => AmbigousReturn { + TypeAnnotationNeeded::E0284 => AmbiguousReturn { span, source_kind, source_name: &name, diff --git a/compiler/rustc_infer/src/infer/higher_ranked/mod.rs b/compiler/rustc_infer/src/infer/higher_ranked/mod.rs index a63cfbc919c65..c304cd25c9c41 100644 --- a/compiler/rustc_infer/src/infer/higher_ranked/mod.rs +++ b/compiler/rustc_infer/src/infer/higher_ranked/mod.rs @@ -42,7 +42,7 @@ impl<'a, 'tcx> CombineFields<'a, 'tcx> { // Next, we instantiate each bound region in the subtype // with a fresh region variable. These region variables -- - // but no other pre-existing region variables -- can name + // but no other preexisting region variables -- can name // the placeholders. let sub_prime = self.infcx.instantiate_binder_with_fresh_vars(span, HigherRankedType, sub); diff --git a/compiler/rustc_infer/src/infer/sub.rs b/compiler/rustc_infer/src/infer/sub.rs index 0dd73a6e999ee..3766c250a9c70 100644 --- a/compiler/rustc_infer/src/infer/sub.rs +++ b/compiler/rustc_infer/src/infer/sub.rs @@ -210,7 +210,7 @@ impl<'tcx> TypeRelation<'tcx> for Sub<'_, '_, 'tcx> { where T: Relate<'tcx>, { - // A binder is always a subtype of itself if it's structually equal to itself + // A binder is always a subtype of itself if it's structurally equal to itself if a == b { return Ok(a); } diff --git a/compiler/rustc_infer/src/traits/project.rs b/compiler/rustc_infer/src/traits/project.rs index ac455055b4303..8d0af738dd115 100644 --- a/compiler/rustc_infer/src/traits/project.rs +++ b/compiler/rustc_infer/src/traits/project.rs @@ -103,7 +103,7 @@ pub enum ProjectionCacheEntry<'tcx> { /// if this field is set. Evaluation only /// cares about the final result, so we don't /// care about any region constraint side-effects - /// produced by evaluating the sub-boligations. + /// produced by evaluating the sub-obligations. /// /// Additionally, we will clear out the sub-obligations /// entirely if we ever evaluate the cache entry (along diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 6b387df785e7d..b986dde5a02b2 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -22,7 +22,7 @@ use crate::fluent_generated as fluent; use crate::{ - errors::BuiltinEllpisisInclusiveRangePatterns, + errors::BuiltinEllipsisInclusiveRangePatterns, lints::{ BuiltinAnonymousParams, BuiltinBoxPointers, BuiltinClashingExtern, BuiltinClashingExternSub, BuiltinConstNoMangle, BuiltinDeprecatedAttrLink, @@ -1711,13 +1711,13 @@ impl EarlyLintPass for EllipsisInclusiveRangePatterns { } } - let (parenthesise, endpoints) = match &pat.kind { + let (parentheses, endpoints) = match &pat.kind { PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)), _ => (false, matches_ellipsis_pat(pat)), }; if let Some((start, end, join)) = endpoints { - if parenthesise { + if parentheses { self.node_id = Some(pat.id); let end = expr_to_string(&end); let replace = match start { @@ -1725,7 +1725,7 @@ impl EarlyLintPass for EllipsisInclusiveRangePatterns { None => format!("&(..={})", end), }; if join.edition() >= Edition::Edition2021 { - cx.sess().emit_err(BuiltinEllpisisInclusiveRangePatterns { + cx.sess().emit_err(BuiltinEllipsisInclusiveRangePatterns { span: pat.span, suggestion: pat.span, replace, @@ -1743,7 +1743,7 @@ impl EarlyLintPass for EllipsisInclusiveRangePatterns { } else { let replace = "..="; if join.edition() >= Edition::Edition2021 { - cx.sess().emit_err(BuiltinEllpisisInclusiveRangePatterns { + cx.sess().emit_err(BuiltinEllipsisInclusiveRangePatterns { span: pat.span, suggestion: join, replace: replace.to_string(), @@ -2560,7 +2560,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { .subst(cx.tcx, substs) .apply_any_module(cx.tcx, cx.param_env) { - // Entirely skip uninhbaited variants. + // Entirely skip uninhabited variants. Some(false) => return None, // Forward the others, but remember which ones are definitely inhabited. Some(true) => true, diff --git a/compiler/rustc_lint/src/errors.rs b/compiler/rustc_lint/src/errors.rs index 9af5284df1e29..bbae3d368f43c 100644 --- a/compiler/rustc_lint/src/errors.rs +++ b/compiler/rustc_lint/src/errors.rs @@ -81,7 +81,7 @@ pub struct UnknownToolInScopedLint { #[derive(Diagnostic)] #[diag(lint_builtin_ellipsis_inclusive_range_patterns, code = "E0783")] -pub struct BuiltinEllpisisInclusiveRangePatterns { +pub struct BuiltinEllipsisInclusiveRangePatterns { #[primary_span] pub span: Span, #[suggestion(style = "short", code = "{replace}", applicability = "machine-applicable")] diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 9d6ab0b75df17..b223b8c137a1a 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -1021,7 +1021,7 @@ declare_lint! { declare_lint! { /// The `invalid_alignment` lint detects dereferences of misaligned pointers during - /// constant evluation. + /// constant evaluation. /// /// ### Example /// @@ -1854,7 +1854,7 @@ declare_lint! { /// When new methods are added to traits in the standard library, they are /// usually added in an "unstable" form which is only available on the /// [nightly channel] with a [`feature` attribute]. If there is any - /// pre-existing code which extends a trait to have a method with the same + /// preexisting code which extends a trait to have a method with the same /// name, then the names will collide. In the future, when the method is /// stabilized, this will cause an error due to the ambiguity. This lint /// is an early-warning to let you know that there may be a collision in diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index 08e38b0c9d59e..c9acbab253e10 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -811,7 +811,7 @@ LLVMRustOptimize( ModulePassManager MPM; bool NeedThinLTOBufferPasses = UseThinLTOBuffers; if (!NoPrepopulatePasses) { - // The pre-link pipelines don't support O0 and require using budilO0DefaultPipeline() instead. + // The pre-link pipelines don't support O0 and require using buildO0DefaultPipeline() instead. // At the same time, the LTO pipelines do support O0 and using them is required. bool IsLTO = OptStage == LLVMRustOptStage::ThinLTO || OptStage == LLVMRustOptStage::FatLTO; if (OptLevel == OptimizationLevel::O0 && !IsLTO) { diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index 2930ce75028b7..e7154167ddb7f 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -117,7 +117,7 @@ pub(crate) struct CrateMetadata { /// Additional data used for decoding `HygieneData` (e.g. `SyntaxContext` /// and `ExpnId`). - /// Note that we store a `HygieneDecodeContext` for each `CrateMetadat`. This is + /// Note that we store a `HygieneDecodeContext` for each `CrateMetadata`. This is /// because `SyntaxContext` ids are not globally unique, so we need /// to track which ids we've decoded on a per-crate basis. hygiene_context: HygieneDecodeContext, @@ -627,7 +627,7 @@ impl<'a, 'tcx> Decodable> for Symbol { let pos = d.read_usize(); let old_pos = d.opaque.position(); - // move to str ofset and read + // move to str offset and read d.opaque.set_position(pos); let s = d.read_str(); let sym = Symbol::intern(s); diff --git a/compiler/rustc_middle/src/mir/interpret/pointer.rs b/compiler/rustc_middle/src/mir/interpret/pointer.rs index 60927eed85d3b..65d04919357f3 100644 --- a/compiler/rustc_middle/src/mir/interpret/pointer.rs +++ b/compiler/rustc_middle/src/mir/interpret/pointer.rs @@ -102,7 +102,7 @@ impl PointerArithmetic for T {} /// This trait abstracts over the kind of provenance that is associated with a `Pointer`. It is /// mostly opaque; the `Machine` trait extends it with some more operations that also have access to /// some global state. -/// The `Debug` rendering is used to distplay bare provenance, and for the default impl of `fmt`. +/// The `Debug` rendering is used to display bare provenance, and for the default impl of `fmt`. pub trait Provenance: Copy + fmt::Debug { /// Says whether the `offset` field of `Pointer`s with this provenance is the actual physical address. /// - If `false`, the offset *must* be relative. This means the bytes representing a pointer are diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 135889d0da810..c38a347809f4f 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -251,7 +251,7 @@ pub enum StatementKind<'tcx> { /// **Needs clarification**: The implication of the above idea would be that assignment implies /// that the resulting value is initialized. I believe we could commit to this separately from /// committing to whatever part of the memory model we would need to decide on to make the above - /// paragragh precise. Do we want to? + /// paragraph precise. Do we want to? /// /// Assignments in which the types of the place and rvalue differ are not well-formed. /// @@ -997,7 +997,7 @@ pub type PlaceElem<'tcx> = ProjectionElem>; /// This is what is implemented in miri today. Are these the semantics we want for MIR? Is this /// something we can even decide without knowing more about Rust's memory model? /// -/// **Needs clarifiation:** Is loading a place that has its variant index set well-formed? Miri +/// **Needs clarification:** Is loading a place that has its variant index set well-formed? Miri /// currently implements it, but it seems like this may be something to check against in the /// validator. #[derive(Clone, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable, TypeVisitable)] diff --git a/compiler/rustc_middle/src/ty/abstract_const.rs b/compiler/rustc_middle/src/ty/abstract_const.rs index f889ce82706b3..223b763e34bfa 100644 --- a/compiler/rustc_middle/src/ty/abstract_const.rs +++ b/compiler/rustc_middle/src/ty/abstract_const.rs @@ -1,4 +1,4 @@ -//! A subset of a mir body used for const evaluatability checking. +//! A subset of a mir body used for const evaluability checking. use crate::ty::{ self, Const, EarlyBinder, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, diff --git a/compiler/rustc_middle/src/ty/fast_reject.rs b/compiler/rustc_middle/src/ty/fast_reject.rs index 31d00b65e9843..76f61d9ac9c2d 100644 --- a/compiler/rustc_middle/src/ty/fast_reject.rs +++ b/compiler/rustc_middle/src/ty/fast_reject.rs @@ -68,7 +68,7 @@ pub enum TreatParams { } /// During fast-rejection, we have the choice of treating projection types -/// as either simplifyable or not, depending on whether we expect the projection +/// as either simplifiable or not, depending on whether we expect the projection /// to be normalized/rigid. #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum TreatProjections { diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 195d951f9f366..1e2fd86e13dc8 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -235,7 +235,7 @@ impl IntoDiagnostic<'_, !> for LayoutError<'_> { } } -// FIXME: Once the other errors that embed this error have been converted to translateable +// FIXME: Once the other errors that embed this error have been converted to translatable // diagnostics, this Display impl should be removed. impl<'tcx> fmt::Display for LayoutError<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -458,10 +458,10 @@ impl<'tcx> SizeSkeleton<'tcx> { } } -/// When creating the layout for types with abstract conts in their size (i.e. [usize; 4 * N]), +/// When creating the layout for types with abstract consts in their size (i.e. [usize; 4 * N]), /// to ensure that they have a canonical order and can be compared directly we combine all /// constants, and sort the other terms. This allows comparison of expressions of sizes, -/// allowing for things like transmutating between types that depend on generic consts. +/// allowing for things like transmuting between types that depend on generic consts. /// This returns `None` if multiplication of constants overflows. fn mul_sorted_consts<'tcx>( tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 7706fdddeb833..8a2258375ab4d 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -197,7 +197,7 @@ impl<'tcx> fmt::Debug for AliasTy<'tcx> { // Atomic structs // // For things that don't carry any arena-allocated data (and are -// copy...), just add them to one of these lists as appropriat. +// copy...), just add them to one of these lists as appropriate. // For things for which the type library provides traversal implementations // for all Interners, we only need to provide a Lift implementation: diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index c8a78ec03d947..b58bd24ec5286 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -642,7 +642,7 @@ impl<'tcx> TyCtxt<'tcx> { } } - /// Return the set of types that should be taken into accound when checking + /// Return the set of types that should be taken into account when checking /// trait bounds on a generator's internal state. pub fn generator_hidden_types( self, @@ -1402,7 +1402,7 @@ pub fn is_trivially_const_drop(ty: Ty<'_>) -> bool { } /// Does the equivalent of -/// ```ignore (ilustrative) +/// ```ignore (illustrative) /// let v = self.iter().map(|p| p.fold_with(folder)).collect::>(); /// folder.tcx().intern_*(&v) /// ``` diff --git a/compiler/rustc_mir_build/src/build/expr/into.rs b/compiler/rustc_mir_build/src/build/expr/into.rs index 05a723a6b6750..9b38ac1cc4ce7 100644 --- a/compiler/rustc_mir_build/src/build/expr/into.rs +++ b/compiler/rustc_mir_build/src/build/expr/into.rs @@ -163,13 +163,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // // [block: If(lhs)] -true-> [else_block: dest = (rhs)] // | (false) - // [shortcurcuit_block: dest = false] + // [shortcircuit_block: dest = false] // // Or: // // [block: If(lhs)] -false-> [else_block: dest = (rhs)] // | (true) - // [shortcurcuit_block: dest = true] + // [shortcircuit_block: dest = true] let (shortcircuit_block, mut else_block, join_block) = ( this.cfg.start_new_block(), diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index 8a03ea7e2cc7f..4536ecf17b813 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -77,7 +77,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { | PatKind::Wild | PatKind::Binding { .. } | PatKind::Leaf { .. } - | PatKind::Deref { .. } => self.error_simplifyable(match_pair), + | PatKind::Deref { .. } => self.error_simplifiable(match_pair), } } @@ -173,7 +173,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { debug_assert_ne!( target_blocks[idx.index()], otherwise_block, - "no canididates for tested discriminant: {:?}", + "no candidates for tested discriminant: {:?}", discr, ); Some((discr.val, target_blocks[idx.index()])) @@ -181,7 +181,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { debug_assert_eq!( target_blocks[idx.index()], otherwise_block, - "found canididates for untested discriminant: {:?}", + "found candidates for untested discriminant: {:?}", discr, ); None @@ -499,7 +499,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// However, in some cases, the test may just not be relevant to candidate. /// For example, suppose we are testing whether `foo.x == 22`, but in one /// match arm we have `Foo { x: _, ... }`... in that case, the test for - /// what value `x` has has no particular relevance to this candidate. In + /// the value of `x` has no particular relevance to this candidate. In /// such cases, this function just returns None without doing anything. /// This is used by the overall `match_candidates` algorithm to structure /// the match as a whole. See `match_candidates` for more details. @@ -763,8 +763,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { candidate.match_pairs.extend(consequent_match_pairs); } - fn error_simplifyable<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> ! { - span_bug!(match_pair.pattern.span, "simplifyable pattern found: {:?}", match_pair.pattern) + fn error_simplifiable<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> ! { + span_bug!(match_pair.pattern.span, "simplifiable pattern found: {:?}", match_pair.pattern) } fn const_range_contains( diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index 32d0404bd0739..c99fc73fe8a34 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -156,7 +156,7 @@ impl<'tcx> ConstToPat<'tcx> { if let Some(non_sm_ty) = structural { if !self.type_may_have_partial_eq_impl(cv.ty()) { - // fatal avoids ICE from resolution of non-existent method (rare case). + // fatal avoids ICE from resolution of nonexistent method (rare case). self.tcx() .sess .emit_fatal(TypeNotStructural { span: self.span, non_sm_ty: non_sm_ty }); diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index 98bebc9b13bc5..d8fd06eab86d1 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -366,7 +366,7 @@ where rustc_index::newtype_index!( /// This index uniquely identifies a place. /// - /// Not every place has a `PlaceIndex`, and not every `PlaceIndex` correspondends to a tracked + /// Not every place has a `PlaceIndex`, and not every `PlaceIndex` corresponds to a tracked /// place. However, every tracked place and all places along its projection have a `PlaceIndex`. pub struct PlaceIndex {} ); diff --git a/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs b/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs index 896fcd9cdd608..b29ffcc70f93f 100644 --- a/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs +++ b/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs @@ -10,7 +10,7 @@ use rustc_middle::mir::patch::MirPatch; /// they are dropped from an aligned address. /// /// For example, if we have something like -/// ```ignore (ilustrative) +/// ```ignore (illustrative) /// #[repr(packed)] /// struct Foo { /// dealign: u8, @@ -25,7 +25,7 @@ use rustc_middle::mir::patch::MirPatch; /// its address is not aligned. /// /// Instead, we move `foo.data` to a local and drop that: -/// ```ignore (ilustrative) +/// ```ignore (illustrative) /// storage.live(drop_temp) /// drop_temp = foo.data; /// drop(drop_temp) -> next diff --git a/compiler/rustc_mir_transform/src/add_retag.rs b/compiler/rustc_mir_transform/src/add_retag.rs index 916f2904dda80..187d38b385be3 100644 --- a/compiler/rustc_mir_transform/src/add_retag.rs +++ b/compiler/rustc_mir_transform/src/add_retag.rs @@ -59,7 +59,7 @@ impl<'tcx> MirPass<'tcx> for AddRetag { let basic_blocks = body.basic_blocks.as_mut(); let local_decls = &body.local_decls; let needs_retag = |place: &Place<'tcx>| { - !place.has_deref() // we're not eally interested in stores to "outside" locations, they are hard to keep track of anyway + !place.has_deref() // we're not really interested in stores to "outside" locations, they are hard to keep track of anyway && may_contain_reference(place.ty(&*local_decls, tcx).ty, /*depth*/ 3, tcx) && !local_decls[place.local].is_deref_temp() }; diff --git a/compiler/rustc_mir_transform/src/const_debuginfo.rs b/compiler/rustc_mir_transform/src/const_debuginfo.rs index 6f0ae4f07ab79..692b3182f7d23 100644 --- a/compiler/rustc_mir_transform/src/const_debuginfo.rs +++ b/compiler/rustc_mir_transform/src/const_debuginfo.rs @@ -22,7 +22,7 @@ impl<'tcx> MirPass<'tcx> for ConstDebugInfo { fn run_pass(&self, _tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { trace!("running ConstDebugInfo on {:?}", body.source); - for (local, constant) in find_optimization_oportunities(body) { + for (local, constant) in find_optimization_opportunities(body) { for debuginfo in &mut body.var_debug_info { if let VarDebugInfoContents::Place(p) = debuginfo.value { if p.local == local && p.projection.is_empty() { @@ -45,7 +45,7 @@ struct LocalUseVisitor { local_assignment_locations: IndexVec>, } -fn find_optimization_oportunities<'tcx>(body: &Body<'tcx>) -> Vec<(Local, Constant<'tcx>)> { +fn find_optimization_opportunities<'tcx>(body: &Body<'tcx>) -> Vec<(Local, Constant<'tcx>)> { let mut visitor = LocalUseVisitor { local_mutating_uses: IndexVec::from_elem(0, &body.local_decls), local_assignment_locations: IndexVec::from_elem(None, &body.local_decls), diff --git a/compiler/rustc_mir_transform/src/const_prop.rs b/compiler/rustc_mir_transform/src/const_prop.rs index c0146e3efb02e..c9537f9a61c09 100644 --- a/compiler/rustc_mir_transform/src/const_prop.rs +++ b/compiler/rustc_mir_transform/src/const_prop.rs @@ -826,7 +826,7 @@ impl Visitor<'_> for CanConstProp { | NonMutatingUse(NonMutatingUseContext::AddressOf) | MutatingUse(MutatingUseContext::Borrow) | MutatingUse(MutatingUseContext::AddressOf) => { - trace!("local {:?} can't be propagaged because it's used: {:?}", local, context); + trace!("local {:?} can't be propagated because it's used: {:?}", local, context); self.can_const_prop[local] = ConstPropMode::NoPropagation; } } diff --git a/compiler/rustc_mir_transform/src/coverage/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs index 7391a77b0a66b..8ff67b5f8d3ff 100644 --- a/compiler/rustc_mir_transform/src/coverage/graph.rs +++ b/compiler/rustc_mir_transform/src/coverage/graph.rs @@ -111,7 +111,7 @@ impl CoverageGraph { if predecessors.len() > 1 { "predecessors.len() > 1".to_owned() } else { - format!("bb {} is not in precessors: {:?}", bb.index(), predecessors) + format!("bb {} is not in predecessors: {:?}", bb.index(), predecessors) } ); } diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index d4db7e2de4039..a56c5cc5c12f9 100644 --- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs +++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs @@ -351,7 +351,7 @@ impl<'a, 'tcx> ConstAnalysis<'a, 'tcx> { } (FlatSet::Bottom, _) | (_, FlatSet::Bottom) => (FlatSet::Bottom, FlatSet::Bottom), (_, _) => { - // Could attempt some algebraic simplifcations here. + // Could attempt some algebraic simplifications here. (FlatSet::Top, FlatSet::Top) } } diff --git a/compiler/rustc_mir_transform/src/dest_prop.rs b/compiler/rustc_mir_transform/src/dest_prop.rs index 3916491777088..5a842714e5dad 100644 --- a/compiler/rustc_mir_transform/src/dest_prop.rs +++ b/compiler/rustc_mir_transform/src/dest_prop.rs @@ -69,7 +69,7 @@ //! of this is that such liveness analysis can report more accurate results about whole locals at //! a time. For example, consider: //! -//! ```ignore (syntax-highliting-only) +//! ```ignore (syntax-highlighting-only) //! _1 = u; //! // unrelated code //! _1.f1 = v; @@ -360,7 +360,7 @@ struct FilterInformation<'a, 'body, 'alloc, 'tcx> { } // We first implement some utility functions which we will expose removing candidates according to -// different needs. Throughout the livenss filtering, the `candidates` are only ever accessed +// different needs. Throughout the liveness filtering, the `candidates` are only ever accessed // through these methods, and not directly. impl<'alloc> Candidates<'alloc> { /// Just `Vec::retain`, but the condition is inverted and we add debugging output diff --git a/compiler/rustc_mir_transform/src/elaborate_drops.rs b/compiler/rustc_mir_transform/src/elaborate_drops.rs index a702113bd9998..1e115be2c2ab9 100644 --- a/compiler/rustc_mir_transform/src/elaborate_drops.rs +++ b/compiler/rustc_mir_transform/src/elaborate_drops.rs @@ -24,7 +24,7 @@ use std::fmt; /// In general, the compiler cannot determine at compile time whether a destructor will run or not. /// /// At a high level, this pass refines Drop to only run the destructor if the -/// target is initialized. The way this is achievied is by inserting drop flags for every variable +/// target is initialized. The way this is achieved is by inserting drop flags for every variable /// that may be dropped, and then using those flags to determine whether a destructor should run. /// Once this is complete, Drop terminators in the MIR correspond to a call to the "drop glue" or /// "drop shim" for the type of the dropped place. diff --git a/compiler/rustc_mir_transform/src/generator.rs b/compiler/rustc_mir_transform/src/generator.rs index 4c4423721fb8c..507e12d723894 100644 --- a/compiler/rustc_mir_transform/src/generator.rs +++ b/compiler/rustc_mir_transform/src/generator.rs @@ -1869,7 +1869,7 @@ fn check_must_not_suspend_ty<'tcx>( }, ) } - // If drop tracking is enabled, we want to look through references, since the referrent + // If drop tracking is enabled, we want to look through references, since the referent // may not be considered live across the await point. ty::Ref(_region, ty, _mutability) => { let descr_pre = &format!("{}reference{} to ", data.descr_pre, plural_suffix); diff --git a/compiler/rustc_mir_transform/src/ssa.rs b/compiler/rustc_mir_transform/src/ssa.rs index be026402dd578..9d9c5d540381a 100644 --- a/compiler/rustc_mir_transform/src/ssa.rs +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -21,7 +21,7 @@ pub struct SsaLocals { /// We often encounter MIR bodies with 1 or 2 basic blocks. In those cases, it's unnecessary to /// actually compute dominators, we can just compare block indices because bb0 is always the first -/// block, and in any body all other blocks are always always dominated by bb0. +/// block, and in any body all other blocks are always dominated by bb0. struct SmallDominators { inner: Option>, } diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 7bcff7e07fb34..2ed628871d2d7 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -402,7 +402,7 @@ fn collect_roots(tcx: TyCtxt<'_>, mode: MonoItemCollectionMode) -> Vec( tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_monomorphize/src/partitioning/default.rs b/compiler/rustc_monomorphize/src/partitioning/default.rs index 769e12f77bf2d..49126045d0cfe 100644 --- a/compiler/rustc_monomorphize/src/partitioning/default.rs +++ b/compiler/rustc_monomorphize/src/partitioning/default.rs @@ -424,7 +424,7 @@ fn mono_item_visibility<'tcx>( InstanceDef::Item(def) => def.did, InstanceDef::DropGlue(def_id, Some(_)) => def_id, - // We match the visiblity of statics here + // We match the visibility of statics here InstanceDef::ThreadLocalShim(def_id) => { return static_visibility(tcx, can_be_internalized, def_id); } diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs index 9e856c9f2120c..ad9b20f9c767a 100644 --- a/compiler/rustc_parse/src/lexer/mod.rs +++ b/compiler/rustc_parse/src/lexer/mod.rs @@ -67,7 +67,7 @@ pub(crate) fn parse_token_trees<'a>( match token_trees { Ok(stream) if unmatched_delims.is_empty() => Ok(stream), _ => { - // Return error if there are unmatched delimiters or unclosng delimiters. + // Return error if there are unmatched delimiters or unclosed delimiters. // We emit delimiter mismatch errors first, then emit the unclosing delimiter mismatch // because the delimiter mismatch is more likely to be the root cause of error diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs index 72402a200907a..2f397e303e508 100644 --- a/compiler/rustc_parse/src/validate_attr.rs +++ b/compiler/rustc_parse/src/validate_attr.rs @@ -68,7 +68,7 @@ pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Meta } } else { // The non-error case can happen with e.g. `#[foo = 1+1]`. The error case can - // happen with e.g. `#[foo = include_str!("non-existent-file.rs")]`; in that + // happen with e.g. `#[foo = include_str!("nonexistent-file.rs")]`; in that // case we delay the error because an earlier error will have already been // reported. let msg = format!("unexpected expression: `{}`", pprust::expr_to_string(expr)); diff --git a/compiler/rustc_query_impl/src/on_disk_cache.rs b/compiler/rustc_query_impl/src/on_disk_cache.rs index 30477c7bd4422..dc3cb64b3c279 100644 --- a/compiler/rustc_query_impl/src/on_disk_cache.rs +++ b/compiler/rustc_query_impl/src/on_disk_cache.rs @@ -744,7 +744,7 @@ impl<'a, 'tcx> Decodable> for Symbol { let pos = d.read_usize(); let old_pos = d.opaque.position(); - // move to str ofset and read + // move to str offset and read d.opaque.set_position(pos); let s = d.read_str(); let sym = Symbol::intern(s); diff --git a/compiler/rustc_query_system/messages.ftl b/compiler/rustc_query_system/messages.ftl index 870e824039cb6..0d01123ad88ba 100644 --- a/compiler/rustc_query_system/messages.ftl +++ b/compiler/rustc_query_system/messages.ftl @@ -1,4 +1,4 @@ -query_system_reentrant = internal compiler error: re-entrant incremental verify failure, suppressing message +query_system_reentrant = internal compiler error: reentrant incremental verify failure, suppressing message query_system_increment_compilation = internal compiler error: encountered incremental compilation error with {$dep_node} .help = This is a known issue with the compiler. Run {$run_cmd} to allow your project to compile diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index a9a2e6dd04c2d..fd9e685ab8085 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -249,7 +249,7 @@ impl DepGraph { /// get an ICE. Normally, we would have tried (and failed) to mark /// some other query green (e.g. `item_children`) which was used /// to obtain `C`, which would prevent us from ever trying to force - /// a non-existent `D`. + /// a nonexistent `D`. /// /// It might be possible to enforce that all `DepNode`s read during /// deserialization already exist in the previous `DepGraph`. In diff --git a/compiler/rustc_query_system/src/query/config.rs b/compiler/rustc_query_system/src/query/config.rs index c8d779385108f..bb9ea50a1ea56 100644 --- a/compiler/rustc_query_system/src/query/config.rs +++ b/compiler/rustc_query_system/src/query/config.rs @@ -63,7 +63,7 @@ pub trait QueryConfig: Copy { fn handle_cycle_error(self) -> HandleCycleError; fn hash_result(self) -> HashResult; - // Just here for convernience and checking that the key matches the kind, don't override this. + // Just here for convenience and checking that the key matches the kind, don't override this. fn construct_dep_node(self, tcx: Qcx::DepContext, key: &Self::Key) -> DepNode { DepNode::construct(tcx, self.dep_kind(), key) } diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index 20310483d7e86..132f3512ff2a6 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -691,7 +691,7 @@ fn incremental_verify_ich_failed( // which may result in another fingerprint mismatch while we're in the middle // of processing this one. To avoid a double-panic (which kills the process // before we can print out the query static), we print out a terse - // but 'safe' message if we detect a re-entrant call to this method. + // but 'safe' message if we detect a reentrant call to this method. thread_local! { static INSIDE_VERIFY_PANIC: Cell = const { Cell::new(false) }; }; diff --git a/compiler/rustc_resolve/src/effective_visibilities.rs b/compiler/rustc_resolve/src/effective_visibilities.rs index bed579f6b9258..87067189a7758 100644 --- a/compiler/rustc_resolve/src/effective_visibilities.rs +++ b/compiler/rustc_resolve/src/effective_visibilities.rs @@ -175,7 +175,7 @@ impl<'r, 'a, 'tcx> EffectiveVisibilitiesVisitor<'r, 'a, 'tcx> { /// to not update anything and we can skip it. /// /// We are checking this condition only if the correct value of private visibility is - /// cheaply available, otherwise it does't make sense performance-wise. + /// cheaply available, otherwise it doesn't make sense performance-wise. /// /// `None` is returned if the update can be skipped, /// and cheap private visibility is returned otherwise. diff --git a/compiler/rustc_resolve/src/errors.rs b/compiler/rustc_resolve/src/errors.rs index afa796cb6453b..af0ec236df063 100644 --- a/compiler/rustc_resolve/src/errors.rs +++ b/compiler/rustc_resolve/src/errors.rs @@ -22,7 +22,7 @@ pub(crate) struct UnderscoreLifetimeNameCannotBeUsedHere(#[primary_span] pub(cra #[derive(Diagnostic)] #[diag(resolve_crate_may_not_be_imported)] -pub(crate) struct CrateMayNotBeImprted(#[primary_span] pub(crate) Span); +pub(crate) struct CrateMayNotBeImported(#[primary_span] pub(crate) Span); #[derive(Diagnostic)] #[diag(resolve_crate_root_imports_must_be_named_explicitly)] diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 90a2fa89cd2ab..a97857e05e2e9 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -1079,7 +1079,7 @@ impl<'a: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast, for rib in self.lifetime_ribs.iter().rev() { match rib.kind { // We are inside a `PolyTraitRef`. The lifetimes are - // to be intoduced in that (maybe implicit) `for<>` binder. + // to be introduced in that (maybe implicit) `for<>` binder. LifetimeRibKind::Generics { binder, kind: LifetimeBinderKind::PolyTrait, @@ -3803,7 +3803,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { // use std::u8; // bring module u8 in scope // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8 // u8::max_value() // OK, resolves to associated function ::max_value, - // // not to non-existent std::u8::max_value + // // not to nonexistent std::u8::max_value // } // // Such behavior is required for backward compatibility. diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 37fbfad2de631..e824a6ddc072f 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -91,7 +91,7 @@ fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, Str /// Description of an elided lifetime. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] pub(super) struct MissingLifetime { - /// Used to overwrite the resolution with the suggestion, to avoid cascasing errors. + /// Used to overwrite the resolution with the suggestion, to avoid cascading errors. pub id: NodeId, /// Where to suggest adding the lifetime. pub span: Span, @@ -408,7 +408,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { } let Some(path_last_segment) = path.last() else { return }; let item_str = path_last_segment.ident; - // Emit help message for fake-self from other languages (e.g., `this` in Javascript). + // Emit help message for fake-self from other languages (e.g., `this` in JavaScript). if ["this", "my"].contains(&item_str.as_str()) { err.span_suggestion_short( span, diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index 29a7e74a81660..7f29922f6965c 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -483,7 +483,7 @@ impl SourceMap { self.span_to_string(sp, FileNameDisplayPreference::Remapped) } - /// Format the span location suitable for pretty printing anotations with relative line numbers + /// Format the span location suitable for pretty printing annotations with relative line numbers pub fn span_to_relative_line_string(&self, sp: Span, relative_to: Span) -> String { if self.files.borrow().source_files.is_empty() || sp.is_dummy() || relative_to.is_dummy() { return "no-location".to_string(); @@ -777,7 +777,7 @@ impl SourceMap { /// Given a 'Span', tries to tell if it's wrapped by "<>" or "()" /// the algorithm searches if the next character is '>' or ')' after skipping white space - /// then searches the previous charactoer to match '<' or '(' after skipping white space + /// then searches the previous character to match '<' or '(' after skipping white space /// return true if wrapped by '<>' or '()' pub fn span_wrapped_by_angle_or_parentheses(&self, span: Span) -> bool { self.span_to_source(span, |src, start_index, end_index| { diff --git a/compiler/rustc_target/src/abi/call/avr.rs b/compiler/rustc_target/src/abi/call/avr.rs index e20f01355a4a6..b01dac8c70d7e 100644 --- a/compiler/rustc_target/src/abi/call/avr.rs +++ b/compiler/rustc_target/src/abi/call/avr.rs @@ -10,7 +10,7 @@ //! > self-consistent and sensible LLVM IR generation, but does not //! > conform to any particular ABI. //! > -//! > - Doxygen Doxumentation of `clang::DefaultABIInfo` +//! > - Doxygen Documentation of `clang::DefaultABIInfo` //! //! This calling convention may not match AVR-GCC in all cases. //! diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 4e5a821f0f6ab..3ee3a8ea227ec 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -2285,13 +2285,13 @@ impl Target { } } } ); - ($key_name:ident, falliable_list) => ( { + ($key_name:ident, fallible_list) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.remove(&name).and_then(|j| { if let Some(v) = j.as_array() { match v.iter().map(|a| FromStr::from_str(a.as_str().unwrap())).collect() { Ok(l) => { base.$key_name = l }, - // FIXME: `falliable_list` can't re-use the `key!` macro for list + // FIXME: `fallible_list` can't re-use the `key!` macro for list // elements and the error messages from that macro, so it has a bad // generic message instead Err(_) => return Some(Err( @@ -2610,7 +2610,7 @@ impl Target { key!(has_thumb_interworking, bool); key!(debuginfo_kind, DebuginfoKind)?; key!(split_debuginfo, SplitDebuginfo)?; - key!(supported_split_debuginfo, falliable_list)?; + key!(supported_split_debuginfo, fallible_list)?; key!(supported_sanitizers, SanitizerSet)?; key!(default_adjusted_cabi, Option)?; key!(generate_arange_section, bool); diff --git a/compiler/rustc_target/src/spec/thumb_base.rs b/compiler/rustc_target/src/spec/thumb_base.rs index 4dcf47fe465c3..2220b9326c977 100644 --- a/compiler/rustc_target/src/spec/thumb_base.rs +++ b/compiler/rustc_target/src/spec/thumb_base.rs @@ -12,7 +12,7 @@ // // We have opted for these instead of one target per processor (e.g., `cortex-m0`, `cortex-m3`, // etc) because the differences between some processors like the cortex-m0 and cortex-m1 are almost -// non-existent from the POV of codegen so it doesn't make sense to have separate targets for them. +// nonexistent from the POV of codegen so it doesn't make sense to have separate targets for them. // And if differences exist between two processors under the same target, rustc flags can be used to // optimize for one processor or the other. // diff --git a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs index 10d817f75ac77..bacb0e32efc1a 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs @@ -51,7 +51,7 @@ pub(super) enum CandidateSource { BuiltinImpl, /// An assumption from the environment. /// - /// More precicely we've used the `n-th` assumption in the `param_env`. + /// More precisely we've used the `n-th` assumption in the `param_env`. /// /// ## Examples /// @@ -241,7 +241,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { // HACK: `_: Trait` is ambiguous, because it may be satisfied via a builtin rule, // object bound, alias bound, etc. We are unable to determine this until we can at - // least structually resolve the type one layer. + // least structurally resolve the type one layer. if goal.predicate.self_ty().is_ty_var() { return vec![Candidate { source: CandidateSource::BuiltinImpl, diff --git a/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs b/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs index dfdd52720a052..23cf0f0c724ba 100644 --- a/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs +++ b/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs @@ -156,8 +156,8 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { } } GenericArgKind::Const(c) => { - if let ty::ConstKind::Bound(debrujin, b) = c.kind() { - assert_eq!(debrujin, ty::INNERMOST); + if let ty::ConstKind::Bound(debruijn, b) = c.kind() { + assert_eq!(debruijn, ty::INNERMOST); opt_values[b] = Some(*original_value); } } @@ -177,7 +177,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { // As an optimization we sometimes avoid creating a new inference variable here. // // All new inference variables we create start out in the current universe of the caller. - // This is conceptionally wrong as these inference variables would be able to name + // This is conceptually wrong as these inference variables would be able to name // more placeholders then they should be able to. However the inference variables have // to "come from somewhere", so by equating them with the original values of the caller // later on, we pull them down into their correct universe again. diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals.rs b/compiler/rustc_trait_selection/src/solve/trait_goals.rs index abd11a15ac23a..1abcc80d01a32 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals.rs @@ -591,7 +591,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { Some(self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)) } - // These types cannot be structurally decomposed into constitutent + // These types cannot be structurally decomposed into constituent // types, and therefore have no built-in auto impl. ty::Dynamic(..) | ty::Param(..) 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 0352f0f380db1..726b08dc7d75d 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -467,7 +467,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } } - self.tcx.sess.delay_span_bug(DUMMY_SP, "expected fullfillment errors") + self.tcx.sess.delay_span_bug(DUMMY_SP, "expected fulfillment errors") } /// Reports that an overflow has occurred and halts compilation. We @@ -2056,7 +2056,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if candidates.iter().any(|c| matches!(c.similarity, CandidateSimilarity::Exact { .. })) { // If any of the candidates is a perfect match, we don't want to show all of them. // This is particularly relevant for the case of numeric types (as they all have the - // same cathegory). + // same category). candidates.retain(|c| matches!(c.similarity, CandidateSimilarity::Exact { .. })); } candidates diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index fb75ec7672920..73207f183a1d8 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -1381,7 +1381,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } } - // Issue #104961, we need to add parentheses properly for compond expressions + // Issue #104961, we need to add parentheses properly for compound expressions // for example, `x.starts_with("hi".to_string() + "you")` // should be `x.starts_with(&("hi".to_string() + "you"))` let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else { return false; }; diff --git a/compiler/rustc_trait_selection/src/traits/misc.rs b/compiler/rustc_trait_selection/src/traits/misc.rs index af567c074384e..63949843aedcd 100644 --- a/compiler/rustc_trait_selection/src/traits/misc.rs +++ b/compiler/rustc_trait_selection/src/traits/misc.rs @@ -14,7 +14,7 @@ use rustc_span::DUMMY_SP; use super::outlives_bounds::InferCtxtExt; pub enum CopyImplementationError<'tcx> { - InfrigingFields(Vec<(&'tcx ty::FieldDef, Ty<'tcx>, InfringingFieldsReason<'tcx>)>), + InfringingFields(Vec<(&'tcx ty::FieldDef, Ty<'tcx>, InfringingFieldsReason<'tcx>)>), NotAnAdt, HasDestructor, } @@ -125,7 +125,7 @@ pub fn type_allowed_to_implement_copy<'tcx>( } if !infringing.is_empty() { - return Err(CopyImplementationError::InfrigingFields(infringing)); + return Err(CopyImplementationError::InfringingFields(infringing)); } if adt.has_dtor(tcx) { diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index ed82b9c015277..4c9df5d9d0a26 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -203,7 +203,7 @@ fn do_normalize_predicates<'tcx>( } }; - debug!("do_normalize_predictes: normalized predicates = {:?}", predicates); + debug!("do_normalize_predicates: normalized predicates = {:?}", predicates); // We can use the `elaborated_env` here; the region code only // cares about declarations like `'a: 'b`. diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 6bb53418beabb..0fdba524e2569 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -888,7 +888,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let c1 = tcx.expand_abstract_consts(c1); let c2 = tcx.expand_abstract_consts(c2); debug!( - "evalaute_predicate_recursively: equating consts:\nc1= {:?}\nc2= {:?}", + "evaluate_predicate_recursively: equating consts:\nc1= {:?}\nc2= {:?}", c1, c2 ); diff --git a/compiler/rustc_ty_utils/src/layout_sanity_check.rs b/compiler/rustc_ty_utils/src/layout_sanity_check.rs index a5311dbd1b770..ed513cb3c7fc8 100644 --- a/compiler/rustc_ty_utils/src/layout_sanity_check.rs +++ b/compiler/rustc_ty_utils/src/layout_sanity_check.rs @@ -285,7 +285,7 @@ pub(super) fn sanity_check_layout<'tcx>( { // These are never actually accessed anyway, so we can skip the coherence check // for them. They also fail that check, since they have - // `Aggregate`/`Uninhbaited` ABI even when the main type is + // `Aggregate`/`Uninhabited` ABI even when the main type is // `Scalar`/`ScalarPair`. (Note that sometimes, variants with fields have size // 0, and sometimes, variants without fields have non-0 size.) continue; diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index de7fd003176bb..5f436f7c9fdf9 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -243,7 +243,7 @@ fn drop_tys_helper<'tcx>( } else { let field_tys = adt_def.all_fields().map(|field| { let r = tcx.type_of(field.did).subst(tcx, substs); - debug!("drop_tys_helper: Subst into {:?} with {:?} gettng {:?}", field, substs, r); + debug!("drop_tys_helper: Subst into {:?} with {:?} getting {:?}", field, substs, r); r }); if only_significant { diff --git a/tests/ui/error-codes/E0026-teach.stderr b/tests/ui/error-codes/E0026-teach.stderr index 1a80edcbbe269..3d460490eb3f5 100644 --- a/tests/ui/error-codes/E0026-teach.stderr +++ b/tests/ui/error-codes/E0026-teach.stderr @@ -4,7 +4,7 @@ error[E0026]: struct `Thing` does not have a field named `z` LL | Thing { x, y, z } => {} | ^ struct `Thing` does not have this field | - = note: This error indicates that a struct pattern attempted to extract a non-existent field from a struct. Struct fields are identified by the name used before the colon : so struct patterns should resemble the declaration of the struct type being matched. + = note: This error indicates that a struct pattern attempted to extract a nonexistent field from a struct. Struct fields are identified by the name used before the colon : so struct patterns should resemble the declaration of the struct type being matched. If you are using shorthand field patterns but want to refer to the struct field by a different name, you should rename it explicitly. diff --git a/tests/ui/type-alias-enum-variants/enum-variant-generic-args.stderr b/tests/ui/type-alias-enum-variants/enum-variant-generic-args.stderr index 758ff31ff7022..e24cb11288e29 100644 --- a/tests/ui/type-alias-enum-variants/enum-variant-generic-args.stderr +++ b/tests/ui/type-alias-enum-variants/enum-variant-generic-args.stderr @@ -115,7 +115,7 @@ LL | Self::SVariant::<()> { v: () }; | not allowed on this type | = note: enum variants can't have type parameters -help: you might have meant to specity type parameters on enum `Enum` +help: you might have meant to specify type parameters on enum `Enum` | LL - Self::SVariant::<()> { v: () }; LL + Enum::<()>::SVariant { v: () }; @@ -196,7 +196,7 @@ LL | Self::<()>::SVariant::<()> { v: () }; | not allowed on this type | = note: enum variants can't have type parameters -help: you might have meant to specity type parameters on enum `Enum` +help: you might have meant to specify type parameters on enum `Enum` | LL - Self::<()>::SVariant::<()> { v: () }; LL + Enum::<()>::SVariant { v: () }; @@ -359,7 +359,7 @@ LL | Alias::SVariant::<()> { v: () }; | not allowed on this type | = note: enum variants can't have type parameters -help: you might have meant to specity type parameters on enum `Enum` +help: you might have meant to specify type parameters on enum `Enum` | LL - Alias::SVariant::<()> { v: () }; LL + Alias::<()>::SVariant { v: () }; @@ -374,7 +374,7 @@ LL | Alias::<()>::SVariant::<()> { v: () }; | not allowed on this type | = note: enum variants can't have type parameters -help: you might have meant to specity type parameters on enum `Enum` +help: you might have meant to specify type parameters on enum `Enum` | LL - Alias::<()>::SVariant::<()> { v: () }; LL + Alias::<()>::SVariant { v: () }; @@ -389,7 +389,7 @@ LL | AliasFixed::SVariant::<()> { v: () }; | not allowed on this type | = note: enum variants can't have type parameters -help: you might have meant to specity type parameters on enum `Enum` +help: you might have meant to specify type parameters on enum `Enum` | LL - AliasFixed::SVariant::<()> { v: () }; LL + AliasFixed::<()>::SVariant { v: () }; @@ -432,7 +432,7 @@ LL | AliasFixed::<()>::SVariant::<()> { v: () }; | not allowed on this type | = note: enum variants can't have type parameters -help: you might have meant to specity type parameters on enum `Enum` +help: you might have meant to specify type parameters on enum `Enum` | LL - AliasFixed::<()>::SVariant::<()> { v: () }; LL + AliasFixed::<()>::SVariant { v: () }; From d6af60266eed9a19ee550278cdfe1d2857763286 Mon Sep 17 00:00:00 2001 From: jyn Date: Mon, 17 Apr 2023 20:00:36 -0500 Subject: [PATCH 096/228] Support `x test --stage 1 ui-fulldeps` Nils had an excellent idea the other day: the same way that rustdoc is able to load `rustc_driver` from the sysroot, ui-fulldeps tests should also be able to load it from the sysroot. That allows us to run fulldeps tests with stage1, without having to fully rebuild the compiler twice. It does unfortunately have the downside that we're running the tests on the *bootstrap* compiler, not the in-tree sources, but since most of the fulldeps tests are for the *API* of the compiler, that seems ok. I think it's possible to extend this to `run-make-fulldeps`, but I've run out of energy for tonight. - Move `plugin` tests into a subdirectory. Plugins are loaded at runtime with `dlopen` and so require the ABI of the running compile to match the ABI of the compiler linked with `rustc_driver`. As a result they can't be supported in stage 1 and have to use `// ignore-stage1`. - Remove `ignore-stage1` from most non-plugin tests - Ignore diagnostic tests in stage 1. Even though this requires a stage 2 build to load rustc_driver, it's primarily testing the error message that the *running* compiler emits when the diagnostic struct is malformed. - Pass `-Zforce-unstable-if-unmarked` in stage1, not just stage2. That allows running `hash-stable-is-unstable` in stage1, since it now suggests adding `rustc_private` to enable loading the crates. - Add libLLVM.so to the stage0 target sysroot, to allow fulldeps tests that act as custom drivers to load it at runtime. - Pass `--sysroot stage0-sysroot` in compiletest so that we use the correct version of std. --- src/bootstrap/bin/rustc.rs | 2 +- src/bootstrap/builder.rs | 15 ++ src/bootstrap/compile.rs | 1 + src/bootstrap/test.rs | 25 ++- src/tools/compiletest/src/common.rs | 4 +- src/tools/compiletest/src/runtest.rs | 3 + src/tools/tidy/src/ui_tests.rs | 2 +- tests/ui-fulldeps/compiler-calls.rs | 1 - tests/ui-fulldeps/hash-stable-is-unstable.rs | 1 - .../hash-stable-is-unstable.stderr | 10 +- tests/ui-fulldeps/pathless-extern-unstable.rs | 1 - .../pathless-extern-unstable.stderr | 2 +- .../{ => plugin}/auxiliary/empty-plugin.rs | 0 .../auxiliary/issue-40001-plugin.rs | 0 .../{ => plugin}/auxiliary/lint-for-crate.rs | 0 .../auxiliary/lint-group-plugin-test.rs | 0 .../auxiliary/lint-plugin-test.rs | 0 .../{ => plugin}/auxiliary/lint-tool-test.rs | 0 .../auxiliary/lto-syntax-extension-lib.rs | 0 .../auxiliary/lto-syntax-extension-plugin.rs | 0 .../auxiliary/multiple-plugins-1.rs | 0 .../auxiliary/multiple-plugins-2.rs | 0 .../auxiliary/outlive-expansion-phase.rs | 0 .../{ => plugin}/auxiliary/rlib-crate-test.rs | 0 .../{ => plugin}/feature-gate-plugin.rs | 0 .../{ => plugin}/feature-gate-plugin.stderr | 0 .../ui-fulldeps/{ => plugin}/gated-plugin.rs | 0 .../{ => plugin}/gated-plugin.stderr | 0 .../{ => plugin}/issue-15778-fail.rs | 0 .../{ => plugin}/issue-15778-fail.stderr | 0 tests/ui-fulldeps/{ => plugin}/issue-40001.rs | 0 .../{ => plugin}/issue-40001.stderr | 0 .../lint-group-plugin-deny-cmdline.rs | 0 .../lint-group-plugin-deny-cmdline.stderr | 0 .../{ => plugin}/lint-group-plugin.rs | 0 .../{ => plugin}/lint-group-plugin.stderr | 0 .../{ => plugin}/lint-plugin-cmdline-allow.rs | 0 .../lint-plugin-cmdline-allow.stderr | 0 .../{ => plugin}/lint-plugin-cmdline-load.rs | 0 .../lint-plugin-cmdline-load.stderr | 0 .../{ => plugin}/lint-plugin-deny-attr.rs | 0 .../{ => plugin}/lint-plugin-deny-attr.stderr | 0 .../{ => plugin}/lint-plugin-deny-cmdline.rs | 0 .../lint-plugin-deny-cmdline.stderr | 0 .../{ => plugin}/lint-plugin-forbid-attrs.rs | 0 .../lint-plugin-forbid-attrs.stderr | 0 .../lint-plugin-forbid-cmdline.rs | 0 .../lint-plugin-forbid-cmdline.stderr | 0 tests/ui-fulldeps/{ => plugin}/lint-plugin.rs | 0 .../{ => plugin}/lint-plugin.stderr | 0 .../{ => plugin}/lint-tool-cmdline-allow.rs | 0 .../lint-tool-cmdline-allow.stderr | 0 .../{ => plugin}/lint-tool-test.rs | 0 .../{ => plugin}/lint-tool-test.stderr | 0 .../{ => plugin}/lto-syntax-extension.rs | 0 .../{ => plugin}/lto-syntax-extension.stderr | 0 .../{ => plugin}/macro-crate-rlib.rs | 1 + .../{ => plugin}/macro-crate-rlib.stderr | 2 +- .../{ => plugin}/multiple-plugins.rs | 0 .../{ => plugin}/multiple-plugins.stderr | 0 .../{ => plugin}/outlive-expansion-phase.rs | 0 .../outlive-expansion-phase.stderr | 0 tests/ui-fulldeps/{ => plugin}/plugin-args.rs | 0 .../{ => plugin}/plugin-args.stderr | 0 .../{ => plugin}/plugin-as-extern-crate.rs | 0 .../session-diagnostic/diagnostic-derive.rs | 1 + .../diagnostic-derive.stderr | 182 +++++++++--------- .../subdiagnostic-derive.rs | 1 + .../subdiagnostic-derive.stderr | 182 +++++++++--------- .../lint-group-denied-lint-allowed.rs | 1 - .../lint-group-forbid-always-trumps-cli.rs | 1 - ...lint-group-forbid-always-trumps-cli.stderr | 2 +- 72 files changed, 236 insertions(+), 204 deletions(-) rename tests/ui-fulldeps/{ => plugin}/auxiliary/empty-plugin.rs (100%) rename tests/ui-fulldeps/{ => plugin}/auxiliary/issue-40001-plugin.rs (100%) rename tests/ui-fulldeps/{ => plugin}/auxiliary/lint-for-crate.rs (100%) rename tests/ui-fulldeps/{ => plugin}/auxiliary/lint-group-plugin-test.rs (100%) rename tests/ui-fulldeps/{ => plugin}/auxiliary/lint-plugin-test.rs (100%) rename tests/ui-fulldeps/{ => plugin}/auxiliary/lint-tool-test.rs (100%) rename tests/ui-fulldeps/{ => plugin}/auxiliary/lto-syntax-extension-lib.rs (100%) rename tests/ui-fulldeps/{ => plugin}/auxiliary/lto-syntax-extension-plugin.rs (100%) rename tests/ui-fulldeps/{ => plugin}/auxiliary/multiple-plugins-1.rs (100%) rename tests/ui-fulldeps/{ => plugin}/auxiliary/multiple-plugins-2.rs (100%) rename tests/ui-fulldeps/{ => plugin}/auxiliary/outlive-expansion-phase.rs (100%) rename tests/ui-fulldeps/{ => plugin}/auxiliary/rlib-crate-test.rs (100%) rename tests/ui-fulldeps/{ => plugin}/feature-gate-plugin.rs (100%) rename tests/ui-fulldeps/{ => plugin}/feature-gate-plugin.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/gated-plugin.rs (100%) rename tests/ui-fulldeps/{ => plugin}/gated-plugin.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/issue-15778-fail.rs (100%) rename tests/ui-fulldeps/{ => plugin}/issue-15778-fail.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/issue-40001.rs (100%) rename tests/ui-fulldeps/{ => plugin}/issue-40001.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lint-group-plugin-deny-cmdline.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lint-group-plugin-deny-cmdline.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lint-group-plugin.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lint-group-plugin.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-cmdline-allow.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-cmdline-allow.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-cmdline-load.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-cmdline-load.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-deny-attr.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-deny-attr.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-deny-cmdline.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-deny-cmdline.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-forbid-attrs.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-forbid-attrs.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-forbid-cmdline.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin-forbid-cmdline.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lint-plugin.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lint-tool-cmdline-allow.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lint-tool-cmdline-allow.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lint-tool-test.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lint-tool-test.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/lto-syntax-extension.rs (100%) rename tests/ui-fulldeps/{ => plugin}/lto-syntax-extension.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/macro-crate-rlib.rs (93%) rename tests/ui-fulldeps/{ => plugin}/macro-crate-rlib.stderr (88%) rename tests/ui-fulldeps/{ => plugin}/multiple-plugins.rs (100%) rename tests/ui-fulldeps/{ => plugin}/multiple-plugins.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/outlive-expansion-phase.rs (100%) rename tests/ui-fulldeps/{ => plugin}/outlive-expansion-phase.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/plugin-args.rs (100%) rename tests/ui-fulldeps/{ => plugin}/plugin-args.stderr (100%) rename tests/ui-fulldeps/{ => plugin}/plugin-as-extern-crate.rs (100%) rename tests/{ui-fulldeps => ui}/lint-group-denied-lint-allowed.rs (70%) rename tests/{ui-fulldeps => ui}/lint-group-forbid-always-trumps-cli.rs (72%) rename tests/{ui-fulldeps => ui}/lint-group-forbid-always-trumps-cli.stderr (81%) diff --git a/src/bootstrap/bin/rustc.rs b/src/bootstrap/bin/rustc.rs index 040fec3615b6e..dd86634b47c83 100644 --- a/src/bootstrap/bin/rustc.rs +++ b/src/bootstrap/bin/rustc.rs @@ -150,7 +150,7 @@ fn main() { // allow the `rustc_private` feature to link to other unstable crates // also in the sysroot. We also do this for host crates, since those // may be proc macros, in which case we might ship them. - if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() && (stage != "0" || target.is_some()) { + if env::var_os("RUSTC_FORCE_UNSTABLE").is_some() { cmd.arg("-Z").arg("force-unstable-if-unmarked"); } diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index e959ea06f8b69..836ed1321f08b 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -1008,9 +1008,24 @@ impl<'a> Builder<'a> { // Avoid deleting the rustlib/ directory we just copied // (in `impl Step for Sysroot`). if !builder.download_rustc() { + builder.verbose(&format!( + "Removing sysroot {} to avoid caching bugs", + sysroot.display() + )); let _ = fs::remove_dir_all(&sysroot); t!(fs::create_dir_all(&sysroot)); } + + if self.compiler.stage == 0 { + // The stage 0 compiler for the build triple is always pre-built. + // Ensure that `libLLVM.so` ends up in the target libdir, so that ui-fulldeps tests can use it when run. + dist::maybe_install_llvm_target( + builder, + self.compiler.host, + &builder.sysroot(self.compiler), + ); + } + INTERNER.intern_path(sysroot) } } diff --git a/src/bootstrap/compile.rs b/src/bootstrap/compile.rs index 4a4e7adcbf388..1573134e35f7d 100644 --- a/src/bootstrap/compile.rs +++ b/src/bootstrap/compile.rs @@ -1260,6 +1260,7 @@ impl Step for Sysroot { }; let sysroot = sysroot_dir(compiler.stage); + builder.verbose(&format!("Removing sysroot {} to avoid caching bugs", sysroot.display())); let _ = fs::remove_dir_all(&sysroot); t!(fs::create_dir_all(&sysroot)); diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index aedf1ecab13c4..1033592d02478 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -1448,7 +1448,7 @@ note: if you're sure you want to do this, please open an issue as to why. In the crate::detail_exit(1); } - let compiler = self.compiler; + let mut compiler = self.compiler; let target = self.target; let mode = self.mode; let suite = self.suite; @@ -1461,15 +1461,28 @@ note: if you're sure you want to do this, please open an issue as to why. In the return; } - if suite == "debuginfo" { - builder - .ensure(dist::DebuggerScripts { sysroot: builder.sysroot(compiler), host: target }); - } + // Support stage 1 ui-fulldeps. This is somewhat complicated: ui-fulldeps tests for the most + // part test the *API* of the compiler, not how it compiles a given file. As a result, we + // can run them against the stage 1 sources as long as we build them with the stage 0 + // bootstrap compiler. + // NOTE: Only stage 1 is special cased because we need the rustc_private artifacts to match the + // running compiler in stage 2 when plugins run. + let stage_id = if suite == "ui-fulldeps" && compiler.stage == 1 { + compiler = builder.compiler(compiler.stage - 1, target); + format!("stage{}-{}", compiler.stage + 1, target) + } else { + format!("stage{}-{}", compiler.stage, target) + }; if suite.ends_with("fulldeps") { builder.ensure(compile::Rustc::new(compiler, target)); } + if suite == "debuginfo" { + builder + .ensure(dist::DebuggerScripts { sysroot: builder.sysroot(compiler), host: target }); + } + builder.ensure(compile::Std::new(compiler, target)); // ensure that `libproc_macro` is available on the host. builder.ensure(compile::Std::new(compiler, compiler.host)); @@ -1528,7 +1541,7 @@ note: if you're sure you want to do this, please open an issue as to why. In the cmd.arg("--src-base").arg(builder.src.join("tests").join(suite)); cmd.arg("--build-base").arg(testdir(builder, compiler.host).join(suite)); cmd.arg("--sysroot-base").arg(builder.sysroot(compiler)); - cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target)); + cmd.arg("--stage-id").arg(stage_id); cmd.arg("--suite").arg(suite); cmd.arg("--mode").arg(mode); cmd.arg("--target").arg(target.rustc_target_arg()); diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index d2f494942cf9b..d2903585a3967 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -419,7 +419,9 @@ pub struct TargetCfgs { impl TargetCfgs { fn new(config: &Config) -> TargetCfgs { - let targets: HashMap = if config.stage_id.starts_with("stage0-") { + let targets: HashMap = if config.stage_id.starts_with("stage0-") + || (config.suite == "ui-fulldeps" && config.stage_id.starts_with("stage1-")) + { // #[cfg(bootstrap)] // Needed only for one cycle, remove during the bootstrap bump. Self::collect_all_slow(config) diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 0fa5c54ae8e68..1a4e9b5838369 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -1900,6 +1900,9 @@ impl<'test> TestCx<'test> { // Use a single thread for efficiency and a deterministic error message order rustc.arg("-Zthreads=1"); + // In stage 0, make sure we use `stage0-sysroot` instead of the bootstrap sysroot. + rustc.arg("--sysroot").arg(&self.config.sysroot_base); + // Optionally prevent default --target if specified in test compile-flags. let custom_target = self.props.compile_flags.iter().any(|x| x.starts_with("--target")); diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index 29664c854c873..b1385edf13e6c 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -9,7 +9,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 ROOT_ENTRY_LIMIT: usize = 894; const ISSUES_ENTRY_LIMIT: usize = 1977; fn check_entries(tests_path: &Path, bad: &mut bool) { diff --git a/tests/ui-fulldeps/compiler-calls.rs b/tests/ui-fulldeps/compiler-calls.rs index a9520b59277ac..b6d3b7b040d16 100644 --- a/tests/ui-fulldeps/compiler-calls.rs +++ b/tests/ui-fulldeps/compiler-calls.rs @@ -2,7 +2,6 @@ // Test that the Callbacks interface to the compiler works. // ignore-cross-compile -// ignore-stage1 // ignore-remote #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/hash-stable-is-unstable.rs b/tests/ui-fulldeps/hash-stable-is-unstable.rs index 11fe688f3913b..37d7472ec6097 100644 --- a/tests/ui-fulldeps/hash-stable-is-unstable.rs +++ b/tests/ui-fulldeps/hash-stable-is-unstable.rs @@ -1,4 +1,3 @@ -// ignore-stage1 // compile-flags: -Zdeduplicate-diagnostics=yes extern crate rustc_data_structures; //~^ use of unstable library feature 'rustc_private' diff --git a/tests/ui-fulldeps/hash-stable-is-unstable.stderr b/tests/ui-fulldeps/hash-stable-is-unstable.stderr index d25657691ed4d..1a8994d722ea0 100644 --- a/tests/ui-fulldeps/hash-stable-is-unstable.stderr +++ b/tests/ui-fulldeps/hash-stable-is-unstable.stderr @@ -1,5 +1,5 @@ error[E0658]: use of unstable library feature 'rustc_private': this crate is being loaded from the sysroot, an unstable location; did you mean to load this crate from crates.io via `Cargo.toml` instead? - --> $DIR/hash-stable-is-unstable.rs:3:1 + --> $DIR/hash-stable-is-unstable.rs:2:1 | LL | extern crate rustc_data_structures; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -8,7 +8,7 @@ LL | extern crate rustc_data_structures; = help: add `#![feature(rustc_private)]` to the crate attributes to enable error[E0658]: use of unstable library feature 'rustc_private': this crate is being loaded from the sysroot, an unstable location; did you mean to load this crate from crates.io via `Cargo.toml` instead? - --> $DIR/hash-stable-is-unstable.rs:5:1 + --> $DIR/hash-stable-is-unstable.rs:4:1 | LL | extern crate rustc_macros; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -17,7 +17,7 @@ LL | extern crate rustc_macros; = help: add `#![feature(rustc_private)]` to the crate attributes to enable error[E0658]: use of unstable library feature 'rustc_private': this crate is being loaded from the sysroot, an unstable location; did you mean to load this crate from crates.io via `Cargo.toml` instead? - --> $DIR/hash-stable-is-unstable.rs:7:1 + --> $DIR/hash-stable-is-unstable.rs:6:1 | LL | extern crate rustc_query_system; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -26,7 +26,7 @@ LL | extern crate rustc_query_system; = help: add `#![feature(rustc_private)]` to the crate attributes to enable error[E0658]: use of unstable library feature 'rustc_private': this crate is being loaded from the sysroot, an unstable location; did you mean to load this crate from crates.io via `Cargo.toml` instead? - --> $DIR/hash-stable-is-unstable.rs:10:5 + --> $DIR/hash-stable-is-unstable.rs:9:5 | LL | use rustc_macros::HashStable; | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -35,7 +35,7 @@ LL | use rustc_macros::HashStable; = help: add `#![feature(rustc_private)]` to the crate attributes to enable error[E0658]: use of unstable library feature 'rustc_private': this crate is being loaded from the sysroot, an unstable location; did you mean to load this crate from crates.io via `Cargo.toml` instead? - --> $DIR/hash-stable-is-unstable.rs:13:10 + --> $DIR/hash-stable-is-unstable.rs:12:10 | LL | #[derive(HashStable)] | ^^^^^^^^^^ diff --git a/tests/ui-fulldeps/pathless-extern-unstable.rs b/tests/ui-fulldeps/pathless-extern-unstable.rs index 524b0c2f73a5d..7fba8343bc088 100644 --- a/tests/ui-fulldeps/pathless-extern-unstable.rs +++ b/tests/ui-fulldeps/pathless-extern-unstable.rs @@ -1,4 +1,3 @@ -// ignore-stage1 // edition:2018 // compile-flags:--extern rustc_middle diff --git a/tests/ui-fulldeps/pathless-extern-unstable.stderr b/tests/ui-fulldeps/pathless-extern-unstable.stderr index dcc3cddd32cfd..174cd3c280477 100644 --- a/tests/ui-fulldeps/pathless-extern-unstable.stderr +++ b/tests/ui-fulldeps/pathless-extern-unstable.stderr @@ -1,5 +1,5 @@ error[E0658]: use of unstable library feature 'rustc_private': this crate is being loaded from the sysroot, an unstable location; did you mean to load this crate from crates.io via `Cargo.toml` instead? - --> $DIR/pathless-extern-unstable.rs:7:9 + --> $DIR/pathless-extern-unstable.rs:6:9 | LL | pub use rustc_middle; | ^^^^^^^^^^^^ diff --git a/tests/ui-fulldeps/auxiliary/empty-plugin.rs b/tests/ui-fulldeps/plugin/auxiliary/empty-plugin.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/empty-plugin.rs rename to tests/ui-fulldeps/plugin/auxiliary/empty-plugin.rs diff --git a/tests/ui-fulldeps/auxiliary/issue-40001-plugin.rs b/tests/ui-fulldeps/plugin/auxiliary/issue-40001-plugin.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/issue-40001-plugin.rs rename to tests/ui-fulldeps/plugin/auxiliary/issue-40001-plugin.rs diff --git a/tests/ui-fulldeps/auxiliary/lint-for-crate.rs b/tests/ui-fulldeps/plugin/auxiliary/lint-for-crate.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/lint-for-crate.rs rename to tests/ui-fulldeps/plugin/auxiliary/lint-for-crate.rs diff --git a/tests/ui-fulldeps/auxiliary/lint-group-plugin-test.rs b/tests/ui-fulldeps/plugin/auxiliary/lint-group-plugin-test.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/lint-group-plugin-test.rs rename to tests/ui-fulldeps/plugin/auxiliary/lint-group-plugin-test.rs diff --git a/tests/ui-fulldeps/auxiliary/lint-plugin-test.rs b/tests/ui-fulldeps/plugin/auxiliary/lint-plugin-test.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/lint-plugin-test.rs rename to tests/ui-fulldeps/plugin/auxiliary/lint-plugin-test.rs diff --git a/tests/ui-fulldeps/auxiliary/lint-tool-test.rs b/tests/ui-fulldeps/plugin/auxiliary/lint-tool-test.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/lint-tool-test.rs rename to tests/ui-fulldeps/plugin/auxiliary/lint-tool-test.rs diff --git a/tests/ui-fulldeps/auxiliary/lto-syntax-extension-lib.rs b/tests/ui-fulldeps/plugin/auxiliary/lto-syntax-extension-lib.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/lto-syntax-extension-lib.rs rename to tests/ui-fulldeps/plugin/auxiliary/lto-syntax-extension-lib.rs diff --git a/tests/ui-fulldeps/auxiliary/lto-syntax-extension-plugin.rs b/tests/ui-fulldeps/plugin/auxiliary/lto-syntax-extension-plugin.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/lto-syntax-extension-plugin.rs rename to tests/ui-fulldeps/plugin/auxiliary/lto-syntax-extension-plugin.rs diff --git a/tests/ui-fulldeps/auxiliary/multiple-plugins-1.rs b/tests/ui-fulldeps/plugin/auxiliary/multiple-plugins-1.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/multiple-plugins-1.rs rename to tests/ui-fulldeps/plugin/auxiliary/multiple-plugins-1.rs diff --git a/tests/ui-fulldeps/auxiliary/multiple-plugins-2.rs b/tests/ui-fulldeps/plugin/auxiliary/multiple-plugins-2.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/multiple-plugins-2.rs rename to tests/ui-fulldeps/plugin/auxiliary/multiple-plugins-2.rs diff --git a/tests/ui-fulldeps/auxiliary/outlive-expansion-phase.rs b/tests/ui-fulldeps/plugin/auxiliary/outlive-expansion-phase.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/outlive-expansion-phase.rs rename to tests/ui-fulldeps/plugin/auxiliary/outlive-expansion-phase.rs diff --git a/tests/ui-fulldeps/auxiliary/rlib-crate-test.rs b/tests/ui-fulldeps/plugin/auxiliary/rlib-crate-test.rs similarity index 100% rename from tests/ui-fulldeps/auxiliary/rlib-crate-test.rs rename to tests/ui-fulldeps/plugin/auxiliary/rlib-crate-test.rs diff --git a/tests/ui-fulldeps/feature-gate-plugin.rs b/tests/ui-fulldeps/plugin/feature-gate-plugin.rs similarity index 100% rename from tests/ui-fulldeps/feature-gate-plugin.rs rename to tests/ui-fulldeps/plugin/feature-gate-plugin.rs diff --git a/tests/ui-fulldeps/feature-gate-plugin.stderr b/tests/ui-fulldeps/plugin/feature-gate-plugin.stderr similarity index 100% rename from tests/ui-fulldeps/feature-gate-plugin.stderr rename to tests/ui-fulldeps/plugin/feature-gate-plugin.stderr diff --git a/tests/ui-fulldeps/gated-plugin.rs b/tests/ui-fulldeps/plugin/gated-plugin.rs similarity index 100% rename from tests/ui-fulldeps/gated-plugin.rs rename to tests/ui-fulldeps/plugin/gated-plugin.rs diff --git a/tests/ui-fulldeps/gated-plugin.stderr b/tests/ui-fulldeps/plugin/gated-plugin.stderr similarity index 100% rename from tests/ui-fulldeps/gated-plugin.stderr rename to tests/ui-fulldeps/plugin/gated-plugin.stderr diff --git a/tests/ui-fulldeps/issue-15778-fail.rs b/tests/ui-fulldeps/plugin/issue-15778-fail.rs similarity index 100% rename from tests/ui-fulldeps/issue-15778-fail.rs rename to tests/ui-fulldeps/plugin/issue-15778-fail.rs diff --git a/tests/ui-fulldeps/issue-15778-fail.stderr b/tests/ui-fulldeps/plugin/issue-15778-fail.stderr similarity index 100% rename from tests/ui-fulldeps/issue-15778-fail.stderr rename to tests/ui-fulldeps/plugin/issue-15778-fail.stderr diff --git a/tests/ui-fulldeps/issue-40001.rs b/tests/ui-fulldeps/plugin/issue-40001.rs similarity index 100% rename from tests/ui-fulldeps/issue-40001.rs rename to tests/ui-fulldeps/plugin/issue-40001.rs diff --git a/tests/ui-fulldeps/issue-40001.stderr b/tests/ui-fulldeps/plugin/issue-40001.stderr similarity index 100% rename from tests/ui-fulldeps/issue-40001.stderr rename to tests/ui-fulldeps/plugin/issue-40001.stderr diff --git a/tests/ui-fulldeps/lint-group-plugin-deny-cmdline.rs b/tests/ui-fulldeps/plugin/lint-group-plugin-deny-cmdline.rs similarity index 100% rename from tests/ui-fulldeps/lint-group-plugin-deny-cmdline.rs rename to tests/ui-fulldeps/plugin/lint-group-plugin-deny-cmdline.rs diff --git a/tests/ui-fulldeps/lint-group-plugin-deny-cmdline.stderr b/tests/ui-fulldeps/plugin/lint-group-plugin-deny-cmdline.stderr similarity index 100% rename from tests/ui-fulldeps/lint-group-plugin-deny-cmdline.stderr rename to tests/ui-fulldeps/plugin/lint-group-plugin-deny-cmdline.stderr diff --git a/tests/ui-fulldeps/lint-group-plugin.rs b/tests/ui-fulldeps/plugin/lint-group-plugin.rs similarity index 100% rename from tests/ui-fulldeps/lint-group-plugin.rs rename to tests/ui-fulldeps/plugin/lint-group-plugin.rs diff --git a/tests/ui-fulldeps/lint-group-plugin.stderr b/tests/ui-fulldeps/plugin/lint-group-plugin.stderr similarity index 100% rename from tests/ui-fulldeps/lint-group-plugin.stderr rename to tests/ui-fulldeps/plugin/lint-group-plugin.stderr diff --git a/tests/ui-fulldeps/lint-plugin-cmdline-allow.rs b/tests/ui-fulldeps/plugin/lint-plugin-cmdline-allow.rs similarity index 100% rename from tests/ui-fulldeps/lint-plugin-cmdline-allow.rs rename to tests/ui-fulldeps/plugin/lint-plugin-cmdline-allow.rs diff --git a/tests/ui-fulldeps/lint-plugin-cmdline-allow.stderr b/tests/ui-fulldeps/plugin/lint-plugin-cmdline-allow.stderr similarity index 100% rename from tests/ui-fulldeps/lint-plugin-cmdline-allow.stderr rename to tests/ui-fulldeps/plugin/lint-plugin-cmdline-allow.stderr diff --git a/tests/ui-fulldeps/lint-plugin-cmdline-load.rs b/tests/ui-fulldeps/plugin/lint-plugin-cmdline-load.rs similarity index 100% rename from tests/ui-fulldeps/lint-plugin-cmdline-load.rs rename to tests/ui-fulldeps/plugin/lint-plugin-cmdline-load.rs diff --git a/tests/ui-fulldeps/lint-plugin-cmdline-load.stderr b/tests/ui-fulldeps/plugin/lint-plugin-cmdline-load.stderr similarity index 100% rename from tests/ui-fulldeps/lint-plugin-cmdline-load.stderr rename to tests/ui-fulldeps/plugin/lint-plugin-cmdline-load.stderr diff --git a/tests/ui-fulldeps/lint-plugin-deny-attr.rs b/tests/ui-fulldeps/plugin/lint-plugin-deny-attr.rs similarity index 100% rename from tests/ui-fulldeps/lint-plugin-deny-attr.rs rename to tests/ui-fulldeps/plugin/lint-plugin-deny-attr.rs diff --git a/tests/ui-fulldeps/lint-plugin-deny-attr.stderr b/tests/ui-fulldeps/plugin/lint-plugin-deny-attr.stderr similarity index 100% rename from tests/ui-fulldeps/lint-plugin-deny-attr.stderr rename to tests/ui-fulldeps/plugin/lint-plugin-deny-attr.stderr diff --git a/tests/ui-fulldeps/lint-plugin-deny-cmdline.rs b/tests/ui-fulldeps/plugin/lint-plugin-deny-cmdline.rs similarity index 100% rename from tests/ui-fulldeps/lint-plugin-deny-cmdline.rs rename to tests/ui-fulldeps/plugin/lint-plugin-deny-cmdline.rs diff --git a/tests/ui-fulldeps/lint-plugin-deny-cmdline.stderr b/tests/ui-fulldeps/plugin/lint-plugin-deny-cmdline.stderr similarity index 100% rename from tests/ui-fulldeps/lint-plugin-deny-cmdline.stderr rename to tests/ui-fulldeps/plugin/lint-plugin-deny-cmdline.stderr diff --git a/tests/ui-fulldeps/lint-plugin-forbid-attrs.rs b/tests/ui-fulldeps/plugin/lint-plugin-forbid-attrs.rs similarity index 100% rename from tests/ui-fulldeps/lint-plugin-forbid-attrs.rs rename to tests/ui-fulldeps/plugin/lint-plugin-forbid-attrs.rs diff --git a/tests/ui-fulldeps/lint-plugin-forbid-attrs.stderr b/tests/ui-fulldeps/plugin/lint-plugin-forbid-attrs.stderr similarity index 100% rename from tests/ui-fulldeps/lint-plugin-forbid-attrs.stderr rename to tests/ui-fulldeps/plugin/lint-plugin-forbid-attrs.stderr diff --git a/tests/ui-fulldeps/lint-plugin-forbid-cmdline.rs b/tests/ui-fulldeps/plugin/lint-plugin-forbid-cmdline.rs similarity index 100% rename from tests/ui-fulldeps/lint-plugin-forbid-cmdline.rs rename to tests/ui-fulldeps/plugin/lint-plugin-forbid-cmdline.rs diff --git a/tests/ui-fulldeps/lint-plugin-forbid-cmdline.stderr b/tests/ui-fulldeps/plugin/lint-plugin-forbid-cmdline.stderr similarity index 100% rename from tests/ui-fulldeps/lint-plugin-forbid-cmdline.stderr rename to tests/ui-fulldeps/plugin/lint-plugin-forbid-cmdline.stderr diff --git a/tests/ui-fulldeps/lint-plugin.rs b/tests/ui-fulldeps/plugin/lint-plugin.rs similarity index 100% rename from tests/ui-fulldeps/lint-plugin.rs rename to tests/ui-fulldeps/plugin/lint-plugin.rs diff --git a/tests/ui-fulldeps/lint-plugin.stderr b/tests/ui-fulldeps/plugin/lint-plugin.stderr similarity index 100% rename from tests/ui-fulldeps/lint-plugin.stderr rename to tests/ui-fulldeps/plugin/lint-plugin.stderr diff --git a/tests/ui-fulldeps/lint-tool-cmdline-allow.rs b/tests/ui-fulldeps/plugin/lint-tool-cmdline-allow.rs similarity index 100% rename from tests/ui-fulldeps/lint-tool-cmdline-allow.rs rename to tests/ui-fulldeps/plugin/lint-tool-cmdline-allow.rs diff --git a/tests/ui-fulldeps/lint-tool-cmdline-allow.stderr b/tests/ui-fulldeps/plugin/lint-tool-cmdline-allow.stderr similarity index 100% rename from tests/ui-fulldeps/lint-tool-cmdline-allow.stderr rename to tests/ui-fulldeps/plugin/lint-tool-cmdline-allow.stderr diff --git a/tests/ui-fulldeps/lint-tool-test.rs b/tests/ui-fulldeps/plugin/lint-tool-test.rs similarity index 100% rename from tests/ui-fulldeps/lint-tool-test.rs rename to tests/ui-fulldeps/plugin/lint-tool-test.rs diff --git a/tests/ui-fulldeps/lint-tool-test.stderr b/tests/ui-fulldeps/plugin/lint-tool-test.stderr similarity index 100% rename from tests/ui-fulldeps/lint-tool-test.stderr rename to tests/ui-fulldeps/plugin/lint-tool-test.stderr diff --git a/tests/ui-fulldeps/lto-syntax-extension.rs b/tests/ui-fulldeps/plugin/lto-syntax-extension.rs similarity index 100% rename from tests/ui-fulldeps/lto-syntax-extension.rs rename to tests/ui-fulldeps/plugin/lto-syntax-extension.rs diff --git a/tests/ui-fulldeps/lto-syntax-extension.stderr b/tests/ui-fulldeps/plugin/lto-syntax-extension.stderr similarity index 100% rename from tests/ui-fulldeps/lto-syntax-extension.stderr rename to tests/ui-fulldeps/plugin/lto-syntax-extension.stderr diff --git a/tests/ui-fulldeps/macro-crate-rlib.rs b/tests/ui-fulldeps/plugin/macro-crate-rlib.rs similarity index 93% rename from tests/ui-fulldeps/macro-crate-rlib.rs rename to tests/ui-fulldeps/plugin/macro-crate-rlib.rs index 1fd514c617329..38bd340539ba1 100644 --- a/tests/ui-fulldeps/macro-crate-rlib.rs +++ b/tests/ui-fulldeps/plugin/macro-crate-rlib.rs @@ -1,4 +1,5 @@ // aux-build:rlib-crate-test.rs +// ignore-stage1 // ignore-cross-compile gives a different error message #![feature(plugin)] diff --git a/tests/ui-fulldeps/macro-crate-rlib.stderr b/tests/ui-fulldeps/plugin/macro-crate-rlib.stderr similarity index 88% rename from tests/ui-fulldeps/macro-crate-rlib.stderr rename to tests/ui-fulldeps/plugin/macro-crate-rlib.stderr index 9c2b992b76558..0651cee56f772 100644 --- a/tests/ui-fulldeps/macro-crate-rlib.stderr +++ b/tests/ui-fulldeps/plugin/macro-crate-rlib.stderr @@ -1,5 +1,5 @@ error[E0457]: plugin `rlib_crate_test` only found in rlib format, but must be available in dylib format - --> $DIR/macro-crate-rlib.rs:5:11 + --> $DIR/macro-crate-rlib.rs:6:11 | LL | #![plugin(rlib_crate_test)] | ^^^^^^^^^^^^^^^ diff --git a/tests/ui-fulldeps/multiple-plugins.rs b/tests/ui-fulldeps/plugin/multiple-plugins.rs similarity index 100% rename from tests/ui-fulldeps/multiple-plugins.rs rename to tests/ui-fulldeps/plugin/multiple-plugins.rs diff --git a/tests/ui-fulldeps/multiple-plugins.stderr b/tests/ui-fulldeps/plugin/multiple-plugins.stderr similarity index 100% rename from tests/ui-fulldeps/multiple-plugins.stderr rename to tests/ui-fulldeps/plugin/multiple-plugins.stderr diff --git a/tests/ui-fulldeps/outlive-expansion-phase.rs b/tests/ui-fulldeps/plugin/outlive-expansion-phase.rs similarity index 100% rename from tests/ui-fulldeps/outlive-expansion-phase.rs rename to tests/ui-fulldeps/plugin/outlive-expansion-phase.rs diff --git a/tests/ui-fulldeps/outlive-expansion-phase.stderr b/tests/ui-fulldeps/plugin/outlive-expansion-phase.stderr similarity index 100% rename from tests/ui-fulldeps/outlive-expansion-phase.stderr rename to tests/ui-fulldeps/plugin/outlive-expansion-phase.stderr diff --git a/tests/ui-fulldeps/plugin-args.rs b/tests/ui-fulldeps/plugin/plugin-args.rs similarity index 100% rename from tests/ui-fulldeps/plugin-args.rs rename to tests/ui-fulldeps/plugin/plugin-args.rs diff --git a/tests/ui-fulldeps/plugin-args.stderr b/tests/ui-fulldeps/plugin/plugin-args.stderr similarity index 100% rename from tests/ui-fulldeps/plugin-args.stderr rename to tests/ui-fulldeps/plugin/plugin-args.stderr diff --git a/tests/ui-fulldeps/plugin-as-extern-crate.rs b/tests/ui-fulldeps/plugin/plugin-as-extern-crate.rs similarity index 100% rename from tests/ui-fulldeps/plugin-as-extern-crate.rs rename to tests/ui-fulldeps/plugin/plugin-as-extern-crate.rs diff --git a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.rs b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.rs index 6cc7bab37266d..ef85fada5066c 100644 --- a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.rs +++ b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.rs @@ -6,6 +6,7 @@ // The proc_macro2 crate handles spans differently when on beta/stable release rather than nightly, // changing the output of this test. Since Diagnostic is strictly internal to the compiler // the test is just ignored on stable and beta: +// ignore-stage1 // ignore-beta // ignore-stable diff --git a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr index a2f3bb5277b55..3f96144956667 100644 --- a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr +++ b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive.stderr @@ -1,11 +1,11 @@ error: unsupported type attribute for diagnostic derive enum - --> $DIR/diagnostic-derive.rs:41:1 + --> $DIR/diagnostic-derive.rs:42:1 | LL | #[diag(no_crate_example, code = "E0123")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:44:5 + --> $DIR/diagnostic-derive.rs:45:5 | LL | Foo, | ^^^ @@ -13,7 +13,7 @@ LL | Foo, = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:46:5 + --> $DIR/diagnostic-derive.rs:47:5 | LL | Bar, | ^^^ @@ -21,19 +21,19 @@ LL | Bar, = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: expected parentheses: #[diag(...)] - --> $DIR/diagnostic-derive.rs:52:8 + --> $DIR/diagnostic-derive.rs:53:8 | LL | #[diag = "E0123"] | ^ error: `#[nonsense(...)]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:57:1 + --> $DIR/diagnostic-derive.rs:58:1 | LL | #[nonsense(no_crate_example, code = "E0123")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:57:1 + --> $DIR/diagnostic-derive.rs:58:1 | LL | / #[nonsense(no_crate_example, code = "E0123")] LL | | @@ -45,7 +45,7 @@ LL | | struct InvalidStructAttr {} = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:64:1 + --> $DIR/diagnostic-derive.rs:65:1 | LL | / #[diag("E0123")] LL | | @@ -55,13 +55,13 @@ LL | | struct InvalidLitNestedAttr {} = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: diagnostic slug must be the first argument - --> $DIR/diagnostic-derive.rs:74:16 + --> $DIR/diagnostic-derive.rs:75:16 | LL | #[diag(nonsense("foo"), code = "E0123", slug = "foo")] | ^ error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:74:1 + --> $DIR/diagnostic-derive.rs:75:1 | LL | / #[diag(nonsense("foo"), code = "E0123", slug = "foo")] LL | | @@ -72,7 +72,7 @@ LL | | struct InvalidNestedStructAttr1 {} = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: unknown argument - --> $DIR/diagnostic-derive.rs:80:8 + --> $DIR/diagnostic-derive.rs:81:8 | LL | #[diag(nonsense = "...", code = "E0123", slug = "foo")] | ^^^^^^^^ @@ -80,7 +80,7 @@ LL | #[diag(nonsense = "...", code = "E0123", slug = "foo")] = note: only the `code` parameter is valid after the slug error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:80:1 + --> $DIR/diagnostic-derive.rs:81:1 | LL | / #[diag(nonsense = "...", code = "E0123", slug = "foo")] LL | | @@ -91,7 +91,7 @@ LL | | struct InvalidNestedStructAttr2 {} = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: unknown argument - --> $DIR/diagnostic-derive.rs:86:8 + --> $DIR/diagnostic-derive.rs:87:8 | LL | #[diag(nonsense = 4, code = "E0123", slug = "foo")] | ^^^^^^^^ @@ -99,7 +99,7 @@ LL | #[diag(nonsense = 4, code = "E0123", slug = "foo")] = note: only the `code` parameter is valid after the slug error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:86:1 + --> $DIR/diagnostic-derive.rs:87:1 | LL | / #[diag(nonsense = 4, code = "E0123", slug = "foo")] LL | | @@ -110,7 +110,7 @@ LL | | struct InvalidNestedStructAttr3 {} = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: unknown argument - --> $DIR/diagnostic-derive.rs:92:42 + --> $DIR/diagnostic-derive.rs:93:42 | LL | #[diag(no_crate_example, code = "E0123", slug = "foo")] | ^^^^ @@ -118,55 +118,55 @@ LL | #[diag(no_crate_example, code = "E0123", slug = "foo")] = note: only the `code` parameter is valid after the slug error: `#[suggestion = ...]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:99:5 + --> $DIR/diagnostic-derive.rs:100:5 | LL | #[suggestion = "bar"] | ^^^^^^^^^^^^^^^^^^^^^ error: specified multiple times - --> $DIR/diagnostic-derive.rs:106:8 + --> $DIR/diagnostic-derive.rs:107:8 | LL | #[diag(no_crate_example, code = "E0456")] | ^^^^^^^^^^^^^^^^ | note: previously specified here - --> $DIR/diagnostic-derive.rs:105:8 + --> $DIR/diagnostic-derive.rs:106:8 | LL | #[diag(no_crate_example, code = "E0123")] | ^^^^^^^^^^^^^^^^ error: specified multiple times - --> $DIR/diagnostic-derive.rs:106:26 + --> $DIR/diagnostic-derive.rs:107:26 | LL | #[diag(no_crate_example, code = "E0456")] | ^^^^ | note: previously specified here - --> $DIR/diagnostic-derive.rs:105:26 + --> $DIR/diagnostic-derive.rs:106:26 | LL | #[diag(no_crate_example, code = "E0123")] | ^^^^ error: specified multiple times - --> $DIR/diagnostic-derive.rs:112:42 + --> $DIR/diagnostic-derive.rs:113:42 | LL | #[diag(no_crate_example, code = "E0456", code = "E0457")] | ^^^^ | note: previously specified here - --> $DIR/diagnostic-derive.rs:112:26 + --> $DIR/diagnostic-derive.rs:113:26 | LL | #[diag(no_crate_example, code = "E0456", code = "E0457")] | ^^^^ error: diagnostic slug must be the first argument - --> $DIR/diagnostic-derive.rs:117:43 + --> $DIR/diagnostic-derive.rs:118:43 | LL | #[diag(no_crate_example, no_crate::example, code = "E0456")] | ^ error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:122:1 + --> $DIR/diagnostic-derive.rs:123:1 | LL | struct KindNotProvided {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -174,7 +174,7 @@ LL | struct KindNotProvided {} = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:125:1 + --> $DIR/diagnostic-derive.rs:126:1 | LL | / #[diag(code = "E0456")] LL | | @@ -184,31 +184,31 @@ LL | | struct SlugNotProvided {} = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: the `#[primary_span]` attribute can only be applied to fields of type `Span` or `MultiSpan` - --> $DIR/diagnostic-derive.rs:136:5 + --> $DIR/diagnostic-derive.rs:137:5 | LL | #[primary_span] | ^^^^^^^^^^^^^^^ error: `#[nonsense]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:144:5 + --> $DIR/diagnostic-derive.rs:145:5 | LL | #[nonsense] | ^^^^^^^^^^^ error: the `#[label(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` - --> $DIR/diagnostic-derive.rs:161:5 + --> $DIR/diagnostic-derive.rs:162:5 | LL | #[label(no_crate_label)] | ^^^^^^^^^^^^^^^^^^^^^^^^ error: `name` doesn't refer to a field on this type - --> $DIR/diagnostic-derive.rs:169:46 + --> $DIR/diagnostic-derive.rs:170:46 | LL | #[suggestion(no_crate_suggestion, code = "{name}")] | ^^^^^^^^ error: invalid format string: expected `'}'` but string was terminated - --> $DIR/diagnostic-derive.rs:174:10 + --> $DIR/diagnostic-derive.rs:175:10 | LL | #[derive(Diagnostic)] | ^^^^^^^^^^ expected `'}'` in format string @@ -217,7 +217,7 @@ LL | #[derive(Diagnostic)] = note: this error originates in the derive macro `Diagnostic` (in Nightly builds, run with -Z macro-backtrace for more info) error: invalid format string: unmatched `}` found - --> $DIR/diagnostic-derive.rs:184:10 + --> $DIR/diagnostic-derive.rs:185:10 | LL | #[derive(Diagnostic)] | ^^^^^^^^^^ unmatched `}` in format string @@ -226,19 +226,19 @@ LL | #[derive(Diagnostic)] = note: this error originates in the derive macro `Diagnostic` (in Nightly builds, run with -Z macro-backtrace for more info) error: the `#[label(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` - --> $DIR/diagnostic-derive.rs:204:5 + --> $DIR/diagnostic-derive.rs:205:5 | LL | #[label(no_crate_label)] | ^^^^^^^^^^^^^^^^^^^^^^^^ error: suggestion without `code = "..."` - --> $DIR/diagnostic-derive.rs:223:5 + --> $DIR/diagnostic-derive.rs:224:5 | LL | #[suggestion(no_crate_suggestion)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: invalid nested attribute - --> $DIR/diagnostic-derive.rs:231:18 + --> $DIR/diagnostic-derive.rs:232:18 | LL | #[suggestion(nonsense = "bar")] | ^^^^^^^^ @@ -246,13 +246,13 @@ LL | #[suggestion(nonsense = "bar")] = help: only `style`, `code` and `applicability` are valid nested attributes error: suggestion without `code = "..."` - --> $DIR/diagnostic-derive.rs:231:5 + --> $DIR/diagnostic-derive.rs:232:5 | LL | #[suggestion(nonsense = "bar")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: invalid nested attribute - --> $DIR/diagnostic-derive.rs:240:18 + --> $DIR/diagnostic-derive.rs:241:18 | LL | #[suggestion(msg = "bar")] | ^^^ @@ -260,13 +260,13 @@ LL | #[suggestion(msg = "bar")] = help: only `style`, `code` and `applicability` are valid nested attributes error: suggestion without `code = "..."` - --> $DIR/diagnostic-derive.rs:240:5 + --> $DIR/diagnostic-derive.rs:241:5 | LL | #[suggestion(msg = "bar")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: wrong field type for suggestion - --> $DIR/diagnostic-derive.rs:263:5 + --> $DIR/diagnostic-derive.rs:264:5 | LL | / #[suggestion(no_crate_suggestion, code = "This is suggested code")] LL | | @@ -276,79 +276,79 @@ LL | | suggestion: Applicability, = help: `#[suggestion(...)]` should be applied to fields of type `Span` or `(Span, Applicability)` error: specified multiple times - --> $DIR/diagnostic-derive.rs:279:24 + --> $DIR/diagnostic-derive.rs:280:24 | LL | suggestion: (Span, Span, Applicability), | ^^^^ | note: previously specified here - --> $DIR/diagnostic-derive.rs:279:18 + --> $DIR/diagnostic-derive.rs:280:18 | LL | suggestion: (Span, Span, Applicability), | ^^^^ error: specified multiple times - --> $DIR/diagnostic-derive.rs:287:33 + --> $DIR/diagnostic-derive.rs:288:33 | LL | suggestion: (Applicability, Applicability, Span), | ^^^^^^^^^^^^^ | note: previously specified here - --> $DIR/diagnostic-derive.rs:287:18 + --> $DIR/diagnostic-derive.rs:288:18 | LL | suggestion: (Applicability, Applicability, Span), | ^^^^^^^^^^^^^ error: `#[label = ...]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:294:5 + --> $DIR/diagnostic-derive.rs:295:5 | LL | #[label = "bar"] | ^^^^^^^^^^^^^^^^ error: specified multiple times - --> $DIR/diagnostic-derive.rs:445:5 + --> $DIR/diagnostic-derive.rs:446:5 | LL | #[suggestion(no_crate_suggestion, code = "...", applicability = "maybe-incorrect")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: previously specified here - --> $DIR/diagnostic-derive.rs:447:24 + --> $DIR/diagnostic-derive.rs:448:24 | LL | suggestion: (Span, Applicability), | ^^^^^^^^^^^^^ error: invalid applicability - --> $DIR/diagnostic-derive.rs:453:69 + --> $DIR/diagnostic-derive.rs:454:69 | LL | #[suggestion(no_crate_suggestion, code = "...", applicability = "batman")] | ^^^^^^^^ error: the `#[help(...)]` attribute can only be applied to fields of type `Span`, `MultiSpan`, `bool` or `()` - --> $DIR/diagnostic-derive.rs:520:5 + --> $DIR/diagnostic-derive.rs:521:5 | LL | #[help(no_crate_help)] | ^^^^^^^^^^^^^^^^^^^^^^ error: a diagnostic slug must be the first argument to the attribute - --> $DIR/diagnostic-derive.rs:529:32 + --> $DIR/diagnostic-derive.rs:530:32 | LL | #[label(no_crate_label, foo)] | ^ error: invalid nested attribute - --> $DIR/diagnostic-derive.rs:537:29 + --> $DIR/diagnostic-derive.rs:538:29 | LL | #[label(no_crate_label, foo = "...")] | ^^^ error: invalid nested attribute - --> $DIR/diagnostic-derive.rs:545:29 + --> $DIR/diagnostic-derive.rs:546:29 | LL | #[label(no_crate_label, foo("..."))] | ^^^ error: `#[primary_span]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:557:5 + --> $DIR/diagnostic-derive.rs:558:5 | LL | #[primary_span] | ^^^^^^^^^^^^^^^ @@ -356,13 +356,13 @@ LL | #[primary_span] = help: the `primary_span` field attribute is not valid for lint diagnostics error: `#[error(...)]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:577:1 + --> $DIR/diagnostic-derive.rs:578:1 | LL | #[error(no_crate_example, code = "E0123")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:577:1 + --> $DIR/diagnostic-derive.rs:578:1 | LL | / #[error(no_crate_example, code = "E0123")] LL | | @@ -374,13 +374,13 @@ LL | | struct ErrorAttribute {} = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: `#[warn_(...)]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:584:1 + --> $DIR/diagnostic-derive.rs:585:1 | LL | #[warn_(no_crate_example, code = "E0123")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:584:1 + --> $DIR/diagnostic-derive.rs:585:1 | LL | / #[warn_(no_crate_example, code = "E0123")] LL | | @@ -392,13 +392,13 @@ LL | | struct WarnAttribute {} = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: `#[lint(...)]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:591:1 + --> $DIR/diagnostic-derive.rs:592:1 | LL | #[lint(no_crate_example, code = "E0123")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:591:1 + --> $DIR/diagnostic-derive.rs:592:1 | LL | / #[lint(no_crate_example, code = "E0123")] LL | | @@ -410,19 +410,19 @@ LL | | struct LintAttributeOnSessionDiag {} = help: specify the slug as the first argument to the `#[diag(...)]` attribute, such as `#[diag(hir_analysis_example_error)]` error: `#[lint(...)]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:598:1 + --> $DIR/diagnostic-derive.rs:599:1 | LL | #[lint(no_crate_example, code = "E0123")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: `#[lint(...)]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:598:1 + --> $DIR/diagnostic-derive.rs:599:1 | LL | #[lint(no_crate_example, code = "E0123")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: diagnostic slug not specified - --> $DIR/diagnostic-derive.rs:598:1 + --> $DIR/diagnostic-derive.rs:599:1 | LL | / #[lint(no_crate_example, code = "E0123")] LL | | @@ -435,19 +435,19 @@ LL | | struct LintAttributeOnLintDiag {} = help: specify the slug as the first argument to the attribute, such as `#[diag(compiletest_example)]` error: specified multiple times - --> $DIR/diagnostic-derive.rs:608:53 + --> $DIR/diagnostic-derive.rs:609:53 | LL | #[suggestion(no_crate_suggestion, code = "...", code = ",,,")] | ^^^^ | note: previously specified here - --> $DIR/diagnostic-derive.rs:608:39 + --> $DIR/diagnostic-derive.rs:609:39 | LL | #[suggestion(no_crate_suggestion, code = "...", code = ",,,")] | ^^^^ error: wrong types for suggestion - --> $DIR/diagnostic-derive.rs:617:24 + --> $DIR/diagnostic-derive.rs:618:24 | LL | suggestion: (Span, usize), | ^^^^^ @@ -455,7 +455,7 @@ LL | suggestion: (Span, usize), = help: `#[suggestion(...)]` on a tuple field must be applied to fields of type `(Span, Applicability)` error: wrong types for suggestion - --> $DIR/diagnostic-derive.rs:625:17 + --> $DIR/diagnostic-derive.rs:626:17 | LL | suggestion: (Span,), | ^^^^^^^ @@ -463,13 +463,13 @@ LL | suggestion: (Span,), = help: `#[suggestion(...)]` on a tuple field must be applied to fields of type `(Span, Applicability)` error: suggestion without `code = "..."` - --> $DIR/diagnostic-derive.rs:632:5 + --> $DIR/diagnostic-derive.rs:633:5 | LL | #[suggestion(no_crate_suggestion)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: `#[multipart_suggestion(...)]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:639:1 + --> $DIR/diagnostic-derive.rs:640:1 | LL | #[multipart_suggestion(no_crate_suggestion)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -477,7 +477,7 @@ LL | #[multipart_suggestion(no_crate_suggestion)] = help: consider creating a `Subdiagnostic` instead error: `#[multipart_suggestion(...)]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:646:5 + --> $DIR/diagnostic-derive.rs:647:5 | LL | #[multipart_suggestion(no_crate_suggestion)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -485,13 +485,13 @@ LL | #[multipart_suggestion(no_crate_suggestion)] = help: consider creating a `Subdiagnostic` instead error: unexpected end of input, unexpected token in nested attribute, expected ident - --> $DIR/diagnostic-derive.rs:642:24 + --> $DIR/diagnostic-derive.rs:643:24 | LL | #[multipart_suggestion()] | ^ error: `#[suggestion(...)]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:654:1 + --> $DIR/diagnostic-derive.rs:655:1 | LL | #[suggestion(no_crate_suggestion, code = "...")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -499,7 +499,7 @@ LL | #[suggestion(no_crate_suggestion, code = "...")] = help: `#[label]` and `#[suggestion]` can only be applied to fields error: `#[label]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:663:1 + --> $DIR/diagnostic-derive.rs:664:1 | LL | #[label] | ^^^^^^^^ @@ -507,31 +507,31 @@ LL | #[label] = help: `#[label]` and `#[suggestion]` can only be applied to fields error: `eager` is the only supported nested attribute for `subdiagnostic` - --> $DIR/diagnostic-derive.rs:697:7 + --> $DIR/diagnostic-derive.rs:698:7 | LL | #[subdiagnostic(bad)] | ^^^^^^^^^^^^^^^^^^ error: `#[subdiagnostic = ...]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:705:5 + --> $DIR/diagnostic-derive.rs:706:5 | LL | #[subdiagnostic = "bad"] | ^^^^^^^^^^^^^^^^^^^^^^^^ error: `eager` is the only supported nested attribute for `subdiagnostic` - --> $DIR/diagnostic-derive.rs:713:7 + --> $DIR/diagnostic-derive.rs:714:7 | LL | #[subdiagnostic(bad, bad)] | ^^^^^^^^^^^^^^^^^^^^^^^ error: `eager` is the only supported nested attribute for `subdiagnostic` - --> $DIR/diagnostic-derive.rs:721:7 + --> $DIR/diagnostic-derive.rs:722:7 | LL | #[subdiagnostic("bad")] | ^^^^^^^^^^^^^^^^^^^^ error: `#[subdiagnostic(...)]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:729:5 + --> $DIR/diagnostic-derive.rs:730:5 | LL | #[subdiagnostic(eager)] | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -539,31 +539,31 @@ LL | #[subdiagnostic(eager)] = help: eager subdiagnostics are not supported on lints error: expected at least one string literal for `code(...)` - --> $DIR/diagnostic-derive.rs:787:23 + --> $DIR/diagnostic-derive.rs:788:23 | LL | #[suggestion(code())] | ^ error: `code(...)` must contain only string literals - --> $DIR/diagnostic-derive.rs:795:23 + --> $DIR/diagnostic-derive.rs:796:23 | LL | #[suggestion(code(foo))] | ^^^ error: unexpected token - --> $DIR/diagnostic-derive.rs:795:23 + --> $DIR/diagnostic-derive.rs:796:23 | LL | #[suggestion(code(foo))] | ^^^ error: expected string literal - --> $DIR/diagnostic-derive.rs:804:25 + --> $DIR/diagnostic-derive.rs:805:25 | LL | #[suggestion(code = 3)] | ^ error: `#[suggestion(...)]` is not a valid attribute - --> $DIR/diagnostic-derive.rs:819:5 + --> $DIR/diagnostic-derive.rs:820:5 | LL | #[suggestion(no_crate_suggestion, code = "")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -573,67 +573,67 @@ LL | #[suggestion(no_crate_suggestion, code = "")] = help: to show a variable set of suggestions, use a `Vec` of `Subdiagnostic`s annotated with `#[suggestion(...)]` error: cannot find attribute `nonsense` in this scope - --> $DIR/diagnostic-derive.rs:57:3 + --> $DIR/diagnostic-derive.rs:58:3 | LL | #[nonsense(no_crate_example, code = "E0123")] | ^^^^^^^^ error: cannot find attribute `nonsense` in this scope - --> $DIR/diagnostic-derive.rs:144:7 + --> $DIR/diagnostic-derive.rs:145:7 | LL | #[nonsense] | ^^^^^^^^ error: cannot find attribute `error` in this scope - --> $DIR/diagnostic-derive.rs:577:3 + --> $DIR/diagnostic-derive.rs:578:3 | LL | #[error(no_crate_example, code = "E0123")] | ^^^^^ error: cannot find attribute `warn_` in this scope - --> $DIR/diagnostic-derive.rs:584:3 + --> $DIR/diagnostic-derive.rs:585:3 | LL | #[warn_(no_crate_example, code = "E0123")] | ^^^^^ help: a built-in attribute with a similar name exists: `warn` error: cannot find attribute `lint` in this scope - --> $DIR/diagnostic-derive.rs:591:3 + --> $DIR/diagnostic-derive.rs:592:3 | LL | #[lint(no_crate_example, code = "E0123")] | ^^^^ help: a built-in attribute with a similar name exists: `link` error: cannot find attribute `lint` in this scope - --> $DIR/diagnostic-derive.rs:598:3 + --> $DIR/diagnostic-derive.rs:599:3 | LL | #[lint(no_crate_example, code = "E0123")] | ^^^^ help: a built-in attribute with a similar name exists: `link` error: cannot find attribute `multipart_suggestion` in this scope - --> $DIR/diagnostic-derive.rs:639:3 + --> $DIR/diagnostic-derive.rs:640:3 | LL | #[multipart_suggestion(no_crate_suggestion)] | ^^^^^^^^^^^^^^^^^^^^ error: cannot find attribute `multipart_suggestion` in this scope - --> $DIR/diagnostic-derive.rs:642:3 + --> $DIR/diagnostic-derive.rs:643:3 | LL | #[multipart_suggestion()] | ^^^^^^^^^^^^^^^^^^^^ error: cannot find attribute `multipart_suggestion` in this scope - --> $DIR/diagnostic-derive.rs:646:7 + --> $DIR/diagnostic-derive.rs:647:7 | LL | #[multipart_suggestion(no_crate_suggestion)] | ^^^^^^^^^^^^^^^^^^^^ error[E0425]: cannot find value `nonsense` in module `crate::fluent_generated` - --> $DIR/diagnostic-derive.rs:69:8 + --> $DIR/diagnostic-derive.rs:70:8 | LL | #[diag(nonsense, code = "E0123")] | ^^^^^^^^ not found in `crate::fluent_generated` error[E0425]: cannot find value `__code_34` in this scope - --> $DIR/diagnostic-derive.rs:801:10 + --> $DIR/diagnostic-derive.rs:802:10 | LL | #[derive(Diagnostic)] | ^^^^^^^^^^ not found in this scope @@ -641,7 +641,7 @@ LL | #[derive(Diagnostic)] = note: this error originates in the derive macro `Diagnostic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `Hello: IntoDiagnosticArg` is not satisfied - --> $DIR/diagnostic-derive.rs:338:10 + --> $DIR/diagnostic-derive.rs:339:10 | LL | #[derive(Diagnostic)] | ^^^^^^^^^^ the trait `IntoDiagnosticArg` is not implemented for `Hello` diff --git a/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs b/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs index 1d928ca93f9cb..73cc1cfc03a2b 100644 --- a/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs +++ b/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.rs @@ -4,6 +4,7 @@ // The proc_macro2 crate handles spans differently when on beta/stable release rather than nightly, // changing the output of this test. Since Subdiagnostic is strictly internal to the compiler // the test is just ignored on stable and beta: +// ignore-stage1 // ignore-beta // ignore-stable diff --git a/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr b/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr index 4211b91f04a0e..529003d90ab88 100644 --- a/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr +++ b/tests/ui-fulldeps/session-diagnostic/subdiagnostic-derive.stderr @@ -1,5 +1,5 @@ error: label without `#[primary_span]` field - --> $DIR/subdiagnostic-derive.rs:49:1 + --> $DIR/subdiagnostic-derive.rs:50:1 | LL | / #[label(no_crate_example)] LL | | @@ -9,133 +9,133 @@ LL | | } | |_^ error: diagnostic slug must be first argument of a `#[label(...)]` attribute - --> $DIR/subdiagnostic-derive.rs:56:1 + --> $DIR/subdiagnostic-derive.rs:57:1 | LL | #[label] | ^^^^^^^^ error: `#[foo]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:65:1 + --> $DIR/subdiagnostic-derive.rs:66:1 | LL | #[foo] | ^^^^^^ error: `#[label = ...]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:75:1 + --> $DIR/subdiagnostic-derive.rs:76:1 | LL | #[label = "..."] | ^^^^^^^^^^^^^^^^ error: invalid nested attribute - --> $DIR/subdiagnostic-derive.rs:84:9 + --> $DIR/subdiagnostic-derive.rs:85:9 | LL | #[label(bug = "...")] | ^^^ error: diagnostic slug must be first argument of a `#[label(...)]` attribute - --> $DIR/subdiagnostic-derive.rs:84:1 + --> $DIR/subdiagnostic-derive.rs:85:1 | LL | #[label(bug = "...")] | ^^^^^^^^^^^^^^^^^^^^^ error: unexpected literal in nested attribute, expected ident - --> $DIR/subdiagnostic-derive.rs:94:9 + --> $DIR/subdiagnostic-derive.rs:95:9 | LL | #[label("...")] | ^^^^^ error: invalid nested attribute - --> $DIR/subdiagnostic-derive.rs:103:9 + --> $DIR/subdiagnostic-derive.rs:104:9 | LL | #[label(slug = 4)] | ^^^^ error: diagnostic slug must be first argument of a `#[label(...)]` attribute - --> $DIR/subdiagnostic-derive.rs:103:1 + --> $DIR/subdiagnostic-derive.rs:104:1 | LL | #[label(slug = 4)] | ^^^^^^^^^^^^^^^^^^ error: invalid nested attribute - --> $DIR/subdiagnostic-derive.rs:113:9 + --> $DIR/subdiagnostic-derive.rs:114:9 | LL | #[label(slug("..."))] | ^^^^ error: diagnostic slug must be first argument of a `#[label(...)]` attribute - --> $DIR/subdiagnostic-derive.rs:113:1 + --> $DIR/subdiagnostic-derive.rs:114:1 | LL | #[label(slug("..."))] | ^^^^^^^^^^^^^^^^^^^^^ error: unexpected end of input, unexpected token in nested attribute, expected ident - --> $DIR/subdiagnostic-derive.rs:133:9 + --> $DIR/subdiagnostic-derive.rs:134:9 | LL | #[label()] | ^ error: invalid nested attribute - --> $DIR/subdiagnostic-derive.rs:142:27 + --> $DIR/subdiagnostic-derive.rs:143:27 | LL | #[label(no_crate_example, code = "...")] | ^^^^ error: invalid nested attribute - --> $DIR/subdiagnostic-derive.rs:151:27 + --> $DIR/subdiagnostic-derive.rs:152:27 | LL | #[label(no_crate_example, applicability = "machine-applicable")] | ^^^^^^^^^^^^^ error: unsupported type attribute for subdiagnostic enum - --> $DIR/subdiagnostic-derive.rs:160:1 + --> $DIR/subdiagnostic-derive.rs:161:1 | LL | #[foo] | ^^^^^^ error: `#[bar]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:174:5 + --> $DIR/subdiagnostic-derive.rs:175:5 | LL | #[bar] | ^^^^^^ error: `#[bar = ...]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:186:5 + --> $DIR/subdiagnostic-derive.rs:187:5 | LL | #[bar = "..."] | ^^^^^^^^^^^^^^ error: `#[bar = ...]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:198:5 + --> $DIR/subdiagnostic-derive.rs:199:5 | LL | #[bar = 4] | ^^^^^^^^^^ error: `#[bar(...)]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:210:5 + --> $DIR/subdiagnostic-derive.rs:211:5 | LL | #[bar("...")] | ^^^^^^^^^^^^^ error: invalid nested attribute - --> $DIR/subdiagnostic-derive.rs:222:13 + --> $DIR/subdiagnostic-derive.rs:223:13 | LL | #[label(code = "...")] | ^^^^ error: diagnostic slug must be first argument of a `#[label(...)]` attribute - --> $DIR/subdiagnostic-derive.rs:222:5 + --> $DIR/subdiagnostic-derive.rs:223:5 | LL | #[label(code = "...")] | ^^^^^^^^^^^^^^^^^^^^^^ error: the `#[primary_span]` attribute can only be applied to fields of type `Span` or `MultiSpan` - --> $DIR/subdiagnostic-derive.rs:251:5 + --> $DIR/subdiagnostic-derive.rs:252:5 | LL | #[primary_span] | ^^^^^^^^^^^^^^^ error: label without `#[primary_span]` field - --> $DIR/subdiagnostic-derive.rs:248:1 + --> $DIR/subdiagnostic-derive.rs:249:1 | LL | / #[label(no_crate_example)] LL | | @@ -147,13 +147,13 @@ LL | | } | |_^ error: `#[applicability]` is only valid on suggestions - --> $DIR/subdiagnostic-derive.rs:261:5 + --> $DIR/subdiagnostic-derive.rs:262:5 | LL | #[applicability] | ^^^^^^^^^^^^^^^^ error: `#[bar]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:271:5 + --> $DIR/subdiagnostic-derive.rs:272:5 | LL | #[bar] | ^^^^^^ @@ -161,13 +161,13 @@ LL | #[bar] = help: only `primary_span`, `applicability` and `skip_arg` are valid field attributes error: `#[bar = ...]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:282:5 + --> $DIR/subdiagnostic-derive.rs:283:5 | LL | #[bar = "..."] | ^^^^^^^^^^^^^^ error: `#[bar(...)]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:293:5 + --> $DIR/subdiagnostic-derive.rs:294:5 | LL | #[bar("...")] | ^^^^^^^^^^^^^ @@ -175,7 +175,7 @@ LL | #[bar("...")] = help: only `primary_span`, `applicability` and `skip_arg` are valid field attributes error: unexpected unsupported untagged union - --> $DIR/subdiagnostic-derive.rs:309:1 + --> $DIR/subdiagnostic-derive.rs:310:1 | LL | / union AC { LL | | @@ -185,73 +185,73 @@ LL | | } | |_^ error: a diagnostic slug must be the first argument to the attribute - --> $DIR/subdiagnostic-derive.rs:324:44 + --> $DIR/subdiagnostic-derive.rs:325:44 | LL | #[label(no_crate_example, no_crate::example)] | ^ error: specified multiple times - --> $DIR/subdiagnostic-derive.rs:337:5 + --> $DIR/subdiagnostic-derive.rs:338:5 | LL | #[primary_span] | ^^^^^^^^^^^^^^^ | note: previously specified here - --> $DIR/subdiagnostic-derive.rs:334:5 + --> $DIR/subdiagnostic-derive.rs:335:5 | LL | #[primary_span] | ^^^^^^^^^^^^^^^ error: subdiagnostic kind not specified - --> $DIR/subdiagnostic-derive.rs:343:8 + --> $DIR/subdiagnostic-derive.rs:344:8 | LL | struct AG { | ^^ error: specified multiple times - --> $DIR/subdiagnostic-derive.rs:380:46 + --> $DIR/subdiagnostic-derive.rs:381:46 | LL | #[suggestion(no_crate_example, code = "...", code = "...")] | ^^^^ | note: previously specified here - --> $DIR/subdiagnostic-derive.rs:380:32 + --> $DIR/subdiagnostic-derive.rs:381:32 | LL | #[suggestion(no_crate_example, code = "...", code = "...")] | ^^^^ error: specified multiple times - --> $DIR/subdiagnostic-derive.rs:398:5 + --> $DIR/subdiagnostic-derive.rs:399:5 | LL | #[applicability] | ^^^^^^^^^^^^^^^^ | note: previously specified here - --> $DIR/subdiagnostic-derive.rs:395:5 + --> $DIR/subdiagnostic-derive.rs:396:5 | LL | #[applicability] | ^^^^^^^^^^^^^^^^ error: the `#[applicability]` attribute can only be applied to fields of type `Applicability` - --> $DIR/subdiagnostic-derive.rs:408:5 + --> $DIR/subdiagnostic-derive.rs:409:5 | LL | #[applicability] | ^^^^^^^^^^^^^^^^ error: suggestion without `code = "..."` - --> $DIR/subdiagnostic-derive.rs:421:1 + --> $DIR/subdiagnostic-derive.rs:422:1 | LL | #[suggestion(no_crate_example)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: invalid applicability - --> $DIR/subdiagnostic-derive.rs:431:62 + --> $DIR/subdiagnostic-derive.rs:432:62 | LL | #[suggestion(no_crate_example, code = "...", applicability = "foo")] | ^^^^^ error: suggestion without `#[primary_span]` field - --> $DIR/subdiagnostic-derive.rs:449:1 + --> $DIR/subdiagnostic-derive.rs:450:1 | LL | / #[suggestion(no_crate_example, code = "...")] LL | | @@ -261,25 +261,25 @@ LL | | } | |_^ error: unsupported type attribute for subdiagnostic enum - --> $DIR/subdiagnostic-derive.rs:463:1 + --> $DIR/subdiagnostic-derive.rs:464:1 | LL | #[label] | ^^^^^^^^ error: `var` doesn't refer to a field on this type - --> $DIR/subdiagnostic-derive.rs:483:39 + --> $DIR/subdiagnostic-derive.rs:484:39 | LL | #[suggestion(no_crate_example, code = "{var}", applicability = "machine-applicable")] | ^^^^^^^ error: `var` doesn't refer to a field on this type - --> $DIR/subdiagnostic-derive.rs:502:43 + --> $DIR/subdiagnostic-derive.rs:503:43 | LL | #[suggestion(no_crate_example, code = "{var}", applicability = "machine-applicable")] | ^^^^^^^ error: `#[suggestion_part]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:525:5 + --> $DIR/subdiagnostic-derive.rs:526:5 | LL | #[suggestion_part] | ^^^^^^^^^^^^^^^^^^ @@ -287,7 +287,7 @@ LL | #[suggestion_part] = help: `#[suggestion_part(...)]` is only valid in multipart suggestions, use `#[primary_span]` instead error: `#[suggestion_part(...)]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:528:5 + --> $DIR/subdiagnostic-derive.rs:529:5 | LL | #[suggestion_part(code = "...")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -295,7 +295,7 @@ LL | #[suggestion_part(code = "...")] = help: `#[suggestion_part(...)]` is only valid in multipart suggestions error: suggestion without `#[primary_span]` field - --> $DIR/subdiagnostic-derive.rs:522:1 + --> $DIR/subdiagnostic-derive.rs:523:1 | LL | / #[suggestion(no_crate_example, code = "...")] LL | | @@ -307,7 +307,7 @@ LL | | } | |_^ error: invalid nested attribute - --> $DIR/subdiagnostic-derive.rs:537:42 + --> $DIR/subdiagnostic-derive.rs:538:42 | LL | #[multipart_suggestion(no_crate_example, code = "...", applicability = "machine-applicable")] | ^^^^ @@ -315,7 +315,7 @@ LL | #[multipart_suggestion(no_crate_example, code = "...", applicability = "mac = help: only `style` and `applicability` are valid nested attributes error: multipart suggestion without any `#[suggestion_part(...)]` fields - --> $DIR/subdiagnostic-derive.rs:537:1 + --> $DIR/subdiagnostic-derive.rs:538:1 | LL | / #[multipart_suggestion(no_crate_example, code = "...", applicability = "machine-applicable")] LL | | @@ -326,19 +326,19 @@ LL | | } | |_^ error: `#[suggestion_part(...)]` attribute without `code = "..."` - --> $DIR/subdiagnostic-derive.rs:547:5 + --> $DIR/subdiagnostic-derive.rs:548:5 | LL | #[suggestion_part] | ^^^^^^^^^^^^^^^^^^ error: unexpected end of input, unexpected token in nested attribute, expected ident - --> $DIR/subdiagnostic-derive.rs:555:23 + --> $DIR/subdiagnostic-derive.rs:556:23 | LL | #[suggestion_part()] | ^ error: `#[primary_span]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:564:5 + --> $DIR/subdiagnostic-derive.rs:565:5 | LL | #[primary_span] | ^^^^^^^^^^^^^^^ @@ -346,7 +346,7 @@ LL | #[primary_span] = help: multipart suggestions use one or more `#[suggestion_part]`s rather than one `#[primary_span]` error: multipart suggestion without any `#[suggestion_part(...)]` fields - --> $DIR/subdiagnostic-derive.rs:561:1 + --> $DIR/subdiagnostic-derive.rs:562:1 | LL | / #[multipart_suggestion(no_crate_example)] LL | | @@ -358,121 +358,121 @@ LL | | } | |_^ error: `#[suggestion_part(...)]` attribute without `code = "..."` - --> $DIR/subdiagnostic-derive.rs:572:5 + --> $DIR/subdiagnostic-derive.rs:573:5 | LL | #[suggestion_part] | ^^^^^^^^^^^^^^^^^^ error: `code` is the only valid nested attribute - --> $DIR/subdiagnostic-derive.rs:578:23 + --> $DIR/subdiagnostic-derive.rs:579:23 | LL | #[suggestion_part(foo = "bar")] | ^^^ error: the `#[suggestion_part(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` - --> $DIR/subdiagnostic-derive.rs:582:5 + --> $DIR/subdiagnostic-derive.rs:583:5 | LL | #[suggestion_part(code = "...")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: the `#[suggestion_part(...)]` attribute can only be applied to fields of type `Span` or `MultiSpan` - --> $DIR/subdiagnostic-derive.rs:585:5 + --> $DIR/subdiagnostic-derive.rs:586:5 | LL | #[suggestion_part()] | ^^^^^^^^^^^^^^^^^^^^ error: unexpected end of input, unexpected token in nested attribute, expected ident - --> $DIR/subdiagnostic-derive.rs:575:23 + --> $DIR/subdiagnostic-derive.rs:576:23 | LL | #[suggestion_part()] | ^ error: expected `,` - --> $DIR/subdiagnostic-derive.rs:578:27 + --> $DIR/subdiagnostic-derive.rs:579:27 | LL | #[suggestion_part(foo = "bar")] | ^ error: specified multiple times - --> $DIR/subdiagnostic-derive.rs:593:37 + --> $DIR/subdiagnostic-derive.rs:594:37 | LL | #[suggestion_part(code = "...", code = ",,,")] | ^^^^ | note: previously specified here - --> $DIR/subdiagnostic-derive.rs:593:23 + --> $DIR/subdiagnostic-derive.rs:594:23 | LL | #[suggestion_part(code = "...", code = ",,,")] | ^^^^ error: `#[applicability]` has no effect if all `#[suggestion]`/`#[multipart_suggestion]` attributes have a static `applicability = "..."` - --> $DIR/subdiagnostic-derive.rs:622:5 + --> $DIR/subdiagnostic-derive.rs:623:5 | LL | #[applicability] | ^^^^^^^^^^^^^^^^ error: expected exactly one string literal for `code = ...` - --> $DIR/subdiagnostic-derive.rs:670:34 + --> $DIR/subdiagnostic-derive.rs:671:34 | LL | #[suggestion_part(code("foo"))] | ^ error: unexpected token - --> $DIR/subdiagnostic-derive.rs:670:28 + --> $DIR/subdiagnostic-derive.rs:671:28 | LL | #[suggestion_part(code("foo"))] | ^^^^^ error: expected exactly one string literal for `code = ...` - --> $DIR/subdiagnostic-derive.rs:680:41 + --> $DIR/subdiagnostic-derive.rs:681:41 | LL | #[suggestion_part(code("foo", "bar"))] | ^ error: unexpected token - --> $DIR/subdiagnostic-derive.rs:680:28 + --> $DIR/subdiagnostic-derive.rs:681:28 | LL | #[suggestion_part(code("foo", "bar"))] | ^^^^^ error: expected exactly one string literal for `code = ...` - --> $DIR/subdiagnostic-derive.rs:690:30 + --> $DIR/subdiagnostic-derive.rs:691:30 | LL | #[suggestion_part(code(3))] | ^ error: unexpected token - --> $DIR/subdiagnostic-derive.rs:690:28 + --> $DIR/subdiagnostic-derive.rs:691:28 | LL | #[suggestion_part(code(3))] | ^ error: expected exactly one string literal for `code = ...` - --> $DIR/subdiagnostic-derive.rs:700:29 + --> $DIR/subdiagnostic-derive.rs:701:29 | LL | #[suggestion_part(code())] | ^ error: expected string literal - --> $DIR/subdiagnostic-derive.rs:712:30 + --> $DIR/subdiagnostic-derive.rs:713:30 | LL | #[suggestion_part(code = 3)] | ^ error: specified multiple times - --> $DIR/subdiagnostic-derive.rs:754:1 + --> $DIR/subdiagnostic-derive.rs:755:1 | LL | #[suggestion(no_crate_example, code = "", style = "hidden", style = "normal")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: previously specified here - --> $DIR/subdiagnostic-derive.rs:754:1 + --> $DIR/subdiagnostic-derive.rs:755:1 | LL | #[suggestion(no_crate_example, code = "", style = "hidden", style = "normal")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: `#[suggestion_hidden(...)]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:763:1 + --> $DIR/subdiagnostic-derive.rs:764:1 | LL | #[suggestion_hidden(no_crate_example, code = "")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -480,7 +480,7 @@ LL | #[suggestion_hidden(no_crate_example, code = "")] = help: Use `#[suggestion(..., style = "hidden")]` instead error: `#[suggestion_hidden(...)]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:771:1 + --> $DIR/subdiagnostic-derive.rs:772:1 | LL | #[suggestion_hidden(no_crate_example, code = "", style = "normal")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -488,7 +488,7 @@ LL | #[suggestion_hidden(no_crate_example, code = "", style = "normal")] = help: Use `#[suggestion(..., style = "hidden")]` instead error: invalid suggestion style - --> $DIR/subdiagnostic-derive.rs:779:51 + --> $DIR/subdiagnostic-derive.rs:780:51 | LL | #[suggestion(no_crate_example, code = "", style = "foo")] | ^^^^^ @@ -496,31 +496,31 @@ LL | #[suggestion(no_crate_example, code = "", style = "foo")] = help: valid styles are `normal`, `short`, `hidden`, `verbose` and `tool-only` error: expected `= "xxx"` - --> $DIR/subdiagnostic-derive.rs:787:49 + --> $DIR/subdiagnostic-derive.rs:788:49 | LL | #[suggestion(no_crate_example, code = "", style = 42)] | ^ error: a diagnostic slug must be the first argument to the attribute - --> $DIR/subdiagnostic-derive.rs:795:48 + --> $DIR/subdiagnostic-derive.rs:796:48 | LL | #[suggestion(no_crate_example, code = "", style)] | ^ error: expected `= "xxx"` - --> $DIR/subdiagnostic-derive.rs:803:48 + --> $DIR/subdiagnostic-derive.rs:804:48 | LL | #[suggestion(no_crate_example, code = "", style("foo"))] | ^ error: expected `,` - --> $DIR/subdiagnostic-derive.rs:803:48 + --> $DIR/subdiagnostic-derive.rs:804:48 | LL | #[suggestion(no_crate_example, code = "", style("foo"))] | ^ error: `#[primary_span]` is not a valid attribute - --> $DIR/subdiagnostic-derive.rs:815:5 + --> $DIR/subdiagnostic-derive.rs:816:5 | LL | #[primary_span] | ^^^^^^^^^^^^^^^ @@ -529,7 +529,7 @@ LL | #[primary_span] = help: to create a suggestion with multiple spans, use `#[multipart_suggestion]` instead error: suggestion without `#[primary_span]` field - --> $DIR/subdiagnostic-derive.rs:812:1 + --> $DIR/subdiagnostic-derive.rs:813:1 | LL | / #[suggestion(no_crate_example, code = "")] LL | | @@ -541,67 +541,67 @@ LL | | } | |_^ error: cannot find attribute `foo` in this scope - --> $DIR/subdiagnostic-derive.rs:65:3 + --> $DIR/subdiagnostic-derive.rs:66:3 | LL | #[foo] | ^^^ error: cannot find attribute `foo` in this scope - --> $DIR/subdiagnostic-derive.rs:160:3 + --> $DIR/subdiagnostic-derive.rs:161:3 | LL | #[foo] | ^^^ error: cannot find attribute `bar` in this scope - --> $DIR/subdiagnostic-derive.rs:174:7 + --> $DIR/subdiagnostic-derive.rs:175:7 | LL | #[bar] | ^^^ error: cannot find attribute `bar` in this scope - --> $DIR/subdiagnostic-derive.rs:186:7 + --> $DIR/subdiagnostic-derive.rs:187:7 | LL | #[bar = "..."] | ^^^ error: cannot find attribute `bar` in this scope - --> $DIR/subdiagnostic-derive.rs:198:7 + --> $DIR/subdiagnostic-derive.rs:199:7 | LL | #[bar = 4] | ^^^ error: cannot find attribute `bar` in this scope - --> $DIR/subdiagnostic-derive.rs:210:7 + --> $DIR/subdiagnostic-derive.rs:211:7 | LL | #[bar("...")] | ^^^ error: cannot find attribute `bar` in this scope - --> $DIR/subdiagnostic-derive.rs:271:7 + --> $DIR/subdiagnostic-derive.rs:272:7 | LL | #[bar] | ^^^ error: cannot find attribute `bar` in this scope - --> $DIR/subdiagnostic-derive.rs:282:7 + --> $DIR/subdiagnostic-derive.rs:283:7 | LL | #[bar = "..."] | ^^^ error: cannot find attribute `bar` in this scope - --> $DIR/subdiagnostic-derive.rs:293:7 + --> $DIR/subdiagnostic-derive.rs:294:7 | LL | #[bar("...")] | ^^^ error[E0425]: cannot find value `slug` in module `crate::fluent_generated` - --> $DIR/subdiagnostic-derive.rs:123:9 + --> $DIR/subdiagnostic-derive.rs:124:9 | LL | #[label(slug)] | ^^^^ not found in `crate::fluent_generated` error[E0425]: cannot find value `__code_29` in this scope - --> $DIR/subdiagnostic-derive.rs:706:10 + --> $DIR/subdiagnostic-derive.rs:707:10 | LL | #[derive(Subdiagnostic)] | ^^^^^^^^^^^^^ not found in this scope diff --git a/tests/ui-fulldeps/lint-group-denied-lint-allowed.rs b/tests/ui/lint-group-denied-lint-allowed.rs similarity index 70% rename from tests/ui-fulldeps/lint-group-denied-lint-allowed.rs rename to tests/ui/lint-group-denied-lint-allowed.rs index 7498745f20699..8156b6ef617e6 100644 --- a/tests/ui-fulldeps/lint-group-denied-lint-allowed.rs +++ b/tests/ui/lint-group-denied-lint-allowed.rs @@ -1,4 +1,3 @@ -// aux-build:lint-group-plugin-test.rs // check-pass // compile-flags: -D unused -A unused-variables diff --git a/tests/ui-fulldeps/lint-group-forbid-always-trumps-cli.rs b/tests/ui/lint-group-forbid-always-trumps-cli.rs similarity index 72% rename from tests/ui-fulldeps/lint-group-forbid-always-trumps-cli.rs rename to tests/ui/lint-group-forbid-always-trumps-cli.rs index fc19bc039063a..77b792f98d5b1 100644 --- a/tests/ui-fulldeps/lint-group-forbid-always-trumps-cli.rs +++ b/tests/ui/lint-group-forbid-always-trumps-cli.rs @@ -1,4 +1,3 @@ -// aux-build:lint-group-plugin-test.rs // compile-flags: -F unused -A unused fn main() { diff --git a/tests/ui-fulldeps/lint-group-forbid-always-trumps-cli.stderr b/tests/ui/lint-group-forbid-always-trumps-cli.stderr similarity index 81% rename from tests/ui-fulldeps/lint-group-forbid-always-trumps-cli.stderr rename to tests/ui/lint-group-forbid-always-trumps-cli.stderr index 6bab367b0d175..8910af87ca222 100644 --- a/tests/ui-fulldeps/lint-group-forbid-always-trumps-cli.stderr +++ b/tests/ui/lint-group-forbid-always-trumps-cli.stderr @@ -1,5 +1,5 @@ error: unused variable: `x` - --> $DIR/lint-group-forbid-always-trumps-cli.rs:5:9 + --> $DIR/lint-group-forbid-always-trumps-cli.rs:4:9 | LL | let x = 1; | ^ help: if this is intentional, prefix it with an underscore: `_x` From 556062ea6e11be560b7e0c176b36566c991e595d Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 18 Apr 2023 03:06:15 +0000 Subject: [PATCH 097/228] Delay a good path bug for TypeErrCtxt --- compiler/rustc_infer/src/infer/error_reporting/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 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 992b07db1543d..fefc8a0f62bf1 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -74,7 +74,6 @@ use rustc_middle::ty::{ self, error::TypeError, List, Region, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, }; -use rustc_span::DUMMY_SP; use rustc_span::{sym, symbol::kw, BytePos, DesugaringKind, Pos, Span}; use rustc_target::spec::abi; use std::ops::{ControlFlow, Deref}; @@ -138,7 +137,7 @@ impl Drop for TypeErrCtxt<'_, '_> { self.infcx .tcx .sess - .delay_span_bug(DUMMY_SP, "used a `TypeErrCtxt` without failing compilation"); + .delay_good_path_bug("used a `TypeErrCtxt` without raising an error or lint"); } } } From ce5d897eb62f85db5b0821428323bb2e2673443c Mon Sep 17 00:00:00 2001 From: Albert Larsan <74931857+albertlarsan68@users.noreply.github.com> Date: Tue, 18 Apr 2023 07:00:51 +0000 Subject: [PATCH 098/228] Fix bootstrap locking Fix the regression introduced in 108607 --- src/bootstrap/bin/main.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/bootstrap/bin/main.rs b/src/bootstrap/bin/main.rs index 912d875e445ea..a80379e85c193 100644 --- a/src/bootstrap/bin/main.rs +++ b/src/bootstrap/bin/main.rs @@ -15,10 +15,12 @@ fn main() { let args = env::args().skip(1).collect::>(); let config = Config::parse(&args); + #[cfg(all(any(unix, windows), not(target_os = "solaris")))] + let mut build_lock; + #[cfg(all(any(unix, windows), not(target_os = "solaris")))] + let _build_lock_guard; #[cfg(all(any(unix, windows), not(target_os = "solaris")))] { - let mut build_lock; - let _build_lock_guard; let path = config.out.join("lock"); build_lock = fd_lock::RwLock::new(t!(std::fs::File::create(&path))); _build_lock_guard = match build_lock.try_write() { From ca882c015d93911a8cfc0782edc8a12ce584c58b Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 18 Apr 2023 11:47:29 +0200 Subject: [PATCH 099/228] Add a failing rustdoc-ui test for public infinite recursive type --- .../error-in-impl-trait/infinite-recursive-type-2.rs | 9 +++++++++ .../infinite-recursive-type-impl-trait-return.rs | 0 .../infinite-recursive-type-impl-trait-return.stderr | 0 .../infinite-recursive-type.rs} | 0 4 files changed, 9 insertions(+) create mode 100644 tests/rustdoc-ui/error-in-impl-trait/infinite-recursive-type-2.rs rename tests/rustdoc-ui/{ => error-in-impl-trait}/infinite-recursive-type-impl-trait-return.rs (100%) rename tests/rustdoc-ui/{ => error-in-impl-trait}/infinite-recursive-type-impl-trait-return.stderr (100%) rename tests/rustdoc-ui/{infinite-recursive-type-impl-trait.rs => error-in-impl-trait/infinite-recursive-type.rs} (100%) diff --git a/tests/rustdoc-ui/error-in-impl-trait/infinite-recursive-type-2.rs b/tests/rustdoc-ui/error-in-impl-trait/infinite-recursive-type-2.rs new file mode 100644 index 0000000000000..e49fe07981379 --- /dev/null +++ b/tests/rustdoc-ui/error-in-impl-trait/infinite-recursive-type-2.rs @@ -0,0 +1,9 @@ +// check-pass + +pub fn f() -> impl Sized { + pub enum E { + V(E), + } + + unimplemented!() +} diff --git a/tests/rustdoc-ui/infinite-recursive-type-impl-trait-return.rs b/tests/rustdoc-ui/error-in-impl-trait/infinite-recursive-type-impl-trait-return.rs similarity index 100% rename from tests/rustdoc-ui/infinite-recursive-type-impl-trait-return.rs rename to tests/rustdoc-ui/error-in-impl-trait/infinite-recursive-type-impl-trait-return.rs diff --git a/tests/rustdoc-ui/infinite-recursive-type-impl-trait-return.stderr b/tests/rustdoc-ui/error-in-impl-trait/infinite-recursive-type-impl-trait-return.stderr similarity index 100% rename from tests/rustdoc-ui/infinite-recursive-type-impl-trait-return.stderr rename to tests/rustdoc-ui/error-in-impl-trait/infinite-recursive-type-impl-trait-return.stderr diff --git a/tests/rustdoc-ui/infinite-recursive-type-impl-trait.rs b/tests/rustdoc-ui/error-in-impl-trait/infinite-recursive-type.rs similarity index 100% rename from tests/rustdoc-ui/infinite-recursive-type-impl-trait.rs rename to tests/rustdoc-ui/error-in-impl-trait/infinite-recursive-type.rs From 71f04bdb5aeaa3d4a013337afd95bb50db4ddd46 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Sun, 9 Apr 2023 17:59:24 -0500 Subject: [PATCH 100/228] Fix no_std tests that load libc when download-rustc is enabled There were a series of unfortunate interactions here. Here's an MCVE of the test this fixes (committed as `tests/ui/meta/no_std-extern-libc.rs`): ```rust #![crate_type = "lib"] #![no_std] #![feature(rustc_private)] extern crate libc; ``` Before, this would give an error about duplicate versions of libc: ``` error[E0464]: multiple candidates for `rlib` dependency `libc` found --> fake-test-src-base/allocator/no_std-alloc-error-handler-default.rs:15:1 | LL | extern crate libc; | ^^^^^^^^^^^^^^^^^^ | = note: candidate #1: /home/gh-jyn514/rust/build/aarch64-unknown-linux-gnu/stage2/lib/rustlib/aarch64-unknown-linux-gnu/lib/liblibc-358db1024b7d9957.rlib = note: candidate #2: /home/gh-jyn514/rust/build/aarch64-unknown-linux-gnu/stage2/lib/rustlib/aarch64-unknown-linux-gnu/lib/liblibc-ebc478710122a279.rmeta ``` Both these versions were downloaded from CI, but one came from the `rust-std` component and one came from `rustc-dev`: ``` ; tar -tf build/cache/f2d9a3d0771504f1ae776226a5799dcb4408a91a/rust-std-nightly-x86_64-unknown-linux-gnu.tar.xz | grep liblibc rust-std-nightly-x86_64-unknown-linux-gnu/rust-std-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/liblibc-68a2d9e195dd6ed2.rlib ; tar -tf build/cache/f2d9a3d0771504f1ae776226a5799dcb4408a91a/rustc-dev-nightly-x86_64-unknown-linux-gnu.tar.xz | grep liblibc rustc-dev-nightly-x86_64-unknown-linux-gnu/rustc-dev/lib/rustlib/x86_64-unknown-linux-gnu/lib/liblibc-f226c9fbdd92a0fd.rmeta ``` The fix was to only copy files from `rust-std` unless a Step explicitly requests for the `rustc-dev` components to be available by calling `builder.ensure(compile::Rustc)`. To avoid having to re-parse the `rustc-dev.tar.xz` tarball every time, which is quite slow, this adds a new `build/host/ci-rustc/.rustc-dev-contents` cache file which stores only the names of files we need to copy into the sysroot. This also allows reverting the hack in https://github.com/rust-lang/rust/pull/110121; now that we only copy rustc-dev on-demand, we can correctly add the `Rustc` check artifacts into the sysroot, so that this works correctly even when `download-rustc` is forced to `true`. --- See https://github.com/rust-lang/rust/issues/108767#issuecomment-1501217657 for why `no_std` is required for the MCVE test to fail; it's complicated and not particularly important. Fixes https://github.com/rust-lang/rust/issues/108767. --- src/bootstrap/check.rs | 14 ++------ src/bootstrap/compile.rs | 51 +++++++++++++++++++++++++++-- src/bootstrap/download.rs | 29 ++++++++++++++-- tests/ui/meta/no_std-extern-libc.rs | 7 ++++ 4 files changed, 84 insertions(+), 17 deletions(-) create mode 100644 tests/ui/meta/no_std-extern-libc.rs diff --git a/src/bootstrap/check.rs b/src/bootstrap/check.rs index fcaa698317df0..44efc502e39d4 100644 --- a/src/bootstrap/check.rs +++ b/src/bootstrap/check.rs @@ -271,17 +271,9 @@ impl Step for Rustc { false, ); - // HACK: This avoids putting the newly built artifacts in the sysroot if we're using - // `download-rustc`, to avoid "multiple candidates for `rmeta`" errors. Technically, that's - // not quite right: people can set `download-rustc = true` to download even if there are - // changes to the compiler, and in that case ideally we would put the *new* artifacts in the - // sysroot, in case there are API changes that should be used by tools. In practice, - // though, that should be very uncommon, and people can still disable download-rustc. - if !builder.download_rustc() { - let libdir = builder.sysroot_libdir(compiler, target); - let hostdir = builder.sysroot_libdir(compiler, compiler.host); - add_to_sysroot(&builder, &libdir, &hostdir, &librustc_stamp(builder, compiler, target)); - } + let libdir = builder.sysroot_libdir(compiler, target); + let hostdir = builder.sysroot_libdir(compiler, compiler.host); + add_to_sysroot(&builder, &libdir, &hostdir, &librustc_stamp(builder, compiler, target)); } } diff --git a/src/bootstrap/compile.rs b/src/bootstrap/compile.rs index 4a4e7adcbf388..d04eb1d1f679e 100644 --- a/src/bootstrap/compile.rs +++ b/src/bootstrap/compile.rs @@ -9,6 +9,7 @@ use std::borrow::Cow; use std::collections::HashSet; use std::env; +use std::ffi::OsStr; use std::fs; use std::io::prelude::*; use std::io::BufReader; @@ -652,8 +653,19 @@ impl Step for Rustc { // so its artifacts can't be reused. if builder.download_rustc() && compiler.stage != 0 { // Copy the existing artifacts instead of rebuilding them. - // NOTE: this path is only taken for tools linking to rustc-dev. - builder.ensure(Sysroot { compiler }); + // NOTE: this path is only taken for tools linking to rustc-dev (including ui-fulldeps tests). + let sysroot = builder.ensure(Sysroot { compiler }); + + let ci_rustc_dir = builder.out.join(&*builder.build.build.triple).join("ci-rustc"); + for file in builder.config.rustc_dev_contents() { + let src = ci_rustc_dir.join(&file); + let dst = sysroot.join(file); + if src.is_dir() { + t!(fs::create_dir_all(dst)); + } else { + builder.copy(&src, &dst); + } + } return; } @@ -1281,7 +1293,40 @@ impl Step for Sysroot { } // Copy the compiler into the correct sysroot. - builder.cp_r(&builder.ci_rustc_dir(builder.build.build), &sysroot); + // NOTE(#108767): We intentionally don't copy `rustc-dev` artifacts until they're requested with `builder.ensure(Rustc)`. + // This fixes an issue where we'd have multiple copies of libc in the sysroot with no way to tell which to load. + // There are a few quirks of bootstrap that interact to make this reliable: + // 1. The order `Step`s are run is hard-coded in `builder.rs` and not configurable. This + // avoids e.g. reordering `test::UiFulldeps` before `test::Ui` and causing the latter to + // fail because of duplicate metadata. + // 2. The sysroot is deleted and recreated between each invocation, so running `x test + // ui-fulldeps && x test ui` can't cause failures. + let mut filtered_files = Vec::new(); + // Don't trim directories or files that aren't loaded per-target; they can't cause conflicts. + let suffix = format!("lib/rustlib/{}/lib", compiler.host); + for path in builder.config.rustc_dev_contents() { + let path = Path::new(&path); + if path.parent().map_or(false, |parent| parent.ends_with(&suffix)) { + filtered_files.push(path.file_name().unwrap().to_owned()); + } + } + + let filtered_extensions = [OsStr::new("rmeta"), OsStr::new("rlib"), OsStr::new("so")]; + let ci_rustc_dir = builder.ci_rustc_dir(builder.config.build); + builder.cp_filtered(&ci_rustc_dir, &sysroot, &|path| { + if path.extension().map_or(true, |ext| !filtered_extensions.contains(&ext)) { + return true; + } + if !path.parent().map_or(true, |p| p.ends_with(&suffix)) { + return true; + } + if !filtered_files.iter().all(|f| f != path.file_name().unwrap()) { + builder.verbose_than(1, &format!("ignoring {}", path.display())); + false + } else { + true + } + }); return INTERNER.intern_path(sysroot); } diff --git a/src/bootstrap/download.rs b/src/bootstrap/download.rs index 2425155658429..133cda639d976 100644 --- a/src/bootstrap/download.rs +++ b/src/bootstrap/download.rs @@ -2,7 +2,7 @@ use std::{ env, ffi::{OsStr, OsString}, fs::{self, File}, - io::{BufRead, BufReader, ErrorKind}, + io::{BufRead, BufReader, BufWriter, ErrorKind, Write}, path::{Path, PathBuf}, process::{Command, Stdio}, }; @@ -262,10 +262,20 @@ impl Config { let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap()); // decompress the file - let data = t!(File::open(tarball)); + let data = t!(File::open(tarball), format!("file {} not found", tarball.display())); let decompressor = XzDecoder::new(BufReader::new(data)); let mut tar = tar::Archive::new(decompressor); + + // `compile::Sysroot` needs to know the contents of the `rustc-dev` tarball to avoid adding + // it to the sysroot unless it was explicitly requested. But parsing the 100 MB tarball is slow. + // Cache the entries when we extract it so we only have to read it once. + let mut recorded_entries = if dst.ends_with("ci-rustc") && pattern == "rustc-dev" { + Some(BufWriter::new(t!(File::create(dst.join(".rustc-dev-contents"))))) + } else { + None + }; + for member in t!(tar.entries()) { let mut member = t!(member); let original_path = t!(member.path()).into_owned(); @@ -283,13 +293,19 @@ impl Config { if !t!(member.unpack_in(dst)) { panic!("path traversal attack ??"); } + if let Some(record) = &mut recorded_entries { + t!(writeln!(record, "{}", short_path.to_str().unwrap())); + } let src_path = dst.join(original_path); if src_path.is_dir() && dst_path.exists() { continue; } t!(fs::rename(src_path, dst_path)); } - t!(fs::remove_dir_all(dst.join(directory_prefix))); + let dst_dir = dst.join(directory_prefix); + if dst_dir.exists() { + t!(fs::remove_dir_all(&dst_dir), format!("failed to remove {}", dst_dir.display())); + } } /// Returns whether the SHA256 checksum of `path` matches `expected`. @@ -365,6 +381,13 @@ impl Config { Some(rustfmt_path) } + pub(crate) fn rustc_dev_contents(&self) -> Vec { + assert!(self.download_rustc()); + let ci_rustc_dir = self.out.join(&*self.build.triple).join("ci-rustc"); + let rustc_dev_contents_file = t!(File::open(ci_rustc_dir.join(".rustc-dev-contents"))); + t!(BufReader::new(rustc_dev_contents_file).lines().collect()) + } + pub(crate) fn download_ci_rustc(&self, commit: &str) { self.verbose(&format!("using downloaded stage2 artifacts from CI (commit {commit})")); diff --git a/tests/ui/meta/no_std-extern-libc.rs b/tests/ui/meta/no_std-extern-libc.rs new file mode 100644 index 0000000000000..763ea740a2740 --- /dev/null +++ b/tests/ui/meta/no_std-extern-libc.rs @@ -0,0 +1,7 @@ +// Test that `download-rustc` doesn't put duplicate copies of libc in the sysroot. +// check-pass +#![crate_type = "lib"] +#![no_std] +#![feature(rustc_private)] + +extern crate libc; From 678792568b2f92c6787547dbb006f1a7a1e9613e Mon Sep 17 00:00:00 2001 From: jyn Date: Tue, 18 Apr 2023 07:29:04 -0500 Subject: [PATCH 101/228] Bump `download-ci-llvm-stamp` for loong support This was missed in https://github.com/rust-lang/rust/pull/96971 and resulted in the LLVM we cache in CI being different from the one built locally. We didn't catch it because nothing tested the loong support. --- src/bootstrap/download-ci-llvm-stamp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/download-ci-llvm-stamp b/src/bootstrap/download-ci-llvm-stamp index 36f9aaa595d0f..4111b7cc0d3f9 100644 --- a/src/bootstrap/download-ci-llvm-stamp +++ b/src/bootstrap/download-ci-llvm-stamp @@ -1,4 +1,4 @@ Change this file to make users of the `download-ci-llvm` configuration download a new version of LLVM from CI, even if the LLVM submodule hasn’t changed. -Last change is for: https://github.com/rust-lang/rust/pull/109373 +Last change is for: https://github.com/rust-lang/rust/pull/96971 From bd1dfcebe3ae34c4c7fb2ac0660707090a0cbe3a Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Mon, 17 Apr 2023 13:37:03 +0000 Subject: [PATCH 102/228] Don't allocate it `IndexVec::remove` --- compiler/rustc_index/src/vec.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_index/src/vec.rs b/compiler/rustc_index/src/vec.rs index 95600f7bcf16f..18e779f786e14 100644 --- a/compiler/rustc_index/src/vec.rs +++ b/compiler/rustc_index/src/vec.rs @@ -460,7 +460,7 @@ impl IndexVec> { #[inline] pub fn remove(&mut self, index: I) -> Option { - self.ensure_contains_elem(index, || None).take() + self.get_mut(index)?.take() } } From ec8f68859a7484d05b42a28ab1b0ece9b2dde629 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 30 Mar 2023 17:25:52 +0400 Subject: [PATCH 103/228] rustc_metadata: Remove `Span` from `ModChild` It can be decoded on demand from regular `def_span` tables. Partially mitigates perf regressions from #109500. --- compiler/rustc_metadata/src/rmeta/decoder.rs | 3 +-- compiler/rustc_metadata/src/rmeta/encoder.rs | 6 +++--- compiler/rustc_middle/src/metadata.rs | 3 --- compiler/rustc_resolve/src/build_reduced_graph.rs | 8 +++++++- compiler/rustc_resolve/src/imports.rs | 8 +------- 5 files changed, 12 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index 2930ce75028b7..af4e9f27c9878 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -998,9 +998,8 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { let ident = self.item_ident(id, sess); let res = Res::Def(self.def_kind(id), self.local_def_id(id)); let vis = self.get_visibility(id); - let span = self.get_span(id, sess); - ModChild { ident, res, vis, span, reexport_chain: Default::default() } + ModChild { ident, res, vis, reexport_chain: Default::default() } } /// Iterates over all named children of the given module, diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index e7c3cf779d3d0..58773f1fb27db 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -831,6 +831,8 @@ fn should_encode_span(def_kind: DefKind) -> bool { | DefKind::AssocFn | DefKind::AssocConst | DefKind::Macro(_) + | DefKind::ExternCrate + | DefKind::Use | DefKind::AnonConst | DefKind::InlineConst | DefKind::OpaqueTy @@ -838,9 +840,7 @@ fn should_encode_span(def_kind: DefKind) -> bool { | DefKind::Impl { .. } | DefKind::Closure | DefKind::Generator => true, - DefKind::ExternCrate - | DefKind::Use - | DefKind::ForeignMod + DefKind::ForeignMod | DefKind::ImplTraitPlaceholder | DefKind::LifetimeParam | DefKind::GlobalAsm => false, diff --git a/compiler/rustc_middle/src/metadata.rs b/compiler/rustc_middle/src/metadata.rs index f3170e0ec0e1c..674402cb4bf9b 100644 --- a/compiler/rustc_middle/src/metadata.rs +++ b/compiler/rustc_middle/src/metadata.rs @@ -4,7 +4,6 @@ use rustc_hir::def::Res; use rustc_macros::HashStable; use rustc_span::def_id::DefId; use rustc_span::symbol::Ident; -use rustc_span::Span; use smallvec::SmallVec; /// A simplified version of `ImportKind` from resolve. @@ -41,8 +40,6 @@ pub struct ModChild { pub res: Res, /// Visibility of the item. pub vis: ty::Visibility, - /// Span of the item. - pub span: Span, /// Reexport chain linking this module child to its original reexported item. /// Empty if the module child is a proper item. pub reexport_chain: SmallVec<[Reexport; 2]>, diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index ff0f1f55975f3..f905cec101106 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -931,7 +931,13 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> { /// Builds the reduced graph for a single item in an external crate. fn build_reduced_graph_for_external_crate_res(&mut self, child: ModChild) { let parent = self.parent_scope.module; - let ModChild { ident, res, vis, span, .. } = child; + let ModChild { ident, res, vis, reexport_chain } = child; + let span = self.r.def_span( + reexport_chain + .first() + .and_then(|reexport| reexport.id()) + .unwrap_or_else(|| res.def_id()), + ); let res = res.expect_non_local(); let expansion = self.parent_scope.expansion; // Record primary definitions. diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index 3c22d51c3d478..d7c518fbdd0dc 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -1276,13 +1276,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { next_binding = binding; } - reexports.push(ModChild { - ident, - res, - vis: binding.vis, - span: binding.span, - reexport_chain, - }); + reexports.push(ModChild { ident, res, vis: binding.vis, reexport_chain }); } }); From 0445fbdd835c92156e4d06e42ce99a39e9315343 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Fri, 7 Apr 2023 23:11:20 -0400 Subject: [PATCH 104/228] Store hashes in special types so they aren't accidentally encoded as numbers --- compiler/rustc_abi/src/layout.rs | 3 +- compiler/rustc_abi/src/lib.rs | 7 +- compiler/rustc_codegen_llvm/src/common.rs | 4 +- .../rustc_codegen_llvm/src/debuginfo/mod.rs | 3 +- .../src/debuginfo/type_names.rs | 5 +- .../src/interpret/intrinsics.rs | 2 +- .../rustc_data_structures/src/fingerprint.rs | 43 +++++-- .../src/fingerprint/tests.rs | 7 +- compiler/rustc_data_structures/src/hashes.rs | 120 ++++++++++++++++++ compiler/rustc_data_structures/src/lib.rs | 1 + .../src/stable_hasher.rs | 27 ++-- .../src/stable_hasher/tests.rs | 2 +- compiler/rustc_data_structures/src/svh.rs | 2 +- compiler/rustc_errors/src/lib.rs | 4 +- compiler/rustc_hir/src/definitions.rs | 6 +- compiler/rustc_hir/src/tests.rs | 3 +- compiler/rustc_incremental/src/persist/fs.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 4 +- .../rustc_middle/src/dep_graph/dep_node.rs | 5 +- .../src/middle/exported_symbols.rs | 2 +- compiler/rustc_middle/src/mir/mono.rs | 19 +-- compiler/rustc_middle/src/ty/consts/int.rs | 10 +- compiler/rustc_middle/src/ty/context.rs | 2 +- compiler/rustc_middle/src/ty/util.rs | 4 +- .../rustc_mir_transform/src/coverage/mod.rs | 7 +- .../rustc_query_impl/src/on_disk_cache.rs | 5 +- compiler/rustc_query_impl/src/plumbing.rs | 4 +- compiler/rustc_query_system/src/query/mod.rs | 5 +- .../rustc_query_system/src/query/plumbing.rs | 2 +- compiler/rustc_session/src/session.rs | 2 +- compiler/rustc_span/src/def_id.rs | 38 +++--- compiler/rustc_span/src/hygiene.rs | 14 +- compiler/rustc_span/src/lib.rs | 22 ++-- compiler/rustc_span/src/source_map.rs | 6 +- compiler/rustc_span/src/tests.rs | 8 +- compiler/rustc_symbol_mangling/src/legacy.rs | 8 +- .../src/typeid/typeid_itanium_cxx_abi.rs | 2 +- compiler/rustc_symbol_mangling/src/v0.rs | 2 +- 38 files changed, 274 insertions(+), 138 deletions(-) create mode 100644 compiler/rustc_data_structures/src/hashes.rs diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index 2b01aca2ee482..f3af031ade4a1 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -79,7 +79,8 @@ pub trait LayoutCalculator { { // `ReprOptions.layout_seed` is a deterministic seed that we can use to // randomize field ordering with - let mut rng = Xoshiro128StarStar::seed_from_u64(repr.field_shuffle_seed); + let mut rng = + Xoshiro128StarStar::seed_from_u64(repr.field_shuffle_seed.as_u64()); // Shuffle the ordering of the fields optimizing.shuffle(&mut rng); diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 402ea6ff48ffd..a5cdaa547d842 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -9,6 +9,7 @@ use std::str::FromStr; use bitflags::bitflags; use rustc_data_structures::intern::Interned; +use rustc_data_structures::stable_hasher::Hash64; #[cfg(feature = "nightly")] use rustc_data_structures::stable_hasher::StableOrd; use rustc_index::vec::{IndexSlice, IndexVec}; @@ -77,12 +78,12 @@ pub struct ReprOptions { pub flags: ReprFlags, /// The seed to be used for randomizing a type's layout /// - /// Note: This could technically be a `[u8; 16]` (a `u128`) which would + /// Note: This could technically be a `Hash128` which would /// be the "most accurate" hash as it'd encompass the item and crate /// hash without loss, but it does pay the price of being larger. - /// Everything's a tradeoff, a `u64` seed should be sufficient for our + /// Everything's a tradeoff, a 64-bit seed should be sufficient for our /// purposes (primarily `-Z randomize-layout`) - pub field_shuffle_seed: u64, + pub field_shuffle_seed: Hash64, } impl ReprOptions { diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index 4f8b5abd9010c..9127fba388bab 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -10,7 +10,7 @@ use crate::value::Value; use rustc_ast::Mutability; use rustc_codegen_ssa::mir::place::PlaceRef; use rustc_codegen_ssa::traits::*; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher}; use rustc_hir::def_id::DefId; use rustc_middle::bug; use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, Scalar}; @@ -261,7 +261,7 @@ impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> { let hash = self.tcx.with_stable_hashing_context(|mut hcx| { let mut hasher = StableHasher::new(); alloc.hash_stable(&mut hcx, &mut hasher); - hasher.finish::() + hasher.finish::() }); llvm::set_value_name(value, format!("alloc_{hash:032x}").as_bytes()); } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index d56c414cf651e..56844c7951fa5 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -21,6 +21,7 @@ use rustc_codegen_ssa::debuginfo::type_names; use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext, VariableKind}; use rustc_codegen_ssa::traits::*; use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::stable_hasher::Hash128; use rustc_data_structures::sync::Lrc; use rustc_hir::def_id::{DefId, DefIdMap}; use rustc_index::vec::IndexVec; @@ -61,7 +62,7 @@ pub struct CodegenUnitDebugContext<'ll, 'tcx> { llcontext: &'ll llvm::Context, llmod: &'ll llvm::Module, builder: &'ll mut DIBuilder<'ll>, - created_files: RefCell, &'ll DIFile>>, + created_files: RefCell, &'ll DIFile>>, type_map: metadata::TypeMap<'ll, 'tcx>, namespace_map: RefCell>, diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index f2469fde3b657..03f33d8d8aa7f 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -12,7 +12,7 @@ // * `"` is treated as the start of a string. use rustc_data_structures::fx::FxHashSet; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher}; use rustc_hir::def_id::DefId; use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData}; use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Mutability}; @@ -675,8 +675,7 @@ fn push_const_param<'tcx>(tcx: TyCtxt<'tcx>, ct: ty::Const<'tcx>, output: &mut S hcx.while_hashing_spans(false, |hcx| { ct.to_valtree().hash_stable(hcx, &mut hasher) }); - let hash: u64 = hasher.finish(); - hash + hasher.finish::() }); if cpp_like_debuginfo(tcx) { diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 26fb041b45513..eada75ae391cb 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -75,7 +75,7 @@ pub(crate) fn eval_nullary_intrinsic<'tcx>( } sym::type_id => { ensure_monomorphic_enough(tcx, tp_ty)?; - ConstValue::from_u64(tcx.type_id_hash(tp_ty)) + ConstValue::from_u64(tcx.type_id_hash(tp_ty).as_u64()) } sym::variant_count => match tp_ty.kind() { // Correctly handles non-monomorphic calls, so there is no need for ensure_monomorphic_enough. diff --git a/compiler/rustc_data_structures/src/fingerprint.rs b/compiler/rustc_data_structures/src/fingerprint.rs index b6e866f15efe3..1c929afb1cf36 100644 --- a/compiler/rustc_data_structures/src/fingerprint.rs +++ b/compiler/rustc_data_structures/src/fingerprint.rs @@ -1,4 +1,4 @@ -use crate::stable_hasher; +use crate::stable_hasher::{Hash64, StableHasher, StableHasherResult}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use std::hash::{Hash, Hasher}; @@ -9,32 +9,47 @@ mod tests; #[repr(C)] pub struct Fingerprint(u64, u64); -impl Fingerprint { - pub const ZERO: Fingerprint = Fingerprint(0, 0); +pub trait FingerprintComponent { + fn as_u64(&self) -> u64; +} - #[inline] - pub fn new(_0: u64, _1: u64) -> Fingerprint { - Fingerprint(_0, _1) +impl FingerprintComponent for Hash64 { + fn as_u64(&self) -> u64 { + Hash64::as_u64(*self) + } +} + +impl FingerprintComponent for u64 { + fn as_u64(&self) -> u64 { + *self } +} + +impl Fingerprint { + pub const ZERO: Fingerprint = Fingerprint(0, 0); #[inline] - pub fn from_smaller_hash(hash: u64) -> Fingerprint { - Fingerprint(hash, hash) + pub fn new(_0: A, _1: B) -> Fingerprint + where + A: FingerprintComponent, + B: FingerprintComponent, + { + Fingerprint(_0.as_u64(), _1.as_u64()) } #[inline] - pub fn to_smaller_hash(&self) -> u64 { + pub fn to_smaller_hash(&self) -> Hash64 { // Even though both halves of the fingerprint are expected to be good // quality hash values, let's still combine the two values because the // Fingerprints in DefPathHash have the StableCrateId portion which is // the same for all DefPathHashes from the same crate. Combining the // two halves makes sure we get a good quality hash in such cases too. - self.0.wrapping_mul(3).wrapping_add(self.1) + Hash64::new(self.0.wrapping_mul(3).wrapping_add(self.1)) } #[inline] - pub fn as_value(&self) -> (u64, u64) { - (self.0, self.1) + pub fn split(&self) -> (Hash64, Hash64) { + (Hash64::new(self.0), Hash64::new(self.1)) } #[inline] @@ -131,9 +146,9 @@ impl FingerprintHasher for crate::unhash::Unhasher { } } -impl stable_hasher::StableHasherResult for Fingerprint { +impl StableHasherResult for Fingerprint { #[inline] - fn finish(hasher: stable_hasher::StableHasher) -> Self { + fn finish(hasher: StableHasher) -> Self { let (_0, _1) = hasher.finalize(); Fingerprint(_0, _1) } diff --git a/compiler/rustc_data_structures/src/fingerprint/tests.rs b/compiler/rustc_data_structures/src/fingerprint/tests.rs index 9b0783e33ab47..09ec2622a651d 100644 --- a/compiler/rustc_data_structures/src/fingerprint/tests.rs +++ b/compiler/rustc_data_structures/src/fingerprint/tests.rs @@ -1,11 +1,12 @@ use super::*; +use crate::stable_hasher::Hash64; // Check that `combine_commutative` is order independent. #[test] fn combine_commutative_is_order_independent() { - let a = Fingerprint::new(0xf6622fb349898b06, 0x70be9377b2f9c610); - let b = Fingerprint::new(0xa9562bf5a2a5303c, 0x67d9b6c82034f13d); - let c = Fingerprint::new(0x0d013a27811dbbc3, 0x9a3f7b3d9142ec43); + let a = Fingerprint::new(Hash64::new(0xf6622fb349898b06), Hash64::new(0x70be9377b2f9c610)); + let b = Fingerprint::new(Hash64::new(0xa9562bf5a2a5303c), Hash64::new(0x67d9b6c82034f13d)); + let c = Fingerprint::new(Hash64::new(0x0d013a27811dbbc3), Hash64::new(0x9a3f7b3d9142ec43)); let permutations = [(a, b, c), (a, c, b), (b, a, c), (b, c, a), (c, a, b), (c, b, a)]; let f = a.combine_commutative(b).combine_commutative(c); for p in &permutations { diff --git a/compiler/rustc_data_structures/src/hashes.rs b/compiler/rustc_data_structures/src/hashes.rs new file mode 100644 index 0000000000000..9f6e0fb76765b --- /dev/null +++ b/compiler/rustc_data_structures/src/hashes.rs @@ -0,0 +1,120 @@ +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; +use std::fmt; +use std::ops::BitXorAssign; +use crate::stable_hasher::{StableHasher, StableHasherResult}; + +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] +pub struct Hash64 { + inner: u64, +} + +impl Hash64 { + pub const ZERO: Hash64 = Hash64 { inner: 0 }; + + #[inline] + pub(crate) fn new(n: u64) -> Self { + Self { inner: n } + } + + #[inline] + pub fn as_u64(self) -> u64 { + self.inner + } +} + +impl BitXorAssign for Hash64 { + fn bitxor_assign(&mut self, rhs: u64) { + self.inner ^= rhs; + } +} + +impl Encodable for Hash64 { + #[inline] + fn encode(&self, s: &mut S) { + s.emit_raw_bytes(&self.inner.to_le_bytes()); + } +} + +impl Decodable for Hash64 { + #[inline] + fn decode(d: &mut D) -> Self { + Self { inner: u64::from_le_bytes(d.read_raw_bytes(8).try_into().unwrap()) } + } +} + +impl StableHasherResult for Hash64 { + #[inline] + fn finish(hasher: StableHasher) -> Self { + Self { inner: hasher.finalize().0 } + } +} + +impl fmt::Debug for Hash64 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.inner.fmt(f) + } +} + +impl fmt::LowerHex for Hash64 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::LowerHex::fmt(&self.inner, f) + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] +pub struct Hash128 { + inner: u128, +} + +impl Hash128 { + #[inline] + pub fn truncate(self) -> Hash64 { + Hash64 { inner: self.inner as u64 } + } + + #[inline] + pub fn wrapping_add(self, other: Self) -> Self { + Self { + inner: self.inner.wrapping_add(other.inner), + } + } + + #[inline] + pub fn as_u128(self) -> u128 { + self.inner + } +} + +impl Encodable for Hash128 { + #[inline] + fn encode(&self, s: &mut S) { + s.emit_raw_bytes(&self.inner.to_le_bytes()); + } +} + +impl Decodable for Hash128 { + #[inline] + fn decode(d: &mut D) -> Self { + Self { inner: u128::from_le_bytes(d.read_raw_bytes(16).try_into().unwrap()) } + } +} + +impl StableHasherResult for Hash128 { + #[inline] + fn finish(hasher: StableHasher) -> Self { + let (_0, _1) = hasher.finalize(); + Self { inner: u128::from(_0) | (u128::from(_1) << 64) } + } +} + +impl fmt::Debug for Hash128 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.inner.fmt(f) + } +} + +impl fmt::LowerHex for Hash128 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::LowerHex::fmt(&self.inner, f) + } +} diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index 7768e0fdeb13b..405ae99395b31 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -86,6 +86,7 @@ pub mod work_queue; pub use atomic_ref::AtomicRef; pub mod aligned; pub mod frozen; +mod hashes; pub mod owned_slice; pub mod sso; pub mod steal; diff --git a/compiler/rustc_data_structures/src/stable_hasher.rs b/compiler/rustc_data_structures/src/stable_hasher.rs index 1608009809f4c..b2bd0bfe71473 100644 --- a/compiler/rustc_data_structures/src/stable_hasher.rs +++ b/compiler/rustc_data_structures/src/stable_hasher.rs @@ -2,6 +2,7 @@ use crate::sip128::SipHasher128; use rustc_index::bit_set; use rustc_index::vec; use smallvec::SmallVec; +use std::fmt; use std::hash::{BuildHasher, Hash, Hasher}; use std::marker::PhantomData; use std::mem; @@ -9,6 +10,8 @@ use std::mem; #[cfg(test)] mod tests; +pub use crate::hashes::{Hash128, Hash64}; + /// When hashing something that ends up affecting properties like symbol names, /// we want these symbol names to be calculated independently of other factors /// like what architecture you're compiling *from*. @@ -20,8 +23,8 @@ pub struct StableHasher { state: SipHasher128, } -impl ::std::fmt::Debug for StableHasher { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Debug for StableHasher { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self.state) } } @@ -42,21 +45,6 @@ impl StableHasher { } } -impl StableHasherResult for u128 { - #[inline] - fn finish(hasher: StableHasher) -> Self { - let (_0, _1) = hasher.finalize(); - u128::from(_0) | (u128::from(_1) << 64) - } -} - -impl StableHasherResult for u64 { - #[inline] - fn finish(hasher: StableHasher) -> Self { - hasher.finalize().0 - } -} - impl StableHasher { #[inline] pub fn finalize(self) -> (u64, u64) { @@ -287,6 +275,9 @@ impl_stable_traits_for_trivial_type!(i128); impl_stable_traits_for_trivial_type!(char); impl_stable_traits_for_trivial_type!(()); +impl_stable_traits_for_trivial_type!(Hash64); +impl_stable_traits_for_trivial_type!(Hash128); + impl HashStable for ! { fn hash_stable(&self, _ctx: &mut CTX, _hasher: &mut StableHasher) { unreachable!() @@ -669,7 +660,7 @@ fn stable_hash_reduce( .map(|value| { let mut hasher = StableHasher::new(); hash_function(&mut hasher, hcx, value); - hasher.finish::() + hasher.finish::() }) .reduce(|accum, value| accum.wrapping_add(value)); hash.hash_stable(hcx, hasher); diff --git a/compiler/rustc_data_structures/src/stable_hasher/tests.rs b/compiler/rustc_data_structures/src/stable_hasher/tests.rs index a98b1bc36261c..c8921f6a7784f 100644 --- a/compiler/rustc_data_structures/src/stable_hasher/tests.rs +++ b/compiler/rustc_data_structures/src/stable_hasher/tests.rs @@ -72,7 +72,7 @@ fn test_hash_isize() { assert_eq!(h.finalize(), expected); } -fn hash>(t: &T) -> u128 { +fn hash>(t: &T) -> Hash128 { let mut h = StableHasher::new(); let ctx = &mut (); t.hash_stable(ctx, &mut h); diff --git a/compiler/rustc_data_structures/src/svh.rs b/compiler/rustc_data_structures/src/svh.rs index b955df94f1633..a3d2724fcdbbb 100644 --- a/compiler/rustc_data_structures/src/svh.rs +++ b/compiler/rustc_data_structures/src/svh.rs @@ -24,7 +24,7 @@ impl Svh { } pub fn as_u64(&self) -> u64 { - self.hash.to_smaller_hash() + self.hash.to_smaller_hash().as_u64() } pub fn to_string(&self) -> String { diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index d20b168904d6f..26791304ef11e 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -31,7 +31,7 @@ use Level::*; use emitter::{is_case_difference, Emitter, EmitterWriter}; use registry::Registry; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; -use rustc_data_structures::stable_hasher::StableHasher; +use rustc_data_structures::stable_hasher::{Hash128, StableHasher}; use rustc_data_structures::sync::{self, Lock, Lrc}; use rustc_data_structures::AtomicRef; pub use rustc_error_messages::{ @@ -427,7 +427,7 @@ struct HandlerInner { /// This set contains a hash of every diagnostic that has been emitted by /// this handler. These hashes is used to avoid emitting the same error /// twice. - emitted_diagnostics: FxHashSet, + emitted_diagnostics: FxHashSet, /// Stashed diagnostics emitted in one stage of the compiler that may be /// stolen by other stages (e.g. to improve them and add more information). diff --git a/compiler/rustc_hir/src/definitions.rs b/compiler/rustc_hir/src/definitions.rs index 8ceb176491b6f..5a5a1e44f12b2 100644 --- a/compiler/rustc_hir/src/definitions.rs +++ b/compiler/rustc_hir/src/definitions.rs @@ -9,7 +9,7 @@ use crate::def_id::{CrateNum, DefIndex, LocalDefId, StableCrateId, CRATE_DEF_IND use crate::def_path_hash_map::DefPathHashMap; use rustc_data_structures::fx::FxHashMap; -use rustc_data_structures::stable_hasher::StableHasher; +use rustc_data_structures::stable_hasher::{Hash64, StableHasher}; use rustc_index::vec::IndexVec; use rustc_span::symbol::{kw, sym, Symbol}; @@ -130,7 +130,7 @@ impl DefKey { disambiguator.hash(&mut hasher); - let local_hash: u64 = hasher.finish(); + let local_hash = hasher.finish(); // Construct the new DefPathHash, making sure that the `crate_id` // portion of the hash is properly copied from the parent. This way the @@ -325,7 +325,7 @@ impl Definitions { }, }; - let parent_hash = DefPathHash::new(stable_crate_id, 0); + let parent_hash = DefPathHash::new(stable_crate_id, Hash64::ZERO); let def_path_hash = key.compute_stable_hash(parent_hash); // Create the root definition. diff --git a/compiler/rustc_hir/src/tests.rs b/compiler/rustc_hir/src/tests.rs index d4791150947fb..c7ac01b333427 100644 --- a/compiler/rustc_hir/src/tests.rs +++ b/compiler/rustc_hir/src/tests.rs @@ -1,4 +1,5 @@ use crate::definitions::{DefKey, DefPathData, DisambiguatedDefPathData}; +use rustc_data_structures::stable_hasher::Hash64; use rustc_span::def_id::{DefPathHash, StableCrateId}; use rustc_span::edition::Edition; use rustc_span::{create_session_if_not_set_then, Symbol}; @@ -24,7 +25,7 @@ fn def_path_hash_depends_on_crate_id() { assert_ne!(h0.local_hash(), h1.local_hash()); fn mk_test_hash(stable_crate_id: StableCrateId) -> DefPathHash { - let parent_hash = DefPathHash::new(stable_crate_id, 0); + let parent_hash = DefPathHash::new(stable_crate_id, Hash64::ZERO); let key = DefKey { parent: None, diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index d6f83838a0417..ec6d61f9e5f82 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -601,7 +601,7 @@ fn string_to_timestamp(s: &str) -> Result { fn crate_path(sess: &Session, crate_name: Symbol, stable_crate_id: StableCrateId) -> PathBuf { let incr_dir = sess.opts.incremental.as_ref().unwrap().clone(); - let stable_crate_id = base_n::encode(stable_crate_id.to_u64() as u128, INT_ENCODE_BASE); + let stable_crate_id = base_n::encode(stable_crate_id.as_u64() as u128, INT_ENCODE_BASE); let crate_name = format!("{}-{}", crate_name, stable_crate_id); incr_dir.join(crate_name) diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index e7c3cf779d3d0..264d08ac4dcfb 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -7,7 +7,7 @@ use rustc_ast::Attribute; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; use rustc_data_structures::memmap::{Mmap, MmapMut}; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher}; use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator}; use rustc_data_structures::temp_dir::MaybeTempDir; use rustc_hir as hir; @@ -531,7 +531,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { adapted.name_hash = { let mut hasher: StableHasher = StableHasher::new(); adapted.name.hash(&mut hasher); - hasher.finish::() + hasher.finish::() }; Lrc::new(adapted) } else { diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 865bb70afb506..82e396a9dd3f9 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -357,7 +357,7 @@ impl<'tcx> DepNodeParams> for HirId { Fingerprint::new( // `owner` is local, so is completely defined by the local hash def_path_hash.local_hash(), - local_id.as_u32().into(), + local_id.as_u32() as u64, ) } @@ -370,7 +370,7 @@ impl<'tcx> DepNodeParams> for HirId { #[inline(always)] fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { if tcx.fingerprint_style(dep_node.kind) == FingerprintStyle::HirId { - let (local_hash, local_id) = Fingerprint::from(dep_node.hash).as_value(); + let (local_hash, local_id) = Fingerprint::from(dep_node.hash).split(); let def_path_hash = DefPathHash::new(tcx.sess.local_stable_crate_id(), local_hash); let def_id = tcx .def_path_hash_to_def_id(def_path_hash, &mut || { @@ -378,6 +378,7 @@ impl<'tcx> DepNodeParams> for HirId { }) .expect_local(); let local_id = local_id + .as_u64() .try_into() .unwrap_or_else(|_| panic!("local id should be u32, found {:?}", local_id)); Some(HirId { owner: OwnerId { def_id }, local_id: ItemLocalId::from_u32(local_id) }) diff --git a/compiler/rustc_middle/src/middle/exported_symbols.rs b/compiler/rustc_middle/src/middle/exported_symbols.rs index c0c0fd07b6e06..9041da9a0604d 100644 --- a/compiler/rustc_middle/src/middle/exported_symbols.rs +++ b/compiler/rustc_middle/src/middle/exported_symbols.rs @@ -72,6 +72,6 @@ pub fn metadata_symbol_name(tcx: TyCtxt<'_>) -> String { format!( "rust_metadata_{}_{:08x}", tcx.crate_name(LOCAL_CRATE), - tcx.sess.local_stable_crate_id().to_u64(), + tcx.sess.local_stable_crate_id(), ) } diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index f592f1515c110..a9468a90b5374 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -4,7 +4,7 @@ use rustc_attr::InlineAttr; use rustc_data_structures::base_n; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher}; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc_hir::ItemId; use rustc_index::vec::Idx; @@ -313,8 +313,8 @@ impl<'tcx> CodegenUnit<'tcx> { // avoid collisions and is still reasonably short for filenames. let mut hasher = StableHasher::new(); human_readable_name.hash(&mut hasher); - let hash: u128 = hasher.finish(); - let hash = hash & ((1u128 << 80) - 1); + let hash: Hash128 = hasher.finish(); + let hash = hash.as_u128() & ((1u128 << 80) - 1); base_n::encode(hash, base_n::CASE_INSENSITIVE) } @@ -505,22 +505,13 @@ impl<'tcx> CodegenUnitNameBuilder<'tcx> { // instantiating stuff for upstream crates. let local_crate_id = if cnum != LOCAL_CRATE { let local_stable_crate_id = tcx.sess.local_stable_crate_id(); - format!( - "-in-{}.{:08x}", - tcx.crate_name(LOCAL_CRATE), - local_stable_crate_id.to_u64() as u32, - ) + format!("-in-{}.{:08x}", tcx.crate_name(LOCAL_CRATE), local_stable_crate_id) } else { String::new() }; let stable_crate_id = tcx.sess.local_stable_crate_id(); - format!( - "{}.{:08x}{}", - tcx.crate_name(cnum), - stable_crate_id.to_u64() as u32, - local_crate_id, - ) + format!("{}.{:08x}{}", tcx.crate_name(cnum), stable_crate_id, local_crate_id) }); write!(cgu_name, "{}", crate_prefix).unwrap(); diff --git a/compiler/rustc_middle/src/ty/consts/int.rs b/compiler/rustc_middle/src/ty/consts/int.rs index c0e557d480d3d..d1dbc531edfc1 100644 --- a/compiler/rustc_middle/src/ty/consts/int.rs +++ b/compiler/rustc_middle/src/ty/consts/int.rs @@ -141,14 +141,18 @@ impl crate::ty::HashStable for ScalarInt { impl Encodable for ScalarInt { fn encode(&self, s: &mut S) { - s.emit_u128(self.data); - s.emit_u8(self.size.get()); + let size = self.size.get(); + s.emit_u8(size); + s.emit_raw_bytes(&self.data.to_le_bytes()[..size as usize]); } } impl Decodable for ScalarInt { fn decode(d: &mut D) -> ScalarInt { - ScalarInt { data: d.read_u128(), size: NonZeroU8::new(d.read_u8()).unwrap() } + let mut data = [0u8; 16]; + let size = d.read_u8(); + data[..size as usize].copy_from_slice(d.read_raw_bytes(size as usize)); + ScalarInt { data: u128::from_le_bytes(data), size: NonZeroU8::new(size).unwrap() } } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index e5356581e6e1d..1871775ee4a88 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -925,7 +925,7 @@ impl<'tcx> TyCtxt<'tcx> { crate_name, // Don't print the whole stable crate id. That's just // annoying in debug output. - stable_crate_id.to_u64() >> (8 * 6), + stable_crate_id.as_u64() >> (8 * 6), self.def_path(def_id).to_string_no_crate_verbose() ) } diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index c8a78ec03d947..9106dce9b77db 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -11,7 +11,7 @@ use crate::ty::{ use crate::ty::{GenericArgKind, SubstsRef}; use rustc_apfloat::Float as _; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher}; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Res}; @@ -124,7 +124,7 @@ impl IntTypeExt for IntegerType { impl<'tcx> TyCtxt<'tcx> { /// Creates a hash of the type `Ty` which will be the same no matter what crate /// context it's calculated within. This is used by the `type_id` intrinsic. - pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 { + pub fn type_id_hash(self, ty: Ty<'tcx>) -> Hash64 { // We want the type_id be independent of the types free regions, so we // erase them. The erase_regions() call will also anonymize bound // regions, which is desirable too. diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index 5ecb2d6a6313e..444b1565d36d8 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -577,5 +577,10 @@ fn get_body_span<'tcx>( fn hash_mir_source<'tcx>(tcx: TyCtxt<'tcx>, hir_body: &'tcx rustc_hir::Body<'tcx>) -> u64 { // FIXME(cjgillot) Stop hashing HIR manually here. let owner = hir_body.id().hir_id.owner; - tcx.hir_owner_nodes(owner).unwrap().opt_hash_including_bodies.unwrap().to_smaller_hash() + tcx.hir_owner_nodes(owner) + .unwrap() + .opt_hash_including_bodies + .unwrap() + .to_smaller_hash() + .as_u64() } diff --git a/compiler/rustc_query_impl/src/on_disk_cache.rs b/compiler/rustc_query_impl/src/on_disk_cache.rs index 30477c7bd4422..37131f5376f51 100644 --- a/compiler/rustc_query_impl/src/on_disk_cache.rs +++ b/compiler/rustc_query_impl/src/on_disk_cache.rs @@ -1,6 +1,7 @@ use crate::QueryCtxt; use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; use rustc_data_structures::memmap::Mmap; +use rustc_data_structures::stable_hasher::Hash64; use rustc_data_structures::sync::{HashMapExt, Lock, Lrc, RwLock}; use rustc_data_structures::unhash::UnhashMap; use rustc_data_structures::unord::UnordSet; @@ -138,7 +139,7 @@ impl AbsoluteBytePos { /// is the only thing available when decoding the cache's [Footer]. #[derive(Encodable, Decodable, Clone, Debug)] struct EncodedSourceFileId { - file_name_hash: u64, + file_name_hash: Hash64, stable_crate_id: StableCrateId, } @@ -667,7 +668,7 @@ impl<'a, 'tcx> Decodable> for ExpnId { #[cfg(debug_assertions)] { use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; - let local_hash: u64 = decoder.tcx.with_stable_hashing_context(|mut hcx| { + let local_hash = decoder.tcx.with_stable_hashing_context(|mut hcx| { let mut hasher = StableHasher::new(); expn_id.expn_data().hash_stable(&mut hcx, &mut hasher); hasher.finish() diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index afbead7d1ae97..32222df25d496 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -5,7 +5,7 @@ use crate::on_disk_cache::{CacheDecoder, CacheEncoder, EncodedDepNodeIndex}; use crate::profiling_support::QueryKeyStringCache; use crate::{on_disk_cache, Queries}; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher}; use rustc_data_structures::sync::{AtomicU64, Lock}; use rustc_errors::{Diagnostic, Handler}; use rustc_middle::dep_graph::{ @@ -342,7 +342,7 @@ pub(crate) fn create_query_frame< let mut hasher = StableHasher::new(); std::mem::discriminant(&kind).hash_stable(&mut hcx, &mut hasher); key.hash_stable(&mut hcx, &mut hasher); - hasher.finish::() + hasher.finish::() }) }; let ty_adt_id = key.ty_adt_id(); diff --git a/compiler/rustc_query_system/src/query/mod.rs b/compiler/rustc_query_system/src/query/mod.rs index 312b0e1688dc9..fa1f51b04da77 100644 --- a/compiler/rustc_query_system/src/query/mod.rs +++ b/compiler/rustc_query_system/src/query/mod.rs @@ -16,6 +16,7 @@ pub use self::config::{HashResult, QueryConfig, TryLoadFromDisk}; use crate::dep_graph::DepKind; use crate::dep_graph::{DepNodeIndex, HasDepContext, SerializedDepNodeIndex}; +use rustc_data_structures::stable_hasher::Hash64; use rustc_data_structures::sync::Lock; use rustc_errors::Diagnostic; use rustc_hir::def::DefKind; @@ -37,7 +38,7 @@ pub struct QueryStackFrame { /// This hash is used to deterministically pick /// a query to remove cycles in the parallel compiler. #[cfg(parallel_compiler)] - hash: u64, + hash: Hash64, } impl QueryStackFrame { @@ -49,7 +50,7 @@ impl QueryStackFrame { def_kind: Option, dep_kind: D, ty_adt_id: Option, - _hash: impl FnOnce() -> u64, + _hash: impl FnOnce() -> Hash64, ) -> Self { Self { description, diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index 20310483d7e86..39b89017593d0 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -573,7 +573,7 @@ where // from disk. Re-hashing results is fairly expensive, so we can't // currently afford to verify every hash. This subset should still // give us some coverage of potential bugs though. - let try_verify = prev_fingerprint.as_value().1 % 32 == 0; + let try_verify = prev_fingerprint.split().1.as_u64() % 32 == 0; if std::intrinsics::unlikely( try_verify || qcx.dep_context().sess().opts.unstable_opts.incremental_verify_ich, ) { diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 340bb158e1791..14a8e8ff7271c 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -811,7 +811,7 @@ impl Session { } pub fn generate_proc_macro_decls_symbol(&self, stable_crate_id: StableCrateId) -> String { - format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.to_u64()) + format!("__rustc_proc_macro_decls_{:08x}__", stable_crate_id.as_u64()) } pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> { diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index b2c58caff2ec4..f05328ac1b423 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -1,12 +1,11 @@ use crate::{HashStableContext, Symbol}; use rustc_data_structures::fingerprint::Fingerprint; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey}; +use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher, ToStableHashKey}; use rustc_data_structures::unhash::Unhasher; use rustc_data_structures::AtomicRef; use rustc_index::vec::Idx; use rustc_macros::HashStable_Generic; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; -use std::borrow::Borrow; use std::fmt; use std::hash::{BuildHasherDefault, Hash, Hasher}; @@ -105,20 +104,20 @@ impl DefPathHash { /// originates from. #[inline] pub fn stable_crate_id(&self) -> StableCrateId { - StableCrateId(self.0.as_value().0) + StableCrateId(self.0.split().0) } /// Returns the crate-local part of the [DefPathHash]. /// /// Used for tests. #[inline] - pub fn local_hash(&self) -> u64 { - self.0.as_value().1 + pub fn local_hash(&self) -> Hash64 { + self.0.split().1 } /// Builds a new [DefPathHash] with the given [StableCrateId] and /// `local_hash`, where `local_hash` must be unique within its crate. - pub fn new(stable_crate_id: StableCrateId, local_hash: u64) -> DefPathHash { + pub fn new(stable_crate_id: StableCrateId, local_hash: Hash64) -> DefPathHash { DefPathHash(Fingerprint::new(stable_crate_id.0, local_hash)) } } @@ -129,13 +128,6 @@ impl Default for DefPathHash { } } -impl Borrow for DefPathHash { - #[inline] - fn borrow(&self) -> &Fingerprint { - &self.0 - } -} - /// A [`StableCrateId`] is a 64-bit hash of a crate name, together with all /// `-Cmetadata` arguments, and some other data. It is to [`CrateNum`] what [`DefPathHash`] is to /// [`DefId`]. It is stable across compilation sessions. @@ -147,15 +139,11 @@ impl Borrow for DefPathHash { /// /// For more information on the possibility of hash collisions in rustc, /// see the discussion in [`DefId`]. -#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)] -#[derive(HashStable_Generic, Encodable, Decodable)] -pub struct StableCrateId(pub(crate) u64); +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] +#[derive(Hash, HashStable_Generic, Encodable, Decodable)] +pub struct StableCrateId(pub(crate) Hash64); impl StableCrateId { - pub fn to_u64(self) -> u64 { - self.0 - } - /// Computes the stable ID for a crate with the given name and /// `-Cmetadata` arguments. pub fn new(crate_name: Symbol, is_exe: bool, mut metadata: Vec) -> StableCrateId { @@ -197,6 +185,16 @@ impl StableCrateId { StableCrateId(hasher.finish()) } + + pub fn as_u64(self) -> u64 { + self.0.as_u64() + } +} + +impl fmt::LowerHex for StableCrateId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::LowerHex::fmt(&self.0, f) + } } rustc_index::newtype_index! { diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index 08c4414034a0a..f8741d85934a2 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -33,7 +33,7 @@ use crate::def_id::{CrateNum, DefId, StableCrateId, CRATE_DEF_ID, LOCAL_CRATE}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::HashingControls; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher}; use rustc_data_structures::sync::{Lock, Lrc}; use rustc_data_structures::unhash::UnhashMap; use rustc_index::vec::IndexVec; @@ -123,15 +123,15 @@ impl ExpnHash { /// originates from. #[inline] pub fn stable_crate_id(self) -> StableCrateId { - StableCrateId(self.0.as_value().0) + StableCrateId(self.0.split().0) } /// Returns the crate-local part of the [ExpnHash]. /// /// Used for tests. #[inline] - pub fn local_hash(self) -> u64 { - self.0.as_value().1 + pub fn local_hash(self) -> Hash64 { + self.0.split().1 } #[inline] @@ -141,7 +141,7 @@ impl ExpnHash { /// Builds a new [ExpnHash] with the given [StableCrateId] and /// `local_hash`, where `local_hash` must be unique within its crate. - fn new(stable_crate_id: StableCrateId, local_hash: u64) -> ExpnHash { + fn new(stable_crate_id: StableCrateId, local_hash: Hash64) -> ExpnHash { ExpnHash(Fingerprint::new(stable_crate_id.0, local_hash)) } } @@ -350,7 +350,7 @@ pub struct HygieneData { /// would have collisions without a disambiguator. /// The keys of this map are always computed with `ExpnData.disambiguator` /// set to 0. - expn_data_disambiguators: FxHashMap, + expn_data_disambiguators: FxHashMap, } impl HygieneData { @@ -1040,7 +1040,7 @@ impl ExpnData { } #[inline] - fn hash_expn(&self, ctx: &mut impl HashStableContext) -> u64 { + fn hash_expn(&self, ctx: &mut impl HashStableContext) -> Hash64 { let mut hasher = StableHasher::new(); self.hash_stable(ctx, &mut hasher); hasher.finish() diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 911d6902c981a..83f4907d51769 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -59,7 +59,7 @@ pub mod fatal_error; pub mod profiling; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::stable_hasher::{Hash128, Hash64, HashStable, StableHasher}; use rustc_data_structures::sync::{Lock, Lrc}; use std::borrow::Cow; @@ -282,22 +282,22 @@ impl RealFileName { pub enum FileName { Real(RealFileName), /// Call to `quote!`. - QuoteExpansion(u64), + QuoteExpansion(Hash64), /// Command line. - Anon(u64), + Anon(Hash64), /// Hack in `src/librustc_ast/parse.rs`. // FIXME(jseyfried) - MacroExpansion(u64), - ProcMacroSourceCode(u64), + MacroExpansion(Hash64), + ProcMacroSourceCode(Hash64), /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`. - CfgSpec(u64), + CfgSpec(Hash64), /// Strings provided as crate attributes in the CLI. - CliCrateAttr(u64), + CliCrateAttr(Hash64), /// Custom sources for explicit parser calls from plugins and drivers. Custom(String), DocTest(PathBuf, isize), /// Post-substitution inline assembly from LLVM. - InlineAsm(u64), + InlineAsm(Hash64), } impl From for FileName { @@ -1343,7 +1343,7 @@ pub struct SourceFile { /// Locations of characters removed during normalization. pub normalized_pos: Vec, /// A hash of the filename, used for speeding up hashing in incremental compilation. - pub name_hash: u128, + pub name_hash: Hash128, /// Indicates which crate this `SourceFile` was imported from. pub cnum: CrateNum, } @@ -1472,7 +1472,7 @@ impl Decodable for SourceFile { }; let multibyte_chars: Vec = Decodable::decode(d); let non_narrow_chars: Vec = Decodable::decode(d); - let name_hash: u128 = Decodable::decode(d); + let name_hash = Decodable::decode(d); let normalized_pos: Vec = Decodable::decode(d); let cnum: CrateNum = Decodable::decode(d); SourceFile { @@ -1514,7 +1514,7 @@ impl SourceFile { let name_hash = { let mut hasher: StableHasher = StableHasher::new(); name.hash(&mut hasher); - hasher.finish::() + hasher.finish() }; let end_pos = start_pos.to_usize() + src.len(); assert!(end_pos <= u32::MAX as usize); diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index 29a7e74a81660..4c32c125fb95c 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -13,7 +13,7 @@ pub use crate::hygiene::{ExpnData, ExpnKind}; pub use crate::*; use rustc_data_structures::fx::FxHashMap; -use rustc_data_structures::stable_hasher::StableHasher; +use rustc_data_structures::stable_hasher::{Hash128, Hash64, StableHasher}; use rustc_data_structures::sync::{AtomicU32, Lrc, MappedReadGuard, ReadGuard, RwLock}; use std::cmp; use std::hash::Hash; @@ -138,7 +138,7 @@ impl FileLoader for RealFileLoader { pub struct StableSourceFileId { /// A hash of the source file's [`FileName`]. This is hash so that it's size /// is more predictable than if we included the actual [`FileName`] value. - pub file_name_hash: u64, + pub file_name_hash: Hash64, /// The [`CrateNum`] of the crate this source file was originally parsed for. /// We cannot include this information in the hash because at the time @@ -331,7 +331,7 @@ impl SourceMap { &self, filename: FileName, src_hash: SourceFileHash, - name_hash: u128, + name_hash: Hash128, source_len: usize, cnum: CrateNum, file_local_lines: Lock, diff --git a/compiler/rustc_span/src/tests.rs b/compiler/rustc_span/src/tests.rs index 5b3915c33387b..a242ad6d1d730 100644 --- a/compiler/rustc_span/src/tests.rs +++ b/compiler/rustc_span/src/tests.rs @@ -3,8 +3,12 @@ use super::*; #[test] fn test_lookup_line() { let source = "abcdefghijklm\nabcdefghij\n...".to_owned(); - let sf = - SourceFile::new(FileName::Anon(0), source, BytePos(3), SourceFileHashAlgorithm::Sha256); + let sf = SourceFile::new( + FileName::Anon(Hash64::ZERO), + source, + BytePos(3), + SourceFileHashAlgorithm::Sha256, + ); sf.lines(|lines| assert_eq!(lines, &[BytePos(3), BytePos(17), BytePos(28)])); assert_eq!(sf.lookup_line(BytePos(0)), None); diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index 5cbca81926b9a..6a0ca06f69caa 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -1,4 +1,4 @@ -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher}; use rustc_hir::def_id::CrateNum; use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; use rustc_middle::ty::print::{PrettyPrinter, Print, Printer}; @@ -93,7 +93,7 @@ fn get_symbol_hash<'tcx>( item_type: Ty<'tcx>, instantiating_crate: Option, -) -> u64 { +) -> Hash64 { let def_id = instance.def_id(); let substs = instance.substs; debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs); @@ -138,7 +138,7 @@ fn get_symbol_hash<'tcx>( }); // 64 bits should be enough to avoid collisions. - hasher.finish::() + hasher.finish::() }) } @@ -176,7 +176,7 @@ impl SymbolPath { } } - fn finish(mut self, hash: u64) -> String { + fn finish(mut self, hash: Hash64) -> String { self.finalize_pending_component(); // E = end name-sequence let _ = write!(self.result, "17h{hash:016x}E"); diff --git a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs index 1a679f32ca59b..262e8546a5d5b 100644 --- a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs +++ b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs @@ -406,7 +406,7 @@ fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String { // Crate disambiguator and name s.push('C'); - s.push_str(&to_disambiguator(tcx.stable_crate_id(def_path.krate).to_u64())); + s.push_str(&to_disambiguator(tcx.stable_crate_id(def_path.krate).as_u64())); let crate_name = tcx.crate_name(def_path.krate).to_string(); let _ = write!(s, "{}{}", crate_name.len(), &crate_name); diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index ee883285531df..2235524129e62 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -731,7 +731,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { fn path_crate(self, cnum: CrateNum) -> Result { self.push("C"); let stable_crate_id = self.tcx.def_path_hash(cnum.as_def_id()).stable_crate_id(); - self.push_disambiguator(stable_crate_id.to_u64()); + self.push_disambiguator(stable_crate_id.as_u64()); let name = self.tcx.crate_name(cnum); self.push_ident(name.as_str()); Ok(self) From a04c09ade8cf6a30b955ad2b02cec71bc1cf3f5f Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Sat, 15 Apr 2023 14:58:50 -0400 Subject: [PATCH 105/228] Document how the HashN types are different from Fingerprint --- compiler/rustc_data_structures/src/hashes.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_data_structures/src/hashes.rs b/compiler/rustc_data_structures/src/hashes.rs index 9f6e0fb76765b..f32f691226760 100644 --- a/compiler/rustc_data_structures/src/hashes.rs +++ b/compiler/rustc_data_structures/src/hashes.rs @@ -1,7 +1,20 @@ +//! rustc encodes a lot of hashes. If hashes are stored as `u64` or `u128`, a `derive(Encodable)` +//! will apply varint encoding to the hashes, which is less efficient than directly encoding the 8 +//! or 16 bytes of the hash. +//! +//! The types in this module represent 64-bit or 128-bit hashes produced by a `StableHasher`. +//! `Hash64` and `Hash128` expose some utilty functions to encourage users to not extract the inner +//! hash value as an integer type and accidentally apply varint encoding to it. +//! +//! In contrast with `Fingerprint`, users of these types cannot and should not attempt to construct +//! and decompose these types into constitutent pieces. The point of these types is only to +//! connect the fact that they can only be produced by a `StableHasher` to their +//! `Encode`/`Decode` impls. + +use crate::stable_hasher::{StableHasher, StableHasherResult}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use std::fmt; use std::ops::BitXorAssign; -use crate::stable_hasher::{StableHasher, StableHasherResult}; #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] pub struct Hash64 { @@ -74,9 +87,7 @@ impl Hash128 { #[inline] pub fn wrapping_add(self, other: Self) -> Self { - Self { - inner: self.inner.wrapping_add(other.inner), - } + Self { inner: self.inner.wrapping_add(other.inner) } } #[inline] From 5f9746b94766e1dca4c4ee39da46a03a41d3fcd8 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Tue, 18 Apr 2023 10:21:04 -0700 Subject: [PATCH 106/228] rustdoc: use a separate template for type layout size --- src/librustdoc/html/render/print_item.rs | 24 +++++++++---------- .../html/templates/type_layout_size.html | 12 ++++++++++ 2 files changed, 24 insertions(+), 12 deletions(-) create mode 100644 src/librustdoc/html/templates/type_layout_size.html diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index e089b55b9c4d1..3045e4b118bfb 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -1945,6 +1945,14 @@ fn document_type_layout<'a, 'cx: 'a>( ty_def_id: DefId, } + #[derive(Template)] + #[template(path = "type_layout_size.html")] + struct TypeLayoutSize { + is_unsized: bool, + is_uninhabited: bool, + size: u64, + } + impl<'a, 'cx: 'a> TypeLayout<'a, 'cx> { fn variants<'b: 'a>(&'b self) -> Option<&'b IndexVec> { if let Variants::Multiple { variants, .. } = @@ -1986,18 +1994,10 @@ fn document_type_layout<'a, 'cx: 'a>( tag_size: u64, ) -> impl fmt::Display + Captures<'cx> + Captures<'b> { display_fn(move |f| { - if layout.abi.is_unsized() { - write!(f, "(unsized)")?; - } else { - let size = layout.size.bytes() - tag_size; - write!(f, "{size} byte{pl}", pl = if size == 1 { "" } else { "s" })?; - if layout.abi.is_uninhabited() { - write!( - f, - " (uninhabited)" - )?; - } - } + let is_unsized = layout.abi.is_unsized(); + let is_uninhabited = layout.abi.is_uninhabited(); + let size = layout.size.bytes() - tag_size; + TypeLayoutSize { is_unsized, is_uninhabited, size }.render_into(f).unwrap(); Ok(()) }) } diff --git a/src/librustdoc/html/templates/type_layout_size.html b/src/librustdoc/html/templates/type_layout_size.html new file mode 100644 index 0000000000000..9c2b39edc9f37 --- /dev/null +++ b/src/librustdoc/html/templates/type_layout_size.html @@ -0,0 +1,12 @@ +{% if is_unsized %} + (unsized) +{% else %} + {% if size == 1 %} + 1 byte + {% else %} + {{ size +}} bytes + {% endif %} + {% if is_uninhabited %} + {# +#} (uninhabited) + {% endif %} +{% endif %} From cddc7743a39342995e299319f670c85d6a73395f Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 18 Apr 2023 17:38:28 +0000 Subject: [PATCH 107/228] Remove `as_substs` usage --- compiler/rustc_middle/src/ty/walk.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_middle/src/ty/walk.rs b/compiler/rustc_middle/src/ty/walk.rs index 182945b9c3db1..04a635a68034d 100644 --- a/compiler/rustc_middle/src/ty/walk.rs +++ b/compiler/rustc_middle/src/ty/walk.rs @@ -194,7 +194,7 @@ fn push_inner<'tcx>(stack: &mut TypeWalkerStack<'tcx>, parent: GenericArg<'tcx>) | ty::FnDef(_, substs) => { stack.extend(substs.iter().rev()); } - ty::Tuple(ts) => stack.extend(ts.as_substs().iter().rev()), + ty::Tuple(ts) => stack.extend(ts.iter().rev().map(GenericArg::from)), ty::GeneratorWitness(ts) => { stack.extend(ts.skip_binder().iter().rev().map(|ty| ty.into())); } From e8c0c1eafe625dd06872184ed5999ed3ee60b424 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 18 Apr 2023 17:39:08 +0000 Subject: [PATCH 108/228] Remove very useless `as_substs` usage from clippy --- src/tools/clippy/clippy_utils/src/ty.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/clippy/clippy_utils/src/ty.rs b/src/tools/clippy/clippy_utils/src/ty.rs index 9449f0b55674d..8b996c188161d 100644 --- a/src/tools/clippy/clippy_utils/src/ty.rs +++ b/src/tools/clippy/clippy_utils/src/ty.rs @@ -975,7 +975,7 @@ pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 { } match (cx.layout_of(ty).map(|layout| layout.size.bytes()), ty.kind()) { (Ok(size), _) => size, - (Err(_), ty::Tuple(list)) => list.as_substs().types().map(|t| approx_ty_size(cx, t)).sum(), + (Err(_), ty::Tuple(list)) => list.iter().map(|t| approx_ty_size(cx, t)).sum(), (Err(_), ty::Array(t, n)) => { n.try_eval_target_usize(cx.tcx, cx.param_env).unwrap_or_default() * approx_ty_size(cx, *t) }, From 10ec03c3fb4509f96df3aa8264858b76e81c9aa1 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Tue, 18 Apr 2023 17:42:30 +0000 Subject: [PATCH 109/228] Don't transmute `&List` <-> `&List` --- compiler/rustc_middle/src/ty/context.rs | 35 +++------------------ compiler/rustc_middle/src/ty/subst.rs | 30 ++++++------------ compiler/rustc_traits/src/chalk/lowering.rs | 20 +++++++++--- 3 files changed, 30 insertions(+), 55 deletions(-) diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index e5356581e6e1d..0a0040e220417 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -141,6 +141,7 @@ pub struct CtxtInterners<'tcx> { type_: InternedSet<'tcx, WithCachedTypeInfo>>, const_lists: InternedSet<'tcx, List>>, substs: InternedSet<'tcx, InternalSubsts<'tcx>>, + type_lists: InternedSet<'tcx, List>>, canonical_var_infos: InternedSet<'tcx, List>>, region: InternedSet<'tcx, RegionKind<'tcx>>, poly_existential_predicates: InternedSet<'tcx, List>>, @@ -163,6 +164,7 @@ impl<'tcx> CtxtInterners<'tcx> { type_: Default::default(), const_lists: Default::default(), substs: Default::default(), + type_lists: Default::default(), region: Default::default(), poly_existential_predicates: Default::default(), canonical_var_infos: Default::default(), @@ -1278,25 +1280,6 @@ macro_rules! nop_lift { }; } -// Can't use the macros as we have reuse the `substs` here. -// -// See `mk_type_list` for more info. -impl<'a, 'tcx> Lift<'tcx> for &'a List> { - type Lifted = &'tcx List>; - fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { - if self.is_empty() { - return Some(List::empty()); - } - - tcx.interners - .substs - .contains_pointer_to(&InternedInSet(self.as_substs())) - // SAFETY: `self` is interned and therefore valid - // for the entire lifetime of the `TyCtxt`. - .then(|| unsafe { mem::transmute::<&'a List>, &'tcx List>>(self) }) - } -} - macro_rules! nop_list_lift { ($set:ident; $ty:ty => $lifted:ty) => { impl<'a, 'tcx> Lift<'tcx> for &'a List<$ty> { @@ -1320,6 +1303,7 @@ nop_lift! {const_; Const<'a> => Const<'tcx>} nop_lift! {const_allocation; ConstAllocation<'a> => ConstAllocation<'tcx>} nop_lift! {predicate; Predicate<'a> => Predicate<'tcx>} +nop_list_lift! {type_lists; Ty<'a> => Ty<'tcx>} nop_list_lift! {poly_existential_predicates; PolyExistentialPredicate<'a> => PolyExistentialPredicate<'tcx>} nop_list_lift! {predicates; Predicate<'a> => Predicate<'tcx>} nop_list_lift! {canonical_var_infos; CanonicalVarInfo<'a> => CanonicalVarInfo<'tcx>} @@ -1594,6 +1578,7 @@ macro_rules! slice_interners { slice_interners!( const_lists: pub mk_const_list(Const<'tcx>), substs: pub mk_substs(GenericArg<'tcx>), + type_lists: pub mk_type_list(Ty<'tcx>), canonical_var_infos: pub mk_canonical_var_infos(CanonicalVarInfo<'tcx>), poly_existential_predicates: intern_poly_existential_predicates(PolyExistentialPredicate<'tcx>), predicates: intern_predicates(Predicate<'tcx>), @@ -2193,18 +2178,6 @@ impl<'tcx> TyCtxt<'tcx> { T::collect_and_apply(iter, |xs| self.mk_const_list(xs)) } - pub fn mk_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { - // Actually intern type lists as lists of `GenericArg`s. - // - // Transmuting from `Ty<'tcx>` to `GenericArg<'tcx>` is sound - // as explained in `ty_slice_as_generic_arg`. With this, - // we guarantee that even when transmuting between `List>` - // and `List>`, the uniqueness requirement for - // lists is upheld. - let substs = self.mk_substs(ty::subst::ty_slice_as_generic_args(ts)); - substs.try_as_type_list().unwrap() - } - // Unlike various other `mk_*_from_iter` functions, this one uses `I: // IntoIterator` instead of `I: Iterator`, and it doesn't have a slice // variant, because of the need to combine `inputs` and `output`. This diff --git a/compiler/rustc_middle/src/ty/subst.rs b/compiler/rustc_middle/src/ty/subst.rs index f05b873432d29..da3cd27f38844 100644 --- a/compiler/rustc_middle/src/ty/subst.rs +++ b/compiler/rustc_middle/src/ty/subst.rs @@ -67,19 +67,6 @@ pub fn ty_slice_as_generic_args<'a, 'tcx>(ts: &'a [Ty<'tcx>]) -> &'a [GenericArg unsafe { slice::from_raw_parts(ts.as_ptr().cast(), ts.len()) } } -impl<'tcx> List> { - /// Allows to freely switch between `List>` and `List>`. - /// - /// As lists are interned, `List>` and `List>` have - /// be interned together, see `mk_type_list` for more details. - #[inline] - pub fn as_substs(&'tcx self) -> SubstsRef<'tcx> { - assert_eq!(TYPE_TAG, 0); - // SAFETY: `List` is `#[repr(C)]`. `Ty` and `GenericArg` is explained above. - unsafe { &*(self as *const List> as *const List>) } - } -} - impl<'tcx> GenericArgKind<'tcx> { #[inline] fn pack(self) -> GenericArg<'tcx> { @@ -268,13 +255,16 @@ pub type InternalSubsts<'tcx> = List>; pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>; impl<'tcx> InternalSubsts<'tcx> { - /// Checks whether all elements of this list are types, if so, transmute. - pub fn try_as_type_list(&'tcx self) -> Option<&'tcx List>> { - self.iter().all(|arg| matches!(arg.unpack(), GenericArgKind::Type(_))).then(|| { - assert_eq!(TYPE_TAG, 0); - // SAFETY: All elements are types, see `List>::as_substs`. - unsafe { &*(self as *const List> as *const List>) } - }) + /// Converts substs to a type list. + /// + /// # Panics + /// + /// If any of the generic arguments are not types. + pub fn into_type_list(&self, tcx: TyCtxt<'tcx>) -> &'tcx List> { + tcx.mk_type_list_from_iter(self.iter().map(|arg| match arg.unpack() { + GenericArgKind::Type(ty) => ty, + _ => bug!("`into_type_list` called on substs with non-types"), + })) } /// Interpret these substitutions as the substitutions of a closure type. diff --git a/compiler/rustc_traits/src/chalk/lowering.rs b/compiler/rustc_traits/src/chalk/lowering.rs index 31eea22d72b88..4d225e36b22cd 100644 --- a/compiler/rustc_traits/src/chalk/lowering.rs +++ b/compiler/rustc_traits/src/chalk/lowering.rs @@ -60,6 +60,20 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::Substitution>> for Subst } } +impl<'tcx> LowerInto<'tcx, chalk_ir::Substitution>> + for &'tcx ty::List> +{ + fn lower_into( + self, + interner: RustInterner<'tcx>, + ) -> chalk_ir::Substitution> { + chalk_ir::Substitution::from_iter( + interner, + self.iter().map(|ty| GenericArg::from(ty).lower_into(interner)), + ) + } +} + impl<'tcx> LowerInto<'tcx, SubstsRef<'tcx>> for &chalk_ir::Substitution> { fn lower_into(self, interner: RustInterner<'tcx>) -> SubstsRef<'tcx> { interner @@ -351,9 +365,7 @@ impl<'tcx> LowerInto<'tcx, chalk_ir::Ty>> for Ty<'tcx> { ty::GeneratorWitness(_) => unimplemented!(), ty::GeneratorWitnessMIR(..) => unimplemented!(), ty::Never => chalk_ir::TyKind::Never, - ty::Tuple(types) => { - chalk_ir::TyKind::Tuple(types.len(), types.as_substs().lower_into(interner)) - } + ty::Tuple(types) => chalk_ir::TyKind::Tuple(types.len(), types.lower_into(interner)), ty::Alias(ty::Projection, ty::AliasTy { def_id, substs, .. }) => { chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy { associated_ty_id: chalk_ir::AssocTypeId(def_id), @@ -435,7 +447,7 @@ impl<'tcx> LowerInto<'tcx, Ty<'tcx>> for &chalk_ir::Ty> { TyKind::GeneratorWitness(..) => unimplemented!(), TyKind::Never => ty::Never, TyKind::Tuple(_len, substitution) => { - ty::Tuple(substitution.lower_into(interner).try_as_type_list().unwrap()) + ty::Tuple(substitution.lower_into(interner).into_type_list(interner.tcx)) } TyKind::Slice(ty) => ty::Slice(ty.lower_into(interner)), TyKind::Raw(mutbl, ty) => ty::RawPtr(ty::TypeAndMut { From 073d99b25d2e656ea053ab8dae03ea921508da76 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Tue, 18 Apr 2023 14:13:19 -0400 Subject: [PATCH 110/228] Add #[inline] to some new functions Co-authored-by: Camille Gillot --- compiler/rustc_data_structures/src/fingerprint.rs | 2 ++ compiler/rustc_data_structures/src/hashes.rs | 1 + compiler/rustc_span/src/def_id.rs | 1 + 3 files changed, 4 insertions(+) diff --git a/compiler/rustc_data_structures/src/fingerprint.rs b/compiler/rustc_data_structures/src/fingerprint.rs index 1c929afb1cf36..6fa76981408ca 100644 --- a/compiler/rustc_data_structures/src/fingerprint.rs +++ b/compiler/rustc_data_structures/src/fingerprint.rs @@ -14,12 +14,14 @@ pub trait FingerprintComponent { } impl FingerprintComponent for Hash64 { + #[inline] fn as_u64(&self) -> u64 { Hash64::as_u64(*self) } } impl FingerprintComponent for u64 { + #[inline] fn as_u64(&self) -> u64 { *self } diff --git a/compiler/rustc_data_structures/src/hashes.rs b/compiler/rustc_data_structures/src/hashes.rs index f32f691226760..ad068cdbc9841 100644 --- a/compiler/rustc_data_structures/src/hashes.rs +++ b/compiler/rustc_data_structures/src/hashes.rs @@ -36,6 +36,7 @@ impl Hash64 { } impl BitXorAssign for Hash64 { + #[inline] fn bitxor_assign(&mut self, rhs: u64) { self.inner ^= rhs; } diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index f05328ac1b423..6004009c6ff1b 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -186,6 +186,7 @@ impl StableCrateId { StableCrateId(hasher.finish()) } + #[inline] pub fn as_u64(self) -> u64 { self.0.as_u64() } From 3a16db1bb4c863b2afe5ecd745c1d7a7741a5e11 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Tue, 18 Apr 2023 10:49:18 -0700 Subject: [PATCH 111/228] rustdoc: create variants list outside of template --- src/librustdoc/html/render/print_item.rs | 109 +++++++++--------- .../html/templates/type_layout.html | 14 +-- 2 files changed, 60 insertions(+), 63 deletions(-) diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 3045e4b118bfb..3ccc694fd2a75 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -5,15 +5,13 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def::CtorKind; use rustc_hir::def_id::DefId; -use rustc_index::vec::IndexVec; use rustc_middle::middle::stability; use rustc_middle::span_bug; -use rustc_middle::ty::layout::{LayoutError, TyAndLayout}; +use rustc_middle::ty::layout::LayoutError; use rustc_middle::ty::{self, Adt, TyCtxt}; use rustc_span::hygiene::MacroKind; use rustc_span::symbol::{kw, sym, Symbol}; -use rustc_target::abi::{LayoutS, Primitive, TagEncoding, VariantIdx, Variants}; -use std::borrow::Borrow; +use rustc_target::abi::{Primitive, TagEncoding, Variants}; use std::cmp::Ordering; use std::fmt; use std::rc::Rc; @@ -1940,9 +1938,9 @@ fn document_type_layout<'a, 'cx: 'a>( ) -> impl fmt::Display + 'a + Captures<'cx> { #[derive(Template)] #[template(path = "type_layout.html")] - struct TypeLayout<'a, 'cx> { - cx: &'a Context<'cx>, - ty_def_id: DefId, + struct TypeLayout<'cx> { + variants: Vec<(Symbol, TypeLayoutSize)>, + type_layout_size: Result>, } #[derive(Template)] @@ -1953,62 +1951,61 @@ fn document_type_layout<'a, 'cx: 'a>( size: u64, } - impl<'a, 'cx: 'a> TypeLayout<'a, 'cx> { - fn variants<'b: 'a>(&'b self) -> Option<&'b IndexVec> { - if let Variants::Multiple { variants, .. } = - self.type_layout().unwrap().layout.variants() && !variants.is_empty() { - Some(&variants) - } else { - None - } - } - fn type_layout<'b: 'a>(&'b self) -> Result, LayoutError<'cx>> { - let tcx = self.cx.tcx(); - let param_env = tcx.param_env(self.ty_def_id); - let ty = tcx.type_of(self.ty_def_id).subst_identity(); - tcx.layout_of(param_env.and(ty)) + display_fn(move |f| { + if !cx.shared.show_type_layout { + return Ok(()); } - fn variant_name<'b: 'a>(&'b self, index: VariantIdx) -> Symbol { - let Adt(adt, _) = self.type_layout().unwrap().ty.kind() else { - span_bug!(self.cx.tcx().def_span(self.ty_def_id), "not an adt") - }; - adt.variant(index).name - } - fn tag_size<'b: 'a>(&'b self) -> u64 { - if let Variants::Multiple { variants, tag, tag_encoding, .. } = - self.type_layout().unwrap().layout.variants() && !variants.is_empty() { - if let TagEncoding::Niche { .. } = tag_encoding { - 0 - } else if let Primitive::Int(i, _) = tag.primitive() { - i.size().bytes() - } else { - span_bug!(self.cx.tcx().def_span(self.ty_def_id), "tag is neither niche nor int") - } + + let variants = { + let tcx = cx.tcx(); + let param_env = tcx.param_env(ty_def_id); + let ty = tcx.type_of(ty_def_id).subst_identity(); + let type_layout = tcx.layout_of(param_env.and(ty)); + if let Ok(type_layout) = type_layout && + let Variants::Multiple { variants, tag, tag_encoding, .. } = + type_layout.layout.variants() && + !variants.is_empty() + { + let tag_size = + if let TagEncoding::Niche { .. } = tag_encoding { + 0 + } else if let Primitive::Int(i, _) = tag.primitive() { + i.size().bytes() + } else { + span_bug!(cx.tcx().def_span(ty_def_id), "tag is neither niche nor int") + }; + let variants = variants + .iter_enumerated() + .map(|(variant_idx, variant_layout)| { + let Adt(adt, _) = type_layout.ty.kind() else { + span_bug!(cx.tcx().def_span(ty_def_id), "not an adt") + }; + let name = adt.variant(variant_idx).name; + let is_unsized = variant_layout.abi.is_unsized(); + let is_uninhabited = variant_layout.abi.is_uninhabited(); + let size = variant_layout.size.bytes() - tag_size; + let type_layout_size = TypeLayoutSize { is_unsized, is_uninhabited, size }; + (name, type_layout_size) + }).collect(); + variants } else { - 0 + Vec::new() } - } - fn write_size<'b: 'a>( - &'b self, - layout: &'b LayoutS, - tag_size: u64, - ) -> impl fmt::Display + Captures<'cx> + Captures<'b> { - display_fn(move |f| { + }; + + let type_layout_size = { + let tcx = cx.tcx(); + let param_env = tcx.param_env(ty_def_id); + let ty = tcx.type_of(ty_def_id).subst_identity(); + tcx.layout_of(param_env.and(ty)).map(|layout| { let is_unsized = layout.abi.is_unsized(); let is_uninhabited = layout.abi.is_uninhabited(); - let size = layout.size.bytes() - tag_size; - TypeLayoutSize { is_unsized, is_uninhabited, size }.render_into(f).unwrap(); - Ok(()) + let size = layout.size.bytes(); + TypeLayoutSize { is_unsized, is_uninhabited, size } }) - } - } - - display_fn(move |f| { - if !cx.shared.show_type_layout { - return Ok(()); - } + }; - Ok(TypeLayout { cx, ty_def_id }.render_into(f).unwrap()) + Ok(TypeLayout { variants, type_layout_size }.render_into(f).unwrap()) }) } diff --git a/src/librustdoc/html/templates/type_layout.html b/src/librustdoc/html/templates/type_layout.html index 70149d4e1ab85..9e2c2049e31bb 100644 --- a/src/librustdoc/html/templates/type_layout.html +++ b/src/librustdoc/html/templates/type_layout.html @@ -2,8 +2,8 @@

{# #} Layout§ {# #}

{# #}
{# #} - {% match self.type_layout() %} - {% when Ok(ty_layout) %} + {% match type_layout_size %} + {% when Ok(type_layout_size) %}
{# #}

{# #} Note: Most layout information is completely {#+ #} @@ -14,14 +14,14 @@

{# #} chapter for details on type layout guarantees. {# #}

{# #}

{# #} -

Size: {{ self.write_size(ty_layout.layout.0.borrow(), 0) | safe }}

{# #} - {% if let Some(variants) = self.variants() %} +

Size: {{ type_layout_size|safe }}

{# #} + {% if !variants.is_empty() %}

Size for each variant:

{# #}
    {# #} - {% for (index, layout) in variants.iter_enumerated() %} + {% for (name, layout_size) in variants %}
  • {# #} - {{ self.variant_name(index.clone()) }}: {#+ #} - {{ self.write_size(layout, self.tag_size()) | safe }} + {{ name }}: {#+ #} + {{ layout_size|safe }}
  • {# #} {% endfor %}
{# #} From e26ae9530b21288ea6f9ca73d8c8d895c47807c3 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Tue, 18 Apr 2023 10:52:36 -0700 Subject: [PATCH 112/228] rustdoc: format type layout template with newline after `

` --- .../html/templates/type_layout.html | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/librustdoc/html/templates/type_layout.html b/src/librustdoc/html/templates/type_layout.html index 9e2c2049e31bb..58b220c7428f4 100644 --- a/src/librustdoc/html/templates/type_layout.html +++ b/src/librustdoc/html/templates/type_layout.html @@ -16,7 +16,9 @@

{# #}

{# #}

Size: {{ type_layout_size|safe }}

{# #} {% if !variants.is_empty() %} -

Size for each variant:

{# #} +

{# #} + Size for each variant: {# #} +

{# #}