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