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