Skip to content

Commit 4385065

Browse files
authored
Rollup merge of #163684 - Albab-Hasan:name-anon-lifetimes-in-use-bound, r=oli-obk
suggest named lifetimes instead of `'_` in `use<...>` for E0700 when a signature has more than one elided lifetime, the suggested `use<'_>` captures only the first in a case like `fn f(_a: &u8, b: &T) -> impl Sized` it stops resolving entirely and adds `error[E0106]` on top of the original error all at `MachineApplicable`. when the hidden type captures more than one anonymous lifetime the suggestion now names them in the signature and lists those names in the bound which is the desired output from the issue. a signature with a single elided lifetime keeps the shorter `use<'_>`. this reuses the three-part shape `AddPreciseCapturingAndParams` already emits for argument-position `impl Trait` in the same function. note. the argument-position `impl Trait` path in `AddPreciseCapturingAndParams` has the same defect when the signature also has elided reference lifetimes: `fn f(_a: impl Sized, x: &u8, y: &u8) -> impl Sized` still suggests `use<'_, T>` which produces `E0106` plus the original `E0700`. it is `MaybeIncorrect` so rustfix does not apply it but the suggestion misleads. ill follow up on that. the new test is `//@ run-rustfix` with a `.fixed` file that compiles which also let `tests/ui/lifetimes/issue-105227.rs` drop its `FIXME(precise_capturing): Add rustfix here after dealing w/ elided lifetimes`. fixes #132199 r? @oli-obk
2 parents dfea230 + 81b952e commit 4385065

8 files changed

Lines changed: 461 additions & 82 deletions

File tree

‎compiler/rustc_trait_selection/src/diagnostics.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1921,6 +1921,20 @@ impl Subdiagnostic for AddPreciseCapturingAndParams {
19211921
}
19221922
}
19231923

1924+
pub(crate) struct AddPreciseCapturingAndNameLifetimes {
1925+
pub suggs: Vec<(Span, String)>,
1926+
}
1927+
1928+
impl Subdiagnostic for AddPreciseCapturingAndNameLifetimes {
1929+
fn add_to_diag(self, diag: &mut Diag<'_>) {
1930+
diag.multipart_suggestion(
1931+
msg!("add `use<...>` bound and name the elided lifetimes to explicitly capture them"),
1932+
self.suggs,
1933+
Applicability::MachineApplicable,
1934+
);
1935+
}
1936+
}
1937+
19241938
/// Given a set of captured `DefId` for an RPIT (opaque_def_id) and a given
19251939
/// function (fn_def_id), try to suggest adding `+ use<...>` to capture just
19261940
/// the specified parameters. If one of those parameters is an APIT, then try

‎compiler/rustc_trait_selection/src/error_reporting/infer/region.rs‎

Lines changed: 233 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
use std::iter;
22

