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