]> git.lizzy.rs Git - rust.git/blob - src/librustc_infer/infer/region_constraints/mod.rs
Prevent modifications without an undo log
[rust.git] / src / librustc_infer / infer / region_constraints / mod.rs
1 //! See `README.md`.
2
3 use self::CombineMapType::*;
4 use self::UndoLog::*;
5
6 use super::unify_key;
7 use super::{
8     InferCtxtUndoLogs, MiscVariable, RegionVariableOrigin, Rollback, Snapshot, SubregionOrigin,
9 };
10
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_data_structures::sync::Lrc;
13 use rustc_data_structures::undo_log::UndoLogs;
14 use rustc_data_structures::unify as ut;
15 use rustc_data_structures::unify::UnifyKey;
16 use rustc_hir::def_id::DefId;
17 use rustc_index::vec::IndexVec;
18 use rustc_middle::ty::ReStatic;
19 use rustc_middle::ty::{self, Ty, TyCtxt};
20 use rustc_middle::ty::{ReLateBound, ReVar};
21 use rustc_middle::ty::{Region, RegionVid};
22 use rustc_span::Span;
23
24 use std::collections::BTreeMap;
25 use std::ops::Range;
26 use std::{cmp, fmt, mem};
27
28 mod leak_check;
29
30 pub use rustc_middle::infer::MemberConstraint;
31
32 #[derive(Default)]
33 pub struct RegionConstraintStorage<'tcx> {
34     /// For each `RegionVid`, the corresponding `RegionVariableOrigin`.
35     var_infos: IndexVec<RegionVid, RegionVariableInfo>,
36
37     data: RegionConstraintData<'tcx>,
38
39     /// For a given pair of regions (R1, R2), maps to a region R3 that
40     /// is designated as their LUB (edges R1 <= R3 and R2 <= R3
41     /// exist). This prevents us from making many such regions.
42     lubs: CombineMap<'tcx>,
43
44     /// For a given pair of regions (R1, R2), maps to a region R3 that
45     /// is designated as their GLB (edges R3 <= R1 and R3 <= R2
46     /// exist). This prevents us from making many such regions.
47     glbs: CombineMap<'tcx>,
48
49     /// When we add a R1 == R2 constriant, we currently add (a) edges
50     /// R1 <= R2 and R2 <= R1 and (b) we unify the two regions in this
51     /// table. You can then call `opportunistic_resolve_var` early
52     /// which will map R1 and R2 to some common region (i.e., either
53     /// R1 or R2). This is important when dropck and other such code
54     /// is iterating to a fixed point, because otherwise we sometimes
55     /// would wind up with a fresh stream of region variables that
56     /// have been equated but appear distinct.
57     pub(super) unification_table: ut::UnificationTableStorage<ty::RegionVid>,
58
59     /// a flag set to true when we perform any unifications; this is used
60     /// to micro-optimize `take_and_reset_data`
61     any_unifications: bool,
62 }
63
64 pub struct RegionConstraintCollector<'tcx, 'a> {
65     storage: &'a mut RegionConstraintStorage<'tcx>,
66     undo_log: &'a mut InferCtxtUndoLogs<'tcx>,
67 }
68
69 impl std::ops::Deref for RegionConstraintCollector<'tcx, '_> {
70     type Target = RegionConstraintStorage<'tcx>;
71     fn deref(&self) -> &RegionConstraintStorage<'tcx> {
72         self.storage
73     }
74 }
75
76 impl std::ops::DerefMut for RegionConstraintCollector<'tcx, '_> {
77     fn deref_mut(&mut self) -> &mut RegionConstraintStorage<'tcx> {
78         self.storage
79     }
80 }
81
82 pub type VarInfos = IndexVec<RegionVid, RegionVariableInfo>;
83
84 /// The full set of region constraints gathered up by the collector.
85 /// Describes constraints between the region variables and other
86 /// regions, as well as other conditions that must be verified, or
87 /// assumptions that can be made.
88 #[derive(Debug, Default, Clone)]
89 pub struct RegionConstraintData<'tcx> {
90     /// Constraints of the form `A <= B`, where either `A` or `B` can
91     /// be a region variable (or neither, as it happens).
92     pub constraints: BTreeMap<Constraint<'tcx>, SubregionOrigin<'tcx>>,
93
94     /// Constraints of the form `R0 member of [R1, ..., Rn]`, meaning that
95     /// `R0` must be equal to one of the regions `R1..Rn`. These occur
96     /// with `impl Trait` quite frequently.
97     pub member_constraints: Vec<MemberConstraint<'tcx>>,
98
99     /// A "verify" is something that we need to verify after inference
100     /// is done, but which does not directly affect inference in any
101     /// way.
102     ///
103     /// An example is a `A <= B` where neither `A` nor `B` are
104     /// inference variables.
105     pub verifys: Vec<Verify<'tcx>>,
106
107     /// A "given" is a relationship that is known to hold. In
108     /// particular, we often know from closure fn signatures that a
109     /// particular free region must be a subregion of a region
110     /// variable:
111     ///
112     ///    foo.iter().filter(<'a> |x: &'a &'b T| ...)
113     ///
114     /// In situations like this, `'b` is in fact a region variable
115     /// introduced by the call to `iter()`, and `'a` is a bound region
116     /// on the closure (as indicated by the `<'a>` prefix). If we are
117     /// naive, we wind up inferring that `'b` must be `'static`,
118     /// because we require that it be greater than `'a` and we do not
119     /// know what `'a` is precisely.
120     ///
121     /// This hashmap is used to avoid that naive scenario. Basically
122     /// we record the fact that `'a <= 'b` is implied by the fn
123     /// signature, and then ignore the constraint when solving
124     /// equations. This is a bit of a hack but seems to work.
125     pub givens: FxHashSet<(Region<'tcx>, ty::RegionVid)>,
126 }
127
128 /// Represents a constraint that influences the inference process.
129 #[derive(Clone, Copy, PartialEq, Eq, Debug, PartialOrd, Ord)]
130 pub enum Constraint<'tcx> {
131     /// A region variable is a subregion of another.
132     VarSubVar(RegionVid, RegionVid),
133
134     /// A concrete region is a subregion of region variable.
135     RegSubVar(Region<'tcx>, RegionVid),
136
137     /// A region variable is a subregion of a concrete region. This does not
138     /// directly affect inference, but instead is checked after
139     /// inference is complete.
140     VarSubReg(RegionVid, Region<'tcx>),
141
142     /// A constraint where neither side is a variable. This does not
143     /// directly affect inference, but instead is checked after
144     /// inference is complete.
145     RegSubReg(Region<'tcx>, Region<'tcx>),
146 }
147
148 impl Constraint<'_> {
149     pub fn involves_placeholders(&self) -> bool {
150         match self {
151             Constraint::VarSubVar(_, _) => false,
152             Constraint::VarSubReg(_, r) | Constraint::RegSubVar(r, _) => r.is_placeholder(),
153             Constraint::RegSubReg(r, s) => r.is_placeholder() || s.is_placeholder(),
154         }
155     }
156 }
157
158 #[derive(Debug, Clone)]
159 pub struct Verify<'tcx> {
160     pub kind: GenericKind<'tcx>,
161     pub origin: SubregionOrigin<'tcx>,
162     pub region: Region<'tcx>,
163     pub bound: VerifyBound<'tcx>,
164 }
165
166 #[derive(Copy, Clone, PartialEq, Eq, Hash, TypeFoldable)]
167 pub enum GenericKind<'tcx> {
168     Param(ty::ParamTy),
169     Projection(ty::ProjectionTy<'tcx>),
170 }
171
172 /// Describes the things that some `GenericKind` value `G` is known to
173 /// outlive. Each variant of `VerifyBound` can be thought of as a
174 /// function:
175 ///
176 ///     fn(min: Region) -> bool { .. }
177 ///
178 /// where `true` means that the region `min` meets that `G: min`.
179 /// (False means nothing.)
180 ///
181 /// So, for example, if we have the type `T` and we have in scope that
182 /// `T: 'a` and `T: 'b`, then the verify bound might be:
183 ///
184 ///     fn(min: Region) -> bool {
185 ///        ('a: min) || ('b: min)
186 ///     }
187 ///
188 /// This is described with a `AnyRegion('a, 'b)` node.
189 #[derive(Debug, Clone)]
190 pub enum VerifyBound<'tcx> {
191     /// Given a kind K and a bound B, expands to a function like the
192     /// following, where `G` is the generic for which this verify
193     /// bound was created:
194     ///
195     /// ```rust
196     /// fn(min) -> bool {
197     ///     if G == K {
198     ///         B(min)
199     ///     } else {
200     ///         false
201     ///     }
202     /// }
203     /// ```
204     ///
205     /// In other words, if the generic `G` that we are checking is
206     /// equal to `K`, then check the associated verify bound
207     /// (otherwise, false).
208     ///
209     /// This is used when we have something in the environment that
210     /// may or may not be relevant, depending on the region inference
211     /// results. For example, we may have `where <T as
212     /// Trait<'a>>::Item: 'b` in our where-clauses. If we are
213     /// generating the verify-bound for `<T as Trait<'0>>::Item`, then
214     /// this where-clause is only relevant if `'0` winds up inferred
215     /// to `'a`.
216     ///
217     /// So we would compile to a verify-bound like
218     ///
219     /// ```
220     /// IfEq(<T as Trait<'a>>::Item, AnyRegion('a))
221     /// ```
222     ///
223     /// meaning, if the subject G is equal to `<T as Trait<'a>>::Item`
224     /// (after inference), and `'a: min`, then `G: min`.
225     IfEq(Ty<'tcx>, Box<VerifyBound<'tcx>>),
226
227     /// Given a region `R`, expands to the function:
228     ///
229     /// ```
230     /// fn(min) -> bool {
231     ///     R: min
232     /// }
233     /// ```
234     ///
235     /// This is used when we can establish that `G: R` -- therefore,
236     /// if `R: min`, then by transitivity `G: min`.
237     OutlivedBy(Region<'tcx>),
238
239     /// Given a region `R`, true if it is `'empty`.
240     IsEmpty,
241
242     /// Given a set of bounds `B`, expands to the function:
243     ///
244     /// ```rust
245     /// fn(min) -> bool {
246     ///     exists (b in B) { b(min) }
247     /// }
248     /// ```
249     ///
250     /// In other words, if we meet some bound in `B`, that suffices.
251     /// This is used when all the bounds in `B` are known to apply to `G`.
252     AnyBound(Vec<VerifyBound<'tcx>>),
253
254     /// Given a set of bounds `B`, expands to the function:
255     ///
256     /// ```rust
257     /// fn(min) -> bool {
258     ///     forall (b in B) { b(min) }
259     /// }
260     /// ```
261     ///
262     /// In other words, if we meet *all* bounds in `B`, that suffices.
263     /// This is used when *some* bound in `B` is known to suffice, but
264     /// we don't know which.
265     AllBounds(Vec<VerifyBound<'tcx>>),
266 }
267
268 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
269 pub(crate) struct TwoRegions<'tcx> {
270     a: Region<'tcx>,
271     b: Region<'tcx>,
272 }
273
274 #[derive(Copy, Clone, PartialEq)]
275 pub(crate) enum UndoLog<'tcx> {
276     /// We added `RegionVid`.
277     AddVar(RegionVid),
278
279     /// We added the given `constraint`.
280     AddConstraint(Constraint<'tcx>),
281
282     /// We added the given `verify`.
283     AddVerify(usize),
284
285     /// We added the given `given`.
286     AddGiven(Region<'tcx>, ty::RegionVid),
287
288     /// We added a GLB/LUB "combination variable".
289     AddCombination(CombineMapType, TwoRegions<'tcx>),
290
291     /// During skolemization, we sometimes purge entries from the undo
292     /// log in a kind of minisnapshot (unlike other snapshots, this
293     /// purging actually takes place *on success*). In that case, we
294     /// replace the corresponding entry with `Noop` so as to avoid the
295     /// need to do a bunch of swapping. (We can't use `swap_remove` as
296     /// the order of the vector is important.)
297     Purged,
298 }
299
300 #[derive(Copy, Clone, PartialEq)]
301 pub(crate) enum CombineMapType {
302     Lub,
303     Glb,
304 }
305
306 type CombineMap<'tcx> = FxHashMap<TwoRegions<'tcx>, RegionVid>;
307
308 #[derive(Debug, Clone, Copy)]
309 pub struct RegionVariableInfo {
310     pub origin: RegionVariableOrigin,
311     pub universe: ty::UniverseIndex,
312 }
313
314 pub struct RegionSnapshot {
315     value_count: usize,
316     any_unifications: bool,
317 }
318
319 /// When working with placeholder regions, we often wish to find all of
320 /// the regions that are either reachable from a placeholder region, or
321 /// which can reach a placeholder region, or both. We call such regions
322 /// *tainted* regions. This struct allows you to decide what set of
323 /// tainted regions you want.
324 #[derive(Debug)]
325 pub struct TaintDirections {
326     incoming: bool,
327     outgoing: bool,
328 }
329
330 impl TaintDirections {
331     pub fn incoming() -> Self {
332         TaintDirections { incoming: true, outgoing: false }
333     }
334
335     pub fn outgoing() -> Self {
336         TaintDirections { incoming: false, outgoing: true }
337     }
338
339     pub fn both() -> Self {
340         TaintDirections { incoming: true, outgoing: true }
341     }
342 }
343
344 impl<'tcx> RegionConstraintStorage<'tcx> {
345     pub fn new() -> Self {
346         Self::default()
347     }
348
349     pub(crate) fn with_log<'a>(
350         &'a mut self,
351         undo_log: &'a mut InferCtxtUndoLogs<'tcx>,
352     ) -> RegionConstraintCollector<'tcx, 'a> {
353         RegionConstraintCollector { storage: self, undo_log }
354     }
355
356     fn rollback_undo_entry(&mut self, undo_entry: UndoLog<'tcx>) {
357         match undo_entry {
358             Purged => {
359                 // nothing to do here
360             }
361             AddVar(vid) => {
362                 self.var_infos.pop().unwrap();
363                 assert_eq!(self.var_infos.len(), vid.index() as usize);
364             }
365             AddConstraint(ref constraint) => {
366                 self.data.constraints.remove(constraint);
367             }
368             AddVerify(index) => {
369                 self.data.verifys.pop();
370                 assert_eq!(self.data.verifys.len(), index);
371             }
372             AddGiven(sub, sup) => {
373                 self.data.givens.remove(&(sub, sup));
374             }
375             AddCombination(Glb, ref regions) => {
376                 self.glbs.remove(regions);
377             }
378             AddCombination(Lub, ref regions) => {
379                 self.lubs.remove(regions);
380             }
381         }
382     }
383 }
384
385 impl<'tcx> RegionConstraintCollector<'tcx, '_> {
386     pub fn num_region_vars(&self) -> usize {
387         self.var_infos.len()
388     }
389
390     pub fn region_constraint_data(&self) -> &RegionConstraintData<'tcx> {
391         &self.data
392     }
393
394     /// Once all the constraints have been gathered, extract out the final data.
395     ///
396     /// Not legal during a snapshot.
397     pub fn into_infos_and_data(self) -> (VarInfos, RegionConstraintData<'tcx>) {
398         assert!(!UndoLogs::<super::UndoLog<'_>>::in_snapshot(&self.undo_log));
399         (mem::take(&mut self.storage.var_infos), mem::take(&mut self.storage.data))
400     }
401
402     /// Takes (and clears) the current set of constraints. Note that
403     /// the set of variables remains intact, but all relationships
404     /// between them are reset. This is used during NLL checking to
405     /// grab the set of constraints that arose from a particular
406     /// operation.
407     ///
408     /// We don't want to leak relationships between variables between
409     /// points because just because (say) `r1 == r2` was true at some
410     /// point P in the graph doesn't imply that it will be true at
411     /// some other point Q, in NLL.
412     ///
413     /// Not legal during a snapshot.
414     pub fn take_and_reset_data(&mut self) -> RegionConstraintData<'tcx> {
415         assert!(!UndoLogs::<super::UndoLog<'_>>::in_snapshot(&self.undo_log));
416
417         // If you add a new field to `RegionConstraintCollector`, you
418         // should think carefully about whether it needs to be cleared
419         // or updated in some way.
420         let RegionConstraintStorage {
421             var_infos: _,
422             data,
423             lubs,
424             glbs,
425             unification_table: _,
426             any_unifications,
427         } = self.storage;
428
429         // Clear the tables of (lubs, glbs), so that we will create
430         // fresh regions if we do a LUB operation. As it happens,
431         // LUB/GLB are not performed by the MIR type-checker, which is
432         // the one that uses this method, but it's good to be correct.
433         lubs.clear();
434         glbs.clear();
435
436         let data = mem::take(data);
437
438         // Clear all unifications and recreate the variables a "now
439         // un-unified" state. Note that when we unify `a` and `b`, we
440         // also insert `a <= b` and a `b <= a` edges, so the
441         // `RegionConstraintData` contains the relationship here.
442         if *any_unifications {
443             *any_unifications = false;
444             self.unification_table()
445                 .reset_unifications(|vid| unify_key::RegionVidKey { min_vid: vid });
446         }
447
448         data
449     }
450
451     pub fn data(&self) -> &RegionConstraintData<'tcx> {
452         &self.data
453     }
454
455     pub fn start_snapshot(&mut self) -> RegionSnapshot {
456         debug!("RegionConstraintCollector: start_snapshot");
457         RegionSnapshot {
458             value_count: self.unification_table.len(),
459             any_unifications: self.any_unifications,
460         }
461     }
462
463     pub fn rollback_to(&mut self, snapshot: RegionSnapshot) {
464         debug!("RegionConstraintCollector: rollback_to({:?})", snapshot);
465         self.any_unifications = snapshot.any_unifications;
466     }
467
468     pub fn new_region_var(
469         &mut self,
470         universe: ty::UniverseIndex,
471         origin: RegionVariableOrigin,
472     ) -> RegionVid {
473         let vid = self.var_infos.push(RegionVariableInfo { origin, universe });
474
475         let u_vid = self.unification_table().new_key(unify_key::RegionVidKey { min_vid: vid });
476         assert_eq!(vid, u_vid);
477         self.undo_log.push(AddVar(vid));
478         debug!("created new region variable {:?} in {:?} with origin {:?}", vid, universe, origin);
479         vid
480     }
481
482     /// Returns the universe for the given variable.
483     pub fn var_universe(&self, vid: RegionVid) -> ty::UniverseIndex {
484         self.var_infos[vid].universe
485     }
486
487     /// Returns the origin for the given variable.
488     pub fn var_origin(&self, vid: RegionVid) -> RegionVariableOrigin {
489         self.var_infos[vid].origin
490     }
491
492     /// Removes all the edges to/from the placeholder regions that are
493     /// in `skols`. This is used after a higher-ranked operation
494     /// completes to remove all trace of the placeholder regions
495     /// created in that time.
496     pub fn pop_placeholders(&mut self, placeholders: &FxHashSet<ty::Region<'tcx>>) {
497         debug!("pop_placeholders(placeholders={:?})", placeholders);
498
499         assert!(UndoLogs::<super::UndoLog<'_>>::in_snapshot(&self.undo_log));
500
501         let constraints_to_kill: Vec<usize> = self
502             .undo_log
503             .iter()
504             .enumerate()
505             .rev()
506             .filter(|&(_, undo_entry)| match undo_entry {
507                 super::UndoLog::RegionConstraintCollector(undo_entry) => {
508                     kill_constraint(placeholders, undo_entry)
509                 }
510                 _ => false,
511             })
512             .map(|(index, _)| index)
513             .collect();
514
515         for index in constraints_to_kill {
516             let undo_entry = match &mut self.undo_log[index] {
517                 super::UndoLog::RegionConstraintCollector(undo_entry) => {
518                     mem::replace(undo_entry, Purged)
519                 }
520                 _ => unreachable!(),
521             };
522             self.rollback_undo_entry(undo_entry);
523         }
524
525         return;
526
527         fn kill_constraint<'tcx>(
528             placeholders: &FxHashSet<ty::Region<'tcx>>,
529             undo_entry: &UndoLog<'tcx>,
530         ) -> bool {
531             match undo_entry {
532                 &AddConstraint(Constraint::VarSubVar(..)) => false,
533                 &AddConstraint(Constraint::RegSubVar(a, _)) => placeholders.contains(&a),
534                 &AddConstraint(Constraint::VarSubReg(_, b)) => placeholders.contains(&b),
535                 &AddConstraint(Constraint::RegSubReg(a, b)) => {
536                     placeholders.contains(&a) || placeholders.contains(&b)
537                 }
538                 &AddGiven(..) => false,
539                 &AddVerify(_) => false,
540                 &AddCombination(_, ref two_regions) => {
541                     placeholders.contains(&two_regions.a) || placeholders.contains(&two_regions.b)
542                 }
543                 &AddVar(..) | &Purged => false,
544             }
545         }
546     }
547
548     fn add_constraint(&mut self, constraint: Constraint<'tcx>, origin: SubregionOrigin<'tcx>) {
549         // cannot add constraints once regions are resolved
550         debug!("RegionConstraintCollector: add_constraint({:?})", constraint);
551
552         // never overwrite an existing (constraint, origin) - only insert one if it isn't
553         // present in the map yet. This prevents origins from outside the snapshot being
554         // replaced with "less informative" origins e.g., during calls to `can_eq`
555         let undo_log = &mut self.undo_log;
556         self.storage.data.constraints.entry(constraint).or_insert_with(|| {
557             undo_log.push(AddConstraint(constraint));
558             origin
559         });
560     }
561
562     fn add_verify(&mut self, verify: Verify<'tcx>) {
563         // cannot add verifys once regions are resolved
564         debug!("RegionConstraintCollector: add_verify({:?})", verify);
565
566         // skip no-op cases known to be satisfied
567         if let VerifyBound::AllBounds(ref bs) = verify.bound {
568             if bs.is_empty() {
569                 return;
570             }
571         }
572
573         let index = self.data.verifys.len();
574         self.data.verifys.push(verify);
575         self.undo_log.push(AddVerify(index));
576     }
577
578     pub fn add_given(&mut self, sub: Region<'tcx>, sup: ty::RegionVid) {
579         // cannot add givens once regions are resolved
580         if self.data.givens.insert((sub, sup)) {
581             debug!("add_given({:?} <= {:?})", sub, sup);
582
583             self.undo_log.push(AddGiven(sub, sup));
584         }
585     }
586
587     pub fn make_eqregion(
588         &mut self,
589         origin: SubregionOrigin<'tcx>,
590         sub: Region<'tcx>,
591         sup: Region<'tcx>,
592     ) {
593         if sub != sup {
594             // Eventually, it would be nice to add direct support for
595             // equating regions.
596             self.make_subregion(origin.clone(), sub, sup);
597             self.make_subregion(origin, sup, sub);
598
599             if let (ty::ReVar(sub), ty::ReVar(sup)) = (*sub, *sup) {
600                 debug!("make_eqregion: uniying {:?} with {:?}", sub, sup);
601                 self.unification_table().union(sub, sup);
602                 self.any_unifications = true;
603             }
604         }
605     }
606
607     pub fn member_constraint(
608         &mut self,
609         opaque_type_def_id: DefId,
610         definition_span: Span,
611         hidden_ty: Ty<'tcx>,
612         member_region: ty::Region<'tcx>,
613         choice_regions: &Lrc<Vec<ty::Region<'tcx>>>,
614     ) {
615         debug!("member_constraint({:?} in {:#?})", member_region, choice_regions);
616
617         if choice_regions.iter().any(|&r| r == member_region) {
618             return;
619         }
620
621         self.data.member_constraints.push(MemberConstraint {
622             opaque_type_def_id,
623             definition_span,
624             hidden_ty,
625             member_region,
626             choice_regions: choice_regions.clone(),
627         });
628     }
629
630     pub fn make_subregion(
631         &mut self,
632         origin: SubregionOrigin<'tcx>,
633         sub: Region<'tcx>,
634         sup: Region<'tcx>,
635     ) {
636         // cannot add constraints once regions are resolved
637         debug!(
638             "RegionConstraintCollector: make_subregion({:?}, {:?}) due to {:?}",
639             sub, sup, origin
640         );
641
642         match (sub, sup) {
643             (&ReLateBound(..), _) | (_, &ReLateBound(..)) => {
644                 span_bug!(origin.span(), "cannot relate bound region: {:?} <= {:?}", sub, sup);
645             }
646             (_, &ReStatic) => {
647                 // all regions are subregions of static, so we can ignore this
648             }
649             (&ReVar(sub_id), &ReVar(sup_id)) => {
650                 self.add_constraint(Constraint::VarSubVar(sub_id, sup_id), origin);
651             }
652             (_, &ReVar(sup_id)) => {
653                 self.add_constraint(Constraint::RegSubVar(sub, sup_id), origin);
654             }
655             (&ReVar(sub_id), _) => {
656                 self.add_constraint(Constraint::VarSubReg(sub_id, sup), origin);
657             }
658             _ => {
659                 self.add_constraint(Constraint::RegSubReg(sub, sup), origin);
660             }
661         }
662     }
663
664     pub fn verify_generic_bound(
665         &mut self,
666         origin: SubregionOrigin<'tcx>,
667         kind: GenericKind<'tcx>,
668         sub: Region<'tcx>,
669         bound: VerifyBound<'tcx>,
670     ) {
671         self.add_verify(Verify { kind, origin, region: sub, bound });
672     }
673
674     pub fn lub_regions(
675         &mut self,
676         tcx: TyCtxt<'tcx>,
677         origin: SubregionOrigin<'tcx>,
678         a: Region<'tcx>,
679         b: Region<'tcx>,
680     ) -> Region<'tcx> {
681         // cannot add constraints once regions are resolved
682         debug!("RegionConstraintCollector: lub_regions({:?}, {:?})", a, b);
683         match (a, b) {
684             (r @ &ReStatic, _) | (_, r @ &ReStatic) => {
685                 r // nothing lives longer than static
686             }
687
688             _ if a == b => {
689                 a // LUB(a,a) = a
690             }
691
692             _ => self.combine_vars(tcx, Lub, a, b, origin),
693         }
694     }
695
696     pub fn glb_regions(
697         &mut self,
698         tcx: TyCtxt<'tcx>,
699         origin: SubregionOrigin<'tcx>,
700         a: Region<'tcx>,
701         b: Region<'tcx>,
702     ) -> Region<'tcx> {
703         // cannot add constraints once regions are resolved
704         debug!("RegionConstraintCollector: glb_regions({:?}, {:?})", a, b);
705         match (a, b) {
706             (&ReStatic, r) | (r, &ReStatic) => {
707                 r // static lives longer than everything else
708             }
709
710             _ if a == b => {
711                 a // GLB(a,a) = a
712             }
713
714             _ => self.combine_vars(tcx, Glb, a, b, origin),
715         }
716     }
717
718     pub fn opportunistic_resolve_var(
719         &mut self,
720         tcx: TyCtxt<'tcx>,
721         rid: RegionVid,
722     ) -> ty::Region<'tcx> {
723         let vid = self.unification_table().probe_value(rid).min_vid;
724         tcx.mk_region(ty::ReVar(vid))
725     }
726
727     fn combine_map(&mut self, t: CombineMapType) -> &mut CombineMap<'tcx> {
728         match t {
729             Glb => &mut self.glbs,
730             Lub => &mut self.lubs,
731         }
732     }
733
734     fn combine_vars(
735         &mut self,
736         tcx: TyCtxt<'tcx>,
737         t: CombineMapType,
738         a: Region<'tcx>,
739         b: Region<'tcx>,
740         origin: SubregionOrigin<'tcx>,
741     ) -> Region<'tcx> {
742         let vars = TwoRegions { a, b };
743         if let Some(&c) = self.combine_map(t).get(&vars) {
744             return tcx.mk_region(ReVar(c));
745         }
746         let a_universe = self.universe(a);
747         let b_universe = self.universe(b);
748         let c_universe = cmp::max(a_universe, b_universe);
749         let c = self.new_region_var(c_universe, MiscVariable(origin.span()));
750         self.combine_map(t).insert(vars, c);
751         self.undo_log.push(AddCombination(t, vars));
752         let new_r = tcx.mk_region(ReVar(c));
753         for &old_r in &[a, b] {
754             match t {
755                 Glb => self.make_subregion(origin.clone(), new_r, old_r),
756                 Lub => self.make_subregion(origin.clone(), old_r, new_r),
757             }
758         }
759         debug!("combine_vars() c={:?}", c);
760         new_r
761     }
762
763     pub fn universe(&self, region: Region<'tcx>) -> ty::UniverseIndex {
764         match *region {
765             ty::ReScope(..)
766             | ty::ReStatic
767             | ty::ReErased
768             | ty::ReFree(..)
769             | ty::ReEarlyBound(..) => ty::UniverseIndex::ROOT,
770             ty::ReEmpty(ui) => ui,
771             ty::RePlaceholder(placeholder) => placeholder.universe,
772             ty::ReVar(vid) => self.var_universe(vid),
773             ty::ReLateBound(..) => bug!("universe(): encountered bound region {:?}", region),
774         }
775     }
776
777     pub fn vars_since_snapshot(
778         &self,
779         mark: &RegionSnapshot,
780     ) -> (Range<RegionVid>, Vec<RegionVariableOrigin>) {
781         let range = RegionVid::from_index(mark.value_count as u32)
782             ..RegionVid::from_index(self.unification_table.len() as u32);
783         (
784             range.clone(),
785             (range.start.index()..range.end.index())
786                 .map(|index| self.var_infos[ty::RegionVid::from(index)].origin)
787                 .collect(),
788         )
789     }
790
791     /// See [`RegionInference::region_constraints_added_in_snapshot`].
792     pub fn region_constraints_added_in_snapshot(&self, mark: &Snapshot<'tcx>) -> Option<bool> {
793         self.undo_log
794             .region_constraints_in_snapshot(mark)
795             .map(|&elt| match elt {
796                 AddConstraint(constraint) => Some(constraint.involves_placeholders()),
797                 _ => None,
798             })
799             .max()
800             .unwrap_or(None)
801     }
802
803     fn unification_table(&mut self) -> super::UnificationTable<'_, 'tcx, ty::RegionVid> {
804         ut::UnificationTable::with_log(&mut self.storage.unification_table, self.undo_log)
805     }
806 }
807
808 impl fmt::Debug for RegionSnapshot {
809     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
810         write!(f, "RegionSnapshot")
811     }
812 }
813
814 impl<'tcx> fmt::Debug for GenericKind<'tcx> {
815     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
816         match *self {
817             GenericKind::Param(ref p) => write!(f, "{:?}", p),
818             GenericKind::Projection(ref p) => write!(f, "{:?}", p),
819         }
820     }
821 }
822
823 impl<'tcx> fmt::Display for GenericKind<'tcx> {
824     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
825         match *self {
826             GenericKind::Param(ref p) => write!(f, "{}", p),
827             GenericKind::Projection(ref p) => write!(f, "{}", p),
828         }
829     }
830 }
831
832 impl<'tcx> GenericKind<'tcx> {
833     pub fn to_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
834         match *self {
835             GenericKind::Param(ref p) => p.to_ty(tcx),
836             GenericKind::Projection(ref p) => tcx.mk_projection(p.item_def_id, p.substs),
837         }
838     }
839 }
840
841 impl<'tcx> VerifyBound<'tcx> {
842     pub fn must_hold(&self) -> bool {
843         match self {
844             VerifyBound::IfEq(..) => false,
845             VerifyBound::OutlivedBy(ty::ReStatic) => true,
846             VerifyBound::OutlivedBy(_) => false,
847             VerifyBound::IsEmpty => false,
848             VerifyBound::AnyBound(bs) => bs.iter().any(|b| b.must_hold()),
849             VerifyBound::AllBounds(bs) => bs.iter().all(|b| b.must_hold()),
850         }
851     }
852
853     pub fn cannot_hold(&self) -> bool {
854         match self {
855             VerifyBound::IfEq(_, b) => b.cannot_hold(),
856             VerifyBound::IsEmpty => false,
857             VerifyBound::OutlivedBy(_) => false,
858             VerifyBound::AnyBound(bs) => bs.iter().all(|b| b.cannot_hold()),
859             VerifyBound::AllBounds(bs) => bs.iter().any(|b| b.cannot_hold()),
860         }
861     }
862
863     pub fn or(self, vb: VerifyBound<'tcx>) -> VerifyBound<'tcx> {
864         if self.must_hold() || vb.cannot_hold() {
865             self
866         } else if self.cannot_hold() || vb.must_hold() {
867             vb
868         } else {
869             VerifyBound::AnyBound(vec![self, vb])
870         }
871     }
872
873     pub fn and(self, vb: VerifyBound<'tcx>) -> VerifyBound<'tcx> {
874         if self.must_hold() && vb.must_hold() {
875             self
876         } else if self.cannot_hold() && vb.cannot_hold() {
877             self
878         } else {
879             VerifyBound::AllBounds(vec![self, vb])
880         }
881     }
882 }
883
884 impl<'tcx> RegionConstraintData<'tcx> {
885     /// Returns `true` if this region constraint data contains no constraints, and `false`
886     /// otherwise.
887     pub fn is_empty(&self) -> bool {
888         let RegionConstraintData { constraints, member_constraints, verifys, givens } = self;
889         constraints.is_empty()
890             && member_constraints.is_empty()
891             && verifys.is_empty()
892             && givens.is_empty()
893     }
894 }
895
896 impl<'tcx> Rollback<UndoLog<'tcx>> for RegionConstraintStorage<'tcx> {
897     fn reverse(&mut self, undo: UndoLog<'tcx>) {
898         self.rollback_undo_entry(undo)
899     }
900 }