3-
use rustc_data_structures::fx::FxIndexSet;
3+
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
44
use rustc_errors::{
55
Applicability, Diag, E0309, E0310, E0311, E0803, Subdiagnostic, msg, struct_span_code_err,
66
};
77
use rustc_hir::def::{DefKind, Namespace};
88
use rustc_hir::def_id::{DefId, LocalDefId};
99
use rustc_hir::intravisit::Visitor;
1010
use rustc_hir::{self as hir, ParamName};
11+
use rustc_middle::hir::nested_filter;
12+
use rustc_middle::middle::resolve_bound_vars as rbv;
1113
use rustc_middle::traits::ObligationCauseCode;
1214
use rustc_middle::ty::error::TypeError;
1315
use rustc_middle::ty::print::RegionHighlightMode;
@@ -934,72 +936,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
934936
lifetime: Region<'tcx>,
935937
add_lt_suggs: &mut Vec<(Span, String)>,
936938
) -> Option<String> {
937-
struct LifetimeReplaceVisitor<'a> {
938-
needle: hir::LifetimeKind,
939-
new_lt: &'a str,
940-
add_lt_suggs: &'a mut Vec<(Span, String)>,
941-
}
942-
943-
impl<'hir> hir::intravisit::Visitor<'hir> for LifetimeReplaceVisitor<'_> {
944-
fn visit_lifetime(&mut self, lt: &'hir hir::Lifetime) {
945-
if lt.kind == self.needle {
946-
self.add_lt_suggs.push(lt.suggestion(self.new_lt));
947-
}
948-
}
949-
}
950-
951-
let (lifetime_def_id, lifetime_scope) =
952-
match self.tcx.is_suitable_region(generic_param_scope, lifetime) {
953-
Some(info) if !lifetime.is_named(self.tcx) => {
954-
(info.region_def_id.expect_local(), info.scope)
955-
}
956-
_ => return Some(lifetime.get_name(self.tcx)?.to_string()),
957-
};
958-
959-
let new_lt = {
960-
let generics = self.tcx.generics_of(lifetime_scope);
961-
let mut used_names =
962-
iter::successors(Some(generics), |g| g.parent.map(|p| self.tcx.generics_of(p)))
963-
.flat_map(|g| &g.own_params)
964-
.filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
965-
.map(|p| p.name)
966-
.collect::<Vec<_>>();
967-
let hir_id = self.tcx.local_def_id_to_hir_id(lifetime_scope);
968-
// consider late-bound lifetimes ...
969-
used_names.extend(self.tcx.late_bound_vars(hir_id).into_iter().filter_map(
970-
|p| match p {
971-
ty::BoundVariableKind::Region(lt) => lt.get_name(self.tcx),
972-
_ => None,
973-
},
974-
));
975-
(b'a'..=b'z')
976-
.map(|c| format!("'{}", c as char))
977-
.find(|candidate| !used_names.iter().any(|e| e.as_str() == candidate))
978-
.unwrap_or_else(|| "'lt".to_string())
979-
};
980-
981-
let mut visitor = LifetimeReplaceVisitor {
982-
needle: hir::LifetimeKind::Param(lifetime_def_id),
983-
add_lt_suggs,
984-
new_lt: &new_lt,
985-
};
986-
match self.tcx.expect_hir_owner_node(lifetime_scope) {
987-
hir::OwnerNode::Item(i) => visitor.visit_item(i),
988-
hir::OwnerNode::ForeignItem(i) => visitor.visit_foreign_item(i),
989-
hir::OwnerNode::ImplItem(i) => visitor.visit_impl_item(i),
990-
hir::OwnerNode::TraitItem(i) => visitor.visit_trait_item(i),
991-
hir::OwnerNode::Crate(_) => bug!("OwnerNode::Crate doesn't not have generics"),
992-
hir::OwnerNode::Synthetic => unreachable!(),
993-
}
994-
995-
let ast_generics = self.tcx.hir_get_generics(lifetime_scope).unwrap();
996-
let sugg = ast_generics
997-
.span_for_lifetime_suggestion()
998-
.map(|span| (span, format!("{new_lt}, ")))
999-
.unwrap_or_else(|| (ast_generics.span, format!("<{new_lt}>")));
1000-
add_lt_suggs.push(sugg);
1001-
1002-
Some(new_lt)
939+
let [name] =
940+
suggest_name_regions(self.tcx, generic_param_scope, &[lifetime], add_lt_suggs)?
941+
.try_into()
942+
.unwrap();
943+
Some(name)
1003944
}
1004945

1005946
fn report_sub_sup_conflict(
@@ -1169,6 +1110,101 @@ pub(super) fn note_and_explain_region<'tcx>(
11691110
emit_msg_span(err, prefix, description, span, suffix);
11701111
}
11711112

