Skip to content

Commit a1f9d5b

Browse files
Dont suggest use<APIT>
1 parent ad20906 commit a1f9d5b

File tree

6 files changed

+133
-56
lines changed

6 files changed

+133
-56
lines changed

compiler/rustc_borrowck/src/diagnostics/opaque_suggestions.rs

+45-26
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,16 @@
44
use std::ops::ControlFlow;
55

66
use either::Either;
7+
use itertools::Itertools as _;
78
use rustc_data_structures::fx::FxIndexSet;
8-
use rustc_errors::{Applicability, Diag};
9+
use rustc_errors::{Diag, Subdiagnostic};
910
use rustc_hir as hir;
1011
use rustc_hir::def_id::DefId;
1112
use rustc_middle::mir::{self, ConstraintCategory, Location};
1213
use rustc_middle::ty::{
1314
self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
1415
};
15-
use rustc_span::Symbol;
16+
use rustc_trait_selection::errors::impl_trait_overcapture_suggestion;
1617

1718
use crate::MirBorrowckCtxt;
1819
use crate::borrow_set::BorrowData;
@@ -61,6 +62,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
6162
// *does* mention. We'll use that for the `+ use<'a>` suggestion below.
6263
let mut visitor = CheckExplicitRegionMentionAndCollectGenerics {
6364
tcx,
65+
generics: tcx.generics_of(opaque_def_id),
6466
offending_region_idx,
6567
seen_opaques: [opaque_def_id].into_iter().collect(),
6668
seen_lifetimes: Default::default(),
@@ -83,34 +85,50 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
8385
"this call may capture more lifetimes than intended, \
8486
because Rust 2024 has adjusted the `impl Trait` lifetime capture rules",
8587
);
86-
let mut seen_generics: Vec<_> =
87-
visitor.seen_lifetimes.iter().map(ToString::to_string).collect();
88-
// Capture all in-scope ty/const params.
89-
seen_generics.extend(
90-
ty::GenericArgs::identity_for_item(tcx, opaque_def_id)
91-
.iter()
92-
.filter(|arg| {
93-
matches!(
94-
arg.unpack(),
95-
ty::GenericArgKind::Type(_) | ty::GenericArgKind::Const(_)
96-
)
97-
})
98-
.map(|arg| arg.to_string()),
99-
);
100-
if opaque_def_id.is_local() {
101-
diag.span_suggestion_verbose(
102-
tcx.def_span(opaque_def_id).shrink_to_hi(),
103-
"add a precise capturing bound to avoid overcapturing",
104-
format!(" + use<{}>", seen_generics.join(", ")),
105-
Applicability::MaybeIncorrect,
106-
);
88+
let mut captured_args = visitor.seen_lifetimes;
89+
// Add in all of the type and const params, too.
90+
// Ordering here is kinda strange b/c we're walking backwards,
91+
// but we're trying to provide *a* suggestion, not a nice one.
92+
let mut next_generics = Some(visitor.generics);
93+
let mut any_synthetic = false;
94+
while let Some(generics) = next_generics {
95+
for param in &generics.own_params {
96+
if param.kind.is_ty_or_const() {
97+
captured_args.insert(param.def_id);
98+
}
99+
if param.kind.is_synthetic() {
100+
any_synthetic = true;
101+
}
102+
}
103+
next_generics = generics.parent.map(|def_id| tcx.generics_of(def_id));
104+
}
105+
106+
if let Some(opaque_def_id) = opaque_def_id.as_local()
107+
&& let hir::OpaqueTyOrigin::FnReturn { parent, .. } =
108+
tcx.hir().expect_opaque_ty(opaque_def_id).origin
109+
{
110+
if let Some(sugg) = impl_trait_overcapture_suggestion(
111+
tcx,
112+
opaque_def_id,
113+
parent,
114+
captured_args,
115+
) {
116+
sugg.add_to_diag(diag);
117+
}
107118
} else {
108119
diag.span_help(
109120
tcx.def_span(opaque_def_id),
110121
format!(
111122
"if you can modify this crate, add a precise \
112123
capturing bound to avoid overcapturing: `+ use<{}>`",
113-
seen_generics.join(", ")
124+
if any_synthetic {
125+
"/* Args */".to_string()
126+
} else {
127+
captured_args
128+
.into_iter()
129+
.map(|def_id| tcx.item_name(def_id))
130+
.join(", ")
131+
}
114132
),
115133
);
116134
}
@@ -182,9 +200,10 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindOpaqueRegion<'_, 'tcx> {
182200

183201
struct CheckExplicitRegionMentionAndCollectGenerics<'tcx> {
184202
tcx: TyCtxt<'tcx>,
203+
generics: &'tcx ty::Generics,
185204
offending_region_idx: usize,
186205
seen_opaques: FxIndexSet<DefId>,
187-
seen_lifetimes: FxIndexSet<Symbol>,
206+
seen_lifetimes: FxIndexSet<DefId>,
188207
}
189208

190209
impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for CheckExplicitRegionMentionAndCollectGenerics<'tcx> {
@@ -214,7 +233,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for CheckExplicitRegionMentionAndCollectGen
214233
if param.index as usize == self.offending_region_idx {
215234
ControlFlow::Break(())
216235
} else {
217-
self.seen_lifetimes.insert(param.name);
236+
self.seen_lifetimes.insert(self.generics.region_param(param, self.tcx).def_id);
218237
ControlFlow::Continue(())
219238
}
220239
}

