From 4e973b0b63ab0177369e60d402ff54198ee357f3 Mon Sep 17 00:00:00 2001 From: Taiki Endo Date: Mon, 8 Jan 2024 00:36:31 +0900 Subject: [PATCH 01/17] rc,sync: Do not create references to uninitialized values --- library/alloc/src/rc.rs | 27 ++++++++++++++++----------- library/alloc/src/sync.rs | 18 +++++++++--------- 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index 263b1449de156..fa652aa0517ac 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -1885,10 +1885,10 @@ impl Rc { // Initialize the RcBox let inner = mem_to_rcbox(ptr.as_non_null_ptr().as_ptr()); unsafe { - debug_assert_eq!(Layout::for_value(&*inner), layout); + debug_assert_eq!(Layout::for_value_raw(inner), layout); - ptr::write(&mut (*inner).strong, Cell::new(1)); - ptr::write(&mut (*inner).weak, Cell::new(1)); + ptr::addr_of_mut!((*inner).strong).write(Cell::new(1)); + ptr::addr_of_mut!((*inner).weak).write(Cell::new(1)); } Ok(inner) @@ -1902,7 +1902,7 @@ impl Rc { // Allocate for the `RcBox` using the given value. unsafe { Rc::::allocate_for_layout( - Layout::for_value(&*ptr), + Layout::for_value_raw(ptr), |layout| alloc.allocate(layout), |mem| mem.with_metadata_of(ptr as *const RcBox), ) @@ -1918,7 +1918,7 @@ impl Rc { // Copy value as bytes ptr::copy_nonoverlapping( &*src as *const T as *const u8, - &mut (*ptr).value as *mut _ as *mut u8, + ptr::addr_of_mut!((*ptr).value) as *mut u8, value_size, ); @@ -1952,7 +1952,11 @@ impl Rc<[T]> { unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { unsafe { let ptr = Self::allocate_for_slice(v.len()); - ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); + ptr::copy_nonoverlapping( + v.as_ptr(), + ptr::addr_of_mut!((*ptr).value) as *mut T, + v.len(), + ); Self::from_ptr(ptr) } } @@ -1987,10 +1991,10 @@ impl Rc<[T]> { let ptr = Self::allocate_for_slice(len); let mem = ptr as *mut _ as *mut u8; - let layout = Layout::for_value(&*ptr); + let layout = Layout::for_value_raw(ptr); // Pointer to first element - let elems = &mut (*ptr).value as *mut [T] as *mut T; + let elems = ptr::addr_of_mut!((*ptr).value) as *mut T; let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 }; @@ -2096,7 +2100,8 @@ unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Rc { self.inner().dec_weak(); if self.inner().weak() == 0 { - self.alloc.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); + self.alloc + .deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr())); } } } @@ -2524,7 +2529,7 @@ impl From> for Rc<[T], A> { let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_alloc(); let rc_ptr = Self::allocate_for_slice_in(len, &alloc); - ptr::copy_nonoverlapping(vec_ptr, &mut (*rc_ptr).value as *mut [T] as *mut T, len); + ptr::copy_nonoverlapping(vec_ptr, ptr::addr_of_mut!((*rc_ptr).value) as *mut T, len); // Create a `Vec` with length 0, to deallocate the buffer // without dropping its contents or the allocator @@ -3514,7 +3519,7 @@ unsafe impl<#[may_dangle] T> Drop for UniqueRc { self.ptr.as_ref().dec_weak(); if self.ptr.as_ref().weak() == 0 { - Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); + Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr())); } } } diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 5273b3cb2dafa..70e1f63dd7385 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -1828,11 +1828,11 @@ impl Arc { mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner, ) -> *mut ArcInner { let inner = mem_to_arcinner(ptr.as_non_null_ptr().as_ptr()); - debug_assert_eq!(unsafe { Layout::for_value(&*inner) }, layout); + debug_assert_eq!(unsafe { Layout::for_value_raw(inner) }, layout); unsafe { - ptr::write(&mut (*inner).strong, atomic::AtomicUsize::new(1)); - ptr::write(&mut (*inner).weak, atomic::AtomicUsize::new(1)); + ptr::addr_of_mut!((*inner).strong).write(atomic::AtomicUsize::new(1)); + ptr::addr_of_mut!((*inner).weak).write(atomic::AtomicUsize::new(1)); } inner @@ -1847,7 +1847,7 @@ impl Arc { // Allocate for the `ArcInner` using the given value. unsafe { Arc::allocate_for_layout( - Layout::for_value(&*ptr), + Layout::for_value_raw(ptr), |layout| alloc.allocate(layout), |mem| mem.with_metadata_of(ptr as *const ArcInner), ) @@ -1863,7 +1863,7 @@ impl Arc { // Copy value as bytes ptr::copy_nonoverlapping( &*src as *const T as *const u8, - &mut (*ptr).data as *mut _ as *mut u8, + ptr::addr_of_mut!((*ptr).data) as *mut u8, value_size, ); @@ -1898,7 +1898,7 @@ impl Arc<[T]> { unsafe { let ptr = Self::allocate_for_slice(v.len()); - ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).data as *mut [T] as *mut T, v.len()); + ptr::copy_nonoverlapping(v.as_ptr(), ptr::addr_of_mut!((*ptr).data) as *mut T, v.len()); Self::from_ptr(ptr) } @@ -1934,10 +1934,10 @@ impl Arc<[T]> { let ptr = Self::allocate_for_slice(len); let mem = ptr as *mut _ as *mut u8; - let layout = Layout::for_value(&*ptr); + let layout = Layout::for_value_raw(ptr); // Pointer to first element - let elems = &mut (*ptr).data as *mut [T] as *mut T; + let elems = ptr::addr_of_mut!((*ptr).data) as *mut T; let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 }; @@ -3380,7 +3380,7 @@ impl From> for Arc<[T], A> { let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_alloc(); let rc_ptr = Self::allocate_for_slice_in(len, &alloc); - ptr::copy_nonoverlapping(vec_ptr, &mut (*rc_ptr).data as *mut [T] as *mut T, len); + ptr::copy_nonoverlapping(vec_ptr, ptr::addr_of_mut!((*rc_ptr).data) as *mut T, len); // Create a `Vec` with length 0, to deallocate the buffer // without dropping its contents or the allocator From b152de29c59fc0d34ab26b0be445a45e9ffe2dfb Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 5 Jan 2024 13:23:05 +1100 Subject: [PATCH 02/17] coverage: Discard code regions that might cause fatal errors in `llvm-cov` --- .../rustc_mir_transform/src/coverage/mod.rs | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index dcd7014f4fc90..4b91f042f007a 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -330,7 +330,7 @@ fn make_code_region( start_line = source_map.doctest_offset_line(&file.name, start_line); end_line = source_map.doctest_offset_line(&file.name, end_line); - Some(CodeRegion { + check_code_region(CodeRegion { file_name, start_line: start_line as u32, start_col: start_col as u32, @@ -339,6 +339,41 @@ fn make_code_region( }) } +/// If `llvm-cov` sees a code region that is improperly ordered (end < start), +/// it will immediately exit with a fatal error. To prevent that from happening, +/// discard regions that are improperly ordered, or might be interpreted in a +/// way that makes them improperly ordered. +fn check_code_region(code_region: CodeRegion) -> Option { + let CodeRegion { file_name: _, start_line, start_col, end_line, end_col } = code_region; + + // Line/column coordinates are supposed to be 1-based. If we ever emit + // coordinates of 0, `llvm-cov` might misinterpret them. + let all_nonzero = [start_line, start_col, end_line, end_col].into_iter().all(|x| x != 0); + // Coverage mappings use the high bit of `end_col` to indicate that a + // region is actually a "gap" region, so make sure it's unset. + let end_col_has_high_bit_unset = (end_col & (1 << 31)) == 0; + // If a region is improperly ordered (end < start), `llvm-cov` will exit + // with a fatal error, which is inconvenient for users and hard to debug. + let is_ordered = (start_line, start_col) <= (end_line, end_col); + + if all_nonzero && end_col_has_high_bit_unset && is_ordered { + Some(code_region) + } else { + debug!( + ?code_region, + ?all_nonzero, + ?end_col_has_high_bit_unset, + ?is_ordered, + "Skipping code region that would be misinterpreted or rejected by LLVM" + ); + if cfg!(debug_assertions) { + // If this happens in a debug build, ICE to make it easier to notice. + bug!("Improper code region: {code_region:?}"); + } + None + } +} + fn is_eligible_for_coverage(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { // Only instrument functions, methods, and closures (not constants since they are evaluated // at compile time by Miri). From bdfc64ac984e892f6061deebaee5a9301b8d271f Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 21 Jan 2024 12:18:48 +1100 Subject: [PATCH 03/17] coverage: Add a test that uses `#[bench]` --- tests/coverage/bench.cov-map | 16 ++++++++++++++++ tests/coverage/bench.coverage | 9 +++++++++ tests/coverage/bench.rs | 8 ++++++++ 3 files changed, 33 insertions(+) create mode 100644 tests/coverage/bench.cov-map create mode 100644 tests/coverage/bench.coverage create mode 100644 tests/coverage/bench.rs diff --git a/tests/coverage/bench.cov-map b/tests/coverage/bench.cov-map new file mode 100644 index 0000000000000..7cdb1b641bf3d --- /dev/null +++ b/tests/coverage/bench.cov-map @@ -0,0 +1,16 @@ +Function name: bench::my_bench +Raw bytes (9): 0x[01, 01, 00, 01, 01, 08, 01, 00, 27] +Number of files: 1 +- file 0 => global file 1 +Number of expressions: 0 +Number of file 0 mappings: 1 +- Code(Counter(0)) at (prev + 8, 1) to (start + 0, 39) + +Function name: bench::my_bench::{closure#0} +Raw bytes (9): 0x[01, 01, 00, 01, 01, 07, 01, 00, 09] +Number of files: 1 +- file 0 => global file 1 +Number of expressions: 0 +Number of file 0 mappings: 1 +- Code(Counter(0)) at (prev + 7, 1) to (start + 0, 9) + diff --git a/tests/coverage/bench.coverage b/tests/coverage/bench.coverage new file mode 100644 index 0000000000000..4642d92cc1911 --- /dev/null +++ b/tests/coverage/bench.coverage @@ -0,0 +1,9 @@ + LL| |#![feature(test)] + LL| |// edition: 2021 + LL| |// compile-flags: --test + LL| | + LL| |extern crate test; + LL| | + LL| 1|#[bench] + LL| 1|fn my_bench(_b: &mut test::Bencher) {} + diff --git a/tests/coverage/bench.rs b/tests/coverage/bench.rs new file mode 100644 index 0000000000000..2dcd7355b2f79 --- /dev/null +++ b/tests/coverage/bench.rs @@ -0,0 +1,8 @@ +#![feature(test)] +// edition: 2021 +// compile-flags: --test + +extern crate test; + +#[bench] +fn my_bench(_b: &mut test::Bencher) {} From 6d7e80c5bc3cc3b176834322afc50dc8dd100599 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 21 Jan 2024 11:26:28 +1100 Subject: [PATCH 04/17] Add `#[coverage(off)]` to closures introduced by `#[test]`/`#[bench]` --- compiler/rustc_builtin_macros/src/lib.rs | 1 + compiler/rustc_builtin_macros/src/test.rs | 21 +++++++++++++++++---- library/core/src/macros/mod.rs | 4 ++-- tests/coverage/bench.cov-map | 8 -------- tests/coverage/bench.coverage | 2 +- tests/coverage/test_harness.cov-map | 8 -------- tests/coverage/test_harness.coverage | 2 +- tests/pretty/tests-are-sorted.pp | 9 ++++++--- 8 files changed, 28 insertions(+), 27 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/lib.rs b/compiler/rustc_builtin_macros/src/lib.rs index f60b73fbe9b13..3e9b06a5b054b 100644 --- a/compiler/rustc_builtin_macros/src/lib.rs +++ b/compiler/rustc_builtin_macros/src/lib.rs @@ -6,6 +6,7 @@ #![doc(rust_logo)] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![feature(array_windows)] +#![feature(assert_matches)] #![feature(box_patterns)] #![feature(decl_macro)] #![feature(if_let_guard)] diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index 4d44e340ae149..0631f796894b1 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -9,6 +9,7 @@ use rustc_errors::{Applicability, DiagnosticBuilder, Level}; use rustc_expand::base::*; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::{ErrorGuaranteed, FileNameDisplayPreference, Span}; +use std::assert_matches::assert_matches; use std::iter; use thin_vec::{thin_vec, ThinVec}; @@ -182,6 +183,16 @@ pub fn expand_test_or_bench( // creates $name: $expr let field = |name, expr| cx.field_imm(sp, Ident::from_str_and_span(name, sp), expr); + // Adds `#[coverage(off)]` to a closure, so it won't be instrumented in + // `-Cinstrument-coverage` builds. + // This requires `#[allow_internal_unstable(coverage_attribute)]` on the + // corresponding macro declaration in `core::macros`. + let coverage_off = |mut expr: P| { + assert_matches!(expr.kind, ast::ExprKind::Closure(_)); + expr.attrs.push(cx.attr_nested_word(sym::coverage, sym::off, sp)); + expr + }; + let test_fn = if is_bench { // A simple ident for a lambda let b = Ident::from_str_and_span("b", attr_sp); @@ -190,8 +201,9 @@ pub fn expand_test_or_bench( sp, cx.expr_path(test_path("StaticBenchFn")), thin_vec![ + // #[coverage(off)] // |b| self::test::assert_test_result( - cx.lambda1( + coverage_off(cx.lambda1( sp, cx.expr_call( sp, @@ -206,7 +218,7 @@ pub fn expand_test_or_bench( ], ), b, - ), // ) + )), // ) ], ) } else { @@ -214,8 +226,9 @@ pub fn expand_test_or_bench( sp, cx.expr_path(test_path("StaticTestFn")), thin_vec![ + // #[coverage(off)] // || { - cx.lambda0( + coverage_off(cx.lambda0( sp, // test::assert_test_result( cx.expr_call( @@ -230,7 +243,7 @@ pub fn expand_test_or_bench( ), // ) ], ), // } - ), // ) + )), // ) ], ) }; diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index a2437feeeb9cf..9bbaf62a5caaf 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -1596,7 +1596,7 @@ pub(crate) mod builtin { /// /// [the reference]: ../../../reference/attributes/testing.html#the-test-attribute #[stable(feature = "rust1", since = "1.0.0")] - #[allow_internal_unstable(test, rustc_attrs)] + #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)] #[rustc_builtin_macro] pub macro test($item:item) { /* compiler built-in */ @@ -1609,7 +1609,7 @@ pub(crate) mod builtin { soft, reason = "`bench` is a part of custom test frameworks which are unstable" )] - #[allow_internal_unstable(test, rustc_attrs)] + #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)] #[rustc_builtin_macro] pub macro bench($item:item) { /* compiler built-in */ diff --git a/tests/coverage/bench.cov-map b/tests/coverage/bench.cov-map index 7cdb1b641bf3d..aa702a4868185 100644 --- a/tests/coverage/bench.cov-map +++ b/tests/coverage/bench.cov-map @@ -6,11 +6,3 @@ Number of expressions: 0 Number of file 0 mappings: 1 - Code(Counter(0)) at (prev + 8, 1) to (start + 0, 39) -Function name: bench::my_bench::{closure#0} -Raw bytes (9): 0x[01, 01, 00, 01, 01, 07, 01, 00, 09] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Counter(0)) at (prev + 7, 1) to (start + 0, 9) - diff --git a/tests/coverage/bench.coverage b/tests/coverage/bench.coverage index 4642d92cc1911..64945dc641502 100644 --- a/tests/coverage/bench.coverage +++ b/tests/coverage/bench.coverage @@ -4,6 +4,6 @@ LL| | LL| |extern crate test; LL| | - LL| 1|#[bench] + LL| |#[bench] LL| 1|fn my_bench(_b: &mut test::Bencher) {} diff --git a/tests/coverage/test_harness.cov-map b/tests/coverage/test_harness.cov-map index 6940d2e282430..f75328b11c9ab 100644 --- a/tests/coverage/test_harness.cov-map +++ b/tests/coverage/test_harness.cov-map @@ -6,14 +6,6 @@ Number of expressions: 0 Number of file 0 mappings: 1 - Code(Counter(0)) at (prev + 10, 1) to (start + 0, 16) -Function name: test_harness::my_test::{closure#0} -Raw bytes (9): 0x[01, 01, 00, 01, 01, 09, 01, 00, 08] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Counter(0)) at (prev + 9, 1) to (start + 0, 8) - Function name: test_harness::unused (unused) Raw bytes (9): 0x[01, 01, 00, 01, 00, 07, 01, 00, 0f] Number of files: 1 diff --git a/tests/coverage/test_harness.coverage b/tests/coverage/test_harness.coverage index ff6009f6fce43..c3f660506fbd8 100644 --- a/tests/coverage/test_harness.coverage +++ b/tests/coverage/test_harness.coverage @@ -6,6 +6,6 @@ LL| |#[allow(dead_code)] LL| 0|fn unused() {} LL| | - LL| 1|#[test] + LL| |#[test] LL| 1|fn my_test() {} diff --git a/tests/pretty/tests-are-sorted.pp b/tests/pretty/tests-are-sorted.pp index fd9386be8f3c3..fbdad0c323f34 100644 --- a/tests/pretty/tests-are-sorted.pp +++ b/tests/pretty/tests-are-sorted.pp @@ -28,7 +28,8 @@ should_panic: test::ShouldPanic::No, test_type: test::TestType::Unknown, }, - testfn: test::StaticTestFn(|| test::assert_test_result(m_test())), + testfn: test::StaticTestFn(#[coverage(off)] || + test::assert_test_result(m_test())), }; fn m_test() {} @@ -51,7 +52,8 @@ should_panic: test::ShouldPanic::No, test_type: test::TestType::Unknown, }, - testfn: test::StaticTestFn(|| test::assert_test_result(z_test())), + testfn: test::StaticTestFn(#[coverage(off)] || + test::assert_test_result(z_test())), }; #[ignore = "not yet implemented"] fn z_test() {} @@ -75,7 +77,8 @@ should_panic: test::ShouldPanic::No, test_type: test::TestType::Unknown, }, - testfn: test::StaticTestFn(|| test::assert_test_result(a_test())), + testfn: test::StaticTestFn(#[coverage(off)] || + test::assert_test_result(a_test())), }; fn a_test() {} #[rustc_main] From df3ec4cf83c525b5615d2e75f1f3c84cde35ddc2 Mon Sep 17 00:00:00 2001 From: Michael Ciraci Date: Sat, 20 Jan 2024 13:57:46 -0600 Subject: [PATCH 05/17] aho-corasick 0.7.20 -> aho-corasick 1.0.2 Removing opener 0.5.2, and updating cargo_metadata 0.15.4 -> cargo_metadata 0.18.0 Reverting rustfmt change Reverting rustfmt patch Reverting dependency change for clippy --- Cargo.lock | 25 +++++++++++++++---------- src/tools/tidy/Cargo.toml | 2 +- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ef5811c6901d4..f93817c560bce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -310,13 +310,12 @@ dependencies = [ [[package]] name = "bstr" -version = "1.5.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a246e68bb43f6cd9db24bea052a53e40405417c5fb372e3d1a8a7f770a564ef5" +checksum = "c48f0051a4b4c5e0b6d365cd04af53aeaa209e3cc15ec2cdb69e73cc87fbd0dc" dependencies = [ "memchr", - "once_cell", - "regex-automata 0.1.10", + "regex-automata 0.4.3", "serde", ] @@ -1589,11 +1588,11 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "globset" -version = "0.4.10" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "029d74589adefde59de1a0c4f4732695c32805624aec7b68d91503d4dba79afc" +checksum = "759c97c1e17c55525b57192c06a267cda0ac5210b222d6b82189a2338fa1c13d" dependencies = [ - "aho-corasick 0.7.20", + "aho-corasick 1.0.2", "bstr", "fnv", "log", @@ -2370,9 +2369,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.5.0" +version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" +checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" dependencies = [ "compiler_builtins", "rustc-std-workspace-core", @@ -3183,6 +3182,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "regex-automata" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f" + [[package]] name = "regex-syntax" version = "0.6.29" @@ -5424,7 +5429,7 @@ name = "tidy" version = "0.1.0" dependencies = [ "cargo-platform", - "cargo_metadata 0.15.4", + "cargo_metadata 0.18.0", "ignore", "lazy_static", "miropt-test-tools", diff --git a/src/tools/tidy/Cargo.toml b/src/tools/tidy/Cargo.toml index 8c6b1eb22ecbb..d288ce81d75c9 100644 --- a/src/tools/tidy/Cargo.toml +++ b/src/tools/tidy/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" autobins = false [dependencies] -cargo_metadata = "0.15" +cargo_metadata = "0.18" cargo-platform = "0.1.2" regex = "1" miropt-test-tools = { path = "../miropt-test-tools" } From 0e3035b512fb020e5f4cee9b151a3e79a86ed144 Mon Sep 17 00:00:00 2001 From: Markus Reiter Date: Sat, 20 Jan 2024 15:11:53 +0100 Subject: [PATCH 06/17] Manually implement derived `NonZero` traits. --- library/core/src/num/nonzero.rs | 109 +++++++++++++++++++++++++++++--- 1 file changed, 101 insertions(+), 8 deletions(-) diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index bda691b16d4a7..2a81146601bea 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -1,6 +1,9 @@ //! Definitions of integer that is known not to equal zero. +use crate::cmp::Ordering; use crate::fmt; +use crate::hash::{Hash, Hasher}; +use crate::marker::StructuralPartialEq; use crate::ops::{BitOr, BitOrAssign, Div, Neg, Rem}; use crate::str::FromStr; @@ -31,13 +34,6 @@ pub trait ZeroablePrimitive: Sized + Copy + private::Sealed { type NonZero; } -#[unstable( - feature = "nonzero_internals", - reason = "implementation detail which may disappear or be replaced at any time", - issue = "none" -)] -pub(crate) type NonZero = ::NonZero; - macro_rules! impl_zeroable_primitive { ($NonZero:ident ( $primitive:ty )) => { #[unstable( @@ -71,6 +67,13 @@ impl_zeroable_primitive!(NonZeroI64(i64)); impl_zeroable_primitive!(NonZeroI128(i128)); impl_zeroable_primitive!(NonZeroIsize(isize)); +#[unstable( + feature = "nonzero_internals", + reason = "implementation detail which may disappear or be replaced at any time", + issue = "none" +)] +pub(crate) type NonZero = ::NonZero; + macro_rules! impl_nonzero_fmt { ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => { $( @@ -128,7 +131,7 @@ macro_rules! nonzero_integer { /// /// [null pointer optimization]: crate::option#representation #[$stability] - #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] + #[derive(Copy, Eq)] #[repr(transparent)] #[rustc_layout_scalar_valid_range_start(1)] #[rustc_nonnull_optimization_guaranteed] @@ -494,6 +497,96 @@ macro_rules! nonzero_integer { } } + #[$stability] + impl Clone for $Ty { + #[inline] + fn clone(&self) -> Self { + // SAFETY: The contained value is non-zero. + unsafe { Self(self.0) } + } + } + + #[$stability] + impl PartialEq for $Ty { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } + + #[inline] + fn ne(&self, other: &Self) -> bool { + self.0 != other.0 + } + } + + #[unstable(feature = "structural_match", issue = "31434")] + impl StructuralPartialEq for $Ty {} + + #[$stability] + impl PartialOrd for $Ty { + #[inline] + fn partial_cmp(&self, other: &Self) -> Option { + self.0.partial_cmp(&other.0) + } + + #[inline] + fn lt(&self, other: &Self) -> bool { + self.0 < other.0 + } + + #[inline] + fn le(&self, other: &Self) -> bool { + self.0 <= other.0 + } + + #[inline] + fn gt(&self, other: &Self) -> bool { + self.0 > other.0 + } + + #[inline] + fn ge(&self, other: &Self) -> bool { + self.0 >= other.0 + } + } + + #[$stability] + impl Ord for $Ty { + #[inline] + fn cmp(&self, other: &Self) -> Ordering { + self.0.cmp(&other.0) + } + + #[inline] + fn max(self, other: Self) -> Self { + // SAFETY: The maximum of two non-zero values is still non-zero. + unsafe { Self(self.0.max(other.0)) } + } + + #[inline] + fn min(self, other: Self) -> Self { + // SAFETY: The minimum of two non-zero values is still non-zero. + unsafe { Self(self.0.min(other.0)) } + } + + #[inline] + fn clamp(self, min: Self, max: Self) -> Self { + // SAFETY: A non-zero value clamped between two non-zero values is still non-zero. + unsafe { Self(self.0.clamp(min.0, max.0)) } + } + } + + #[$stability] + impl Hash for $Ty { + #[inline] + fn hash(&self, state: &mut H) + where + H: Hasher, + { + self.0.hash(state) + } + } + #[stable(feature = "from_nonzero", since = "1.31.0")] impl From<$Ty> for $Int { #[doc = concat!("Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`")] From 56bc5525b301bcbde05f464493cdf368e9997104 Mon Sep 17 00:00:00 2001 From: clubby789 Date: Sun, 21 Jan 2024 17:16:26 +0000 Subject: [PATCH 07/17] Bump `object` version --- Cargo.lock | 34 +++++++--------------------------- src/tools/tidy/src/deps.rs | 2 -- 2 files changed, 7 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ef5811c6901d4..2f759bf85231e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -373,9 +373,9 @@ dependencies = [ [[package]] name = "byteorder" -version = "1.4.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" @@ -2588,9 +2588,9 @@ checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" [[package]] name = "object" -version = "0.32.1" +version = "0.32.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0" +checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441" dependencies = [ "compiler_builtins", "crc32fast", @@ -4789,12 +4789,12 @@ checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06" [[package]] name = "ruzstd" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3ffab8f9715a0d455df4bbb9d21e91135aab3cd3ca187af0cd0c3c3f868fdc" +checksum = "58c4eb8a81997cf040a091d1f7e1938aeab6749d3a0dfa73af43cdc32393483d" dependencies = [ "byteorder", - "thiserror-core", + "derive_more", "twox-hash", ] @@ -5357,26 +5357,6 @@ dependencies = [ "thiserror-impl", ] -[[package]] -name = "thiserror-core" -version = "1.0.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d97345f6437bb2004cd58819d8a9ef8e36cdd7661c2abc4bbde0a7c40d9f497" -dependencies = [ - "thiserror-core-impl", -] - -[[package]] -name = "thiserror-core-impl" -version = "1.0.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10ac1c5050e43014d16b2f94d0d2ce79e65ffdd8b38d8048f9c8f6a8a6da62ac" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "thiserror-impl" version = "1.0.47" diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index b03811e5efda5..b06c072a2b0fd 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -340,8 +340,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "termize", "thin-vec", "thiserror", - "thiserror-core", - "thiserror-core-impl", "thiserror-impl", "thorin-dwp", "thread_local", From b50b333a0f17fd674ae487f7bd2baf0395b2dd15 Mon Sep 17 00:00:00 2001 From: clubby789 Date: Sun, 21 Jan 2024 17:17:34 +0000 Subject: [PATCH 08/17] Bump `uniq-langid` version --- Cargo.lock | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2f759bf85231e..a8543eceb22d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5729,9 +5729,9 @@ dependencies = [ [[package]] name = "unic-langid" -version = "0.9.1" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "398f9ad7239db44fd0f80fe068d12ff22d78354080332a5077dc6f52f14dcf2f" +checksum = "238722e6d794ed130f91f4ea33e01fcff4f188d92337a21297892521c72df516" dependencies = [ "unic-langid-impl", "unic-langid-macros", @@ -5739,18 +5739,18 @@ dependencies = [ [[package]] name = "unic-langid-impl" -version = "0.9.1" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35bfd2f2b8796545b55d7d3fd3e89a0613f68a0d1c8bc28cb7ff96b411a35ff" +checksum = "4bd55a2063fdea4ef1f8633243a7b0524cbeef1905ae04c31a1c9b9775c55bc6" dependencies = [ "tinystr", ] [[package]] name = "unic-langid-macros" -version = "0.9.1" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "055e618bf694161ffff0466d95cef3e1a5edc59f6ba1888e97801f2b4ebdc4fe" +checksum = "5c854cefb82ff2816410ce606acbad1b3af065140907b29be9229040752b83ec" dependencies = [ "proc-macro-hack", "tinystr", @@ -5760,13 +5760,13 @@ dependencies = [ [[package]] name = "unic-langid-macros-impl" -version = "0.9.1" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f5cdec05b907f4e2f6843f4354f4ce6a5bebe1a56df320a49134944477ce4d8" +checksum = "fea2a4c80deb4fb3ca51f66b5e2dd91e3642bbce52234bcf22e41668281208e4" dependencies = [ "proc-macro-hack", "quote", - "syn 1.0.109", + "syn 2.0.32", "unic-langid-impl", ] From 41dcba805d8ea2c5142cce7044c146aa15d0358c Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sun, 21 Jan 2024 15:07:11 +1100 Subject: [PATCH 09/17] coverage: Don't instrument `#[automatically_derived]` functions --- .../rustc_mir_transform/src/coverage/mod.rs | 11 +++++ tests/coverage-run-rustdoc/doctest.coverage | 5 +- tests/coverage/bad_counter_ids.cov-map | 16 ------- tests/coverage/bad_counter_ids.coverage | 2 +- tests/coverage/issue-83601.cov-map | 16 ------- tests/coverage/issue-83601.coverage | 3 +- tests/coverage/issue-84561.cov-map | 8 ---- tests/coverage/issue-84561.coverage | 2 +- tests/coverage/partial_eq.cov-map | 48 ------------------- tests/coverage/partial_eq.coverage | 3 +- 10 files changed, 17 insertions(+), 97 deletions(-) diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index a11d224e8f1b5..a495dcdbc4e19 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -351,7 +351,18 @@ fn is_eligible_for_coverage(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { return false; } + // Don't instrument functions with `#[automatically_derived]` on their + // enclosing impl block, on the assumption that most users won't care about + // coverage for derived impls. + if let Some(impl_of) = tcx.impl_of_method(def_id.to_def_id()) + && tcx.is_automatically_derived(impl_of) + { + trace!("InstrumentCoverage skipped for {def_id:?} (automatically derived)"); + return false; + } + if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NO_COVERAGE) { + trace!("InstrumentCoverage skipped for {def_id:?} (`#[coverage(off)]`)"); return false; } diff --git a/tests/coverage-run-rustdoc/doctest.coverage b/tests/coverage-run-rustdoc/doctest.coverage index 5797784f411cc..5125dc075ee2c 100644 --- a/tests/coverage-run-rustdoc/doctest.coverage +++ b/tests/coverage-run-rustdoc/doctest.coverage @@ -34,8 +34,7 @@ $DIR/doctest.rs: LL| |//! LL| |//! doctest returning a result: LL| 1|//! ``` - LL| 2|//! #[derive(Debug, PartialEq)] - ^1 + LL| 1|//! #[derive(Debug, PartialEq)] LL| 1|//! struct SomeError { LL| 1|//! msg: String, LL| 1|//! } @@ -63,7 +62,7 @@ $DIR/doctest.rs: LL| 1|//! println!("called some_func()"); LL| 1|//! } LL| |//! - LL| 0|//! #[derive(Debug)] + LL| |//! #[derive(Debug)] LL| |//! struct SomeError; LL| |//! LL| |//! extern crate doctest_crate; diff --git a/tests/coverage/bad_counter_ids.cov-map b/tests/coverage/bad_counter_ids.cov-map index 0b8081acfa6d8..3b51e3ef9de66 100644 --- a/tests/coverage/bad_counter_ids.cov-map +++ b/tests/coverage/bad_counter_ids.cov-map @@ -1,19 +1,3 @@ -Function name: ::eq -Raw bytes (9): 0x[01, 01, 00, 01, 01, 0c, 11, 00, 1a] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Counter(0)) at (prev + 12, 17) to (start + 0, 26) - -Function name: ::fmt -Raw bytes (9): 0x[01, 01, 00, 01, 01, 0c, 0a, 00, 0f] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Counter(0)) at (prev + 12, 10) to (start + 0, 15) - Function name: bad_counter_ids::eq_bad Raw bytes (14): 0x[01, 01, 00, 02, 01, 23, 01, 02, 1f, 00, 03, 01, 00, 02] Number of files: 1 diff --git a/tests/coverage/bad_counter_ids.coverage b/tests/coverage/bad_counter_ids.coverage index d69ebf160ea64..5474ec2f78552 100644 --- a/tests/coverage/bad_counter_ids.coverage +++ b/tests/coverage/bad_counter_ids.coverage @@ -9,7 +9,7 @@ LL| |// a too-large counter ID and silently discard the entire function from its LL| |// coverage reports. LL| | - LL| 8|#[derive(Debug, PartialEq, Eq)] + LL| |#[derive(Debug, PartialEq, Eq)] LL| |struct Foo(u32); LL| | LL| 1|fn eq_good() { diff --git a/tests/coverage/issue-83601.cov-map b/tests/coverage/issue-83601.cov-map index f5db3a89750c7..f2447e3c92c8a 100644 --- a/tests/coverage/issue-83601.cov-map +++ b/tests/coverage/issue-83601.cov-map @@ -1,19 +1,3 @@ -Function name: ::eq -Raw bytes (9): 0x[01, 01, 00, 01, 01, 03, 11, 00, 1a] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Counter(0)) at (prev + 3, 17) to (start + 0, 26) - -Function name: ::fmt -Raw bytes (9): 0x[01, 01, 00, 01, 01, 03, 0a, 00, 0f] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Counter(0)) at (prev + 3, 10) to (start + 0, 15) - Function name: issue_83601::main Raw bytes (21): 0x[01, 01, 01, 05, 09, 03, 01, 06, 01, 02, 1c, 05, 03, 09, 01, 1c, 02, 02, 05, 03, 02] Number of files: 1 diff --git a/tests/coverage/issue-83601.coverage b/tests/coverage/issue-83601.coverage index 7995332cad339..e050106e6f0b0 100644 --- a/tests/coverage/issue-83601.coverage +++ b/tests/coverage/issue-83601.coverage @@ -1,7 +1,6 @@ LL| |// Shows that rust-lang/rust/83601 is resolved LL| | - LL| 3|#[derive(Debug, PartialEq, Eq)] - ^2 + LL| |#[derive(Debug, PartialEq, Eq)] LL| |struct Foo(u32); LL| | LL| 1|fn main() { diff --git a/tests/coverage/issue-84561.cov-map b/tests/coverage/issue-84561.cov-map index 6d577b3d4851d..88436964af0f7 100644 --- a/tests/coverage/issue-84561.cov-map +++ b/tests/coverage/issue-84561.cov-map @@ -1,11 +1,3 @@ -Function name: ::eq -Raw bytes (9): 0x[01, 01, 00, 01, 01, 04, 0a, 00, 13] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Counter(0)) at (prev + 4, 10) to (start + 0, 19) - Function name: ::fmt Raw bytes (29): 0x[01, 01, 02, 01, 05, 05, 02, 04, 01, 8a, 01, 05, 01, 25, 05, 01, 25, 00, 26, 02, 01, 09, 00, 0f, 07, 01, 05, 00, 06] Number of files: 1 diff --git a/tests/coverage/issue-84561.coverage b/tests/coverage/issue-84561.coverage index 9080d95eff5fc..90a2d069d3949 100644 --- a/tests/coverage/issue-84561.coverage +++ b/tests/coverage/issue-84561.coverage @@ -1,7 +1,7 @@ LL| |// This demonstrated Issue #84561: function-like macros produce unintuitive coverage results. LL| | LL| |// failure-status: 101 - LL| 21|#[derive(PartialEq, Eq)] + LL| |#[derive(PartialEq, Eq)] LL| |struct Foo(u32); LL| | LL| |#[rustfmt::skip] diff --git a/tests/coverage/partial_eq.cov-map b/tests/coverage/partial_eq.cov-map index 5e4aae0260b5c..80670fbfa5a75 100644 --- a/tests/coverage/partial_eq.cov-map +++ b/tests/coverage/partial_eq.cov-map @@ -1,51 +1,3 @@ -Function name: ::clone (unused) -Raw bytes (9): 0x[01, 01, 00, 01, 00, 04, 0a, 00, 0f] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 4, 10) to (start + 0, 15) - -Function name: ::cmp (unused) -Raw bytes (14): 0x[01, 01, 00, 02, 00, 04, 33, 00, 34, 00, 00, 35, 00, 36] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 2 -- Code(Zero) at (prev + 4, 51) to (start + 0, 52) -- Code(Zero) at (prev + 0, 53) to (start + 0, 54) - -Function name: ::eq (unused) -Raw bytes (14): 0x[01, 01, 00, 02, 00, 04, 18, 00, 19, 00, 00, 20, 00, 21] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 2 -- Code(Zero) at (prev + 4, 24) to (start + 0, 25) -- Code(Zero) at (prev + 0, 32) to (start + 0, 33) - -Function name: ::partial_cmp -Raw bytes (22): 0x[01, 01, 04, 07, 0b, 00, 09, 0f, 15, 00, 11, 02, 01, 04, 27, 00, 28, 03, 00, 30, 00, 31] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 4 -- expression 0 operands: lhs = Expression(1, Add), rhs = Expression(2, Add) -- expression 1 operands: lhs = Zero, rhs = Counter(2) -- expression 2 operands: lhs = Expression(3, Add), rhs = Counter(5) -- expression 3 operands: lhs = Zero, rhs = Counter(4) -Number of file 0 mappings: 2 -- Code(Counter(0)) at (prev + 4, 39) to (start + 0, 40) -- Code(Expression(0, Add)) at (prev + 0, 48) to (start + 0, 49) - = ((Zero + c2) + ((Zero + c4) + c5)) - -Function name: ::fmt -Raw bytes (9): 0x[01, 01, 00, 01, 01, 04, 11, 00, 16] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Counter(0)) at (prev + 4, 17) to (start + 0, 22) - Function name: ::new Raw bytes (9): 0x[01, 01, 00, 01, 01, 0c, 05, 06, 06] Number of files: 1 diff --git a/tests/coverage/partial_eq.coverage b/tests/coverage/partial_eq.coverage index 6e3696386a773..9de1c933570cb 100644 --- a/tests/coverage/partial_eq.coverage +++ b/tests/coverage/partial_eq.coverage @@ -1,8 +1,7 @@ LL| |// This test confirms an earlier problem was resolved, supporting the MIR graph generated by the LL| |// structure of this test. LL| | - LL| 2|#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] - ^0 ^0 ^0 ^1 ^1 ^0^0 + LL| |#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] LL| |pub struct Version { LL| | major: usize, LL| | minor: usize, From f58af9ba28f1bb49f880da43227c65cc10673be2 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 9 Jan 2024 11:12:30 +0000 Subject: [PATCH 10/17] Add a simpler and more targetted code path for impl trait in assoc items --- .../rustc_hir_analysis/src/collect/type_of.rs | 6 +- .../src/collect/type_of/opaque.rs | 71 +++++++++++++++++-- compiler/rustc_middle/src/query/mod.rs | 9 +++ compiler/rustc_ty_utils/src/opaque_types.rs | 10 ++- 4 files changed, 88 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index bfa9dc42422cb..3674a760cbf9d 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -530,9 +530,13 @@ pub(super) fn type_of_opaque( Ok(ty::EarlyBinder::bind(match tcx.hir_node_by_def_id(def_id) { Node::Item(item) => match item.kind { ItemKind::OpaqueTy(OpaqueTy { - origin: hir::OpaqueTyOrigin::TyAlias { .. }, + origin: hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false }, .. }) => opaque::find_opaque_ty_constraints_for_tait(tcx, def_id), + ItemKind::OpaqueTy(OpaqueTy { + origin: hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: true }, + .. + }) => opaque::find_opaque_ty_constraints_for_impl_trait_in_assoc_type(tcx, def_id), // Opaque types desugared from `impl Trait`. ItemKind::OpaqueTy(&OpaqueTy { origin: diff --git a/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs b/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs index 85093bc12b378..51b2401531c7a 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs @@ -23,6 +23,60 @@ pub fn test_opaque_hidden_types(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> res } +/// Checks "defining uses" of opaque `impl Trait` in associated types. +/// These can only be defined by associated items of the same trait. +#[instrument(skip(tcx), level = "debug")] +pub(super) fn find_opaque_ty_constraints_for_impl_trait_in_assoc_type( + tcx: TyCtxt<'_>, + def_id: LocalDefId, +) -> Ty<'_> { + let mut parent_def_id = def_id; + while tcx.def_kind(parent_def_id) == def::DefKind::OpaqueTy { + // Account for `type Alias = impl Trait;` (#116031) + parent_def_id = tcx.local_parent(parent_def_id); + } + let impl_def_id = tcx.local_parent(parent_def_id); + match tcx.def_kind(impl_def_id) { + DefKind::Impl { .. } => {} + other => bug!("invalid impl trait in assoc type parent: {other:?}"), + } + + let mut locator = TaitConstraintLocator { def_id, tcx, found: None, typeck_types: vec![] }; + + for &assoc_id in tcx.associated_item_def_ids(impl_def_id) { + let assoc = tcx.associated_item(assoc_id); + match assoc.kind { + ty::AssocKind::Const | ty::AssocKind::Fn => { + locator.check(assoc_id.expect_local(), true) + } + // Associated types don't have bodies, so they can't constrain hidden types + ty::AssocKind::Type => {} + } + } + + if let Some(hidden) = locator.found { + // Only check against typeck if we didn't already error + if !hidden.ty.references_error() { + for concrete_type in locator.typeck_types { + if concrete_type.ty != tcx.erase_regions(hidden.ty) + && !(concrete_type, hidden).references_error() + { + hidden.report_mismatch(&concrete_type, def_id, tcx).emit(); + } + } + } + + hidden.ty + } else { + let reported = tcx.dcx().emit_err(UnconstrainedOpaqueType { + span: tcx.def_span(def_id), + name: tcx.item_name(parent_def_id.to_def_id()), + what: "impl", + }); + Ty::new_error(tcx, reported) + } +} + /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions /// laid for "higher-order pattern unification". /// This ensures that inference is tractable. @@ -130,7 +184,7 @@ struct TaitConstraintLocator<'tcx> { impl TaitConstraintLocator<'_> { #[instrument(skip(self), level = "debug")] - fn check(&mut self, item_def_id: LocalDefId) { + fn check(&mut self, item_def_id: LocalDefId, impl_trait_in_assoc_type: bool) { // Don't try to check items that cannot possibly constrain the type. if !self.tcx.has_typeck_results(item_def_id) { debug!("no constraint: no typeck results"); @@ -182,7 +236,12 @@ impl TaitConstraintLocator<'_> { continue; } constrained = true; - if !self.tcx.opaque_types_defined_by(item_def_id).contains(&self.def_id) { + let opaque_types_defined_by = if impl_trait_in_assoc_type { + self.tcx.impl_trait_in_assoc_types_defined_by(item_def_id) + } else { + self.tcx.opaque_types_defined_by(item_def_id) + }; + if !opaque_types_defined_by.contains(&self.def_id) { self.tcx.dcx().emit_err(TaitForwardCompat { span: hidden_type.span, item_span: self @@ -240,7 +299,7 @@ impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> { } fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) { if let hir::ExprKind::Closure(closure) = ex.kind { - self.check(closure.def_id); + self.check(closure.def_id, false); } intravisit::walk_expr(self, ex); } @@ -248,7 +307,7 @@ impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> { trace!(?it.owner_id); // The opaque type itself or its children are not within its reveal scope. if it.owner_id.def_id != self.def_id { - self.check(it.owner_id.def_id); + self.check(it.owner_id.def_id, false); intravisit::walk_item(self, it); } } @@ -256,13 +315,13 @@ impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> { trace!(?it.owner_id); // The opaque type itself or its children are not within its reveal scope. if it.owner_id.def_id != self.def_id { - self.check(it.owner_id.def_id); + self.check(it.owner_id.def_id, false); intravisit::walk_impl_item(self, it); } } fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) { trace!(?it.owner_id); - self.check(it.owner_id.def_id); + self.check(it.owner_id.def_id, false); intravisit::walk_trait_item(self, it); } fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) { diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index a9dc7f5d11a20..23daefd5a65b9 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -343,6 +343,15 @@ rustc_queries! { } } + query impl_trait_in_assoc_types_defined_by( + key: LocalDefId + ) -> &'tcx ty::List { + desc { + |tcx| "computing the opaque types defined by `{}`", + tcx.def_path_str(key.to_def_id()) + } + } + /// Returns the list of bounds that can be used for /// `SelectionCandidate::ProjectionCandidate(_)` and /// `ProjectionTyCandidate::TraitDef`. diff --git a/compiler/rustc_ty_utils/src/opaque_types.rs b/compiler/rustc_ty_utils/src/opaque_types.rs index 0bb833c66fa76..eae4c57fc9989 100644 --- a/compiler/rustc_ty_utils/src/opaque_types.rs +++ b/compiler/rustc_ty_utils/src/opaque_types.rs @@ -272,6 +272,13 @@ impl<'tcx> TypeVisitor> for OpaqueTypeCollector<'tcx> { } } +fn impl_trait_in_assoc_types_defined_by<'tcx>( + tcx: TyCtxt<'tcx>, + item: LocalDefId, +) -> &'tcx ty::List { + opaque_types_defined_by(tcx, item) +} + fn opaque_types_defined_by<'tcx>( tcx: TyCtxt<'tcx>, item: LocalDefId, @@ -321,5 +328,6 @@ fn opaque_types_defined_by<'tcx>( } pub(super) fn provide(providers: &mut Providers) { - *providers = Providers { opaque_types_defined_by, ..*providers }; + *providers = + Providers { opaque_types_defined_by, impl_trait_in_assoc_types_defined_by, ..*providers }; } From ac332bd9163990491d225e2a24ff92af89030dac Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 9 Jan 2024 11:16:32 +0000 Subject: [PATCH 11/17] Pull opaque type check into a separate method --- compiler/rustc_ty_utils/src/opaque_types.rs | 125 ++++++++++---------- 1 file changed, 64 insertions(+), 61 deletions(-) diff --git a/compiler/rustc_ty_utils/src/opaque_types.rs b/compiler/rustc_ty_utils/src/opaque_types.rs index eae4c57fc9989..1d9c0405b7d76 100644 --- a/compiler/rustc_ty_utils/src/opaque_types.rs +++ b/compiler/rustc_ty_utils/src/opaque_types.rs @@ -118,6 +118,69 @@ impl<'tcx> OpaqueTypeCollector<'tcx> { } TaitInBodyFinder { collector: self }.visit_expr(body); } + + fn visit_opaque_ty(&mut self, alias_ty: &ty::AliasTy<'tcx>) { + if !self.seen.insert(alias_ty.def_id.expect_local()) { + return; + } + + // TAITs outside their defining scopes are ignored. + let origin = self.tcx.opaque_type_origin(alias_ty.def_id.expect_local()); + trace!(?origin); + match origin { + rustc_hir::OpaqueTyOrigin::FnReturn(_) | rustc_hir::OpaqueTyOrigin::AsyncFn(_) => {} + rustc_hir::OpaqueTyOrigin::TyAlias { in_assoc_ty } => { + if !in_assoc_ty { + if !self.check_tait_defining_scope(alias_ty.def_id.expect_local()) { + return; + } + } + } + } + + self.opaques.push(alias_ty.def_id.expect_local()); + + let parent_count = self.tcx.generics_of(alias_ty.def_id).parent_count; + // Only check that the parent generics of the TAIT/RPIT are unique. + // the args owned by the opaque are going to always be duplicate + // lifetime params for RPITs, and empty for TAITs. + match self + .tcx + .uses_unique_generic_params(&alias_ty.args[..parent_count], CheckRegions::FromFunction) + { + Ok(()) => { + // FIXME: implement higher kinded lifetime bounds on nested opaque types. They are not + // supported at all, so this is sound to do, but once we want to support them, you'll + // start seeing the error below. + + // Collect opaque types nested within the associated type bounds of this opaque type. + // We use identity args here, because we already know that the opaque type uses + // only generic parameters, and thus substituting would not give us more information. + for (pred, span) in self + .tcx + .explicit_item_bounds(alias_ty.def_id) + .instantiate_identity_iter_copied() + { + trace!(?pred); + self.visit_spanned(span, pred); + } + } + Err(NotUniqueParam::NotParam(arg)) => { + self.tcx.dcx().emit_err(NotParam { + arg, + span: self.span(), + opaque_span: self.tcx.def_span(alias_ty.def_id), + }); + } + Err(NotUniqueParam::DuplicateParam(arg)) => { + self.tcx.dcx().emit_err(DuplicateArg { + arg, + span: self.span(), + opaque_span: self.tcx.def_span(alias_ty.def_id), + }); + } + } + } } impl<'tcx> super::sig_types::SpannedTypeVisitor<'tcx> for OpaqueTypeCollector<'tcx> { @@ -134,67 +197,7 @@ impl<'tcx> TypeVisitor> for OpaqueTypeCollector<'tcx> { t.super_visit_with(self)?; match t.kind() { ty::Alias(ty::Opaque, alias_ty) if alias_ty.def_id.is_local() => { - if !self.seen.insert(alias_ty.def_id.expect_local()) { - return ControlFlow::Continue(()); - } - - // TAITs outside their defining scopes are ignored. - let origin = self.tcx.opaque_type_origin(alias_ty.def_id.expect_local()); - trace!(?origin); - match origin { - rustc_hir::OpaqueTyOrigin::FnReturn(_) - | rustc_hir::OpaqueTyOrigin::AsyncFn(_) => {} - rustc_hir::OpaqueTyOrigin::TyAlias { in_assoc_ty } => { - if !in_assoc_ty { - if !self.check_tait_defining_scope(alias_ty.def_id.expect_local()) { - return ControlFlow::Continue(()); - } - } - } - } - - self.opaques.push(alias_ty.def_id.expect_local()); - - let parent_count = self.tcx.generics_of(alias_ty.def_id).parent_count; - // Only check that the parent generics of the TAIT/RPIT are unique. - // the args owned by the opaque are going to always be duplicate - // lifetime params for RPITs, and empty for TAITs. - match self.tcx.uses_unique_generic_params( - &alias_ty.args[..parent_count], - CheckRegions::FromFunction, - ) { - Ok(()) => { - // FIXME: implement higher kinded lifetime bounds on nested opaque types. They are not - // supported at all, so this is sound to do, but once we want to support them, you'll - // start seeing the error below. - - // Collect opaque types nested within the associated type bounds of this opaque type. - // We use identity args here, because we already know that the opaque type uses - // only generic parameters, and thus substituting would not give us more information. - for (pred, span) in self - .tcx - .explicit_item_bounds(alias_ty.def_id) - .instantiate_identity_iter_copied() - { - trace!(?pred); - self.visit_spanned(span, pred); - } - } - Err(NotUniqueParam::NotParam(arg)) => { - self.tcx.dcx().emit_err(NotParam { - arg, - span: self.span(), - opaque_span: self.tcx.def_span(alias_ty.def_id), - }); - } - Err(NotUniqueParam::DuplicateParam(arg)) => { - self.tcx.dcx().emit_err(DuplicateArg { - arg, - span: self.span(), - opaque_span: self.tcx.def_span(alias_ty.def_id), - }); - } - } + self.visit_opaque_ty(alias_ty); } ty::Alias(ty::Weak, alias_ty) if alias_ty.def_id.is_local() => { self.tcx From f75361fec7aecfcede9cf6f0b97f2b1e7756e47b Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 9 Jan 2024 11:28:05 +0000 Subject: [PATCH 12/17] Limit impl trait in assoc type defining scope --- compiler/rustc_ty_utils/src/opaque_types.rs | 80 ++++++++++++++++++- .../hidden_behind_struct_field2.rs | 8 +- .../hidden_behind_struct_field2.stderr | 15 ++++ 3 files changed, 98 insertions(+), 5 deletions(-) create mode 100644 tests/ui/type-alias-impl-trait/hidden_behind_struct_field2.stderr diff --git a/compiler/rustc_ty_utils/src/opaque_types.rs b/compiler/rustc_ty_utils/src/opaque_types.rs index 1d9c0405b7d76..ef67317a601ac 100644 --- a/compiler/rustc_ty_utils/src/opaque_types.rs +++ b/compiler/rustc_ty_utils/src/opaque_types.rs @@ -275,11 +275,89 @@ impl<'tcx> TypeVisitor> for OpaqueTypeCollector<'tcx> { } } +struct ImplTraitInAssocTypeCollector<'tcx>(OpaqueTypeCollector<'tcx>); + +impl<'tcx> super::sig_types::SpannedTypeVisitor<'tcx> for ImplTraitInAssocTypeCollector<'tcx> { + #[instrument(skip(self), ret, level = "trace")] + fn visit(&mut self, span: Span, value: impl TypeVisitable>) -> ControlFlow { + let old = self.0.span; + self.0.span = Some(span); + value.visit_with(self); + self.0.span = old; + + ControlFlow::Continue(()) + } +} + +impl<'tcx> TypeVisitor> for ImplTraitInAssocTypeCollector<'tcx> { + #[instrument(skip(self), ret, level = "trace")] + fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow { + t.super_visit_with(self)?; + match t.kind() { + ty::Alias(ty::Opaque, alias_ty) if alias_ty.def_id.is_local() => { + self.0.visit_opaque_ty(alias_ty); + } + ty::Alias(ty::Projection, alias_ty) => { + // This avoids having to do normalization of `Self::AssocTy` by only + // supporting the case of a method defining opaque types from assoc types + // in the same impl block. + let parent_trait_ref = self + .0 + .parent_trait_ref() + .expect("impl trait in assoc type collector used on non-assoc item"); + // If the trait ref of the associated item and the impl differs, + // then we can't use the impl's identity substitutions below, so + // just skip. + if alias_ty.trait_ref(self.0.tcx) == parent_trait_ref { + let parent = self.0.parent().expect("we should have a parent here"); + + for &assoc in self.0.tcx.associated_items(parent).in_definition_order() { + trace!(?assoc); + if assoc.trait_item_def_id != Some(alias_ty.def_id) { + continue; + } + + // If the type is further specializable, then the type_of + // is not actually correct below. + if !assoc.defaultness(self.0.tcx).is_final() { + continue; + } + + let impl_args = alias_ty.args.rebase_onto( + self.0.tcx, + parent_trait_ref.def_id, + ty::GenericArgs::identity_for_item(self.0.tcx, parent), + ); + + if check_args_compatible(self.0.tcx, assoc, impl_args) { + return self + .0 + .tcx + .type_of(assoc.def_id) + .instantiate(self.0.tcx, impl_args) + .visit_with(self); + } else { + self.0.tcx.dcx().span_delayed_bug( + self.0.tcx.def_span(assoc.def_id), + "item had incorrect args", + ); + } + } + } + } + _ => trace!(kind=?t.kind()), + } + ControlFlow::Continue(()) + } +} + fn impl_trait_in_assoc_types_defined_by<'tcx>( tcx: TyCtxt<'tcx>, item: LocalDefId, ) -> &'tcx ty::List { - opaque_types_defined_by(tcx, item) + let mut collector = ImplTraitInAssocTypeCollector(OpaqueTypeCollector::new(tcx, item)); + super::sig_types::walk_types(tcx, item, &mut collector); + tcx.mk_local_def_ids(&collector.0.opaques) } fn opaque_types_defined_by<'tcx>( diff --git a/tests/ui/type-alias-impl-trait/hidden_behind_struct_field2.rs b/tests/ui/type-alias-impl-trait/hidden_behind_struct_field2.rs index e440dce5e514f..4c881dd133086 100644 --- a/tests/ui/type-alias-impl-trait/hidden_behind_struct_field2.rs +++ b/tests/ui/type-alias-impl-trait/hidden_behind_struct_field2.rs @@ -1,9 +1,8 @@ -//! This test shows that we can even follow projections -//! into associated types of the same impl if they are -//! indirectly mentioned in a struct field. +//! This test shows that we do not treat opaque types +//! as defined by a method if the opaque type is +//! only indirectly mentioned in a struct field. #![feature(impl_trait_in_assoc_type)] -// check-pass struct Bar; @@ -16,6 +15,7 @@ impl Trait for Bar { type Assoc = impl std::fmt::Debug; fn foo() -> Foo { Foo { field: () } + //~^ ERROR: item constrains opaque type that is not in its signature } } diff --git a/tests/ui/type-alias-impl-trait/hidden_behind_struct_field2.stderr b/tests/ui/type-alias-impl-trait/hidden_behind_struct_field2.stderr new file mode 100644 index 0000000000000..5c53dfa3a7500 --- /dev/null +++ b/tests/ui/type-alias-impl-trait/hidden_behind_struct_field2.stderr @@ -0,0 +1,15 @@ +error: item constrains opaque type that is not in its signature + --> $DIR/hidden_behind_struct_field2.rs:17:22 + | +LL | Foo { field: () } + | ^^ + | + = note: this item must mention the opaque type in its signature in order to be able to register hidden types +note: this item must mention the opaque type in its signature in order to be able to register hidden types + --> $DIR/hidden_behind_struct_field2.rs:16:8 + | +LL | fn foo() -> Foo { + | ^^^ + +error: aborting due to 1 previous error + From 4e0769956bf5c966fccb54acbb0866f029c79818 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 9 Jan 2024 14:12:59 +0000 Subject: [PATCH 13/17] Add some tests --- tests/ui/impl-trait/rpit/early_bound.rs | 13 ++++++ tests/ui/impl-trait/rpit/early_bound.stderr | 26 ++++++++++++ ...pl_trait_in_trait_defined_outside_trait.rs | 38 +++++++++++++++++ ...rait_in_trait_defined_outside_trait.stderr | 41 +++++++++++++++++++ ...l_trait_in_trait_defined_outside_trait2.rs | 22 ++++++++++ ...ait_in_trait_defined_outside_trait2.stderr | 17 ++++++++ ...l_trait_in_trait_defined_outside_trait3.rs | 38 +++++++++++++++++ .../in-assoc-ty-early-bound.rs | 17 ++++++++ .../in-assoc-ty-early-bound.stderr | 13 ++++++ .../in-assoc-ty-early-bound2.rs | 21 ++++++++++ .../in-assoc-ty-early-bound2.stderr | 22 ++++++++++ 11 files changed, 268 insertions(+) create mode 100644 tests/ui/impl-trait/rpit/early_bound.rs create mode 100644 tests/ui/impl-trait/rpit/early_bound.stderr create mode 100644 tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait.rs create mode 100644 tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait.stderr create mode 100644 tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait2.rs create mode 100644 tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait2.stderr create mode 100644 tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait3.rs create mode 100644 tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound.rs create mode 100644 tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound.stderr create mode 100644 tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound2.rs create mode 100644 tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound2.stderr diff --git a/tests/ui/impl-trait/rpit/early_bound.rs b/tests/ui/impl-trait/rpit/early_bound.rs new file mode 100644 index 0000000000000..03bd64d4d76d0 --- /dev/null +++ b/tests/ui/impl-trait/rpit/early_bound.rs @@ -0,0 +1,13 @@ +use std::convert::identity; + +fn test<'a: 'a>(n: bool) -> impl Sized + 'a { + //~^ ERROR concrete type differs from previous defining opaque type use + let true = n else { loop {} }; + let _ = || { + let _ = identity::<&'a ()>(test(false)); + //~^ ERROR hidden type for `impl Sized + 'a` captures lifetime that does not appear in bounds + }; + loop {} +} + +fn main() {} diff --git a/tests/ui/impl-trait/rpit/early_bound.stderr b/tests/ui/impl-trait/rpit/early_bound.stderr new file mode 100644 index 0000000000000..815368f250e35 --- /dev/null +++ b/tests/ui/impl-trait/rpit/early_bound.stderr @@ -0,0 +1,26 @@ +error[E0700]: hidden type for `impl Sized + 'a` captures lifetime that does not appear in bounds + --> $DIR/early_bound.rs:7:17 + | +LL | fn test<'a: 'a>(n: bool) -> impl Sized + 'a { + | -- --------------- opaque type defined here + | | + | hidden type `&'a ()` captures the lifetime `'a` as defined here +... +LL | let _ = identity::<&'a ()>(test(false)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: concrete type differs from previous defining opaque type use + --> $DIR/early_bound.rs:3:29 + | +LL | fn test<'a: 'a>(n: bool) -> impl Sized + 'a { + | ^^^^^^^^^^^^^^^ expected `&()`, got `()` + | +note: previous use here + --> $DIR/early_bound.rs:7:36 + | +LL | let _ = identity::<&'a ()>(test(false)); + | ^^^^^^^^^^^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0700`. diff --git a/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait.rs b/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait.rs new file mode 100644 index 0000000000000..a788563ab779e --- /dev/null +++ b/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait.rs @@ -0,0 +1,38 @@ +//! Check that we cannot instantiate a hidden type in the body +//! of an assoc fn or const unless mentioned in the signature. + +#![feature(impl_trait_in_assoc_type)] + +trait Trait: Sized { + type Assoc; + fn foo(); + fn bar() -> Self::Assoc; +} + +impl Trait for () { + type Assoc = impl std::fmt::Debug; + fn foo() { + let x: Self::Assoc = 42; //~ ERROR: mismatched types + } + fn bar() -> Self::Assoc { + "" + } +} + +trait Trait2: Sized { + type Assoc; + const FOO: (); + fn bar() -> Self::Assoc; +} + +impl Trait2 for () { + type Assoc = impl std::fmt::Debug; + const FOO: () = { + let x: Self::Assoc = 42; //~ ERROR: mismatched types + }; + fn bar() -> Self::Assoc { + "" + } +} + +fn main() {} diff --git a/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait.stderr b/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait.stderr new file mode 100644 index 0000000000000..1d7a97c536713 --- /dev/null +++ b/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait.stderr @@ -0,0 +1,41 @@ +error[E0308]: mismatched types + --> $DIR/impl_trait_in_trait_defined_outside_trait.rs:15:30 + | +LL | type Assoc = impl std::fmt::Debug; + | -------------------- the expected opaque type +LL | fn foo() { +LL | let x: Self::Assoc = 42; + | ----------- ^^ expected opaque type, found integer + | | + | expected due to this + | + = note: expected opaque type `<() as Trait>::Assoc` + found type `{integer}` +note: this item must have the opaque type in its signature in order to be able to register hidden types + --> $DIR/impl_trait_in_trait_defined_outside_trait.rs:14:8 + | +LL | fn foo() { + | ^^^ + +error[E0308]: mismatched types + --> $DIR/impl_trait_in_trait_defined_outside_trait.rs:31:30 + | +LL | type Assoc = impl std::fmt::Debug; + | -------------------- the expected opaque type +LL | const FOO: () = { +LL | let x: Self::Assoc = 42; + | ----------- ^^ expected opaque type, found integer + | | + | expected due to this + | + = note: expected opaque type `<() as Trait2>::Assoc` + found type `{integer}` +note: this item must have the opaque type in its signature in order to be able to register hidden types + --> $DIR/impl_trait_in_trait_defined_outside_trait.rs:30:11 + | +LL | const FOO: () = { + | ^^^ + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait2.rs b/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait2.rs new file mode 100644 index 0000000000000..77cdca198daea --- /dev/null +++ b/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait2.rs @@ -0,0 +1,22 @@ +//! Check that we cannot instantiate a hidden type from another assoc type. + +#![feature(impl_trait_in_assoc_type)] + +trait Trait: Sized { + type Assoc; + type Foo; + fn foo() -> Self::Assoc; +} + +impl Trait for () { + type Assoc = impl std::fmt::Debug; + type Foo = [(); { + let x: Self::Assoc = 42; //~ ERROR: mismatched types + 3 + }]; + fn foo() -> Self::Assoc { + "" + } +} + +fn main() {} diff --git a/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait2.stderr b/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait2.stderr new file mode 100644 index 0000000000000..708c3f28d2d2e --- /dev/null +++ b/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait2.stderr @@ -0,0 +1,17 @@ +error[E0308]: mismatched types + --> $DIR/impl_trait_in_trait_defined_outside_trait2.rs:14:30 + | +LL | type Assoc = impl std::fmt::Debug; + | -------------------- the expected opaque type +LL | type Foo = [(); { +LL | let x: Self::Assoc = 42; + | ----------- ^^ expected opaque type, found integer + | | + | expected due to this + | + = note: expected opaque type `<() as Trait>::Assoc` + found type `{integer}` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait3.rs b/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait3.rs new file mode 100644 index 0000000000000..dfcf733653376 --- /dev/null +++ b/tests/ui/type-alias-impl-trait/impl_trait_in_trait_defined_outside_trait3.rs @@ -0,0 +1,38 @@ +//! Check that non-defining assoc items can use the opaque type +//! opaquely. + +// check-pass + +#![feature(impl_trait_in_assoc_type)] + +trait Trait: Sized { + type Assoc; + fn foo(); + fn bar() -> Self::Assoc; +} + +impl Trait for () { + type Assoc = impl std::fmt::Debug; + fn foo() { + let x: Self::Assoc = Self::bar(); + } + fn bar() -> Self::Assoc { + "" + } +} + +trait Trait2: Sized { + type Assoc; + const FOO: (); + const BAR: Self::Assoc; +} + +impl Trait2 for () { + type Assoc = impl Copy; + const FOO: () = { + let x: Self::Assoc = Self::BAR; + }; + const BAR: Self::Assoc = ""; +} + +fn main() {} diff --git a/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound.rs b/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound.rs new file mode 100644 index 0000000000000..baeba1d3de635 --- /dev/null +++ b/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound.rs @@ -0,0 +1,17 @@ +#![feature(impl_trait_in_assoc_type)] + +trait Foo { + type Assoc<'a, 'b>; + fn bar<'a: 'a, 'b: 'b>(_: &'a ()) -> Self::Assoc<'a, 'b>; +} + +impl Foo for () { + type Assoc<'a, 'b> = impl Sized; + fn bar<'a: 'a, 'b: 'b>(x: &'a ()) -> Self::Assoc<'a, 'b> { + let closure = |x: &'a ()| -> Self::Assoc<'b, 'a> { x }; + //~^ ERROR `<() as Foo>::Assoc<'b, 'a>` captures lifetime that does not appear in bounds + x + } +} + +fn main() {} diff --git a/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound.stderr b/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound.stderr new file mode 100644 index 0000000000000..a7d3e7f0be403 --- /dev/null +++ b/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound.stderr @@ -0,0 +1,13 @@ +error[E0700]: hidden type for `<() as Foo>::Assoc<'b, 'a>` captures lifetime that does not appear in bounds + --> $DIR/in-assoc-ty-early-bound.rs:11:60 + | +LL | type Assoc<'a, 'b> = impl Sized; + | ---------- opaque type defined here +LL | fn bar<'a: 'a, 'b: 'b>(x: &'a ()) -> Self::Assoc<'a, 'b> { + | -- hidden type `&'a ()` captures the lifetime `'a` as defined here +LL | let closure = |x: &'a ()| -> Self::Assoc<'b, 'a> { x }; + | ^ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0700`. diff --git a/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound2.rs b/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound2.rs new file mode 100644 index 0000000000000..7452000b65dc8 --- /dev/null +++ b/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound2.rs @@ -0,0 +1,21 @@ +#![feature(impl_trait_in_assoc_type)] + +trait Foo { + type Assoc<'a>; + fn bar<'a: 'a>(); +} + +impl Foo for () { + type Assoc<'a> = impl Sized; //~ ERROR unconstrained opaque type + fn bar<'a: 'a>() + where + Self::Assoc<'a>:, + { + let _ = |x: &'a ()| { + let _: Self::Assoc<'a> = x; + //~^ ERROR `<() as Foo>::Assoc<'a>` captures lifetime that does not appear in bound + }; + } +} + +fn main() {} diff --git a/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound2.stderr b/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound2.stderr new file mode 100644 index 0000000000000..1274a8b60dea0 --- /dev/null +++ b/tests/ui/type-alias-impl-trait/in-assoc-ty-early-bound2.stderr @@ -0,0 +1,22 @@ +error[E0700]: hidden type for `<() as Foo>::Assoc<'a>` captures lifetime that does not appear in bounds + --> $DIR/in-assoc-ty-early-bound2.rs:15:20 + | +LL | type Assoc<'a> = impl Sized; + | ---------- opaque type defined here +LL | fn bar<'a: 'a>() + | -- hidden type `&'a ()` captures the lifetime `'a` as defined here +... +LL | let _: Self::Assoc<'a> = x; + | ^^^^^^^^^^^^^^^ + +error: unconstrained opaque type + --> $DIR/in-assoc-ty-early-bound2.rs:9:22 + | +LL | type Assoc<'a> = impl Sized; + | ^^^^^^^^^^ + | + = note: `Assoc` must be used in combination with a concrete type within the same impl + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0700`. From 1829aa631fe3df4db1217922ec420e7c57501d50 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 16 Jan 2024 09:21:54 +0000 Subject: [PATCH 14/17] Use an enum instead of a bool --- .../src/collect/type_of/opaque.rs | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs b/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs index 51b2401531c7a..79cb384c5bded 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs @@ -47,7 +47,7 @@ pub(super) fn find_opaque_ty_constraints_for_impl_trait_in_assoc_type( let assoc = tcx.associated_item(assoc_id); match assoc.kind { ty::AssocKind::Const | ty::AssocKind::Fn => { - locator.check(assoc_id.expect_local(), true) + locator.check(assoc_id.expect_local(), ImplTraitSource::AssocTy) } // Associated types don't have bodies, so they can't constrain hidden types ty::AssocKind::Type => {} @@ -182,9 +182,15 @@ struct TaitConstraintLocator<'tcx> { typeck_types: Vec>, } +#[derive(Debug)] +enum ImplTraitSource { + AssocTy, + TyAlias, +} + impl TaitConstraintLocator<'_> { #[instrument(skip(self), level = "debug")] - fn check(&mut self, item_def_id: LocalDefId, impl_trait_in_assoc_type: bool) { + fn check(&mut self, item_def_id: LocalDefId, source: ImplTraitSource) { // Don't try to check items that cannot possibly constrain the type. if !self.tcx.has_typeck_results(item_def_id) { debug!("no constraint: no typeck results"); @@ -236,10 +242,11 @@ impl TaitConstraintLocator<'_> { continue; } constrained = true; - let opaque_types_defined_by = if impl_trait_in_assoc_type { - self.tcx.impl_trait_in_assoc_types_defined_by(item_def_id) - } else { - self.tcx.opaque_types_defined_by(item_def_id) + let opaque_types_defined_by = match source { + ImplTraitSource::AssocTy => { + self.tcx.impl_trait_in_assoc_types_defined_by(item_def_id) + } + ImplTraitSource::TyAlias => self.tcx.opaque_types_defined_by(item_def_id), }; if !opaque_types_defined_by.contains(&self.def_id) { self.tcx.dcx().emit_err(TaitForwardCompat { @@ -299,7 +306,7 @@ impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> { } fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) { if let hir::ExprKind::Closure(closure) = ex.kind { - self.check(closure.def_id, false); + self.check(closure.def_id, ImplTraitSource::TyAlias); } intravisit::walk_expr(self, ex); } @@ -307,7 +314,7 @@ impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> { trace!(?it.owner_id); // The opaque type itself or its children are not within its reveal scope. if it.owner_id.def_id != self.def_id { - self.check(it.owner_id.def_id, false); + self.check(it.owner_id.def_id, ImplTraitSource::TyAlias); intravisit::walk_item(self, it); } } @@ -315,13 +322,13 @@ impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> { trace!(?it.owner_id); // The opaque type itself or its children are not within its reveal scope. if it.owner_id.def_id != self.def_id { - self.check(it.owner_id.def_id, false); + self.check(it.owner_id.def_id, ImplTraitSource::TyAlias); intravisit::walk_impl_item(self, it); } } fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) { trace!(?it.owner_id); - self.check(it.owner_id.def_id, false); + self.check(it.owner_id.def_id, ImplTraitSource::TyAlias); intravisit::walk_trait_item(self, it); } fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) { From 5e5d1350b600ad8922a7c4bee44611bea597d082 Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Tue, 16 Jan 2024 10:17:58 +0000 Subject: [PATCH 15/17] Check that we forbid nested items, but not nested closures --- .../itiat-allow-nested-closures.bad.stderr | 23 ++++++++++++++++ .../itiat-allow-nested-closures.rs | 26 +++++++++++++++++++ .../itiat-forbid-nested-items.rs | 20 ++++++++++++++ .../itiat-forbid-nested-items.stderr | 22 ++++++++++++++++ 4 files changed, 91 insertions(+) create mode 100644 tests/ui/type-alias-impl-trait/itiat-allow-nested-closures.bad.stderr create mode 100644 tests/ui/type-alias-impl-trait/itiat-allow-nested-closures.rs create mode 100644 tests/ui/type-alias-impl-trait/itiat-forbid-nested-items.rs create mode 100644 tests/ui/type-alias-impl-trait/itiat-forbid-nested-items.stderr diff --git a/tests/ui/type-alias-impl-trait/itiat-allow-nested-closures.bad.stderr b/tests/ui/type-alias-impl-trait/itiat-allow-nested-closures.bad.stderr new file mode 100644 index 0000000000000..4acc47eaef220 --- /dev/null +++ b/tests/ui/type-alias-impl-trait/itiat-allow-nested-closures.bad.stderr @@ -0,0 +1,23 @@ +error[E0308]: mismatched types + --> $DIR/itiat-allow-nested-closures.rs:21:22 + | +LL | type Assoc = impl Sized; + | ---------- the found opaque type +... +LL | let _: i32 = closure(); + | --- ^^^^^^^^^ expected `i32`, found opaque type + | | + | expected due to this + +error[E0308]: mismatched types + --> $DIR/itiat-allow-nested-closures.rs:22:9 + | +LL | fn bar() -> Self::Assoc { + | ----------- expected `()` because of return type +... +LL | 1i32 + | ^^^^ expected `()`, found `i32` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/type-alias-impl-trait/itiat-allow-nested-closures.rs b/tests/ui/type-alias-impl-trait/itiat-allow-nested-closures.rs new file mode 100644 index 0000000000000..55994d6a3259d --- /dev/null +++ b/tests/ui/type-alias-impl-trait/itiat-allow-nested-closures.rs @@ -0,0 +1,26 @@ +#![feature(impl_trait_in_assoc_type)] + +// revisions: ok bad +// [ok] check-pass + +trait Foo { + type Assoc; + fn bar() -> Self::Assoc; +} + +impl Foo for () { + type Assoc = impl Sized; + fn bar() -> Self::Assoc { + let closure = || -> Self::Assoc { + #[cfg(ok)] + let x: Self::Assoc = 42_i32; + #[cfg(bad)] + let x: Self::Assoc = (); + x + }; + let _: i32 = closure(); //[bad]~ ERROR mismatched types + 1i32 //[bad]~ ERROR mismatched types + } +} + +fn main() {} diff --git a/tests/ui/type-alias-impl-trait/itiat-forbid-nested-items.rs b/tests/ui/type-alias-impl-trait/itiat-forbid-nested-items.rs new file mode 100644 index 0000000000000..8c9d780c1119d --- /dev/null +++ b/tests/ui/type-alias-impl-trait/itiat-forbid-nested-items.rs @@ -0,0 +1,20 @@ +#![feature(impl_trait_in_assoc_type)] + +trait Foo { + type Assoc; + fn bar() -> Self::Assoc; +} + +impl Foo for () { + type Assoc = impl Sized; + fn bar() -> Self::Assoc { + fn foo() -> <() as Foo>::Assoc { + let x: <() as Foo>::Assoc = 42_i32; //~ ERROR mismatched types + x + }; + let _: i32 = foo(); + 1i32 + } +} + +fn main() {} diff --git a/tests/ui/type-alias-impl-trait/itiat-forbid-nested-items.stderr b/tests/ui/type-alias-impl-trait/itiat-forbid-nested-items.stderr new file mode 100644 index 0000000000000..c177201431a61 --- /dev/null +++ b/tests/ui/type-alias-impl-trait/itiat-forbid-nested-items.stderr @@ -0,0 +1,22 @@ +error[E0308]: mismatched types + --> $DIR/itiat-forbid-nested-items.rs:12:41 + | +LL | type Assoc = impl Sized; + | ---------- the expected opaque type +... +LL | let x: <() as Foo>::Assoc = 42_i32; + | ------------------ ^^^^^^ expected opaque type, found `i32` + | | + | expected due to this + | + = note: expected opaque type `<() as Foo>::Assoc` + found type `i32` +note: this item must have the opaque type in its signature in order to be able to register hidden types + --> $DIR/itiat-forbid-nested-items.rs:11:12 + | +LL | fn foo() -> <() as Foo>::Assoc { + | ^^^ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`. From 21e5beae3cc4ffd2adea9ae7b4a9d8b84a4bc0a8 Mon Sep 17 00:00:00 2001 From: Wesley Wiser Date: Mon, 22 Jan 2024 10:10:00 -0600 Subject: [PATCH 16/17] Use debug_assert instead of expanded equivalent --- compiler/rustc_mir_transform/src/coverage/mod.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index 4b91f042f007a..afeacbf2232d3 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -366,10 +366,8 @@ fn check_code_region(code_region: CodeRegion) -> Option { ?is_ordered, "Skipping code region that would be misinterpreted or rejected by LLVM" ); - if cfg!(debug_assertions) { - // If this happens in a debug build, ICE to make it easier to notice. - bug!("Improper code region: {code_region:?}"); - } + // If this happens in a debug build, ICE to make it easier to notice. + debug_assert!(false, "Improper code region: {code_region:?}"); None } } From ce11b70979aa82cdfec6548b01197e0b826b53b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Mon, 22 Jan 2024 19:02:35 +0000 Subject: [PATCH 17/17] Re-add estebank to review rotation --- triagebot.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/triagebot.toml b/triagebot.toml index b3f3051e177f2..d963b6bb3d17f 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -639,6 +639,7 @@ compiler-team = [ "@compiler-errors", "@petrochenkov", "@davidtwco", + "@estebank", "@oli-obk", "@wesleywiser", ] @@ -688,18 +689,21 @@ incremental = [ diagnostics = [ "@compiler-errors", "@davidtwco", + "@estebank", "@oli-obk", "@TaKO8Ki", ] parser = [ "@compiler-errors", "@davidtwco", + "@estebank", "@nnethercote", "@petrochenkov", ] lexer = [ "@nnethercote", "@petrochenkov", + "@estebank", ] mir = [ "@davidtwco", @@ -723,6 +727,7 @@ borrowck = [ ] ast_lowering = [ "@compiler-errors", + "@estebank", "@spastorino", ] fallback = [