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