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