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