1 use std
::collections
::VecDeque
;
4 use rustc
::infer
::canonical
::QueryOutlivesConstraint
;
5 use rustc
::infer
::region_constraints
::{GenericKind, VarInfos, VerifyBound}
;
6 use rustc
::infer
::{InferCtxt, NLLRegionVariableOrigin, RegionVariableOrigin}
;
8 Body
, ClosureOutlivesRequirement
, ClosureOutlivesSubject
, ClosureRegionRequirements
,
9 ConstraintCategory
, Local
, Location
,
11 use rustc
::ty
::{self, subst::SubstsRef, RegionVid, Ty, TyCtxt, TypeFoldable}
;
12 use rustc_data_structures
::binary_search_util
;
13 use rustc_data_structures
::fx
::{FxHashMap, FxHashSet}
;
14 use rustc_data_structures
::graph
::scc
::Sccs
;
15 use rustc_data_structures
::graph
::vec_graph
::VecGraph
;
16 use rustc_data_structures
::graph
::WithSuccessors
;
17 use rustc_hir
::def_id
::DefId
;
18 use rustc_index
::bit_set
::BitSet
;
19 use rustc_index
::vec
::IndexVec
;
22 use crate::borrow_check
::{
24 graph
::NormalConstraintGraph
, ConstraintSccIndex
, OutlivesConstraint
, OutlivesConstraintSet
,
26 diagnostics
::{RegionErrorKind, RegionErrors}
,
27 member_constraints
::{MemberConstraintSet, NllMemberConstraintIndex}
,
28 nll
::{PoloniusOutput, ToRegionVid}
,
29 region_infer
::values
::{
30 LivenessValues
, PlaceholderIndices
, RegionElement
, RegionValueElements
, RegionValues
,
33 type_check
::{free_region_relations::UniversalRegionRelations, Locations}
,
34 universal_regions
::UniversalRegions
,
42 pub struct RegionInferenceContext
<'tcx
> {
43 /// Contains the definition for every region variable. Region
44 /// variables are identified by their index (`RegionVid`). The
45 /// definition contains information about where the region came
46 /// from as well as its final inferred value.
47 definitions
: IndexVec
<RegionVid
, RegionDefinition
<'tcx
>>,
49 /// The liveness constraints added to each region. For most
50 /// regions, these start out empty and steadily grow, though for
51 /// each universally quantified region R they start out containing
52 /// the entire CFG and `end(R)`.
53 liveness_constraints
: LivenessValues
<RegionVid
>,
55 /// The outlives constraints computed by the type-check.
56 constraints
: Rc
<OutlivesConstraintSet
>,
58 /// The constraint-set, but in graph form, making it easy to traverse
59 /// the constraints adjacent to a particular region. Used to construct
60 /// the SCC (see `constraint_sccs`) and for error reporting.
61 constraint_graph
: Rc
<NormalConstraintGraph
>,
63 /// The SCC computed from `constraints` and the constraint
64 /// graph. We have an edge from SCC A to SCC B if `A: B`. Used to
65 /// compute the values of each region.
66 constraint_sccs
: Rc
<Sccs
<RegionVid
, ConstraintSccIndex
>>,
68 /// Reverse of the SCC constraint graph -- i.e., an edge `A -> B`
69 /// exists if `B: A`. Computed lazilly.
70 rev_constraint_graph
: Option
<Rc
<VecGraph
<ConstraintSccIndex
>>>,
72 /// The "R0 member of [R1..Rn]" constraints, indexed by SCC.
73 member_constraints
: Rc
<MemberConstraintSet
<'tcx
, ConstraintSccIndex
>>,
75 /// Records the member constraints that we applied to each scc.
76 /// This is useful for error reporting. Once constraint
77 /// propagation is done, this vector is sorted according to
78 /// `member_region_scc`.
79 member_constraints_applied
: Vec
<AppliedMemberConstraint
>,
81 /// Map closure bounds to a `Span` that should be used for error reporting.
82 closure_bounds_mapping
:
83 FxHashMap
<Location
, FxHashMap
<(RegionVid
, RegionVid
), (ConstraintCategory
, Span
)>>,
85 /// Contains the minimum universe of any variable within the same
86 /// SCC. We will ensure that no SCC contains values that are not
87 /// visible from this index.
88 scc_universes
: IndexVec
<ConstraintSccIndex
, ty
::UniverseIndex
>,
90 /// Contains a "representative" from each SCC. This will be the
91 /// minimal RegionVid belonging to that universe. It is used as a
92 /// kind of hacky way to manage checking outlives relationships,
93 /// since we can 'canonicalize' each region to the representative
94 /// of its SCC and be sure that -- if they have the same repr --
95 /// they *must* be equal (though not having the same repr does not
96 /// mean they are unequal).
97 scc_representatives
: IndexVec
<ConstraintSccIndex
, ty
::RegionVid
>,
99 /// The final inferred values of the region variables; we compute
100 /// one value per SCC. To get the value for any given *region*,
101 /// you first find which scc it is a part of.
102 scc_values
: RegionValues
<ConstraintSccIndex
>,
104 /// Type constraints that we check after solving.
105 type_tests
: Vec
<TypeTest
<'tcx
>>,
107 /// Information about the universally quantified regions in scope
108 /// on this function.
109 universal_regions
: Rc
<UniversalRegions
<'tcx
>>,
111 /// Information about how the universally quantified regions in
112 /// scope on this function relate to one another.
113 universal_region_relations
: Rc
<UniversalRegionRelations
<'tcx
>>,
116 /// Each time that `apply_member_constraint` is successful, it appends
117 /// one of these structs to the `member_constraints_applied` field.
118 /// This is used in error reporting to trace out what happened.
120 /// The way that `apply_member_constraint` works is that it effectively
121 /// adds a new lower bound to the SCC it is analyzing: so you wind up
122 /// with `'R: 'O` where `'R` is the pick-region and `'O` is the
123 /// minimal viable option.
124 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
125 pub(crate) struct AppliedMemberConstraint
{
126 /// The SCC that was affected. (The "member region".)
128 /// The vector if `AppliedMemberConstraint` elements is kept sorted
130 pub(in crate::borrow_check
) member_region_scc
: ConstraintSccIndex
,
132 /// The "best option" that `apply_member_constraint` found -- this was
133 /// added as an "ad-hoc" lower-bound to `member_region_scc`.
134 pub(in crate::borrow_check
) min_choice
: ty
::RegionVid
,
136 /// The "member constraint index" -- we can find out details about
137 /// the constraint from
138 /// `set.member_constraints[member_constraint_index]`.
139 pub(in crate::borrow_check
) member_constraint_index
: NllMemberConstraintIndex
,
142 pub(crate) struct RegionDefinition
<'tcx
> {
143 /// What kind of variable is this -- a free region? existential
144 /// variable? etc. (See the `NLLRegionVariableOrigin` for more
146 pub(in crate::borrow_check
) origin
: NLLRegionVariableOrigin
,
148 /// Which universe is this region variable defined in? This is
149 /// most often `ty::UniverseIndex::ROOT`, but when we encounter
150 /// forall-quantifiers like `for<'a> { 'a = 'b }`, we would create
151 /// the variable for `'a` in a fresh universe that extends ROOT.
152 pub(in crate::borrow_check
) universe
: ty
::UniverseIndex
,
154 /// If this is 'static or an early-bound region, then this is
155 /// `Some(X)` where `X` is the name of the region.
156 pub(in crate::borrow_check
) external_name
: Option
<ty
::Region
<'tcx
>>,
159 /// N.B., the variants in `Cause` are intentionally ordered. Lower
160 /// values are preferred when it comes to error messages. Do not
161 /// reorder willy nilly.
162 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
163 pub(crate) enum Cause
{
164 /// point inserted because Local was live at the given Location
165 LiveVar(Local
, Location
),
167 /// point inserted because Local was dropped at the given Location
168 DropVar(Local
, Location
),
171 /// A "type test" corresponds to an outlives constraint between a type
172 /// and a lifetime, like `T: 'x` or `<T as Foo>::Bar: 'x`. They are
173 /// translated from the `Verify` region constraints in the ordinary
174 /// inference context.
176 /// These sorts of constraints are handled differently than ordinary
177 /// constraints, at least at present. During type checking, the
178 /// `InferCtxt::process_registered_region_obligations` method will
179 /// attempt to convert a type test like `T: 'x` into an ordinary
180 /// outlives constraint when possible (for example, `&'a T: 'b` will
181 /// be converted into `'a: 'b` and registered as a `Constraint`).
183 /// In some cases, however, there are outlives relationships that are
184 /// not converted into a region constraint, but rather into one of
185 /// these "type tests". The distinction is that a type test does not
186 /// influence the inference result, but instead just examines the
187 /// values that we ultimately inferred for each region variable and
188 /// checks that they meet certain extra criteria. If not, an error
191 /// One reason for this is that these type tests typically boil down
192 /// to a check like `'a: 'x` where `'a` is a universally quantified
193 /// region -- and therefore not one whose value is really meant to be
194 /// *inferred*, precisely (this is not always the case: one can have a
195 /// type test like `<Foo as Trait<'?0>>::Bar: 'x`, where `'?0` is an
196 /// inference variable). Another reason is that these type tests can
197 /// involve *disjunction* -- that is, they can be satisfied in more
200 /// For more information about this translation, see
201 /// `InferCtxt::process_registered_region_obligations` and
202 /// `InferCtxt::type_must_outlive` in `rustc::infer::outlives`.
203 #[derive(Clone, Debug)]
204 pub struct TypeTest
<'tcx
> {
205 /// The type `T` that must outlive the region.
206 pub generic_kind
: GenericKind
<'tcx
>,
208 /// The region `'x` that the type must outlive.
209 pub lower_bound
: RegionVid
,
211 /// Where did this constraint arise and why?
212 pub locations
: Locations
,
214 /// A test which, if met by the region `'x`, proves that this type
215 /// constraint is satisfied.
216 pub verify_bound
: VerifyBound
<'tcx
>,
219 /// When we have an unmet lifetime constraint, we try to propagate it outward (e.g. to a closure
220 /// environment). If we can't, it is an error.
221 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
222 enum RegionRelationCheckResult
{
228 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
231 FromOutlivesConstraint(OutlivesConstraint
),
235 impl<'tcx
> RegionInferenceContext
<'tcx
> {
236 /// Creates a new region inference context with a total of
237 /// `num_region_variables` valid inference variables; the first N
238 /// of those will be constant regions representing the free
239 /// regions defined in `universal_regions`.
241 /// The `outlives_constraints` and `type_tests` are an initial set
242 /// of constraints produced by the MIR type check.
245 universal_regions
: Rc
<UniversalRegions
<'tcx
>>,
246 placeholder_indices
: Rc
<PlaceholderIndices
>,
247 universal_region_relations
: Rc
<UniversalRegionRelations
<'tcx
>>,
248 outlives_constraints
: OutlivesConstraintSet
,
249 member_constraints_in
: MemberConstraintSet
<'tcx
, RegionVid
>,
250 closure_bounds_mapping
: FxHashMap
<
252 FxHashMap
<(RegionVid
, RegionVid
), (ConstraintCategory
, Span
)>,
254 type_tests
: Vec
<TypeTest
<'tcx
>>,
255 liveness_constraints
: LivenessValues
<RegionVid
>,
256 elements
: &Rc
<RegionValueElements
>,
258 // Create a RegionDefinition for each inference variable.
259 let definitions
: IndexVec
<_
, _
> = var_infos
261 .map(|info
| RegionDefinition
::new(info
.universe
, info
.origin
))
264 let constraints
= Rc
::new(outlives_constraints
); // freeze constraints
265 let constraint_graph
= Rc
::new(constraints
.graph(definitions
.len()));
266 let fr_static
= universal_regions
.fr_static
;
267 let constraint_sccs
= Rc
::new(constraints
.compute_sccs(&constraint_graph
, fr_static
));
270 RegionValues
::new(elements
, universal_regions
.len(), &placeholder_indices
);
272 for region
in liveness_constraints
.rows() {
273 let scc
= constraint_sccs
.scc(region
);
274 scc_values
.merge_liveness(scc
, region
, &liveness_constraints
);
277 let scc_universes
= Self::compute_scc_universes(&constraint_sccs
, &definitions
);
279 let scc_representatives
= Self::compute_scc_representatives(&constraint_sccs
, &definitions
);
281 let member_constraints
=
282 Rc
::new(member_constraints_in
.into_mapped(|r
| constraint_sccs
.scc(r
)));
284 let mut result
= Self {
286 liveness_constraints
,
290 rev_constraint_graph
: None
,
292 member_constraints_applied
: Vec
::new(),
293 closure_bounds_mapping
,
299 universal_region_relations
,
302 result
.init_free_and_bound_regions();
307 /// Each SCC is the combination of many region variables which
308 /// have been equated. Therefore, we can associate a universe with
309 /// each SCC which is minimum of all the universes of its
310 /// constituent regions -- this is because whatever value the SCC
311 /// takes on must be a value that each of the regions within the
312 /// SCC could have as well. This implies that the SCC must have
313 /// the minimum, or narrowest, universe.
314 fn compute_scc_universes(
315 constraints_scc
: &Sccs
<RegionVid
, ConstraintSccIndex
>,
316 definitions
: &IndexVec
<RegionVid
, RegionDefinition
<'tcx
>>,
317 ) -> IndexVec
<ConstraintSccIndex
, ty
::UniverseIndex
> {
318 let num_sccs
= constraints_scc
.num_sccs();
319 let mut scc_universes
= IndexVec
::from_elem_n(ty
::UniverseIndex
::MAX
, num_sccs
);
321 for (region_vid
, region_definition
) in definitions
.iter_enumerated() {
322 let scc
= constraints_scc
.scc(region_vid
);
323 let scc_universe
= &mut scc_universes
[scc
];
324 *scc_universe
= ::std
::cmp
::min(*scc_universe
, region_definition
.universe
);
327 debug
!("compute_scc_universes: scc_universe = {:#?}", scc_universes
);
332 /// For each SCC, we compute a unique `RegionVid` (in fact, the
333 /// minimal one that belongs to the SCC). See
334 /// `scc_representatives` field of `RegionInferenceContext` for
336 fn compute_scc_representatives(
337 constraints_scc
: &Sccs
<RegionVid
, ConstraintSccIndex
>,
338 definitions
: &IndexVec
<RegionVid
, RegionDefinition
<'tcx
>>,
339 ) -> IndexVec
<ConstraintSccIndex
, ty
::RegionVid
> {
340 let num_sccs
= constraints_scc
.num_sccs();
341 let next_region_vid
= definitions
.next_index();
342 let mut scc_representatives
= IndexVec
::from_elem_n(next_region_vid
, num_sccs
);
344 for region_vid
in definitions
.indices() {
345 let scc
= constraints_scc
.scc(region_vid
);
346 let prev_min
= scc_representatives
[scc
];
347 scc_representatives
[scc
] = region_vid
.min(prev_min
);
353 /// Initializes the region variables for each universally
354 /// quantified region (lifetime parameter). The first N variables
355 /// always correspond to the regions appearing in the function
356 /// signature (both named and anonymous) and where-clauses. This
357 /// function iterates over those regions and initializes them with
362 /// fn foo<'a, 'b>(..) where 'a: 'b
364 /// would initialize two variables like so:
366 /// R0 = { CFG, R0 } // 'a
367 /// R1 = { CFG, R0, R1 } // 'b
369 /// Here, R0 represents `'a`, and it contains (a) the entire CFG
370 /// and (b) any universally quantified regions that it outlives,
371 /// which in this case is just itself. R1 (`'b`) in contrast also
372 /// outlives `'a` and hence contains R0 and R1.
373 fn init_free_and_bound_regions(&mut self) {
374 // Update the names (if any)
375 for (external_name
, variable
) in self.universal_regions
.named_universal_regions() {
377 "init_universal_regions: region {:?} has external name {:?}",
378 variable
, external_name
380 self.definitions
[variable
].external_name
= Some(external_name
);
383 for variable
in self.definitions
.indices() {
384 let scc
= self.constraint_sccs
.scc(variable
);
386 match self.definitions
[variable
].origin
{
387 NLLRegionVariableOrigin
::FreeRegion
=> {
388 // For each free, universally quantified region X:
390 // Add all nodes in the CFG to liveness constraints
391 self.liveness_constraints
.add_all_points(variable
);
392 self.scc_values
.add_all_points(scc
);
394 // Add `end(X)` into the set for X.
395 self.scc_values
.add_element(scc
, variable
);
398 NLLRegionVariableOrigin
::Placeholder(placeholder
) => {
399 // Each placeholder region is only visible from
400 // its universe `ui` and its extensions. So we
401 // can't just add it into `scc` unless the
402 // universe of the scc can name this region.
403 let scc_universe
= self.scc_universes
[scc
];
404 if scc_universe
.can_name(placeholder
.universe
) {
405 self.scc_values
.add_element(scc
, placeholder
);
408 "init_free_and_bound_regions: placeholder {:?} is \
409 not compatible with universe {:?} of its SCC {:?}",
410 placeholder
, scc_universe
, scc
,
412 self.add_incompatible_universe(scc
);
416 NLLRegionVariableOrigin
::Existential { .. }
=> {
417 // For existential, regions, nothing to do.
423 /// Returns an iterator over all the region indices.
424 pub fn regions(&self) -> impl Iterator
<Item
= RegionVid
> {
425 self.definitions
.indices()
428 /// Given a universal region in scope on the MIR, returns the
429 /// corresponding index.
431 /// (Panics if `r` is not a registered universal region.)
432 pub fn to_region_vid(&self, r
: ty
::Region
<'tcx
>) -> RegionVid
{
433 self.universal_regions
.to_region_vid(r
)
436 /// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
437 crate fn annotate(&self, tcx
: TyCtxt
<'tcx
>, err
: &mut rustc_errors
::DiagnosticBuilder
<'_
>) {
438 self.universal_regions
.annotate(tcx
, err
)
441 /// Returns `true` if the region `r` contains the point `p`.
443 /// Panics if called before `solve()` executes,
444 crate fn region_contains(&self, r
: impl ToRegionVid
, p
: impl ToElementIndex
) -> bool
{
445 let scc
= self.constraint_sccs
.scc(r
.to_region_vid());
446 self.scc_values
.contains(scc
, p
)
449 /// Returns access to the value of `r` for debugging purposes.
450 crate fn region_value_str(&self, r
: RegionVid
) -> String
{
451 let scc
= self.constraint_sccs
.scc(r
.to_region_vid());
452 self.scc_values
.region_value_str(scc
)
455 /// Returns access to the value of `r` for debugging purposes.
456 crate fn region_universe(&self, r
: RegionVid
) -> ty
::UniverseIndex
{
457 let scc
= self.constraint_sccs
.scc(r
.to_region_vid());
458 self.scc_universes
[scc
]
461 /// Once region solving has completed, this function will return
462 /// the member constraints that were applied to the value of a given
463 /// region `r`. See `AppliedMemberConstraint`.
464 pub(in crate::borrow_check
) fn applied_member_constraints(
467 ) -> &[AppliedMemberConstraint
] {
468 let scc
= self.constraint_sccs
.scc(r
.to_region_vid());
469 binary_search_util
::binary_search_slice(
470 &self.member_constraints_applied
,
471 |applied
| applied
.member_region_scc
,
476 /// Performs region inference and report errors if we see any
477 /// unsatisfiable constraints. If this is a closure, returns the
478 /// region requirements to propagate to our creator, if any.
481 infcx
: &InferCtxt
<'_
, 'tcx
>,
484 polonius_output
: Option
<Rc
<PoloniusOutput
>>,
485 ) -> (Option
<ClosureRegionRequirements
<'tcx
>>, RegionErrors
<'tcx
>) {
486 self.propagate_constraints(body
);
488 let mut errors_buffer
= RegionErrors
::new();
490 // If this is a closure, we can propagate unsatisfied
491 // `outlives_requirements` to our creator, so create a vector
492 // to store those. Otherwise, we'll pass in `None` to the
493 // functions below, which will trigger them to report errors
495 let mut outlives_requirements
= infcx
.tcx
.is_closure(mir_def_id
).then(|| vec
![]);
497 self.check_type_tests(infcx
, body
, outlives_requirements
.as_mut(), &mut errors_buffer
);
499 // In Polonius mode, the errors about missing universal region relations are in the output
500 // and need to be emitted or propagated. Otherwise, we need to check whether the
501 // constraints were too strong, and if so, emit or propagate those errors.
502 if infcx
.tcx
.sess
.opts
.debugging_opts
.polonius
{
503 self.check_polonius_subset_errors(
505 outlives_requirements
.as_mut(),
507 polonius_output
.expect("Polonius output is unavailable despite `-Z polonius`"),
510 self.check_universal_regions(body
, outlives_requirements
.as_mut(), &mut errors_buffer
);
513 self.check_member_constraints(infcx
, &mut errors_buffer
);
515 let outlives_requirements
= outlives_requirements
.unwrap_or(vec
![]);
517 if outlives_requirements
.is_empty() {
518 (None
, errors_buffer
)
520 let num_external_vids
= self.universal_regions
.num_global_and_external_regions();
522 Some(ClosureRegionRequirements { num_external_vids, outlives_requirements }
),
528 /// Propagate the region constraints: this will grow the values
529 /// for each region variable until all the constraints are
530 /// satisfied. Note that some values may grow **too** large to be
531 /// feasible, but we check this later.
532 fn propagate_constraints(&mut self, _body
: &Body
<'tcx
>) {
533 debug
!("propagate_constraints()");
535 debug
!("propagate_constraints: constraints={:#?}", {
536 let mut constraints
: Vec
<_
> = self.constraints
.outlives().iter().collect();
540 .map(|c
| (c
, self.constraint_sccs
.scc(c
.sup
), self.constraint_sccs
.scc(c
.sub
)))
544 // To propagate constraints, we walk the DAG induced by the
545 // SCC. For each SCC, we visit its successors and compute
546 // their values, then we union all those values to get our
548 let visited
= &mut BitSet
::new_empty(self.constraint_sccs
.num_sccs());
549 for scc_index
in self.constraint_sccs
.all_sccs() {
550 self.propagate_constraint_sccs_if_new(scc_index
, visited
);
553 // Sort the applied member constraints so we can binary search
554 // through them later.
555 self.member_constraints_applied
.sort_by_key(|applied
| applied
.member_region_scc
);
558 /// Computes the value of the SCC `scc_a` if it has not already
559 /// been computed. The `visited` parameter is a bitset
561 fn propagate_constraint_sccs_if_new(
563 scc_a
: ConstraintSccIndex
,
564 visited
: &mut BitSet
<ConstraintSccIndex
>,
566 if visited
.insert(scc_a
) {
567 self.propagate_constraint_sccs_new(scc_a
, visited
);
571 /// Computes the value of the SCC `scc_a`, which has not yet been
572 /// computed. This works by first computing all successors of the
573 /// SCC (if they haven't been computed already) and then unioning
574 /// together their elements.
575 fn propagate_constraint_sccs_new(
577 scc_a
: ConstraintSccIndex
,
578 visited
: &mut BitSet
<ConstraintSccIndex
>,
580 let constraint_sccs
= self.constraint_sccs
.clone();
582 // Walk each SCC `B` such that `A: B`...
583 for &scc_b
in constraint_sccs
.successors(scc_a
) {
584 debug
!("propagate_constraint_sccs: scc_a = {:?} scc_b = {:?}", scc_a
, scc_b
);
586 // ...compute the value of `B`...
587 self.propagate_constraint_sccs_if_new(scc_b
, visited
);
589 // ...and add elements from `B` into `A`. One complication
590 // arises because of universes: If `B` contains something
591 // that `A` cannot name, then `A` can only contain `B` if
592 // it outlives static.
593 if self.universe_compatible(scc_b
, scc_a
) {
594 // `A` can name everything that is in `B`, so just
596 self.scc_values
.add_region(scc_a
, scc_b
);
598 self.add_incompatible_universe(scc_a
);
602 // Now take member constraints into account.
603 let member_constraints
= self.member_constraints
.clone();
604 for m_c_i
in member_constraints
.indices(scc_a
) {
605 self.apply_member_constraint(scc_a
, m_c_i
, member_constraints
.choice_regions(m_c_i
));
609 "propagate_constraint_sccs: scc_a = {:?} has value {:?}",
611 self.scc_values
.region_value_str(scc_a
),
615 /// Invoked for each `R0 member of [R1..Rn]` constraint.
617 /// `scc` is the SCC containing R0, and `choice_regions` are the
618 /// `R1..Rn` regions -- they are always known to be universal
619 /// regions (and if that's not true, we just don't attempt to
620 /// enforce the constraint).
622 /// The current value of `scc` at the time the method is invoked
623 /// is considered a *lower bound*. If possible, we will modify
624 /// the constraint to set it equal to one of the option regions.
625 /// If we make any changes, returns true, else false.
626 fn apply_member_constraint(
628 scc
: ConstraintSccIndex
,
629 member_constraint_index
: NllMemberConstraintIndex
,
630 choice_regions
: &[ty
::RegionVid
],
632 debug
!("apply_member_constraint(scc={:?}, choice_regions={:#?})", scc
, choice_regions
,);
635 choice_regions
.iter().find(|&&r
| !self.universal_regions
.is_universal_region(r
))
637 // FIXME(#61773): This case can only occur with
638 // `impl_trait_in_bindings`, I believe, and we are just
639 // opting not to handle it for now. See #61773 for
642 "member constraint for `{:?}` has an option region `{:?}` \
643 that is not a universal region",
644 self.member_constraints
[member_constraint_index
].opaque_type_def_id
,
649 // Create a mutable vector of the options. We'll try to winnow
651 let mut choice_regions
: Vec
<ty
::RegionVid
> = choice_regions
.to_vec();
653 // The 'member region' in a member constraint is part of the
654 // hidden type, which must be in the root universe. Therefore,
655 // it cannot have any placeholders in its value.
656 assert
!(self.scc_universes
[scc
] == ty
::UniverseIndex
::ROOT
);
658 self.scc_values
.placeholders_contained_in(scc
).next().is_none(),
659 "scc {:?} in a member constraint has placeholder value: {:?}",
661 self.scc_values
.region_value_str(scc
),
664 // The existing value for `scc` is a lower-bound. This will
665 // consist of some set `{P} + {LB}` of points `{P}` and
666 // lower-bound free regions `{LB}`. As each choice region `O`
667 // is a free region, it will outlive the points. But we can
668 // only consider the option `O` if `O: LB`.
669 choice_regions
.retain(|&o_r
| {
671 .universal_regions_outlived_by(scc
)
672 .all(|lb
| self.universal_region_relations
.outlives(o_r
, lb
))
674 debug
!("apply_member_constraint: after lb, choice_regions={:?}", choice_regions
);
676 // Now find all the *upper bounds* -- that is, each UB is a
677 // free region that must outlive the member region `R0` (`UB:
678 // R0`). Therefore, we need only keep an option `O` if `UB: O`
680 if choice_regions
.len() > 1 {
681 let universal_region_relations
= self.universal_region_relations
.clone();
682 let rev_constraint_graph
= self.rev_constraint_graph();
683 for ub
in self.upper_bounds(scc
, &rev_constraint_graph
) {
684 debug
!("apply_member_constraint: ub={:?}", ub
);
685 choice_regions
.retain(|&o_r
| universal_region_relations
.outlives(ub
, o_r
));
687 debug
!("apply_member_constraint: after ub, choice_regions={:?}", choice_regions
);
690 // If we ruled everything out, we're done.
691 if choice_regions
.is_empty() {
695 // Otherwise, we need to find the minimum remaining choice, if
696 // any, and take that.
697 debug
!("apply_member_constraint: choice_regions remaining are {:#?}", choice_regions
);
698 let min
= |r1
: ty
::RegionVid
, r2
: ty
::RegionVid
| -> Option
<ty
::RegionVid
> {
699 let r1_outlives_r2
= self.universal_region_relations
.outlives(r1
, r2
);
700 let r2_outlives_r1
= self.universal_region_relations
.outlives(r2
, r1
);
701 match (r1_outlives_r2
, r2_outlives_r1
) {
702 (true, true) => Some(r1
.min(r2
)),
703 (true, false) => Some(r2
),
704 (false, true) => Some(r1
),
705 (false, false) => None
,
708 let mut min_choice
= choice_regions
[0];
709 for &other_option
in &choice_regions
[1..] {
711 "apply_member_constraint: min_choice={:?} other_option={:?}",
712 min_choice
, other_option
,
714 match min(min_choice
, other_option
) {
715 Some(m
) => min_choice
= m
,
718 "apply_member_constraint: {:?} and {:?} are incomparable; no min choice",
719 min_choice
, other_option
,
726 let min_choice_scc
= self.constraint_sccs
.scc(min_choice
);
728 "apply_member_constraint: min_choice={:?} best_choice_scc={:?}",
729 min_choice
, min_choice_scc
,
731 if self.scc_values
.add_region(scc
, min_choice_scc
) {
732 self.member_constraints_applied
.push(AppliedMemberConstraint
{
733 member_region_scc
: scc
,
735 member_constraint_index
,
744 /// Compute and return the reverse SCC-based constraint graph (lazilly).
747 scc0
: ConstraintSccIndex
,
748 rev_constraint_graph
: &'a VecGraph
<ConstraintSccIndex
>,
749 ) -> impl Iterator
<Item
= RegionVid
> + 'a
{
750 let scc_values
= &self.scc_values
;
751 let mut duplicates
= FxHashSet
::default();
753 .depth_first_search(scc0
)
755 .flat_map(move |scc1
| scc_values
.universal_regions_outlived_by(scc1
))
756 .filter(move |&r
| duplicates
.insert(r
))
759 /// Compute and return the reverse SCC-based constraint graph (lazilly).
760 fn rev_constraint_graph(&mut self) -> Rc
<VecGraph
<ConstraintSccIndex
>> {
761 if let Some(g
) = &self.rev_constraint_graph
{
765 let rev_graph
= Rc
::new(self.constraint_sccs
.reverse());
766 self.rev_constraint_graph
= Some(rev_graph
.clone());
770 /// Returns `true` if all the elements in the value of `scc_b` are nameable
771 /// in `scc_a`. Used during constraint propagation, and only once
772 /// the value of `scc_b` has been computed.
773 fn universe_compatible(&self, scc_b
: ConstraintSccIndex
, scc_a
: ConstraintSccIndex
) -> bool
{
774 let universe_a
= self.scc_universes
[scc_a
];
776 // Quick check: if scc_b's declared universe is a subset of
777 // scc_a's declared univese (typically, both are ROOT), then
778 // it cannot contain any problematic universe elements.
779 if universe_a
.can_name(self.scc_universes
[scc_b
]) {
783 // Otherwise, we have to iterate over the universe elements in
784 // B's value, and check whether all of them are nameable
786 self.scc_values
.placeholders_contained_in(scc_b
).all(|p
| universe_a
.can_name(p
.universe
))
789 /// Extend `scc` so that it can outlive some placeholder region
790 /// from a universe it can't name; at present, the only way for
791 /// this to be true is if `scc` outlives `'static`. This is
792 /// actually stricter than necessary: ideally, we'd support bounds
793 /// like `for<'a: 'b`>` that might then allow us to approximate
794 /// `'a` with `'b` and not `'static`. But it will have to do for
796 fn add_incompatible_universe(&mut self, scc
: ConstraintSccIndex
) {
797 debug
!("add_incompatible_universe(scc={:?})", scc
);
799 let fr_static
= self.universal_regions
.fr_static
;
800 self.scc_values
.add_all_points(scc
);
801 self.scc_values
.add_element(scc
, fr_static
);
804 /// Once regions have been propagated, this method is used to see
805 /// whether the "type tests" produced by typeck were satisfied;
806 /// type tests encode type-outlives relationships like `T:
807 /// 'a`. See `TypeTest` for more details.
810 infcx
: &InferCtxt
<'_
, 'tcx
>,
812 mut propagated_outlives_requirements
: Option
<&mut Vec
<ClosureOutlivesRequirement
<'tcx
>>>,
813 errors_buffer
: &mut RegionErrors
<'tcx
>,
817 // Sometimes we register equivalent type-tests that would
818 // result in basically the exact same error being reported to
819 // the user. Avoid that.
820 let mut deduplicate_errors
= FxHashSet
::default();
822 for type_test
in &self.type_tests
{
823 debug
!("check_type_test: {:?}", type_test
);
825 let generic_ty
= type_test
.generic_kind
.to_ty(tcx
);
826 if self.eval_verify_bound(
830 type_test
.lower_bound
,
831 &type_test
.verify_bound
,
836 if let Some(propagated_outlives_requirements
) = &mut propagated_outlives_requirements
{
837 if self.try_promote_type_test(
841 propagated_outlives_requirements
,
847 // Type-test failed. Report the error.
848 let erased_generic_kind
= infcx
.tcx
.erase_regions(&type_test
.generic_kind
);
850 // Skip duplicate-ish errors.
851 if deduplicate_errors
.insert((
853 type_test
.lower_bound
,
857 "check_type_test: reporting error for erased_generic_kind={:?}, \
858 lower_bound_region={:?}, \
859 type_test.locations={:?}",
860 erased_generic_kind
, type_test
.lower_bound
, type_test
.locations
,
863 errors_buffer
.push(RegionErrorKind
::TypeTestError { type_test: type_test.clone() }
);
868 /// Invoked when we have some type-test (e.g., `T: 'X`) that we cannot
869 /// prove to be satisfied. If this is a closure, we will attempt to
870 /// "promote" this type-test into our `ClosureRegionRequirements` and
871 /// hence pass it up the creator. To do this, we have to phrase the
872 /// type-test in terms of external free regions, as local free
873 /// regions are not nameable by the closure's creator.
875 /// Promotion works as follows: we first check that the type `T`
876 /// contains only regions that the creator knows about. If this is
877 /// true, then -- as a consequence -- we know that all regions in
878 /// the type `T` are free regions that outlive the closure body. If
879 /// false, then promotion fails.
881 /// Once we've promoted T, we have to "promote" `'X` to some region
882 /// that is "external" to the closure. Generally speaking, a region
883 /// may be the union of some points in the closure body as well as
884 /// various free lifetimes. We can ignore the points in the closure
885 /// body: if the type T can be expressed in terms of external regions,
886 /// we know it outlives the points in the closure body. That
887 /// just leaves the free regions.
889 /// The idea then is to lower the `T: 'X` constraint into multiple
890 /// bounds -- e.g., if `'X` is the union of two free lifetimes,
891 /// `'1` and `'2`, then we would create `T: '1` and `T: '2`.
892 fn try_promote_type_test(
894 infcx
: &InferCtxt
<'_
, 'tcx
>,
896 type_test
: &TypeTest
<'tcx
>,
897 propagated_outlives_requirements
: &mut Vec
<ClosureOutlivesRequirement
<'tcx
>>,
901 let TypeTest { generic_kind, lower_bound, locations, verify_bound: _ }
= type_test
;
903 let generic_ty
= generic_kind
.to_ty(tcx
);
904 let subject
= match self.try_promote_type_test_subject(infcx
, generic_ty
) {
906 None
=> return false,
909 // For each region outlived by lower_bound find a non-local,
910 // universal region (it may be the same region) and add it to
911 // `ClosureOutlivesRequirement`.
912 let r_scc
= self.constraint_sccs
.scc(*lower_bound
);
913 for ur
in self.scc_values
.universal_regions_outlived_by(r_scc
) {
914 // Check whether we can already prove that the "subject" outlives `ur`.
915 // If so, we don't have to propagate this requirement to our caller.
917 // To continue the example from the function, if we are trying to promote
918 // a requirement that `T: 'X`, and we know that `'X = '1 + '2` (i.e., the union
919 // `'1` and `'2`), then in this loop `ur` will be `'1` (and `'2`). So here
920 // we check whether `T: '1` is something we *can* prove. If so, no need
921 // to propagate that requirement.
923 // This is needed because -- particularly in the case
924 // where `ur` is a local bound -- we are sometimes in a
925 // position to prove things that our caller cannot. See
926 // #53570 for an example.
927 if self.eval_verify_bound(tcx
, body
, generic_ty
, ur
, &type_test
.verify_bound
) {
931 debug
!("try_promote_type_test: ur={:?}", ur
);
933 let non_local_ub
= self.universal_region_relations
.non_local_upper_bounds(&ur
);
934 debug
!("try_promote_type_test: non_local_ub={:?}", non_local_ub
);
936 // This is slightly too conservative. To show T: '1, given `'2: '1`
937 // and `'3: '1` we only need to prove that T: '2 *or* T: '3, but to
938 // avoid potential non-determinism we approximate this by requiring
940 for &upper_bound
in non_local_ub
{
941 debug_assert
!(self.universal_regions
.is_universal_region(upper_bound
));
942 debug_assert
!(!self.universal_regions
.is_local_free_region(upper_bound
));
944 let requirement
= ClosureOutlivesRequirement
{
946 outlived_free_region
: upper_bound
,
947 blame_span
: locations
.span(body
),
948 category
: ConstraintCategory
::Boring
,
950 debug
!("try_promote_type_test: pushing {:#?}", requirement
);
951 propagated_outlives_requirements
.push(requirement
);
957 /// When we promote a type test `T: 'r`, we have to convert the
958 /// type `T` into something we can store in a query result (so
959 /// something allocated for `'tcx`). This is problematic if `ty`
960 /// contains regions. During the course of NLL region checking, we
961 /// will have replaced all of those regions with fresh inference
962 /// variables. To create a test subject, we want to replace those
963 /// inference variables with some region from the closure
964 /// signature -- this is not always possible, so this is a
965 /// fallible process. Presuming we do find a suitable region, we
966 /// will represent it with a `ReClosureBound`, which is a
967 /// `RegionKind` variant that can be allocated in the gcx.
968 fn try_promote_type_test_subject(
970 infcx
: &InferCtxt
<'_
, 'tcx
>,
972 ) -> Option
<ClosureOutlivesSubject
<'tcx
>> {
975 debug
!("try_promote_type_test_subject(ty = {:?})", ty
);
977 let ty
= tcx
.fold_regions(&ty
, &mut false, |r
, _depth
| {
978 let region_vid
= self.to_region_vid(r
);
980 // The challenge if this. We have some region variable `r`
981 // whose value is a set of CFG points and universal
982 // regions. We want to find if that set is *equivalent* to
983 // any of the named regions found in the closure.
985 // To do so, we compute the
986 // `non_local_universal_upper_bound`. This will be a
987 // non-local, universal region that is greater than `r`.
988 // However, it might not be *contained* within `r`, so
989 // then we further check whether this bound is contained
990 // in `r`. If so, we can say that `r` is equivalent to the
993 // Let's work through a few examples. For these, imagine
994 // that we have 3 non-local regions (I'll denote them as
995 // `'static`, `'a`, and `'b`, though of course in the code
996 // they would be represented with indices) where:
1001 // First, let's assume that `r` is some existential
1002 // variable with an inferred value `{'a, 'static}` (plus
1003 // some CFG nodes). In this case, the non-local upper
1004 // bound is `'static`, since that outlives `'a`. `'static`
1005 // is also a member of `r` and hence we consider `r`
1006 // equivalent to `'static` (and replace it with
1009 // Now let's consider the inferred value `{'a, 'b}`. This
1010 // means `r` is effectively `'a | 'b`. I'm not sure if
1011 // this can come about, actually, but assuming it did, we
1012 // would get a non-local upper bound of `'static`. Since
1013 // `'static` is not contained in `r`, we would fail to
1014 // find an equivalent.
1015 let upper_bound
= self.non_local_universal_upper_bound(region_vid
);
1016 if self.region_contains(region_vid
, upper_bound
) {
1017 tcx
.mk_region(ty
::ReClosureBound(upper_bound
))
1019 // In the case of a failure, use a `ReVar`
1020 // result. This will cause the `lift` later on to
1025 debug
!("try_promote_type_test_subject: folded ty = {:?}", ty
);
1027 // `has_local_value` will only be true if we failed to promote some region.
1028 if ty
.has_local_value() {
1032 Some(ClosureOutlivesSubject
::Ty(ty
))
1035 /// Given some universal or existential region `r`, finds a
1036 /// non-local, universal region `r+` that outlives `r` at entry to (and
1037 /// exit from) the closure. In the worst case, this will be
1040 /// This is used for two purposes. First, if we are propagated
1041 /// some requirement `T: r`, we can use this method to enlarge `r`
1042 /// to something we can encode for our creator (which only knows
1043 /// about non-local, universal regions). It is also used when
1044 /// encoding `T` as part of `try_promote_type_test_subject` (see
1045 /// that fn for details).
1047 /// This is based on the result `'y` of `universal_upper_bound`,
1048 /// except that it converts further takes the non-local upper
1049 /// bound of `'y`, so that the final result is non-local.
1050 fn non_local_universal_upper_bound(&self, r
: RegionVid
) -> RegionVid
{
1051 debug
!("non_local_universal_upper_bound(r={:?}={})", r
, self.region_value_str(r
));
1053 let lub
= self.universal_upper_bound(r
);
1055 // Grow further to get smallest universal region known to
1057 let non_local_lub
= self.universal_region_relations
.non_local_upper_bound(lub
);
1059 debug
!("non_local_universal_upper_bound: non_local_lub={:?}", non_local_lub
);
1064 /// Returns a universally quantified region that outlives the
1065 /// value of `r` (`r` may be existentially or universally
1068 /// Since `r` is (potentially) an existential region, it has some
1069 /// value which may include (a) any number of points in the CFG
1070 /// and (b) any number of `end('x)` elements of universally
1071 /// quantified regions. To convert this into a single universal
1072 /// region we do as follows:
1074 /// - Ignore the CFG points in `'r`. All universally quantified regions
1075 /// include the CFG anyhow.
1076 /// - For each `end('x)` element in `'r`, compute the mutual LUB, yielding
1078 pub(in crate::borrow_check
) fn universal_upper_bound(&self, r
: RegionVid
) -> RegionVid
{
1079 debug
!("universal_upper_bound(r={:?}={})", r
, self.region_value_str(r
));
1081 // Find the smallest universal region that contains all other
1082 // universal regions within `region`.
1083 let mut lub
= self.universal_regions
.fr_fn_body
;
1084 let r_scc
= self.constraint_sccs
.scc(r
);
1085 for ur
in self.scc_values
.universal_regions_outlived_by(r_scc
) {
1086 lub
= self.universal_region_relations
.postdom_upper_bound(lub
, ur
);
1089 debug
!("universal_upper_bound: r={:?} lub={:?}", r
, lub
);
1094 /// Tests if `test` is true when applied to `lower_bound` at
1096 fn eval_verify_bound(
1100 generic_ty
: Ty
<'tcx
>,
1101 lower_bound
: RegionVid
,
1102 verify_bound
: &VerifyBound
<'tcx
>,
1104 debug
!("eval_verify_bound(lower_bound={:?}, verify_bound={:?})", lower_bound
, verify_bound
);
1106 match verify_bound
{
1107 VerifyBound
::IfEq(test_ty
, verify_bound1
) => {
1108 self.eval_if_eq(tcx
, body
, generic_ty
, lower_bound
, test_ty
, verify_bound1
)
1111 VerifyBound
::OutlivedBy(r
) => {
1112 let r_vid
= self.to_region_vid(r
);
1113 self.eval_outlives(r_vid
, lower_bound
)
1116 VerifyBound
::AnyBound(verify_bounds
) => verify_bounds
.iter().any(|verify_bound
| {
1117 self.eval_verify_bound(tcx
, body
, generic_ty
, lower_bound
, verify_bound
)
1120 VerifyBound
::AllBounds(verify_bounds
) => verify_bounds
.iter().all(|verify_bound
| {
1121 self.eval_verify_bound(tcx
, body
, generic_ty
, lower_bound
, verify_bound
)
1130 generic_ty
: Ty
<'tcx
>,
1131 lower_bound
: RegionVid
,
1133 verify_bound
: &VerifyBound
<'tcx
>,
1135 let generic_ty_normalized
= self.normalize_to_scc_representatives(tcx
, generic_ty
);
1136 let test_ty_normalized
= self.normalize_to_scc_representatives(tcx
, test_ty
);
1137 if generic_ty_normalized
== test_ty_normalized
{
1138 self.eval_verify_bound(tcx
, body
, generic_ty
, lower_bound
, verify_bound
)
1144 /// This is a conservative normalization procedure. It takes every
1145 /// free region in `value` and replaces it with the
1146 /// "representative" of its SCC (see `scc_representatives` field).
1147 /// We are guaranteed that if two values normalize to the same
1148 /// thing, then they are equal; this is a conservative check in
1149 /// that they could still be equal even if they normalize to
1150 /// different results. (For example, there might be two regions
1151 /// with the same value that are not in the same SCC).
1153 /// N.B., this is not an ideal approach and I would like to revisit
1154 /// it. However, it works pretty well in practice. In particular,
1155 /// this is needed to deal with projection outlives bounds like
1157 /// <T as Foo<'0>>::Item: '1
1159 /// In particular, this routine winds up being important when
1160 /// there are bounds like `where <T as Foo<'a>>::Item: 'b` in the
1161 /// environment. In this case, if we can show that `'0 == 'a`,
1162 /// and that `'b: '1`, then we know that the clause is
1163 /// satisfied. In such cases, particularly due to limitations of
1164 /// the trait solver =), we usually wind up with a where-clause like
1165 /// `T: Foo<'a>` in scope, which thus forces `'0 == 'a` to be added as
1166 /// a constraint, and thus ensures that they are in the same SCC.
1168 /// So why can't we do a more correct routine? Well, we could
1169 /// *almost* use the `relate_tys` code, but the way it is
1170 /// currently setup it creates inference variables to deal with
1171 /// higher-ranked things and so forth, and right now the inference
1172 /// context is not permitted to make more inference variables. So
1173 /// we use this kind of hacky solution.
1174 fn normalize_to_scc_representatives
<T
>(&self, tcx
: TyCtxt
<'tcx
>, value
: T
) -> T
1176 T
: TypeFoldable
<'tcx
>,
1178 tcx
.fold_regions(&value
, &mut false, |r
, _db
| {
1179 let vid
= self.to_region_vid(r
);
1180 let scc
= self.constraint_sccs
.scc(vid
);
1181 let repr
= self.scc_representatives
[scc
];
1182 tcx
.mk_region(ty
::ReVar(repr
))
1186 // Evaluate whether `sup_region == sub_region`.
1187 fn eval_equal(&self, r1
: RegionVid
, r2
: RegionVid
) -> bool
{
1188 self.eval_outlives(r1
, r2
) && self.eval_outlives(r2
, r1
)
1191 // Evaluate whether `sup_region: sub_region`.
1192 fn eval_outlives(&self, sup_region
: RegionVid
, sub_region
: RegionVid
) -> bool
{
1193 debug
!("eval_outlives({:?}: {:?})", sup_region
, sub_region
);
1196 "eval_outlives: sup_region's value = {:?} universal={:?}",
1197 self.region_value_str(sup_region
),
1198 self.universal_regions
.is_universal_region(sup_region
),
1201 "eval_outlives: sub_region's value = {:?} universal={:?}",
1202 self.region_value_str(sub_region
),
1203 self.universal_regions
.is_universal_region(sub_region
),
1206 let sub_region_scc
= self.constraint_sccs
.scc(sub_region
);
1207 let sup_region_scc
= self.constraint_sccs
.scc(sup_region
);
1209 // Both the `sub_region` and `sup_region` consist of the union
1210 // of some number of universal regions (along with the union
1211 // of various points in the CFG; ignore those points for
1212 // now). Therefore, the sup-region outlives the sub-region if,
1213 // for each universal region R1 in the sub-region, there
1214 // exists some region R2 in the sup-region that outlives R1.
1215 let universal_outlives
=
1216 self.scc_values
.universal_regions_outlived_by(sub_region_scc
).all(|r1
| {
1218 .universal_regions_outlived_by(sup_region_scc
)
1219 .any(|r2
| self.universal_region_relations
.outlives(r2
, r1
))
1222 if !universal_outlives
{
1226 // Now we have to compare all the points in the sub region and make
1227 // sure they exist in the sup region.
1229 if self.universal_regions
.is_universal_region(sup_region
) {
1230 // Micro-opt: universal regions contain all points.
1234 self.scc_values
.contains_points(sup_region_scc
, sub_region_scc
)
1237 /// Once regions have been propagated, this method is used to see
1238 /// whether any of the constraints were too strong. In particular,
1239 /// we want to check for a case where a universally quantified
1240 /// region exceeded its bounds. Consider:
1242 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1244 /// In this case, returning `x` requires `&'a u32 <: &'b u32`
1245 /// and hence we establish (transitively) a constraint that
1246 /// `'a: 'b`. The `propagate_constraints` code above will
1247 /// therefore add `end('a)` into the region for `'b` -- but we
1248 /// have no evidence that `'b` outlives `'a`, so we want to report
1251 /// If `propagated_outlives_requirements` is `Some`, then we will
1252 /// push unsatisfied obligations into there. Otherwise, we'll
1253 /// report them as errors.
1254 fn check_universal_regions(
1257 mut propagated_outlives_requirements
: Option
<&mut Vec
<ClosureOutlivesRequirement
<'tcx
>>>,
1258 errors_buffer
: &mut RegionErrors
<'tcx
>,
1260 for (fr
, fr_definition
) in self.definitions
.iter_enumerated() {
1261 match fr_definition
.origin
{
1262 NLLRegionVariableOrigin
::FreeRegion
=> {
1263 // Go through each of the universal regions `fr` and check that
1264 // they did not grow too large, accumulating any requirements
1265 // for our caller into the `outlives_requirements` vector.
1266 self.check_universal_region(
1269 &mut propagated_outlives_requirements
,
1274 NLLRegionVariableOrigin
::Placeholder(placeholder
) => {
1275 self.check_bound_universal_region(fr
, placeholder
, errors_buffer
);
1278 NLLRegionVariableOrigin
::Existential { .. }
=> {
1279 // nothing to check here
1285 /// Checks if Polonius has found any unexpected free region relations.
1287 /// In Polonius terms, a "subset error" (or "illegal subset relation error") is the equivalent
1288 /// of NLL's "checking if any region constraints were too strong": a placeholder origin `'a`
1289 /// was unexpectedly found to be a subset of another placeholder origin `'b`, and means in NLL
1290 /// terms that the "longer free region" `'a` outlived the "shorter free region" `'b`.
1292 /// More details can be found in this blog post by Niko:
1293 /// http://smallcultfollowing.com/babysteps/blog/2019/01/17/polonius-and-region-errors/
1295 /// In the canonical example
1297 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
1299 /// returning `x` requires `&'a u32 <: &'b u32` and hence we establish (transitively) a
1300 /// constraint that `'a: 'b`. It is an error that we have no evidence that this
1301 /// constraint holds.
1303 /// If `propagated_outlives_requirements` is `Some`, then we will
1304 /// push unsatisfied obligations into there. Otherwise, we'll
1305 /// report them as errors.
1306 fn check_polonius_subset_errors(
1309 mut propagated_outlives_requirements
: Option
<&mut Vec
<ClosureOutlivesRequirement
<'tcx
>>>,
1310 errors_buffer
: &mut RegionErrors
<'tcx
>,
1311 polonius_output
: Rc
<PoloniusOutput
>,
1314 "check_polonius_subset_errors: {} subset_errors",
1315 polonius_output
.subset_errors
.len()
1318 // Similarly to `check_universal_regions`: a free region relation, which was not explicitly
1319 // declared ("known") was found by Polonius, so emit an error, or propagate the
1320 // requirements for our caller into the `propagated_outlives_requirements` vector.
1322 // Polonius doesn't model regions ("origins") as CFG-subsets or durations, but the
1323 // `longer_fr` and `shorter_fr` terminology will still be used here, for consistency with
1324 // the rest of the NLL infrastructure. The "subset origin" is the "longer free region",
1325 // and the "superset origin" is the outlived "shorter free region".
1327 // Note: Polonius will produce a subset error at every point where the unexpected
1328 // `longer_fr`'s "placeholder loan" is contained in the `shorter_fr`. This can be helpful
1329 // for diagnostics in the future, e.g. to point more precisely at the key locations
1330 // requiring this constraint to hold. However, the error and diagnostics code downstream
1331 // expects that these errors are not duplicated (and that they are in a certain order).
1332 // Otherwise, diagnostics messages such as the ones giving names like `'1` to elided or
1333 // anonymous lifetimes for example, could give these names differently, while others like
1334 // the outlives suggestions or the debug output from `#[rustc_regions]` would be
1335 // duplicated. The polonius subset errors are deduplicated here, while keeping the
1336 // CFG-location ordering.
1337 let mut subset_errors
: Vec
<_
> = polonius_output
1340 .flat_map(|(_location
, subset_errors
)| subset_errors
.iter())
1342 subset_errors
.sort();
1343 subset_errors
.dedup();
1345 for (longer_fr
, shorter_fr
) in subset_errors
.into_iter() {
1347 "check_polonius_subset_errors: subset_error longer_fr={:?},\
1349 longer_fr
, shorter_fr
1352 let propagated
= self.try_propagate_universal_region_error(
1356 &mut propagated_outlives_requirements
,
1358 if propagated
== RegionRelationCheckResult
::Error
{
1359 errors_buffer
.push(RegionErrorKind
::RegionError
{
1360 longer_fr
: *longer_fr
,
1361 shorter_fr
: *shorter_fr
,
1362 fr_origin
: NLLRegionVariableOrigin
::FreeRegion
,
1368 // Handle the placeholder errors as usual, until the chalk-rustc-polonius triumvirate has
1369 // a more complete picture on how to separate this responsibility.
1370 for (fr
, fr_definition
) in self.definitions
.iter_enumerated() {
1371 match fr_definition
.origin
{
1372 NLLRegionVariableOrigin
::FreeRegion
=> {
1373 // handled by polonius above
1376 NLLRegionVariableOrigin
::Placeholder(placeholder
) => {
1377 self.check_bound_universal_region(fr
, placeholder
, errors_buffer
);
1380 NLLRegionVariableOrigin
::Existential { .. }
=> {
1381 // nothing to check here
1387 /// Checks the final value for the free region `fr` to see if it
1388 /// grew too large. In particular, examine what `end(X)` points
1389 /// wound up in `fr`'s final value; for each `end(X)` where `X !=
1390 /// fr`, we want to check that `fr: X`. If not, that's either an
1391 /// error, or something we have to propagate to our creator.
1393 /// Things that are to be propagated are accumulated into the
1394 /// `outlives_requirements` vector.
1395 fn check_universal_region(
1398 longer_fr
: RegionVid
,
1399 propagated_outlives_requirements
: &mut Option
<&mut Vec
<ClosureOutlivesRequirement
<'tcx
>>>,
1400 errors_buffer
: &mut RegionErrors
<'tcx
>,
1402 debug
!("check_universal_region(fr={:?})", longer_fr
);
1404 let longer_fr_scc
= self.constraint_sccs
.scc(longer_fr
);
1406 // Because this free region must be in the ROOT universe, we
1407 // know it cannot contain any bound universes.
1408 assert
!(self.scc_universes
[longer_fr_scc
] == ty
::UniverseIndex
::ROOT
);
1409 debug_assert
!(self.scc_values
.placeholders_contained_in(longer_fr_scc
).next().is_none());
1411 // Only check all of the relations for the main representative of each
1412 // SCC, otherwise just check that we outlive said representative. This
1413 // reduces the number of redundant relations propagated out of
1415 // Note that the representative will be a universal region if there is
1416 // one in this SCC, so we will always check the representative here.
1417 let representative
= self.scc_representatives
[longer_fr_scc
];
1418 if representative
!= longer_fr
{
1419 if let RegionRelationCheckResult
::Error
= self.check_universal_region_relation(
1423 propagated_outlives_requirements
,
1425 errors_buffer
.push(RegionErrorKind
::RegionError
{
1427 shorter_fr
: representative
,
1428 fr_origin
: NLLRegionVariableOrigin
::FreeRegion
,
1435 // Find every region `o` such that `fr: o`
1436 // (because `fr` includes `end(o)`).
1437 let mut error_reported
= false;
1438 for shorter_fr
in self.scc_values
.universal_regions_outlived_by(longer_fr_scc
) {
1439 if let RegionRelationCheckResult
::Error
= self.check_universal_region_relation(
1443 propagated_outlives_requirements
,
1445 // We only report the first region error. Subsequent errors are hidden so as
1446 // not to overwhelm the user, but we do record them so as to potentially print
1447 // better diagnostics elsewhere...
1448 errors_buffer
.push(RegionErrorKind
::RegionError
{
1451 fr_origin
: NLLRegionVariableOrigin
::FreeRegion
,
1452 is_reported
: !error_reported
,
1455 error_reported
= true;
1460 /// Checks that we can prove that `longer_fr: shorter_fr`. If we can't we attempt to propagate
1461 /// the constraint outward (e.g. to a closure environment), but if that fails, there is an
1463 fn check_universal_region_relation(
1465 longer_fr
: RegionVid
,
1466 shorter_fr
: RegionVid
,
1468 propagated_outlives_requirements
: &mut Option
<&mut Vec
<ClosureOutlivesRequirement
<'tcx
>>>,
1469 ) -> RegionRelationCheckResult
{
1470 // If it is known that `fr: o`, carry on.
1471 if self.universal_region_relations
.outlives(longer_fr
, shorter_fr
) {
1472 RegionRelationCheckResult
::Ok
1474 // If we are not in a context where we can't propagate errors, or we
1475 // could not shrink `fr` to something smaller, then just report an
1478 // Note: in this case, we use the unapproximated regions to report the
1479 // error. This gives better error messages in some cases.
1480 self.try_propagate_universal_region_error(
1484 propagated_outlives_requirements
,
1489 /// Attempt to propagate a region error (e.g. `'a: 'b`) that is not met to a closure's
1490 /// creator. If we cannot, then the caller should report an error to the user.
1491 fn try_propagate_universal_region_error(
1493 longer_fr
: RegionVid
,
1494 shorter_fr
: RegionVid
,
1496 propagated_outlives_requirements
: &mut Option
<&mut Vec
<ClosureOutlivesRequirement
<'tcx
>>>,
1497 ) -> RegionRelationCheckResult
{
1498 if let Some(propagated_outlives_requirements
) = propagated_outlives_requirements
{
1499 // Shrink `longer_fr` until we find a non-local region (if we do).
1500 // We'll call it `fr-` -- it's ever so slightly smaller than
1502 if let Some(fr_minus
) = self.universal_region_relations
.non_local_lower_bound(longer_fr
)
1504 debug
!("try_propagate_universal_region_error: fr_minus={:?}", fr_minus
);
1506 let blame_span_category
= self.find_outlives_blame_span(
1509 NLLRegionVariableOrigin
::FreeRegion
,
1513 // Grow `shorter_fr` until we find some non-local regions. (We
1514 // always will.) We'll call them `shorter_fr+` -- they're ever
1515 // so slightly larger than `shorter_fr`.
1516 let shorter_fr_plus
=
1517 self.universal_region_relations
.non_local_upper_bounds(&shorter_fr
);
1519 "try_propagate_universal_region_error: shorter_fr_plus={:?}",
1522 for &&fr
in &shorter_fr_plus
{
1523 // Push the constraint `fr-: shorter_fr+`
1524 propagated_outlives_requirements
.push(ClosureOutlivesRequirement
{
1525 subject
: ClosureOutlivesSubject
::Region(fr_minus
),
1526 outlived_free_region
: fr
,
1527 blame_span
: blame_span_category
.1,
1528 category
: blame_span_category
.0,
1531 return RegionRelationCheckResult
::Propagated
;
1535 RegionRelationCheckResult
::Error
1538 fn check_bound_universal_region(
1540 longer_fr
: RegionVid
,
1541 placeholder
: ty
::PlaceholderRegion
,
1542 errors_buffer
: &mut RegionErrors
<'tcx
>,
1544 debug
!("check_bound_universal_region(fr={:?}, placeholder={:?})", longer_fr
, placeholder
,);
1546 let longer_fr_scc
= self.constraint_sccs
.scc(longer_fr
);
1547 debug
!("check_bound_universal_region: longer_fr_scc={:?}", longer_fr_scc
,);
1549 // If we have some bound universal region `'a`, then the only
1550 // elements it can contain is itself -- we don't know anything
1552 let error_element
= match {
1553 self.scc_values
.elements_contained_in(longer_fr_scc
).find(|element
| match element
{
1554 RegionElement
::Location(_
) => true,
1555 RegionElement
::RootUniversalRegion(_
) => true,
1556 RegionElement
::PlaceholderRegion(placeholder1
) => placeholder
!= *placeholder1
,
1562 debug
!("check_bound_universal_region: error_element = {:?}", error_element
);
1564 // Find the region that introduced this `error_element`.
1565 errors_buffer
.push(RegionErrorKind
::BoundUniversalRegionError
{
1568 fr_origin
: NLLRegionVariableOrigin
::Placeholder(placeholder
),
1572 fn check_member_constraints(
1574 infcx
: &InferCtxt
<'_
, 'tcx
>,
1575 errors_buffer
: &mut RegionErrors
<'tcx
>,
1577 let member_constraints
= self.member_constraints
.clone();
1578 for m_c_i
in member_constraints
.all_indices() {
1579 debug
!("check_member_constraint(m_c_i={:?})", m_c_i
);
1580 let m_c
= &member_constraints
[m_c_i
];
1581 let member_region_vid
= m_c
.member_region_vid
;
1583 "check_member_constraint: member_region_vid={:?} with value {}",
1585 self.region_value_str(member_region_vid
),
1587 let choice_regions
= member_constraints
.choice_regions(m_c_i
);
1588 debug
!("check_member_constraint: choice_regions={:?}", choice_regions
);
1590 // Did the member region wind up equal to any of the option regions?
1592 choice_regions
.iter().find(|&&o_r
| self.eval_equal(o_r
, m_c
.member_region_vid
))
1594 debug
!("check_member_constraint: evaluated as equal to {:?}", o
);
1598 // If not, report an error.
1599 let member_region
= infcx
.tcx
.mk_region(ty
::ReVar(member_region_vid
));
1600 errors_buffer
.push(RegionErrorKind
::UnexpectedHiddenRegion
{
1601 opaque_type_def_id
: m_c
.opaque_type_def_id
,
1602 hidden_ty
: m_c
.hidden_ty
,
1608 /// We have a constraint `fr1: fr2` that is not satisfied, where
1609 /// `fr2` represents some universal region. Here, `r` is some
1610 /// region where we know that `fr1: r` and this function has the
1611 /// job of determining whether `r` is "to blame" for the fact that
1612 /// `fr1: fr2` is required.
1614 /// This is true under two conditions:
1617 /// - `fr2` is `'static` and `r` is some placeholder in a universe
1618 /// that cannot be named by `fr1`; in that case, we will require
1619 /// that `fr1: 'static` because it is the only way to `fr1: r` to
1620 /// be satisfied. (See `add_incompatible_universe`.)
1621 crate fn provides_universal_region(
1627 debug
!("provides_universal_region(r={:?}, fr1={:?}, fr2={:?})", r
, fr1
, fr2
);
1630 fr2
== self.universal_regions
.fr_static
&& self.cannot_name_placeholder(fr1
, r
)
1633 debug
!("provides_universal_region: result = {:?}", result
);
1637 /// If `r2` represents a placeholder region, then this returns
1638 /// `true` if `r1` cannot name that placeholder in its
1639 /// value; otherwise, returns `false`.
1640 crate fn cannot_name_placeholder(&self, r1
: RegionVid
, r2
: RegionVid
) -> bool
{
1641 debug
!("cannot_name_value_of(r1={:?}, r2={:?})", r1
, r2
);
1643 match self.definitions
[r2
].origin
{
1644 NLLRegionVariableOrigin
::Placeholder(placeholder
) => {
1645 let universe1
= self.definitions
[r1
].universe
;
1647 "cannot_name_value_of: universe1={:?} placeholder={:?}",
1648 universe1
, placeholder
1650 universe1
.cannot_name(placeholder
.universe
)
1653 NLLRegionVariableOrigin
::FreeRegion
| NLLRegionVariableOrigin
::Existential { .. }
=> {
1659 crate fn retrieve_closure_constraint_info(
1662 constraint
: &OutlivesConstraint
,
1663 ) -> (ConstraintCategory
, bool
, Span
) {
1664 let loc
= match constraint
.locations
{
1665 Locations
::All(span
) => return (constraint
.category
, false, span
),
1666 Locations
::Single(loc
) => loc
,
1669 let opt_span_category
=
1670 self.closure_bounds_mapping
[&loc
].get(&(constraint
.sup
, constraint
.sub
));
1671 opt_span_category
.map(|&(category
, span
)| (category
, true, span
)).unwrap_or((
1672 constraint
.category
,
1674 body
.source_info(loc
).span
,
1678 /// Finds a good span to blame for the fact that `fr1` outlives `fr2`.
1679 crate fn find_outlives_blame_span(
1683 fr1_origin
: NLLRegionVariableOrigin
,
1685 ) -> (ConstraintCategory
, Span
) {
1686 let (category
, _
, span
) = self.best_blame_constraint(body
, fr1
, fr1_origin
, |r
| {
1687 self.provides_universal_region(r
, fr1
, fr2
)
1692 /// Walks the graph of constraints (where `'a: 'b` is considered
1693 /// an edge `'a -> 'b`) to find all paths from `from_region` to
1694 /// `to_region`. The paths are accumulated into the vector
1695 /// `results`. The paths are stored as a series of
1696 /// `ConstraintIndex` values -- in other words, a list of *edges*.
1698 /// Returns: a series of constraints as well as the region `R`
1699 /// that passed the target test.
1700 crate fn find_constraint_paths_between_regions(
1702 from_region
: RegionVid
,
1703 target_test
: impl Fn(RegionVid
) -> bool
,
1704 ) -> Option
<(Vec
<OutlivesConstraint
>, RegionVid
)> {
1705 let mut context
= IndexVec
::from_elem(Trace
::NotVisited
, &self.definitions
);
1706 context
[from_region
] = Trace
::StartRegion
;
1708 // Use a deque so that we do a breadth-first search. We will
1709 // stop at the first match, which ought to be the shortest
1710 // path (fewest constraints).
1711 let mut deque
= VecDeque
::new();
1712 deque
.push_back(from_region
);
1714 while let Some(r
) = deque
.pop_front() {
1716 "find_constraint_paths_between_regions: from_region={:?} r={:?} value={}",
1719 self.region_value_str(r
),
1722 // Check if we reached the region we were looking for. If so,
1723 // we can reconstruct the path that led to it and return it.
1725 let mut result
= vec
![];
1729 Trace
::NotVisited
=> {
1730 bug
!("found unvisited region {:?} on path to {:?}", p
, r
)
1733 Trace
::FromOutlivesConstraint(c
) => {
1738 Trace
::StartRegion
=> {
1740 return Some((result
, r
));
1746 // Otherwise, walk over the outgoing constraints and
1747 // enqueue any regions we find, keeping track of how we
1750 // A constraint like `'r: 'x` can come from our constraint
1752 let fr_static
= self.universal_regions
.fr_static
;
1753 let outgoing_edges_from_graph
=
1754 self.constraint_graph
.outgoing_edges(r
, &self.constraints
, fr_static
);
1756 // Always inline this closure because it can be hot.
1757 let mut handle_constraint
= #[inline(always)]
1758 |constraint
: OutlivesConstraint
| {
1759 debug_assert_eq
!(constraint
.sup
, r
);
1760 let sub_region
= constraint
.sub
;
1761 if let Trace
::NotVisited
= context
[sub_region
] {
1762 context
[sub_region
] = Trace
::FromOutlivesConstraint(constraint
);
1763 deque
.push_back(sub_region
);
1767 // This loop can be hot.
1768 for constraint
in outgoing_edges_from_graph
{
1769 handle_constraint(constraint
);
1772 // Member constraints can also give rise to `'r: 'x` edges that
1773 // were not part of the graph initially, so watch out for those.
1774 // (But they are extremely rare; this loop is very cold.)
1775 for constraint
in self.applied_member_constraints(r
) {
1776 let p_c
= &self.member_constraints
[constraint
.member_constraint_index
];
1777 let constraint
= OutlivesConstraint
{
1779 sub
: constraint
.min_choice
,
1780 locations
: Locations
::All(p_c
.definition_span
),
1781 category
: ConstraintCategory
::OpaqueType
,
1783 handle_constraint(constraint
);
1790 /// Finds some region R such that `fr1: R` and `R` is live at `elem`.
1791 crate fn find_sub_region_live_at(&self, fr1
: RegionVid
, elem
: Location
) -> RegionVid
{
1792 debug
!("find_sub_region_live_at(fr1={:?}, elem={:?})", fr1
, elem
);
1793 self.find_constraint_paths_between_regions(fr1
, |r
| {
1794 // First look for some `r` such that `fr1: r` and `r` is live at `elem`
1796 "find_sub_region_live_at: liveness_constraints for {:?} are {:?}",
1798 self.liveness_constraints
.region_value_str(r
),
1800 self.liveness_constraints
.contains(r
, elem
)
1803 // If we fail to find that, we may find some `r` such that
1804 // `fr1: r` and `r` is a placeholder from some universe
1805 // `fr1` cannot name. This would force `fr1` to be
1807 self.find_constraint_paths_between_regions(fr1
, |r
| {
1808 self.cannot_name_placeholder(fr1
, r
)
1812 // If we fail to find THAT, it may be that `fr1` is a
1813 // placeholder that cannot "fit" into its SCC. In that
1814 // case, there should be some `r` where `fr1: r`, both
1815 // `fr1` and `r` are in the same SCC, and `fr1` is a
1816 // placeholder that `r` cannot name. We can blame that
1818 self.find_constraint_paths_between_regions(fr1
, |r
| {
1819 self.constraint_sccs
.scc(fr1
) == self.constraint_sccs
.scc(r
)
1820 && self.cannot_name_placeholder(r
, fr1
)
1823 .map(|(_path
, r
)| r
)
1827 /// Get the region outlived by `longer_fr` and live at `element`.
1828 crate fn region_from_element(&self, longer_fr
: RegionVid
, element
: RegionElement
) -> RegionVid
{
1830 RegionElement
::Location(l
) => self.find_sub_region_live_at(longer_fr
, l
),
1831 RegionElement
::RootUniversalRegion(r
) => r
,
1832 RegionElement
::PlaceholderRegion(error_placeholder
) => self
1835 .filter_map(|(r
, definition
)| match definition
.origin
{
1836 NLLRegionVariableOrigin
::Placeholder(p
) if p
== error_placeholder
=> Some(r
),
1844 /// Get the region definition of `r`.
1845 crate fn region_definition(&self, r
: RegionVid
) -> &RegionDefinition
<'tcx
> {
1846 &self.definitions
[r
]
1849 /// Check if the SCC of `r` contains `upper`.
1850 crate fn upper_bound_in_region_scc(&self, r
: RegionVid
, upper
: RegionVid
) -> bool
{
1851 let r_scc
= self.constraint_sccs
.scc(r
);
1852 self.scc_values
.contains(r_scc
, upper
)
1855 crate fn universal_regions(&self) -> &UniversalRegions
<'tcx
> {
1856 self.universal_regions
.as_ref()
1859 /// Tries to find the best constraint to blame for the fact that
1860 /// `R: from_region`, where `R` is some region that meets
1861 /// `target_test`. This works by following the constraint graph,
1862 /// creating a constraint path that forces `R` to outlive
1863 /// `from_region`, and then finding the best choices within that
1865 crate fn best_blame_constraint(
1868 from_region
: RegionVid
,
1869 from_region_origin
: NLLRegionVariableOrigin
,
1870 target_test
: impl Fn(RegionVid
) -> bool
,
1871 ) -> (ConstraintCategory
, bool
, Span
) {
1873 "best_blame_constraint(from_region={:?}, from_region_origin={:?})",
1874 from_region
, from_region_origin
1878 let (path
, target_region
) =
1879 self.find_constraint_paths_between_regions(from_region
, target_test
).unwrap();
1881 "best_blame_constraint: path={:#?}",
1884 "{:?} ({:?}: {:?})",
1886 self.constraint_sccs
.scc(c
.sup
),
1887 self.constraint_sccs
.scc(c
.sub
),
1889 .collect
::<Vec
<_
>>()
1892 // Classify each of the constraints along the path.
1893 let mut categorized_path
: Vec
<(ConstraintCategory
, bool
, Span
)> = path
1896 if constraint
.category
== ConstraintCategory
::ClosureBounds
{
1897 self.retrieve_closure_constraint_info(body
, &constraint
)
1899 (constraint
.category
, false, constraint
.locations
.span(body
))
1903 debug
!("best_blame_constraint: categorized_path={:#?}", categorized_path
);
1905 // To find the best span to cite, we first try to look for the
1906 // final constraint that is interesting and where the `sup` is
1907 // not unified with the ultimate target region. The reason
1908 // for this is that we have a chain of constraints that lead
1909 // from the source to the target region, something like:
1911 // '0: '1 ('0 is the source)
1916 // '5: '6 ('6 is the target)
1918 // Some of those regions are unified with `'6` (in the same
1919 // SCC). We want to screen those out. After that point, the
1920 // "closest" constraint we have to the end is going to be the
1921 // most likely to be the point where the value escapes -- but
1922 // we still want to screen for an "interesting" point to
1923 // highlight (e.g., a call site or something).
1924 let target_scc
= self.constraint_sccs
.scc(target_region
);
1925 let mut range
= 0..path
.len();
1927 // As noted above, when reporting an error, there is typically a chain of constraints
1928 // leading from some "source" region which must outlive some "target" region.
1929 // In most cases, we prefer to "blame" the constraints closer to the target --
1930 // but there is one exception. When constraints arise from higher-ranked subtyping,
1931 // we generally prefer to blame the source value,
1932 // as the "target" in this case tends to be some type annotation that the user gave.
1933 // Therefore, if we find that the region origin is some instantiation
1934 // of a higher-ranked region, we start our search from the "source" point
1935 // rather than the "target", and we also tweak a few other things.
1937 // An example might be this bit of Rust code:
1940 // let x: fn(&'static ()) = |_| {};
1941 // let y: for<'a> fn(&'a ()) = x;
1944 // In MIR, this will be converted into a combination of assignments and type ascriptions.
1945 // In particular, the 'static is imposed through a type ascription:
1949 // AscribeUserType(x, fn(&'static ())
1953 // We wind up ultimately with constraints like
1956 // !a: 'temp1 // from the `y = x` statement
1958 // 'temp2: 'static // from the AscribeUserType
1961 // and here we prefer to blame the source (the y = x statement).
1962 let blame_source
= match from_region_origin
{
1963 NLLRegionVariableOrigin
::FreeRegion
1964 | NLLRegionVariableOrigin
::Existential { from_forall: false }
=> true,
1965 NLLRegionVariableOrigin
::Placeholder(_
)
1966 | NLLRegionVariableOrigin
::Existential { from_forall: true }
=> false,
1969 let find_region
= |i
: &usize| {
1970 let constraint
= path
[*i
];
1972 let constraint_sup_scc
= self.constraint_sccs
.scc(constraint
.sup
);
1975 match categorized_path
[*i
].0 {
1976 ConstraintCategory
::OpaqueType
1977 | ConstraintCategory
::Boring
1978 | ConstraintCategory
::BoringNoLocation
1979 | ConstraintCategory
::Internal
=> false,
1980 ConstraintCategory
::TypeAnnotation
1981 | ConstraintCategory
::Return
1982 | ConstraintCategory
::Yield
=> true,
1983 _
=> constraint_sup_scc
!= target_scc
,
1986 match categorized_path
[*i
].0 {
1987 ConstraintCategory
::OpaqueType
1988 | ConstraintCategory
::Boring
1989 | ConstraintCategory
::BoringNoLocation
1990 | ConstraintCategory
::Internal
=> false,
1997 if blame_source { range.rev().find(find_region) }
else { range.find(find_region) }
;
2000 "best_blame_constraint: best_choice={:?} blame_source={}",
2001 best_choice
, blame_source
2004 if let Some(i
) = best_choice
{
2005 if let Some(next
) = categorized_path
.get(i
+ 1) {
2006 if categorized_path
[i
].0 == ConstraintCategory
::Return
2007 && next
.0 == ConstraintCategory
::OpaqueType
2009 // The return expression is being influenced by the return type being
2010 // impl Trait, point at the return type and not the return expr.
2014 return categorized_path
[i
];
2017 // If that search fails, that is.. unusual. Maybe everything
2018 // is in the same SCC or something. In that case, find what
2019 // appears to be the most interesting point to report to the
2020 // user via an even more ad-hoc guess.
2021 categorized_path
.sort_by(|p0
, p1
| p0
.0
.cmp(&p1
.0
));
2022 debug
!("`: sorted_path={:#?}", categorized_path
);
2024 *categorized_path
.first().unwrap()
2028 impl<'tcx
> RegionDefinition
<'tcx
> {
2029 fn new(universe
: ty
::UniverseIndex
, rv_origin
: RegionVariableOrigin
) -> Self {
2030 // Create a new region definition. Note that, for free
2031 // regions, the `external_name` field gets updated later in
2032 // `init_universal_regions`.
2034 let origin
= match rv_origin
{
2035 RegionVariableOrigin
::NLL(origin
) => origin
,
2036 _
=> NLLRegionVariableOrigin
::Existential { from_forall: false }
,
2039 Self { origin, universe, external_name: None }
2043 pub trait ClosureRegionRequirementsExt
<'tcx
> {
2044 fn apply_requirements(
2047 closure_def_id
: DefId
,
2048 closure_substs
: SubstsRef
<'tcx
>,
2049 ) -> Vec
<QueryOutlivesConstraint
<'tcx
>>;
2051 fn subst_closure_mapping
<T
>(
2054 closure_mapping
: &IndexVec
<RegionVid
, ty
::Region
<'tcx
>>,
2058 T
: TypeFoldable
<'tcx
>;
2061 impl<'tcx
> ClosureRegionRequirementsExt
<'tcx
> for ClosureRegionRequirements
<'tcx
> {
2062 /// Given an instance T of the closure type, this method
2063 /// instantiates the "extra" requirements that we computed for the
2064 /// closure into the inference context. This has the effect of
2065 /// adding new outlives obligations to existing variables.
2067 /// As described on `ClosureRegionRequirements`, the extra
2068 /// requirements are expressed in terms of regionvids that index
2069 /// into the free regions that appear on the closure type. So, to
2070 /// do this, we first copy those regions out from the type T into
2071 /// a vector. Then we can just index into that vector to extract
2072 /// out the corresponding region from T and apply the
2074 fn apply_requirements(
2077 closure_def_id
: DefId
,
2078 closure_substs
: SubstsRef
<'tcx
>,
2079 ) -> Vec
<QueryOutlivesConstraint
<'tcx
>> {
2081 "apply_requirements(closure_def_id={:?}, closure_substs={:?})",
2082 closure_def_id
, closure_substs
2085 // Extract the values of the free regions in `closure_substs`
2086 // into a vector. These are the regions that we will be
2087 // relating to one another.
2088 let closure_mapping
= &UniversalRegions
::closure_mapping(
2091 self.num_external_vids
,
2092 tcx
.closure_base_def_id(closure_def_id
),
2094 debug
!("apply_requirements: closure_mapping={:?}", closure_mapping
);
2096 // Create the predicates.
2097 self.outlives_requirements
2099 .map(|outlives_requirement
| {
2100 let outlived_region
= closure_mapping
[outlives_requirement
.outlived_free_region
];
2102 match outlives_requirement
.subject
{
2103 ClosureOutlivesSubject
::Region(region
) => {
2104 let region
= closure_mapping
[region
];
2106 "apply_requirements: region={:?} \
2107 outlived_region={:?} \
2108 outlives_requirement={:?}",
2109 region
, outlived_region
, outlives_requirement
,
2111 ty
::Binder
::dummy(ty
::OutlivesPredicate(region
.into(), outlived_region
))
2114 ClosureOutlivesSubject
::Ty(ty
) => {
2115 let ty
= self.subst_closure_mapping(tcx
, closure_mapping
, &ty
);
2117 "apply_requirements: ty={:?} \
2118 outlived_region={:?} \
2119 outlives_requirement={:?}",
2120 ty
, outlived_region
, outlives_requirement
,
2122 ty
::Binder
::dummy(ty
::OutlivesPredicate(ty
.into(), outlived_region
))
2129 fn subst_closure_mapping
<T
>(
2132 closure_mapping
: &IndexVec
<RegionVid
, ty
::Region
<'tcx
>>,
2136 T
: TypeFoldable
<'tcx
>,
2138 tcx
.fold_regions(value
, &mut false, |r
, _depth
| {
2139 if let ty
::ReClosureBound(vid
) = r
{
2140 closure_mapping
[*vid
]
2142 bug
!("subst_closure_mapping: encountered non-closure bound free region {:?}", r
)