compiler/rustc_lint/src/impl_trait_overcaptures.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ use rustc_session::lint::FutureIncompatibilityReason;
2222
use rustc_session::{declare_lint, declare_lint_pass};
2323
use rustc_span::edition::Edition;
2424
use rustc_span::{Span, Symbol};
25-
use rustc_trait_selection::errors::{impl_trait_overcapture_suggestion, AddPreciseCapturingForOvercapture};
25+
use rustc_trait_selection::errors::{
26+
AddPreciseCapturingForOvercapture, impl_trait_overcapture_suggestion,
27+
};
2628
use rustc_trait_selection::traits::ObligationCtxt;
2729
use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt;
2830

compiler/rustc_trait_selection/messages.ftl

+4-4
Original file line numberDiff line numberDiff line change
@@ -280,10 +280,10 @@ trait_selection_outlives_content = lifetime of reference outlives lifetime of bo
280280
trait_selection_precise_capturing_existing = add `{$new_lifetime}` to the `use<...>` bound to explicitly capture it
281281
trait_selection_precise_capturing_new = add a `use<...>` bound to explicitly capture `{$new_lifetime}`
282282
283-
trait_selection_precise_capturing_overcaptures = use the precise capturing `use<...>` syntax to make the captures explicit
284-
285283
trait_selection_precise_capturing_new_but_apit = add a `use<...>` bound to explicitly capture `{$new_lifetime}` after turning all argument-position `impl Trait` into type parameters, noting that this possibly affects the API of this crate
286284
285+
trait_selection_precise_capturing_overcaptures = use the precise capturing `use<...>` syntax to make the captures explicit
286+
287287
trait_selection_prlf_defined_with_sub = the lifetime `{$sub_symbol}` defined here...
288288
trait_selection_prlf_defined_without_sub = the lifetime defined here...
289289
trait_selection_prlf_known_limitation = this is a known limitation that will be removed in the future (see issue #100013 <https://github.com/rust-lang/rust/issues/100013> for more information)
@@ -457,10 +457,10 @@ trait_selection_unable_to_construct_constant_value = unable to construct a const
457457
trait_selection_unknown_format_parameter_for_on_unimplemented_attr = there is no parameter `{$argument_name}` on trait `{$trait_name}`
458458
.help = expect either a generic argument name or {"`{Self}`"} as format argument
459459
460-
trait_selection_warn_removing_apit_params_for_undercapture = you could use a `use<...>` bound to explicitly capture `{$new_lifetime}`, but argument-position `impl Trait`s are not nameable
461-
462460
trait_selection_warn_removing_apit_params_for_overcapture = you could use a `use<...>` bound to explicitly specify captures, but argument-position `impl Trait`s are not nameable
463461
462+
trait_selection_warn_removing_apit_params_for_undercapture = you could use a `use<...>` bound to explicitly capture `{$new_lifetime}`, but argument-position `impl Trait`s are not nameable
463+
464464
trait_selection_where_copy_predicates = copy the `where` clause predicates from the trait
465465
466466
trait_selection_where_remove = remove the `where` clause

compiler/rustc_trait_selection/src/errors.rs

+20-13
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ use rustc_errors::{
66
Applicability, Diag, DiagCtxtHandle, DiagMessage, DiagStyledString, Diagnostic,
77
EmissionGuarantee, IntoDiagArg, Level, MultiSpan, SubdiagMessageOp, Subdiagnostic,
88
};
9-
use rustc_hir::def::DefKind;
109
use rustc_hir as hir;
10+
use rustc_hir::def::DefKind;
1111
use rustc_hir::def_id::{DefId, LocalDefId};
1212
use rustc_hir::intravisit::{Visitor, walk_ty};
1313
use rustc_hir::{FnRetTy, GenericParamKind};
@@ -1793,10 +1793,17 @@ impl Subdiagnostic for AddPreciseCapturingAndParams {
17931793
self.suggs,
17941794
Applicability::MaybeIncorrect,
17951795
);
1796-
diag.span_note(self.apit_spans, fluent::trait_selection_warn_removing_apit_params_for_undercapture);
1796+
diag.span_note(
1797+
self.apit_spans,
1798+
fluent::trait_selection_warn_removing_apit_params_for_undercapture,
1799+
);
17971800
}
17981801
}
17991802

