]> git.lizzy.rs Git - rust.git/blob - src/librustc_infer/infer/mod.rs
Increase accuracy of lifetime bound on trait object impl suggestion
[rust.git] / src / librustc_infer / infer / mod.rs
1 //! See the Book for more information.
2
3 pub use self::freshen::TypeFreshener;
4 pub use self::LateBoundRegionConversionTime::*;
5 pub use self::RegionVariableOrigin::*;
6 pub use self::SubregionOrigin::*;
7 pub use self::ValuePairs::*;
8
9 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
10
11 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
12
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_data_structures::sync::Lrc;
15 use rustc_data_structures::undo_log::Rollback;
16 use rustc_data_structures::unify as ut;
17 use rustc_errors::DiagnosticBuilder;
18 use rustc_hir as hir;
19 use rustc_hir::def_id::{DefId, LocalDefId};
20 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
21 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
22 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
23 use rustc_middle::mir;
24 use rustc_middle::mir::interpret::ConstEvalResult;
25 use rustc_middle::traits::select;
26 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
27 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
28 use rustc_middle::ty::relate::RelateResult;
29 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
30 pub use rustc_middle::ty::IntVarValue;
31 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
32 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
33 use rustc_session::config::BorrowckMode;
34 use rustc_span::symbol::Symbol;
35 use rustc_span::Span;
36
37 use std::cell::{Cell, Ref, RefCell};
38 use std::collections::BTreeMap;
39 use std::fmt;
40
41 use self::combine::CombineFields;
42 use self::free_regions::RegionRelations;
43 use self::lexical_region_resolve::LexicalRegionResolutions;
44 use self::outlives::env::OutlivesEnvironment;
45 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
46 use self::region_constraints::{
47     RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
48 };
49 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
50
51 pub mod at;
52 pub mod canonical;
53 mod combine;
54 mod equate;
55 pub mod error_reporting;
56 pub mod free_regions;
57 mod freshen;
58 mod fudge;
59 mod glb;
60 mod higher_ranked;
61 pub mod lattice;
62 mod lexical_region_resolve;
63 mod lub;
64 pub mod nll_relate;
65 pub mod outlives;
66 pub mod region_constraints;
67 pub mod resolve;
68 mod sub;
69 pub mod type_variable;
70 mod undo_log;
71
72 use crate::infer::canonical::OriginalQueryValues;
73 pub use rustc_middle::infer::unify_key;
74
75 #[must_use]
76 #[derive(Debug)]
77 pub struct InferOk<'tcx, T> {
78     pub value: T,
79     pub obligations: PredicateObligations<'tcx>,
80 }
81 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
82
83 pub type Bound<T> = Option<T>;
84 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
85 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
86
87 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
88     ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
89 >;
90
91 /// How we should handle region solving.
92 ///
93 /// This is used so that the region values inferred by HIR region solving are
94 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
95 /// typeck will also do.
96 #[derive(Copy, Clone, Debug)]
97 pub enum RegionckMode {
98     /// The default mode: report region errors, don't erase regions.
99     Solve,
100     /// Erase the results of region after solving.
101     Erase {
102         /// A flag that is used to suppress region errors, when we are doing
103         /// region checks that the NLL borrow checker will also do -- it might
104         /// be set to true.
105         suppress_errors: bool,
106     },
107 }
108
109 impl Default for RegionckMode {
110     fn default() -> Self {
111         RegionckMode::Solve
112     }
113 }
114
115 impl RegionckMode {
116     pub fn suppressed(self) -> bool {
117         match self {
118             Self::Solve => false,
119             Self::Erase { suppress_errors } => suppress_errors,
120         }
121     }
122
123     /// Indicates that the MIR borrowck will repeat these region
124     /// checks, so we should ignore errors if NLL is (unconditionally)
125     /// enabled.
126     pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
127         // FIXME(Centril): Once we actually remove `::Migrate` also make
128         // this always `true` and then proceed to eliminate the dead code.
129         match tcx.borrowck_mode() {
130             // If we're on Migrate mode, report AST region errors
131             BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
132
133             // If we're on MIR, don't report AST region errors as they should be reported by NLL
134             BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
135         }
136     }
137 }
138
139 /// This type contains all the things within `InferCtxt` that sit within a
140 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
141 /// operations are hot enough that we want only one call to `borrow_mut` per
142 /// call to `start_snapshot` and `rollback_to`.
143 pub struct InferCtxtInner<'tcx> {
144     /// Cache for projections. This cache is snapshotted along with the infcx.
145     ///
146     /// Public so that `traits::project` can use it.
147     pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
148
149     /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
150     /// that might instantiate a general type variable have an order,
151     /// represented by its upper and lower bounds.
152     type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
153
154     /// Map from const parameter variable to the kind of const it represents.
155     const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
156
157     /// Map from integral variable to the kind of integer it represents.
158     int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
159
160     /// Map from floating variable to the kind of float it represents.
161     float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
162
163     /// Tracks the set of region variables and the constraints between them.
164     /// This is initially `Some(_)` but when
165     /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
166     /// -- further attempts to perform unification, etc., may fail if new
167     /// region constraints would've been added.
168     region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
169
170     /// A set of constraints that regionck must validate. Each
171     /// constraint has the form `T:'a`, meaning "some type `T` must
172     /// outlive the lifetime 'a". These constraints derive from
173     /// instantiated type parameters. So if you had a struct defined
174     /// like
175     ///
176     ///     struct Foo<T:'static> { ... }
177     ///
178     /// then in some expression `let x = Foo { ... }` it will
179     /// instantiate the type parameter `T` with a fresh type `$0`. At
180     /// the same time, it will record a region obligation of
181     /// `$0:'static`. This will get checked later by regionck. (We
182     /// can't generally check these things right away because we have
183     /// to wait until types are resolved.)
184     ///
185     /// These are stored in a map keyed to the id of the innermost
186     /// enclosing fn body / static initializer expression. This is
187     /// because the location where the obligation was incurred can be
188     /// relevant with respect to which sublifetime assumptions are in
189     /// place. The reason that we store under the fn-id, and not
190     /// something more fine-grained, is so that it is easier for
191     /// regionck to be sure that it has found *all* the region
192     /// obligations (otherwise, it's easy to fail to walk to a
193     /// particular node-id).
194     ///
195     /// Before running `resolve_regions_and_report_errors`, the creator
196     /// of the inference context is expected to invoke
197     /// `process_region_obligations` (defined in `self::region_obligations`)
198     /// for each body-id in this map, which will process the
199     /// obligations within. This is expected to be done 'late enough'
200     /// that all type inference variables have been bound and so forth.
201     region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
202
203     undo_log: InferCtxtUndoLogs<'tcx>,
204 }
205
206 impl<'tcx> InferCtxtInner<'tcx> {
207     fn new() -> InferCtxtInner<'tcx> {
208         InferCtxtInner {
209             projection_cache: Default::default(),
210             type_variable_storage: type_variable::TypeVariableStorage::new(),
211             undo_log: InferCtxtUndoLogs::default(),
212             const_unification_storage: ut::UnificationTableStorage::new(),
213             int_unification_storage: ut::UnificationTableStorage::new(),
214             float_unification_storage: ut::UnificationTableStorage::new(),
215             region_constraint_storage: Some(RegionConstraintStorage::new()),
216             region_obligations: vec![],
217         }
218     }
219
220     #[inline]
221     pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
222         &self.region_obligations
223     }
224
225     #[inline]
226     pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
227         self.projection_cache.with_log(&mut self.undo_log)
228     }
229
230     #[inline]
231     fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
232         self.type_variable_storage.with_log(&mut self.undo_log)
233     }
234
235     #[inline]
236     fn int_unification_table(
237         &mut self,
238     ) -> ut::UnificationTable<
239         ut::InPlace<
240             ty::IntVid,
241             &mut ut::UnificationStorage<ty::IntVid>,
242             &mut InferCtxtUndoLogs<'tcx>,
243         >,
244     > {
245         self.int_unification_storage.with_log(&mut self.undo_log)
246     }
247
248     #[inline]
249     fn float_unification_table(
250         &mut self,
251     ) -> ut::UnificationTable<
252         ut::InPlace<
253             ty::FloatVid,
254             &mut ut::UnificationStorage<ty::FloatVid>,
255             &mut InferCtxtUndoLogs<'tcx>,
256         >,
257     > {
258         self.float_unification_storage.with_log(&mut self.undo_log)
259     }
260
261     #[inline]
262     fn const_unification_table(
263         &mut self,
264     ) -> ut::UnificationTable<
265         ut::InPlace<
266             ty::ConstVid<'tcx>,
267             &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
268             &mut InferCtxtUndoLogs<'tcx>,
269         >,
270     > {
271         self.const_unification_storage.with_log(&mut self.undo_log)
272     }
273
274     #[inline]
275     pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
276         self.region_constraint_storage
277             .as_mut()
278             .expect("region constraints already solved")
279             .with_log(&mut self.undo_log)
280     }
281 }
282
283 pub struct InferCtxt<'a, 'tcx> {
284     pub tcx: TyCtxt<'tcx>,
285
286     /// During type-checking/inference of a body, `in_progress_typeck_results`
287     /// contains a reference to the typeck results being built up, which are
288     /// used for reading closure kinds/signatures as they are inferred,
289     /// and for error reporting logic to read arbitrary node types.
290     pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
291
292     pub inner: RefCell<InferCtxtInner<'tcx>>,
293
294     /// If set, this flag causes us to skip the 'leak check' during
295     /// higher-ranked subtyping operations. This flag is a temporary one used
296     /// to manage the removal of the leak-check: for the time being, we still run the
297     /// leak-check, but we issue warnings. This flag can only be set to true
298     /// when entering a snapshot.
299     skip_leak_check: Cell<bool>,
300
301     /// Once region inference is done, the values for each variable.
302     lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
303
304     /// Caches the results of trait selection. This cache is used
305     /// for things that have to do with the parameters in scope.
306     pub selection_cache: select::SelectionCache<'tcx>,
307
308     /// Caches the results of trait evaluation.
309     pub evaluation_cache: select::EvaluationCache<'tcx>,
310
311     /// the set of predicates on which errors have been reported, to
312     /// avoid reporting the same error twice.
313     pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
314
315     pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
316
317     /// When an error occurs, we want to avoid reporting "derived"
318     /// errors that are due to this original failure. Normally, we
319     /// handle this with the `err_count_on_creation` count, which
320     /// basically just tracks how many errors were reported when we
321     /// started type-checking a fn and checks to see if any new errors
322     /// have been reported since then. Not great, but it works.
323     ///
324     /// However, when errors originated in other passes -- notably
325     /// resolve -- this heuristic breaks down. Therefore, we have this
326     /// auxiliary flag that one can set whenever one creates a
327     /// type-error that is due to an error in a prior pass.
328     ///
329     /// Don't read this flag directly, call `is_tainted_by_errors()`
330     /// and `set_tainted_by_errors()`.
331     tainted_by_errors_flag: Cell<bool>,
332
333     /// Track how many errors were reported when this infcx is created.
334     /// If the number of errors increases, that's also a sign (line
335     /// `tained_by_errors`) to avoid reporting certain kinds of errors.
336     // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
337     err_count_on_creation: usize,
338
339     /// This flag is true while there is an active snapshot.
340     in_snapshot: Cell<bool>,
341
342     /// What is the innermost universe we have created? Starts out as
343     /// `UniverseIndex::root()` but grows from there as we enter
344     /// universal quantifiers.
345     ///
346     /// N.B., at present, we exclude the universal quantifiers on the
347     /// item we are type-checking, and just consider those names as
348     /// part of the root universe. So this would only get incremented
349     /// when we enter into a higher-ranked (`for<..>`) type or trait
350     /// bound.
351     universe: Cell<ty::UniverseIndex>,
352 }
353
354 /// A map returned by `replace_bound_vars_with_placeholders()`
355 /// indicating the placeholder region that each late-bound region was
356 /// replaced with.
357 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
358
359 /// See the `error_reporting` module for more details.
360 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
361 pub enum ValuePairs<'tcx> {
362     Types(ExpectedFound<Ty<'tcx>>),
363     Regions(ExpectedFound<ty::Region<'tcx>>),
364     Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
365     TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
366     PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
367 }
368
369 /// The trace designates the path through inference that we took to
370 /// encounter an error or subtyping constraint.
371 ///
372 /// See the `error_reporting` module for more details.
373 #[derive(Clone, Debug)]
374 pub struct TypeTrace<'tcx> {
375     cause: ObligationCause<'tcx>,
376     values: ValuePairs<'tcx>,
377 }
378
379 /// The origin of a `r1 <= r2` constraint.
380 ///
381 /// See `error_reporting` module for more details
382 #[derive(Clone, Debug)]
383 pub enum SubregionOrigin<'tcx> {
384     /// Arose from a subtyping relation
385     Subtype(Box<TypeTrace<'tcx>>),
386
387     /// When casting `&'a T` to an `&'b Trait` object,
388     /// relating `'a` to `'b`
389     RelateObjectBound(Span),
390
391     /// Some type parameter was instantiated with the given type,
392     /// and that type must outlive some region.
393     RelateParamBound(Span, Ty<'tcx>),
394
395     /// The given region parameter was instantiated with a region
396     /// that must outlive some other region.
397     RelateRegionParamBound(Span),
398
399     /// Creating a pointer `b` to contents of another reference
400     Reborrow(Span),
401
402     /// Creating a pointer `b` to contents of an upvar
403     ReborrowUpvar(Span, ty::UpvarId),
404
405     /// Data with type `Ty<'tcx>` was borrowed
406     DataBorrowed(Ty<'tcx>, Span),
407
408     /// (&'a &'b T) where a >= b
409     ReferenceOutlivesReferent(Ty<'tcx>, Span),
410
411     /// Region in return type of invoked fn must enclose call
412     CallReturn(Span),
413
414     /// Comparing the signature and requirements of an impl method against
415     /// the containing trait.
416     CompareImplMethodObligation {
417         span: Span,
418         item_name: Symbol,
419         impl_item_def_id: DefId,
420         trait_item_def_id: DefId,
421     },
422 }
423
424 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
425 #[cfg(target_arch = "x86_64")]
426 static_assert_size!(SubregionOrigin<'_>, 32);
427
428 /// Places that type/region parameters can appear.
429 #[derive(Clone, Copy, Debug)]
430 pub enum ParameterOrigin {
431     Path,               // foo::bar
432     MethodCall,         // foo.bar() <-- parameters on impl providing bar()
433     OverloadedOperator, // a + b when overloaded
434     OverloadedDeref,    // *a when overloaded
435 }
436
437 /// Times when we replace late-bound regions with variables:
438 #[derive(Clone, Copy, Debug)]
439 pub enum LateBoundRegionConversionTime {
440     /// when a fn is called
441     FnCall,
442
443     /// when two higher-ranked types are compared
444     HigherRankedType,
445
446     /// when projecting an associated type
447     AssocTypeProjection(DefId),
448 }
449
450 /// Reasons to create a region inference variable
451 ///
452 /// See `error_reporting` module for more details
453 #[derive(Copy, Clone, Debug)]
454 pub enum RegionVariableOrigin {
455     /// Region variables created for ill-categorized reasons,
456     /// mostly indicates places in need of refactoring
457     MiscVariable(Span),
458
459     /// Regions created by a `&P` or `[...]` pattern
460     PatternRegion(Span),
461
462     /// Regions created by `&` operator
463     AddrOfRegion(Span),
464
465     /// Regions created as part of an autoref of a method receiver
466     Autoref(Span, ty::AssocItem),
467
468     /// Regions created as part of an automatic coercion
469     Coercion(Span),
470
471     /// Region variables created as the values for early-bound regions
472     EarlyBoundRegion(Span, Symbol),
473
474     /// Region variables created for bound regions
475     /// in a function or method that is called
476     LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
477
478     UpvarRegion(ty::UpvarId, Span),
479
480     BoundRegionInCoherence(Symbol),
481
482     /// This origin is used for the inference variables that we create
483     /// during NLL region processing.
484     NLL(NLLRegionVariableOrigin),
485 }
486
487 #[derive(Copy, Clone, Debug)]
488 pub enum NLLRegionVariableOrigin {
489     /// During NLL region processing, we create variables for free
490     /// regions that we encounter in the function signature and
491     /// elsewhere. This origin indices we've got one of those.
492     FreeRegion,
493
494     /// "Universal" instantiation of a higher-ranked region (e.g.,
495     /// from a `for<'a> T` binder). Meant to represent "any region".
496     Placeholder(ty::PlaceholderRegion),
497
498     /// The variable we create to represent `'empty(U0)`.
499     RootEmptyRegion,
500
501     Existential {
502         /// If this is true, then this variable was created to represent a lifetime
503         /// bound in a `for` binder. For example, it might have been created to
504         /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
505         /// Such variables are created when we are trying to figure out if there
506         /// is any valid instantiation of `'a` that could fit into some scenario.
507         ///
508         /// This is used to inform error reporting: in the case that we are trying to
509         /// determine whether there is any valid instantiation of a `'a` variable that meets
510         /// some constraint C, we want to blame the "source" of that `for` type,
511         /// rather than blaming the source of the constraint C.
512         from_forall: bool,
513     },
514 }
515
516 impl NLLRegionVariableOrigin {
517     pub fn is_universal(self) -> bool {
518         match self {
519             NLLRegionVariableOrigin::FreeRegion => true,
520             NLLRegionVariableOrigin::Placeholder(..) => true,
521             NLLRegionVariableOrigin::Existential { .. } => false,
522             NLLRegionVariableOrigin::RootEmptyRegion => false,
523         }
524     }
525
526     pub fn is_existential(self) -> bool {
527         !self.is_universal()
528     }
529 }
530
531 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
532 #[derive(Copy, Clone, Debug)]
533 pub enum FixupError<'tcx> {
534     UnresolvedIntTy(IntVid),
535     UnresolvedFloatTy(FloatVid),
536     UnresolvedTy(TyVid),
537     UnresolvedConst(ConstVid<'tcx>),
538 }
539
540 /// See the `region_obligations` field for more information.
541 #[derive(Clone)]
542 pub struct RegionObligation<'tcx> {
543     pub sub_region: ty::Region<'tcx>,
544     pub sup_type: Ty<'tcx>,
545     pub origin: SubregionOrigin<'tcx>,
546 }
547
548 impl<'tcx> fmt::Display for FixupError<'tcx> {
549     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550         use self::FixupError::*;
551
552         match *self {
553             UnresolvedIntTy(_) => write!(
554                 f,
555                 "cannot determine the type of this integer; \
556                  add a suffix to specify the type explicitly"
557             ),
558             UnresolvedFloatTy(_) => write!(
559                 f,
560                 "cannot determine the type of this number; \
561                  add a suffix to specify the type explicitly"
562             ),
563             UnresolvedTy(_) => write!(f, "unconstrained type"),
564             UnresolvedConst(_) => write!(f, "unconstrained const value"),
565         }
566     }
567 }
568
569 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
570 /// Necessary because we can't write the following bound:
571 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
572 pub struct InferCtxtBuilder<'tcx> {
573     tcx: TyCtxt<'tcx>,
574     fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
575 }
576
577 pub trait TyCtxtInferExt<'tcx> {
578     fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
579 }
580
581 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
582     fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
583         InferCtxtBuilder { tcx: self, fresh_typeck_results: None }
584     }
585 }
586
587 impl<'tcx> InferCtxtBuilder<'tcx> {
588     /// Used only by `rustc_typeck` during body type-checking/inference,
589     /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
590     pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
591         self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
592         self
593     }
594
595     /// Given a canonical value `C` as a starting point, create an
596     /// inference context that contains each of the bound values
597     /// within instantiated as a fresh variable. The `f` closure is
598     /// invoked with the new infcx, along with the instantiated value
599     /// `V` and a substitution `S`. This substitution `S` maps from
600     /// the bound values in `C` to their instantiated values in `V`
601     /// (in other words, `S(C) = V`).
602     pub fn enter_with_canonical<T, R>(
603         &mut self,
604         span: Span,
605         canonical: &Canonical<'tcx, T>,
606         f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
607     ) -> R
608     where
609         T: TypeFoldable<'tcx>,
610     {
611         self.enter(|infcx| {
612             let (value, subst) =
613                 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
614             f(infcx, value, subst)
615         })
616     }
617
618     pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
619         let InferCtxtBuilder { tcx, ref fresh_typeck_results } = *self;
620         let in_progress_typeck_results = fresh_typeck_results.as_ref();
621         f(InferCtxt {
622             tcx,
623             in_progress_typeck_results,
624             inner: RefCell::new(InferCtxtInner::new()),
625             lexical_region_resolutions: RefCell::new(None),
626             selection_cache: Default::default(),
627             evaluation_cache: Default::default(),
628             reported_trait_errors: Default::default(),
629             reported_closure_mismatch: Default::default(),
630             tainted_by_errors_flag: Cell::new(false),
631             err_count_on_creation: tcx.sess.err_count(),
632             in_snapshot: Cell::new(false),
633             skip_leak_check: Cell::new(false),
634             universe: Cell::new(ty::UniverseIndex::ROOT),
635         })
636     }
637 }
638
639 impl<'tcx, T> InferOk<'tcx, T> {
640     pub fn unit(self) -> InferOk<'tcx, ()> {
641         InferOk { value: (), obligations: self.obligations }
642     }
643
644     /// Extracts `value`, registering any obligations into `fulfill_cx`.
645     pub fn into_value_registering_obligations(
646         self,
647         infcx: &InferCtxt<'_, 'tcx>,
648         fulfill_cx: &mut dyn TraitEngine<'tcx>,
649     ) -> T {
650         let InferOk { value, obligations } = self;
651         for obligation in obligations {
652             fulfill_cx.register_predicate_obligation(infcx, obligation);
653         }
654         value
655     }
656 }
657
658 impl<'tcx> InferOk<'tcx, ()> {
659     pub fn into_obligations(self) -> PredicateObligations<'tcx> {
660         self.obligations
661     }
662 }
663
664 #[must_use = "once you start a snapshot, you should always consume it"]
665 pub struct CombinedSnapshot<'a, 'tcx> {
666     undo_snapshot: Snapshot<'tcx>,
667     region_constraints_snapshot: RegionSnapshot,
668     universe: ty::UniverseIndex,
669     was_in_snapshot: bool,
670     _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
671 }
672
673 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
674     pub fn is_in_snapshot(&self) -> bool {
675         self.in_snapshot.get()
676     }
677
678     pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
679         t.fold_with(&mut self.freshener())
680     }
681
682     pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
683         match ty.kind {
684             ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
685             _ => false,
686         }
687     }
688
689     pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
690         freshen::TypeFreshener::new(self)
691     }
692
693     pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
694         use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
695         use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
696         match ty.kind {
697             ty::Infer(ty::IntVar(vid)) => {
698                 if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
699                     Neither
700                 } else {
701                     UnconstrainedInt
702                 }
703             }
704             ty::Infer(ty::FloatVar(vid)) => {
705                 if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
706                     Neither
707                 } else {
708                     UnconstrainedFloat
709                 }
710             }
711             _ => Neither,
712         }
713     }
714
715     pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
716         let mut inner = self.inner.borrow_mut();
717         // FIXME(const_generics): should there be an equivalent function for const variables?
718
719         let mut vars: Vec<Ty<'_>> = inner
720             .type_variables()
721             .unsolved_variables()
722             .into_iter()
723             .map(|t| self.tcx.mk_ty_var(t))
724             .collect();
725         vars.extend(
726             (0..inner.int_unification_table().len())
727                 .map(|i| ty::IntVid { index: i as u32 })
728                 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
729                 .map(|v| self.tcx.mk_int_var(v)),
730         );
731         vars.extend(
732             (0..inner.float_unification_table().len())
733                 .map(|i| ty::FloatVid { index: i as u32 })
734                 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
735                 .map(|v| self.tcx.mk_float_var(v)),
736         );
737         vars
738     }
739
740     fn combine_fields(
741         &'a self,
742         trace: TypeTrace<'tcx>,
743         param_env: ty::ParamEnv<'tcx>,
744     ) -> CombineFields<'a, 'tcx> {
745         CombineFields {
746             infcx: self,
747             trace,
748             cause: None,
749             param_env,
750             obligations: PredicateObligations::new(),
751         }
752     }
753
754     /// Clear the "currently in a snapshot" flag, invoke the closure,
755     /// then restore the flag to its original value. This flag is a
756     /// debugging measure designed to detect cases where we start a
757     /// snapshot, create type variables, and register obligations
758     /// which may involve those type variables in the fulfillment cx,
759     /// potentially leaving "dangling type variables" behind.
760     /// In such cases, an assertion will fail when attempting to
761     /// register obligations, within a snapshot. Very useful, much
762     /// better than grovelling through megabytes of `RUSTC_LOG` output.
763     ///
764     /// HOWEVER, in some cases the flag is unhelpful. In particular, we
765     /// sometimes create a "mini-fulfilment-cx" in which we enroll
766     /// obligations. As long as this fulfillment cx is fully drained
767     /// before we return, this is not a problem, as there won't be any
768     /// escaping obligations in the main cx. In those cases, you can
769     /// use this function.
770     pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
771     where
772         F: FnOnce(&Self) -> R,
773     {
774         let flag = self.in_snapshot.replace(false);
775         let result = func(self);
776         self.in_snapshot.set(flag);
777         result
778     }
779
780     fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
781         debug!("start_snapshot()");
782
783         let in_snapshot = self.in_snapshot.replace(true);
784
785         let mut inner = self.inner.borrow_mut();
786
787         CombinedSnapshot {
788             undo_snapshot: inner.undo_log.start_snapshot(),
789             region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
790             universe: self.universe(),
791             was_in_snapshot: in_snapshot,
792             // Borrow typeck results "in progress" (i.e., during typeck)
793             // to ban writes from within a snapshot to them.
794             _in_progress_typeck_results: self
795                 .in_progress_typeck_results
796                 .map(|typeck_results| typeck_results.borrow()),
797         }
798     }
799
800     fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
801         debug!("rollback_to(cause={})", cause);
802         let CombinedSnapshot {
803             undo_snapshot,
804             region_constraints_snapshot,
805             universe,
806             was_in_snapshot,
807             _in_progress_typeck_results,
808         } = snapshot;
809
810         self.in_snapshot.set(was_in_snapshot);
811         self.universe.set(universe);
812
813         let mut inner = self.inner.borrow_mut();
814         inner.rollback_to(undo_snapshot);
815         inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
816     }
817
818     fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
819         debug!("commit_from()");
820         let CombinedSnapshot {
821             undo_snapshot,
822             region_constraints_snapshot: _,
823             universe: _,
824             was_in_snapshot,
825             _in_progress_typeck_results,
826         } = snapshot;
827
828         self.in_snapshot.set(was_in_snapshot);
829
830         self.inner.borrow_mut().commit(undo_snapshot);
831     }
832
833     /// Executes `f` and commit the bindings.
834     pub fn commit_unconditionally<R, F>(&self, f: F) -> R
835     where
836         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
837     {
838         debug!("commit_unconditionally()");
839         let snapshot = self.start_snapshot();
840         let r = f(&snapshot);
841         self.commit_from(snapshot);
842         r
843     }
844
845     /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
846     pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
847     where
848         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
849     {
850         debug!("commit_if_ok()");
851         let snapshot = self.start_snapshot();
852         let r = f(&snapshot);
853         debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
854         match r {
855             Ok(_) => {
856                 self.commit_from(snapshot);
857             }
858             Err(_) => {
859                 self.rollback_to("commit_if_ok -- error", snapshot);
860             }
861         }
862         r
863     }
864
865     /// Execute `f` then unroll any bindings it creates.
866     pub fn probe<R, F>(&self, f: F) -> R
867     where
868         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
869     {
870         debug!("probe()");
871         let snapshot = self.start_snapshot();
872         let r = f(&snapshot);
873         self.rollback_to("probe", snapshot);
874         r
875     }
876
877     /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
878     pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
879     where
880         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
881     {
882         debug!("probe()");
883         let snapshot = self.start_snapshot();
884         let was_skip_leak_check = self.skip_leak_check.get();
885         if should_skip {
886             self.skip_leak_check.set(true);
887         }
888         let r = f(&snapshot);
889         self.rollback_to("probe", snapshot);
890         self.skip_leak_check.set(was_skip_leak_check);
891         r
892     }
893
894     /// Scan the constraints produced since `snapshot` began and returns:
895     ///
896     /// - `None` -- if none of them involve "region outlives" constraints
897     /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
898     /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
899     pub fn region_constraints_added_in_snapshot(
900         &self,
901         snapshot: &CombinedSnapshot<'a, 'tcx>,
902     ) -> Option<bool> {
903         self.inner
904             .borrow_mut()
905             .unwrap_region_constraints()
906             .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
907     }
908
909     pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
910         self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
911     }
912
913     pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
914     where
915         T: at::ToTrace<'tcx>,
916     {
917         let origin = &ObligationCause::dummy();
918         self.probe(|_| {
919             self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
920                 // Ignore obligations, since we are unrolling
921                 // everything anyway.
922             })
923         })
924     }
925
926     pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
927     where
928         T: at::ToTrace<'tcx>,
929     {
930         let origin = &ObligationCause::dummy();
931         self.probe(|_| {
932             self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
933                 // Ignore obligations, since we are unrolling
934                 // everything anyway.
935             })
936         })
937     }
938
939     pub fn sub_regions(
940         &self,
941         origin: SubregionOrigin<'tcx>,
942         a: ty::Region<'tcx>,
943         b: ty::Region<'tcx>,
944     ) {
945         debug!("sub_regions({:?} <: {:?})", a, b);
946         self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
947     }
948
949     /// Require that the region `r` be equal to one of the regions in
950     /// the set `regions`.
951     pub fn member_constraint(
952         &self,
953         opaque_type_def_id: DefId,
954         definition_span: Span,
955         hidden_ty: Ty<'tcx>,
956         region: ty::Region<'tcx>,
957         in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
958     ) {
959         debug!("member_constraint({:?} <: {:?})", region, in_regions);
960         self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
961             opaque_type_def_id,
962             definition_span,
963             hidden_ty,
964             region,
965             in_regions,
966         );
967     }
968
969     pub fn subtype_predicate(
970         &self,
971         cause: &ObligationCause<'tcx>,
972         param_env: ty::ParamEnv<'tcx>,
973         predicate: ty::PolySubtypePredicate<'tcx>,
974     ) -> Option<InferResult<'tcx, ()>> {
975         // Subtle: it's ok to skip the binder here and resolve because
976         // `shallow_resolve` just ignores anything that is not a type
977         // variable, and because type variable's can't (at present, at
978         // least) capture any of the things bound by this binder.
979         //
980         // NOTE(nmatsakis): really, there is no *particular* reason to do this
981         // `shallow_resolve` here except as a micro-optimization.
982         // Naturally I could not resist.
983         let two_unbound_type_vars = {
984             let a = self.shallow_resolve(predicate.skip_binder().a);
985             let b = self.shallow_resolve(predicate.skip_binder().b);
986             a.is_ty_var() && b.is_ty_var()
987         };
988
989         if two_unbound_type_vars {
990             // Two unbound type variables? Can't make progress.
991             return None;
992         }
993
994         Some(self.commit_if_ok(|_snapshot| {
995             let (ty::SubtypePredicate { a_is_expected, a, b }, _) =
996                 self.replace_bound_vars_with_placeholders(&predicate);
997
998             let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
999
1000             Ok(ok.unit())
1001         }))
1002     }
1003
1004     pub fn region_outlives_predicate(
1005         &self,
1006         cause: &traits::ObligationCause<'tcx>,
1007         predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1008     ) -> UnitResult<'tcx> {
1009         self.commit_if_ok(|_snapshot| {
1010             let (ty::OutlivesPredicate(r_a, r_b), _) =
1011                 self.replace_bound_vars_with_placeholders(&predicate);
1012             let origin = SubregionOrigin::from_obligation_cause(cause, || {
1013                 RelateRegionParamBound(cause.span)
1014             });
1015             self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1016             Ok(())
1017         })
1018     }
1019
1020     pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1021         self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
1022     }
1023
1024     pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1025         self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1026     }
1027
1028     pub fn next_ty_var_in_universe(
1029         &self,
1030         origin: TypeVariableOrigin,
1031         universe: ty::UniverseIndex,
1032     ) -> Ty<'tcx> {
1033         let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
1034         self.tcx.mk_ty_var(vid)
1035     }
1036
1037     pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1038         self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1039     }
1040
1041     pub fn next_const_var(
1042         &self,
1043         ty: Ty<'tcx>,
1044         origin: ConstVariableOrigin,
1045     ) -> &'tcx ty::Const<'tcx> {
1046         self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1047     }
1048
1049     pub fn next_const_var_in_universe(
1050         &self,
1051         ty: Ty<'tcx>,
1052         origin: ConstVariableOrigin,
1053         universe: ty::UniverseIndex,
1054     ) -> &'tcx ty::Const<'tcx> {
1055         let vid = self
1056             .inner
1057             .borrow_mut()
1058             .const_unification_table()
1059             .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1060         self.tcx.mk_const_var(vid, ty)
1061     }
1062
1063     pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1064         self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1065             origin,
1066             val: ConstVariableValue::Unknown { universe: self.universe() },
1067         })
1068     }
1069
1070     fn next_int_var_id(&self) -> IntVid {
1071         self.inner.borrow_mut().int_unification_table().new_key(None)
1072     }
1073
1074     pub fn next_int_var(&self) -> Ty<'tcx> {
1075         self.tcx.mk_int_var(self.next_int_var_id())
1076     }
1077
1078     fn next_float_var_id(&self) -> FloatVid {
1079         self.inner.borrow_mut().float_unification_table().new_key(None)
1080     }
1081
1082     pub fn next_float_var(&self) -> Ty<'tcx> {
1083         self.tcx.mk_float_var(self.next_float_var_id())
1084     }
1085
1086     /// Creates a fresh region variable with the next available index.
1087     /// The variable will be created in the maximum universe created
1088     /// thus far, allowing it to name any region created thus far.
1089     pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1090         self.next_region_var_in_universe(origin, self.universe())
1091     }
1092
1093     /// Creates a fresh region variable with the next available index
1094     /// in the given universe; typically, you can use
1095     /// `next_region_var` and just use the maximal universe.
1096     pub fn next_region_var_in_universe(
1097         &self,
1098         origin: RegionVariableOrigin,
1099         universe: ty::UniverseIndex,
1100     ) -> ty::Region<'tcx> {
1101         let region_var =
1102             self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1103         self.tcx.mk_region(ty::ReVar(region_var))
1104     }
1105
1106     /// Return the universe that the region `r` was created in.  For
1107     /// most regions (e.g., `'static`, named regions from the user,
1108     /// etc) this is the root universe U0. For inference variables or
1109     /// placeholders, however, it will return the universe which which
1110     /// they are associated.
1111     fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1112         self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1113     }
1114
1115     /// Number of region variables created so far.
1116     pub fn num_region_vars(&self) -> usize {
1117         self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1118     }
1119
1120     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1121     pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1122         self.next_region_var(RegionVariableOrigin::NLL(origin))
1123     }
1124
1125     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1126     pub fn next_nll_region_var_in_universe(
1127         &self,
1128         origin: NLLRegionVariableOrigin,
1129         universe: ty::UniverseIndex,
1130     ) -> ty::Region<'tcx> {
1131         self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1132     }
1133
1134     pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1135         match param.kind {
1136             GenericParamDefKind::Lifetime => {
1137                 // Create a region inference variable for the given
1138                 // region parameter definition.
1139                 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1140             }
1141             GenericParamDefKind::Type { .. } => {
1142                 // Create a type inference variable for the given
1143                 // type parameter definition. The substitutions are
1144                 // for actual parameters that may be referred to by
1145                 // the default of this type parameter, if it exists.
1146                 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1147                 // used in a path such as `Foo::<T, U>::new()` will
1148                 // use an inference variable for `C` with `[T, U]`
1149                 // as the substitutions for the default, `(T, U)`.
1150                 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1151                     self.universe(),
1152                     false,
1153                     TypeVariableOrigin {
1154                         kind: TypeVariableOriginKind::TypeParameterDefinition(
1155                             param.name,
1156                             Some(param.def_id),
1157                         ),
1158                         span,
1159                     },
1160                 );
1161
1162                 self.tcx.mk_ty_var(ty_var_id).into()
1163             }
1164             GenericParamDefKind::Const { .. } => {
1165                 let origin = ConstVariableOrigin {
1166                     kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1167                     span,
1168                 };
1169                 let const_var_id =
1170                     self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1171                         origin,
1172                         val: ConstVariableValue::Unknown { universe: self.universe() },
1173                     });
1174                 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1175             }
1176         }
1177     }
1178
1179     /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1180     /// type/region parameter to a fresh inference variable.
1181     pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1182         InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1183     }
1184
1185     /// Returns `true` if errors have been reported since this infcx was
1186     /// created. This is sometimes used as a heuristic to skip
1187     /// reporting errors that often occur as a result of earlier
1188     /// errors, but where it's hard to be 100% sure (e.g., unresolved
1189     /// inference variables, regionck errors).
1190     pub fn is_tainted_by_errors(&self) -> bool {
1191         debug!(
1192             "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1193              tainted_by_errors_flag={})",
1194             self.tcx.sess.err_count(),
1195             self.err_count_on_creation,
1196             self.tainted_by_errors_flag.get()
1197         );
1198
1199         if self.tcx.sess.err_count() > self.err_count_on_creation {
1200             return true; // errors reported since this infcx was made
1201         }
1202         self.tainted_by_errors_flag.get()
1203     }
1204
1205     /// Set the "tainted by errors" flag to true. We call this when we
1206     /// observe an error from a prior pass.
1207     pub fn set_tainted_by_errors(&self) {
1208         debug!("set_tainted_by_errors()");
1209         self.tainted_by_errors_flag.set(true)
1210     }
1211
1212     /// Process the region constraints and report any errors that
1213     /// result. After this, no more unification operations should be
1214     /// done -- or the compiler will panic -- but it is legal to use
1215     /// `resolve_vars_if_possible` as well as `fully_resolve`.
1216     pub fn resolve_regions_and_report_errors(
1217         &self,
1218         region_context: DefId,
1219         outlives_env: &OutlivesEnvironment<'tcx>,
1220         mode: RegionckMode,
1221     ) {
1222         let (var_infos, data) = {
1223             let mut inner = self.inner.borrow_mut();
1224             let inner = &mut *inner;
1225             assert!(
1226                 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1227                 "region_obligations not empty: {:#?}",
1228                 inner.region_obligations
1229             );
1230             inner
1231                 .region_constraint_storage
1232                 .take()
1233                 .expect("regions already resolved")
1234                 .with_log(&mut inner.undo_log)
1235                 .into_infos_and_data()
1236         };
1237
1238         let region_rels =
1239             &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1240
1241         let (lexical_region_resolutions, errors) =
1242             lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1243
1244         let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1245         assert!(old_value.is_none());
1246
1247         if !self.is_tainted_by_errors() {
1248             // As a heuristic, just skip reporting region errors
1249             // altogether if other errors have been reported while
1250             // this infcx was in use.  This is totally hokey but
1251             // otherwise we have a hard time separating legit region
1252             // errors from silly ones.
1253             self.report_region_errors(&errors);
1254         }
1255     }
1256
1257     /// Obtains (and clears) the current set of region
1258     /// constraints. The inference context is still usable: further
1259     /// unifications will simply add new constraints.
1260     ///
1261     /// This method is not meant to be used with normal lexical region
1262     /// resolution. Rather, it is used in the NLL mode as a kind of
1263     /// interim hack: basically we run normal type-check and generate
1264     /// region constraints as normal, but then we take them and
1265     /// translate them into the form that the NLL solver
1266     /// understands. See the NLL module for mode details.
1267     pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1268         assert!(
1269             self.inner.borrow().region_obligations.is_empty(),
1270             "region_obligations not empty: {:#?}",
1271             self.inner.borrow().region_obligations
1272         );
1273
1274         self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1275     }
1276
1277     /// Gives temporary access to the region constraint data.
1278     #[allow(non_camel_case_types)] // bug with impl trait
1279     pub fn with_region_constraints<R>(
1280         &self,
1281         op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1282     ) -> R {
1283         let mut inner = self.inner.borrow_mut();
1284         op(inner.unwrap_region_constraints().data())
1285     }
1286
1287     /// Takes ownership of the list of variable regions. This implies
1288     /// that all the region constraints have already been taken, and
1289     /// hence that `resolve_regions_and_report_errors` can never be
1290     /// called. This is used only during NLL processing to "hand off" ownership
1291     /// of the set of region variables into the NLL region context.
1292     pub fn take_region_var_origins(&self) -> VarInfos {
1293         let mut inner = self.inner.borrow_mut();
1294         let (var_infos, data) = inner
1295             .region_constraint_storage
1296             .take()
1297             .expect("regions already resolved")
1298             .with_log(&mut inner.undo_log)
1299             .into_infos_and_data();
1300         assert!(data.is_empty());
1301         var_infos
1302     }
1303
1304     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1305         self.resolve_vars_if_possible(&t).to_string()
1306     }
1307
1308     pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1309         let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1310         format!("({})", tstrs.join(", "))
1311     }
1312
1313     pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1314         self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1315     }
1316
1317     /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1318     /// universe index of `TyVar(vid)`.
1319     pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1320         use self::type_variable::TypeVariableValue;
1321
1322         match self.inner.borrow_mut().type_variables().probe(vid) {
1323             TypeVariableValue::Known { value } => Ok(value),
1324             TypeVariableValue::Unknown { universe } => Err(universe),
1325         }
1326     }
1327
1328     /// Resolve any type variables found in `value` -- but only one
1329     /// level.  So, if the variable `?X` is bound to some type
1330     /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1331     /// itself be bound to a type).
1332     ///
1333     /// Useful when you only need to inspect the outermost level of
1334     /// the type and don't care about nested types (or perhaps you
1335     /// will be resolving them as well, e.g. in a loop).
1336     pub fn shallow_resolve<T>(&self, value: T) -> T
1337     where
1338         T: TypeFoldable<'tcx>,
1339     {
1340         value.fold_with(&mut ShallowResolver { infcx: self })
1341     }
1342
1343     pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1344         self.inner.borrow_mut().type_variables().root_var(var)
1345     }
1346
1347     /// Where possible, replaces type/const variables in
1348     /// `value` with their final value. Note that region variables
1349     /// are unaffected. If a type/const variable has not been unified, it
1350     /// is left as is. This is an idempotent operation that does
1351     /// not affect inference state in any way and so you can do it
1352     /// at will.
1353     pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1354     where
1355         T: TypeFoldable<'tcx>,
1356     {
1357         if !value.needs_infer() {
1358             return value.clone(); // Avoid duplicated subst-folding.
1359         }
1360         let mut r = resolve::OpportunisticVarResolver::new(self);
1361         value.fold_with(&mut r)
1362     }
1363
1364     /// Returns the first unresolved variable contained in `T`. In the
1365     /// process of visiting `T`, this will resolve (where possible)
1366     /// type variables in `T`, but it never constructs the final,
1367     /// resolved type, so it's more efficient than
1368     /// `resolve_vars_if_possible()`.
1369     pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1370     where
1371         T: TypeFoldable<'tcx>,
1372     {
1373         let mut r = resolve::UnresolvedTypeFinder::new(self);
1374         value.visit_with(&mut r);
1375         r.first_unresolved
1376     }
1377
1378     pub fn probe_const_var(
1379         &self,
1380         vid: ty::ConstVid<'tcx>,
1381     ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1382         match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1383             ConstVariableValue::Known { value } => Ok(value),
1384             ConstVariableValue::Unknown { universe } => Err(universe),
1385         }
1386     }
1387
1388     pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1389         /*!
1390          * Attempts to resolve all type/region/const variables in
1391          * `value`. Region inference must have been run already (e.g.,
1392          * by calling `resolve_regions_and_report_errors`). If some
1393          * variable was never unified, an `Err` results.
1394          *
1395          * This method is idempotent, but it not typically not invoked
1396          * except during the writeback phase.
1397          */
1398
1399         resolve::fully_resolve(self, value)
1400     }
1401
1402     // [Note-Type-error-reporting]
1403     // An invariant is that anytime the expected or actual type is Error (the special
1404     // error type, meaning that an error occurred when typechecking this expression),
1405     // this is a derived error. The error cascaded from another error (that was already
1406     // reported), so it's not useful to display it to the user.
1407     // The following methods implement this logic.
1408     // They check if either the actual or expected type is Error, and don't print the error
1409     // in this case. The typechecker should only ever report type errors involving mismatched
1410     // types using one of these methods, and should not call span_err directly for such
1411     // errors.
1412
1413     pub fn type_error_struct_with_diag<M>(
1414         &self,
1415         sp: Span,
1416         mk_diag: M,
1417         actual_ty: Ty<'tcx>,
1418     ) -> DiagnosticBuilder<'tcx>
1419     where
1420         M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1421     {
1422         let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1423         debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1424
1425         // Don't report an error if actual type is `Error`.
1426         if actual_ty.references_error() {
1427             return self.tcx.sess.diagnostic().struct_dummy();
1428         }
1429
1430         mk_diag(self.ty_to_string(actual_ty))
1431     }
1432
1433     pub fn report_mismatched_types(
1434         &self,
1435         cause: &ObligationCause<'tcx>,
1436         expected: Ty<'tcx>,
1437         actual: Ty<'tcx>,
1438         err: TypeError<'tcx>,
1439     ) -> DiagnosticBuilder<'tcx> {
1440         let trace = TypeTrace::types(cause, true, expected, actual);
1441         self.report_and_explain_type_error(trace, &err)
1442     }
1443
1444     pub fn report_mismatched_consts(
1445         &self,
1446         cause: &ObligationCause<'tcx>,
1447         expected: &'tcx ty::Const<'tcx>,
1448         actual: &'tcx ty::Const<'tcx>,
1449         err: TypeError<'tcx>,
1450     ) -> DiagnosticBuilder<'tcx> {
1451         let trace = TypeTrace::consts(cause, true, expected, actual);
1452         self.report_and_explain_type_error(trace, &err)
1453     }
1454
1455     pub fn replace_bound_vars_with_fresh_vars<T>(
1456         &self,
1457         span: Span,
1458         lbrct: LateBoundRegionConversionTime,
1459         value: &ty::Binder<T>,
1460     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1461     where
1462         T: TypeFoldable<'tcx>,
1463     {
1464         let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1465         let fld_t = |_| {
1466             self.next_ty_var(TypeVariableOrigin {
1467                 kind: TypeVariableOriginKind::MiscVariable,
1468                 span,
1469             })
1470         };
1471         let fld_c = |_, ty| {
1472             self.next_const_var(
1473                 ty,
1474                 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1475             )
1476         };
1477         self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1478     }
1479
1480     /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1481     pub fn verify_generic_bound(
1482         &self,
1483         origin: SubregionOrigin<'tcx>,
1484         kind: GenericKind<'tcx>,
1485         a: ty::Region<'tcx>,
1486         bound: VerifyBound<'tcx>,
1487     ) {
1488         debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1489
1490         self.inner
1491             .borrow_mut()
1492             .unwrap_region_constraints()
1493             .verify_generic_bound(origin, kind, a, bound);
1494     }
1495
1496     /// Obtains the latest type of the given closure; this may be a
1497     /// closure in the current function, in which case its
1498     /// `ClosureKind` may not yet be known.
1499     pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1500         let closure_kind_ty = closure_substs.as_closure().kind_ty();
1501         let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1502         closure_kind_ty.to_opt_closure_kind()
1503     }
1504
1505     /// Clears the selection, evaluation, and projection caches. This is useful when
1506     /// repeatedly attempting to select an `Obligation` while changing only
1507     /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1508     pub fn clear_caches(&self) {
1509         self.selection_cache.clear();
1510         self.evaluation_cache.clear();
1511         self.inner.borrow_mut().projection_cache().clear();
1512     }
1513
1514     fn universe(&self) -> ty::UniverseIndex {
1515         self.universe.get()
1516     }
1517
1518     /// Creates and return a fresh universe that extends all previous
1519     /// universes. Updates `self.universe` to that new universe.
1520     pub fn create_next_universe(&self) -> ty::UniverseIndex {
1521         let u = self.universe.get().next_universe();
1522         self.universe.set(u);
1523         u
1524     }
1525
1526     /// Resolves and evaluates a constant.
1527     ///
1528     /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1529     /// substitutions and environment are used to resolve the constant. Alternatively if the
1530     /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1531     /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1532     /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1533     /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1534     /// returned.
1535     ///
1536     /// This handles inferences variables within both `param_env` and `substs` by
1537     /// performing the operation on their respective canonical forms.
1538     pub fn const_eval_resolve(
1539         &self,
1540         param_env: ty::ParamEnv<'tcx>,
1541         def: ty::WithOptConstParam<DefId>,
1542         substs: SubstsRef<'tcx>,
1543         promoted: Option<mir::Promoted>,
1544         span: Option<Span>,
1545     ) -> ConstEvalResult<'tcx> {
1546         let mut original_values = OriginalQueryValues::default();
1547         let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1548
1549         let (param_env, substs) = canonical.value;
1550         // The return value is the evaluated value which doesn't contain any reference to inference
1551         // variables, thus we don't need to substitute back the original values.
1552         self.tcx.const_eval_resolve(param_env, def, substs, promoted, span)
1553     }
1554
1555     /// If `typ` is a type variable of some kind, resolve it one level
1556     /// (but do not resolve types found in the result). If `typ` is
1557     /// not a type variable, just return it unmodified.
1558     // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1559     fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1560         match typ.kind {
1561             ty::Infer(ty::TyVar(v)) => {
1562                 // Not entirely obvious: if `typ` is a type variable,
1563                 // it can be resolved to an int/float variable, which
1564                 // can then be recursively resolved, hence the
1565                 // recursion. Note though that we prevent type
1566                 // variables from unifying to other type variables
1567                 // directly (though they may be embedded
1568                 // structurally), and we prevent cycles in any case,
1569                 // so this recursion should always be of very limited
1570                 // depth.
1571                 //
1572                 // Note: if these two lines are combined into one we get
1573                 // dynamic borrow errors on `self.inner`.
1574                 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1575                 known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
1576             }
1577
1578             ty::Infer(ty::IntVar(v)) => self
1579                 .inner
1580                 .borrow_mut()
1581                 .int_unification_table()
1582                 .probe_value(v)
1583                 .map(|v| v.to_type(self.tcx))
1584                 .unwrap_or(typ),
1585
1586             ty::Infer(ty::FloatVar(v)) => self
1587                 .inner
1588                 .borrow_mut()
1589                 .float_unification_table()
1590                 .probe_value(v)
1591                 .map(|v| v.to_type(self.tcx))
1592                 .unwrap_or(typ),
1593
1594             _ => typ,
1595         }
1596     }
1597
1598     /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1599     ///   * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1600     ///   * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1601     ///
1602     /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1603     /// inlined, despite being large, because it has only two call sites that
1604     /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1605     /// inference variables), and it handles both `Ty` and `ty::Const` without
1606     /// having to resort to storing full `GenericArg`s in `stalled_on`.
1607     #[inline(always)]
1608     pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1609         match infer_var {
1610             TyOrConstInferVar::Ty(v) => {
1611                 use self::type_variable::TypeVariableValue;
1612
1613                 // If `inlined_probe` returns a `Known` value, it never equals
1614                 // `ty::Infer(ty::TyVar(v))`.
1615                 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1616                     TypeVariableValue::Unknown { .. } => false,
1617                     TypeVariableValue::Known { .. } => true,
1618                 }
1619             }
1620
1621             TyOrConstInferVar::TyInt(v) => {
1622                 // If `inlined_probe_value` returns a value it's always a
1623                 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1624                 // `ty::Infer(_)`.
1625                 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1626             }
1627
1628             TyOrConstInferVar::TyFloat(v) => {
1629                 // If `probe_value` returns a value it's always a
1630                 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1631                 //
1632                 // Not `inlined_probe_value(v)` because this call site is colder.
1633                 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1634             }
1635
1636             TyOrConstInferVar::Const(v) => {
1637                 // If `probe_value` returns a `Known` value, it never equals
1638                 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1639                 //
1640                 // Not `inlined_probe_value(v)` because this call site is colder.
1641                 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1642                     ConstVariableValue::Unknown { .. } => false,
1643                     ConstVariableValue::Known { .. } => true,
1644                 }
1645             }
1646         }
1647     }
1648 }
1649
1650 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1651 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1652 #[derive(Copy, Clone, Debug)]
1653 pub enum TyOrConstInferVar<'tcx> {
1654     /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1655     Ty(TyVid),
1656     /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1657     TyInt(IntVid),
1658     /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1659     TyFloat(FloatVid),
1660
1661     /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1662     Const(ConstVid<'tcx>),
1663 }
1664
1665 impl TyOrConstInferVar<'tcx> {
1666     /// Tries to extract an inference variable from a type or a constant, returns `None`
1667     /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1668     /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1669     pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1670         match arg.unpack() {
1671             GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1672             GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1673             GenericArgKind::Lifetime(_) => None,
1674         }
1675     }
1676
1677     /// Tries to extract an inference variable from a type, returns `None`
1678     /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1679     pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1680         match ty.kind {
1681             ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1682             ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1683             ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1684             _ => None,
1685         }
1686     }
1687
1688     /// Tries to extract an inference variable from a constant, returns `None`
1689     /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1690     pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1691         match ct.val {
1692             ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1693             _ => None,
1694         }
1695     }
1696 }
1697
1698 struct ShallowResolver<'a, 'tcx> {
1699     infcx: &'a InferCtxt<'a, 'tcx>,
1700 }
1701
1702 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1703     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1704         self.infcx.tcx
1705     }
1706
1707     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1708         self.infcx.shallow_resolve_ty(ty)
1709     }
1710
1711     fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1712         if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1713             self.infcx
1714                 .inner
1715                 .borrow_mut()
1716                 .const_unification_table()
1717                 .probe_value(*vid)
1718                 .val
1719                 .known()
1720                 .unwrap_or(ct)
1721         } else {
1722             ct
1723         }
1724     }
1725 }
1726
1727 impl<'tcx> TypeTrace<'tcx> {
1728     pub fn span(&self) -> Span {
1729         self.cause.span
1730     }
1731
1732     pub fn types(
1733         cause: &ObligationCause<'tcx>,
1734         a_is_expected: bool,
1735         a: Ty<'tcx>,
1736         b: Ty<'tcx>,
1737     ) -> TypeTrace<'tcx> {
1738         TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1739     }
1740
1741     pub fn consts(
1742         cause: &ObligationCause<'tcx>,
1743         a_is_expected: bool,
1744         a: &'tcx ty::Const<'tcx>,
1745         b: &'tcx ty::Const<'tcx>,
1746     ) -> TypeTrace<'tcx> {
1747         TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
1748     }
1749
1750     pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1751         let err = tcx.ty_error();
1752         TypeTrace {
1753             cause: ObligationCause::dummy(),
1754             values: Types(ExpectedFound { expected: err, found: err }),
1755         }
1756     }
1757 }
1758
1759 impl<'tcx> SubregionOrigin<'tcx> {
1760     pub fn span(&self) -> Span {
1761         match *self {
1762             Subtype(ref a) => a.span(),
1763             RelateObjectBound(a) => a,
1764             RelateParamBound(a, _) => a,
1765             RelateRegionParamBound(a) => a,
1766             Reborrow(a) => a,
1767             ReborrowUpvar(a, _) => a,
1768             DataBorrowed(_, a) => a,
1769             ReferenceOutlivesReferent(_, a) => a,
1770             CallReturn(a) => a,
1771             CompareImplMethodObligation { span, .. } => span,
1772         }
1773     }
1774
1775     pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1776     where
1777         F: FnOnce() -> Self,
1778     {
1779         match cause.code {
1780             traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1781                 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1782             }
1783
1784             traits::ObligationCauseCode::CompareImplMethodObligation {
1785                 item_name,
1786                 impl_item_def_id,
1787                 trait_item_def_id,
1788             } => SubregionOrigin::CompareImplMethodObligation {
1789                 span: cause.span,
1790                 item_name,
1791                 impl_item_def_id,
1792                 trait_item_def_id,
1793             },
1794
1795             _ => default(),
1796         }
1797     }
1798 }
1799
1800 impl RegionVariableOrigin {
1801     pub fn span(&self) -> Span {
1802         match *self {
1803             MiscVariable(a)
1804             | PatternRegion(a)
1805             | AddrOfRegion(a)
1806             | Autoref(a, _)
1807             | Coercion(a)
1808             | EarlyBoundRegion(a, ..)
1809             | LateBoundRegion(a, ..)
1810             | UpvarRegion(_, a) => a,
1811             BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1812             NLL(..) => bug!("NLL variable used with `span`"),
1813         }
1814     }
1815 }
1816
1817 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1818     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1819         write!(
1820             f,
1821             "RegionObligation(sub_region={:?}, sup_type={:?})",
1822             self.sub_region, self.sup_type
1823         )
1824     }
1825 }