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