From 7cf9717bc3e24081d0bb86b3faa1d75076a44d30 Mon Sep 17 00:00:00 2001 From: Iwan Snel Date: Wed, 25 Nov 2026 14:18:16 +0100 Subject: [PATCH 1/5] remove `Box::into_boxed_slice` --- library/alloc/src/boxed.rs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index e25805d37c292..3b960fcbc1e3d 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -717,16 +717,6 @@ impl Box { Self::into_pin(Self::new_in(x, alloc)) } - /// Converts a `Box` into a `Box<[T]>` - /// - /// This conversion does not allocate on the heap and happens in place. - #[unstable(feature = "box_into_boxed_slice", issue = "71582")] - pub fn into_boxed_slice(boxed: Self) -> Box<[T], A> { - let (raw, alloc) = Box::into_raw_with_allocator(boxed); - // SAFETY: A pointer to T is also a valid pointer to [T; 1]. - unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) } - } - /// Consumes the `Box`, returning the wrapped value. /// /// # Examples From 086538af97a14b9c0504c66960312984fc9da802 Mon Sep 17 00:00:00 2001 From: Iwan Snel Date: Wed, 25 Nov 2026 16:39:08 +0100 Subject: [PATCH 2/5] remove stray UI tests --- tests/ui/box/into-boxed-slice-fail.rs | 12 ---------- tests/ui/box/into-boxed-slice-fail.stderr | 27 ----------------------- tests/ui/box/into-boxed-slice.rs | 9 -------- 3 files changed, 48 deletions(-) delete mode 100644 tests/ui/box/into-boxed-slice-fail.rs delete mode 100644 tests/ui/box/into-boxed-slice-fail.stderr delete mode 100644 tests/ui/box/into-boxed-slice.rs diff --git a/tests/ui/box/into-boxed-slice-fail.rs b/tests/ui/box/into-boxed-slice-fail.rs deleted file mode 100644 index db2e5623264e6..0000000000000 --- a/tests/ui/box/into-boxed-slice-fail.rs +++ /dev/null @@ -1,12 +0,0 @@ -#![feature(box_into_boxed_slice)] - -use std::boxed::Box; -use std::fmt::Debug; -fn main() { - let boxed_slice = Box::new([1,2,3]) as Box<[u8]>; - let _ = Box::into_boxed_slice(boxed_slice); - //~^ ERROR the size for values of type `[u8]` cannot be known at compilation time - let boxed_trait: Box = Box::new(5u8); - let _ = Box::into_boxed_slice(boxed_trait); - //~^ ERROR the size for values of type `dyn Debug` cannot be known at compilation time -} diff --git a/tests/ui/box/into-boxed-slice-fail.stderr b/tests/ui/box/into-boxed-slice-fail.stderr deleted file mode 100644 index a66fa533c6f02..0000000000000 --- a/tests/ui/box/into-boxed-slice-fail.stderr +++ /dev/null @@ -1,27 +0,0 @@ -error[E0277]: the size for values of type `[u8]` cannot be known at compilation time - --> $DIR/into-boxed-slice-fail.rs:7:35 - | -LL | let _ = Box::into_boxed_slice(boxed_slice); - | --------------------- ^^^^^^^^^^^ doesn't have a size known at compile-time - | | - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `[u8]` -note: required by a bound in `Box::::into_boxed_slice` - --> $SRC_DIR/alloc/src/boxed.rs:LL:COL - -error[E0277]: the size for values of type `dyn Debug` cannot be known at compilation time - --> $DIR/into-boxed-slice-fail.rs:10:35 - | -LL | let _ = Box::into_boxed_slice(boxed_trait); - | --------------------- ^^^^^^^^^^^ doesn't have a size known at compile-time - | | - | required by a bound introduced by this call - | - = help: the trait `Sized` is not implemented for `dyn Debug` -note: required by a bound in `Box::::into_boxed_slice` - --> $SRC_DIR/alloc/src/boxed.rs:LL:COL - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/box/into-boxed-slice.rs b/tests/ui/box/into-boxed-slice.rs deleted file mode 100644 index 1487cd651459a..0000000000000 --- a/tests/ui/box/into-boxed-slice.rs +++ /dev/null @@ -1,9 +0,0 @@ -//@ run-pass -#![feature(box_into_boxed_slice)] -fn main() { - assert_eq!(Box::into_boxed_slice(Box::new(5u8)), Box::new([5u8]) as Box<[u8]>); - assert_eq!(Box::into_boxed_slice(Box::new([25u8])), Box::new([[25u8]]) as Box<[[u8; 1]]>); - let a: Box<[Box<[u8; 1]>]> = Box::into_boxed_slice(Box::new(Box::new([5u8]))); - let b: Box<[Box<[u8; 1]>]> = Box::new([Box::new([5u8])]); - assert_eq!(a, b); -} From b5d04d2178bf4e1327b2791c1b74b5c54291a06f Mon Sep 17 00:00:00 2001 From: puranikyashaswin Date: Thu, 19 Nov 2026 16:42:13 +0530 Subject: [PATCH 3/5] autodiff: don't ICE on invalid macro arguments --- compiler/rustc_builtin_macros/src/autodiff.rs | 96 ++++++++----------- .../rustc_builtin_macros/src/diagnostics.rs | 6 ++ tests/crashes/160329.rs | 4 - tests/ui/autodiff/invalid-macro-args.rs | 38 ++++++++ tests/ui/autodiff/invalid-macro-args.stderr | 40 ++++++++ .../ui/autodiff/invalid-signature-recovery.rs | 13 +++ .../invalid-signature-recovery.stderr | 20 ++++ 7 files changed, 155 insertions(+), 62 deletions(-) delete mode 100644 tests/crashes/160329.rs create mode 100644 tests/ui/autodiff/invalid-macro-args.rs create mode 100644 tests/ui/autodiff/invalid-macro-args.stderr create mode 100644 tests/ui/autodiff/invalid-signature-recovery.rs create mode 100644 tests/ui/autodiff/invalid-signature-recovery.stderr diff --git a/compiler/rustc_builtin_macros/src/autodiff.rs b/compiler/rustc_builtin_macros/src/autodiff.rs index 2704496b0fbaf..e3b6411d73db8 100644 --- a/compiler/rustc_builtin_macros/src/autodiff.rs +++ b/compiler/rustc_builtin_macros/src/autodiff.rs @@ -3,7 +3,6 @@ //! configs (autodiff enabled or disabled), so we have to add cfg's to each import. use std::str::FromStr; -use std::string::String; use rustc_ast::expand::autodiff_attrs::{ DiffActivity, DiffMode, valid_input_activity, valid_ret_activity, valid_ty_for_activity, @@ -42,26 +41,6 @@ fn has_ret(ty: &FnRetTy) -> bool { FnRetTy::Default(_) => false, } } -fn first_ident(x: &MetaItemInner) -> rustc_span::Ident { - if let Some(l) = x.lit() { - match l.kind { - ast::LitKind::Int(val, _) => { - // get an Ident from a lit - return rustc_span::Ident::from_str(val.get().to_string().as_str()); - } - _ => {} - } - } - - let segments = &x.meta_item().unwrap().path.segments; - assert!(segments.len() == 1); - segments[0].ident -} - -fn name(x: &MetaItemInner) -> String { - first_ident(x).name.to_string() -} - fn width(x: &MetaItemInner) -> Option { let lit = x.lit()?; match lit.kind { @@ -113,7 +92,15 @@ fn from_ast( let mut activities: Vec = vec![]; let mut errors = false; for x in &meta_item[first_activity..] { - let activity_str = name(x); + let Some(ident) = x.ident() else { + dcx.emit_err(diagnostics::AutoDiffUnknownActivity { + span: x.span(), + act: rustc_ast_pretty::pprust::meta_list_item_to_string(x), + }); + errors = true; + continue; + }; + let activity_str = ident.name.to_string(); let res = DiffActivity::from_str(&activity_str); match res { Ok(x) => activities.push(x), @@ -132,15 +119,10 @@ fn from_ast( // If a return type exist, we need to split the last activity, // otherwise we return None as placeholder. - let (ret_activity, input_activity) = if has_ret { - let Some((last, rest)) = activities.split_last() else { - unreachable!( - "should not be reachable because we counted the number of activities previously" - ); - }; - (last, rest) - } else { - (&DiffActivity::None, activities.as_slice()) + // A missing return activity is reported by the count check in `gen_enzyme_decl`. + let (ret_activity, input_activity) = match activities.split_last() { + Some((last, rest)) if has_ret => (last, rest), + _ => (&DiffActivity::None, activities.as_slice()), }; RustcAutodiff { @@ -153,7 +135,7 @@ fn from_ast( fn meta_item_inner_to_ts(t: &MetaItemInner, ts: &mut Vec) { let comma = Token::new(TokenKind::Comma, Span::default()); - let val = first_ident(t); + let val = t.ident().expect("activities are validated in `from_ast`"); let t = Token::from_ast_ident(val); ts.push(TokenTree::Token(t, Spacing::Joint)); ts.push(TokenTree::Token(comma, Spacing::Alone)); @@ -255,6 +237,18 @@ fn expand_with_mode( return vec![item]; } + let Some(d_ident) = meta_item_vec[0].ident() else { + dcx.emit_err(diagnostics::AutoDiffInvalidName { span: meta_item_vec[0].span() }); + return vec![item]; + }; + + let x = from_ast(ecx, &meta_item_vec, has_ret, mode); + if !x.is_active() { + // We encountered an error, so we return the original item. + // This allows us to potentially parse other attributes. + return vec![item]; + } + let mode_symbol = match mode { DiffMode::Forward => sym::Forward, DiffMode::Reverse => sym::Reverse, @@ -302,32 +296,18 @@ fn expand_with_mode( ts.pop(); let ts = TokenStream::from_iter(ts); - let x = from_ast(ecx, &meta_item_vec, has_ret, mode); - if !x.is_active() { - // We encountered an error, so we return the original item. - // This allows us to potentially parse other attributes. - return vec![item]; - } let span = ecx.with_def_site_ctxt(expand_span); - let d_sig = gen_enzyme_decl(ecx, &sig, &x, span); + let Some(d_sig) = gen_enzyme_decl(ecx, &sig, &x, span) else { + return vec![item]; + }; let d_body = ecx.block( span, - thin_vec![call_autodiff( - ecx, - primal, - first_ident(&meta_item_vec[0]), - span, - &sig, - &d_sig, - &generics, - is_impl, - )], + thin_vec![call_autodiff(ecx, primal, d_ident, span, &sig, &d_sig, &generics, is_impl)], ); - // The first element of it is the name of the function to be generated - let d_fn = ecx.item_fn(d_sig, first_ident(&meta_item_vec[0]), generics, Some(d_body)); + let d_fn = ecx.item_fn(d_sig, d_ident, generics, Some(d_body)); let mut rustc_ad_attr = Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_autodiff))); @@ -588,8 +568,9 @@ fn gen_turbofish_expr( // Each argument of the primal function (and the return type if existing) must be annotated with an // activity. // -// Error handling: If the user provides an invalid configuration (incorrect numbers, types, or -// both), we emit an error and return the original signature. This allows us to continue parsing. +// Error handling: If the user provides the wrong number of activities, we emit an error and +// return `None`. If the types don't fit the activities, we emit an error and return the +// original signature. This allows us to continue parsing. // FIXME(Sa4dUs): make individual activities' span available so errors // can point to only the activity instead of the entire attribute fn gen_enzyme_decl( @@ -597,7 +578,7 @@ fn gen_enzyme_decl( sig: &ast::FnSig, x: &RustcAutodiff, span: Span, -) -> ast::FnSig { +) -> Option { let dcx = ecx.sess.dcx(); let has_ret = has_ret(&sig.decl.output); let sig_args = sig.decl.inputs.len() + if has_ret { 1 } else { 0 }; @@ -608,8 +589,7 @@ fn gen_enzyme_decl( expected: sig_args, found: num_activities, }); - // This is not the right signature, but we can continue parsing. - return sig.clone(); + return None; } assert!(sig.decl.inputs.len() == x.input_activity.len()); assert!(has_ret == x.has_ret_activity()); @@ -650,7 +630,7 @@ fn gen_enzyme_decl( if errors { // This is not the right signature, but we can continue parsing. - return sig.clone(); + return Some(sig.clone()); } let unsafe_activities = x @@ -822,5 +802,5 @@ fn gen_enzyme_decl( } let d_sig = FnSig { header: d_header, decl: d_decl, span }; trace!("Generated signature: {:?}", d_sig); - d_sig + Some(d_sig) } diff --git a/compiler/rustc_builtin_macros/src/diagnostics.rs b/compiler/rustc_builtin_macros/src/diagnostics.rs index 851317cde7f4e..eef6f9a394577 100644 --- a/compiler/rustc_builtin_macros/src/diagnostics.rs +++ b/compiler/rustc_builtin_macros/src/diagnostics.rs @@ -174,6 +174,12 @@ mod autodiff { pub(crate) span: Span, } #[derive(Diagnostic)] + #[diag("expected an identifier for the generated function name")] + pub(crate) struct AutoDiffInvalidName { + #[primary_span] + pub(crate) span: Span, + } + #[derive(Diagnostic)] #[diag("did not recognize Activity: `{$act}`")] pub(crate) struct AutoDiffUnknownActivity { #[primary_span] diff --git a/tests/crashes/160329.rs b/tests/crashes/160329.rs deleted file mode 100644 index e436795e5fca9..0000000000000 --- a/tests/crashes/160329.rs +++ /dev/null @@ -1,4 +0,0 @@ -//@ known-bug: #160329 -#![feature(autodiff)] -#[core::autodiff::autodiff_forward(fd_inner, Dual)] -fn f(_x: struct S) {} diff --git a/tests/ui/autodiff/invalid-macro-args.rs b/tests/ui/autodiff/invalid-macro-args.rs new file mode 100644 index 0000000000000..4b3d5ff1cc5be --- /dev/null +++ b/tests/ui/autodiff/invalid-macro-args.rs @@ -0,0 +1,38 @@ +//! Regression test for , +//! and +//! . +//! Invalid arguments to the autodiff macros used to ICE during expansion. + +#![feature(autodiff)] + +use std::autodiff::{autodiff_forward, autodiff_reverse}; + +// A return type, but no activities at all. +#[autodiff_reverse(df1)] +//~^ ERROR expected 1 activities, but found 0 +fn f1() -> f64 { + 0.0 +} + +// The name has a leading `::`. +#[autodiff_forward(::df2)] +//~^ ERROR expected an identifier for the generated function name +fn f2() {} + +// The name is a float literal. +#[autodiff_reverse(2.0f)] +//~^ ERROR invalid suffix `f` for float literal +//~| ERROR expected an identifier for the generated function name +fn f3() {} + +// An activity that is a float literal. +#[autodiff_reverse(df4, 2.0)] +//~^ ERROR did not recognize Activity: `2.0` +fn f4(x: f64) {} + +// An activity with a path. +#[autodiff_reverse(df5, ::Active)] +//~^ ERROR did not recognize Activity: `::Active` +fn f5(x: f64) {} + +fn main() {} diff --git a/tests/ui/autodiff/invalid-macro-args.stderr b/tests/ui/autodiff/invalid-macro-args.stderr new file mode 100644 index 0000000000000..b77a1322dd284 --- /dev/null +++ b/tests/ui/autodiff/invalid-macro-args.stderr @@ -0,0 +1,40 @@ +error: expected 1 activities, but found 0 + --> $DIR/invalid-macro-args.rs:11:1 + | +LL | #[autodiff_reverse(df1)] + | ^^^^^^^^^^^^^^^^^^^^^^^^ + +error: expected an identifier for the generated function name + --> $DIR/invalid-macro-args.rs:18:20 + | +LL | #[autodiff_forward(::df2)] + | ^^^^^ + +error: invalid suffix `f` for float literal + --> $DIR/invalid-macro-args.rs:23:20 + | +LL | #[autodiff_reverse(2.0f)] + | ^^^^ invalid suffix `f` + | + = help: valid suffixes are `f32` and `f64` + +error: expected an identifier for the generated function name + --> $DIR/invalid-macro-args.rs:23:20 + | +LL | #[autodiff_reverse(2.0f)] + | ^^^^ + +error: did not recognize Activity: `2.0` + --> $DIR/invalid-macro-args.rs:29:25 + | +LL | #[autodiff_reverse(df4, 2.0)] + | ^^^ + +error: did not recognize Activity: `::Active` + --> $DIR/invalid-macro-args.rs:34:25 + | +LL | #[autodiff_reverse(df5, ::Active)] + | ^^^^^^^^ + +error: aborting due to 6 previous errors + diff --git a/tests/ui/autodiff/invalid-signature-recovery.rs b/tests/ui/autodiff/invalid-signature-recovery.rs new file mode 100644 index 0000000000000..cb03dc9354271 --- /dev/null +++ b/tests/ui/autodiff/invalid-signature-recovery.rs @@ -0,0 +1,13 @@ +//! Regression test for . +//! Parser recovery left the function with more parameters than activities, +//! and expansion used to ICE instead of stopping at the count error. + +#![feature(autodiff)] + +#[core::autodiff::autodiff_forward(fd_inner, Dual)] +//~^ ERROR expected 2 activities, but found 1 +fn f(_x: struct S) {} +//~^ ERROR expected type, found keyword `struct` +//~| ERROR expected one of `:`, `@`, or `|`, found `>` + +fn main() {} diff --git a/tests/ui/autodiff/invalid-signature-recovery.stderr b/tests/ui/autodiff/invalid-signature-recovery.stderr new file mode 100644 index 0000000000000..9c87027be552a --- /dev/null +++ b/tests/ui/autodiff/invalid-signature-recovery.stderr @@ -0,0 +1,20 @@ +error: expected type, found keyword `struct` + --> $DIR/invalid-signature-recovery.rs:9:10 + | +LL | fn f(_x: struct S) {} + | ^^^^^^ expected type + +error: expected one of `:`, `@`, or `|`, found `>` + --> $DIR/invalid-signature-recovery.rs:9:23 + | +LL | fn f(_x: struct S) {} + | ^ expected one of `:`, `@`, or `|` + +error: expected 2 activities, but found 1 + --> $DIR/invalid-signature-recovery.rs:7:1 + | +LL | #[core::autodiff::autodiff_forward(fd_inner, Dual)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 3 previous errors + From 7526545a025574189a58c7a848878ca74e288756 Mon Sep 17 00:00:00 2001 From: Iwan Snel Date: Wed, 25 Nov 2026 17:44:13 +0100 Subject: [PATCH 4/5] update affected ui tests --- tests/ui/parallel-rustc/ty-variance-issue-124423.stderr | 2 +- tests/ui/parallel-rustc/ty-variance-issue-127971.stderr | 2 +- tests/ui/privacy/suggest-box-new.stderr | 4 ++-- tests/ui/suggestions/multi-suggestion.ascii.stderr | 4 ++-- tests/ui/suggestions/multi-suggestion.unicode.stderr | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/ui/parallel-rustc/ty-variance-issue-124423.stderr b/tests/ui/parallel-rustc/ty-variance-issue-124423.stderr index 83764f9e22312..e7a1f2c085759 100644 --- a/tests/ui/parallel-rustc/ty-variance-issue-124423.stderr +++ b/tests/ui/parallel-rustc/ty-variance-issue-124423.stderr @@ -278,7 +278,7 @@ note: if you're trying to build a new `Box<_, _>` consider using one of the foll Box::::new_uninit Box::::new_zeroed Box::::try_new - and 27 others + and 26 others --> $SRC_DIR/alloc/src/boxed.rs:LL:COL error: aborting due to 30 previous errors diff --git a/tests/ui/parallel-rustc/ty-variance-issue-127971.stderr b/tests/ui/parallel-rustc/ty-variance-issue-127971.stderr index e1e00243caaa3..6631a0594c8cb 100644 --- a/tests/ui/parallel-rustc/ty-variance-issue-127971.stderr +++ b/tests/ui/parallel-rustc/ty-variance-issue-127971.stderr @@ -104,7 +104,7 @@ note: if you're trying to build a new `Box<_, _>` consider using one of the foll Box::::new_uninit Box::::new_zeroed Box::::try_new - and 27 others + and 26 others --> $SRC_DIR/alloc/src/boxed.rs:LL:COL error: aborting due to 11 previous errors diff --git a/tests/ui/privacy/suggest-box-new.stderr b/tests/ui/privacy/suggest-box-new.stderr index 53578389db95d..0039051dde216 100644 --- a/tests/ui/privacy/suggest-box-new.stderr +++ b/tests/ui/privacy/suggest-box-new.stderr @@ -68,7 +68,7 @@ LL - x: (), LL - })), LL + wtf: Some(Box::new_in(_, _)), | - = and 16 other candidates + = and 15 other candidates help: consider using the `Default` trait | LL - wtf: Some(Box(U { @@ -125,7 +125,7 @@ LL + let _ = Box::new_zeroed(); LL - let _ = Box {}; LL + let _ = Box::new_in(_, _); | - = and 17 other candidates + = and 16 other candidates help: consider using the `Default` trait | LL - let _ = Box {}; diff --git a/tests/ui/suggestions/multi-suggestion.ascii.stderr b/tests/ui/suggestions/multi-suggestion.ascii.stderr index 76fc55177070d..ecc4c5aa7c23b 100644 --- a/tests/ui/suggestions/multi-suggestion.ascii.stderr +++ b/tests/ui/suggestions/multi-suggestion.ascii.stderr @@ -68,7 +68,7 @@ LL - x: (), LL - })), LL + wtf: Some(Box::new_in(_, _)), | - = and 16 other candidates + = and 15 other candidates help: consider using the `Default` trait | LL - wtf: Some(Box(U { @@ -125,7 +125,7 @@ LL + let _ = Box::new_zeroed(); LL - let _ = Box {}; LL + let _ = Box::new_in(_, _); | - = and 17 other candidates + = and 16 other candidates help: consider using the `Default` trait | LL - let _ = Box {}; diff --git a/tests/ui/suggestions/multi-suggestion.unicode.stderr b/tests/ui/suggestions/multi-suggestion.unicode.stderr index 6bbd95c44a529..1f28a4d8fa289 100644 --- a/tests/ui/suggestions/multi-suggestion.unicode.stderr +++ b/tests/ui/suggestions/multi-suggestion.unicode.stderr @@ -68,7 +68,7 @@ LL - x: (), LL - })), LL + wtf: Some(Box::new_in(_, _)), │ - ╰ and 16 other candidates + ╰ and 15 other candidates help: consider using the `Default` trait ╭╴ LL - wtf: Some(Box(U { @@ -125,7 +125,7 @@ LL + let _ = Box::new_zeroed(); LL - let _ = Box {}; LL + let _ = Box::new_in(_, _); │ - ╰ and 17 other candidates + ╰ and 16 other candidates help: consider using the `Default` trait ╭╴ LL - let _ = Box {}; From 9f1b6caacdfa208b4444a1c7c1fb9f2eca46fc37 Mon Sep 17 00:00:00 2001 From: Dnreikronos Date: Thu, 19 Nov 2026 11:02:34 -0300 Subject: [PATCH 5/5] Borrow the whole value under each lifetime when nothing is reborrowed When no field of a `Reborrow` type is reborrowed, borrowck borrows the whole source value instead. That fallback assumed the target type has exactly one lifetime and hit a `bug!` otherwise, even though `Reborrow` impls on types with several lifetimes are accepted. Borrow the source under each of the target's lifetimes instead. The one lifetime case is unchanged, and the source stays borrowed for as long as any of the target's lifetimes is live. --- compiler/rustc_borrowck/src/borrow_set.rs | 34 ++++--- .../reborrow-multiple-lifetimes-exclusive.rs | 24 +++++ ...borrow-multiple-lifetimes-exclusive.stderr | 13 +++ ...eborrow-multiple-lifetimes-issue-165653.rs | 23 +++++ ...row-multiple-lifetimes-issue-165653.stderr | 14 +++ ...-multiple-lifetimes-no-reborrowed-field.rs | 96 +++++++++++++++++++ 6 files changed, 191 insertions(+), 13 deletions(-) create mode 100644 tests/ui/reborrow/reborrow-multiple-lifetimes-exclusive.rs create mode 100644 tests/ui/reborrow/reborrow-multiple-lifetimes-exclusive.stderr create mode 100644 tests/ui/reborrow/reborrow-multiple-lifetimes-issue-165653.rs create mode 100644 tests/ui/reborrow/reborrow-multiple-lifetimes-issue-165653.stderr create mode 100644 tests/ui/reborrow/reborrow-multiple-lifetimes-no-reborrowed-field.rs diff --git a/compiler/rustc_borrowck/src/borrow_set.rs b/compiler/rustc_borrowck/src/borrow_set.rs index 3c5e939cd93b7..329f28fc29c5a 100644 --- a/compiler/rustc_borrowck/src/borrow_set.rs +++ b/compiler/rustc_borrowck/src/borrow_set.rs @@ -399,20 +399,28 @@ impl<'a, 'tcx> GatherBorrows<'a, 'tcx> { // to avoid capturing the local variable's place. let source_phantom_deref_place = source_place.project_deeper(&[PlaceElem::PhantomDeref], self.tcx); - if target_args.regions().count() != 1 { - bug!( - "ADT containing no '&mut T' or 'T: Reborrow' fields must only have one lifetime to implement Reborrow" - ); + // With no field to reborrow we don't know which of the target's lifetimes + // the borrow should be tied to, so borrow the whole source under each of them. + let mut target_regions: SmallVec<[RegionVid; 1]> = SmallVec::new(); + for region in target_args.regions() { + let region = region.as_var(); + if !target_regions.contains(®ion) { + target_regions.push(region); + } + } + if target_regions.is_empty() { + bug!("Reborrow target type has no lifetime arguments"); + } + for region in target_regions { + v.push(BorrowData { + kind, + region, + reserve_location: location, + activation_location: TwoPhaseActivation::NotTwoPhase, + borrowed_place: source_phantom_deref_place, + assigned_place: target_place, + }); } - let target_region = target_args.regions().next().unwrap(); - v.push(BorrowData { - kind, - region: target_region.as_var(), - reserve_location: location, - activation_location: TwoPhaseActivation::NotTwoPhase, - borrowed_place: source_phantom_deref_place, - assigned_place: target_place, - }); } } } diff --git a/tests/ui/reborrow/reborrow-multiple-lifetimes-exclusive.rs b/tests/ui/reborrow/reborrow-multiple-lifetimes-exclusive.rs new file mode 100644 index 0000000000000..b9f3f5c5984f9 --- /dev/null +++ b/tests/ui/reborrow/reborrow-multiple-lifetimes-exclusive.rs @@ -0,0 +1,24 @@ +//! A `Reborrow` type with two lifetimes and no reborrowed field is borrowed as a +//! whole, under both lifetimes, so two live reborrows still conflict. + +#![feature(reborrow)] + +use std::marker::{PhantomData, Reborrow}; + +struct Marker<'a, 'b>(PhantomData<(&'a mut (), &'b mut ())>); + +impl<'a, 'b> Reborrow for Marker<'a, 'b> {} + +fn reborrow<'a, 'b>(m: Marker<'a, 'b>) -> Marker<'a, 'b> { + m +} + +fn keep(_: &Marker<'_, '_>) {} + +fn main() { + let m = Marker(PhantomData); + let x = reborrow(m); + let y = reborrow(m); //~ ERROR cannot borrow `m` as mutable more than once at a time + keep(&x); + keep(&y); +} diff --git a/tests/ui/reborrow/reborrow-multiple-lifetimes-exclusive.stderr b/tests/ui/reborrow/reborrow-multiple-lifetimes-exclusive.stderr new file mode 100644 index 0000000000000..16d92d3c05747 --- /dev/null +++ b/tests/ui/reborrow/reborrow-multiple-lifetimes-exclusive.stderr @@ -0,0 +1,13 @@ +error[E0499]: cannot borrow `m` as mutable more than once at a time + --> $DIR/reborrow-multiple-lifetimes-exclusive.rs:21:22 + | +LL | let x = reborrow(m); + | - first mutable borrow occurs here +LL | let y = reborrow(m); + | ^ second mutable borrow occurs here +LL | keep(&x); + | -- first borrow later used here + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0499`. diff --git a/tests/ui/reborrow/reborrow-multiple-lifetimes-issue-165653.rs b/tests/ui/reborrow/reborrow-multiple-lifetimes-issue-165653.rs new file mode 100644 index 0000000000000..fd2b4221ff3ca --- /dev/null +++ b/tests/ui/reborrow/reborrow-multiple-lifetimes-issue-165653.rs @@ -0,0 +1,23 @@ +//! Regression test for . +//! +//! Reborrowing a type with two lifetimes and no `&mut` or `Reborrow` field used to +//! hit a `bug!` in borrowck. It now gives the same error as the one lifetime case. + +#![feature(reborrow)] + +use std::marker::Reborrow; + +impl<'a, 'b> Reborrow for DerivedShared<'a, 'b> {} + +struct DerivedShared<'a, 'b> { + a: &'a &'b str, +} + +impl<'a, 'b> DerivedShared<'a, 'b> { + fn clone(&self) -> Self { + *self + //~^ ERROR cannot borrow `*self` as mutable, as it is behind a `&` reference + } +} + +fn main() {} diff --git a/tests/ui/reborrow/reborrow-multiple-lifetimes-issue-165653.stderr b/tests/ui/reborrow/reborrow-multiple-lifetimes-issue-165653.stderr new file mode 100644 index 0000000000000..2d316d11f69db --- /dev/null +++ b/tests/ui/reborrow/reborrow-multiple-lifetimes-issue-165653.stderr @@ -0,0 +1,14 @@ +error[E0596]: cannot borrow `*self` as mutable, as it is behind a `&` reference + --> $DIR/reborrow-multiple-lifetimes-issue-165653.rs:18:9 + | +LL | *self + | ^^^^^ `self` is a `&` reference, so it cannot be borrowed as mutable + | +help: consider changing this to be a mutable reference + | +LL | fn clone(&mut self) -> Self { + | +++ + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0596`. diff --git a/tests/ui/reborrow/reborrow-multiple-lifetimes-no-reborrowed-field.rs b/tests/ui/reborrow/reborrow-multiple-lifetimes-no-reborrowed-field.rs new file mode 100644 index 0000000000000..aea67d4a92f31 --- /dev/null +++ b/tests/ui/reborrow/reborrow-multiple-lifetimes-no-reborrowed-field.rs @@ -0,0 +1,96 @@ +//@ check-pass +//! Types with more than one lifetime where borrowck finds no field to reborrow. +//! Borrowck used to hit a `bug!` on all of these. Where a value is used twice, the +//! second use only compiles if the first one was a reborrow and not a move. + +#![feature(reborrow)] + +use std::marker::{CoerceShared, PhantomData, Reborrow}; + +// Only a marker field. +struct Marker<'a, 'b>(PhantomData<(&'a mut (), &'b mut ())>); + +impl<'a, 'b> Reborrow for Marker<'a, 'b> {} + +fn marker<'a, 'b>(m: Marker<'a, 'b>) -> Marker<'a, 'b> { + m +} + +// A type parameter field. +struct Generic<'a, 'b, T> { + t: T, + marker: PhantomData<(&'a (), &'b ())>, +} + +impl<'a, 'b, T: Reborrow> Reborrow for Generic<'a, 'b, T> {} + +fn generic<'a, 'b>(g: Generic<'a, 'b, Inner<'a>>) -> Generic<'a, 'b, Inner<'a>> { + g +} + +// An associated type field that normalizes to `&mut`. +trait HasAssoc<'a> { + type Assoc; +} + +impl<'a> HasAssoc<'a> for () { + type Assoc = &'a mut (); +} + +struct Assoc<'a, 'b> { + assoc: <() as HasAssoc<'a>>::Assoc, + shared: &'b (), +} + +impl<'a, 'b> Reborrow for Assoc<'a, 'b> {} + +fn assoc<'a, 'b>(x: Assoc<'a, 'b>) -> Assoc<'a, 'b> { + x +} + +// A field that is only `Copy` when `T: Copy`, used in a body with that bound. +#[derive(Clone, Copy)] +struct Wrap<'a, T>(PhantomData<&'a ()>, T); + +impl<'a, T: Reborrow> Reborrow for Wrap<'a, T> {} + +struct WithWrap<'a, 'b, T> { + w: Wrap<'a, T>, + shared: &'b (), +} + +impl<'a, 'b, T: Reborrow> Reborrow for WithWrap<'a, 'b, T> {} + +fn with_wrap<'a, 'b, T: Reborrow + Copy>(x: WithWrap<'a, 'b, T>) -> WithWrap<'a, 'b, T> { + x +} + +// A `CoerceShared` target with more lifetimes than the source. +struct Src<'a>(PhantomData<(&'a (), &'a ())>); + +impl<'a> Reborrow for Src<'a> {} + +#[derive(Clone, Copy)] +struct Dst<'a, 'b>(PhantomData<(&'a (), &'b ())>); + +impl<'a> CoerceShared> for Src<'a> {} + +fn coerce<'a>(x: Src<'a>) -> Dst<'a, 'a> { + x +} + +struct Inner<'a>(&'a mut ()); + +impl<'a> Reborrow for Inner<'a> {} + +fn main() { + let m = Marker(PhantomData); + let _ = marker(m); + let _ = marker(m); + + let mut a = (); + let g = Generic { t: Inner(&mut a), marker: PhantomData }; + let _ = generic(g); + let _ = generic(g); + +}