Skip to content

Commit 803a759

Browse files
committed
Auto merge of #94751 - Dylan-DPC:rollup-zr7viw0, r=Dylan-DPC
Rollup of 5 pull requests Successful merges: - #94689 (Use impl substs in `#[rustc_on_unimplemented]`) - #94714 (Enable `close_read_wakes_up` test on Windows) - #94723 (Add core::hint::must_use) - #94724 (unix: Avoid name conversions in `remove_dir_all_recursive`) - #94730 (Reverted atomic_mut_ptr feature removal causing compilation break) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2 parents 1eb7258 + 5629026 commit 803a759

File tree

14 files changed

+262
-53
lines changed

14 files changed

+262
-53
lines changed

compiler/rustc_middle/src/ty/sty.rs

-1
Original file line numberDiff line numberDiff line change
@@ -977,7 +977,6 @@ impl<'tcx> TraitRef<'tcx> {
977977
substs: SubstsRef<'tcx>,
978978
) -> ty::TraitRef<'tcx> {
979979
let defs = tcx.generics_of(trait_id);
980-
981980
ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) }
982981
}
983982
}

compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs

+14-14
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use super::{
44
use crate::infer::InferCtxt;
55
use rustc_hir as hir;
66
use rustc_hir::def_id::DefId;
7-
use rustc_middle::ty::subst::Subst;
7+
use rustc_middle::ty::subst::{Subst, SubstsRef};
88
use rustc_middle::ty::{self, GenericParamDefKind};
99
use rustc_span::symbol::sym;
1010
use std::iter;
@@ -17,7 +17,7 @@ crate trait InferCtxtExt<'tcx> {
1717
&self,
1818
trait_ref: ty::PolyTraitRef<'tcx>,
1919
obligation: &PredicateObligation<'tcx>,
20-
) -> Option<DefId>;
20+
) -> Option<(DefId, SubstsRef<'tcx>)>;
2121

2222
/*private*/
2323
fn describe_enclosure(&self, hir_id: hir::HirId) -> Option<&'static str>;
@@ -34,7 +34,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
3434
&self,
3535
trait_ref: ty::PolyTraitRef<'tcx>,
3636
obligation: &PredicateObligation<'tcx>,
37-
) -> Option<DefId> {
37+
) -> Option<(DefId, SubstsRef<'tcx>)> {
3838
let tcx = self.tcx;
3939
let param_env = obligation.param_env;
4040
let trait_ref = tcx.erase_late_bound_regions(trait_ref);
@@ -50,28 +50,29 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
5050
let impl_self_ty = impl_trait_ref.self_ty();
5151

5252
if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
53-
self_match_impls.push(def_id);
53+
self_match_impls.push((def_id, impl_substs));
5454

5555
if iter::zip(
5656
trait_ref.substs.types().skip(1),
5757
impl_trait_ref.substs.types().skip(1),
5858
)
5959
.all(|(u, v)| self.fuzzy_match_tys(u, v, false).is_some())
6060
{
61-
fuzzy_match_impls.push(def_id);
61+
fuzzy_match_impls.push((def_id, impl_substs));
6262
}
6363
}
6464
});
6565

66-
let impl_def_id = if self_match_impls.len() == 1 {
66+
let impl_def_id_and_substs = if self_match_impls.len() == 1 {
6767
self_match_impls[0]
6868
} else if fuzzy_match_impls.len() == 1 {
6969
fuzzy_match_impls[0]
7070
} else {
7171
return None;
7272
};
7373

74-
tcx.has_attr(impl_def_id, sym::rustc_on_unimplemented).then_some(impl_def_id)
74+
tcx.has_attr(impl_def_id_and_substs.0, sym::rustc_on_unimplemented)
75+
.then_some(impl_def_id_and_substs)
7576
}
7677