1803+
/// Given a set of captured `DefId` for an RPIT (opaque_def_id) and a given
1804+
/// function (fn_def_id), try to suggest adding `+ use<...>` to capture just
1805+
/// the specified parameters. If one of those parameters is an APIT, then try
1806+
/// to suggest turning it into a regular type parameter.
18001807
pub fn impl_trait_overcapture_suggestion<'tcx>(
18011808
tcx: TyCtxt<'tcx>,
18021809
opaque_def_id: LocalDefId,
@@ -1839,12 +1846,12 @@ pub fn impl_trait_overcapture_suggestion<'tcx>(
18391846
let mut new_params = String::new();
18401847
for (i, (span, name)) in synthetics.into_iter().enumerate() {
18411848
apit_spans.push(span);
1842-
1849+
18431850
let fresh_param = next_fresh_param();
1844-
1851+
18451852
// Suggest renaming.
18461853
suggs.push((span, fresh_param.to_string()));
1847-
1854+
18481855
// Super jank. Turn `impl Trait` into `T: Trait`.
18491856
//
18501857
// This currently involves stripping the `impl` from the name of
@@ -1860,12 +1867,12 @@ pub fn impl_trait_overcapture_suggestion<'tcx>(
18601867
new_params += ": ";
18611868
new_params += name_as_bounds;
18621869
}
1863-
1870+
18641871
let Some(generics) = tcx.hir().get_generics(fn_def_id) else {
18651872
// This shouldn't happen, but don't ICE.
18661873
return None;
18671874
};
1868-
1875+
18691876
// Add generics or concatenate to the end of the list.
18701877
suggs.push(if let Some(params_span) = generics.span_for_param_suggestion() {
18711878
(params_span, format!(", {new_params}"))
@@ -1886,10 +1893,7 @@ pub fn impl_trait_overcapture_suggestion<'tcx>(
18861893
format!(" + use<{concatenated_bounds}>"),
18871894
));
18881895

1889-
Some(AddPreciseCapturingForOvercapture {
1890-
suggs,
1891-
apit_spans,
1892-
})
1896+
Some(AddPreciseCapturingForOvercapture { suggs, apit_spans })
18931897
}
18941898

18951899
pub struct AddPreciseCapturingForOvercapture {
@@ -1909,7 +1913,10 @@ impl Subdiagnostic for AddPreciseCapturingForOvercapture {
19091913
Applicability::MaybeIncorrect,
19101914
);
19111915
if !self.apit_spans.is_empty() {
1912-
diag.span_note(self.apit_spans, fluent::trait_selection_warn_removing_apit_params_for_overcapture);
1916+
diag.span_note(
1917+
self.apit_spans,
1918+
fluent::trait_selection_warn_removing_apit_params_for_overcapture,
1919+
);
19131920
}
19141921
}
1915-
}
1922+
}

tests/ui/impl-trait/precise-capturing/migration-note.rs

+15
Original file line numberDiff line numberDiff line change
@@ -187,4 +187,19 @@ fn returned() -> impl Sized {
187187
}
188188
//~^ NOTE `x` dropped here while still borrowed
189189

190+
fn capture_apit(x: &impl Sized) -> impl Sized {}
191+
//~^ NOTE you could use a `use<...>` bound to explicitly specify captures, but
192+
193+
fn test_apit() {
194+
let x = String::new();
195+
//~^ NOTE binding `x` declared here
196+
let y = capture_apit(&x);
197+
//~^ NOTE borrow of `x` occurs here
198+
//~| NOTE this call may capture more lifetimes than intended
199+
drop(x);
200+
//~^ ERROR cannot move out of `x` because it is borrowed
201+
//~| NOTE move out of `x` occurs here
202+
}
203+
//~^ NOTE borrow might be used here, when `y` is dropped
204+
190205
fn main() {}

0 commit comments

Comments
 (0)