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