7778
/// Used to set on_unimplemented's `ItemContext`
@@ -120,8 +121,9 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
120121
trait_ref: ty::PolyTraitRef<'tcx>,
121122
obligation: &PredicateObligation<'tcx>,
122123
) -> OnUnimplementedNote {
123-
let def_id =
124-
self.impl_similar_to(trait_ref, obligation).unwrap_or_else(|| trait_ref.def_id());
124+
let (def_id, substs) = self
125+
.impl_similar_to(trait_ref, obligation)
126+
.unwrap_or_else(|| (trait_ref.def_id(), trait_ref.skip_binder().substs));
125127
let trait_ref = trait_ref.skip_binder();
126128

127129
let mut flags = vec![(
@@ -176,15 +178,15 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
176178
for param in generics.params.iter() {
177179
let value = match param.kind {
178180
GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
179-
trait_ref.substs[param.index as usize].to_string()
181+
substs[param.index as usize].to_string()
180182
}
181183
GenericParamDefKind::Lifetime => continue,
182184
};
183185
let name = param.name;
184186
flags.push((name, Some(value)));
185187

186188
if let GenericParamDefKind::Type { .. } = param.kind {
187-
let param_ty = trait_ref.substs[param.index as usize].expect_ty();
189+
let param_ty = substs[param.index as usize].expect_ty();
188190
if let Some(def) = param_ty.ty_adt_def() {
189191
// We also want to be able to select the parameter's
190192
// original signature with no type arguments resolved
@@ -229,9 +231,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
229231
}
230232
});
231233

232-
if let Ok(Some(command)) =
233-
OnUnimplementedDirective::of_item(self.tcx, trait_ref.def_id, def_id)
234-
{
234+
if let Ok(Some(command)) = OnUnimplementedDirective::of_item(self.tcx, def_id) {
235235
command.evaluate(self.tcx, trait_ref, &flags)
236236
} else {
237237
OnUnimplementedNote::default()

compiler/rustc_trait_selection/src/traits/on_unimplemented.rs

+26-20
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ fn parse_error(
5454
impl<'tcx> OnUnimplementedDirective {
5555
fn parse(
5656
tcx: TyCtxt<'tcx>,
57-
trait_def_id: DefId,
57+
item_def_id: DefId,
5858
items: &[NestedMetaItem],
5959
span: Span,
6060
is_root: bool,
@@ -63,7 +63,7 @@ impl<'tcx> OnUnimplementedDirective {
6363
let mut item_iter = items.iter();
6464

6565
let parse_value = |value_str| {
66-
OnUnimplementedFormatString::try_parse(tcx, trait_def_id, value_str, span).map(Some)
66+
OnUnimplementedFormatString::try_parse(tcx, item_def_id, value_str, span).map(Some)
6767
};
6868

6969
let condition = if is_root {
@@ -135,7 +135,7 @@ impl<'tcx> OnUnimplementedDirective {
135135
{
136136
if let Some(items) = item.meta_item_list() {
137137
if let Ok(subcommand) =
138-
Self::parse(tcx, trait_def_id, &items, item.span(), false)
138+
Self::parse(tcx, item_def_id, &items, item.span(), false)
139139
{
140140
subcommands.push(subcommand);
141141
} else {
@@ -178,27 +178,23 @@ impl<'tcx> OnUnimplementedDirective {
178178
}
179179
}
180180

181-
pub fn of_item(
182-
tcx: TyCtxt<'tcx>,
183-
trait_def_id: DefId,
184-
impl_def_id: DefId,
185-
) -> Result<Option<Self>, ErrorGuaranteed> {
186-
let attrs = tcx.get_attrs(impl_def_id);
181+
pub fn of_item(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> Result<Option<Self>, ErrorGuaranteed> {
182+
let attrs = tcx.get_attrs(item_def_id);
187183

188184
let Some(attr) = tcx.sess.find_by_name(&attrs, sym::rustc_on_unimplemented) else {
189185
return Ok(None);
190186
};
191187

192188
let result = if let Some(items) = attr.meta_item_list() {
193-
Self::parse(tcx, trait_def_id, &items, attr.span, true).map(Some)
189+
Self::parse(tcx, item_def_id, &items, attr.span, true).map(Some)
194190
} else if let Some(value) = attr.value_str() {
195191
Ok(Some(OnUnimplementedDirective {
196192
condition: None,
197193
message: None,
198194
subcommands: vec![],
199195
label: Some(OnUnimplementedFormatString::try_parse(
200196
tcx,
201-
trait_def_id,
197+
item_def_id,
202198
value,
203199
attr.span,
204200
)?),
@@ -209,7 +205,7 @@ impl<'tcx> OnUnimplementedDirective {
209205
} else {
210206
return Err(ErrorGuaranteed);
211207
};
212-
debug!("of_item({:?}/{:?}) = {:?}", trait_def_id, impl_def_id, result);
208+
debug!("of_item({:?}) = {:?}", item_def_id, result);
213209
result
214210
}
215211

@@ -280,23 +276,29 @@ impl<'tcx> OnUnimplementedDirective {
280276
impl<'tcx> OnUnimplementedFormatString {
281277
fn try_parse(
282278
tcx: TyCtxt<'tcx>,
283-
trait_def_id: DefId,
279+
item_def_id: DefId,
284280
from: Symbol,
285281
err_sp: Span,
286282
) -> Result<Self, ErrorGuaranteed> {
287283
let result = OnUnimplementedFormatString(from);
288-
result.verify(tcx, trait_def_id, err_sp)?;
284+
result.verify(tcx, item_def_id, err_sp)?;
289285
Ok(result)
290286
}
291287

292288
fn verify(
293289
&self,
294290
tcx: TyCtxt<'tcx>,
295-
trait_def_id: DefId,
291+
item_def_id: DefId,
296292
span: Span,
297293
) -> Result<(), ErrorGuaranteed> {
298-
let name = tcx.item_name(trait_def_id);
299-
let generics = tcx.generics_of(trait_def_id);
294+
let trait_def_id = if tcx.is_trait(item_def_id) {
295+
item_def_id
296+
} else {
297+
tcx.trait_id_of_impl(item_def_id)
298+
.expect("expected `on_unimplemented` to correspond to a trait")
299+
};
300+
let trait_name = tcx.item_name(trait_def_id);
301+
let generics = tcx.generics_of(item_def_id);
300302
let s = self.0.as_str();
301303
let parser = Parser::new(s, None, None, false, ParseMode::Format);
302304
let mut result = Ok(());
@@ -307,7 +309,7 @@ impl<'tcx> OnUnimplementedFormatString {
307309
// `{Self}` is allowed
308310
Position::ArgumentNamed(s, _) if s == kw::SelfUpper => (),
309311
// `{ThisTraitsName}` is allowed
310-
Position::ArgumentNamed(s, _) if s == name => (),
312+
Position::ArgumentNamed(s, _) if s == trait_name => (),
311313
// `{from_method}` is allowed
312314
Position::ArgumentNamed(s, _) if s == sym::from_method => (),
313315
// `{from_desugaring}` is allowed
@@ -329,9 +331,13 @@ impl<'tcx> OnUnimplementedFormatString {
329331
tcx.sess,
330332
span,
331333
E0230,
332-
"there is no parameter `{}` on trait `{}`",
334+
"there is no parameter `{}` on {}",
333335
s,
334-
name
336+
if trait_def_id == item_def_id {
337+
format!("trait `{}`", trait_name)
338+
} else {
339+
"impl".to_string()
340+
}
335341
)
336342
.emit();
337343
result = Err(ErrorGuaranteed);

compiler/rustc_typeck/src/check/check.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -742,12 +742,11 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
742742
impl_trait_ref,
743743
&impl_.items,
744744
);
745-
let trait_def_id = impl_trait_ref.def_id;
746-
check_on_unimplemented(tcx, trait_def_id, it);
745+
check_on_unimplemented(tcx, it);
747746
}
748747
}
749748
hir::ItemKind::Trait(_, _, _, _, ref items) => {
750-
check_on_unimplemented(tcx, it.def_id.to_def_id(), it);
749+
check_on_unimplemented(tcx, it);
751750

752751
for item in items.iter() {
753752
let item = tcx.hir().trait_item(item.id);
@@ -857,9 +856,9 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
857856
}
858857
}
859858

860-
pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) {
859+
pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
861860
// an error would be reported if this fails.
862-
let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item.def_id.to_def_id());
861+
let _ = traits::OnUnimplementedDirective::of_item(tcx, item.def_id.to_def_id());
863862
}
864863

865864
pub(super) fn check_specialization_validity<'tcx>(

library/core/src/hint.rs

+123
Original file line numberDiff line numberDiff line change
@@ -173,3 +173,126 @@ pub fn spin_loop() {
173173
pub const fn black_box<T>(dummy: T) -> T {
174174
crate::intrinsics::black_box(dummy)
175175
}
176+
177+
/// An identity function that causes an `unused_must_use` warning to be
178+
/// triggered if the given value is not used (returned, stored in a variable,
179+
/// etc) by the caller.
180+
///
181+
/// This is primarily intended for use in macro-generated code, in which a
182+
/// [`#[must_use]` attribute][must_use] either on a type or a function would not
183+
/// be convenient.
184+
///
185+
/// [must_use]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
186+
///
187+
/// # Example
188+
///
189+
/// ```
190+
/// #![feature(hint_must_use)]
191+
///
192+
/// use core::fmt;
193+
///
194+
/// pub struct Error(/* ... */);
195+
///
196+
/// #[macro_export]
197+
/// macro_rules! make_error {
198+
/// ($($args:expr),*) => {
199+
/// core::hint::must_use({
200+
/// let error = $crate::make_error(core::format_args!($($args),*));
201+
/// error
202+
/// })
203+
/// };
204+
/// }
205+
///
206+
/// // Implementation detail of make_error! macro.
207+
/// #[doc(hidden)]
208+
/// pub fn make_error(args: fmt::Arguments<'_>) -> Error {
209+
/// Error(/* ... */)
210+
/// }
211+
///
212+
/// fn demo() -> Option<Error> {
213+
/// if true {
214+
/// // Oops, meant to write `return Some(make_error!("..."));`
215+
/// Some(make_error!("..."));
216+
/// }
217+
/// None
218+
/// }
219+
/// #
220+
/// # // Make rustdoc not wrap the whole snippet in fn main, so that $crate::make_error works
221+
/// # fn main() {}
222+
/// ```
223+
///
224+
/// In the above example, we'd like an `unused_must_use` lint to apply to the
225+
/// value created by `make_error!`. However, neither `#[must_use]` on a struct
226+
/// nor `#[must_use]` on a function is appropriate here, so the macro expands
227+
/// using `core::hint::must_use` instead.
228+
///
229+
/// - We wouldn't want `#[must_use]` on the `struct Error` because that would
230+
/// make the following unproblematic code trigger a warning:
231+
///
232+
/// ```
233+
/// # struct Error;
234+
/// #
235+
/// fn f(arg: &str) -> Result<(), Error>
236+
/// # { Ok(()) }
237+
///
238+
/// #[test]
239+
/// fn t() {
240+
/// // Assert that `f` returns error if passed an empty string.
241+
/// // A value of type `Error` is unused here but that's not a problem.
242+
/// f("").unwrap_err();
243+
/// }
244+
/// ```
245+
///
246+
/// - Using `#[must_use]` on `fn make_error` can't help because the return value
247+
/// *is* used, as the right-hand side of a `let` statement. The `let`
248+
/// statement looks useless but is in fact necessary for ensuring that
249+
/// temporaries within the `format_args` expansion are not kept alive past the
250+
/// creation of the `Error`, as keeping them alive past that point can cause
251+
/// autotrait issues in async code:
252+
///
253+
/// ```
254+
/// # #![feature(hint_must_use)]
255+
/// #
256+
/// # struct Error;
257+
/// #
258+
/// # macro_rules! make_error {
259+
/// # ($($args:expr),*) => {
260+
/// # core::hint::must_use({
261+
/// # // If `let` isn't used, then `f()` produces a non-Send future.
262+
/// # let error = make_error(core::format_args!($($args),*));
263+
/// # error
264+
/// # })
265+
/// # };
266+
/// # }
267+
/// #
268+
/// # fn make_error(args: core::fmt::Arguments<'_>) -> Error {
269+
/// # Error
270+
/// # }
271+
/// #
272+
/// async fn f() {
273+
/// // Using `let` inside the make_error expansion causes temporaries like
274+
/// // `unsync()` to drop at the semicolon of that `let` statement, which
275+
/// // is prior to the await point. They would otherwise stay around until
276+
/// // the semicolon on *this* statement, which is after the await point,
277+
/// // and the enclosing Future would not implement Send.
278+
/// log(make_error!("look: {:p}", unsync())).await;
279+
/// }
280+
///
281+
/// async fn log(error: Error) {/* ... */}
282+
///
283+
/// // Returns something without a Sync impl.
284+
/// fn unsync() -> *const () {
285+
/// 0 as *const ()
286+
/// }
287+
/// #
288+
/// # fn test() {
289+
/// # fn assert_send(_: impl Send) {}
290+
/// # assert_send(f());
291+
/// # }
292+
/// ```
293+
#[unstable(feature = "hint_must_use", issue = "94745")]
294+
#[rustc_const_unstable(feature = "hint_must_use", issue = "94745")]
295+
#[must_use] // <-- :)
296+
pub const fn must_use<T>(value: T) -> T {
297+
value
298+
}

library/std/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,7 @@
231231
#![feature(assert_matches)]
232232
#![feature(associated_type_bounds)]
233233
#![feature(async_iterator)]
234+
#![feature(atomic_mut_ptr)]
234235
#![feature(bench_black_box)]
235236
#![feature(box_syntax)]
236237
#![feature(c_unwind)]

0 commit comments

Comments
 (0)