diff --git a/compiler/rustc_trait_selection/src/diagnostics.rs b/compiler/rustc_trait_selection/src/diagnostics.rs index 90f6faaad1d..112cbf68f83 100644 --- a/compiler/rustc_trait_selection/src/diagnostics.rs +++ b/compiler/rustc_trait_selection/src/diagnostics.rs @@ -1935,6 +1935,17 @@ pub fn impl_trait_overcapture_suggestion<'tcx>( fn_def_id: LocalDefId, captured_args: FxIndexSet, ) -> Option { + let rpit_span = tcx.def_span(opaque_def_id); + + // Every suggestion below is anchored on the opaque's span, so bail if that span is not one + // the user can edit. AST lowering marks it with the `impl Trait` desugaring, hence the + // question is about the span it desugared from: for an opaque created inside a macro + // expansion that span is the expansion site, which for an attribute macro is the attribute + // itself, where `+ use<..>` does not even parse. + if rpit_span.parent_callsite().is_some_and(|span| !span.can_be_used_for_suggestions()) { + return None; + } + let generics = tcx.generics_of(fn_def_id); let mut captured_lifetimes = FxIndexSet::default(); @@ -2036,7 +2047,6 @@ pub fn impl_trait_overcapture_suggestion<'tcx>( _ => ("", ""), }; - let rpit_span = tcx.def_span(opaque_def_id); if !lparen.is_empty() { suggs.push((rpit_span.shrink_to_lo(), lparen.to_string())); } diff --git a/tests/ui/impl-trait/precise-capturing/overcapture-suggestion-in-macro-issue-139567.stderr b/tests/ui/impl-trait/precise-capturing/overcapture-suggestion-in-macro-issue-139567.stderr index ab6bd9c1173..9f70c2f0759 100644 --- a/tests/ui/impl-trait/precise-capturing/overcapture-suggestion-in-macro-issue-139567.stderr +++ b/tests/ui/impl-trait/precise-capturing/overcapture-suggestion-in-macro-issue-139567.stderr @@ -18,10 +18,6 @@ note: the lint level is defined here LL | #![deny(impl_trait_overcaptures)] | ^^^^^^^^^^^^^^^^^^^^^^^ = note: this error originates in the attribute macro `overcapture_attr_pm::rpc` (in Nightly builds, run with -Z macro-backtrace for more info) -help: use the precise capturing `use<...>` syntax to make the captures explicit - | -LL | #[overcapture_attr_pm::rpc] + use<> - | +++++++ error: `impl Sized` will capture more lifetimes than possibly intended in edition 2024 --> $DIR/overcapture-suggestion-in-macro-issue-139567.rs:12:25 @@ -88,10 +84,6 @@ LL | mk_body!(); = note: all lifetimes in scope will be captured by `impl Trait`s in edition 2024 = warning: this changes meaning in Rust 2024 = note: for more information, see -help: use the precise capturing `use<...>` syntax to make the captures explicit - | -LL | pub fn from_macro_body(x: &u8) -> impl Sized + use<> { *x } - | +++++++ error: aborting due to 4 previous errors