]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/region_infer/mod.rs
Rollup merge of #66827 - RalfJung:miri-missing-ret-place, r=oli-obk
[rust.git] / src / librustc_mir / borrow_check / nll / region_infer / mod.rs
1 use std::rc::Rc;
2
3 use crate::borrow_check::nll::{
4     constraints::{
5         graph::NormalConstraintGraph,
6         ConstraintSccIndex,
7         OutlivesConstraint,
8         OutlivesConstraintSet,
9     },
10     member_constraints::{MemberConstraintSet, NllMemberConstraintIndex},
11     region_infer::values::{
12         PlaceholderIndices, RegionElement, ToElementIndex
13     },
14     region_infer::error_reporting::outlives_suggestion::OutlivesSuggestionBuilder,
15     type_check::{free_region_relations::UniversalRegionRelations, Locations},
16 };
17 use crate::borrow_check::Upvar;
18
19 use rustc::hir::def_id::DefId;
20 use rustc::infer::canonical::QueryOutlivesConstraint;
21 use rustc::infer::opaque_types;
22 use rustc::infer::region_constraints::{GenericKind, VarInfos, VerifyBound};
23 use rustc::infer::{InferCtxt, NLLRegionVariableOrigin, RegionVariableOrigin};
24 use rustc::mir::{
25     Body, ClosureOutlivesRequirement, ClosureOutlivesSubject, ClosureRegionRequirements,
26     ConstraintCategory, Local, Location,
27 };
28 use rustc::ty::{self, subst::SubstsRef, RegionVid, Ty, TyCtxt, TypeFoldable};
29 use rustc::util::common::ErrorReported;
30 use rustc_data_structures::binary_search_util;
31 use rustc_index::bit_set::BitSet;
32 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
33 use rustc_data_structures::graph::WithSuccessors;
34 use rustc_data_structures::graph::scc::Sccs;
35 use rustc_data_structures::graph::vec_graph::VecGraph;
36 use rustc_index::vec::IndexVec;
37 use rustc_errors::{Diagnostic, DiagnosticBuilder};
38 use syntax_pos::Span;
39 use syntax_pos::symbol::Symbol;
40
41 crate use self::error_reporting::{RegionName, RegionNameSource, RegionErrorNamingCtx};
42 use self::values::{LivenessValues, RegionValueElements, RegionValues};
43 use super::universal_regions::UniversalRegions;
44 use super::ToRegionVid;
45
46 mod dump_mir;
47 mod error_reporting;
48 mod graphviz;
49
50 pub mod values;
51
52 pub struct RegionInferenceContext<'tcx> {
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: Rc<OutlivesConstraintSet>,
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: Rc<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`
79     /// exists if `B: A`. Computed lazilly.
80     rev_constraint_graph: Option<Rc<VecGraph<ConstraintSccIndex>>>,
81
82     /// The "R0 member of [R1..Rn]" constraints, indexed by SCC.
83     member_constraints: Rc<MemberConstraintSet<'tcx, ConstraintSccIndex>>,
84
85     /// Records the member constraints that we applied to each scc.
86     /// This is useful for error reporting. Once constraint
87     /// propagation is done, this vector is sorted according to
88     /// `member_region_scc`.
89     member_constraints_applied: Vec<AppliedMemberConstraint>,
90
91     /// Map closure bounds to a `Span` that should be used for error reporting.
92     closure_bounds_mapping:
93         FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
94
95     /// Contains the minimum universe of any variable within the same
96     /// SCC. We will ensure that no SCC contains values that are not
97     /// visible from this index.
98     scc_universes: IndexVec<ConstraintSccIndex, ty::UniverseIndex>,
99
100     /// Contains a "representative" from each SCC. This will be the
101     /// minimal RegionVid belonging to that universe. It is used as a
102     /// kind of hacky way to manage checking outlives relationships,
103     /// since we can 'canonicalize' each region to the representative
104     /// of its SCC and be sure that -- if they have the same repr --
105     /// they *must* be equal (though not having the same repr does not
106     /// mean they are unequal).
107     scc_representatives: IndexVec<ConstraintSccIndex, ty::RegionVid>,
108
109     /// The final inferred values of the region variables; we compute
110     /// one value per SCC. To get the value for any given *region*,
111     /// you first find which scc it is a part of.
112     scc_values: RegionValues<ConstraintSccIndex>,
113
114     /// Type constraints that we check after solving.
115     type_tests: Vec<TypeTest<'tcx>>,
116
117     /// Information about the universally quantified regions in scope
118     /// on this function.
119     universal_regions: Rc<UniversalRegions<'tcx>>,
120
121     /// Information about how the universally quantified regions in
122     /// scope on this function relate to one another.
123     universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
124 }
125
126 /// Each time that `apply_member_constraint` is successful, it appends
127 /// one of these structs to the `member_constraints_applied` field.
128 /// This is used in error reporting to trace out what happened.
129 ///
130 /// The way that `apply_member_constraint` works is that it effectively
131 /// adds a new lower bound to the SCC it is analyzing: so you wind up
132 /// with `'R: 'O` where `'R` is the pick-region and `'O` is the
133 /// minimal viable option.
134 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
135 struct AppliedMemberConstraint {
136     /// The SCC that was affected. (The "member region".)
137     ///
138     /// The vector if `AppliedMemberConstraint` elements is kept sorted
139     /// by this field.
140     member_region_scc: ConstraintSccIndex,
141
142     /// The "best option" that `apply_member_constraint` found -- this was
143     /// added as an "ad-hoc" lower-bound to `member_region_scc`.
144     min_choice: ty::RegionVid,
145
146     /// The "member constraint index" -- we can find out details about
147     /// the constraint from
148     /// `set.member_constraints[member_constraint_index]`.
149     member_constraint_index: NllMemberConstraintIndex,
150 }
151
152 struct RegionDefinition<'tcx> {
153     /// What kind of variable is this -- a free region? existential
154     /// variable? etc. (See the `NLLRegionVariableOrigin` for more
155     /// info.)
156     origin: NLLRegionVariableOrigin,
157
158     /// Which universe is this region variable defined in? This is
159     /// most often `ty::UniverseIndex::ROOT`, but when we encounter
160     /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create
161     /// the variable for `'a` in a fresh universe that extends ROOT.
162     universe: ty::UniverseIndex,
163
164     /// If this is 'static or an early-bound region, then this is
165     /// `Some(X)` where `X` is the name of the region.
166     external_name: Option<ty::Region<'tcx>>,
167 }
168
169 /// N.B., the variants in `Cause` are intentionally ordered. Lower
170 /// values are preferred when it comes to error messages. Do not
171 /// reorder willy nilly.
172 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
173 pub(crate) enum Cause {
174     /// point inserted because Local was live at the given Location
175     LiveVar(Local, Location),
176
177     /// point inserted because Local was dropped at the given Location
178     DropVar(Local, Location),
179 }
180
181 /// A "type test" corresponds to an outlives constraint between a type
182 /// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are
183 /// translated from the `Verify` region constraints in the ordinary
184 /// inference context.
185 ///
186 /// These sorts of constraints are handled differently than ordinary
187 /// constraints, at least at present. During type checking, the
188 /// `InferCtxt::process_registered_region_obligations` method will
189 /// attempt to convert a type test like `T: 'x` into an ordinary
190 /// outlives constraint when possible (for example, `&'a T: 'b` will
191 /// be converted into `'a: 'b` and registered as a `Constraint`).
192 ///
193 /// In some cases, however, there are outlives relationships that are
194 /// not converted into a region constraint, but rather into one of
195 /// these "type tests". The distinction is that a type test does not
196 /// influence the inference result, but instead just examines the
197 /// values that we ultimately inferred for each region variable and
198 /// checks that they meet certain extra criteria. If not, an error
199 /// can be issued.
200 ///
201 /// One reason for this is that these type tests typically boil down
202 /// to a check like `'a: 'x` where `'a` is a universally quantified
203 /// region -- and therefore not one whose value is really meant to be
204 /// *inferred*, precisely (this is not always the case: one can have a
205 /// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an
206 /// inference variable). Another reason is that these type tests can
207 /// involve *disjunction* -- that is, they can be satisfied in more
208 /// than one way.
209 ///
210 /// For more information about this translation, see
211 /// `InferCtxt::process_registered_region_obligations` and
212 /// `InferCtxt::type_must_outlive` in `rustc::infer::outlives`.
213 #[derive(Clone, Debug)]
214 pub struct TypeTest<'tcx> {
215     /// The type `T` that must outlive the region.
216     pub generic_kind: GenericKind<'tcx>,
217
218     /// The region `'x` that the type must outlive.
219     pub lower_bound: RegionVid,
220
221     /// Where did this constraint arise and why?
222     pub locations: Locations,
223
224     /// A test which, if met by the region `'x`, proves that this type
225     /// constraint is satisfied.
226     pub verify_bound: VerifyBound<'tcx>,
227 }
228
229 impl<'tcx> RegionInferenceContext<'tcx> {
230     /// Creates a new region inference context with a total of
231     /// `num_region_variables` valid inference variables; the first N
232     /// of those will be constant regions representing the free
233     /// regions defined in `universal_regions`.
234     ///
235     /// The `outlives_constraints` and `type_tests` are an initial set
236     /// of constraints produced by the MIR type check.
237     pub(crate) fn new(
238         var_infos: VarInfos,
239         universal_regions: Rc<UniversalRegions<'tcx>>,
240         placeholder_indices: Rc<PlaceholderIndices>,
241         universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
242         _body: &Body<'tcx>,
243         outlives_constraints: OutlivesConstraintSet,
244         member_constraints_in: MemberConstraintSet<'tcx, RegionVid>,
245         closure_bounds_mapping: FxHashMap<
246             Location,
247             FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>,
248         >,
249         type_tests: Vec<TypeTest<'tcx>>,
250         liveness_constraints: LivenessValues<RegionVid>,
251         elements: &Rc<RegionValueElements>,
252     ) -> Self {
253         // Create a RegionDefinition for each inference variable.
254         let definitions: IndexVec<_, _> = var_infos
255             .into_iter()
256             .map(|info| RegionDefinition::new(info.universe, info.origin))
257             .collect();
258
259         let constraints = Rc::new(outlives_constraints); // freeze constraints
260         let constraint_graph = Rc::new(constraints.graph(definitions.len()));
261         let fr_static = universal_regions.fr_static;
262         let constraint_sccs = Rc::new(constraints.compute_sccs(&constraint_graph, fr_static));
263
264         let mut scc_values =
265             RegionValues::new(elements, universal_regions.len(), &placeholder_indices);
266
267         for region in liveness_constraints.rows() {
268             let scc = constraint_sccs.scc(region);
269             scc_values.merge_liveness(scc, region, &liveness_constraints);
270         }
271
272         let scc_universes = Self::compute_scc_universes(&constraint_sccs, &definitions);
273
274         let scc_representatives = Self::compute_scc_representatives(&constraint_sccs, &definitions);
275
276         let member_constraints =
277             Rc::new(member_constraints_in.into_mapped(|r| constraint_sccs.scc(r)));
278
279         let mut result = Self {
280             definitions,
281             liveness_constraints,
282             constraints,
283             constraint_graph,
284             constraint_sccs,
285             rev_constraint_graph: None,
286             member_constraints,
287             member_constraints_applied: Vec::new(),
288             closure_bounds_mapping,
289             scc_universes,
290             scc_representatives,
291             scc_values,
292             type_tests,
293             universal_regions,
294             universal_region_relations,
295         };
296
297         result.init_free_and_bound_regions();
298
299         result
300     }
301
302     /// Each SCC is the combination of many region variables which
303     /// have been equated. Therefore, we can associate a universe with
304     /// each SCC which is minimum of all the universes of its
305     /// constituent regions -- this is because whatever value the SCC
306     /// takes on must be a value that each of the regions within the
307     /// SCC could have as well. This implies that the SCC must have
308     /// the minimum, or narrowest, universe.
309     fn compute_scc_universes(
310         constraints_scc: &Sccs<RegionVid, ConstraintSccIndex>,
311         definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
312     ) -> IndexVec<ConstraintSccIndex, ty::UniverseIndex> {
313         let num_sccs = constraints_scc.num_sccs();
314         let mut scc_universes = IndexVec::from_elem_n(ty::UniverseIndex::MAX, num_sccs);
315
316         for (region_vid, region_definition) in definitions.iter_enumerated() {
317             let scc = constraints_scc.scc(region_vid);
318             let scc_universe = &mut scc_universes[scc];
319             *scc_universe = ::std::cmp::min(*scc_universe, region_definition.universe);
320         }
321
322         debug!("compute_scc_universes: scc_universe = {:#?}", scc_universes);
323
324         scc_universes
325     }
326
327     /// For each SCC, we compute a unique `RegionVid` (in fact, the
328     /// minimal one that belongs to the SCC). See
329     /// `scc_representatives` field of `RegionInferenceContext` for
330     /// more details.
331     fn compute_scc_representatives(
332         constraints_scc: &Sccs<RegionVid, ConstraintSccIndex>,
333         definitions: &IndexVec<RegionVid, RegionDefinition<'tcx>>,
334     ) -> IndexVec<ConstraintSccIndex, ty::RegionVid> {
335         let num_sccs = constraints_scc.num_sccs();
336         let next_region_vid = definitions.next_index();
337         let mut scc_representatives = IndexVec::from_elem_n(next_region_vid, num_sccs);
338
339         for region_vid in definitions.indices() {
340             let scc = constraints_scc.scc(region_vid);
341             let prev_min = scc_representatives[scc];
342             scc_representatives[scc] = region_vid.min(prev_min);
343         }
344
345         scc_representatives
346     }
347
348     /// Initializes the region variables for each universally
349     /// quantified region (lifetime parameter). The first N variables
350     /// always correspond to the regions appearing in the function
351     /// signature (both named and anonymous) and where-clauses. This
352     /// function iterates over those regions and initializes them with
353     /// minimum values.
354     ///
355     /// For example:
356     ///
357     ///     fn foo<'a, 'b>(..) where 'a: 'b
358     ///
359     /// would initialize two variables like so:
360     ///
361     ///     R0 = { CFG, R0 } // 'a
362     ///     R1 = { CFG, R0, R1 } // 'b
363     ///
364     /// Here, R0 represents `'a`, and it contains (a) the entire CFG
365     /// and (b) any universally quantified regions that it outlives,
366     /// which in this case is just itself. R1 (`'b`) in contrast also
367     /// outlives `'a` and hence contains R0 and R1.
368     fn init_free_and_bound_regions(&mut self) {
369         // Update the names (if any)
370         for (external_name, variable) in self.universal_regions.named_universal_regions() {
371             debug!(
372                 "init_universal_regions: region {:?} has external name {:?}",
373                 variable, external_name
374             );
375             self.definitions[variable].external_name = Some(external_name);
376         }
377
378         for variable in self.definitions.indices() {
379             let scc = self.constraint_sccs.scc(variable);
380
381             match self.definitions[variable].origin {
382                 NLLRegionVariableOrigin::FreeRegion => {
383                     // For each free, universally quantified region X:
384
385                     // Add all nodes in the CFG to liveness constraints
386                     self.liveness_constraints.add_all_points(variable);
387                     self.scc_values.add_all_points(scc);
388
389                     // Add `end(X)` into the set for X.
390                     self.scc_values.add_element(scc, variable);
391                 }
392
393                 NLLRegionVariableOrigin::Placeholder(placeholder) => {
394                     // Each placeholder region is only visible from
395                     // its universe `ui` and its extensions. So we
396                     // can't just add it into `scc` unless the
397                     // universe of the scc can name this region.
398                     let scc_universe = self.scc_universes[scc];
399                     if scc_universe.can_name(placeholder.universe) {
400                         self.scc_values.add_element(scc, placeholder);
401                     } else {
402                         debug!(
403                             "init_free_and_bound_regions: placeholder {:?} is \
404                              not compatible with universe {:?} of its SCC {:?}",
405                             placeholder, scc_universe, scc,
406                         );
407                         self.add_incompatible_universe(scc);
408                     }
409                 }
410
411                 NLLRegionVariableOrigin::Existential { .. } => {
412                     // For existential, regions, nothing to do.
413                 }
414             }
415         }
416     }
417
418     /// Returns an iterator over all the region indices.
419     pub fn regions(&self) -> impl Iterator<Item = RegionVid> {
420         self.definitions.indices()
421     }
422
423     /// Given a universal region in scope on the MIR, returns the
424     /// corresponding index.
425     ///
426     /// (Panics if `r` is not a registered universal region.)
427     pub fn to_region_vid(&self, r: ty::Region<'tcx>) -> RegionVid {
428         self.universal_regions.to_region_vid(r)
429     }
430
431     /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
432     crate fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut DiagnosticBuilder<'_>) {
433         self.universal_regions.annotate(tcx, err)
434     }
435
436     /// Returns `true` if the region `r` contains the point `p`.
437     ///
438     /// Panics if called before `solve()` executes,
439     crate fn region_contains(&self, r: impl ToRegionVid, p: impl ToElementIndex) -> bool {
440         let scc = self.constraint_sccs.scc(r.to_region_vid());
441         self.scc_values.contains(scc, p)
442     }
443
444     /// Returns access to the value of `r` for debugging purposes.
445     crate fn region_value_str(&self, r: RegionVid) -> String {
446         let scc = self.constraint_sccs.scc(r.to_region_vid());
447         self.scc_values.region_value_str(scc)
448     }
449
450     /// Returns access to the value of `r` for debugging purposes.
451     crate fn region_universe(&self, r: RegionVid) -> ty::UniverseIndex {
452         let scc = self.constraint_sccs.scc(r.to_region_vid());
453         self.scc_universes[scc]
454     }
455
456     /// Once region solving has completed, this function will return
457     /// the member constraints that were applied to the value of a given
458     /// region `r`. See `AppliedMemberConstraint`.
459     fn applied_member_constraints(&self, r: impl ToRegionVid) -> &[AppliedMemberConstraint] {
460         let scc = self.constraint_sccs.scc(r.to_region_vid());
461         binary_search_util::binary_search_slice(
462             &self.member_constraints_applied,
463             |applied| applied.member_region_scc,
464             &scc,
465         )
466     }
467
468     /// Performs region inference and report errors if we see any
469     /// unsatisfiable constraints. If this is a closure, returns the
470     /// region requirements to propagate to our creator, if any.
471     pub(super) fn solve(
472         &mut self,
473         infcx: &InferCtxt<'_, 'tcx>,
474         body: &Body<'tcx>,
475         local_names: &IndexVec<Local, Option<Symbol>>,
476         upvars: &[Upvar],
477         mir_def_id: DefId,
478         errors_buffer: &mut Vec<Diagnostic>,
479     ) -> Option<ClosureRegionRequirements<'tcx>> {
480         self.propagate_constraints(body);
481
482         // If this is a closure, we can propagate unsatisfied
483         // `outlives_requirements` to our creator, so create a vector
484         // to store those. Otherwise, we'll pass in `None` to the
485         // functions below, which will trigger them to report errors
486         // eagerly.
487         let mut outlives_requirements =
488             if infcx.tcx.is_closure(mir_def_id) { Some(vec![]) } else { None };
489
490         self.check_type_tests(
491             infcx,
492             body,
493             mir_def_id,
494             outlives_requirements.as_mut(),
495             errors_buffer,
496         );
497
498         // If we produce any errors, we keep track of the names of all regions, so that we can use
499         // the same error names in any suggestions we produce. Note that we need names to be unique
500         // across different errors for the same MIR def so that we can make suggestions that fix
501         // multiple problems.
502         let mut region_naming = RegionErrorNamingCtx::new();
503
504         self.check_universal_regions(
505             infcx,
506             body,
507             local_names,
508             upvars,
509             mir_def_id,
510             outlives_requirements.as_mut(),
511             errors_buffer,
512             &mut region_naming,
513         );
514
515         self.check_member_constraints(infcx, mir_def_id, errors_buffer);
516
517         let outlives_requirements = outlives_requirements.unwrap_or(vec![]);
518
519         if outlives_requirements.is_empty() {
520             None
521         } else {
522             let num_external_vids = self.universal_regions.num_global_and_external_regions();
523             Some(ClosureRegionRequirements { num_external_vids, outlives_requirements })
524         }
525     }
526
527     /// Propagate the region constraints: this will grow the values
528     /// for each region variable until all the constraints are
529     /// satisfied. Note that some values may grow **too** large to be
530     /// feasible, but we check this later.
531     fn propagate_constraints(&mut self, _body: &Body<'tcx>) {
532         debug!("propagate_constraints()");
533
534         debug!("propagate_constraints: constraints={:#?}", {
535             let mut constraints: Vec<_> = self.constraints.outlives().iter().collect();
536             constraints.sort();
537             constraints
538                 .into_iter()
539                 .map(|c| (c, self.constraint_sccs.scc(c.sup), self.constraint_sccs.scc(c.sub)))
540                 .collect::<Vec<_>>()
541         });
542
543         // To propagate constraints, we walk the DAG induced by the
544         // SCC. For each SCC, we visit its successors and compute
545         // their values, then we union all those values to get our
546         // own.
547         let visited = &mut BitSet::new_empty(self.constraint_sccs.num_sccs());
548         for scc_index in self.constraint_sccs.all_sccs() {
549             self.propagate_constraint_sccs_if_new(scc_index, visited);
550         }
551
552         // Sort the applied member constraints so we can binary search
553         // through them later.
554         self.member_constraints_applied.sort_by_key(|applied| applied.member_region_scc);
555     }
556
557     /// Computes the value of the SCC `scc_a` if it has not already
558     /// been computed. The `visited` parameter is a bitset
559     #[inline]
560     fn propagate_constraint_sccs_if_new(
561         &mut self,
562         scc_a: ConstraintSccIndex,
563         visited: &mut BitSet<ConstraintSccIndex>,
564     ) {
565         if visited.insert(scc_a) {
566             self.propagate_constraint_sccs_new(scc_a, visited);
567         }
568     }
569
570     /// Computes the value of the SCC `scc_a`, which has not yet been
571     /// computed. This works by first computing all successors of the
572     /// SCC (if they haven't been computed already) and then unioning
573     /// together their elements.
574     fn propagate_constraint_sccs_new(
575         &mut self,
576         scc_a: ConstraintSccIndex,
577         visited: &mut BitSet<ConstraintSccIndex>,
578     ) {
579         let constraint_sccs = self.constraint_sccs.clone();
580
581         // Walk each SCC `B` such that `A: B`...
582         for &scc_b in constraint_sccs.successors(scc_a) {
583             debug!("propagate_constraint_sccs: scc_a = {:?} scc_b = {:?}", scc_a, scc_b);
584
585             // ...compute the value of `B`...
586             self.propagate_constraint_sccs_if_new(scc_b, visited);
587
588             // ...and add elements from `B` into `A`. One complication
589             // arises because of universes: If `B` contains something
590             // that `A` cannot name, then `A` can only contain `B` if
591             // it outlives static.
592             if self.universe_compatible(scc_b, scc_a) {
593                 // `A` can name everything that is in `B`, so just
594                 // merge the bits.
595                 self.scc_values.add_region(scc_a, scc_b);
596             } else {
597                 self.add_incompatible_universe(scc_a);
598             }
599         }
600
601         // Now take member constraints into account.
602         let member_constraints = self.member_constraints.clone();
603         for m_c_i in member_constraints.indices(scc_a) {
604             self.apply_member_constraint(
605                 scc_a,
606                 m_c_i,
607                 member_constraints.choice_regions(m_c_i),
608             );
609         }
610
611         debug!(
612             "propagate_constraint_sccs: scc_a = {:?} has value {:?}",
613             scc_a,
614             self.scc_values.region_value_str(scc_a),
615         );
616     }
617
618     /// Invoked for each `R0 member of [R1..Rn]` constraint.
619     ///
620     /// `scc` is the SCC containing R0, and `choice_regions` are the
621     /// `R1..Rn` regions -- they are always known to be universal
622     /// regions (and if that's not true, we just don't attempt to
623     /// enforce the constraint).
624     ///
625     /// The current value of `scc` at the time the method is invoked
626     /// is considered a *lower bound*.  If possible, we will modify
627     /// the constraint to set it equal to one of the option regions.
628     /// If we make any changes, returns true, else false.
629     fn apply_member_constraint(
630         &mut self,
631         scc: ConstraintSccIndex,
632         member_constraint_index: NllMemberConstraintIndex,
633         choice_regions: &[ty::RegionVid],
634     ) -> bool {
635         debug!("apply_member_constraint(scc={:?}, choice_regions={:#?})", scc, choice_regions,);
636
637         if let Some(uh_oh) =
638             choice_regions.iter().find(|&&r| !self.universal_regions.is_universal_region(r))
639         {
640             // FIXME(#61773): This case can only occur with
641             // `impl_trait_in_bindings`, I believe, and we are just
642             // opting not to handle it for now. See #61773 for
643             // details.
644             bug!(
645                 "member constraint for `{:?}` has an option region `{:?}` \
646                  that is not a universal region",
647                 self.member_constraints[member_constraint_index].opaque_type_def_id,
648                 uh_oh,
649             );
650         }
651
652         // Create a mutable vector of the options. We'll try to winnow
653         // them down.
654         let mut choice_regions: Vec<ty::RegionVid> = choice_regions.to_vec();
655
656         // The 'member region' in a member constraint is part of the
657         // hidden type, which must be in the root universe. Therefore,
658         // it cannot have any placeholders in its value.
659         assert!(self.scc_universes[scc] == ty::UniverseIndex::ROOT);
660         debug_assert!(
661             self.scc_values.placeholders_contained_in(scc).next().is_none(),
662             "scc {:?} in a member constraint has placeholder value: {:?}",
663             scc,
664             self.scc_values.region_value_str(scc),
665         );
666
667         // The existing value for `scc` is a lower-bound. This will
668         // consist of some set `{P} + {LB}` of points `{P}` and
669         // lower-bound free regions `{LB}`. As each choice region `O`
670         // is a free region, it will outlive the points. But we can
671         // only consider the option `O` if `O: LB`.
672         choice_regions.retain(|&o_r| {
673             self.scc_values
674                 .universal_regions_outlived_by(scc)
675                 .all(|lb| self.universal_region_relations.outlives(o_r, lb))
676         });
677         debug!("apply_member_constraint: after lb, choice_regions={:?}", choice_regions);
678
679         // Now find all the *upper bounds* -- that is, each UB is a
680         // free region that must outlive the member region `R0` (`UB:
681         // R0`). Therefore, we need only keep an option `O` if `UB: O`
682         // for all UB.
683         if choice_regions.len() > 1 {
684             let universal_region_relations = self.universal_region_relations.clone();
685             let rev_constraint_graph = self.rev_constraint_graph();
686             for ub in self.upper_bounds(scc, &rev_constraint_graph) {
687                 debug!("apply_member_constraint: ub={:?}", ub);
688                 choice_regions.retain(|&o_r| universal_region_relations.outlives(ub, o_r));
689             }
690             debug!("apply_member_constraint: after ub, choice_regions={:?}", choice_regions);
691         }
692
693         // If we ruled everything out, we're done.
694         if choice_regions.is_empty() {
695             return false;
696         }
697
698         // Otherwise, we need to find the minimum remaining choice, if
699         // any, and take that.
700         debug!("apply_member_constraint: choice_regions remaining are {:#?}", choice_regions);
701         let min = |r1: ty::RegionVid, r2: ty::RegionVid| -> Option<ty::RegionVid> {
702             let r1_outlives_r2 = self.universal_region_relations.outlives(r1, r2);
703             let r2_outlives_r1 = self.universal_region_relations.outlives(r2, r1);
704             if r1_outlives_r2 && r2_outlives_r1 {
705                 Some(r1.min(r2))
706             } else if r1_outlives_r2 {
707                 Some(r2)
708             } else if r2_outlives_r1 {
709                 Some(r1)
710             } else {
711                 None
712             }
713         };
714         let mut min_choice = choice_regions[0];
715         for &other_option in &choice_regions[1..] {
716             debug!(
717                 "apply_member_constraint: min_choice={:?} other_option={:?}",
718                 min_choice, other_option,
719             );
720             match min(min_choice, other_option) {
721                 Some(m) => min_choice = m,
722                 None => {
723                     debug!(
724                         "apply_member_constraint: {:?} and {:?} are incomparable; no min choice",
725                         min_choice, other_option,
726                     );
727                     return false;
728                 }
729             }
730         }
731
732         let min_choice_scc = self.constraint_sccs.scc(min_choice);
733         debug!(
734             "apply_member_constraint: min_choice={:?} best_choice_scc={:?}",
735             min_choice,
736             min_choice_scc,
737         );
738         if self.scc_values.add_region(scc, min_choice_scc) {
739             self.member_constraints_applied.push(AppliedMemberConstraint {
740                 member_region_scc: scc,
741                 min_choice,
742                 member_constraint_index,
743             });
744
745             true
746         } else {
747             false
748         }
749     }
750
751     /// Compute and return the reverse SCC-based constraint graph (lazilly).
752     fn upper_bounds(
753         &'a mut self,
754         scc0: ConstraintSccIndex,
755         rev_constraint_graph: &'a VecGraph<ConstraintSccIndex>,
756     ) -> impl Iterator<Item = RegionVid> + 'a {
757         let scc_values = &self.scc_values;
758         let mut duplicates = FxHashSet::default();
759         rev_constraint_graph
760             .depth_first_search(scc0)
761             .skip(1)
762             .flat_map(move |scc1| scc_values.universal_regions_outlived_by(scc1))
763             .filter(move |&r| duplicates.insert(r))
764     }
765
766     /// Compute and return the reverse SCC-based constraint graph (lazilly).
767     fn rev_constraint_graph(
768         &mut self,
769     ) -> Rc<VecGraph<ConstraintSccIndex>> {
770         if let Some(g) = &self.rev_constraint_graph {
771             return g.clone();
772         }
773
774         let rev_graph = Rc::new(self.constraint_sccs.reverse());
775         self.rev_constraint_graph = Some(rev_graph.clone());
776         rev_graph
777     }
778
779     /// Returns `true` if all the elements in the value of `scc_b` are nameable
780     /// in `scc_a`. Used during constraint propagation, and only once
781     /// the value of `scc_b` has been computed.
782     fn universe_compatible(&self, scc_b: ConstraintSccIndex, scc_a: ConstraintSccIndex) -> bool {
783         let universe_a = self.scc_universes[scc_a];
784
785         // Quick check: if scc_b's declared universe is a subset of
786         // scc_a's declared univese (typically, both are ROOT), then
787         // it cannot contain any problematic universe elements.
788         if universe_a.can_name(self.scc_universes[scc_b]) {
789             return true;
790         }
791
792         // Otherwise, we have to iterate over the universe elements in
793         // B's value, and check whether all of them are nameable
794         // from universe_a
795         self.scc_values.placeholders_contained_in(scc_b).all(|p| universe_a.can_name(p.universe))
796     }
797
798     /// Extend `scc` so that it can outlive some placeholder region
799     /// from a universe it can't name; at present, the only way for
800     /// this to be true is if `scc` outlives `'static`. This is
801     /// actually stricter than necessary: ideally, we'd support bounds
802     /// like `for<'a: 'b`>` that might then allow us to approximate
803     /// `'a` with `'b` and not `'static`. But it will have to do for
804     /// now.
805     fn add_incompatible_universe(&mut self, scc: ConstraintSccIndex) {
806         debug!("add_incompatible_universe(scc={:?})", scc);
807
808         let fr_static = self.universal_regions.fr_static;
809         self.scc_values.add_all_points(scc);
810         self.scc_values.add_element(scc, fr_static);
811     }
812
813     /// Once regions have been propagated, this method is used to see
814     /// whether the "type tests" produced by typeck were satisfied;
815     /// type tests encode type-outlives relationships like `T:
816     /// 'a`. See `TypeTest` for more details.
817     fn check_type_tests(
818         &self,
819         infcx: &InferCtxt<'_, 'tcx>,
820         body: &Body<'tcx>,
821         mir_def_id: DefId,
822         mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
823         errors_buffer: &mut Vec<Diagnostic>,
824     ) {
825         let tcx = infcx.tcx;
826
827         // Sometimes we register equivalent type-tests that would
828         // result in basically the exact same error being reported to
829         // the user. Avoid that.
830         let mut deduplicate_errors = FxHashSet::default();
831
832         for type_test in &self.type_tests {
833             debug!("check_type_test: {:?}", type_test);
834
835             let generic_ty = type_test.generic_kind.to_ty(tcx);
836             if self.eval_verify_bound(
837                 tcx,
838                 body,
839                 generic_ty,
840                 type_test.lower_bound,
841                 &type_test.verify_bound,
842             ) {
843                 continue;
844             }
845
846             if let Some(propagated_outlives_requirements) = &mut propagated_outlives_requirements {
847                 if self.try_promote_type_test(
848                     infcx,
849                     body,
850                     type_test,
851                     propagated_outlives_requirements,
852                 ) {
853                     continue;
854                 }
855             }
856
857             // Type-test failed. Report the error.
858
859             // Try to convert the lower-bound region into something named we can print for the user.
860             let lower_bound_region = self.to_error_region(type_test.lower_bound);
861
862             // Skip duplicate-ish errors.
863             let type_test_span = type_test.locations.span(body);
864             let erased_generic_kind = tcx.erase_regions(&type_test.generic_kind);
865             if !deduplicate_errors.insert((
866                 erased_generic_kind,
867                 lower_bound_region,
868                 type_test.locations,
869             )) {
870                 continue;
871             } else {
872                 debug!(
873                     "check_type_test: reporting error for erased_generic_kind={:?}, \
874                      lower_bound_region={:?}, \
875                      type_test.locations={:?}",
876                     erased_generic_kind, lower_bound_region, type_test.locations,
877                 );
878             }
879
880             if let Some(lower_bound_region) = lower_bound_region {
881                 let region_scope_tree = &tcx.region_scope_tree(mir_def_id);
882                 infcx
883                     .construct_generic_bound_failure(
884                         region_scope_tree,
885                         type_test_span,
886                         None,
887                         type_test.generic_kind,
888                         lower_bound_region,
889                     )
890                     .buffer(errors_buffer);
891             } else {
892                 // FIXME. We should handle this case better. It
893                 // indicates that we have e.g., some region variable
894                 // whose value is like `'a+'b` where `'a` and `'b` are
895                 // distinct unrelated univesal regions that are not
896                 // known to outlive one another. It'd be nice to have
897                 // some examples where this arises to decide how best
898                 // to report it; we could probably handle it by
899                 // iterating over the universal regions and reporting
900                 // an error that multiple bounds are required.
901                 tcx.sess
902                     .struct_span_err(
903                         type_test_span,
904                         &format!("`{}` does not live long enough", type_test.generic_kind,),
905                     )
906                     .buffer(errors_buffer);
907             }
908         }
909     }
910
911     /// Converts a region inference variable into a `ty::Region` that
912     /// we can use for error reporting. If `r` is universally bound,
913     /// then we use the name that we have on record for it. If `r` is
914     /// existentially bound, then we check its inferred value and try
915     /// to find a good name from that. Returns `None` if we can't find
916     /// one (e.g., this is just some random part of the CFG).
917     pub fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
918         self.to_error_region_vid(r).and_then(|r| self.definitions[r].external_name)
919     }
920
921     /// Returns the [RegionVid] corresponding to the region returned by
922     /// `to_error_region`.
923     pub fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
924         if self.universal_regions.is_universal_region(r) {
925             Some(r)
926         } else {
927             let r_scc = self.constraint_sccs.scc(r);
928             let upper_bound = self.universal_upper_bound(r);
929             if self.scc_values.contains(r_scc, upper_bound) {
930                 self.to_error_region_vid(upper_bound)
931             } else {
932                 None
933             }
934         }
935     }
936
937     /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot
938     /// prove to be satisfied. If this is a closure, we will attempt to
939     /// "promote" this type-test into our `ClosureRegionRequirements` and
940     /// hence pass it up the creator. To do this, we have to phrase the
941     /// type-test in terms of external free regions, as local free
942     /// regions are not nameable by the closure's creator.
943     ///
944     /// Promotion works as follows: we first check that the type `T`
945     /// contains only regions that the creator knows about. If this is
946     /// true, then -- as a consequence -- we know that all regions in
947     /// the type `T` are free regions that outlive the closure body. If
948     /// false, then promotion fails.
949     ///
950     /// Once we've promoted T, we have to "promote" `'X` to some region
951     /// that is "external" to the closure. Generally speaking, a region
952     /// may be the union of some points in the closure body as well as
953     /// various free lifetimes. We can ignore the points in the closure
954     /// body: if the type T can be expressed in terms of external regions,
955     /// we know it outlives the points in the closure body. That
956     /// just leaves the free regions.
957     ///
958     /// The idea then is to lower the `T: 'X` constraint into multiple
959     /// bounds -- e.g., if `'X` is the union of two free lifetimes,
960     /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.
961     fn try_promote_type_test(
962         &self,
963         infcx: &InferCtxt<'_, 'tcx>,
964         body: &Body<'tcx>,
965         type_test: &TypeTest<'tcx>,
966         propagated_outlives_requirements: &mut Vec<ClosureOutlivesRequirement<'tcx>>,
967     ) -> bool {
968         let tcx = infcx.tcx;
969
970         let TypeTest { generic_kind, lower_bound, locations, verify_bound: _ } = type_test;
971
972         let generic_ty = generic_kind.to_ty(tcx);
973         let subject = match self.try_promote_type_test_subject(infcx, generic_ty) {
974             Some(s) => s,
975             None => return false,
976         };
977
978         // For each region outlived by lower_bound find a non-local,
979         // universal region (it may be the same region) and add it to
980         // `ClosureOutlivesRequirement`.
981         let r_scc = self.constraint_sccs.scc(*lower_bound);
982         for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
983             // Check whether we can already prove that the "subject" outlives `ur`.
984             // If so, we don't have to propagate this requirement to our caller.
985             //
986             // To continue the example from the function, if we are trying to promote
987             // a requirement that `T: 'X`, and we know that `'X = '1 + '2` (i.e., the union
988             // `'1` and `'2`), then in this loop `ur` will be `'1` (and `'2`). So here
989             // we check whether `T: '1` is something we *can* prove. If so, no need
990             // to propagate that requirement.
991             //
992             // This is needed because -- particularly in the case
993             // where `ur` is a local bound -- we are sometimes in a
994             // position to prove things that our caller cannot.  See
995             // #53570 for an example.
996             if self.eval_verify_bound(tcx, body, generic_ty, ur, &type_test.verify_bound) {
997                 continue;
998             }
999
1000             debug!("try_promote_type_test: ur={:?}", ur);
1001
1002             let non_local_ub = self.universal_region_relations.non_local_upper_bounds(&ur);
1003             debug!("try_promote_type_test: non_local_ub={:?}", non_local_ub);
1004
1005             // This is slightly too conservative. To show T: '1, given `'2: '1`
1006             // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to
1007             // avoid potential non-determinism we approximate this by requiring
1008             // T: '1 and T: '2.
1009             for &upper_bound in non_local_ub {
1010                 debug_assert!(self.universal_regions.is_universal_region(upper_bound));
1011                 debug_assert!(!self.universal_regions.is_local_free_region(upper_bound));
1012
1013                 let requirement = ClosureOutlivesRequirement {
1014                     subject,
1015                     outlived_free_region: upper_bound,
1016                     blame_span: locations.span(body),
1017                     category: ConstraintCategory::Boring,
1018                 };
1019                 debug!("try_promote_type_test: pushing {:#?}", requirement);
1020                 propagated_outlives_requirements.push(requirement);
1021             }
1022         }
1023         true
1024     }
1025
1026     /// When we promote a type test `T: 'r`, we have to convert the
1027     /// type `T` into something we can store in a query result (so
1028     /// something allocated for `'tcx`). This is problematic if `ty`
1029     /// contains regions. During the course of NLL region checking, we
1030     /// will have replaced all of those regions with fresh inference
1031     /// variables. To create a test subject, we want to replace those
1032     /// inference variables with some region from the closure
1033     /// signature -- this is not always possible, so this is a
1034     /// fallible process. Presuming we do find a suitable region, we
1035     /// will represent it with a `ReClosureBound`, which is a
1036     /// `RegionKind` variant that can be allocated in the gcx.
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         debug!("try_promote_type_test_subject(ty = {:?})", ty);
1045
1046         let ty = tcx.fold_regions(&ty, &mut false, |r, _depth| {
1047             let region_vid = self.to_region_vid(r);
1048
1049             // The challenge if this. We have some region variable `r`
1050             // whose value is a set of CFG points and universal
1051             // regions. We want to find if that set is *equivalent* to
1052             // any of the named regions found in the closure.
1053             //
1054             // To do so, we compute the
1055             // `non_local_universal_upper_bound`. This will be a
1056             // non-local, universal region that is greater than `r`.
1057             // However, it might not be *contained* within `r`, so
1058             // then we further check whether this bound is contained
1059             // in `r`. If so, we can say that `r` is equivalent to the
1060             // bound.
1061             //
1062             // Let's work through a few examples. For these, imagine
1063             // that we have 3 non-local regions (I'll denote them as
1064             // `'static`, `'a`, and `'b`, though of course in the code
1065             // they would be represented with indices) where:
1066             //
1067             // - `'static: 'a`
1068             // - `'static: 'b`
1069             //
1070             // First, let's assume that `r` is some existential
1071             // variable with an inferred value `{'a, 'static}` (plus
1072             // some CFG nodes). In this case, the non-local upper
1073             // bound is `'static`, since that outlives `'a`. `'static`
1074             // is also a member of `r` and hence we consider `r`
1075             // equivalent to `'static` (and replace it with
1076             // `'static`).
1077             //
1078             // Now let's consider the inferred value `{'a, 'b}`. This
1079             // means `r` is effectively `'a | 'b`. I'm not sure if
1080             // this can come about, actually, but assuming it did, we
1081             // would get a non-local upper bound of `'static`. Since
1082             // `'static` is not contained in `r`, we would fail to
1083             // find an equivalent.
1084             let upper_bound = self.non_local_universal_upper_bound(region_vid);
1085             if self.region_contains(region_vid, upper_bound) {
1086                 tcx.mk_region(ty::ReClosureBound(upper_bound))
1087             } else {
1088                 // In the case of a failure, use a `ReVar`
1089                 // result. This will cause the `lift` later on to
1090                 // fail.
1091                 r
1092             }
1093         });
1094         debug!("try_promote_type_test_subject: folded ty = {:?}", ty);
1095
1096         // `has_local_value` will only be true if we failed to promote some region.
1097         if ty.has_local_value() {
1098             return None;
1099         }
1100
1101         Some(ClosureOutlivesSubject::Ty(ty))
1102     }
1103
1104     /// Given some universal or existential region `r`, finds a
1105     /// non-local, universal region `r+` that outlives `r` at entry to (and
1106     /// exit from) the closure. In the worst case, this will be
1107     /// `'static`.
1108     ///
1109     /// This is used for two purposes. First, if we are propagated
1110     /// some requirement `T: r`, we can use this method to enlarge `r`
1111     /// to something we can encode for our creator (which only knows
1112     /// about non-local, universal regions). It is also used when
1113     /// encoding `T` as part of `try_promote_type_test_subject` (see
1114     /// that fn for details).
1115     ///
1116     /// This is based on the result `'y` of `universal_upper_bound`,
1117     /// except that it converts further takes the non-local upper
1118     /// bound of `'y`, so that the final result is non-local.
1119     fn non_local_universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1120         debug!("non_local_universal_upper_bound(r={:?}={})", r, self.region_value_str(r));
1121
1122         let lub = self.universal_upper_bound(r);
1123
1124         // Grow further to get smallest universal region known to
1125         // creator.
1126         let non_local_lub = self.universal_region_relations.non_local_upper_bound(lub);
1127
1128         debug!("non_local_universal_upper_bound: non_local_lub={:?}", non_local_lub);
1129
1130         non_local_lub
1131     }
1132
1133     /// Returns a universally quantified region that outlives the
1134     /// value of `r` (`r` may be existentially or universally
1135     /// quantified).
1136     ///
1137     /// Since `r` is (potentially) an existential region, it has some
1138     /// value which may include (a) any number of points in the CFG
1139     /// and (b) any number of `end('x)` elements of universally
1140     /// quantified regions. To convert this into a single universal
1141     /// region we do as follows:
1142     ///
1143     /// - Ignore the CFG points in `'r`. All universally quantified regions
1144     ///   include the CFG anyhow.
1145     /// - For each `end('x)` element in `'r`, compute the mutual LUB, yielding
1146     ///   a result `'y`.
1147     fn universal_upper_bound(&self, r: RegionVid) -> RegionVid {
1148         debug!("universal_upper_bound(r={:?}={})", r, self.region_value_str(r));
1149
1150         // Find the smallest universal region that contains all other
1151         // universal regions within `region`.
1152         let mut lub = self.universal_regions.fr_fn_body;
1153         let r_scc = self.constraint_sccs.scc(r);
1154         for ur in self.scc_values.universal_regions_outlived_by(r_scc) {
1155             lub = self.universal_region_relations.postdom_upper_bound(lub, ur);
1156         }
1157
1158         debug!("universal_upper_bound: r={:?} lub={:?}", r, lub);
1159
1160         lub
1161     }
1162
1163     /// Tests if `test` is true when applied to `lower_bound` at
1164     /// `point`.
1165     fn eval_verify_bound(
1166         &self,
1167         tcx: TyCtxt<'tcx>,
1168         body: &Body<'tcx>,
1169         generic_ty: Ty<'tcx>,
1170         lower_bound: RegionVid,
1171         verify_bound: &VerifyBound<'tcx>,
1172     ) -> bool {
1173         debug!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound, verify_bound);
1174
1175         match verify_bound {
1176             VerifyBound::IfEq(test_ty, verify_bound1) => {
1177                 self.eval_if_eq(tcx, body, generic_ty, lower_bound, test_ty, verify_bound1)
1178             }
1179
1180             VerifyBound::OutlivedBy(r) => {
1181                 let r_vid = self.to_region_vid(r);
1182                 self.eval_outlives(r_vid, lower_bound)
1183             }
1184
1185             VerifyBound::AnyBound(verify_bounds) => verify_bounds.iter().any(|verify_bound| {
1186                 self.eval_verify_bound(tcx, body, generic_ty, lower_bound, verify_bound)
1187             }),
1188
1189             VerifyBound::AllBounds(verify_bounds) => verify_bounds.iter().all(|verify_bound| {
1190                 self.eval_verify_bound(tcx, body, generic_ty, lower_bound, verify_bound)
1191             }),
1192         }
1193     }
1194
1195     fn eval_if_eq(
1196         &self,
1197         tcx: TyCtxt<'tcx>,
1198         body: &Body<'tcx>,
1199         generic_ty: Ty<'tcx>,
1200         lower_bound: RegionVid,
1201         test_ty: Ty<'tcx>,
1202         verify_bound: &VerifyBound<'tcx>,
1203     ) -> bool {
1204         let generic_ty_normalized = self.normalize_to_scc_representatives(tcx, generic_ty);
1205         let test_ty_normalized = self.normalize_to_scc_representatives(tcx, test_ty);
1206         if generic_ty_normalized == test_ty_normalized {
1207             self.eval_verify_bound(tcx, body, generic_ty, lower_bound, verify_bound)
1208         } else {
1209             false
1210         }
1211     }
1212
1213     /// This is a conservative normalization procedure. It takes every
1214     /// free region in `value` and replaces it with the
1215     /// "representative" of its SCC (see `scc_representatives` field).
1216     /// We are guaranteed that if two values normalize to the same
1217     /// thing, then they are equal; this is a conservative check in
1218     /// that they could still be equal even if they normalize to
1219     /// different results. (For example, there might be two regions
1220     /// with the same value that are not in the same SCC).
1221     ///
1222     /// N.B., this is not an ideal approach and I would like to revisit
1223     /// it. However, it works pretty well in practice. In particular,
1224     /// this is needed to deal with projection outlives bounds like
1225     ///
1226     ///     <T as Foo<'0>>::Item: '1
1227     ///
1228     /// In particular, this routine winds up being important when
1229     /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the
1230     /// environment. In this case, if we can show that `'0 == 'a`,
1231     /// and that `'b: '1`, then we know that the clause is
1232     /// satisfied. In such cases, particularly due to limitations of
1233     /// the trait solver =), we usually wind up with a where-clause like
1234     /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as
1235     /// a constraint, and thus ensures that they are in the same SCC.
1236     ///
1237     /// So why can't we do a more correct routine? Well, we could
1238     /// *almost* use the `relate_tys` code, but the way it is
1239     /// currently setup it creates inference variables to deal with
1240     /// higher-ranked things and so forth, and right now the inference
1241     /// context is not permitted to make more inference variables. So
1242     /// we use this kind of hacky solution.
1243     fn normalize_to_scc_representatives<T>(&self, tcx: TyCtxt<'tcx>, value: T) -> T
1244     where
1245         T: TypeFoldable<'tcx>,
1246     {
1247         tcx.fold_regions(&value, &mut false, |r, _db| {
1248             let vid = self.to_region_vid(r);
1249             let scc = self.constraint_sccs.scc(vid);
1250             let repr = self.scc_representatives[scc];
1251             tcx.mk_region(ty::ReVar(repr))
1252         })
1253     }
1254
1255     // Evaluate whether `sup_region == sub_region`.
1256     fn eval_equal(&self, r1: RegionVid, r2: RegionVid) -> bool {
1257         self.eval_outlives(r1, r2) && self.eval_outlives(r2, r1)
1258     }
1259
1260     // Evaluate whether `sup_region: sub_region`.
1261     fn eval_outlives(&self, sup_region: RegionVid, sub_region: RegionVid) -> bool {
1262         debug!("eval_outlives({:?}: {:?})", sup_region, sub_region);
1263
1264         debug!(
1265             "eval_outlives: sup_region's value = {:?} universal={:?}",
1266             self.region_value_str(sup_region),
1267             self.universal_regions.is_universal_region(sup_region),
1268         );
1269         debug!(
1270             "eval_outlives: sub_region's value = {:?} universal={:?}",
1271             self.region_value_str(sub_region),
1272             self.universal_regions.is_universal_region(sub_region),
1273         );
1274
1275         let sub_region_scc = self.constraint_sccs.scc(sub_region);
1276         let sup_region_scc = self.constraint_sccs.scc(sup_region);
1277
1278         // Both the `sub_region` and `sup_region` consist of the union
1279         // of some number of universal regions (along with the union
1280         // of various points in the CFG; ignore those points for
1281         // now). Therefore, the sup-region outlives the sub-region if,
1282         // for each universal region R1 in the sub-region, there
1283         // exists some region R2 in the sup-region that outlives R1.
1284         let universal_outlives =
1285             self.scc_values.universal_regions_outlived_by(sub_region_scc).all(|r1| {
1286                 self.scc_values
1287                     .universal_regions_outlived_by(sup_region_scc)
1288                     .any(|r2| self.universal_region_relations.outlives(r2, r1))
1289             });
1290
1291         if !universal_outlives {
1292             return false;
1293         }
1294
1295         // Now we have to compare all the points in the sub region and make
1296         // sure they exist in the sup region.
1297
1298         if self.universal_regions.is_universal_region(sup_region) {
1299             // Micro-opt: universal regions contain all points.
1300             return true;
1301         }
1302
1303         self.scc_values.contains_points(sup_region_scc, sub_region_scc)
1304     }
1305
1306     /// Once regions have been propagated, this method is used to see
1307     /// whether any of the constraints were too strong. In particular,
1308     /// we want to check for a case where a universally quantified
1309     /// region exceeded its bounds. Consider:
1310     ///
1311     ///     fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1312     ///
1313     /// In this case, returning `x` requires `&'a u32 <: &'b u32`
1314     /// and hence we establish (transitively) a constraint that
1315     /// `'a: 'b`. The `propagate_constraints` code above will
1316     /// therefore add `end('a)` into the region for `'b` -- but we
1317     /// have no evidence that `'b` outlives `'a`, so we want to report
1318     /// an error.
1319     ///
1320     /// If `propagated_outlives_requirements` is `Some`, then we will
1321     /// push unsatisfied obligations into there. Otherwise, we'll
1322     /// report them as errors.
1323     fn check_universal_regions(
1324         &self,
1325         infcx: &InferCtxt<'_, 'tcx>,
1326         body: &Body<'tcx>,
1327         local_names: &IndexVec<Local, Option<Symbol>>,
1328         upvars: &[Upvar],
1329         mir_def_id: DefId,
1330         mut propagated_outlives_requirements: Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1331         errors_buffer: &mut Vec<Diagnostic>,
1332         region_naming: &mut RegionErrorNamingCtx,
1333     ) {
1334         let mut outlives_suggestion = OutlivesSuggestionBuilder::new(mir_def_id, local_names);
1335
1336         for (fr, fr_definition) in self.definitions.iter_enumerated() {
1337             match fr_definition.origin {
1338                 NLLRegionVariableOrigin::FreeRegion => {
1339                     // Go through each of the universal regions `fr` and check that
1340                     // they did not grow too large, accumulating any requirements
1341                     // for our caller into the `outlives_requirements` vector.
1342                     self.check_universal_region(
1343                         infcx,
1344                         body,
1345                         local_names,
1346                         upvars,
1347                         mir_def_id,
1348                         fr,
1349                         &mut propagated_outlives_requirements,
1350                         &mut outlives_suggestion,
1351                         errors_buffer,
1352                         region_naming,
1353                     );
1354                 }
1355
1356                 NLLRegionVariableOrigin::Placeholder(placeholder) => {
1357                     self.check_bound_universal_region(infcx, body, mir_def_id, fr, placeholder);
1358                 }
1359
1360                 NLLRegionVariableOrigin::Existential { .. } => {
1361                     // nothing to check here
1362                 }
1363             }
1364         }
1365
1366         // Emit outlives suggestions
1367         outlives_suggestion.add_suggestion(body, self, infcx, errors_buffer, region_naming);
1368     }
1369
1370     /// Checks the final value for the free region `fr` to see if it
1371     /// grew too large. In particular, examine what `end(X)` points
1372     /// wound up in `fr`'s final value; for each `end(X)` where `X !=
1373     /// fr`, we want to check that `fr: X`. If not, that's either an
1374     /// error, or something we have to propagate to our creator.
1375     ///
1376     /// Things that are to be propagated are accumulated into the
1377     /// `outlives_requirements` vector.
1378     fn check_universal_region(
1379         &self,
1380         infcx: &InferCtxt<'_, 'tcx>,
1381         body: &Body<'tcx>,
1382         local_names: &IndexVec<Local, Option<Symbol>>,
1383         upvars: &[Upvar],
1384         mir_def_id: DefId,
1385         longer_fr: RegionVid,
1386         propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1387         outlives_suggestion: &mut OutlivesSuggestionBuilder<'_>,
1388         errors_buffer: &mut Vec<Diagnostic>,
1389         region_naming: &mut RegionErrorNamingCtx,
1390     ) {
1391         debug!("check_universal_region(fr={:?})", longer_fr);
1392
1393         let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1394
1395         // Because this free region must be in the ROOT universe, we
1396         // know it cannot contain any bound universes.
1397         assert!(self.scc_universes[longer_fr_scc] == ty::UniverseIndex::ROOT);
1398         debug_assert!(self.scc_values.placeholders_contained_in(longer_fr_scc).next().is_none());
1399
1400         // Only check all of the relations for the main representative of each
1401         // SCC, otherwise just check that we outlive said representative. This
1402         // reduces the number of redundant relations propagated out of
1403         // closures.
1404         // Note that the representative will be a universal region if there is
1405         // one in this SCC, so we will always check the representative here.
1406         let representative = self.scc_representatives[longer_fr_scc];
1407         if representative != longer_fr {
1408             self.check_universal_region_relation(
1409                 longer_fr,
1410                 representative,
1411                 infcx,
1412                 body,
1413                 local_names,
1414                 upvars,
1415                 mir_def_id,
1416                 propagated_outlives_requirements,
1417                 outlives_suggestion,
1418                 errors_buffer,
1419                 region_naming,
1420             );
1421             return;
1422         }
1423
1424         // Find every region `o` such that `fr: o`
1425         // (because `fr` includes `end(o)`).
1426         for shorter_fr in self.scc_values.universal_regions_outlived_by(longer_fr_scc) {
1427             if let Some(ErrorReported) = self.check_universal_region_relation(
1428                 longer_fr,
1429                 shorter_fr,
1430                 infcx,
1431                 body,
1432                 local_names,
1433                 upvars,
1434                 mir_def_id,
1435                 propagated_outlives_requirements,
1436                 outlives_suggestion,
1437                 errors_buffer,
1438                 region_naming,
1439             ) {
1440                 // continuing to iterate just reports more errors than necessary
1441                 //
1442                 // FIXME It would also allow us to report more Outlives Suggestions, though, so
1443                 // it's not clear that that's a bad thing. Somebody should try commenting out this
1444                 // line and see it is actually a regression.
1445                 return;
1446             }
1447         }
1448     }
1449
1450     fn check_universal_region_relation(
1451         &self,
1452         longer_fr: RegionVid,
1453         shorter_fr: RegionVid,
1454         infcx: &InferCtxt<'_, 'tcx>,
1455         body: &Body<'tcx>,
1456         local_names: &IndexVec<Local, Option<Symbol>>,
1457         upvars: &[Upvar],
1458         mir_def_id: DefId,
1459         propagated_outlives_requirements: &mut Option<&mut Vec<ClosureOutlivesRequirement<'tcx>>>,
1460         outlives_suggestion: &mut OutlivesSuggestionBuilder<'_>,
1461         errors_buffer: &mut Vec<Diagnostic>,
1462         region_naming: &mut RegionErrorNamingCtx,
1463     ) -> Option<ErrorReported> {
1464         // If it is known that `fr: o`, carry on.
1465         if self.universal_region_relations.outlives(longer_fr, shorter_fr) {
1466             return None;
1467         }
1468
1469         debug!(
1470             "check_universal_region_relation: fr={:?} does not outlive shorter_fr={:?}",
1471             longer_fr, shorter_fr,
1472         );
1473
1474         if let Some(propagated_outlives_requirements) = propagated_outlives_requirements {
1475             // Shrink `longer_fr` until we find a non-local region (if we do).
1476             // We'll call it `fr-` -- it's ever so slightly smaller than
1477             // `longer_fr`.
1478
1479             if let Some(fr_minus) = self.universal_region_relations.non_local_lower_bound(longer_fr)
1480             {
1481                 debug!("check_universal_region: fr_minus={:?}", fr_minus);
1482
1483                 let blame_span_category =
1484                     self.find_outlives_blame_span(body, longer_fr,
1485                                                   NLLRegionVariableOrigin::FreeRegion,shorter_fr);
1486
1487                 // Grow `shorter_fr` until we find some non-local regions. (We
1488                 // always will.)  We'll call them `shorter_fr+` -- they're ever
1489                 // so slightly larger than `shorter_fr`.
1490                 let shorter_fr_plus =
1491                     self.universal_region_relations.non_local_upper_bounds(&shorter_fr);
1492                 debug!("check_universal_region: shorter_fr_plus={:?}", shorter_fr_plus);
1493                 for &&fr in &shorter_fr_plus {
1494                     // Push the constraint `fr-: shorter_fr+`
1495                     propagated_outlives_requirements.push(ClosureOutlivesRequirement {
1496                         subject: ClosureOutlivesSubject::Region(fr_minus),
1497                         outlived_free_region: fr,
1498                         blame_span: blame_span_category.1,
1499                         category: blame_span_category.0,
1500                     });
1501                 }
1502                 return None;
1503             }
1504         }
1505
1506         // If we are not in a context where we can't propagate errors, or we
1507         // could not shrink `fr` to something smaller, then just report an
1508         // error.
1509         //
1510         // Note: in this case, we use the unapproximated regions to report the
1511         // error. This gives better error messages in some cases.
1512         let db = self.report_error(
1513             body,
1514             local_names,
1515             upvars,
1516             infcx,
1517             mir_def_id,
1518             longer_fr,
1519             NLLRegionVariableOrigin::FreeRegion,
1520             shorter_fr,
1521             outlives_suggestion,
1522             region_naming,
1523         );
1524
1525         db.buffer(errors_buffer);
1526
1527         Some(ErrorReported)
1528     }
1529
1530     fn check_bound_universal_region(
1531         &self,
1532         infcx: &InferCtxt<'_, 'tcx>,
1533         body: &Body<'tcx>,
1534         _mir_def_id: DefId,
1535         longer_fr: RegionVid,
1536         placeholder: ty::PlaceholderRegion,
1537     ) {
1538         debug!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr, placeholder,);
1539
1540         let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
1541         debug!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc,);
1542
1543         // If we have some bound universal region `'a`, then the only
1544         // elements it can contain is itself -- we don't know anything
1545         // else about it!
1546         let error_element = match {
1547             self.scc_values.elements_contained_in(longer_fr_scc).find(|element| match element {
1548                 RegionElement::Location(_) => true,
1549                 RegionElement::RootUniversalRegion(_) => true,
1550                 RegionElement::PlaceholderRegion(placeholder1) => placeholder != *placeholder1,
1551             })
1552         } {
1553             Some(v) => v,
1554             None => return,
1555         };
1556         debug!("check_bound_universal_region: error_element = {:?}", error_element);
1557
1558         // Find the region that introduced this `error_element`.
1559         let error_region = match error_element {
1560             RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),
1561             RegionElement::RootUniversalRegion(r) => r,
1562             RegionElement::PlaceholderRegion(error_placeholder) => self
1563                 .definitions
1564                 .iter_enumerated()
1565                 .filter_map(|(r, definition)| match definition.origin {
1566                     NLLRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),
1567                     _ => None,
1568                 })
1569                 .next()
1570                 .unwrap(),
1571         };
1572
1573         // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
1574         let (_, span) = self.find_outlives_blame_span(
1575             body, longer_fr, NLLRegionVariableOrigin::Placeholder(placeholder), error_region
1576         );
1577
1578         // Obviously, this error message is far from satisfactory.
1579         // At present, though, it only appears in unit tests --
1580         // the AST-based checker uses a more conservative check,
1581         // so to even see this error, one must pass in a special
1582         // flag.
1583         let mut diag = infcx.tcx.sess.struct_span_err(span, "higher-ranked subtype error");
1584         diag.emit();
1585     }
1586
1587     fn check_member_constraints(
1588         &self,
1589         infcx: &InferCtxt<'_, 'tcx>,
1590         mir_def_id: DefId,
1591         errors_buffer: &mut Vec<Diagnostic>,
1592     ) {
1593         let member_constraints = self.member_constraints.clone();
1594         for m_c_i in member_constraints.all_indices() {
1595             debug!("check_member_constraint(m_c_i={:?})", m_c_i);
1596             let m_c = &member_constraints[m_c_i];
1597             let member_region_vid = m_c.member_region_vid;
1598             debug!(
1599                 "check_member_constraint: member_region_vid={:?} with value {}",
1600                 member_region_vid,
1601                 self.region_value_str(member_region_vid),
1602             );
1603             let choice_regions = member_constraints.choice_regions(m_c_i);
1604             debug!("check_member_constraint: choice_regions={:?}", choice_regions);
1605
1606             // Did the member region wind up equal to any of the option regions?
1607             if let Some(o) = choice_regions.iter().find(|&&o_r| {
1608                 self.eval_equal(o_r, m_c.member_region_vid)
1609             }) {
1610                 debug!("check_member_constraint: evaluated as equal to {:?}", o);
1611                 continue;
1612             }
1613
1614             // If not, report an error.
1615             let region_scope_tree = &infcx.tcx.region_scope_tree(mir_def_id);
1616             let member_region = infcx.tcx.mk_region(ty::ReVar(member_region_vid));
1617             opaque_types::unexpected_hidden_region_diagnostic(
1618                 infcx.tcx,
1619                 Some(region_scope_tree),
1620                 m_c.opaque_type_def_id,
1621                 m_c.hidden_ty,
1622                 member_region,
1623             )
1624             .buffer(errors_buffer);
1625         }
1626     }
1627 }
1628
1629 impl<'tcx> RegionDefinition<'tcx> {
1630     fn new(universe: ty::UniverseIndex, rv_origin: RegionVariableOrigin) -> Self {
1631         // Create a new region definition. Note that, for free
1632         // regions, the `external_name` field gets updated later in
1633         // `init_universal_regions`.
1634
1635         let origin = match rv_origin {
1636             RegionVariableOrigin::NLL(origin) => origin,
1637             _ => NLLRegionVariableOrigin::Existential { from_forall: false },
1638         };
1639
1640         Self { origin, universe, external_name: None }
1641     }
1642 }
1643
1644 pub trait ClosureRegionRequirementsExt<'tcx> {
1645     fn apply_requirements(
1646         &self,
1647         tcx: TyCtxt<'tcx>,
1648         closure_def_id: DefId,
1649         closure_substs: SubstsRef<'tcx>,
1650     ) -> Vec<QueryOutlivesConstraint<'tcx>>;
1651
1652     fn subst_closure_mapping<T>(
1653         &self,
1654         tcx: TyCtxt<'tcx>,
1655         closure_mapping: &IndexVec<RegionVid, ty::Region<'tcx>>,
1656         value: &T,
1657     ) -> T
1658     where
1659         T: TypeFoldable<'tcx>;
1660 }
1661
1662 impl<'tcx> ClosureRegionRequirementsExt<'tcx> for ClosureRegionRequirements<'tcx> {
1663     /// Given an instance T of the closure type, this method
1664     /// instantiates the "extra" requirements that we computed for the
1665     /// closure into the inference context. This has the effect of
1666     /// adding new outlives obligations to existing variables.
1667     ///
1668     /// As described on `ClosureRegionRequirements`, the extra
1669     /// requirements are expressed in terms of regionvids that index
1670     /// into the free regions that appear on the closure type. So, to
1671     /// do this, we first copy those regions out from the type T into
1672     /// a vector. Then we can just index into that vector to extract
1673     /// out the corresponding region from T and apply the
1674     /// requirements.
1675     fn apply_requirements(
1676         &self,
1677         tcx: TyCtxt<'tcx>,
1678         closure_def_id: DefId,
1679         closure_substs: SubstsRef<'tcx>,
1680     ) -> Vec<QueryOutlivesConstraint<'tcx>> {
1681         debug!(
1682             "apply_requirements(closure_def_id={:?}, closure_substs={:?})",
1683             closure_def_id, closure_substs
1684         );
1685
1686         // Extract the values of the free regions in `closure_substs`
1687         // into a vector.  These are the regions that we will be
1688         // relating to one another.
1689         let closure_mapping = &UniversalRegions::closure_mapping(
1690             tcx,
1691             closure_substs,
1692             self.num_external_vids,
1693             tcx.closure_base_def_id(closure_def_id),
1694         );
1695         debug!("apply_requirements: closure_mapping={:?}", closure_mapping);
1696
1697         // Create the predicates.
1698         self.outlives_requirements
1699             .iter()
1700             .map(|outlives_requirement| {
1701                 let outlived_region = closure_mapping[outlives_requirement.outlived_free_region];
1702
1703                 match outlives_requirement.subject {
1704                     ClosureOutlivesSubject::Region(region) => {
1705                         let region = closure_mapping[region];
1706                         debug!(
1707                             "apply_requirements: region={:?} \
1708                              outlived_region={:?} \
1709                              outlives_requirement={:?}",
1710                             region, outlived_region, outlives_requirement,
1711                         );
1712                         ty::Binder::dummy(ty::OutlivesPredicate(region.into(), outlived_region))
1713                     }
1714
1715                     ClosureOutlivesSubject::Ty(ty) => {
1716                         let ty = self.subst_closure_mapping(tcx, closure_mapping, &ty);
1717                         debug!(
1718                             "apply_requirements: ty={:?} \
1719                              outlived_region={:?} \
1720                              outlives_requirement={:?}",
1721                             ty, outlived_region, outlives_requirement,
1722                         );
1723                         ty::Binder::dummy(ty::OutlivesPredicate(ty.into(), outlived_region))
1724                     }
1725                 }
1726             })
1727             .collect()
1728     }
1729
1730     fn subst_closure_mapping<T>(
1731         &self,
1732         tcx: TyCtxt<'tcx>,
1733         closure_mapping: &IndexVec<RegionVid, ty::Region<'tcx>>,
1734         value: &T,
1735     ) -> T
1736     where
1737         T: TypeFoldable<'tcx>,
1738     {
1739         tcx.fold_regions(value, &mut false, |r, _depth| {
1740             if let ty::ReClosureBound(vid) = r {
1741                 closure_mapping[*vid]
1742             } else {
1743                 bug!("subst_closure_mapping: encountered non-closure bound free region {:?}", r)
1744             }
1745         })
1746     }
1747 }