Skip to content

Commit 6106b05

Browse files
committed
Auto merge of #128142 - matthiaskrgr:rollup-rep8ofv, r=matthiaskrgr
Rollup of 9 pull requests Successful merges: - #126152 (size_of_val_raw: for length 0 this is safe to call) - #127252 (Add edge-case examples to `{count,leading,trailing}_{ones,zeros}` methods) - #127374 (Tweak "wrong # of generics" suggestions) - #127457 (Make tidy fast without compromising case alternation) - #127480 (Fix build failure on vxworks #127084 ) - #127733 (Replace some `mem::forget`'s with `ManuallyDrop`) - #128120 (Gate `AsyncFn*` under `async_closure` feature) - #128131 (Import `c_void` rather than using the full path) - #128133 (Improve spans on evaluated `cfg_attr`s.) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 2ccafed + 2dc88bf commit 6106b05

File tree

107 files changed

+528
-435
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

107 files changed

+528
-435
lines changed

compiler/rustc_ast_lowering/src/path.rs

+15-7
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
4444
let mut res = self.lower_res(base_res);
4545

4646
// When we have an `async` kw on a bound, map the trait it resolves to.
47-
let mut bound_modifier_allowed_features = None;
4847
if let Some(TraitBoundModifiers { asyncness: BoundAsyncness::Async(_), .. }) = modifiers {
4948
match res {
5049
Res::Def(DefKind::Trait, def_id) => {
51-
if let Some((async_def_id, features)) = self.map_trait_to_async_trait(def_id) {
50+
if let Some(async_def_id) = self.map_trait_to_async_trait(def_id) {
5251
res = Res::Def(DefKind::Trait, async_def_id);
53-
bound_modifier_allowed_features = Some(features);
5452
} else {
5553
self.dcx().emit_err(AsyncBoundOnlyForFnTraits { span: p.span });
5654
}
@@ -67,6 +65,16 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
6765
}
6866
}
6967

68+
// Ungate the `async_fn_traits` feature in the path if the trait is
69+
// named via either `async Fn*()` or `AsyncFn*()`.
70+
let bound_modifier_allowed_features = if let Res::Def(DefKind::Trait, async_def_id) = res
71+
&& self.tcx.async_fn_trait_kind_from_def_id(async_def_id).is_some()
72+
{
73+
Some(self.allow_async_fn_traits.clone())
74+
} else {
75+
None
76+
};
77+
7078
let path_span_lo = p.span.shrink_to_lo();
7179
let proj_start = p.segments.len() - unresolved_segments;
7280
let path = self.arena.alloc(hir::Path {
@@ -506,14 +514,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
506514
/// This only needs to be done until we unify `AsyncFn` and `Fn` traits into one
507515
/// that is generic over `async`ness, if that's ever possible, or modify the
508516
/// lowering of `async Fn()` bounds to desugar to another trait like `LendingFn`.
509-
fn map_trait_to_async_trait(&self, def_id: DefId) -> Option<(DefId, Lrc<[Symbol]>)> {
517+
fn map_trait_to_async_trait(&self, def_id: DefId) -> Option<DefId> {
510518
let lang_items = self.tcx.lang_items();
511519
if Some(def_id) == lang_items.fn_trait() {
512-
Some((lang_items.async_fn_trait()?, self.allow_async_fn_traits.clone()))
520+
lang_items.async_fn_trait()
513521
} else if Some(def_id) == lang_items.fn_mut_trait() {
514-
Some((lang_items.async_fn_mut_trait()?, self.allow_async_fn_traits.clone()))
522+
lang_items.async_fn_mut_trait()
515523
} else if Some(def_id) == lang_items.fn_once_trait() {
516-
Some((lang_items.async_fn_once_trait()?, self.allow_async_fn_traits.clone()))
524+
lang_items.async_fn_once_trait()
517525
} else {
518526
None
519527
}

compiler/rustc_expand/src/config.rs

+28-28
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::errors::{
66
};
77
use rustc_ast::ptr::P;
88
use rustc_ast::token::{Delimiter, Token, TokenKind};
9-
use rustc_ast::tokenstream::{AttrTokenStream, AttrTokenTree, DelimSpacing, DelimSpan, Spacing};
9+
use rustc_ast::tokenstream::{AttrTokenStream, AttrTokenTree, Spacing};
1010
use rustc_ast::tokenstream::{LazyAttrTokenStream, TokenTree};
1111
use rustc_ast::NodeId;
1212
use rustc_ast::{self as ast, AttrStyle, Attribute, HasAttrs, HasTokens, MetaItem};
@@ -298,47 +298,47 @@ impl<'a> StripUnconfigured<'a> {
298298
cfg_attr: &Attribute,
299299
(item, item_span): (ast::AttrItem, Span),
300300
) -> Attribute {
301-
// We are taking an attribute of the form `#[cfg_attr(pred, attr)]`
302-
// and producing an attribute of the form `#[attr]`. We
303-
// have captured tokens for `attr` itself, but we need to
304-
// synthesize tokens for the wrapper `#` and `[]`, which
305-
// we do below.
306-
307-
// Use the `#` in `#[cfg_attr(pred, attr)]` as the `#` token
308-
// for `attr` when we expand it to `#[attr]`
301+
// Convert `#[cfg_attr(pred, attr)]` to `#[attr]`.
302+
303+
// Use the `#` from `#[cfg_attr(pred, attr)]` in the result `#[attr]`.
309304
let mut orig_trees = cfg_attr.token_trees().into_iter();
310-
let TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _) =
311-
orig_trees.next().unwrap().clone()
305+
let Some(TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _)) =
306+
orig_trees.next()
312307
else {
313308
panic!("Bad tokens for attribute {cfg_attr:?}");
314309
};
315310

316-
// We don't really have a good span to use for the synthesized `[]`
317-
// in `#[attr]`, so just use the span of the `#` token.
318-
let bracket_group = AttrTokenTree::Delimited(
319-
DelimSpan::from_single(pound_token.span),
320-
DelimSpacing::new(Spacing::JointHidden, Spacing::Alone),
321-
Delimiter::Bracket,
322-
item.tokens
323-
.as_ref()
324-
.unwrap_or_else(|| panic!("Missing tokens for {item:?}"))
325-
.to_attr_token_stream(),
326-
);
327-
let trees = if cfg_attr.style == AttrStyle::Inner {
328-
// For inner attributes, we do the same thing for the `!` in `#![some_attr]`
329-
let TokenTree::Token(bang_token @ Token { kind: TokenKind::Not, .. }, _) =
330-
orig_trees.next().unwrap().clone()
311+
// For inner attributes, we do the same thing for the `!` in `#![attr]`.
312+
let mut trees = if cfg_attr.style == AttrStyle::Inner {
313+
let Some(TokenTree::Token(bang_token @ Token { kind: TokenKind::Not, .. }, _)) =
314+
orig_trees.next()
331315
else {
332316
panic!("Bad tokens for attribute {cfg_attr:?}");
333317
};
334318
vec![
335319
AttrTokenTree::Token(pound_token, Spacing::Joint),
336320
AttrTokenTree::Token(bang_token, Spacing::JointHidden),
337-
bracket_group,
338321
]
339322
} else {
340-
vec![AttrTokenTree::Token(pound_token, Spacing::JointHidden), bracket_group]
323+
vec![AttrTokenTree::Token(pound_token, Spacing::JointHidden)]
341324
};
325+
326+
// And the same thing for the `[`/`]` delimiters in `#[attr]`.
327+
let Some(TokenTree::Delimited(delim_span, delim_spacing, Delimiter::Bracket, _)) =
328+
orig_trees.next()
329+
else {
330+
panic!("Bad tokens for attribute {cfg_attr:?}");
331+
};
332+
trees.push(AttrTokenTree::Delimited(
333+
delim_span,
334+
delim_spacing,
335+
Delimiter::Bracket,
336+
item.tokens
337+
.as_ref()
338+
.unwrap_or_else(|| panic!("Missing tokens for {item:?}"))
339+
.to_attr_token_stream(),
340+
));
341+
342342
let tokens = Some(LazyAttrTokenStream::new(AttrTokenStream::new(trees)));
343343
let attr = attr::mk_attr_from_item(
344344
&self.sess.psess.attr_id_generator,

compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs

+20-14
Original file line numberDiff line numberDiff line change
@@ -888,7 +888,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
888888
let comma = if args.len() > 0 { ", " } else { "" };
889889
let trait_path = self.tcx.def_path_str(trait_def_id);
890890
let method_name = self.tcx.item_name(self.def_id);
891-
err.span_suggestion(
891+
err.span_suggestion_verbose(
892892
expr.span,
893893
msg,
894894
format!("{trait_path}::{generics}::{method_name}({rcvr}{comma}{rest})"),
@@ -939,18 +939,20 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
939939
}
940940
}
941941

942-
let span_lo_redundant_lt_args = lt_arg_spans[self.num_expected_lifetime_args()];
942+
let span_lo_redundant_lt_args = if self.num_expected_lifetime_args() == 0 {
943+
lt_arg_spans[0]
944+
} else {
945+
lt_arg_spans[self.num_expected_lifetime_args() - 1]
946+
};
943947
let span_hi_redundant_lt_args = lt_arg_spans[lt_arg_spans.len() - 1];
944948

945-
let span_redundant_lt_args = span_lo_redundant_lt_args.to(span_hi_redundant_lt_args);
949+
let span_redundant_lt_args =
950+
span_lo_redundant_lt_args.shrink_to_hi().to(span_hi_redundant_lt_args);
946951
debug!("span_redundant_lt_args: {:?}", span_redundant_lt_args);
947952

948953
let num_redundant_lt_args = lt_arg_spans.len() - self.num_expected_lifetime_args();
949-
let msg_lifetimes = format!(
950-
"remove {these} lifetime argument{s}",
951-
these = pluralize!("this", num_redundant_lt_args),
952-
s = pluralize!(num_redundant_lt_args),
953-
);
954+
let msg_lifetimes =
955+
format!("remove the lifetime argument{s}", s = pluralize!(num_redundant_lt_args));
954956

955957
err.span_suggestion(
956958
span_redundant_lt_args,
@@ -979,18 +981,22 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
979981
}
980982

981983
let span_lo_redundant_type_or_const_args =
982-
gen_arg_spans[self.num_expected_type_or_const_args()];
984+
if self.num_expected_type_or_const_args() == 0 {
985+
gen_arg_spans[0]
986+
} else {
987+
gen_arg_spans[self.num_expected_type_or_const_args() - 1]
988+
};
983989
let span_hi_redundant_type_or_const_args = gen_arg_spans[gen_arg_spans.len() - 1];
990+
let span_redundant_type_or_const_args = span_lo_redundant_type_or_const_args
991+
.shrink_to_hi()
992+
.to(span_hi_redundant_type_or_const_args);
984993

985-
let span_redundant_type_or_const_args =
986-
span_lo_redundant_type_or_const_args.to(span_hi_redundant_type_or_const_args);
987994
debug!("span_redundant_type_or_const_args: {:?}", span_redundant_type_or_const_args);
988995

989996
let num_redundant_gen_args =
990997
gen_arg_spans.len() - self.num_expected_type_or_const_args();
991998
let msg_types_or_consts = format!(
992-
"remove {these} generic argument{s}",
993-
these = pluralize!("this", num_redundant_gen_args),
999+
"remove the unnecessary generic argument{s}",
9941000
s = pluralize!(num_redundant_gen_args),
9951001
);
9961002

@@ -1036,7 +1042,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
10361042
.with_lo(self.path_segment.ident.span.hi());
10371043

10381044
let msg = format!(
1039-
"remove these {}generics",
1045+
"remove the unnecessary {}generics",
10401046
if self.gen_args.parenthesized == hir::GenericArgsParentheses::ParenSugar {
10411047
"parenthetical "
10421048
} else {

library/alloc/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@
101101
#![feature(array_windows)]
102102
#![feature(ascii_char)]
103103
#![feature(assert_matches)]
104+
#![feature(async_closure)]
104105
#![feature(async_fn_traits)]
105106
#![feature(async_iterator)]
106107
#![feature(clone_to_uninit)]

library/alloc/src/rc.rs

+22-25
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ use core::intrinsics::abort;
259259
#[cfg(not(no_global_oom_handling))]
260260
use core::iter;
261261
use core::marker::{PhantomData, Unsize};
262-
use core::mem::{self, align_of_val_raw, forget, ManuallyDrop};
262+
use core::mem::{self, align_of_val_raw, ManuallyDrop};
263263
use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver};
264264
use core::panic::{RefUnwindSafe, UnwindSafe};
265265
#[cfg(not(no_global_oom_handling))]
@@ -908,19 +908,18 @@ impl<T, A: Allocator> Rc<T, A> {
908908
#[stable(feature = "rc_unique", since = "1.4.0")]
909909
pub fn try_unwrap(this: Self) -> Result<T, Self> {
910910
if Rc::strong_count(&this) == 1 {
911-
unsafe {
912-
let val = ptr::read(&*this); // copy the contained object
913-
let alloc = ptr::read(&this.alloc); // copy the allocator
914-
915-
// Indicate to Weaks that they can't be promoted by decrementing
916-
// the strong count, and then remove the implicit "strong weak"
917-
// pointer while also handling drop logic by just crafting a
918-
// fake Weak.
919-
this.inner().dec_strong();
920-
let _weak = Weak { ptr: this.ptr, alloc };
921-
forget(this);
922-
Ok(val)
923-
}
911+
let this = ManuallyDrop::new(this);
912+
913+
let val: T = unsafe { ptr::read(&**this) }; // copy the contained object
914+
let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator
915+
916+
// Indicate to Weaks that they can't be promoted by decrementing
917+
// the strong count, and then remove the implicit "strong weak"
918+
// pointer while also handling drop logic by just crafting a
919+
// fake Weak.
920+
this.inner().dec_strong();
921+
let _weak = Weak { ptr: this.ptr, alloc };
922+
Ok(val)
924923
} else {
925924
Err(this)
926925
}
@@ -1354,9 +1353,8 @@ impl<T: ?Sized, A: Allocator> Rc<T, A> {
13541353
#[stable(feature = "rc_raw", since = "1.17.0")]
13551354
#[rustc_never_returns_null_ptr]
13561355
pub fn into_raw(this: Self) -> *const T {
1357-
let ptr = Self::as_ptr(&this);
1358-
mem::forget(this);
1359-
ptr
1356+
let this = ManuallyDrop::new(this);
1357+
Self::as_ptr(&*this)
13601358
}
13611359

13621360
/// Consumes the `Rc`, returning the wrapped pointer and allocator.
@@ -2127,7 +2125,7 @@ impl<T> Rc<[T]> {
21272125
}
21282126

21292127
// All clear. Forget the guard so it doesn't free the new RcBox.
2130-
forget(guard);
2128+
mem::forget(guard);
21312129

21322130
Self::from_ptr(ptr)
21332131
}
@@ -3080,9 +3078,7 @@ impl<T: ?Sized, A: Allocator> Weak<T, A> {
30803078
#[must_use = "losing the pointer will leak memory"]
30813079
#[stable(feature = "weak_into_raw", since = "1.45.0")]
30823080
pub fn into_raw(self) -> *const T {
3083-
let result = self.as_ptr();
3084-
mem::forget(self);
3085-
result
3081+
mem::ManuallyDrop::new(self).as_ptr()
30863082
}
30873083

30883084
/// Consumes the `Weak<T>`, returning the wrapped pointer and allocator.
@@ -3762,10 +3758,11 @@ impl<T: ?Sized, A: Allocator> UniqueRcUninit<T, A> {
37623758
/// # Safety
37633759
///
37643760
/// The data must have been initialized (by writing to [`Self::data_ptr()`]).
3765-
unsafe fn into_rc(mut self) -> Rc<T, A> {
3766-
let ptr = self.ptr;
3767-
let alloc = self.alloc.take().unwrap();
3768-
mem::forget(self);
3761+
unsafe fn into_rc(self) -> Rc<T, A> {
3762+
let mut this = ManuallyDrop::new(self);
3763+
let ptr = this.ptr;
3764+
let alloc = this.alloc.take().unwrap();
3765+
37693766
// SAFETY: The pointer is valid as per `UniqueRcUninit::new`, and the caller is responsible
37703767
// for having initialized the data.
37713768
unsafe { Rc::from_ptr_in(ptr.as_ptr(), alloc) }

library/alloc/src/sync.rs

+16-20
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use core::intrinsics::abort;
2020
#[cfg(not(no_global_oom_handling))]
2121
use core::iter;
2222
use core::marker::{PhantomData, Unsize};
23-
use core::mem::{self, align_of_val_raw};
23+
use core::mem::{self, align_of_val_raw, ManuallyDrop};
2424
use core::ops::{CoerceUnsized, Deref, DerefPure, DispatchFromDyn, Receiver};
2525
use core::panic::{RefUnwindSafe, UnwindSafe};
2626
use core::pin::Pin;
@@ -960,16 +960,14 @@ impl<T, A: Allocator> Arc<T, A> {
960960

961961
acquire!(this.inner().strong);
962962

963-
unsafe {
964-
let elem = ptr::read(&this.ptr.as_ref().data);
965-
let alloc = ptr::read(&this.alloc); // copy the allocator
963+
let this = ManuallyDrop::new(this);
964+
let elem: T = unsafe { ptr::read(&this.ptr.as_ref().data) };
965+
let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator
966966

967-
// Make a weak pointer to clean up the implicit strong-weak reference
968-
let _weak = Weak { ptr: this.ptr, alloc };
969-
mem::forget(this);
967+
// Make a weak pointer to clean up the implicit strong-weak reference
968+
let _weak = Weak { ptr: this.ptr, alloc };
970969

971-
Ok(elem)
972-
}
970+
Ok(elem)
973971
}
974972

975973
/// Returns the inner value, if the `Arc` has exactly one strong reference.
@@ -1493,9 +1491,8 @@ impl<T: ?Sized, A: Allocator> Arc<T, A> {
14931491
#[stable(feature = "rc_raw", since = "1.17.0")]
14941492
#[rustc_never_returns_null_ptr]
14951493
pub fn into_raw(this: Self) -> *const T {
1496-
let ptr = Self::as_ptr(&this);
1497-
mem::forget(this);
1498-
ptr
1494+
let this = ManuallyDrop::new(this);
1495+
Self::as_ptr(&*this)
14991496
}
15001497

15011498
/// Consumes the `Arc`, returning the wrapped pointer and allocator.
@@ -2801,9 +2798,7 @@ impl<T: ?Sized, A: Allocator> Weak<T, A> {
28012798
#[must_use = "losing the pointer will leak memory"]
28022799
#[stable(feature = "weak_into_raw", since = "1.45.0")]
28032800
pub fn into_raw(self) -> *const T {
2804-
let result = self.as_ptr();
2805-
mem::forget(self);
2806-
result
2801+
ManuallyDrop::new(self).as_ptr()
28072802
}
28082803

28092804
/// Consumes the `Weak<T>`, returning the wrapped pointer and allocator.
@@ -3875,13 +3870,14 @@ impl<T: ?Sized, A: Allocator> UniqueArcUninit<T, A> {
38753870
/// # Safety
38763871
///
38773872
/// The data must have been initialized (by writing to [`Self::data_ptr()`]).
3878-
unsafe fn into_arc(mut self) -> Arc<T, A> {
3879-
let ptr = self.ptr;
3880-
let alloc = self.alloc.take().unwrap();
3881-
mem::forget(self);
3873+
unsafe fn into_arc(self) -> Arc<T, A> {
3874+
let mut this = ManuallyDrop::new(self);
3875+
let ptr = this.ptr.as_ptr();
3876+
let alloc = this.alloc.take().unwrap();
3877+
38823878
// SAFETY: The pointer is valid as per `UniqueArcUninit::new`, and the caller is responsible
38833879
// for having initialized the data.
3884-
unsafe { Arc::from_ptr_in(ptr.as_ptr(), alloc) }
3880+
unsafe { Arc::from_ptr_in(ptr, alloc) }
38853881
}
38863882
}
38873883

library/core/src/alloc/layout.rs

+2
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,8 @@ impl Layout {
183183
/// - a [slice], then the length of the slice tail must be an initialized
184184
/// integer, and the size of the *entire value*
185185
/// (dynamic tail length + statically sized prefix) must fit in `isize`.
186+
/// For the special case where the dynamic tail length is 0, this function
187+
/// is safe to call.
186188
/// - a [trait object], then the vtable part of the pointer must point
187189
/// to a valid vtable for the type `T` acquired by an unsizing coercion,
188190
/// and the size of the *entire value*

0 commit comments

Comments
 (0)