1113+
fn suggest_name_regions<'tcx>(
1114+
tcx: TyCtxt<'tcx>,
1115+
generic_param_scope: LocalDefId,
1116+
lifetimes: &[Region<'tcx>],
1117+
add_lt_suggs: &mut Vec<(Span, String)>,
1118+
) -> Option<Vec<String>> {
1119+
struct LifetimeReplaceVisitor<'a> {
1120+
new_lts: &'a [(LocalDefId, String)],
1121+
add_lt_suggs: &'a mut Vec<(Span, String)>,
1122+
}
1123+
1124+
impl<'hir> hir::intravisit::Visitor<'hir> for LifetimeReplaceVisitor<'_> {
1125+
fn visit_lifetime(&mut self, lt: &'hir hir::Lifetime) {
1126+
if let hir::LifetimeKind::Param(def_id) = lt.kind
1127+
&& let Some((_, new_lt)) = self.new_lts.iter().find(|(id, _)| *id == def_id)
1128+
{
1129+
self.add_lt_suggs.push(lt.suggestion(new_lt));
1130+
}
1131+
}
1132+
}
1133+
1134+
let mut lifetime_scope = None;
1135+
let mut used_names = vec![];
1136+
let mut new_lts: Vec<(LocalDefId, String)> = vec![];
1137+
let names: Vec<_> = lifetimes
1138+
.iter()
1139+
.map(|&lifetime| {
1140+
let (lifetime_def_id, scope) =
1141+
match tcx.is_suitable_region(generic_param_scope, lifetime) {
1142+
Some(info) if !lifetime.is_named(tcx) => {
1143+
(info.region_def_id.expect_local(), info.scope)
1144+
}
1145+
_ => return Some(lifetime.get_name(tcx)?.to_string()),
1146+
};
1147+
if *lifetime_scope.get_or_insert_with(|| {
1148+
used_names.extend(
1149+
iter::successors(Some(tcx.generics_of(scope)), |g| {
1150+
g.parent.map(|p| tcx.generics_of(p))
1151+
})
1152+
.flat_map(|g| &g.own_params)
1153+
.filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
1154+
.map(|p| p.name),
1155+
);
1156+
// consider late-bound lifetimes ...
1157+
used_names.extend(
1158+
tcx.late_bound_vars(tcx.local_def_id_to_hir_id(scope)).into_iter().filter_map(
1159+
|p| match p {
1160+
ty::BoundVariableKind::Region(lt) => lt.get_name(tcx),
1161+
_ => None,
1162+
},
1163+
),
1164+
);
1165+
scope
1166+
}) != scope
1167+
{
1168+
return Some(lifetime.get_name(tcx)?.to_string());
1169+
}
1170+
if let Some((_, name)) = new_lts.iter().find(|(id, _)| *id == lifetime_def_id) {
1171+
return Some(name.clone());
1172+
}
1173+
let new_lt = (b'a'..=b'z')
1174+
.map(|c| format!("'{}", c as char))
1175+
.find(|candidate| !used_names.iter().any(|e| e.as_str() == candidate))
1176+
.unwrap_or_else(|| "'lt".to_string());
1177+
used_names.push(Symbol::intern(&new_lt));
1178+
new_lts.push((lifetime_def_id, new_lt.clone()));
1179+
Some(new_lt)
1180+
})
1181+
.collect::<Option<_>>()?;
1182+
1183+
let Some(lifetime_scope) = lifetime_scope else {
1184+
return Some(names);
1185+
};
1186+
1187+
let mut visitor = LifetimeReplaceVisitor { new_lts: &new_lts, add_lt_suggs };
1188+
match tcx.expect_hir_owner_node(lifetime_scope) {
1189+
hir::OwnerNode::Item(i) => visitor.visit_item(i),
1190+
hir::OwnerNode::ForeignItem(i) => visitor.visit_foreign_item(i),
1191+
hir::OwnerNode::ImplItem(i) => visitor.visit_impl_item(i),
1192+
hir::OwnerNode::TraitItem(i) => visitor.visit_trait_item(i),
1193+
hir::OwnerNode::Crate(_) => bug!("OwnerNode::Crate doesn't not have generics"),
1194+
hir::OwnerNode::Synthetic => unreachable!(),
1195+
}
1196+
1197+
let new_lt = new_lts.into_iter().map(|(_, name)| name).collect::<Vec<_>>().join(", ");
1198+
let ast_generics = tcx.hir_get_generics(lifetime_scope).unwrap();
1199+
let sugg = ast_generics
1200+
.span_for_lifetime_suggestion()
1201+
.map(|span| (span, format!("{new_lt}, ")))
1202+
.unwrap_or_else(|| (ast_generics.span, format!("<{new_lt}>")));
1203+
add_lt_suggs.push(sugg);
1204+
1205+
Some(names)
1206+
}
1207+
11721208
fn explain_free_region<'tcx>(
11731209
tcx: TyCtxt<'tcx>,
11741210
err: &mut Diag<'_>,
@@ -1319,7 +1355,14 @@ pub fn unexpected_hidden_region_diagnostic<'a, 'tcx>(
13191355
"",
13201356
);
13211357
if let Some(_) = tcx.is_suitable_region(generic_param_scope, hidden_region) {
1322-
suggest_precise_capturing(tcx, opaque_ty_key.def_id, hidden_region, &mut err);
1358+
suggest_precise_capturing(
1359+
tcx,
1360+
generic_param_scope,
1361+
opaque_ty_key.def_id,
1362+
hidden_ty.value,
1363+
hidden_region,
1364+
&mut err,
1365+
);
13231366
}
13241367
}
13251368
ty::RePlaceholder(_) => {
@@ -1368,7 +1411,9 @@ pub fn unexpected_hidden_region_diagnostic<'a, 'tcx>(
13681411

13691412
fn suggest_precise_capturing<'tcx>(
13701413
tcx: TyCtxt<'tcx>,
1414+
generic_param_scope: LocalDefId,
13711415
opaque_def_id: LocalDefId,
1416+
hidden_ty: Ty<'tcx>,
13721417
captured_lifetime: ty::Region<'tcx>,
13731418
diag: &mut Diag<'_>,
13741419
) {
@@ -1455,11 +1500,30 @@ fn suggest_precise_capturing<'tcx>(
14551500
}
14561501
}
14571502

