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