]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_borrowck/src/region_infer/mod.rs
Better errors for implied static bound
[rust.git] / compiler / rustc_borrowck / src / region_infer / mod.rs
1 use std::collections::VecDeque;
2 use std::rc::Rc;
3
4 use rustc_data_structures::binary_search_util;
5 use rustc_data_structures::frozen::Frozen;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_data_structures::graph::scc::Sccs;
8 use rustc_errors::Diagnostic;
9 use rustc_hir::def_id::{DefId, CRATE_DEF_ID};
10 use rustc_hir::CRATE_HIR_ID;
11 use rustc_index::vec::IndexVec;
12 use rustc_infer::infer::canonical::QueryOutlivesConstraint;
13 use rustc_infer::infer::outlives::test_type_match;
14 use rustc_infer::infer::region_constraints::{GenericKind, VarInfos, VerifyBound, VerifyIfEq};
15 use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin};
16 use rustc_middle::mir::{
17     Body, ClosureOutlivesRequirement, ClosureOutlivesSubject, ClosureRegionRequirements,
18     ConstraintCategory, Local, Location, ReturnConstraint,
19 };
20 use rustc_middle::traits::ObligationCause;
21 use rustc_middle::traits::ObligationCauseCode;
22 use rustc_middle::ty::{
23     self, subst::SubstsRef, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitable,
24 };
25 use rustc_span::Span;
26
27 use crate::{
28     constraints::{
29         graph::NormalConstraintGraph, ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet,
30     },
31     diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo},
32     member_constraints::{MemberConstraintSet, NllMemberConstraintIndex},
33     nll::{PoloniusOutput, ToRegionVid},
34     region_infer::reverse_sccs::ReverseSccGraph,
35     region_infer::values::{
36         LivenessValues, PlaceholderIndices, RegionElement, RegionValueElements, RegionValues,
37         ToElementIndex,
38     },
39     type_check::{free_region_relations::UniversalRegionRelations, Locations},
40     universal_regions::UniversalRegions,
41 };
42
43 mod dump_mir;
44 mod graphviz;
45 mod opaque_types;
46 mod reverse_sccs;
47
48 pub mod values;
49
50 pub struct RegionInferenceContext<'tcx> {
51     pub var_infos: VarInfos,
52
53     /// Contains the definition for every region variable. Region
54     /// variables are identified by their index (`RegionVid`). The
55     /// definition contains information about where the region came
56     /// from as well as its final inferred value.
57     definitions: IndexVec<RegionVid, RegionDefinition<'tcx>>,
58
59     /// The liveness constraints added to each region. For most
60     /// regions, these start out empty and steadily grow, though for
61     /// each universally quantified region R they start out containing
62     /// the entire CFG and `end(R)`.
63     liveness_constraints: LivenessValues<RegionVid>,
64
65     /// The outlives constraints computed by the type-check.
66     constraints: Frozen<OutlivesConstraintSet<'tcx>>,
67
68     /// The constraint-set, but in graph form, making it easy to traverse
69     /// the constraints adjacent to a particular region. Used to construct
70     /// the SCC (see `constraint_sccs`) and for error reporting.
71     constraint_graph: Frozen<NormalConstraintGraph>,
72
73     /// The SCC computed from `constraints` and the constraint
74     /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to
75     /// compute the values of each region.
76     constraint_sccs: Rc<Sccs<RegionVid, ConstraintSccIndex>>,
77
78     /// Reverse of the SCC constraint graph --  i.e., an edge `A -> B` exists if
79     /// `B: A`. This is used to compute the universal regions that are required
80     /// to outlive a given SCC. Computed lazily.
81     rev_scc_graph: Option<Rc<ReverseSccGraph>>,
82
83     /// The "R0 member of [R1..Rn]" constraints, indexed by SCC.
84     member_constraints: Rc<MemberConstraintSet<'tcx, ConstraintSccIndex>>,
85
86     /// Records the member constraints that we applied to each scc.
87     /// This is useful for error reporting. Once constraint
88     /// propagation is done, this vector is sorted according to
89     /// `member_region_scc`.
90     member_constraints_applied: Vec<AppliedMemberConstraint>,
91
92     /// Map closure bounds to a `Span` that should be used for error reporting.
93     closure_bounds_mapping:
94         FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory<'tcx>, Span)>>,
95
96     /// Map universe indexes to information on why we created it.
97     universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
98
99     /// Contains the minimum universe of any variable within the same
100     /// SCC. We will ensure that no SCC contains values that are not
101     /// visible from this index.
102     scc_universes: IndexVec<ConstraintSccIndex, ty::UniverseIndex>,
103
104     /// Contains a "representative" from each SCC. This will be the
105     /// minimal RegionVid belonging to that universe. It is used as a
106     /// kind of hacky way to manage checking outlives relationships,
107     /// since we can 'canonicalize' each region to the representative
108     /// of its SCC and be sure that -- if they have the same repr --
109     /// they *must* be equal (though not having the same repr does not
110     /// mean they are unequal).
111     scc_representatives: IndexVec<ConstraintSccIndex, ty::RegionVid>,
112
113     /// The final inferred values of the region variables; we compute
114     /// one value per SCC. To get the value for any given *region*,
115     /// you first find which scc it is a part of.
116     scc_values: RegionValues<ConstraintSccIndex>,
117
118     /// Type constraints that we check after solving.
119     type_tests: Vec<TypeTest<'tcx>>,
120
121     /// Information about the universally quantified regions in scope
122     /// on this function.
123     universal_regions: Rc<UniversalRegions<'tcx>>,
124
125     /// Information about how the universally quantified regions in
126     /// scope on this function relate to one another.
127     universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
128 }
129
130 /// Each time that `apply_member_constraint` is successful, it appends
131 /// one of these structs to the `member_constraints_applied` field.
132 /// This is used in error reporting to trace out what happened.
133 ///
134 /// The way that `apply_member_constraint` works is that it effectively
135 /// adds a new lower bound to the SCC it is analyzing: so you wind up
136 /// with `'R: 'O` where `'R` is the pick-region and `'O` is the
137 /// minimal viable option.
138 pub(crate) struct AppliedMemberConstraint {
139     /// The SCC that was affected. (The "member region".)
140     ///
141     /// The vector if `AppliedMemberConstraint` elements is kept sorted
142     /// by this field.
143     pub(crate) member_region_scc: ConstraintSccIndex,
144
145     /// The "best option" that `apply_member_constraint` found -- this was
146     /// added as an "ad-hoc" lower-bound to `member_region_scc`.
147     pub(crate) min_choice: ty::RegionVid,
148
149     /// The "member constraint index" -- we can find out details about
150     /// the constraint from
151     /// `set.member_constraints[member_constraint_index]`.
152     pub(crate) member_constraint_index: NllMemberConstraintIndex,
153 }
154
155 pub(crate) struct RegionDefinition<'tcx> {
156     /// What kind of variable is this -- a free region? existential
157     /// variable? etc. (See the `NllRegionVariableOrigin` for more
158     /// info.)
159     pub(crate) origin: NllRegionVariableOrigin,
160
161     /// Which universe is this region variable defined in? This is
162     /// most often `ty::UniverseIndex::ROOT`, but when we encounter
163     /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create
164     /// the variable for `'a` in a fresh universe that extends ROOT.
165     pub(crate) universe: ty::UniverseIndex,
166
167     /// If this is 'static or an early-bound region, then this is
168     /// `Some(X)` where `X` is the name of the region.
169     pub(crate) external_name: Option<ty::Region<'tcx>>,
170 }
171
172 /// N.B., the variants in `Cause` are intentionally ordered. Lower
173 /// values are preferred when it comes to error messages. Do not
174 /// reorder willy nilly.
175 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
176 pub(crate) enum Cause {
177     /// point inserted because Local was live at the given Location
178     LiveVar(Local, Location),
179
180     /// point inserted because Local was dropped at the given Location
181     DropVar(Local, Location),
182 }
183
184 /// A "type test" corresponds to an outlives constraint between a type
185 /// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are
186 /// translated from the `Verify` region constraints in the ordinary
187 /// inference context.
188 ///
189 /// These sorts of constraints are handled differently than ordinary
190 /// constraints, at least at present. During type checking, the
191 /// `InferCtxt::process_registered_region_obligations` method will
192 /// attempt to convert a type test like `T: 'x` into an ordinary
193 /// outlives constraint when possible (for example, `&'a T: 'b` will
194 /// be converted into `'a: 'b` and registered as a `Constraint`).
195 ///
196 /// In some cases, however, there are outlives relationships that are
197 /// not converted into a region constraint, but rather into one of
198 /// these "type tests". The distinction is that a type test does not
199 /// influence the inference result, but instead just examines the
200 /// values that we ultimately inferred for each region variable and
201 /// checks that they meet certain extra criteria. If not, an error
202 /// can be issued.
203 ///
204 /// One reason for this is that these type tests typically boil down
205 /// to a check like `'a: 'x` where `'a` is a universally quantified
206 /// region -- and therefore not one whose value is really meant to be
207 /// *inferred*, precisely (this is not always the case: one can have a
208 /// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an
209 /// inference variable). Another reason is that these type tests can
210 /// involve *disjunction* -- that is, they can be satisfied in more
211 /// than one way.
212 ///
213 /// For more information about this translation, see
214 /// `InferCtxt::process_registered_region_obligations` and
215 /// `InferCtxt::type_must_outlive` in `rustc_infer::infer::InferCtxt`.
216 #[derive(Clone, Debug)]
217 pub struct TypeTest<'tcx> {
218     /// The type `T` that must outlive the region.
219     pub generic_kind: GenericKind<'tcx>,
220
221     /// The region `'x` that the type must outlive.
222     pub lower_bound: RegionVid,
223
224     /// Where did this constraint arise and why?
225     pub locations: Locations,
226
227     /// A test which, if met by the region `'x`, proves that this type
228     /// constraint is satisfied.
229     pub verify_bound: VerifyBound<'tcx>,
230 }
231
232 /// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure
233 /// environment). If we can't, it is an error.
234 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
235 enum RegionRelationCheckResult {
236     Ok,
237     Propagated,
238     Error,
239 }
240
241 #[derive(Clone, PartialEq, Eq, Debug)]
242 enum Trace<'tcx> {
243     StartRegion,
244     FromOutlivesConstraint(OutlivesConstraint<'tcx>),
245     NotVisited,
246 }
247
248 #[derive(Clone, PartialEq, Eq, Debug)]
249 pub enum ExtraConstraintInfo {
250     PlaceholderFromPredicate(Span),
251 }
252
253 impl<'tcx> RegionInferenceContext<'tcx> {
254     /// Creates a new region inference context with a total of
255     /// `num_region_variables` valid inference variables; the first N
256     /// of those will be constant regions representing the free
257     /// regions defined in `universal_regions`.
258     ///
259     /// The `outlives_constraints` and `type_tests` are an initial set
260     /// of constraints produced by the MIR type check.
261     pub(crate) fn new(
262         var_infos: VarInfos,
263         universal_regions: Rc<UniversalRegions<'tcx>>,
264         placeholder_indices: Rc<PlaceholderIndices>,
265         universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
266         outlives_constraints: OutlivesConstraintSet<'tcx>,
267         member_constraints_in: MemberConstraintSet<'tcx, RegionVid>,
268         closure_bounds_mapping: FxHashMap<
269             Location,
270             FxHashMap<(RegionVid, RegionVid), (ConstraintCategory<'tcx>, Span)>,
271         >,
272         universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
273         type_tests: Vec<TypeTest<'tcx>>,
274         liveness_constraints: LivenessValues<RegionVid>,
275         elements: &Rc<RegionValueElements>,
276     ) -> Self {
277         // Create a RegionDefinition for each inference variable.
278         let definitions: IndexVec<_, _> = var_infos
279             .iter()
280             .map(|info| RegionDefinition::new(info.universe, info.origin))
281             .collect();
282
283         let constraints = Frozen::freeze(outlives_constraints);
284         let constraint_graph = Frozen::freeze(constraints.graph(definitions.len()));
285         let fr_static = universal_regions.fr_static;
286         let constraint_sccs = Rc::new(constraints.compute_sccs(&constraint_graph, fr_static));
287
288         let mut scc_values =
289             RegionValues::new(elements, universal_regions.len(), &placeholder_indices);
290
291         for region in liveness_constraints.rows() {
292             let scc = constraint_sccs.scc(region);
293             scc_values.merge_liveness(scc, region, &liveness_constraints);
294         }
295
296         let scc_universes = Self::compute_scc_universes(&constraint_sccs, &definitions);
297
298         let scc_representatives = Self::compute_scc_representatives(&constraint_sccs, &definitions);
299
300         let member_constraints =
301             Rc::new(member_constraints_in.into_mapped(|r| constraint_sccs.scc(r)));
302
303         let mut result = Self {
304             var_infos,
305             definitions,
306             liveness_constraints,
307             constraints,
308             constraint_graph,
309             constraint_sccs,
310             rev_scc_graph: None,
311             member_constraints,
312             member_constraints_applied: Vec::new(),
313             closure_bounds_mapping,
314             universe_causes,
315             scc_universes,
316             scc_representatives,
317             scc_values,
318             type_tests,
319             universal_regions,
320             universal_region_relations,
321         };
322
323         result.init_free_and_bound_regions();
324
325         result
326     }
327
328     /// Each SCC is the combination of many region variables which
329     /// have been equated. Therefore, we can associate a universe with
330     /// each SCC which is minimum of all the universes of its
331     /// constituent regions -- this is because whatever value the SCC
332     /// takes on must be a value that each of the regions within the
333     /// SCC could have as well. This implies that the SCC must have
334     /// the minimum, or narrowest, universe.
335     fn compute_scc_universes(
336         constraint_sccs: &Sccs<RegionVid, ConstraintSccIndex>,
337         definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
338     ) -> IndexVec<ConstraintSccIndex, ty::UniverseIndex> {
339         let num_sccs = constraint_sccs.num_sccs();
340         let mut scc_universes = IndexVec::from_elem_n(ty::UniverseIndex::MAX, num_sccs);
341
342         debug!("compute_scc_universes()");
343
344         // For each region R in universe U, ensure that the universe for the SCC
345         // that contains R is "no bigger" than U. This effectively sets the universe
346         // for each SCC to be the minimum of the regions within.
347         for (region_vid, region_definition) in definitions.iter_enumerated() {
348             let scc = constraint_sccs.scc(region_vid);
349             let scc_universe = &mut scc_universes[scc];
350             let scc_min = std::cmp::min(region_definition.universe, *scc_universe);
351             if scc_min != *scc_universe {
352                 *scc_universe = scc_min;
353                 debug!(
354                     "compute_scc_universes: lowered universe of {scc:?} to {scc_min:?} \
355                     because it contains {region_vid:?} in {region_universe:?}",
356                     scc = scc,
357                     scc_min = scc_min,
358                     region_vid = region_vid,
359                     region_universe = region_definition.universe,
360                 );
361             }
362         }
363
364         // Walk each SCC `A` and `B` such that `A: B`
365         // and ensure that universe(A) can see universe(B).
366         //
367         // This serves to enforce the 'empty/placeholder' hierarchy
368         // (described in more detail on `RegionKind`):
369         //
370         // ```
371         // static -----+
372         //   |         |
373         // empty(U0) placeholder(U1)
374         //   |      /
375         // empty(U1)
376         // ```
377         //
378         // In particular, imagine we have variables R0 in U0 and R1
379         // created in U1, and constraints like this;
380         //
381         // ```
382         // R1: !1 // R1 outlives the placeholder in U1
383         // R1: R0 // R1 outlives R0
384         // ```
385         //
386         // Here, we wish for R1 to be `'static`, because it
387         // cannot outlive `placeholder(U1)` and `empty(U0)` any other way.
388         //
389         // Thanks to this loop, what happens is that the `R1: R0`
390         // constraint lowers the universe of `R1` to `U0`, which in turn
391         // means that the `R1: !1` constraint will (later) cause
392         // `R1` to become `'static`.
393         for scc_a in constraint_sccs.all_sccs() {
394             for &scc_b in constraint_sccs.successors(scc_a) {
395                 let scc_universe_a = scc_universes[scc_a];
396                 let scc_universe_b = scc_universes[scc_b];
397                 let scc_universe_min = std::cmp::min(scc_universe_a, scc_universe_b);
398                 if scc_universe_a != scc_universe_min {
399                     scc_universes[scc_a] = scc_universe_min;
400
401                     debug!(
402                         "compute_scc_universes: lowered universe of {scc_a:?} to {scc_universe_min:?} \
403                         because {scc_a:?}: {scc_b:?} and {scc_b:?} is in universe {scc_universe_b:?}",
404                         scc_a = scc_a,
405                         scc_b = scc_b,
406                         scc_universe_min = scc_universe_min,
407                         scc_universe_b = scc_universe_b
408                     );
409                 }
410             }
411         }
412
413         debug!("compute_scc_universes: scc_universe = {:#?}", scc_universes);
414
415         scc_universes
416     }
417
418     /// For each SCC, we compute a unique `RegionVid` (in fact, the
419     /// minimal one that belongs to the SCC). See
420     /// `scc_representatives` field of `RegionInferenceContext` for
421     /// more details.
422     fn compute_scc_representatives(
423         constraints_scc: &Sccs<RegionVid, ConstraintSccIndex>,
424         definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
425     ) -> IndexVec<ConstraintSccIndex, ty::RegionVid> {
426         let num_sccs = constraints_scc.num_sccs();
427         let next_region_vid = definitions.next_index();
428         let mut scc_representatives = IndexVec::from_elem_n(next_region_vid, num_sccs);
429
430         for region_vid in definitions.indices() {
431             let scc = constraints_scc.scc(region_vid);
432             let prev_min = scc_representatives[scc];
433             scc_representatives[scc] = region_vid.min(prev_min);
434         }
435
436         scc_representatives
437     }
438
439     /// Initializes the region variables for each universally
440     /// quantified region (lifetime parameter). The first N variables
441     /// always correspond to the regions appearing in the function
442     /// signature (both named and anonymous) and where-clauses. This
443     /// function iterates over those regions and initializes them with
444     /// minimum values.
445     ///
446     /// For example:
447     /// ```
448     /// fn foo<'a, 'b>( /* ... */ ) where 'a: 'b { /* ... */ }
449     /// ```
450     /// would initialize two variables like so:
451     /// ```ignore (illustrative)
452     /// R0 = { CFG, R0 } // 'a
453     /// R1 = { CFG, R0, R1 } // 'b
454     /// ```
455     /// Here, R0 represents `'a`, and it contains (a) the entire CFG
456     /// and (b) any universally quantified regions that it outlives,
457     /// which in this case is just itself. R1 (`'b`) in contrast also
458     /// outlives `'a` and hence contains R0 and R1.
459     fn init_free_and_bound_regions(&mut self) {
460         // Update the names (if any)
461         for (external_name, variable) in self.universal_regions.named_universal_regions() {
462             debug!(
463                 "init_universal_regions: region {:?} has external name {:?}",
464                 variable, external_name
465             );
466             self.definitions[variable].external_name = Some(external_name);
467         }
468
469         for variable in self.definitions.indices() {
470             let scc = self.constraint_sccs.scc(variable);
471
472             match self.definitions[variable].origin {
473                 NllRegionVariableOrigin::FreeRegion => {
474                     // For each free, universally quantified region X:
475
476                     // Add all nodes in the CFG to liveness constraints
477                     self.liveness_constraints.add_all_points(variable);
478                     self.scc_values.add_all_points(scc);
479
480                     // Add `end(X)` into the set for X.
481                     self.scc_values.add_element(scc, variable);
482                 }
483
484                 NllRegionVariableOrigin::Placeholder(placeholder) => {
485                     // Each placeholder region is only visible from
486                     // its universe `ui` and its extensions. So we
487                     // can't just add it into `scc` unless the
488                     // universe of the scc can name this region.
489                     let scc_universe = self.scc_universes[scc];
490                     if scc_universe.can_name(placeholder.universe) {
491                         self.scc_values.add_element(scc, placeholder);
492                     } else {
493                         debug!(
494                             "init_free_and_bound_regions: placeholder {:?} is \
495                              not compatible with universe {:?} of its SCC {:?}",
496                             placeholder, scc_universe, scc,
497                         );
498                         self.add_incompatible_universe(scc);
499                     }
500                 }
501
502                 NllRegionVariableOrigin::Existential { .. } => {
503                     // For existential, regions, nothing to do.
504                 }
505             }
506         }
507     }
508
509     /// Returns an iterator over all the region indices.
510     pub fn regions(&self) -> impl Iterator<Item = RegionVid> + 'tcx {
511         self.definitions.indices()
512     }
513
514     /// Given a universal region in scope on the MIR, returns the
515     /// corresponding index.
516     ///
517     /// (Panics if `r` is not a registered universal region.)
518     pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
519         self.universal_regions.to_region_vid(r)
520     }
521
522     /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
523     pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
524         self.universal_regions.annotate(tcx, err)
525     }
526
527     /// Returns `true` if the region `r` contains the point `p`.
528     ///
529     /// Panics if called before `solve()` executes,
530     pub(crate) fn region_contains(&self, r: impl ToRegionVid, p: impl ToElementIndex) -> bool {
531         let scc = self.constraint_sccs.scc(r.to_region_vid());
532         self.scc_values.contains(scc, p)
533     }
534
535     /// Returns access to the value of `r` for debugging purposes.
536     pub(crate) fn region_value_str(&self, r: RegionVid) -> String {
537         let scc = self.constraint_sccs.scc(r.to_region_vid());
538         self.scc_values.region_value_str(scc)
539     }
540
541     /// Returns access to the value of `r` for debugging purposes.
542     pub(crate) fn region_universe(&self, r: RegionVid) -> ty::UniverseIndex {
543         let scc = self.constraint_sccs.scc(r.to_region_vid());
544         self.scc_universes[scc]
545     }
546
547     /// Once region solving has completed, this function will return
548     /// the member constraints that were applied to the value of a given
549     /// region `r`. See `AppliedMemberConstraint`.
550     pub(crate) fn applied_member_constraints(
551         &self,
552         r: impl ToRegionVid,
553     ) -> &[AppliedMemberConstraint] {
554         let scc = self.constraint_sccs.scc(r.to_region_vid());
555         binary_search_util::binary_search_slice(
556             &self.member_constraints_applied,
557             |applied| applied.member_region_scc,
558             &scc,
559         )
560     }
561
562     /// Performs region inference and report errors if we see any
563     /// unsatisfiable constraints. If this is a closure, returns the
564     /// region requirements to propagate to our creator, if any.
565     #[instrument(skip(self, infcx, body, polonius_output), level = "debug")]
566     pub(super) fn solve(
567         &mut self,
568         infcx: &InferCtxt<'_, 'tcx>,
569         param_env: ty::ParamEnv<'tcx>,
570         body: &Body<'tcx>,
571         polonius_output: Option<Rc<PoloniusOutput>>,
572     ) -> (Option<ClosureRegionRequirements<'tcx>>, RegionErrors<'tcx>) {
573         let mir_def_id = body.source.def_id();
574         self.propagate_constraints(body);
575
576         let mut errors_buffer = RegionErrors::new();
577
578         // If this is a closure, we can propagate unsatisfied
579         // `outlives_requirements` to our creator, so create a vector
580         // to store those. Otherwise, we'll pass in `None` to the
581         // functions below, which will trigger them to report errors
582         // eagerly.
583         let mut outlives_requirements = infcx.tcx.is_typeck_child(mir_def_id).then(Vec::new);
584
585         self.check_type_tests(
586             infcx,
587             param_env,
588             body,
589             outlives_requirements.as_mut(),
590             &mut errors_buffer,
591         );
592
593         // In Polonius mode, the errors about missing universal region relations are in the output
594         // and need to be emitted or propagated. Otherwise, we need to check whether the
595         // constraints were too strong, and if so, emit or propagate those errors.
596         if infcx.tcx.sess.opts.unstable_opts.polonius {
597             self.check_polonius_subset_errors(
598                 outlives_requirements.as_mut(),
599                 &mut errors_buffer,
600                 polonius_output.expect("Polonius output is unavailable despite `-Z polonius`"),
601             );
602         } else {
603             self.check_universal_regions(outlives_requirements.as_mut(), &mut errors_buffer);
604         }
605
606         if errors_buffer.is_empty() {
607             self.check_member_constraints(infcx, &mut errors_buffer);
608         }
609
610         let outlives_requirements = outlives_requirements.unwrap_or_default();
611
612         if outlives_requirements.is_empty() {
613             (None, errors_buffer)
614         } else {
615             let num_external_vids = self.universal_regions.num_global_and_external_regions();
616             (
617                 Some(ClosureRegionRequirements { num_external_vids, outlives_requirements }),
618                 errors_buffer,
619             )
620         }
621     }
622
623     /// Propagate the region constraints: this will grow the values
624     /// for each region variable until all the constraints are
625     /// satisfied. Note that some values may grow **too** large to be
626     /// feasible, but we check this later.
627     #[instrument(skip(self, _body), level = "debug")]
628     fn propagate_constraints(&mut self, _body: &Body<'tcx>) {
629         debug!("constraints={:#?}", {
630             let mut constraints: Vec<_> = self.constraints.outlives().iter().collect();
631             constraints.sort_by_key(|c| (c.sup, c.sub));
632             constraints
633                 .into_iter()
634                 .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub)))
635                 .collect::<Vec<_>>()
636         });
637
638         // To propagate constraints, we walk the DAG induced by the
639         // SCC. For each SCC, we visit its successors and compute
640         // their values, then we union all those values to get our
641         // own.
642         let constraint_sccs = self.constraint_sccs.clone();
643         for scc in constraint_sccs.all_sccs() {
644             self.compute_value_for_scc(scc);
645         }
646
647         // Sort the applied member constraints so we can binary search
648         // through them later.
649         self.member_constraints_applied.sort_by_key(|applied| applied.member_region_scc);
650     }
651
652     /// Computes the value of the SCC `scc_a`, which has not yet been
653     /// computed, by unioning the values of its successors.
654     /// Assumes that all successors have been computed already
655     /// (which is assured by iterating over SCCs in dependency order).
656     #[instrument(skip(self), level = "debug")]
657     fn compute_value_for_scc(&mut self, scc_a: ConstraintSccIndex) {
658         let constraint_sccs = self.constraint_sccs.clone();
659
660         // Walk each SCC `B` such that `A: B`...
661         for &scc_b in constraint_sccs.successors(scc_a) {
662             debug!(?scc_b);
663
664             // ...and add elements from `B` into `A`. One complication
665             // arises because of universes: If `B` contains something
666             // that `A` cannot name, then `A` can only contain `B` if
667             // it outlives static.
668             if self.universe_compatible(scc_b, scc_a) {
669                 // `A` can name everything that is in `B`, so just
670                 // merge the bits.
671                 self.scc_values.add_region(scc_a, scc_b);
672             } else {
673                 self.add_incompatible_universe(scc_a);
674             }
675         }
676
677         // Now take member constraints into account.
678         let member_constraints = self.member_constraints.clone();
679         for m_c_i in member_constraints.indices(scc_a) {
680             self.apply_member_constraint(scc_a, m_c_i, member_constraints.choice_regions(m_c_i));
681         }
682
683         debug!(value = ?self.scc_values.region_value_str(scc_a));
684     }
685
686     /// Invoked for each `R0 member of [R1..Rn]` constraint.
687     ///
688     /// `scc` is the SCC containing R0, and `choice_regions` are the
689     /// `R1..Rn` regions -- they are always known to be universal
690     /// regions (and if that's not true, we just don't attempt to
691     /// enforce the constraint).
692     ///
693     /// The current value of `scc` at the time the method is invoked
694     /// is considered a *lower bound*.  If possible, we will modify
695     /// the constraint to set it equal to one of the option regions.
696     /// If we make any changes, returns true, else false.
697     #[instrument(skip(self, member_constraint_index), level = "debug")]
698     fn apply_member_constraint(
699         &mut self,
700         scc: ConstraintSccIndex,
701         member_constraint_index: NllMemberConstraintIndex,
702         choice_regions: &[ty::RegionVid],
703     ) -> bool {
704         // Create a mutable vector of the options. We'll try to winnow
705         // them down.
706         let mut choice_regions: Vec<ty::RegionVid> = choice_regions.to_vec();
707
708         // Convert to the SCC representative: sometimes we have inference
709         // variables in the member constraint that wind up equated with
710         // universal regions. The scc representative is the minimal numbered
711         // one from the corresponding scc so it will be the universal region
712         // if one exists.
713         for c_r in &mut choice_regions {
714             let scc = self.constraint_sccs.scc(*c_r);
715             *c_r = self.scc_representatives[scc];
716         }
717
718         // The 'member region' in a member constraint is part of the
719         // hidden type, which must be in the root universe. Therefore,
720         // it cannot have any placeholders in its value.
721         assert!(self.scc_universes[scc] == ty::UniverseIndex::ROOT);
722         debug_assert!(
723             self.scc_values.placeholders_contained_in(scc).next().is_none(),
724             "scc {:?} in a member constraint has placeholder value: {:?}",
725             scc,
726             self.scc_values.region_value_str(scc),
727         );
728
729         // The existing value for `scc` is a lower-bound. This will
730         // consist of some set `{P} + {LB}` of points `{P}` and
731         // lower-bound free regions `{LB}`. As each choice region `O`
732         // is a free region, it will outlive the points. But we can
733         // only consider the option `O` if `O: LB`.
734         choice_regions.retain(|&o_r| {
735             self.scc_values
736                 .universal_regions_outlived_by(scc)
737                 .all(|lb| self.universal_region_relations.outlives(o_r, lb))
738         });
739         debug!(?choice_regions, "after lb");
740
741         // Now find all the *upper bounds* -- that is, each UB is a
742         // free region that must outlive the member region `R0` (`UB:
743         // R0`). Therefore, we need only keep an option `O` if `UB: O`
744         // for all UB.
745         let rev_scc_graph = self.reverse_scc_graph();
746         let universal_region_relations = &self.universal_region_relations;
747         for ub in rev_scc_graph.upper_bounds(scc) {
748             debug!(?ub);
749             choice_regions.retain(|&o_r| universal_region_relations.outlives(ub, o_r));
750         }
751         debug!(?choice_regions, "after ub");
752
753         // If we ruled everything out, we're done.
754         if choice_regions.is_empty() {
755             return false;
756         }
757
758         // Otherwise, we need to find the minimum remaining choice, if
759         // any, and take that.
760         debug!("choice_regions remaining are {:#?}", choice_regions);
761         let min = |r1: ty::RegionVid, r2: ty::RegionVid| -> Option<ty::RegionVid> {
762             let r1_outlives_r2 = self.universal_region_relations.outlives(r1, r2);
763             let r2_outlives_r1 = self.universal_region_relations.outlives(r2, r1);
764             match (r1_outlives_r2, r2_outlives_r1) {
765                 (true, true) => Some(r1.min(r2)),
766                 (true, false) => Some(r2),
767                 (false, true) => Some(r1),
768                 (false, false) => None,
769             }
770         };
771         let mut min_choice = choice_regions[0];
772         for &other_option in &choice_regions[1..] {
773             debug!(?min_choice, ?other_option,);
774             match min(min_choice, other_option) {
775                 Some(m) => min_choice = m,
776                 None => {
777                     debug!(?min_choice, ?other_option, "incomparable; no min choice",);
778                     return false;
779                 }
780             }
781         }
782
783         let min_choice_scc = self.constraint_sccs.scc(min_choice);
784         debug!(?min_choice, ?min_choice_scc);
785         if self.scc_values.add_region(scc, min_choice_scc) {
786             self.member_constraints_applied.push(AppliedMemberConstraint {
787                 member_region_scc: scc,
788                 min_choice,
789                 member_constraint_index,
790             });
791
792             true
793         } else {
794             false
795         }
796     }
797
798     /// Returns `true` if all the elements in the value of `scc_b` are nameable
799     /// in `scc_a`. Used during constraint propagation, and only once
800     /// the value of `scc_b` has been computed.
801     fn universe_compatible(&self, scc_b: ConstraintSccIndex, scc_a: ConstraintSccIndex) -> bool {
802         let universe_a = self.scc_universes[scc_a];
803
804         // Quick check: if scc_b's declared universe is a subset of
805         // scc_a's declared universe (typically, both are ROOT), then
806         // it cannot contain any problematic universe elements.
807         if universe_a.can_name(self.scc_universes[scc_b]) {
808             return true;
809         }
810
811         // Otherwise, we have to iterate over the universe elements in
812         // B's value, and check whether all of them are nameable
813         // from universe_a
814         self.scc_values.placeholders_contained_in(scc_b).all(|p| universe_a.can_name(p.universe))
815     }
816
817     /// Extend `scc` so that it can outlive some placeholder region
818     /// from a universe it can't name; at present, the only way for
819     /// this to be true is if `scc` outlives `'static`. This is
820     /// actually stricter than necessary: ideally, we'd support bounds
821     /// like `for<'a: 'b`>` that might then allow us to approximate
822     /// `'a` with `'b` and not `'static`. But it will have to do for
823     /// now.
824     fn add_incompatible_universe(&mut self, scc: ConstraintSccIndex) {
825         debug!("add_incompatible_universe(scc={:?})", scc);
826
827         let fr_static = self.universal_regions.fr_static;
828         self.scc_values.add_all_points(scc);
829         self.scc_values.add_element(scc, fr_static);
830     }
831
832     /// Once regions have been propagated, this method is used to see
833     /// whether the "type tests" produced by typeck were satisfied;
834     /// type tests encode type-outlives relationships like `T:
835     /// 'a`. See `TypeTest` for more details.
836     fn check_type_tests(
837         &self,
838         infcx: &InferCtxt<'_, 'tcx>,
839         param_env: ty::ParamEnv<'tcx>,
840         body: &Body<'tcx>,
841         mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
842         errors_buffer: &mut RegionErrors<'tcx>,
843     ) {
844         let tcx = infcx.tcx;
845
846         // Sometimes we register equivalent type-tests that would
847         // result in basically the exact same error being reported to
848         // the user. Avoid that.
849         let mut deduplicate_errors = FxHashSet::default();
850
851         for type_test in &self.type_tests {
852             debug!("check_type_test: {:?}", type_test);
853
854             let generic_ty = type_test.generic_kind.to_ty(tcx);
855             if self.eval_verify_bound(
856                 infcx,
857                 param_env,
858                 body,
859                 generic_ty,
860                 type_test.lower_bound,
861                 &type_test.verify_bound,
862             ) {
863                 continue;
864             }
865
866             if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements {
867                 if self.try_promote_type_test(
868                     infcx,
869                     param_env,
870                     body,
871                     type_test,
872                     propagated_outlives_requirements,
873                 ) {
874                     continue;
875                 }
876             }
877
878             // Type-test failed. Report the error.
879             let erased_generic_kind = infcx.tcx.erase_regions(type_test.generic_kind);
880
881             // Skip duplicate-ish errors.
882             if deduplicate_errors.insert((
883                 erased_generic_kind,
884                 type_test.lower_bound,
885                 type_test.locations,
886             )) {
887                 debug!(
888                     "check_type_test: reporting error for erased_generic_kind={:?}, \
889                      lower_bound_region={:?}, \
890                      type_test.locations={:?}",
891                     erased_generic_kind, type_test.lower_bound, type_test.locations,
892                 );
893
894                 errors_buffer.push(RegionErrorKind::TypeTestError { type_test: type_test.clone() });
895             }
896         }
897     }
898
899     /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot
900     /// prove to be satisfied. If this is a closure, we will attempt to
901     /// "promote" this type-test into our `ClosureRegionRequirements` and
902     /// hence pass it up the creator. To do this, we have to phrase the
903     /// type-test in terms of external free regions, as local free
904     /// regions are not nameable by the closure's creator.
905     ///
906     /// Promotion works as follows: we first check that the type `T`
907     /// contains only regions that the creator knows about. If this is
908     /// true, then -- as a consequence -- we know that all regions in
909     /// the type `T` are free regions that outlive the closure body. If
910     /// false, then promotion fails.
911     ///
912     /// Once we've promoted T, we have to "promote" `'X` to some region
913     /// that is "external" to the closure. Generally speaking, a region
914     /// may be the union of some points in the closure body as well as
915     /// various free lifetimes. We can ignore the points in the closure
916     /// body: if the type T can be expressed in terms of external regions,
917     /// we know it outlives the points in the closure body. That
918     /// just leaves the free regions.
919     ///
920     /// The idea then is to lower the `T: 'X` constraint into multiple
921     /// bounds -- e.g., if `'X` is the union of two free lifetimes,
922     /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.
923     #[instrument(level = "debug", skip(self, infcx, propagated_outlives_requirements))]
924     fn try_promote_type_test(
925         &self,
926         infcx: &InferCtxt<'_, 'tcx>,
927         param_env: ty::ParamEnv<'tcx>,
928         body: &Body<'tcx>,
929         type_test: &TypeTest<'tcx>,
930         propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>,
931     ) -> bool {
932         let tcx = infcx.tcx;
933
934         let TypeTest { generic_kind, lower_bound, locations, verify_bound: _ } = type_test;
935
936         let generic_ty = generic_kind.to_ty(tcx);
937         let Some(subject) = self.try_promote_type_test_subject(infcx, generic_ty) else {
938             return false;
939         };
940
941         debug!("subject = {:?}", subject);
942
943         let r_scc = self.constraint_sccs.scc(*lower_bound);
944
945         debug!(
946             "lower_bound = {:?} r_scc={:?} universe={:?}",
947             lower_bound, r_scc, self.scc_universes[r_scc]
948         );
949
950         // If the type test requires that `T: 'a` where `'a` is a
951         // placeholder from another universe, that effectively requires
952         // `T: 'static`, so we have to propagate that requirement.
953         //
954         // It doesn't matter *what* universe because the promoted `T` will
955         // always be in the root universe.
956         if let Some(p) = self.scc_values.placeholders_contained_in(r_scc).next() {
957             debug!("encountered placeholder in higher universe: {:?}, requiring 'static", p);
958             let static_r = self.universal_regions.fr_static;
959             propagated_outlives_requirements.push(ClosureOutlivesRequirement {
960                 subject,
961                 outlived_free_region: static_r,
962                 blame_span: locations.span(body),
963                 category: ConstraintCategory::Boring,
964             });
965
966             // we can return here -- the code below might push add'l constraints
967             // but they would all be weaker than this one.
968             return true;
969         }
970
971         // For each region outlived by lower_bound find a non-local,
972         // universal region (it may be the same region) and add it to
973         // `ClosureOutlivesRequirement`.
974         for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
975             debug!("universal_region_outlived_by ur={:?}", ur);
976             // Check whether we can already prove that the "subject" outlives `ur`.
977             // If so, we don't have to propagate this requirement to our caller.
978             //
979             // To continue the example from the function, if we are trying to promote
980             // a requirement that `T: 'X`, and we know that `'X = '1 + '2` (i.e., the union
981             // `'1` and `'2`), then in this loop `ur` will be `'1` (and `'2`). So here
982             // we check whether `T: '1` is something we *can* prove. If so, no need
983             // to propagate that requirement.
984             //
985             // This is needed because -- particularly in the case
986             // where `ur` is a local bound -- we are sometimes in a
987             // position to prove things that our caller cannot.  See
988             // #53570 for an example.
989             if self.eval_verify_bound(
990                 infcx,
991                 param_env,
992                 body,
993                 generic_ty,
994                 ur,
995                 &type_test.verify_bound,
996             ) {
997                 continue;
998             }
999
1000             let non_local_ub = self.universal_region_relations.non_local_upper_bounds(ur);
1001             debug!("try_promote_type_test: non_local_ub={:?}", non_local_ub);
1002
1003             // This is slightly too conservative. To show T: '1, given `'2: '1`
1004             // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to
1005             // avoid potential non-determinism we approximate this by requiring
1006             // T: '1 and T: '2.
1007             for upper_bound in non_local_ub {
1008                 debug_assert!(self.universal_regions.is_universal_region(upper_bound));
1009                 debug_assert!(!self.universal_regions.is_local_free_region(upper_bound));
1010
1011                 let requirement = ClosureOutlivesRequirement {
1012                     subject,
1013                     outlived_free_region: upper_bound,
1014                     blame_span: locations.span(body),
1015                     category: ConstraintCategory::Boring,
1016                 };
1017                 debug!("try_promote_type_test: pushing {:#?}", requirement);
1018                 propagated_outlives_requirements.push(requirement);
1019             }
1020         }
1021         true
1022     }
1023
1024     /// When we promote a type test `T: 'r`, we have to convert the
1025     /// type `T` into something we can store in a query result (so
1026     /// something allocated for `'tcx`). This is problematic if `ty`
1027     /// contains regions. During the course of NLL region checking, we
1028     /// will have replaced all of those regions with fresh inference
1029     /// variables. To create a test subject, we want to replace those
1030     /// inference variables with some region from the closure
1031     /// signature -- this is not always possible, so this is a
1032     /// fallible process. Presuming we do find a suitable region, we
1033     /// will use it's *external name*, which will be a `RegionKind`
1034     /// variant that can be used in query responses such as
1035     /// `ReEarlyBound`.
1036     #[instrument(level = "debug", skip(self, infcx))]
1037     fn try_promote_type_test_subject(
1038         &self,
1039         infcx: &InferCtxt<'_, 'tcx>,
1040         ty: Ty<'tcx>,
1041     ) -> Option<ClosureOutlivesSubject<'tcx>> {
1042         let tcx = infcx.tcx;
1043
1044         let ty = tcx.fold_regions(ty, |r, _depth| {
1045             let region_vid = self.to_region_vid(r);
1046
1047             // The challenge if this. We have some region variable `r`
1048             // whose value is a set of CFG points and universal
1049             // regions. We want to find if that set is *equivalent* to
1050             // any of the named regions found in the closure.
1051             //
1052             // To do so, we compute the
1053             // `non_local_universal_upper_bound`. This will be a
1054             // non-local, universal region that is greater than `r`.
1055             // However, it might not be *contained* within `r`, so
1056             // then we further check whether this bound is contained
1057             // in `r`. If so, we can say that `r` is equivalent to the
1058             // bound.
1059             //
1060             // Let's work through a few examples. For these, imagine
1061             // that we have 3 non-local regions (I'll denote them as
1062             // `'static`, `'a`, and `'b`, though of course in the code
1063             // they would be represented with indices) where:
1064             //
1065             // - `'static: 'a`
1066             // - `'static: 'b`
1067             //
1068             // First, let's assume that `r` is some existential
1069             // variable with an inferred value `{'a, 'static}` (plus
1070             // some CFG nodes). In this case, the non-local upper
1071             // bound is `'static`, since that outlives `'a`. `'static`
1072             // is also a member of `r` and hence we consider `r`
1073             // equivalent to `'static` (and replace it with
1074             // `'static`).
1075             //
1076             // Now let's consider the inferred value `{'a, 'b}`. This
1077             // means `r` is effectively `'a | 'b`. I'm not sure if
1078             // this can come about, actually, but assuming it did, we
1079             // would get a non-local upper bound of `'static`. Since
1080             // `'static` is not contained in `r`, we would fail to
1081             // find an equivalent.
1082             let upper_bound = self.non_local_universal_upper_bound(region_vid);
1083             if self.region_contains(region_vid, upper_bound) {
1084                 self.definitions[upper_bound].external_name.unwrap_or(r)
1085             } else {
1086                 // In the case of a failure, use a `ReVar` result. This will
1087                 // cause the `needs_infer` later on to return `None`.
1088                 r
1089             }
1090         });
1091
1092         debug!("try_promote_type_test_subject: folded ty = {:?}", ty);
1093
1094         // `needs_infer` will only be true if we failed to promote some region.
1095         if ty.needs_infer() {
1096             return None;
1097         }
1098
1099         Some(ClosureOutlivesSubject::Ty(ty))
1100     }
1101
1102     /// Given some universal or existential region `r`, finds a
1103     /// non-local, universal region `r+` that outlives `r` at entry to (and
1104     /// exit from) the closure. In the worst case, this will be
1105     /// `'static`.
1106     ///
1107     /// This is used for two purposes. First, if we are propagated
1108     /// some requirement `T: r`, we can use this method to enlarge `r`
1109     /// to something we can encode for our creator (which only knows
1110     /// about non-local, universal regions). It is also used when
1111     /// encoding `T` as part of `try_promote_type_test_subject` (see
1112     /// that fn for details).
1113     ///
1114     /// This is based on the result `'y` of `universal_upper_bound`,
1115     /// except that it converts further takes the non-local upper
1116     /// bound of `'y`, so that the final result is non-local.
1117     fn non_local_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1118         debug!("non_local_universal_upper_bound(r={:?}={})", r, self.region_value_str(r));
1119
1120         let lub = self.universal_upper_bound(r);
1121
1122         // Grow further to get smallest universal region known to
1123         // creator.
1124         let non_local_lub = self.universal_region_relations.non_local_upper_bound(lub);
1125
1126         debug!("non_local_universal_upper_bound: non_local_lub={:?}", non_local_lub);
1127
1128         non_local_lub
1129     }
1130
1131     /// Returns a universally quantified region that outlives the
1132     /// value of `r` (`r` may be existentially or universally
1133     /// quantified).
1134     ///
1135     /// Since `r` is (potentially) an existential region, it has some
1136     /// value which may include (a) any number of points in the CFG
1137     /// and (b) any number of `end('x)` elements of universally
1138     /// quantified regions. To convert this into a single universal
1139     /// region we do as follows:
1140     ///
1141     /// - Ignore the CFG points in `'r`. All universally quantified regions
1142     ///   include the CFG anyhow.
1143     /// - For each `end('x)` element in `'r`, compute the mutual LUB, yielding
1144     ///   a result `'y`.
1145     #[instrument(skip(self), level = "debug", ret)]
1146     pub(crate) fn universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1147         debug!(r = %self.region_value_str(r));
1148
1149         // Find the smallest universal region that contains all other
1150         // universal regions within `region`.
1151         let mut lub = self.universal_regions.fr_fn_body;
1152         let r_scc = self.constraint_sccs.scc(r);
1153         for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1154             lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1155         }
1156
1157         lub
1158     }
1159
1160     /// Like `universal_upper_bound`, but returns an approximation more suitable
1161     /// for diagnostics. If `r` contains multiple disjoint universal regions
1162     /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region.
1163     /// This corresponds to picking named regions over unnamed regions
1164     /// (e.g. picking early-bound regions over a closure late-bound region).
1165     ///
1166     /// This means that the returned value may not be a true upper bound, since
1167     /// only 'static is known to outlive disjoint universal regions.
1168     /// Therefore, this method should only be used in diagnostic code,
1169     /// where displaying *some* named universal region is better than
1170     /// falling back to 'static.
1171     #[instrument(level = "debug", skip(self))]
1172     pub(crate) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1173         debug!("{}", self.region_value_str(r));
1174
1175         // Find the smallest universal region that contains all other
1176         // universal regions within `region`.
1177         let mut lub = self.universal_regions.fr_fn_body;
1178         let r_scc = self.constraint_sccs.scc(r);
1179         let static_r = self.universal_regions.fr_static;
1180         for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1181             let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1182             debug!(?ur, ?lub, ?new_lub);
1183             // The upper bound of two non-static regions is static: this
1184             // means we know nothing about the relationship between these
1185             // two regions. Pick a 'better' one to use when constructing
1186             // a diagnostic
1187             if ur != static_r && lub != static_r && new_lub == static_r {
1188                 // Prefer the region with an `external_name` - this
1189                 // indicates that the region is early-bound, so working with
1190                 // it can produce a nicer error.
1191                 if self.region_definition(ur).external_name.is_some() {
1192                     lub = ur;
1193                 } else if self.region_definition(lub).external_name.is_some() {
1194                     // Leave lub unchanged
1195                 } else {
1196                     // If we get here, we don't have any reason to prefer
1197                     // one region over the other. Just pick the
1198                     // one with the lower index for now.
1199                     lub = std::cmp::min(ur, lub);
1200                 }
1201             } else {
1202                 lub = new_lub;
1203             }
1204         }
1205
1206         debug!(?r, ?lub);
1207
1208         lub
1209     }
1210
1211     /// Tests if `test` is true when applied to `lower_bound` at
1212     /// `point`.
1213     fn eval_verify_bound(
1214         &self,
1215         infcx: &InferCtxt<'_, 'tcx>,
1216         param_env: ty::ParamEnv<'tcx>,
1217         body: &Body<'tcx>,
1218         generic_ty: Ty<'tcx>,
1219         lower_bound: RegionVid,
1220         verify_bound: &VerifyBound<'tcx>,
1221     ) -> bool {
1222         debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound);
1223
1224         match verify_bound {
1225             VerifyBound::IfEq(verify_if_eq_b) => {
1226                 self.eval_if_eq(infcx, param_env, generic_ty, lower_bound, *verify_if_eq_b)
1227             }
1228
1229             VerifyBound::IsEmpty => {
1230                 let lower_bound_scc = self.constraint_sccs.scc(lower_bound);
1231                 self.scc_values.elements_contained_in(lower_bound_scc).next().is_none()
1232             }
1233
1234             VerifyBound::OutlivedBy(r) => {
1235                 let r_vid = self.to_region_vid(*r);
1236                 self.eval_outlives(r_vid, lower_bound)
1237             }
1238
1239             VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {
1240                 self.eval_verify_bound(
1241                     infcx,
1242                     param_env,
1243                     body,
1244                     generic_ty,
1245                     lower_bound,
1246                     verify_bound,
1247                 )
1248             }),
1249
1250             VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {
1251                 self.eval_verify_bound(
1252                     infcx,
1253                     param_env,
1254                     body,
1255                     generic_ty,
1256                     lower_bound,
1257                     verify_bound,
1258                 )
1259             }),
1260         }
1261     }
1262
1263     fn eval_if_eq(
1264         &self,
1265         infcx: &InferCtxt<'_, 'tcx>,
1266         param_env: ty::ParamEnv<'tcx>,
1267         generic_ty: Ty<'tcx>,
1268         lower_bound: RegionVid,
1269         verify_if_eq_b: ty::Binder<'tcx, VerifyIfEq<'tcx>>,
1270     ) -> bool {
1271         let generic_ty = self.normalize_to_scc_representatives(infcx.tcx, generic_ty);
1272         let verify_if_eq_b = self.normalize_to_scc_representatives(infcx.tcx, verify_if_eq_b);
1273         match test_type_match::extract_verify_if_eq(
1274             infcx.tcx,
1275             param_env,
1276             &verify_if_eq_b,
1277             generic_ty,
1278         ) {
1279             Some(r) => {
1280                 let r_vid = self.to_region_vid(r);
1281                 self.eval_outlives(r_vid, lower_bound)
1282             }
1283             None => false,
1284         }
1285     }
1286
1287     /// This is a conservative normalization procedure. It takes every
1288     /// free region in `value` and replaces it with the
1289     /// "representative" of its SCC (see `scc_representatives` field).
1290     /// We are guaranteed that if two values normalize to the same
1291     /// thing, then they are equal; this is a conservative check in
1292     /// that they could still be equal even if they normalize to
1293     /// different results. (For example, there might be two regions
1294     /// with the same value that are not in the same SCC).
1295     ///
1296     /// N.B., this is not an ideal approach and I would like to revisit
1297     /// it. However, it works pretty well in practice. In particular,
1298     /// this is needed to deal with projection outlives bounds like
1299     ///
1300     /// ```text
1301     /// <T as Foo<'0>>::Item: '1
1302     /// ```
1303     ///
1304     /// In particular, this routine winds up being important when
1305     /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the
1306     /// environment. In this case, if we can show that `'0 == 'a`,
1307     /// and that `'b: '1`, then we know that the clause is
1308     /// satisfied. In such cases, particularly due to limitations of
1309     /// the trait solver =), we usually wind up with a where-clause like
1310     /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as
1311     /// a constraint, and thus ensures that they are in the same SCC.
1312     ///
1313     /// So why can't we do a more correct routine? Well, we could
1314     /// *almost* use the `relate_tys` code, but the way it is
1315     /// currently setup it creates inference variables to deal with
1316     /// higher-ranked things and so forth, and right now the inference
1317     /// context is not permitted to make more inference variables. So
1318     /// we use this kind of hacky solution.
1319     fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
1320     where
1321         T: TypeFoldable<'tcx>,
1322     {
1323         tcx.fold_regions(value, |r, _db| {
1324             let vid = self.to_region_vid(r);
1325             let scc = self.constraint_sccs.scc(vid);
1326             let repr = self.scc_representatives[scc];
1327             tcx.mk_region(ty::ReVar(repr))
1328         })
1329     }
1330
1331     // Evaluate whether `sup_region == sub_region`.
1332     fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool {
1333         self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1)
1334     }
1335
1336     // Evaluate whether `sup_region: sub_region`.
1337     #[instrument(skip(self), level = "debug", ret)]
1338     fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool {
1339         debug!(
1340             "sup_region's value = {:?} universal={:?}",
1341             self.region_value_str(sup_region),
1342             self.universal_regions.is_universal_region(sup_region),
1343         );
1344         debug!(
1345             "sub_region's value = {:?} universal={:?}",
1346             self.region_value_str(sub_region),
1347             self.universal_regions.is_universal_region(sub_region),
1348         );
1349
1350         let sub_region_scc = self.constraint_sccs.scc(sub_region);
1351         let sup_region_scc = self.constraint_sccs.scc(sup_region);
1352
1353         // If we are checking that `'sup: 'sub`, and `'sub` contains
1354         // some placeholder that `'sup` cannot name, then this is only
1355         // true if `'sup` outlives static.
1356         if !self.universe_compatible(sub_region_scc, sup_region_scc) {
1357             debug!(
1358                 "sub universe `{sub_region_scc:?}` is not nameable \
1359                 by super `{sup_region_scc:?}`, promoting to static",
1360             );
1361
1362             return self.eval_outlives(sup_region, self.universal_regions.fr_static);
1363         }
1364
1365         // Both the `sub_region` and `sup_region` consist of the union
1366         // of some number of universal regions (along with the union
1367         // of various points in the CFG; ignore those points for
1368         // now). Therefore, the sup-region outlives the sub-region if,
1369         // for each universal region R1 in the sub-region, there
1370         // exists some region R2 in the sup-region that outlives R1.
1371         let universal_outlives =
1372             self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| {
1373                 self.scc_values
1374                     .universal_regions_outlived_by(sup_region_scc)
1375                     .any(|r2| self.universal_region_relations.outlives(r2, r1))
1376             });
1377
1378         if !universal_outlives {
1379             debug!("sub region contains a universal region not present in super");
1380             return false;
1381         }
1382
1383         // Now we have to compare all the points in the sub region and make
1384         // sure they exist in the sup region.
1385
1386         if self.universal_regions.is_universal_region(sup_region) {
1387             // Micro-opt: universal regions contain all points.
1388             debug!("super is universal and hence contains all points");
1389             return true;
1390         }
1391
1392         debug!("comparison between points in sup/sub");
1393
1394         self.scc_values.contains_points(sup_region_scc, sub_region_scc)
1395     }
1396
1397     /// Once regions have been propagated, this method is used to see
1398     /// whether any of the constraints were too strong. In particular,
1399     /// we want to check for a case where a universally quantified
1400     /// region exceeded its bounds. Consider:
1401     /// ```compile_fail,E0312
1402     /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1403     /// ```
1404     /// In this case, returning `x` requires `&'a u32 <: &'b u32`
1405     /// and hence we establish (transitively) a constraint that
1406     /// `'a: 'b`. The `propagate_constraints` code above will
1407     /// therefore add `end('a)` into the region for `'b` -- but we
1408     /// have no evidence that `'b` outlives `'a`, so we want to report
1409     /// an error.
1410     ///
1411     /// If `propagated_outlives_requirements` is `Some`, then we will
1412     /// push unsatisfied obligations into there. Otherwise, we'll
1413     /// report them as errors.
1414     fn check_universal_regions(
1415         &self,
1416         mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1417         errors_buffer: &mut RegionErrors<'tcx>,
1418     ) {
1419         for (fr, fr_definition) in self.definitions.iter_enumerated() {
1420             match fr_definition.origin {
1421                 NllRegionVariableOrigin::FreeRegion => {
1422                     // Go through each of the universal regions `fr` and check that
1423                     // they did not grow too large, accumulating any requirements
1424                     // for our caller into the `outlives_requirements` vector.
1425                     self.check_universal_region(
1426                         fr,
1427                         &mut propagated_outlives_requirements,
1428                         errors_buffer,
1429                     );
1430                 }
1431
1432                 NllRegionVariableOrigin::Placeholder(placeholder) => {
1433                     self.check_bound_universal_region(fr, placeholder, errors_buffer);
1434                 }
1435
1436                 NllRegionVariableOrigin::Existential { .. } => {
1437                     // nothing to check here
1438                 }
1439             }
1440         }
1441     }
1442
1443     /// Checks if Polonius has found any unexpected free region relations.
1444     ///
1445     /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent
1446     /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a`
1447     /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL
1448     /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`.
1449     ///
1450     /// More details can be found in this blog post by Niko:
1451     /// <https://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/>
1452     ///
1453     /// In the canonical example
1454     /// ```compile_fail,E0312
1455     /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1456     /// ```
1457     /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a
1458     /// constraint that `'a: 'b`. It is an error that we have no evidence that this
1459     /// constraint holds.
1460     ///
1461     /// If `propagated_outlives_requirements` is `Some`, then we will
1462     /// push unsatisfied obligations into there. Otherwise, we'll
1463     /// report them as errors.
1464     fn check_polonius_subset_errors(
1465         &self,
1466         mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1467         errors_buffer: &mut RegionErrors<'tcx>,
1468         polonius_output: Rc<PoloniusOutput>,
1469     ) {
1470         debug!(
1471             "check_polonius_subset_errors: {} subset_errors",
1472             polonius_output.subset_errors.len()
1473         );
1474
1475         // Similarly to `check_universal_regions`: a free region relation, which was not explicitly
1476         // declared ("known") was found by Polonius, so emit an error, or propagate the
1477         // requirements for our caller into the `propagated_outlives_requirements` vector.
1478         //
1479         // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the
1480         // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with
1481         // the rest of the NLL infrastructure. The "subset origin" is the "longer free region",
1482         // and the "superset origin" is the outlived "shorter free region".
1483         //
1484         // Note: Polonius will produce a subset error at every point where the unexpected
1485         // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful
1486         // for diagnostics in the future, e.g. to point more precisely at the key locations
1487         // requiring this constraint to hold. However, the error and diagnostics code downstream
1488         // expects that these errors are not duplicated (and that they are in a certain order).
1489         // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or
1490         // anonymous lifetimes for example, could give these names differently, while others like
1491         // the outlives suggestions or the debug output from `#[rustc_regions]` would be
1492         // duplicated. The polonius subset errors are deduplicated here, while keeping the
1493         // CFG-location ordering.
1494         let mut subset_errors: Vec<_> = polonius_output
1495             .subset_errors
1496             .iter()
1497             .flat_map(|(_location, subset_errors)| subset_errors.iter())
1498             .collect();
1499         subset_errors.sort();
1500         subset_errors.dedup();
1501
1502         for (longer_fr, shorter_fr) in subset_errors.into_iter() {
1503             debug!(
1504                 "check_polonius_subset_errors: subset_error longer_fr={:?},\
1505                  shorter_fr={:?}",
1506                 longer_fr, shorter_fr
1507             );
1508
1509             let propagated = self.try_propagate_universal_region_error(
1510                 *longer_fr,
1511                 *shorter_fr,
1512                 &mut propagated_outlives_requirements,
1513             );
1514             if propagated == RegionRelationCheckResult::Error {
1515                 errors_buffer.push(RegionErrorKind::RegionError {
1516                     longer_fr: *longer_fr,
1517                     shorter_fr: *shorter_fr,
1518                     fr_origin: NllRegionVariableOrigin::FreeRegion,
1519                     is_reported: true,
1520                 });
1521             }
1522         }
1523
1524         // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has
1525         // a more complete picture on how to separate this responsibility.
1526         for (fr, fr_definition) in self.definitions.iter_enumerated() {
1527             match fr_definition.origin {
1528                 NllRegionVariableOrigin::FreeRegion => {
1529                     // handled by polonius above
1530                 }
1531
1532                 NllRegionVariableOrigin::Placeholder(placeholder) => {
1533                     self.check_bound_universal_region(fr, placeholder, errors_buffer);
1534                 }
1535
1536                 NllRegionVariableOrigin::Existential { .. } => {
1537                     // nothing to check here
1538                 }
1539             }
1540         }
1541     }
1542
1543     /// Checks the final value for the free region `fr` to see if it
1544     /// grew too large. In particular, examine what `end(X)` points
1545     /// wound up in `fr`'s final value; for each `end(X)` where `X !=
1546     /// fr`, we want to check that `fr: X`. If not, that's either an
1547     /// error, or something we have to propagate to our creator.
1548     ///
1549     /// Things that are to be propagated are accumulated into the
1550     /// `outlives_requirements` vector.
1551     #[instrument(skip(self, propagated_outlives_requirements, errors_buffer), level = "debug")]
1552     fn check_universal_region(
1553         &self,
1554         longer_fr: RegionVid,
1555         propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1556         errors_buffer: &mut RegionErrors<'tcx>,
1557     ) {
1558         let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1559
1560         // Because this free region must be in the ROOT universe, we
1561         // know it cannot contain any bound universes.
1562         assert!(self.scc_universes[longer_fr_scc] == ty::UniverseIndex::ROOT);
1563         debug_assert!(self.scc_values.placeholders_contained_in(longer_fr_scc).next().is_none());
1564
1565         // Only check all of the relations for the main representative of each
1566         // SCC, otherwise just check that we outlive said representative. This
1567         // reduces the number of redundant relations propagated out of
1568         // closures.
1569         // Note that the representative will be a universal region if there is
1570         // one in this SCC, so we will always check the representative here.
1571         let representative = self.scc_representatives[longer_fr_scc];
1572         if representative != longer_fr {
1573             if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1574                 longer_fr,
1575                 representative,
1576                 propagated_outlives_requirements,
1577             ) {
1578                 errors_buffer.push(RegionErrorKind::RegionError {
1579                     longer_fr,
1580                     shorter_fr: representative,
1581                     fr_origin: NllRegionVariableOrigin::FreeRegion,
1582                     is_reported: true,
1583                 });
1584             }
1585             return;
1586         }
1587
1588         // Find every region `o` such that `fr: o`
1589         // (because `fr` includes `end(o)`).
1590         let mut error_reported = false;
1591         for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {
1592             if let RegionRelationCheckResult::Error = self.check_universal_region_relation(
1593                 longer_fr,
1594                 shorter_fr,
1595                 propagated_outlives_requirements,
1596             ) {
1597                 // We only report the first region error. Subsequent errors are hidden so as
1598                 // not to overwhelm the user, but we do record them so as to potentially print
1599                 // better diagnostics elsewhere...
1600                 errors_buffer.push(RegionErrorKind::RegionError {
1601                     longer_fr,
1602                     shorter_fr,
1603                     fr_origin: NllRegionVariableOrigin::FreeRegion,
1604                     is_reported: !error_reported,
1605                 });
1606
1607                 error_reported = true;
1608             }
1609         }
1610     }
1611
1612     /// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate
1613     /// the constraint outward (e.g. to a closure environment), but if that fails, there is an
1614     /// error.
1615     fn check_universal_region_relation(
1616         &self,
1617         longer_fr: RegionVid,
1618         shorter_fr: RegionVid,
1619         propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1620     ) -> RegionRelationCheckResult {
1621         // If it is known that `fr: o`, carry on.
1622         if self.universal_region_relations.outlives(longer_fr, shorter_fr) {
1623             RegionRelationCheckResult::Ok
1624         } else {
1625             // If we are not in a context where we can't propagate errors, or we
1626             // could not shrink `fr` to something smaller, then just report an
1627             // error.
1628             //
1629             // Note: in this case, we use the unapproximated regions to report the
1630             // error. This gives better error messages in some cases.
1631             self.try_propagate_universal_region_error(
1632                 longer_fr,
1633                 shorter_fr,
1634                 propagated_outlives_requirements,
1635             )
1636         }
1637     }
1638
1639     /// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's
1640     /// creator. If we cannot, then the caller should report an error to the user.
1641     fn try_propagate_universal_region_error(
1642         &self,
1643         longer_fr: RegionVid,
1644         shorter_fr: RegionVid,
1645         propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1646     ) -> RegionRelationCheckResult {
1647         if let Some(propagated_outlives_requirements) = propagated_outlives_requirements {
1648             // Shrink `longer_fr` until we find a non-local region (if we do).
1649             // We'll call it `fr-` -- it's ever so slightly smaller than
1650             // `longer_fr`.
1651             if let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr)
1652             {
1653                 debug!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus);
1654
1655                 let blame_span_category = self.find_outlives_blame_span(
1656                     longer_fr,
1657                     NllRegionVariableOrigin::FreeRegion,
1658                     shorter_fr,
1659                 );
1660
1661                 // Grow `shorter_fr` until we find some non-local regions. (We
1662                 // always will.)  We'll call them `shorter_fr+` -- they're ever
1663                 // so slightly larger than `shorter_fr`.
1664                 let shorter_fr_plus =
1665                     self.universal_region_relations.non_local_upper_bounds(shorter_fr);
1666                 debug!(
1667                     "try_propagate_universal_region_error: shorter_fr_plus={:?}",
1668                     shorter_fr_plus
1669                 );
1670                 for fr in shorter_fr_plus {
1671                     // Push the constraint `fr-: shorter_fr+`
1672                     propagated_outlives_requirements.push(ClosureOutlivesRequirement {
1673                         subject: ClosureOutlivesSubject::Region(fr_minus),
1674                         outlived_free_region: fr,
1675                         blame_span: blame_span_category.1.span,
1676                         category: blame_span_category.0,
1677                     });
1678                 }
1679                 return RegionRelationCheckResult::Propagated;
1680             }
1681         }
1682
1683         RegionRelationCheckResult::Error
1684     }
1685
1686     fn check_bound_universal_region(
1687         &self,
1688         longer_fr: RegionVid,
1689         placeholder: ty::PlaceholderRegion,
1690         errors_buffer: &mut RegionErrors<'tcx>,
1691     ) {
1692         debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,);
1693
1694         let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1695         debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,);
1696
1697         // If we have some bound universal region `'a`, then the only
1698         // elements it can contain is itself -- we don't know anything
1699         // else about it!
1700         let Some(error_element) = ({
1701             self.scc_values.elements_contained_in(longer_fr_scc).find(|element| match element {
1702                 RegionElement::Location(_) => true,
1703                 RegionElement::RootUniversalRegion(_) => true,
1704                 RegionElement::PlaceholderRegion(placeholder1) => placeholder != *placeholder1,
1705             })
1706         }) else {
1707             return;
1708         };
1709         debug!("check_bound_universal_region: error_element = {:?}", error_element);
1710
1711         // Find the region that introduced this `error_element`.
1712         errors_buffer.push(RegionErrorKind::BoundUniversalRegionError {
1713             longer_fr,
1714             error_element,
1715             placeholder,
1716         });
1717     }
1718
1719     fn check_member_constraints(
1720         &self,
1721         infcx: &InferCtxt<'_, 'tcx>,
1722         errors_buffer: &mut RegionErrors<'tcx>,
1723     ) {
1724         let member_constraints = self.member_constraints.clone();
1725         for m_c_i in member_constraints.all_indices() {
1726             debug!("check_member_constraint(m_c_i={:?})", m_c_i);
1727             let m_c = &member_constraints[m_c_i];
1728             let member_region_vid = m_c.member_region_vid;
1729             debug!(
1730                 "check_member_constraint: member_region_vid={:?} with value {}",
1731                 member_region_vid,
1732                 self.region_value_str(member_region_vid),
1733             );
1734             let choice_regions = member_constraints.choice_regions(m_c_i);
1735             debug!("check_member_constraint: choice_regions={:?}", choice_regions);
1736
1737             // Did the member region wind up equal to any of the option regions?
1738             if let Some(o) =
1739                 choice_regions.iter().find(|&&o_r| self.eval_equal(o_r, m_c.member_region_vid))
1740             {
1741                 debug!("check_member_constraint: evaluated as equal to {:?}", o);
1742                 continue;
1743             }
1744
1745             // If not, report an error.
1746             let member_region = infcx.tcx.mk_region(ty::ReVar(member_region_vid));
1747             errors_buffer.push(RegionErrorKind::UnexpectedHiddenRegion {
1748                 span: m_c.definition_span,
1749                 hidden_ty: m_c.hidden_ty,
1750                 key: m_c.key,
1751                 member_region,
1752             });
1753         }
1754     }
1755
1756     /// We have a constraint `fr1: fr2` that is not satisfied, where
1757     /// `fr2` represents some universal region. Here, `r` is some
1758     /// region where we know that `fr1: r` and this function has the
1759     /// job of determining whether `r` is "to blame" for the fact that
1760     /// `fr1: fr2` is required.
1761     ///
1762     /// This is true under two conditions:
1763     ///
1764     /// - `r == fr2`
1765     /// - `fr2` is `'static` and `r` is some placeholder in a universe
1766     ///   that cannot be named by `fr1`; in that case, we will require
1767     ///   that `fr1: 'static` because it is the only way to `fr1: r` to
1768     ///   be satisfied. (See `add_incompatible_universe`.)
1769     pub(crate) fn provides_universal_region(
1770         &self,
1771         r: RegionVid,
1772         fr1: RegionVid,
1773         fr2: RegionVid,
1774     ) -> bool {
1775         debug!("provides_universal_region(r={:?}, fr1={:?}, fr2={:?})", r, fr1, fr2);
1776         let result = {
1777             r == fr2 || {
1778                 fr2 == self.universal_regions.fr_static && self.cannot_name_placeholder(fr1, r)
1779             }
1780         };
1781         debug!("provides_universal_region: result = {:?}", result);
1782         result
1783     }
1784
1785     /// If `r2` represents a placeholder region, then this returns
1786     /// `true` if `r1` cannot name that placeholder in its
1787     /// value; otherwise, returns `false`.
1788     pub(crate) fn cannot_name_placeholder(&self, r1: RegionVid, r2: RegionVid) -> bool {
1789         debug!("cannot_name_value_of(r1={:?}, r2={:?})", r1, r2);
1790
1791         match self.definitions[r2].origin {
1792             NllRegionVariableOrigin::Placeholder(placeholder) => {
1793                 let universe1 = self.definitions[r1].universe;
1794                 debug!(
1795                     "cannot_name_value_of: universe1={:?} placeholder={:?}",
1796                     universe1, placeholder
1797                 );
1798                 universe1.cannot_name(placeholder.universe)
1799             }
1800
1801             NllRegionVariableOrigin::FreeRegion | NllRegionVariableOrigin::Existential { .. } => {
1802                 false
1803             }
1804         }
1805     }
1806
1807     pub(crate) fn retrieve_closure_constraint_info(
1808         &self,
1809         constraint: OutlivesConstraint<'tcx>,
1810     ) -> Option<(ConstraintCategory<'tcx>, Span)> {
1811         match constraint.locations {
1812             Locations::All(_) => None,
1813             Locations::Single(loc) => {
1814                 self.closure_bounds_mapping[&loc].get(&(constraint.sup, constraint.sub)).copied()
1815             }
1816         }
1817     }
1818
1819     /// Finds a good `ObligationCause` to blame for the fact that `fr1` outlives `fr2`.
1820     pub(crate) fn find_outlives_blame_span(
1821         &self,
1822         fr1: RegionVid,
1823         fr1_origin: NllRegionVariableOrigin,
1824         fr2: RegionVid,
1825     ) -> (ConstraintCategory<'tcx>, ObligationCause<'tcx>) {
1826         let BlameConstraint { category, cause, .. } = self
1827             .best_blame_constraint(fr1, fr1_origin, |r| self.provides_universal_region(r, fr1, fr2))
1828             .0;
1829         (category, cause)
1830     }
1831
1832     /// Walks the graph of constraints (where `'a: 'b` is considered
1833     /// an edge `'a -> 'b`) to find all paths from `from_region` to
1834     /// `to_region`. The paths are accumulated into the vector
1835     /// `results`. The paths are stored as a series of
1836     /// `ConstraintIndex` values -- in other words, a list of *edges*.
1837     ///
1838     /// Returns: a series of constraints as well as the region `R`
1839     /// that passed the target test.
1840     pub(crate) fn find_constraint_paths_between_regions(
1841         &self,
1842         from_region: RegionVid,
1843         target_test: impl Fn(RegionVid) -> bool,
1844     ) -> Option<(Vec<OutlivesConstraint<'tcx>>, RegionVid)> {
1845         let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions);
1846         context[from_region] = Trace::StartRegion;
1847
1848         // Use a deque so that we do a breadth-first search. We will
1849         // stop at the first match, which ought to be the shortest
1850         // path (fewest constraints).
1851         let mut deque = VecDeque::new();
1852         deque.push_back(from_region);
1853
1854         while let Some(r) = deque.pop_front() {
1855             debug!(
1856                 "find_constraint_paths_between_regions: from_region={:?} r={:?} value={}",
1857                 from_region,
1858                 r,
1859                 self.region_value_str(r),
1860             );
1861
1862             // Check if we reached the region we were looking for. If so,
1863             // we can reconstruct the path that led to it and return it.
1864             if target_test(r) {
1865                 let mut result = vec![];
1866                 let mut p = r;
1867                 loop {
1868                     match context[p].clone() {
1869                         Trace::NotVisited => {
1870                             bug!("found unvisited region {:?} on path to {:?}", p, r)
1871                         }
1872
1873                         Trace::FromOutlivesConstraint(c) => {
1874                             p = c.sup;
1875                             result.push(c);
1876                         }
1877
1878                         Trace::StartRegion => {
1879                             result.reverse();
1880                             return Some((result, r));
1881                         }
1882                     }
1883                 }
1884             }
1885
1886             // Otherwise, walk over the outgoing constraints and
1887             // enqueue any regions we find, keeping track of how we
1888             // reached them.
1889
1890             // A constraint like `'r: 'x` can come from our constraint
1891             // graph.
1892             let fr_static = self.universal_regions.fr_static;
1893             let outgoing_edges_from_graph =
1894                 self.constraint_graph.outgoing_edges(r, &self.constraints, fr_static);
1895
1896             // Always inline this closure because it can be hot.
1897             let mut handle_constraint = #[inline(always)]
1898             |constraint: OutlivesConstraint<'tcx>| {
1899                 debug_assert_eq!(constraint.sup, r);
1900                 let sub_region = constraint.sub;
1901                 if let Trace::NotVisited = context[sub_region] {
1902                     context[sub_region] = Trace::FromOutlivesConstraint(constraint);
1903                     deque.push_back(sub_region);
1904                 }
1905             };
1906
1907             // This loop can be hot.
1908             for constraint in outgoing_edges_from_graph {
1909                 handle_constraint(constraint);
1910             }
1911
1912             // Member constraints can also give rise to `'r: 'x` edges that
1913             // were not part of the graph initially, so watch out for those.
1914             // (But they are extremely rare; this loop is very cold.)
1915             for constraint in self.applied_member_constraints(r) {
1916                 let p_c = &self.member_constraints[constraint.member_constraint_index];
1917                 let constraint = OutlivesConstraint {
1918                     sup: r,
1919                     sub: constraint.min_choice,
1920                     locations: Locations::All(p_c.definition_span),
1921                     span: p_c.definition_span,
1922                     category: ConstraintCategory::OpaqueType,
1923                     variance_info: ty::VarianceDiagInfo::default(),
1924                 };
1925                 handle_constraint(constraint);
1926             }
1927         }
1928
1929         None
1930     }
1931
1932     /// Finds some region R such that `fr1: R` and `R` is live at `elem`.
1933     #[instrument(skip(self), level = "trace", ret)]
1934     pub(crate) fn find_sub_region_live_at(&self, fr1: RegionVid, elem: Location) -> RegionVid {
1935         trace!(scc = ?self.constraint_sccs.scc(fr1));
1936         trace!(universe = ?self.scc_universes[self.constraint_sccs.scc(fr1)]);
1937         self.find_constraint_paths_between_regions(fr1, |r| {
1938             // First look for some `r` such that `fr1: r` and `r` is live at `elem`
1939             trace!(?r, liveness_constraints=?self.liveness_constraints.region_value_str(r));
1940             self.liveness_constraints.contains(r, elem)
1941         })
1942         .or_else(|| {
1943             // If we fail to find that, we may find some `r` such that
1944             // `fr1: r` and `r` is a placeholder from some universe
1945             // `fr1` cannot name. This would force `fr1` to be
1946             // `'static`.
1947             self.find_constraint_paths_between_regions(fr1, |r| {
1948                 self.cannot_name_placeholder(fr1, r)
1949             })
1950         })
1951         .or_else(|| {
1952             // If we fail to find THAT, it may be that `fr1` is a
1953             // placeholder that cannot "fit" into its SCC. In that
1954             // case, there should be some `r` where `fr1: r` and `fr1` is a
1955             // placeholder that `r` cannot name. We can blame that
1956             // edge.
1957             //
1958             // Remember that if `R1: R2`, then the universe of R1
1959             // must be able to name the universe of R2, because R2 will
1960             // be at least `'empty(Universe(R2))`, and `R1` must be at
1961             // larger than that.
1962             self.find_constraint_paths_between_regions(fr1, |r| {
1963                 self.cannot_name_placeholder(r, fr1)
1964             })
1965         })
1966         .map(|(_path, r)| r)
1967         .unwrap()
1968     }
1969
1970     /// Get the region outlived by `longer_fr` and live at `element`.
1971     pub(crate) fn region_from_element(
1972         &self,
1973         longer_fr: RegionVid,
1974         element: &RegionElement,
1975     ) -> RegionVid {
1976         match *element {
1977             RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),
1978             RegionElement::RootUniversalRegion(r) => r,
1979             RegionElement::PlaceholderRegion(error_placeholder) => self
1980                 .definitions
1981                 .iter_enumerated()
1982                 .find_map(|(r, definition)| match definition.origin {
1983                     NllRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),
1984                     _ => None,
1985                 })
1986                 .unwrap(),
1987         }
1988     }
1989
1990     /// Get the region definition of `r`.
1991     pub(crate) fn region_definition(&self, r: RegionVid) -> &RegionDefinition<'tcx> {
1992         &self.definitions[r]
1993     }
1994
1995     /// Check if the SCC of `r` contains `upper`.
1996     pub(crate) fn upper_bound_in_region_scc(&self, r: RegionVid, upper: RegionVid) -> bool {
1997         let r_scc = self.constraint_sccs.scc(r);
1998         self.scc_values.contains(r_scc, upper)
1999     }
2000
2001     pub(crate) fn universal_regions(&self) -> &UniversalRegions<'tcx> {
2002         self.universal_regions.as_ref()
2003     }
2004
2005     /// Tries to find the best constraint to blame for the fact that
2006     /// `R: from_region`, where `R` is some region that meets
2007     /// `target_test`. This works by following the constraint graph,
2008     /// creating a constraint path that forces `R` to outlive
2009     /// `from_region`, and then finding the best choices within that
2010     /// path to blame.
2011     #[instrument(level = "debug", skip(self, target_test))]
2012     pub(crate) fn best_blame_constraint(
2013         &self,
2014         from_region: RegionVid,
2015         from_region_origin: NllRegionVariableOrigin,
2016         target_test: impl Fn(RegionVid) -> bool,
2017     ) -> (BlameConstraint<'tcx>, Vec<ExtraConstraintInfo>) {
2018         // Find all paths
2019         let (path, target_region) =
2020             self.find_constraint_paths_between_regions(from_region, target_test).unwrap();
2021         debug!(
2022             "path={:#?}",
2023             path.iter()
2024                 .map(|c| format!(
2025                     "{:?} ({:?}: {:?})",
2026                     c,
2027                     self.constraint_sccs.scc(c.sup),
2028                     self.constraint_sccs.scc(c.sub),
2029                 ))
2030                 .collect::<Vec<_>>()
2031         );
2032
2033         let mut extra_info = vec![];
2034         for constraint in path.iter() {
2035             let outlived = constraint.sub;
2036             let Some(origin) = self.var_infos.get(outlived) else { continue; };
2037             let RegionVariableOrigin::Nll(NllRegionVariableOrigin::Placeholder(p)) = origin.origin else { continue; };
2038             debug!(?constraint, ?p);
2039             let ConstraintCategory::Predicate(span) = constraint.category else { continue; };
2040             extra_info.push(ExtraConstraintInfo::PlaceholderFromPredicate(span));
2041             // We only want to point to one
2042             break;
2043         }
2044
2045         // We try to avoid reporting a `ConstraintCategory::Predicate` as our best constraint.
2046         // Instead, we use it to produce an improved `ObligationCauseCode`.
2047         // FIXME - determine what we should do if we encounter multiple `ConstraintCategory::Predicate`
2048         // constraints. Currently, we just pick the first one.
2049         let cause_code = path
2050             .iter()
2051             .find_map(|constraint| {
2052                 if let ConstraintCategory::Predicate(predicate_span) = constraint.category {
2053                     // We currently do not store the `DefId` in the `ConstraintCategory`
2054                     // for performances reasons. The error reporting code used by NLL only
2055                     // uses the span, so this doesn't cause any problems at the moment.
2056                     Some(ObligationCauseCode::BindingObligation(
2057                         CRATE_DEF_ID.to_def_id(),
2058                         predicate_span,
2059                     ))
2060                 } else {
2061                     None
2062                 }
2063             })
2064             .unwrap_or_else(|| ObligationCauseCode::MiscObligation);
2065
2066         // Classify each of the constraints along the path.
2067         let mut categorized_path: Vec<BlameConstraint<'tcx>> = path
2068             .iter()
2069             .map(|constraint| {
2070                 let (category, span, from_closure, cause_code) =
2071                     if constraint.category == ConstraintCategory::ClosureBounds {
2072                         if let Some((category, span)) =
2073                             self.retrieve_closure_constraint_info(*constraint)
2074                         {
2075                             (category, span, true, ObligationCauseCode::MiscObligation)
2076                         } else {
2077                             (
2078                                 constraint.category,
2079                                 constraint.span,
2080                                 false,
2081                                 ObligationCauseCode::MiscObligation,
2082                             )
2083                         }
2084                     } else {
2085                         (constraint.category, constraint.span, false, cause_code.clone())
2086                     };
2087                 BlameConstraint {
2088                     category,
2089                     from_closure,
2090                     cause: ObligationCause::new(span, CRATE_HIR_ID, cause_code),
2091                     variance_info: constraint.variance_info,
2092                     outlives_constraint: *constraint,
2093                 }
2094             })
2095             .collect();
2096         debug!("categorized_path={:#?}", categorized_path);
2097
2098         // To find the best span to cite, we first try to look for the
2099         // final constraint that is interesting and where the `sup` is
2100         // not unified with the ultimate target region. The reason
2101         // for this is that we have a chain of constraints that lead
2102         // from the source to the target region, something like:
2103         //
2104         //    '0: '1 ('0 is the source)
2105         //    '1: '2
2106         //    '2: '3
2107         //    '3: '4
2108         //    '4: '5
2109         //    '5: '6 ('6 is the target)
2110         //
2111         // Some of those regions are unified with `'6` (in the same
2112         // SCC).  We want to screen those out. After that point, the
2113         // "closest" constraint we have to the end is going to be the
2114         // most likely to be the point where the value escapes -- but
2115         // we still want to screen for an "interesting" point to
2116         // highlight (e.g., a call site or something).
2117         let target_scc = self.constraint_sccs.scc(target_region);
2118         let mut range = 0..path.len();
2119
2120         // As noted above, when reporting an error, there is typically a chain of constraints
2121         // leading from some "source" region which must outlive some "target" region.
2122         // In most cases, we prefer to "blame" the constraints closer to the target --
2123         // but there is one exception. When constraints arise from higher-ranked subtyping,
2124         // we generally prefer to blame the source value,
2125         // as the "target" in this case tends to be some type annotation that the user gave.
2126         // Therefore, if we find that the region origin is some instantiation
2127         // of a higher-ranked region, we start our search from the "source" point
2128         // rather than the "target", and we also tweak a few other things.
2129         //
2130         // An example might be this bit of Rust code:
2131         //
2132         // ```rust
2133         // let x: fn(&'static ()) = |_| {};
2134         // let y: for<'a> fn(&'a ()) = x;
2135         // ```
2136         //
2137         // In MIR, this will be converted into a combination of assignments and type ascriptions.
2138         // In particular, the 'static is imposed through a type ascription:
2139         //
2140         // ```rust
2141         // x = ...;
2142         // AscribeUserType(x, fn(&'static ())
2143         // y = x;
2144         // ```
2145         //
2146         // We wind up ultimately with constraints like
2147         //
2148         // ```rust
2149         // !a: 'temp1 // from the `y = x` statement
2150         // 'temp1: 'temp2
2151         // 'temp2: 'static // from the AscribeUserType
2152         // ```
2153         //
2154         // and here we prefer to blame the source (the y = x statement).
2155         let blame_source = match from_region_origin {
2156             NllRegionVariableOrigin::FreeRegion
2157             | NllRegionVariableOrigin::Existential { from_forall: false } => true,
2158             NllRegionVariableOrigin::Placeholder(_)
2159             | NllRegionVariableOrigin::Existential { from_forall: true } => false,
2160         };
2161
2162         let find_region = |i: &usize| {
2163             let constraint = &path[*i];
2164
2165             let constraint_sup_scc = self.constraint_sccs.scc(constraint.sup);
2166
2167             if blame_source {
2168                 match categorized_path[*i].category {
2169                     ConstraintCategory::OpaqueType
2170                     | ConstraintCategory::Boring
2171                     | ConstraintCategory::BoringNoLocation
2172                     | ConstraintCategory::Internal
2173                     | ConstraintCategory::Predicate(_) => false,
2174                     ConstraintCategory::TypeAnnotation
2175                     | ConstraintCategory::Return(_)
2176                     | ConstraintCategory::Yield => true,
2177                     _ => constraint_sup_scc != target_scc,
2178                 }
2179             } else {
2180                 !matches!(
2181                     categorized_path[*i].category,
2182                     ConstraintCategory::OpaqueType
2183                         | ConstraintCategory::Boring
2184                         | ConstraintCategory::BoringNoLocation
2185                         | ConstraintCategory::Internal
2186                         | ConstraintCategory::Predicate(_)
2187                 )
2188             }
2189         };
2190
2191         let best_choice =
2192             if blame_source { range.rev().find(find_region) } else { range.find(find_region) };
2193
2194         debug!(?best_choice, ?blame_source, ?extra_info);
2195
2196         if let Some(i) = best_choice {
2197             if let Some(next) = categorized_path.get(i + 1) {
2198                 if matches!(categorized_path[i].category, ConstraintCategory::Return(_))
2199                     && next.category == ConstraintCategory::OpaqueType
2200                 {
2201                     // The return expression is being influenced by the return type being
2202                     // impl Trait, point at the return type and not the return expr.
2203                     return (next.clone(), extra_info);
2204                 }
2205             }
2206
2207             if categorized_path[i].category == ConstraintCategory::Return(ReturnConstraint::Normal)
2208             {
2209                 let field = categorized_path.iter().find_map(|p| {
2210                     if let ConstraintCategory::ClosureUpvar(f) = p.category {
2211                         Some(f)
2212                     } else {
2213                         None
2214                     }
2215                 });
2216
2217                 if let Some(field) = field {
2218                     categorized_path[i].category =
2219                         ConstraintCategory::Return(ReturnConstraint::ClosureUpvar(field));
2220                 }
2221             }
2222
2223             return (categorized_path[i].clone(), extra_info);
2224         }
2225
2226         // If that search fails, that is.. unusual. Maybe everything
2227         // is in the same SCC or something. In that case, find what
2228         // appears to be the most interesting point to report to the
2229         // user via an even more ad-hoc guess.
2230         categorized_path.sort_by(|p0, p1| p0.category.cmp(&p1.category));
2231         debug!("sorted_path={:#?}", categorized_path);
2232
2233         (categorized_path.remove(0), extra_info)
2234     }
2235
2236     pub(crate) fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
2237         self.universe_causes[&universe].clone()
2238     }
2239 }
2240
2241 impl<'tcx> RegionDefinition<'tcx> {
2242     fn new(universe: ty::UniverseIndex, rv_origin: RegionVariableOrigin) -> Self {
2243         // Create a new region definition. Note that, for free
2244         // regions, the `external_name` field gets updated later in
2245         // `init_universal_regions`.
2246
2247         let origin = match rv_origin {
2248             RegionVariableOrigin::Nll(origin) => origin,
2249             _ => NllRegionVariableOrigin::Existential { from_forall: false },
2250         };
2251
2252         Self { origin, universe, external_name: None }
2253     }
2254 }
2255
2256 pub trait ClosureRegionRequirementsExt<'tcx> {
2257     fn apply_requirements(
2258         &self,
2259         tcx: TyCtxt<'tcx>,
2260         closure_def_id: DefId,
2261         closure_substs: SubstsRef<'tcx>,
2262     ) -> Vec<QueryOutlivesConstraint<'tcx>>;
2263 }
2264
2265 impl<'tcx> ClosureRegionRequirementsExt<'tcx> for ClosureRegionRequirements<'tcx> {
2266     /// Given an instance T of the closure type, this method
2267     /// instantiates the "extra" requirements that we computed for the
2268     /// closure into the inference context. This has the effect of
2269     /// adding new outlives obligations to existing variables.
2270     ///
2271     /// As described on `ClosureRegionRequirements`, the extra
2272     /// requirements are expressed in terms of regionvids that index
2273     /// into the free regions that appear on the closure type. So, to
2274     /// do this, we first copy those regions out from the type T into
2275     /// a vector. Then we can just index into that vector to extract
2276     /// out the corresponding region from T and apply the
2277     /// requirements.
2278     fn apply_requirements(
2279         &self,
2280         tcx: TyCtxt<'tcx>,
2281         closure_def_id: DefId,
2282         closure_substs: SubstsRef<'tcx>,
2283     ) -> Vec<QueryOutlivesConstraint<'tcx>> {
2284         debug!(
2285             "apply_requirements(closure_def_id={:?}, closure_substs={:?})",
2286             closure_def_id, closure_substs
2287         );
2288
2289         // Extract the values of the free regions in `closure_substs`
2290         // into a vector.  These are the regions that we will be
2291         // relating to one another.
2292         let closure_mapping = &UniversalRegions::closure_mapping(
2293             tcx,
2294             closure_substs,
2295             self.num_external_vids,
2296             tcx.typeck_root_def_id(closure_def_id),
2297         );
2298         debug!("apply_requirements: closure_mapping={:?}", closure_mapping);
2299
2300         // Create the predicates.
2301         self.outlives_requirements
2302             .iter()
2303             .map(|outlives_requirement| {
2304                 let outlived_region = closure_mapping[outlives_requirement.outlived_free_region];
2305
2306                 match outlives_requirement.subject {
2307                     ClosureOutlivesSubject::Region(region) => {
2308                         let region = closure_mapping[region];
2309                         debug!(
2310                             "apply_requirements: region={:?} \
2311                              outlived_region={:?} \
2312                              outlives_requirement={:?}",
2313                             region, outlived_region, outlives_requirement,
2314                         );
2315                         (
2316                             ty::Binder::dummy(ty::OutlivesPredicate(
2317                                 region.into(),
2318                                 outlived_region,
2319                             )),
2320                             ConstraintCategory::BoringNoLocation,
2321                         )
2322                     }
2323
2324                     ClosureOutlivesSubject::Ty(ty) => {
2325                         debug!(
2326                             "apply_requirements: ty={:?} \
2327                              outlived_region={:?} \
2328                              outlives_requirement={:?}",
2329                             ty, outlived_region, outlives_requirement,
2330                         );
2331                         (
2332                             ty::Binder::dummy(ty::OutlivesPredicate(ty.into(), outlived_region)),
2333                             ConstraintCategory::BoringNoLocation,
2334                         )
2335                     }
2336                 }
2337             })
2338             .collect()
2339     }
2340 }
2341
2342 #[derive(Clone, Debug)]
2343 pub struct BlameConstraint<'tcx> {
2344     pub category: ConstraintCategory<'tcx>,
2345     pub from_closure: bool,
2346     pub cause: ObligationCause<'tcx>,
2347     pub variance_info: ty::VarianceDiagInfo<'tcx>,
2348     pub outlives_constraint: OutlivesConstraint<'tcx>,
2349 }