|
1 | 1 | use std::iter; |
2 | 2 |
|
3 | | -use rustc_data_structures::fx::FxIndexSet; |
| 3 | +use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; |
4 | 4 | use rustc_errors::{ |
5 | 5 | Applicability, Diag, E0309, E0310, E0311, E0803, Subdiagnostic, msg, struct_span_code_err, |
6 | 6 | }; |
7 | 7 | use rustc_hir::def::{DefKind, Namespace}; |
8 | 8 | use rustc_hir::def_id::{DefId, LocalDefId}; |
9 | 9 | use rustc_hir::intravisit::Visitor; |
10 | 10 | use rustc_hir::{self as hir, ParamName}; |
| 11 | +use rustc_middle::hir::nested_filter; |
| 12 | +use rustc_middle::middle::resolve_bound_vars as rbv; |
11 | 13 | use rustc_middle::traits::ObligationCauseCode; |
12 | 14 | use rustc_middle::ty::error::TypeError; |
13 | 15 | use rustc_middle::ty::print::RegionHighlightMode; |
@@ -934,72 +936,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { |
934 | 936 | lifetime: Region<'tcx>, |
935 | 937 | add_lt_suggs: &mut Vec<(Span, String)>, |
936 | 938 | ) -> 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) |
1003 | 944 | } |
1004 | 945 |
|
1005 | 946 | fn report_sub_sup_conflict( |
@@ -1169,6 +1110,101 @@ pub(super) fn note_and_explain_region<'tcx>( |
1169 | 1110 | emit_msg_span(err, prefix, description, span, suffix); |
1170 | 1111 | } |
1171 | 1112 |
|
| 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 | + |
1172 | 1208 | fn explain_free_region<'tcx>( |
1173 | 1209 | tcx: TyCtxt<'tcx>, |
1174 | 1210 | err: &mut Diag<'_>, |
@@ -1319,7 +1355,14 @@ pub fn unexpected_hidden_region_diagnostic<'a, 'tcx>( |
1319 | 1355 | "", |
1320 | 1356 | ); |
1321 | 1357 | 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 | + ); |
1323 | 1366 | } |
1324 | 1367 | } |
1325 | 1368 | ty::RePlaceholder(_) => { |
@@ -1368,7 +1411,9 @@ pub fn unexpected_hidden_region_diagnostic<'a, 'tcx>( |
1368 | 1411 |
|
1369 | 1412 | fn suggest_precise_capturing<'tcx>( |
1370 | 1413 | tcx: TyCtxt<'tcx>, |
| 1414 | + generic_param_scope: LocalDefId, |
1371 | 1415 | opaque_def_id: LocalDefId, |
| 1416 | + hidden_ty: Ty<'tcx>, |
1372 | 1417 | captured_lifetime: ty::Region<'tcx>, |
1373 | 1418 | diag: &mut Diag<'_>, |
1374 | 1419 | ) { |
@@ -1455,11 +1500,30 @@ fn suggest_precise_capturing<'tcx>( |
1455 | 1500 | } |
1456 | 1501 | } |
1457 | 1502 |
|
1458 | | - if !captured_lifetimes.insert(new_lifetime) { |
| 1503 | + if captured_lifetimes.contains(&new_lifetime) { |
1459 | 1504 | // Uh, strange. This lifetime appears to already be captured... |
1460 | 1505 | return; |
1461 | 1506 | } |
1462 | 1507 |
|
| 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 | + |
1463 | 1527 | if synthetics.is_empty() { |
1464 | 1528 | let concatenated_bounds = captured_lifetimes |
1465 | 1529 | .into_iter() |
@@ -1543,3 +1607,103 @@ fn suggest_precise_capturing<'tcx>( |
1543 | 1607 | } |
1544 | 1608 | } |
1545 | 1609 | } |
| 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(|(_, ®ion)| 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, ®ions, &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