1458-
if !captured_lifetimes.insert(new_lifetime) {
1503+
if captured_lifetimes.contains(&new_lifetime) {
14591504
// Uh, strange. This lifetime appears to already be captured...
14601505
return;
14611506
}
14621507

1508+
// `'_` in a capture list only resolves when the signature has a single anonymous
1509+
// lifetime, so when there are several the suggestion has to name them first.
1510+
if synthetics.is_empty()
1511+
&& let Some(suggs) = name_anon_lifetimes_suggestion(
1512+
tcx,
1513+
generic_param_scope,
1514+
opaque_def_id,
1515+
fn_def_id,
1516+
hidden_ty,
1517+
&captured_lifetimes,
1518+
&captured_non_lifetimes,
1519+
)
1520+
{
1521+
diag.subdiagnostic(diagnostics::AddPreciseCapturingAndNameLifetimes { suggs });
1522+
return;
1523+
}
1524+
1525+
captured_lifetimes.insert(new_lifetime);
1526+
14631527
if synthetics.is_empty() {
14641528
let concatenated_bounds = captured_lifetimes
14651529
.into_iter()
@@ -1543,3 +1607,103 @@ fn suggest_precise_capturing<'tcx>(
15431607
}
15441608
}
15451609
}
1610+
1611+
/// Build a suggestion that names every anonymous lifetime the hidden type captures and then
1612+
/// lists them in a `use<..>` bound.
1613+
///
1614+
/// This exists because a `use<..>` list cannot refer to more than one anonymous lifetime: `'_`
1615+
/// resolves like any other elided lifetime, so with several in the signature it either picks the
1616+
/// wrong one or fails to resolve at all. Naming them is the only way to write the bound the hidden
1617+
/// type actually needs.
1618+
///
1619+
/// Returns `None` whenever the plain `'_` suggestion is still correct, so that the common
1620+
/// single-lifetime case keeps its shorter form.
1621+
fn name_anon_lifetimes_suggestion<'tcx>(
1622+
tcx: TyCtxt<'tcx>,
1623+
generic_param_scope: LocalDefId,
1624+
opaque_def_id: LocalDefId,
1625+
fn_def_id: LocalDefId,
1626+
hidden_ty: Ty<'tcx>,
1627+
captured_lifetimes: &FxIndexSet<Symbol>,
1628+
captured_non_lifetimes: &FxIndexSet<Symbol>,
1629+
) -> Option<Vec<(Span, String)>> {
1630+
let fn_sig = tcx.hir_node_by_def_id(fn_def_id).fn_sig()?;
1631+
1632+
let mut collector = AnonLifetimeCollector { tcx, anon_lifetimes: Default::default() };
1633+
for input in fn_sig.decl.inputs {
1634+
collector.visit_ty_unambig(input);
1635+
}
1636+
// With a single anonymous lifetime in the signature `'_` resolves to it, so leave that case
1637+
// to the caller.
1638+
if collector.anon_lifetimes.len() < 2 {
1639+
return None;
1640+
}
1641+
1642+
let mut hidden_regions = FxIndexMap::default();
1643+
tcx.for_each_free_region(&hidden_ty, |region| {
1644+
if let Some(info) = tcx.is_suitable_region(generic_param_scope, region) {
1645+
hidden_regions.entry(info.region_def_id).or_insert(region);
1646+
}
1647+
});
1648+
1649+
// A lifetime the user already named stays as it is; only the anonymous ones need inventing
1650+
// a name, and they are named in the order they appear in the signature.
1651+
let named = hidden_regions
1652+
.iter()
1653+
.filter(|(def_id, _)| !collector.anon_lifetimes.contains(*def_id))
1654+
.map(|(_, &region)| region);
1655+
let anon: Vec<_> = collector
1656+
.anon_lifetimes
1657+
.iter()
1658+
.filter_map(|def_id| hidden_regions.get(def_id).copied())
1659+
.collect();
1660+
if anon.is_empty() {
1661+
return None;
1662+
}
1663+
let regions: Vec<_> = named.chain(anon).collect();
1664+
1665+
let mut suggs = vec![];
1666+
let mut bounds = captured_lifetimes.clone();
1667+
bounds.extend(
1668+
suggest_name_regions(tcx, generic_param_scope, &regions, &mut suggs)?
1669+
.iter()
1670+
.map(|name| Symbol::intern(name)),
1671+
);
1672+
1673+
let concatenated_bounds = bounds
1674+
.into_iter()
1675+
.chain(captured_non_lifetimes.iter().copied())
1676+
.map(|sym| sym.to_string())
1677+
.collect::<Vec<_>>()
1678+
.join(", ");
1679+
suggs.push((
1680+
tcx.def_span(opaque_def_id).shrink_to_hi(),
1681+
format!(" + use<{concatenated_bounds}>"),
1682+
));
1683+
1684+
Some(suggs)
1685+
}
1686+
1687+
/// Collects every anonymous lifetime written in a function signature.
1688+
struct AnonLifetimeCollector<'tcx> {
1689+
tcx: TyCtxt<'tcx>,
1690+
anon_lifetimes: FxIndexSet<DefId>,
1691+
}
1692+
1693+
impl<'tcx> Visitor<'tcx> for AnonLifetimeCollector<'tcx> {
1694+
type NestedFilter = nested_filter::OnlyBodies;
1695+
1696+
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1697+
self.tcx
1698+
}
1699+
1700+
fn visit_lifetime(&mut self, lifetime: &'tcx hir::Lifetime) {
1701+
if lifetime.is_anonymous()
1702+
&& let Some(
1703+
rbv::ResolvedArg::EarlyBound(def_id) | rbv::ResolvedArg::LateBound(_, _, def_id),
1704+
) = self.tcx.named_bound_var(lifetime.hir_id)
1705+
{
1706+
self.anon_lifetimes.insert(def_id.to_def_id());
1707+
}
1708+
}
1709+
}

0 commit comments

Comments
 (0)