1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::Diagnostic;
use rustc_middle::ty::RegionVid;
use smallvec::SmallVec;
use std::collections::BTreeMap;
use crate::MirBorrowckCtxt;
use super::{ErrorConstraintInfo, RegionName, RegionNameSource};
enum SuggestedConstraint {
Outlives(RegionName, SmallVec<[RegionName; 2]>),
Equal(RegionName, RegionName),
Static(RegionName),
}
#[derive(Default)]
pub struct OutlivesSuggestionBuilder {
constraints_to_add: BTreeMap<RegionVid, Vec<RegionVid>>,
}
impl OutlivesSuggestionBuilder {
fn region_name_is_suggestable(name: &RegionName) -> bool {
match name.source {
RegionNameSource::NamedEarlyBoundRegion(..)
| RegionNameSource::NamedFreeRegion(..)
| RegionNameSource::Static => true,
RegionNameSource::SynthesizedFreeEnvRegion(..)
| RegionNameSource::AnonRegionFromArgument(..)
| RegionNameSource::AnonRegionFromUpvar(..)
| RegionNameSource::AnonRegionFromOutput(..)
| RegionNameSource::AnonRegionFromYieldTy(..)
| RegionNameSource::AnonRegionFromAsyncFn(..)
| RegionNameSource::AnonRegionFromImplSignature(..) => {
debug!("Region {:?} is NOT suggestable", name);
false
}
}
}
fn region_vid_to_name(
&self,
mbcx: &MirBorrowckCtxt<'_, '_>,
region: RegionVid,
) -> Option<RegionName> {
mbcx.give_region_a_name(region).filter(Self::region_name_is_suggestable)
}
fn compile_all_suggestions(
&self,
mbcx: &MirBorrowckCtxt<'_, '_>,
) -> SmallVec<[SuggestedConstraint; 2]> {
let mut suggested = SmallVec::new();
let mut unified_already = FxHashSet::default();
for (fr, outlived) in &self.constraints_to_add {
let Some(fr_name) = self.region_vid_to_name(mbcx, *fr) else {
continue;
};
let outlived = outlived
.iter()
.filter_map(|fr| self.region_vid_to_name(mbcx, *fr).map(|rname| (fr, rname)))
.collect::<Vec<_>>();
if outlived.is_empty() {
continue;
}
if outlived
.iter()
.any(|(_, outlived_name)| matches!(outlived_name.source, RegionNameSource::Static))
{
suggested.push(SuggestedConstraint::Static(fr_name));
} else {
let (unified, other): (Vec<_>, Vec<_>) = outlived.into_iter().partition(
|(r, _)| {
self.constraints_to_add
.get(r)
.map(|r_outlived| r_outlived.as_slice().contains(fr))
.unwrap_or(false)
},
);
for (r, bound) in unified.into_iter() {
if !unified_already.contains(fr) {
suggested.push(SuggestedConstraint::Equal(fr_name.clone(), bound));
unified_already.insert(r);
}
}
if !other.is_empty() {
let other =
other.iter().map(|(_, rname)| rname.clone()).collect::<SmallVec<_>>();
suggested.push(SuggestedConstraint::Outlives(fr_name, other))
}
}
}
suggested
}
pub(crate) fn collect_constraint(&mut self, fr: RegionVid, outlived_fr: RegionVid) {
debug!("Collected {:?}: {:?}", fr, outlived_fr);
self.constraints_to_add.entry(fr).or_default().push(outlived_fr);
}
pub(crate) fn intermediate_suggestion(
&mut self,
mbcx: &MirBorrowckCtxt<'_, '_>,
errci: &ErrorConstraintInfo<'_>,
diag: &mut Diagnostic,
) {
let fr_name = self.region_vid_to_name(mbcx, errci.fr);
let outlived_fr_name = self.region_vid_to_name(mbcx, errci.outlived_fr);
if let (Some(fr_name), Some(outlived_fr_name)) = (fr_name, outlived_fr_name)
&& !matches!(outlived_fr_name.source, RegionNameSource::Static)
{
diag.help(&format!(
"consider adding the following bound: `{fr_name}: {outlived_fr_name}`",
));
}
}
pub(crate) fn add_suggestion(&self, mbcx: &mut MirBorrowckCtxt<'_, '_>) {
if self.constraints_to_add.is_empty() {
debug!("No constraints to suggest.");
return;
}
if self.constraints_to_add.len() == 1
&& self.constraints_to_add.values().next().unwrap().len() == 1
{
debug!("Only 1 suggestion. Skipping.");
return;
}
let suggested = self.compile_all_suggestions(mbcx);
if suggested.is_empty() {
debug!("Only 1 suggestable constraint. Skipping.");
return;
}
let mut diag = if suggested.len() == 1 {
mbcx.infcx.tcx.sess.diagnostic().struct_help(&match suggested.last().unwrap() {
SuggestedConstraint::Outlives(a, bs) => {
let bs: SmallVec<[String; 2]> = bs.iter().map(|r| format!("{}", r)).collect();
format!("add bound `{}: {}`", a, bs.join(" + "))
}
SuggestedConstraint::Equal(a, b) => {
format!("`{}` and `{}` must be the same: replace one with the other", a, b)
}
SuggestedConstraint::Static(a) => format!("replace `{}` with `'static`", a),
})
} else {
let mut diag = mbcx
.infcx
.tcx
.sess
.diagnostic()
.struct_help("the following changes may resolve your lifetime errors");
for constraint in suggested {
match constraint {
SuggestedConstraint::Outlives(a, bs) => {
let bs: SmallVec<[String; 2]> =
bs.iter().map(|r| format!("{}", r)).collect();
diag.help(&format!("add bound `{}: {}`", a, bs.join(" + ")));
}
SuggestedConstraint::Equal(a, b) => {
diag.help(&format!(
"`{}` and `{}` must be the same: replace one with the other",
a, b
));
}
SuggestedConstraint::Static(a) => {
diag.help(&format!("replace `{}` with `'static`", a));
}
}
}
diag
};
let mir_span = mbcx.body.span;
diag.sort_span = mir_span.shrink_to_hi();
mbcx.buffer_non_error_diag(diag);
}
}