]> git.lizzy.rs Git - rust.git/blob - src/librustc_infer/infer/mod.rs
Rollup merge of #71688 - ecstatic-morse:const-downcast, r=oli-obk
[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     /// The variable we create to represent `'empty(U0)`.
477     RootEmptyRegion,
478
479     Existential {
480         /// If this is true, then this variable was created to represent a lifetime
481         /// bound in a `for` binder. For example, it might have been created to
482         /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
483         /// Such variables are created when we are trying to figure out if there
484         /// is any valid instantiation of `'a` that could fit into some scenario.
485         ///
486         /// This is used to inform error reporting: in the case that we are trying to
487         /// determine whether there is any valid instantiation of a `'a` variable that meets
488         /// some constraint C, we want to blame the "source" of that `for` type,
489         /// rather than blaming the source of the constraint C.
490         from_forall: bool,
491     },
492 }
493
494 impl NLLRegionVariableOrigin {
495     pub fn is_universal(self) -> bool {
496         match self {
497             NLLRegionVariableOrigin::FreeRegion => true,
498             NLLRegionVariableOrigin::Placeholder(..) => true,
499             NLLRegionVariableOrigin::Existential { .. } => false,
500             NLLRegionVariableOrigin::RootEmptyRegion => false,
501         }
502     }
503
504     pub fn is_existential(self) -> bool {
505         !self.is_universal()
506     }
507 }
508
509 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
510 #[derive(Copy, Clone, Debug)]
511 pub enum FixupError<'tcx> {
512     UnresolvedIntTy(IntVid),
513     UnresolvedFloatTy(FloatVid),
514     UnresolvedTy(TyVid),
515     UnresolvedConst(ConstVid<'tcx>),
516 }
517
518 /// See the `region_obligations` field for more information.
519 #[derive(Clone)]
520 pub struct RegionObligation<'tcx> {
521     pub sub_region: ty::Region<'tcx>,
522     pub sup_type: Ty<'tcx>,
523     pub origin: SubregionOrigin<'tcx>,
524 }
525
526 impl<'tcx> fmt::Display for FixupError<'tcx> {
527     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528         use self::FixupError::*;
529
530         match *self {
531             UnresolvedIntTy(_) => write!(
532                 f,
533                 "cannot determine the type of this integer; \
534                  add a suffix to specify the type explicitly"
535             ),
536             UnresolvedFloatTy(_) => write!(
537                 f,
538                 "cannot determine the type of this number; \
539                  add a suffix to specify the type explicitly"
540             ),
541             UnresolvedTy(_) => write!(f, "unconstrained type"),
542             UnresolvedConst(_) => write!(f, "unconstrained const value"),
543         }
544     }
545 }
546
547 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
548 /// Necessary because we can't write the following bound:
549 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
550 pub struct InferCtxtBuilder<'tcx> {
551     global_tcx: TyCtxt<'tcx>,
552     fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
553 }
554
555 pub trait TyCtxtInferExt<'tcx> {
556     fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
557 }
558
559 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
560     fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
561         InferCtxtBuilder { global_tcx: self, fresh_tables: None }
562     }
563 }
564
565 impl<'tcx> InferCtxtBuilder<'tcx> {
566     /// Used only by `rustc_typeck` during body type-checking/inference,
567     /// will initialize `in_progress_tables` with fresh `TypeckTables`.
568     pub fn with_fresh_in_progress_tables(mut self, table_owner: LocalDefId) -> Self {
569         self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
570         self
571     }
572
573     /// Given a canonical value `C` as a starting point, create an
574     /// inference context that contains each of the bound values
575     /// within instantiated as a fresh variable. The `f` closure is
576     /// invoked with the new infcx, along with the instantiated value
577     /// `V` and a substitution `S`. This substitution `S` maps from
578     /// the bound values in `C` to their instantiated values in `V`
579     /// (in other words, `S(C) = V`).
580     pub fn enter_with_canonical<T, R>(
581         &mut self,
582         span: Span,
583         canonical: &Canonical<'tcx, T>,
584         f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
585     ) -> R
586     where
587         T: TypeFoldable<'tcx>,
588     {
589         self.enter(|infcx| {
590             let (value, subst) =
591                 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
592             f(infcx, value, subst)
593         })
594     }
595
596     pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
597         let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
598         let in_progress_tables = fresh_tables.as_ref();
599         global_tcx.enter_local(|tcx| {
600             f(InferCtxt {
601                 tcx,
602                 in_progress_tables,
603                 inner: RefCell::new(InferCtxtInner::new()),
604                 lexical_region_resolutions: RefCell::new(None),
605                 selection_cache: Default::default(),
606                 evaluation_cache: Default::default(),
607                 reported_trait_errors: Default::default(),
608                 reported_closure_mismatch: Default::default(),
609                 tainted_by_errors_flag: Cell::new(false),
610                 err_count_on_creation: tcx.sess.err_count(),
611                 in_snapshot: Cell::new(false),
612                 skip_leak_check: Cell::new(false),
613                 universe: Cell::new(ty::UniverseIndex::ROOT),
614             })
615         })
616     }
617 }
618
619 impl<'tcx, T> InferOk<'tcx, T> {
620     pub fn unit(self) -> InferOk<'tcx, ()> {
621         InferOk { value: (), obligations: self.obligations }
622     }
623
624     /// Extracts `value`, registering any obligations into `fulfill_cx`.
625     pub fn into_value_registering_obligations(
626         self,
627         infcx: &InferCtxt<'_, 'tcx>,
628         fulfill_cx: &mut dyn TraitEngine<'tcx>,
629     ) -> T {
630         let InferOk { value, obligations } = self;
631         for obligation in obligations {
632             fulfill_cx.register_predicate_obligation(infcx, obligation);
633         }
634         value
635     }
636 }
637
638 impl<'tcx> InferOk<'tcx, ()> {
639     pub fn into_obligations(self) -> PredicateObligations<'tcx> {
640         self.obligations
641     }
642 }
643
644 #[must_use = "once you start a snapshot, you should always consume it"]
645 pub struct CombinedSnapshot<'a, 'tcx> {
646     projection_cache_snapshot: traits::ProjectionCacheSnapshot,
647     type_snapshot: type_variable::Snapshot<'tcx>,
648     const_snapshot: ut::Snapshot<ut::InPlace<ty::ConstVid<'tcx>>>,
649     int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
650     float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
651     region_constraints_snapshot: RegionSnapshot,
652     region_obligations_snapshot: usize,
653     universe: ty::UniverseIndex,
654     was_in_snapshot: bool,
655     was_skip_leak_check: bool,
656     _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
657 }
658
659 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
660     pub fn is_in_snapshot(&self) -> bool {
661         self.in_snapshot.get()
662     }
663
664     pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
665         t.fold_with(&mut self.freshener())
666     }
667
668     pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
669         match ty.kind {
670             ty::Infer(ty::TyVar(vid)) => self.inner.borrow().type_variables.var_diverges(vid),
671             _ => false,
672         }
673     }
674
675     pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
676         freshen::TypeFreshener::new(self)
677     }
678
679     pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
680         use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
681         use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
682         match ty.kind {
683             ty::Infer(ty::IntVar(vid)) => {
684                 if self.inner.borrow_mut().int_unification_table.probe_value(vid).is_some() {
685                     Neither
686                 } else {
687                     UnconstrainedInt
688                 }
689             }
690             ty::Infer(ty::FloatVar(vid)) => {
691                 if self.inner.borrow_mut().float_unification_table.probe_value(vid).is_some() {
692                     Neither
693                 } else {
694                     UnconstrainedFloat
695                 }
696             }
697             _ => Neither,
698         }
699     }
700
701     pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
702         let mut inner = self.inner.borrow_mut();
703         // FIXME(const_generics): should there be an equivalent function for const variables?
704
705         let mut vars: Vec<Ty<'_>> = inner
706             .type_variables
707             .unsolved_variables()
708             .into_iter()
709             .map(|t| self.tcx.mk_ty_var(t))
710             .collect();
711         vars.extend(
712             (0..inner.int_unification_table.len())
713                 .map(|i| ty::IntVid { index: i as u32 })
714                 .filter(|&vid| inner.int_unification_table.probe_value(vid).is_none())
715                 .map(|v| self.tcx.mk_int_var(v)),
716         );
717         vars.extend(
718             (0..inner.float_unification_table.len())
719                 .map(|i| ty::FloatVid { index: i as u32 })
720                 .filter(|&vid| inner.float_unification_table.probe_value(vid).is_none())
721                 .map(|v| self.tcx.mk_float_var(v)),
722         );
723         vars
724     }
725
726     fn combine_fields(
727         &'a self,
728         trace: TypeTrace<'tcx>,
729         param_env: ty::ParamEnv<'tcx>,
730     ) -> CombineFields<'a, 'tcx> {
731         CombineFields {
732             infcx: self,
733             trace,
734             cause: None,
735             param_env,
736             obligations: PredicateObligations::new(),
737         }
738     }
739
740     /// Clear the "currently in a snapshot" flag, invoke the closure,
741     /// then restore the flag to its original value. This flag is a
742     /// debugging measure designed to detect cases where we start a
743     /// snapshot, create type variables, and register obligations
744     /// which may involve those type variables in the fulfillment cx,
745     /// potentially leaving "dangling type variables" behind.
746     /// In such cases, an assertion will fail when attempting to
747     /// register obligations, within a snapshot. Very useful, much
748     /// better than grovelling through megabytes of `RUSTC_LOG` output.
749     ///
750     /// HOWEVER, in some cases the flag is unhelpful. In particular, we
751     /// sometimes create a "mini-fulfilment-cx" in which we enroll
752     /// obligations. As long as this fulfillment cx is fully drained
753     /// before we return, this is not a problem, as there won't be any
754     /// escaping obligations in the main cx. In those cases, you can
755     /// use this function.
756     pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
757     where
758         F: FnOnce(&Self) -> R,
759     {
760         let flag = self.in_snapshot.replace(false);
761         let result = func(self);
762         self.in_snapshot.set(flag);
763         result
764     }
765
766     fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
767         debug!("start_snapshot()");
768
769         let in_snapshot = self.in_snapshot.replace(true);
770
771         let mut inner = self.inner.borrow_mut();
772         CombinedSnapshot {
773             projection_cache_snapshot: inner.projection_cache.snapshot(),
774             type_snapshot: inner.type_variables.snapshot(),
775             const_snapshot: inner.const_unification_table.snapshot(),
776             int_snapshot: inner.int_unification_table.snapshot(),
777             float_snapshot: inner.float_unification_table.snapshot(),
778             region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
779             region_obligations_snapshot: inner.region_obligations.len(),
780             universe: self.universe(),
781             was_in_snapshot: in_snapshot,
782             was_skip_leak_check: self.skip_leak_check.get(),
783             // Borrow tables "in progress" (i.e., during typeck)
784             // to ban writes from within a snapshot to them.
785             _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
786         }
787     }
788
789     fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
790         debug!("rollback_to(cause={})", cause);
791         let CombinedSnapshot {
792             projection_cache_snapshot,
793             type_snapshot,
794             const_snapshot,
795             int_snapshot,
796             float_snapshot,
797             region_constraints_snapshot,
798             region_obligations_snapshot,
799             universe,
800             was_in_snapshot,
801             was_skip_leak_check,
802             _in_progress_tables,
803         } = snapshot;
804
805         self.in_snapshot.set(was_in_snapshot);
806         self.universe.set(universe);
807         self.skip_leak_check.set(was_skip_leak_check);
808
809         let mut inner = self.inner.borrow_mut();
810         inner.projection_cache.rollback_to(projection_cache_snapshot);
811         inner.type_variables.rollback_to(type_snapshot);
812         inner.const_unification_table.rollback_to(const_snapshot);
813         inner.int_unification_table.rollback_to(int_snapshot);
814         inner.float_unification_table.rollback_to(float_snapshot);
815         inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
816         inner.region_obligations.truncate(region_obligations_snapshot);
817     }
818
819     fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
820         debug!("commit_from()");
821         let CombinedSnapshot {
822             projection_cache_snapshot,
823             type_snapshot,
824             const_snapshot,
825             int_snapshot,
826             float_snapshot,
827             region_constraints_snapshot,
828             region_obligations_snapshot: _,
829             universe: _,
830             was_in_snapshot,
831             was_skip_leak_check,
832             _in_progress_tables,
833         } = snapshot;
834
835         self.in_snapshot.set(was_in_snapshot);
836         self.skip_leak_check.set(was_skip_leak_check);
837
838         let mut inner = self.inner.borrow_mut();
839         inner.projection_cache.commit(projection_cache_snapshot);
840         inner.type_variables.commit(type_snapshot);
841         inner.const_unification_table.commit(const_snapshot);
842         inner.int_unification_table.commit(int_snapshot);
843         inner.float_unification_table.commit(float_snapshot);
844         inner.unwrap_region_constraints().commit(region_constraints_snapshot);
845     }
846
847     /// Executes `f` and commit the bindings.
848     pub fn commit_unconditionally<R, F>(&self, f: F) -> R
849     where
850         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
851     {
852         debug!("commit_unconditionally()");
853         let snapshot = self.start_snapshot();
854         let r = f(&snapshot);
855         self.commit_from(snapshot);
856         r
857     }
858
859     /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
860     pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
861     where
862         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
863     {
864         debug!("commit_if_ok()");
865         let snapshot = self.start_snapshot();
866         let r = f(&snapshot);
867         debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
868         match r {
869             Ok(_) => {
870                 self.commit_from(snapshot);
871             }
872             Err(_) => {
873                 self.rollback_to("commit_if_ok -- error", snapshot);
874             }
875         }
876         r
877     }
878
879     /// Execute `f` then unroll any bindings it creates.
880     pub fn probe<R, F>(&self, f: F) -> R
881     where
882         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
883     {
884         debug!("probe()");
885         let snapshot = self.start_snapshot();
886         let r = f(&snapshot);
887         self.rollback_to("probe", snapshot);
888         r
889     }
890
891     /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
892     pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
893     where
894         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
895     {
896         debug!("probe()");
897         let snapshot = self.start_snapshot();
898         let skip_leak_check = should_skip || self.skip_leak_check.get();
899         self.skip_leak_check.set(skip_leak_check);
900         let r = f(&snapshot);
901         self.rollback_to("probe", snapshot);
902         r
903     }
904
905     /// Scan the constraints produced since `snapshot` began and returns:
906     ///
907     /// - `None` -- if none of them involve "region outlives" constraints
908     /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
909     /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
910     pub fn region_constraints_added_in_snapshot(
911         &self,
912         snapshot: &CombinedSnapshot<'a, 'tcx>,
913     ) -> Option<bool> {
914         self.inner
915             .borrow_mut()
916             .unwrap_region_constraints()
917             .region_constraints_added_in_snapshot(&snapshot.region_constraints_snapshot)
918     }
919
920     pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
921         self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
922     }
923
924     pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
925     where
926         T: at::ToTrace<'tcx>,
927     {
928         let origin = &ObligationCause::dummy();
929         self.probe(|_| {
930             self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
931                 // Ignore obligations, since we are unrolling
932                 // everything anyway.
933             })
934         })
935     }
936
937     pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
938     where
939         T: at::ToTrace<'tcx>,
940     {
941         let origin = &ObligationCause::dummy();
942         self.probe(|_| {
943             self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
944                 // Ignore obligations, since we are unrolling
945                 // everything anyway.
946             })
947         })
948     }
949
950     pub fn sub_regions(
951         &self,
952         origin: SubregionOrigin<'tcx>,
953         a: ty::Region<'tcx>,
954         b: ty::Region<'tcx>,
955     ) {
956         debug!("sub_regions({:?} <: {:?})", a, b);
957         self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
958     }
959
960     /// Require that the region `r` be equal to one of the regions in
961     /// the set `regions`.
962     pub fn member_constraint(
963         &self,
964         opaque_type_def_id: DefId,
965         definition_span: Span,
966         hidden_ty: Ty<'tcx>,
967         region: ty::Region<'tcx>,
968         in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
969     ) {
970         debug!("member_constraint({:?} <: {:?})", region, in_regions);
971         self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
972             opaque_type_def_id,
973             definition_span,
974             hidden_ty,
975             region,
976             in_regions,
977         );
978     }
979
980     pub fn subtype_predicate(
981         &self,
982         cause: &ObligationCause<'tcx>,
983         param_env: ty::ParamEnv<'tcx>,
984         predicate: &ty::PolySubtypePredicate<'tcx>,
985     ) -> Option<InferResult<'tcx, ()>> {
986         // Subtle: it's ok to skip the binder here and resolve because
987         // `shallow_resolve` just ignores anything that is not a type
988         // variable, and because type variable's can't (at present, at
989         // least) capture any of the things bound by this binder.
990         //
991         // NOTE(nmatsakis): really, there is no *particular* reason to do this
992         // `shallow_resolve` here except as a micro-optimization.
993         // Naturally I could not resist.
994         let two_unbound_type_vars = {
995             let a = self.shallow_resolve(predicate.skip_binder().a);
996             let b = self.shallow_resolve(predicate.skip_binder().b);
997             a.is_ty_var() && b.is_ty_var()
998         };
999
1000         if two_unbound_type_vars {
1001             // Two unbound type variables? Can't make progress.
1002             return None;
1003         }
1004
1005         Some(self.commit_if_ok(|snapshot| {
1006             let (ty::SubtypePredicate { a_is_expected, a, b }, placeholder_map) =
1007                 self.replace_bound_vars_with_placeholders(predicate);
1008
1009             let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1010
1011             self.leak_check(false, &placeholder_map, snapshot)?;
1012
1013             Ok(ok.unit())
1014         }))
1015     }
1016
1017     pub fn region_outlives_predicate(
1018         &self,
1019         cause: &traits::ObligationCause<'tcx>,
1020         predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
1021     ) -> UnitResult<'tcx> {
1022         self.commit_if_ok(|snapshot| {
1023             let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
1024                 self.replace_bound_vars_with_placeholders(predicate);
1025             let origin = SubregionOrigin::from_obligation_cause(cause, || {
1026                 RelateRegionParamBound(cause.span)
1027             });
1028             self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1029             self.leak_check(false, &placeholder_map, snapshot)?;
1030             Ok(())
1031         })
1032     }
1033
1034     pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1035         self.inner.borrow_mut().type_variables.new_var(self.universe(), diverging, origin)
1036     }
1037
1038     pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1039         self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1040     }
1041
1042     pub fn next_ty_var_in_universe(
1043         &self,
1044         origin: TypeVariableOrigin,
1045         universe: ty::UniverseIndex,
1046     ) -> Ty<'tcx> {
1047         let vid = self.inner.borrow_mut().type_variables.new_var(universe, false, origin);
1048         self.tcx.mk_ty_var(vid)
1049     }
1050
1051     pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1052         self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1053     }
1054
1055     pub fn next_const_var(
1056         &self,
1057         ty: Ty<'tcx>,
1058         origin: ConstVariableOrigin,
1059     ) -> &'tcx ty::Const<'tcx> {
1060         self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1061     }
1062
1063     pub fn next_const_var_in_universe(
1064         &self,
1065         ty: Ty<'tcx>,
1066         origin: ConstVariableOrigin,
1067         universe: ty::UniverseIndex,
1068     ) -> &'tcx ty::Const<'tcx> {
1069         let vid = self
1070             .inner
1071             .borrow_mut()
1072             .const_unification_table
1073             .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1074         self.tcx.mk_const_var(vid, ty)
1075     }
1076
1077     pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1078         self.inner.borrow_mut().const_unification_table.new_key(ConstVarValue {
1079             origin,
1080             val: ConstVariableValue::Unknown { universe: self.universe() },
1081         })
1082     }
1083
1084     fn next_int_var_id(&self) -> IntVid {
1085         self.inner.borrow_mut().int_unification_table.new_key(None)
1086     }
1087
1088     pub fn next_int_var(&self) -> Ty<'tcx> {
1089         self.tcx.mk_int_var(self.next_int_var_id())
1090     }
1091
1092     fn next_float_var_id(&self) -> FloatVid {
1093         self.inner.borrow_mut().float_unification_table.new_key(None)
1094     }
1095
1096     pub fn next_float_var(&self) -> Ty<'tcx> {
1097         self.tcx.mk_float_var(self.next_float_var_id())
1098     }
1099
1100     /// Creates a fresh region variable with the next available index.
1101     /// The variable will be created in the maximum universe created
1102     /// thus far, allowing it to name any region created thus far.
1103     pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1104         self.next_region_var_in_universe(origin, self.universe())
1105     }
1106
1107     /// Creates a fresh region variable with the next available index
1108     /// in the given universe; typically, you can use
1109     /// `next_region_var` and just use the maximal universe.
1110     pub fn next_region_var_in_universe(
1111         &self,
1112         origin: RegionVariableOrigin,
1113         universe: ty::UniverseIndex,
1114     ) -> ty::Region<'tcx> {
1115         let region_var =
1116             self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1117         self.tcx.mk_region(ty::ReVar(region_var))
1118     }
1119
1120     /// Return the universe that the region `r` was created in.  For
1121     /// most regions (e.g., `'static`, named regions from the user,
1122     /// etc) this is the root universe U0. For inference variables or
1123     /// placeholders, however, it will return the universe which which
1124     /// they are associated.
1125     fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1126         self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1127     }
1128
1129     /// Number of region variables created so far.
1130     pub fn num_region_vars(&self) -> usize {
1131         self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1132     }
1133
1134     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1135     pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1136         self.next_region_var(RegionVariableOrigin::NLL(origin))
1137     }
1138
1139     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1140     pub fn next_nll_region_var_in_universe(
1141         &self,
1142         origin: NLLRegionVariableOrigin,
1143         universe: ty::UniverseIndex,
1144     ) -> ty::Region<'tcx> {
1145         self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1146     }
1147
1148     pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1149         match param.kind {
1150             GenericParamDefKind::Lifetime => {
1151                 // Create a region inference variable for the given
1152                 // region parameter definition.
1153                 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1154             }
1155             GenericParamDefKind::Type { .. } => {
1156                 // Create a type inference variable for the given
1157                 // type parameter definition. The substitutions are
1158                 // for actual parameters that may be referred to by
1159                 // the default of this type parameter, if it exists.
1160                 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1161                 // used in a path such as `Foo::<T, U>::new()` will
1162                 // use an inference variable for `C` with `[T, U]`
1163                 // as the substitutions for the default, `(T, U)`.
1164                 let ty_var_id = self.inner.borrow_mut().type_variables.new_var(
1165                     self.universe(),
1166                     false,
1167                     TypeVariableOrigin {
1168                         kind: TypeVariableOriginKind::TypeParameterDefinition(
1169                             param.name,
1170                             Some(param.def_id),
1171                         ),
1172                         span,
1173                     },
1174                 );
1175
1176                 self.tcx.mk_ty_var(ty_var_id).into()
1177             }
1178             GenericParamDefKind::Const { .. } => {
1179                 let origin = ConstVariableOrigin {
1180                     kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1181                     span,
1182                 };
1183                 let const_var_id =
1184                     self.inner.borrow_mut().const_unification_table.new_key(ConstVarValue {
1185                         origin,
1186                         val: ConstVariableValue::Unknown { universe: self.universe() },
1187                     });
1188                 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1189             }
1190         }
1191     }
1192
1193     /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1194     /// type/region parameter to a fresh inference variable.
1195     pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1196         InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1197     }
1198
1199     /// Returns `true` if errors have been reported since this infcx was
1200     /// created. This is sometimes used as a heuristic to skip
1201     /// reporting errors that often occur as a result of earlier
1202     /// errors, but where it's hard to be 100% sure (e.g., unresolved
1203     /// inference variables, regionck errors).
1204     pub fn is_tainted_by_errors(&self) -> bool {
1205         debug!(
1206             "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1207              tainted_by_errors_flag={})",
1208             self.tcx.sess.err_count(),
1209             self.err_count_on_creation,
1210             self.tainted_by_errors_flag.get()
1211         );
1212
1213         if self.tcx.sess.err_count() > self.err_count_on_creation {
1214             return true; // errors reported since this infcx was made
1215         }
1216         self.tainted_by_errors_flag.get()
1217     }
1218
1219     /// Set the "tainted by errors" flag to true. We call this when we
1220     /// observe an error from a prior pass.
1221     pub fn set_tainted_by_errors(&self) {
1222         debug!("set_tainted_by_errors()");
1223         self.tainted_by_errors_flag.set(true)
1224     }
1225
1226     /// Process the region constraints and report any errors that
1227     /// result. After this, no more unification operations should be
1228     /// done -- or the compiler will panic -- but it is legal to use
1229     /// `resolve_vars_if_possible` as well as `fully_resolve`.
1230     pub fn resolve_regions_and_report_errors(
1231         &self,
1232         region_context: DefId,
1233         region_map: &region::ScopeTree,
1234         outlives_env: &OutlivesEnvironment<'tcx>,
1235         mode: RegionckMode,
1236     ) {
1237         assert!(
1238             self.is_tainted_by_errors() || self.inner.borrow().region_obligations.is_empty(),
1239             "region_obligations not empty: {:#?}",
1240             self.inner.borrow().region_obligations
1241         );
1242         let (var_infos, data) = self
1243             .inner
1244             .borrow_mut()
1245             .region_constraints
1246             .take()
1247             .expect("regions already resolved")
1248             .into_infos_and_data();
1249
1250         let region_rels = &RegionRelations::new(
1251             self.tcx,
1252             region_context,
1253             region_map,
1254             outlives_env.free_region_map(),
1255         );
1256
1257         let (lexical_region_resolutions, errors) =
1258             lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1259
1260         let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1261         assert!(old_value.is_none());
1262
1263         if !self.is_tainted_by_errors() {
1264             // As a heuristic, just skip reporting region errors
1265             // altogether if other errors have been reported while
1266             // this infcx was in use.  This is totally hokey but
1267             // otherwise we have a hard time separating legit region
1268             // errors from silly ones.
1269             self.report_region_errors(region_map, &errors);
1270         }
1271     }
1272
1273     /// Obtains (and clears) the current set of region
1274     /// constraints. The inference context is still usable: further
1275     /// unifications will simply add new constraints.
1276     ///
1277     /// This method is not meant to be used with normal lexical region
1278     /// resolution. Rather, it is used in the NLL mode as a kind of
1279     /// interim hack: basically we run normal type-check and generate
1280     /// region constraints as normal, but then we take them and
1281     /// translate them into the form that the NLL solver
1282     /// understands. See the NLL module for mode details.
1283     pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1284         assert!(
1285             self.inner.borrow().region_obligations.is_empty(),
1286             "region_obligations not empty: {:#?}",
1287             self.inner.borrow().region_obligations
1288         );
1289
1290         self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1291     }
1292
1293     /// Gives temporary access to the region constraint data.
1294     #[allow(non_camel_case_types)] // bug with impl trait
1295     pub fn with_region_constraints<R>(
1296         &self,
1297         op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1298     ) -> R {
1299         let mut inner = self.inner.borrow_mut();
1300         op(inner.unwrap_region_constraints().data())
1301     }
1302
1303     /// Takes ownership of the list of variable regions. This implies
1304     /// that all the region constraints have already been taken, and
1305     /// hence that `resolve_regions_and_report_errors` can never be
1306     /// called. This is used only during NLL processing to "hand off" ownership
1307     /// of the set of region variables into the NLL region context.
1308     pub fn take_region_var_origins(&self) -> VarInfos {
1309         let (var_infos, data) = self
1310             .inner
1311             .borrow_mut()
1312             .region_constraints
1313             .take()
1314             .expect("regions already resolved")
1315             .into_infos_and_data();
1316         assert!(data.is_empty());
1317         var_infos
1318     }
1319
1320     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1321         self.resolve_vars_if_possible(&t).to_string()
1322     }
1323
1324     pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1325         let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1326         format!("({})", tstrs.join(", "))
1327     }
1328
1329     pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1330         self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1331     }
1332
1333     /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1334     /// universe index of `TyVar(vid)`.
1335     pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1336         use self::type_variable::TypeVariableValue;
1337
1338         match self.inner.borrow_mut().type_variables.probe(vid) {
1339             TypeVariableValue::Known { value } => Ok(value),
1340             TypeVariableValue::Unknown { universe } => Err(universe),
1341         }
1342     }
1343
1344     /// Resolve any type variables found in `value` -- but only one
1345     /// level.  So, if the variable `?X` is bound to some type
1346     /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1347     /// itself be bound to a type).
1348     ///
1349     /// Useful when you only need to inspect the outermost level of
1350     /// the type and don't care about nested types (or perhaps you
1351     /// will be resolving them as well, e.g. in a loop).
1352     pub fn shallow_resolve<T>(&self, value: T) -> T
1353     where
1354         T: TypeFoldable<'tcx>,
1355     {
1356         value.fold_with(&mut ShallowResolver { infcx: self })
1357     }
1358
1359     pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1360         self.inner.borrow_mut().type_variables.root_var(var)
1361     }
1362
1363     /// Where possible, replaces type/const variables in
1364     /// `value` with their final value. Note that region variables
1365     /// are unaffected. If a type/const variable has not been unified, it
1366     /// is left as is. This is an idempotent operation that does
1367     /// not affect inference state in any way and so you can do it
1368     /// at will.
1369     pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1370     where
1371         T: TypeFoldable<'tcx>,
1372     {
1373         if !value.needs_infer() {
1374             return value.clone(); // Avoid duplicated subst-folding.
1375         }
1376         let mut r = resolve::OpportunisticVarResolver::new(self);
1377         value.fold_with(&mut r)
1378     }
1379
1380     /// Returns the first unresolved variable contained in `T`. In the
1381     /// process of visiting `T`, this will resolve (where possible)
1382     /// type variables in `T`, but it never constructs the final,
1383     /// resolved type, so it's more efficient than
1384     /// `resolve_vars_if_possible()`.
1385     pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1386     where
1387         T: TypeFoldable<'tcx>,
1388     {
1389         let mut r = resolve::UnresolvedTypeFinder::new(self);
1390         value.visit_with(&mut r);
1391         r.first_unresolved
1392     }
1393
1394     pub fn probe_const_var(
1395         &self,
1396         vid: ty::ConstVid<'tcx>,
1397     ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1398         match self.inner.borrow_mut().const_unification_table.probe_value(vid).val {
1399             ConstVariableValue::Known { value } => Ok(value),
1400             ConstVariableValue::Unknown { universe } => Err(universe),
1401         }
1402     }
1403
1404     pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1405         /*!
1406          * Attempts to resolve all type/region/const variables in
1407          * `value`. Region inference must have been run already (e.g.,
1408          * by calling `resolve_regions_and_report_errors`). If some
1409          * variable was never unified, an `Err` results.
1410          *
1411          * This method is idempotent, but it not typically not invoked
1412          * except during the writeback phase.
1413          */
1414
1415         resolve::fully_resolve(self, value)
1416     }
1417
1418     // [Note-Type-error-reporting]
1419     // An invariant is that anytime the expected or actual type is Error (the special
1420     // error type, meaning that an error occurred when typechecking this expression),
1421     // this is a derived error. The error cascaded from another error (that was already
1422     // reported), so it's not useful to display it to the user.
1423     // The following methods implement this logic.
1424     // They check if either the actual or expected type is Error, and don't print the error
1425     // in this case. The typechecker should only ever report type errors involving mismatched
1426     // types using one of these methods, and should not call span_err directly for such
1427     // errors.
1428
1429     pub fn type_error_struct_with_diag<M>(
1430         &self,
1431         sp: Span,
1432         mk_diag: M,
1433         actual_ty: Ty<'tcx>,
1434     ) -> DiagnosticBuilder<'tcx>
1435     where
1436         M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1437     {
1438         let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1439         debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1440
1441         // Don't report an error if actual type is `Error`.
1442         if actual_ty.references_error() {
1443             return self.tcx.sess.diagnostic().struct_dummy();
1444         }
1445
1446         mk_diag(self.ty_to_string(actual_ty))
1447     }
1448
1449     pub fn report_mismatched_types(
1450         &self,
1451         cause: &ObligationCause<'tcx>,
1452         expected: Ty<'tcx>,
1453         actual: Ty<'tcx>,
1454         err: TypeError<'tcx>,
1455     ) -> DiagnosticBuilder<'tcx> {
1456         let trace = TypeTrace::types(cause, true, expected, actual);
1457         self.report_and_explain_type_error(trace, &err)
1458     }
1459
1460     pub fn replace_bound_vars_with_fresh_vars<T>(
1461         &self,
1462         span: Span,
1463         lbrct: LateBoundRegionConversionTime,
1464         value: &ty::Binder<T>,
1465     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1466     where
1467         T: TypeFoldable<'tcx>,
1468     {
1469         let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1470         let fld_t = |_| {
1471             self.next_ty_var(TypeVariableOrigin {
1472                 kind: TypeVariableOriginKind::MiscVariable,
1473                 span,
1474             })
1475         };
1476         let fld_c = |_, ty| {
1477             self.next_const_var(
1478                 ty,
1479                 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1480             )
1481         };
1482         self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1483     }
1484
1485     /// See the [`region_constraints::verify_generic_bound`] method.
1486     pub fn verify_generic_bound(
1487         &self,
1488         origin: SubregionOrigin<'tcx>,
1489         kind: GenericKind<'tcx>,
1490         a: ty::Region<'tcx>,
1491         bound: VerifyBound<'tcx>,
1492     ) {
1493         debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1494
1495         self.inner
1496             .borrow_mut()
1497             .unwrap_region_constraints()
1498             .verify_generic_bound(origin, kind, a, bound);
1499     }
1500
1501     /// Obtains the latest type of the given closure; this may be a
1502     /// closure in the current function, in which case its
1503     /// `ClosureKind` may not yet be known.
1504     pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1505         let closure_kind_ty = closure_substs.as_closure().kind_ty();
1506         let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1507         closure_kind_ty.to_opt_closure_kind()
1508     }
1509
1510     /// Clears the selection, evaluation, and projection caches. This is useful when
1511     /// repeatedly attempting to select an `Obligation` while changing only
1512     /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1513     pub fn clear_caches(&self) {
1514         self.selection_cache.clear();
1515         self.evaluation_cache.clear();
1516         self.inner.borrow_mut().projection_cache.clear();
1517     }
1518
1519     fn universe(&self) -> ty::UniverseIndex {
1520         self.universe.get()
1521     }
1522
1523     /// Creates and return a fresh universe that extends all previous
1524     /// universes. Updates `self.universe` to that new universe.
1525     pub fn create_next_universe(&self) -> ty::UniverseIndex {
1526         let u = self.universe.get().next_universe();
1527         self.universe.set(u);
1528         u
1529     }
1530
1531     /// Resolves and evaluates a constant.
1532     ///
1533     /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1534     /// substitutions and environment are used to resolve the constant. Alternatively if the
1535     /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1536     /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1537     /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1538     /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1539     /// returned.
1540     ///
1541     /// This handles inferences variables within both `param_env` and `substs` by
1542     /// performing the operation on their respective canonical forms.
1543     pub fn const_eval_resolve(
1544         &self,
1545         param_env: ty::ParamEnv<'tcx>,
1546         def_id: DefId,
1547         substs: SubstsRef<'tcx>,
1548         promoted: Option<mir::Promoted>,
1549         span: Option<Span>,
1550     ) -> ConstEvalResult<'tcx> {
1551         let mut original_values = OriginalQueryValues::default();
1552         let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1553
1554         let (param_env, substs) = canonical.value;
1555         // The return value is the evaluated value which doesn't contain any reference to inference
1556         // variables, thus we don't need to substitute back the original values.
1557         self.tcx.const_eval_resolve(param_env, def_id, substs, promoted, span)
1558     }
1559
1560     /// If `typ` is a type variable of some kind, resolve it one level
1561     /// (but do not resolve types found in the result). If `typ` is
1562     /// not a type variable, just return it unmodified.
1563     // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1564     fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1565         match typ.kind {
1566             ty::Infer(ty::TyVar(v)) => {
1567                 // Not entirely obvious: if `typ` is a type variable,
1568                 // it can be resolved to an int/float variable, which
1569                 // can then be recursively resolved, hence the
1570                 // recursion. Note though that we prevent type
1571                 // variables from unifying to other type variables
1572                 // directly (though they may be embedded
1573                 // structurally), and we prevent cycles in any case,
1574                 // so this recursion should always be of very limited
1575                 // depth.
1576                 //
1577                 // Note: if these two lines are combined into one we get
1578                 // dynamic borrow errors on `self.inner`.
1579                 let known = self.inner.borrow_mut().type_variables.probe(v).known();
1580                 known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
1581             }
1582
1583             ty::Infer(ty::IntVar(v)) => self
1584                 .inner
1585                 .borrow_mut()
1586                 .int_unification_table
1587                 .probe_value(v)
1588                 .map(|v| v.to_type(self.tcx))
1589                 .unwrap_or(typ),
1590
1591             ty::Infer(ty::FloatVar(v)) => self
1592                 .inner
1593                 .borrow_mut()
1594                 .float_unification_table
1595                 .probe_value(v)
1596                 .map(|v| v.to_type(self.tcx))
1597                 .unwrap_or(typ),
1598
1599             _ => typ,
1600         }
1601     }
1602
1603     /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1604     ///   * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1605     ///   * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1606     ///
1607     /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1608     /// inlined, despite being large, because it has only two call sites that
1609     /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1610     /// inference variables), and it handles both `Ty` and `ty::Const` without
1611     /// having to resort to storing full `GenericArg`s in `stalled_on`.
1612     #[inline(always)]
1613     pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1614         match infer_var {
1615             TyOrConstInferVar::Ty(v) => {
1616                 use self::type_variable::TypeVariableValue;
1617
1618                 // If `inlined_probe` returns a `Known` value, it never equals
1619                 // `ty::Infer(ty::TyVar(v))`.
1620                 match self.inner.borrow_mut().type_variables.inlined_probe(v) {
1621                     TypeVariableValue::Unknown { .. } => false,
1622                     TypeVariableValue::Known { .. } => true,
1623                 }
1624             }
1625
1626             TyOrConstInferVar::TyInt(v) => {
1627                 // If `inlined_probe_value` returns a value it's always a
1628                 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1629                 // `ty::Infer(_)`.
1630                 self.inner.borrow_mut().int_unification_table.inlined_probe_value(v).is_some()
1631             }
1632
1633             TyOrConstInferVar::TyFloat(v) => {
1634                 // If `probe_value` returns a value it's always a
1635                 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1636                 //
1637                 // Not `inlined_probe_value(v)` because this call site is colder.
1638                 self.inner.borrow_mut().float_unification_table.probe_value(v).is_some()
1639             }
1640
1641             TyOrConstInferVar::Const(v) => {
1642                 // If `probe_value` returns a `Known` value, it never equals
1643                 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1644                 //
1645                 // Not `inlined_probe_value(v)` because this call site is colder.
1646                 match self.inner.borrow_mut().const_unification_table.probe_value(v).val {
1647                     ConstVariableValue::Unknown { .. } => false,
1648                     ConstVariableValue::Known { .. } => true,
1649                 }
1650             }
1651         }
1652     }
1653 }
1654
1655 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1656 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1657 #[derive(Copy, Clone, Debug)]
1658 pub enum TyOrConstInferVar<'tcx> {
1659     /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1660     Ty(TyVid),
1661     /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1662     TyInt(IntVid),
1663     /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1664     TyFloat(FloatVid),
1665
1666     /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1667     Const(ConstVid<'tcx>),
1668 }
1669
1670 impl TyOrConstInferVar<'tcx> {
1671     /// Tries to extract an inference variable from a type or a constant, returns `None`
1672     /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1673     /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1674     pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1675         match arg.unpack() {
1676             GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1677             GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1678             GenericArgKind::Lifetime(_) => None,
1679         }
1680     }
1681
1682     /// Tries to extract an inference variable from a type, returns `None`
1683     /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1684     pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1685         match ty.kind {
1686             ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1687             ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1688             ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1689             _ => None,
1690         }
1691     }
1692
1693     /// Tries to extract an inference variable from a constant, returns `None`
1694     /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1695     pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1696         match ct.val {
1697             ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1698             _ => None,
1699         }
1700     }
1701 }
1702
1703 struct ShallowResolver<'a, 'tcx> {
1704     infcx: &'a InferCtxt<'a, 'tcx>,
1705 }
1706
1707 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1708     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1709         self.infcx.tcx
1710     }
1711
1712     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1713         self.infcx.shallow_resolve_ty(ty)
1714     }
1715
1716     fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1717         if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1718             self.infcx
1719                 .inner
1720                 .borrow_mut()
1721                 .const_unification_table
1722                 .probe_value(*vid)
1723                 .val
1724                 .known()
1725                 .unwrap_or(ct)
1726         } else {
1727             ct
1728         }
1729     }
1730 }
1731
1732 impl<'tcx> TypeTrace<'tcx> {
1733     pub fn span(&self) -> Span {
1734         self.cause.span
1735     }
1736
1737     pub fn types(
1738         cause: &ObligationCause<'tcx>,
1739         a_is_expected: bool,
1740         a: Ty<'tcx>,
1741         b: Ty<'tcx>,
1742     ) -> TypeTrace<'tcx> {
1743         TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1744     }
1745
1746     pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1747         TypeTrace {
1748             cause: ObligationCause::dummy(),
1749             values: Types(ExpectedFound { expected: tcx.types.err, found: tcx.types.err }),
1750         }
1751     }
1752 }
1753
1754 impl<'tcx> SubregionOrigin<'tcx> {
1755     pub fn span(&self) -> Span {
1756         match *self {
1757             Subtype(ref a) => a.span(),
1758             InfStackClosure(a) => a,
1759             InvokeClosure(a) => a,
1760             DerefPointer(a) => a,
1761             ClosureCapture(a, _) => a,
1762             IndexSlice(a) => a,
1763             RelateObjectBound(a) => a,
1764             RelateParamBound(a, _) => a,
1765             RelateRegionParamBound(a) => a,
1766             RelateDefaultParamBound(a, _) => a,
1767             Reborrow(a) => a,
1768             ReborrowUpvar(a, _) => a,
1769             DataBorrowed(_, a) => a,
1770             ReferenceOutlivesReferent(_, a) => a,
1771             ParameterInScope(_, a) => a,
1772             ExprTypeIsNotInScope(_, a) => a,
1773             BindingTypeIsNotValidAtDecl(a) => a,
1774             CallRcvr(a) => a,
1775             CallArg(a) => a,
1776             CallReturn(a) => a,
1777             Operand(a) => a,
1778             AddrOf(a) => a,
1779             AutoBorrow(a) => a,
1780             SafeDestructor(a) => a,
1781             CompareImplMethodObligation { span, .. } => span,
1782         }
1783     }
1784
1785     pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1786     where
1787         F: FnOnce() -> Self,
1788     {
1789         match cause.code {
1790             traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1791                 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1792             }
1793
1794             traits::ObligationCauseCode::CompareImplMethodObligation {
1795                 item_name,
1796                 impl_item_def_id,
1797                 trait_item_def_id,
1798             } => SubregionOrigin::CompareImplMethodObligation {
1799                 span: cause.span,
1800                 item_name,
1801                 impl_item_def_id,
1802                 trait_item_def_id,
1803             },
1804
1805             _ => default(),
1806         }
1807     }
1808 }
1809
1810 impl RegionVariableOrigin {
1811     pub fn span(&self) -> Span {
1812         match *self {
1813             MiscVariable(a) => a,
1814             PatternRegion(a) => a,
1815             AddrOfRegion(a) => a,
1816             Autoref(a) => a,
1817             Coercion(a) => a,
1818             EarlyBoundRegion(a, ..) => a,
1819             LateBoundRegion(a, ..) => a,
1820             BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1821             UpvarRegion(_, a) => a,
1822             NLL(..) => bug!("NLL variable used with `span`"),
1823         }
1824     }
1825 }
1826
1827 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1828     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1829         write!(
1830             f,
1831             "RegionObligation(sub_region={:?}, sup_type={:?})",
1832             self.sub_region, self.sup_type
1833         )
1834     }
1835 }