]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/mod.rs
Auto merge of #98369 - jyn514:configure.py, r=Mark-Simulacrum
[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::def_id::{DefId, LocalDefId};
19 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
20 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
21 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
22 use rustc_middle::mir::interpret::{ErrorHandled, EvalToValTreeResult};
23 use rustc_middle::traits::select;
24 use rustc_middle::ty::error::{ExpectedFound, TypeError};
25 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
26 use rustc_middle::ty::relate::RelateResult;
27 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
28 use rustc_middle::ty::visit::TypeVisitable;
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<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) -> &[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, TypeVisitable)]
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     Existential {
470         /// If this is true, then this variable was created to represent a lifetime
471         /// bound in a `for` binder. For example, it might have been created to
472         /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
473         /// Such variables are created when we are trying to figure out if there
474         /// is any valid instantiation of `'a` that could fit into some scenario.
475         ///
476         /// This is used to inform error reporting: in the case that we are trying to
477         /// determine whether there is any valid instantiation of a `'a` variable that meets
478         /// some constraint C, we want to blame the "source" of that `for` type,
479         /// rather than blaming the source of the constraint C.
480         from_forall: bool,
481     },
482 }
483
484 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
485 #[derive(Copy, Clone, Debug)]
486 pub enum FixupError<'tcx> {
487     UnresolvedIntTy(IntVid),
488     UnresolvedFloatTy(FloatVid),
489     UnresolvedTy(TyVid),
490     UnresolvedConst(ConstVid<'tcx>),
491 }
492
493 /// See the `region_obligations` field for more information.
494 #[derive(Clone)]
495 pub struct RegionObligation<'tcx> {
496     pub sub_region: ty::Region<'tcx>,
497     pub sup_type: Ty<'tcx>,
498     pub origin: SubregionOrigin<'tcx>,
499 }
500
501 impl<'tcx> fmt::Display for FixupError<'tcx> {
502     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503         use self::FixupError::*;
504
505         match *self {
506             UnresolvedIntTy(_) => write!(
507                 f,
508                 "cannot determine the type of this integer; \
509                  add a suffix to specify the type explicitly"
510             ),
511             UnresolvedFloatTy(_) => write!(
512                 f,
513                 "cannot determine the type of this number; \
514                  add a suffix to specify the type explicitly"
515             ),
516             UnresolvedTy(_) => write!(f, "unconstrained type"),
517             UnresolvedConst(_) => write!(f, "unconstrained const value"),
518         }
519     }
520 }
521
522 /// A temporary returned by `tcx.infer_ctxt()`. This is necessary
523 /// for multiple `InferCtxt` to share the same `in_progress_typeck_results`
524 /// without using `Rc` or something similar.
525 pub struct InferCtxtBuilder<'tcx> {
526     tcx: TyCtxt<'tcx>,
527     fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
528     defining_use_anchor: Option<LocalDefId>,
529 }
530
531 pub trait TyCtxtInferExt<'tcx> {
532     fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
533 }
534
535 impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
536     fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
537         InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None }
538     }
539 }
540
541 impl<'tcx> InferCtxtBuilder<'tcx> {
542     /// Used only by `rustc_typeck` during body type-checking/inference,
543     /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
544     /// Will also change the scope for opaque type defining use checks to the given owner.
545     pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
546         self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
547         self.with_opaque_type_inference(table_owner)
548     }
549
550     /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
551     /// you need to call this function. Otherwise the opaque type will be treated opaquely.
552     ///
553     /// It is only meant to be called in two places, for typeck
554     /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used
555     /// in mir borrowck.
556     pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self {
557         self.defining_use_anchor = Some(defining_use_anchor);
558         self
559     }
560
561     /// Given a canonical value `C` as a starting point, create an
562     /// inference context that contains each of the bound values
563     /// within instantiated as a fresh variable. The `f` closure is
564     /// invoked with the new infcx, along with the instantiated value
565     /// `V` and a substitution `S`. This substitution `S` maps from
566     /// the bound values in `C` to their instantiated values in `V`
567     /// (in other words, `S(C) = V`).
568     pub fn enter_with_canonical<T, R>(
569         &mut self,
570         span: Span,
571         canonical: &Canonical<'tcx, T>,
572         f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
573     ) -> R
574     where
575         T: TypeFoldable<'tcx>,
576     {
577         self.enter(|infcx| {
578             let (value, subst) =
579                 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
580             f(infcx, value, subst)
581         })
582     }
583
584     pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
585         let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self;
586         let in_progress_typeck_results = fresh_typeck_results.as_ref();
587         f(InferCtxt {
588             tcx,
589             defining_use_anchor,
590             in_progress_typeck_results,
591             inner: RefCell::new(InferCtxtInner::new()),
592             lexical_region_resolutions: RefCell::new(None),
593             selection_cache: Default::default(),
594             evaluation_cache: Default::default(),
595             reported_trait_errors: Default::default(),
596             reported_closure_mismatch: Default::default(),
597             tainted_by_errors_flag: Cell::new(false),
598             err_count_on_creation: tcx.sess.err_count(),
599             in_snapshot: Cell::new(false),
600             skip_leak_check: Cell::new(false),
601             universe: Cell::new(ty::UniverseIndex::ROOT),
602         })
603     }
604 }
605
606 impl<'tcx, T> InferOk<'tcx, T> {
607     pub fn unit(self) -> InferOk<'tcx, ()> {
608         InferOk { value: (), obligations: self.obligations }
609     }
610
611     /// Extracts `value`, registering any obligations into `fulfill_cx`.
612     pub fn into_value_registering_obligations(
613         self,
614         infcx: &InferCtxt<'_, 'tcx>,
615         fulfill_cx: &mut dyn TraitEngine<'tcx>,
616     ) -> T {
617         let InferOk { value, obligations } = self;
618         for obligation in obligations {
619             fulfill_cx.register_predicate_obligation(infcx, obligation);
620         }
621         value
622     }
623 }
624
625 impl<'tcx> InferOk<'tcx, ()> {
626     pub fn into_obligations(self) -> PredicateObligations<'tcx> {
627         self.obligations
628     }
629 }
630
631 #[must_use = "once you start a snapshot, you should always consume it"]
632 pub struct CombinedSnapshot<'a, 'tcx> {
633     undo_snapshot: Snapshot<'tcx>,
634     region_constraints_snapshot: RegionSnapshot,
635     universe: ty::UniverseIndex,
636     was_in_snapshot: bool,
637     _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
638 }
639
640 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
641     /// calls `tcx.try_unify_abstract_consts` after
642     /// canonicalizing the consts.
643     #[instrument(skip(self), level = "debug")]
644     pub fn try_unify_abstract_consts(
645         &self,
646         a: ty::Unevaluated<'tcx, ()>,
647         b: ty::Unevaluated<'tcx, ()>,
648         param_env: ty::ParamEnv<'tcx>,
649     ) -> bool {
650         // Reject any attempt to unify two unevaluated constants that contain inference
651         // variables, since inference variables in queries lead to ICEs.
652         if a.substs.has_infer_types_or_consts()
653             || b.substs.has_infer_types_or_consts()
654             || param_env.has_infer_types_or_consts()
655         {
656             debug!("a or b or param_env contain infer vars in its substs -> cannot unify");
657             return false;
658         }
659
660         let param_env_and = param_env.and((a, b));
661         let erased = self.tcx.erase_regions(param_env_and);
662         debug!("after erase_regions: {:?}", erased);
663
664         self.tcx.try_unify_abstract_consts(erased)
665     }
666
667     pub fn is_in_snapshot(&self) -> bool {
668         self.in_snapshot.get()
669     }
670
671     pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
672         t.fold_with(&mut self.freshener())
673     }
674
675     /// Returns the origin of the type variable identified by `vid`, or `None`
676     /// if this is not a type variable.
677     ///
678     /// No attempt is made to resolve `ty`.
679     pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
680         match *ty.kind() {
681             ty::Infer(ty::TyVar(vid)) => {
682                 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
683             }
684             _ => None,
685         }
686     }
687
688     pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
689         freshen::TypeFreshener::new(self, false)
690     }
691
692     /// Like `freshener`, but does not replace `'static` regions.
693     pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
694         freshen::TypeFreshener::new(self, true)
695     }
696
697     pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
698         let mut inner = self.inner.borrow_mut();
699         let mut vars: Vec<Ty<'_>> = inner
700             .type_variables()
701             .unsolved_variables()
702             .into_iter()
703             .map(|t| self.tcx.mk_ty_var(t))
704             .collect();
705         vars.extend(
706             (0..inner.int_unification_table().len())
707                 .map(|i| ty::IntVid { index: i as u32 })
708                 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
709                 .map(|v| self.tcx.mk_int_var(v)),
710         );
711         vars.extend(
712             (0..inner.float_unification_table().len())
713                 .map(|i| ty::FloatVid { index: i as u32 })
714                 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
715                 .map(|v| self.tcx.mk_float_var(v)),
716         );
717         vars
718     }
719
720     fn combine_fields(
721         &'a self,
722         trace: TypeTrace<'tcx>,
723         param_env: ty::ParamEnv<'tcx>,
724         define_opaque_types: bool,
725     ) -> CombineFields<'a, 'tcx> {
726         CombineFields {
727             infcx: self,
728             trace,
729             cause: None,
730             param_env,
731             obligations: PredicateObligations::new(),
732             define_opaque_types,
733         }
734     }
735
736     /// Clear the "currently in a snapshot" flag, invoke the closure,
737     /// then restore the flag to its original value. This flag is a
738     /// debugging measure designed to detect cases where we start a
739     /// snapshot, create type variables, and register obligations
740     /// which may involve those type variables in the fulfillment cx,
741     /// potentially leaving "dangling type variables" behind.
742     /// In such cases, an assertion will fail when attempting to
743     /// register obligations, within a snapshot. Very useful, much
744     /// better than grovelling through megabytes of `RUSTC_LOG` output.
745     ///
746     /// HOWEVER, in some cases the flag is unhelpful. In particular, we
747     /// sometimes create a "mini-fulfilment-cx" in which we enroll
748     /// obligations. As long as this fulfillment cx is fully drained
749     /// before we return, this is not a problem, as there won't be any
750     /// escaping obligations in the main cx. In those cases, you can
751     /// use this function.
752     pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
753     where
754         F: FnOnce(&Self) -> R,
755     {
756         let flag = self.in_snapshot.replace(false);
757         let result = func(self);
758         self.in_snapshot.set(flag);
759         result
760     }
761
762     fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
763         debug!("start_snapshot()");
764
765         let in_snapshot = self.in_snapshot.replace(true);
766
767         let mut inner = self.inner.borrow_mut();
768
769         CombinedSnapshot {
770             undo_snapshot: inner.undo_log.start_snapshot(),
771             region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
772             universe: self.universe(),
773             was_in_snapshot: in_snapshot,
774             // Borrow typeck results "in progress" (i.e., during typeck)
775             // to ban writes from within a snapshot to them.
776             _in_progress_typeck_results: self
777                 .in_progress_typeck_results
778                 .map(|typeck_results| typeck_results.borrow()),
779         }
780     }
781
782     #[instrument(skip(self, snapshot), level = "debug")]
783     fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
784         let CombinedSnapshot {
785             undo_snapshot,
786             region_constraints_snapshot,
787             universe,
788             was_in_snapshot,
789             _in_progress_typeck_results,
790         } = snapshot;
791
792         self.in_snapshot.set(was_in_snapshot);
793         self.universe.set(universe);
794
795         let mut inner = self.inner.borrow_mut();
796         inner.rollback_to(undo_snapshot);
797         inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
798     }
799
800     #[instrument(skip(self, snapshot), level = "debug")]
801     fn commit_from(&self, 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
812         self.inner.borrow_mut().commit(undo_snapshot);
813     }
814
815     /// Executes `f` and commit the bindings.
816     #[instrument(skip(self, f), level = "debug")]
817     pub fn commit_unconditionally<R, F>(&self, f: F) -> R
818     where
819         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
820     {
821         let snapshot = self.start_snapshot();
822         let r = f(&snapshot);
823         self.commit_from(snapshot);
824         r
825     }
826
827     /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
828     #[instrument(skip(self, f), level = "debug")]
829     pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
830     where
831         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
832     {
833         let snapshot = self.start_snapshot();
834         let r = f(&snapshot);
835         debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
836         match r {
837             Ok(_) => {
838                 self.commit_from(snapshot);
839             }
840             Err(_) => {
841                 self.rollback_to("commit_if_ok -- error", snapshot);
842             }
843         }
844         r
845     }
846
847     /// Execute `f` then unroll any bindings it creates.
848     #[instrument(skip(self, f), level = "debug")]
849     pub fn probe<R, F>(&self, f: F) -> R
850     where
851         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
852     {
853         let snapshot = self.start_snapshot();
854         let r = f(&snapshot);
855         self.rollback_to("probe", snapshot);
856         r
857     }
858
859     /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
860     #[instrument(skip(self, f), level = "debug")]
861     pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
862     where
863         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
864     {
865         let snapshot = self.start_snapshot();
866         let was_skip_leak_check = self.skip_leak_check.get();
867         if should_skip {
868             self.skip_leak_check.set(true);
869         }
870         let r = f(&snapshot);
871         self.rollback_to("probe", snapshot);
872         self.skip_leak_check.set(was_skip_leak_check);
873         r
874     }
875
876     /// Scan the constraints produced since `snapshot` began and returns:
877     ///
878     /// - `None` -- if none of them involve "region outlives" constraints
879     /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
880     /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
881     pub fn region_constraints_added_in_snapshot(
882         &self,
883         snapshot: &CombinedSnapshot<'a, 'tcx>,
884     ) -> Option<bool> {
885         self.inner
886             .borrow_mut()
887             .unwrap_region_constraints()
888             .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
889     }
890
891     pub fn opaque_types_added_in_snapshot(&self, snapshot: &CombinedSnapshot<'a, 'tcx>) -> bool {
892         self.inner.borrow().undo_log.opaque_types_in_snapshot(&snapshot.undo_snapshot)
893     }
894
895     pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
896         self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
897     }
898
899     pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
900     where
901         T: at::ToTrace<'tcx>,
902     {
903         let origin = &ObligationCause::dummy();
904         self.probe(|_| {
905             self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
906                 // Ignore obligations, since we are unrolling
907                 // everything anyway.
908             })
909         })
910     }
911
912     pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
913     where
914         T: at::ToTrace<'tcx>,
915     {
916         let origin = &ObligationCause::dummy();
917         self.probe(|_| {
918             self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
919                 // Ignore obligations, since we are unrolling
920                 // everything anyway.
921             })
922         })
923     }
924
925     #[instrument(skip(self), level = "debug")]
926     pub fn sub_regions(
927         &self,
928         origin: SubregionOrigin<'tcx>,
929         a: ty::Region<'tcx>,
930         b: ty::Region<'tcx>,
931     ) {
932         self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
933     }
934
935     /// Require that the region `r` be equal to one of the regions in
936     /// the set `regions`.
937     #[instrument(skip(self), level = "debug")]
938     pub fn member_constraint(
939         &self,
940         opaque_type_def_id: DefId,
941         definition_span: Span,
942         hidden_ty: Ty<'tcx>,
943         region: ty::Region<'tcx>,
944         in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
945     ) {
946         self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
947             opaque_type_def_id,
948             definition_span,
949             hidden_ty,
950             region,
951             in_regions,
952         );
953     }
954
955     /// Processes a `Coerce` predicate from the fulfillment context.
956     /// This is NOT the preferred way to handle coercion, which is to
957     /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
958     ///
959     /// This method here is actually a fallback that winds up being
960     /// invoked when `FnCtxt::coerce` encounters unresolved type variables
961     /// and records a coercion predicate. Presently, this method is equivalent
962     /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
963     /// actually requiring `a <: b`. This is of course a valid coercion,
964     /// but it's not as flexible as `FnCtxt::coerce` would be.
965     ///
966     /// (We may refactor this in the future, but there are a number of
967     /// practical obstacles. Among other things, `FnCtxt::coerce` presently
968     /// records adjustments that are required on the HIR in order to perform
969     /// the coercion, and we don't currently have a way to manage that.)
970     pub fn coerce_predicate(
971         &self,
972         cause: &ObligationCause<'tcx>,
973         param_env: ty::ParamEnv<'tcx>,
974         predicate: ty::PolyCoercePredicate<'tcx>,
975     ) -> Option<InferResult<'tcx, ()>> {
976         let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
977             a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
978             a: p.a,
979             b: p.b,
980         });
981         self.subtype_predicate(cause, param_env, subtype_predicate)
982     }
983
984     pub fn subtype_predicate(
985         &self,
986         cause: &ObligationCause<'tcx>,
987         param_env: ty::ParamEnv<'tcx>,
988         predicate: ty::PolySubtypePredicate<'tcx>,
989     ) -> Option<InferResult<'tcx, ()>> {
990         // Check for two unresolved inference variables, in which case we can
991         // make no progress. This is partly a micro-optimization, but it's
992         // also an opportunity to "sub-unify" the variables. This isn't
993         // *necessary* to prevent cycles, because they would eventually be sub-unified
994         // anyhow during generalization, but it helps with diagnostics (we can detect
995         // earlier that they are sub-unified).
996         //
997         // Note that we can just skip the binders here because
998         // type variables can't (at present, at
999         // least) capture any of the things bound by this binder.
1000         //
1001         // Note that this sub here is not just for diagnostics - it has semantic
1002         // effects as well.
1003         let r_a = self.shallow_resolve(predicate.skip_binder().a);
1004         let r_b = self.shallow_resolve(predicate.skip_binder().b);
1005         match (r_a.kind(), r_b.kind()) {
1006             (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
1007                 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
1008                 return None;
1009             }
1010             _ => {}
1011         }
1012
1013         Some(self.commit_if_ok(|_snapshot| {
1014             let ty::SubtypePredicate { a_is_expected, a, b } =
1015                 self.replace_bound_vars_with_placeholders(predicate);
1016
1017             let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1018
1019             Ok(ok.unit())
1020         }))
1021     }
1022
1023     pub fn region_outlives_predicate(
1024         &self,
1025         cause: &traits::ObligationCause<'tcx>,
1026         predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1027     ) -> UnitResult<'tcx> {
1028         self.commit_if_ok(|_snapshot| {
1029             let ty::OutlivesPredicate(r_a, r_b) =
1030                 self.replace_bound_vars_with_placeholders(predicate);
1031             let origin = SubregionOrigin::from_obligation_cause(cause, || {
1032                 RelateRegionParamBound(cause.span)
1033             });
1034             self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1035             Ok(())
1036         })
1037     }
1038
1039     /// Number of type variables created so far.
1040     pub fn num_ty_vars(&self) -> usize {
1041         self.inner.borrow_mut().type_variables().num_vars()
1042     }
1043
1044     pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1045         self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1046     }
1047
1048     pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1049         self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1050     }
1051
1052     pub fn next_ty_var_id_in_universe(
1053         &self,
1054         origin: TypeVariableOrigin,
1055         universe: ty::UniverseIndex,
1056     ) -> TyVid {
1057         self.inner.borrow_mut().type_variables().new_var(universe, origin)
1058     }
1059
1060     pub fn next_ty_var_in_universe(
1061         &self,
1062         origin: TypeVariableOrigin,
1063         universe: ty::UniverseIndex,
1064     ) -> Ty<'tcx> {
1065         let vid = self.next_ty_var_id_in_universe(origin, universe);
1066         self.tcx.mk_ty_var(vid)
1067     }
1068
1069     pub fn next_const_var(&self, ty: Ty<'tcx>, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
1070         self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1071     }
1072
1073     pub fn next_const_var_in_universe(
1074         &self,
1075         ty: Ty<'tcx>,
1076         origin: ConstVariableOrigin,
1077         universe: ty::UniverseIndex,
1078     ) -> ty::Const<'tcx> {
1079         let vid = self
1080             .inner
1081             .borrow_mut()
1082             .const_unification_table()
1083             .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1084         self.tcx.mk_const_var(vid, ty)
1085     }
1086
1087     pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1088         self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1089             origin,
1090             val: ConstVariableValue::Unknown { universe: self.universe() },
1091         })
1092     }
1093
1094     fn next_int_var_id(&self) -> IntVid {
1095         self.inner.borrow_mut().int_unification_table().new_key(None)
1096     }
1097
1098     pub fn next_int_var(&self) -> Ty<'tcx> {
1099         self.tcx.mk_int_var(self.next_int_var_id())
1100     }
1101
1102     fn next_float_var_id(&self) -> FloatVid {
1103         self.inner.borrow_mut().float_unification_table().new_key(None)
1104     }
1105
1106     pub fn next_float_var(&self) -> Ty<'tcx> {
1107         self.tcx.mk_float_var(self.next_float_var_id())
1108     }
1109
1110     /// Creates a fresh region variable with the next available index.
1111     /// The variable will be created in the maximum universe created
1112     /// thus far, allowing it to name any region created thus far.
1113     pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1114         self.next_region_var_in_universe(origin, self.universe())
1115     }
1116
1117     /// Creates a fresh region variable with the next available index
1118     /// in the given universe; typically, you can use
1119     /// `next_region_var` and just use the maximal universe.
1120     pub fn next_region_var_in_universe(
1121         &self,
1122         origin: RegionVariableOrigin,
1123         universe: ty::UniverseIndex,
1124     ) -> ty::Region<'tcx> {
1125         let region_var =
1126             self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1127         self.tcx.mk_region(ty::ReVar(region_var))
1128     }
1129
1130     /// Return the universe that the region `r` was created in.  For
1131     /// most regions (e.g., `'static`, named regions from the user,
1132     /// etc) this is the root universe U0. For inference variables or
1133     /// placeholders, however, it will return the universe which which
1134     /// they are associated.
1135     pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1136         self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1137     }
1138
1139     /// Number of region variables created so far.
1140     pub fn num_region_vars(&self) -> usize {
1141         self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1142     }
1143
1144     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1145     pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1146         self.next_region_var(RegionVariableOrigin::Nll(origin))
1147     }
1148
1149     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1150     pub fn next_nll_region_var_in_universe(
1151         &self,
1152         origin: NllRegionVariableOrigin,
1153         universe: ty::UniverseIndex,
1154     ) -> ty::Region<'tcx> {
1155         self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1156     }
1157
1158     pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1159         match param.kind {
1160             GenericParamDefKind::Lifetime => {
1161                 // Create a region inference variable for the given
1162                 // region parameter definition.
1163                 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1164             }
1165             GenericParamDefKind::Type { .. } => {
1166                 // Create a type inference variable for the given
1167                 // type parameter definition. The substitutions are
1168                 // for actual parameters that may be referred to by
1169                 // the default of this type parameter, if it exists.
1170                 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1171                 // used in a path such as `Foo::<T, U>::new()` will
1172                 // use an inference variable for `C` with `[T, U]`
1173                 // as the substitutions for the default, `(T, U)`.
1174                 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1175                     self.universe(),
1176                     TypeVariableOrigin {
1177                         kind: TypeVariableOriginKind::TypeParameterDefinition(
1178                             param.name,
1179                             Some(param.def_id),
1180                         ),
1181                         span,
1182                     },
1183                 );
1184
1185                 self.tcx.mk_ty_var(ty_var_id).into()
1186             }
1187             GenericParamDefKind::Const { .. } => {
1188                 let origin = ConstVariableOrigin {
1189                     kind: ConstVariableOriginKind::ConstParameterDefinition(
1190                         param.name,
1191                         param.def_id,
1192                     ),
1193                     span,
1194                 };
1195                 let const_var_id =
1196                     self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1197                         origin,
1198                         val: ConstVariableValue::Unknown { universe: self.universe() },
1199                     });
1200                 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1201             }
1202         }
1203     }
1204
1205     /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1206     /// type/region parameter to a fresh inference variable.
1207     pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1208         InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1209     }
1210
1211     /// Returns `true` if errors have been reported since this infcx was
1212     /// created. This is sometimes used as a heuristic to skip
1213     /// reporting errors that often occur as a result of earlier
1214     /// errors, but where it's hard to be 100% sure (e.g., unresolved
1215     /// inference variables, regionck errors).
1216     pub fn is_tainted_by_errors(&self) -> bool {
1217         debug!(
1218             "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1219              tainted_by_errors_flag={})",
1220             self.tcx.sess.err_count(),
1221             self.err_count_on_creation,
1222             self.tainted_by_errors_flag.get()
1223         );
1224
1225         if self.tcx.sess.err_count() > self.err_count_on_creation {
1226             return true; // errors reported since this infcx was made
1227         }
1228         self.tainted_by_errors_flag.get()
1229     }
1230
1231     /// Set the "tainted by errors" flag to true. We call this when we
1232     /// observe an error from a prior pass.
1233     pub fn set_tainted_by_errors(&self) {
1234         debug!("set_tainted_by_errors()");
1235         self.tainted_by_errors_flag.set(true)
1236     }
1237
1238     pub fn skip_region_resolution(&self) {
1239         let (var_infos, _) = {
1240             let mut inner = self.inner.borrow_mut();
1241             let inner = &mut *inner;
1242             // Note: `inner.region_obligations` may not be empty, because we
1243             // didn't necessarily call `process_registered_region_obligations`.
1244             // This is okay, because that doesn't introduce new vars.
1245             inner
1246                 .region_constraint_storage
1247                 .take()
1248                 .expect("regions already resolved")
1249                 .with_log(&mut inner.undo_log)
1250                 .into_infos_and_data()
1251         };
1252
1253         let lexical_region_resolutions = LexicalRegionResolutions {
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         outlives_env: &OutlivesEnvironment<'tcx>,
1271     ) -> Vec<RegionResolutionError<'tcx>> {
1272         let (var_infos, data) = {
1273             let mut inner = self.inner.borrow_mut();
1274             let inner = &mut *inner;
1275             assert!(
1276                 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1277                 "region_obligations not empty: {:#?}",
1278                 inner.region_obligations
1279             );
1280             inner
1281                 .region_constraint_storage
1282                 .take()
1283                 .expect("regions already resolved")
1284                 .with_log(&mut inner.undo_log)
1285                 .into_infos_and_data()
1286         };
1287
1288         let region_rels = &RegionRelations::new(self.tcx, outlives_env.free_region_map());
1289
1290         let (lexical_region_resolutions, errors) =
1291             lexical_region_resolve::resolve(outlives_env.param_env, region_rels, var_infos, data);
1292
1293         let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1294         assert!(old_value.is_none());
1295
1296         errors
1297     }
1298
1299     /// Process the region constraints and report any errors that
1300     /// result. After this, no more unification operations should be
1301     /// done -- or the compiler will panic -- but it is legal to use
1302     /// `resolve_vars_if_possible` as well as `fully_resolve`.
1303     pub fn resolve_regions_and_report_errors(&self, outlives_env: &OutlivesEnvironment<'tcx>) {
1304         let errors = self.resolve_regions(outlives_env);
1305
1306         if !self.is_tainted_by_errors() {
1307             // As a heuristic, just skip reporting region errors
1308             // altogether if other errors have been reported while
1309             // this infcx was in use.  This is totally hokey but
1310             // otherwise we have a hard time separating legit region
1311             // errors from silly ones.
1312             self.report_region_errors(&errors);
1313         }
1314     }
1315
1316     /// Obtains (and clears) the current set of region
1317     /// constraints. The inference context is still usable: further
1318     /// unifications will simply add new constraints.
1319     ///
1320     /// This method is not meant to be used with normal lexical region
1321     /// resolution. Rather, it is used in the NLL mode as a kind of
1322     /// interim hack: basically we run normal type-check and generate
1323     /// region constraints as normal, but then we take them and
1324     /// translate them into the form that the NLL solver
1325     /// understands. See the NLL module for mode details.
1326     pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1327         assert!(
1328             self.inner.borrow().region_obligations.is_empty(),
1329             "region_obligations not empty: {:#?}",
1330             self.inner.borrow().region_obligations
1331         );
1332
1333         self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1334     }
1335
1336     /// Gives temporary access to the region constraint data.
1337     pub fn with_region_constraints<R>(
1338         &self,
1339         op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1340     ) -> R {
1341         let mut inner = self.inner.borrow_mut();
1342         op(inner.unwrap_region_constraints().data())
1343     }
1344
1345     pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1346         let mut inner = self.inner.borrow_mut();
1347         let inner = &mut *inner;
1348         inner
1349             .region_constraint_storage
1350             .as_mut()
1351             .expect("regions already resolved")
1352             .with_log(&mut inner.undo_log)
1353             .var_origin(vid)
1354     }
1355
1356     /// Takes ownership of the list of variable regions. This implies
1357     /// that all the region constraints have already been taken, and
1358     /// hence that `resolve_regions_and_report_errors` can never be
1359     /// called. This is used only during NLL processing to "hand off" ownership
1360     /// of the set of region variables into the NLL region context.
1361     pub fn take_region_var_origins(&self) -> VarInfos {
1362         let mut inner = self.inner.borrow_mut();
1363         let (var_infos, data) = inner
1364             .region_constraint_storage
1365             .take()
1366             .expect("regions already resolved")
1367             .with_log(&mut inner.undo_log)
1368             .into_infos_and_data();
1369         assert!(data.is_empty());
1370         var_infos
1371     }
1372
1373     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1374         self.resolve_vars_if_possible(t).to_string()
1375     }
1376
1377     /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1378     /// universe index of `TyVar(vid)`.
1379     pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1380         use self::type_variable::TypeVariableValue;
1381
1382         match self.inner.borrow_mut().type_variables().probe(vid) {
1383             TypeVariableValue::Known { value } => Ok(value),
1384             TypeVariableValue::Unknown { universe } => Err(universe),
1385         }
1386     }
1387
1388     /// Resolve any type variables found in `value` -- but only one
1389     /// level.  So, if the variable `?X` is bound to some type
1390     /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1391     /// itself be bound to a type).
1392     ///
1393     /// Useful when you only need to inspect the outermost level of
1394     /// the type and don't care about nested types (or perhaps you
1395     /// will be resolving them as well, e.g. in a loop).
1396     pub fn shallow_resolve<T>(&self, value: T) -> T
1397     where
1398         T: TypeFoldable<'tcx>,
1399     {
1400         value.fold_with(&mut ShallowResolver { infcx: self })
1401     }
1402
1403     pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1404         self.inner.borrow_mut().type_variables().root_var(var)
1405     }
1406
1407     /// Where possible, replaces type/const variables in
1408     /// `value` with their final value. Note that region variables
1409     /// are unaffected. If a type/const variable has not been unified, it
1410     /// is left as is. This is an idempotent operation that does
1411     /// not affect inference state in any way and so you can do it
1412     /// at will.
1413     pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1414     where
1415         T: TypeFoldable<'tcx>,
1416     {
1417         if !value.needs_infer() {
1418             return value; // Avoid duplicated subst-folding.
1419         }
1420         let mut r = resolve::OpportunisticVarResolver::new(self);
1421         value.fold_with(&mut r)
1422     }
1423
1424     pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1425     where
1426         T: TypeFoldable<'tcx>,
1427     {
1428         if !value.needs_infer() {
1429             return value; // Avoid duplicated subst-folding.
1430         }
1431         let mut r = InferenceLiteralEraser { tcx: self.tcx };
1432         value.fold_with(&mut r)
1433     }
1434
1435     /// Returns the first unresolved variable contained in `T`. In the
1436     /// process of visiting `T`, this will resolve (where possible)
1437     /// type variables in `T`, but it never constructs the final,
1438     /// resolved type, so it's more efficient than
1439     /// `resolve_vars_if_possible()`.
1440     pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1441     where
1442         T: TypeVisitable<'tcx>,
1443     {
1444         value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1445     }
1446
1447     pub fn probe_const_var(
1448         &self,
1449         vid: ty::ConstVid<'tcx>,
1450     ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1451         match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1452             ConstVariableValue::Known { value } => Ok(value),
1453             ConstVariableValue::Unknown { universe } => Err(universe),
1454         }
1455     }
1456
1457     pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1458         /*!
1459          * Attempts to resolve all type/region/const variables in
1460          * `value`. Region inference must have been run already (e.g.,
1461          * by calling `resolve_regions_and_report_errors`). If some
1462          * variable was never unified, an `Err` results.
1463          *
1464          * This method is idempotent, but it not typically not invoked
1465          * except during the writeback phase.
1466          */
1467
1468         resolve::fully_resolve(self, value)
1469     }
1470
1471     // [Note-Type-error-reporting]
1472     // An invariant is that anytime the expected or actual type is Error (the special
1473     // error type, meaning that an error occurred when typechecking this expression),
1474     // this is a derived error. The error cascaded from another error (that was already
1475     // reported), so it's not useful to display it to the user.
1476     // The following methods implement this logic.
1477     // They check if either the actual or expected type is Error, and don't print the error
1478     // in this case. The typechecker should only ever report type errors involving mismatched
1479     // types using one of these methods, and should not call span_err directly for such
1480     // errors.
1481
1482     pub fn type_error_struct_with_diag<M>(
1483         &self,
1484         sp: Span,
1485         mk_diag: M,
1486         actual_ty: Ty<'tcx>,
1487     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>
1488     where
1489         M: FnOnce(String) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1490     {
1491         let actual_ty = self.resolve_vars_if_possible(actual_ty);
1492         debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1493
1494         let mut err = mk_diag(self.ty_to_string(actual_ty));
1495
1496         // Don't report an error if actual type is `Error`.
1497         if actual_ty.references_error() {
1498             err.downgrade_to_delayed_bug();
1499         }
1500
1501         err
1502     }
1503
1504     pub fn report_mismatched_types(
1505         &self,
1506         cause: &ObligationCause<'tcx>,
1507         expected: Ty<'tcx>,
1508         actual: Ty<'tcx>,
1509         err: TypeError<'tcx>,
1510     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1511         let trace = TypeTrace::types(cause, true, expected, actual);
1512         self.report_and_explain_type_error(trace, &err)
1513     }
1514
1515     pub fn report_mismatched_consts(
1516         &self,
1517         cause: &ObligationCause<'tcx>,
1518         expected: ty::Const<'tcx>,
1519         actual: ty::Const<'tcx>,
1520         err: TypeError<'tcx>,
1521     ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1522         let trace = TypeTrace::consts(cause, true, expected, actual);
1523         self.report_and_explain_type_error(trace, &err)
1524     }
1525
1526     pub fn replace_bound_vars_with_fresh_vars<T>(
1527         &self,
1528         span: Span,
1529         lbrct: LateBoundRegionConversionTime,
1530         value: ty::Binder<'tcx, T>,
1531     ) -> T
1532     where
1533         T: TypeFoldable<'tcx> + Copy,
1534     {
1535         if let Some(inner) = value.no_bound_vars() {
1536             return inner;
1537         }
1538
1539         let mut region_map = FxHashMap::default();
1540         let fld_r = |br: ty::BoundRegion| {
1541             *region_map
1542                 .entry(br)
1543                 .or_insert_with(|| self.next_region_var(LateBoundRegion(span, br.kind, lbrct)))
1544         };
1545
1546         let mut ty_map = FxHashMap::default();
1547         let fld_t = |bt: ty::BoundTy| {
1548             *ty_map.entry(bt).or_insert_with(|| {
1549                 self.next_ty_var(TypeVariableOrigin {
1550                     kind: TypeVariableOriginKind::MiscVariable,
1551                     span,
1552                 })
1553             })
1554         };
1555         let mut ct_map = FxHashMap::default();
1556         let fld_c = |bc: ty::BoundVar, ty| {
1557             *ct_map.entry(bc).or_insert_with(|| {
1558                 self.next_const_var(
1559                     ty,
1560                     ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1561                 )
1562             })
1563         };
1564         self.tcx.replace_bound_vars_uncached(value, fld_r, fld_t, fld_c)
1565     }
1566
1567     /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1568     pub fn verify_generic_bound(
1569         &self,
1570         origin: SubregionOrigin<'tcx>,
1571         kind: GenericKind<'tcx>,
1572         a: ty::Region<'tcx>,
1573         bound: VerifyBound<'tcx>,
1574     ) {
1575         debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1576
1577         self.inner
1578             .borrow_mut()
1579             .unwrap_region_constraints()
1580             .verify_generic_bound(origin, kind, a, bound);
1581     }
1582
1583     /// Obtains the latest type of the given closure; this may be a
1584     /// closure in the current function, in which case its
1585     /// `ClosureKind` may not yet be known.
1586     pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1587         let closure_kind_ty = closure_substs.as_closure().kind_ty();
1588         let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1589         closure_kind_ty.to_opt_closure_kind()
1590     }
1591
1592     /// Clears the selection, evaluation, and projection caches. This is useful when
1593     /// repeatedly attempting to select an `Obligation` while changing only
1594     /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1595     pub fn clear_caches(&self) {
1596         self.selection_cache.clear();
1597         self.evaluation_cache.clear();
1598         self.inner.borrow_mut().projection_cache().clear();
1599     }
1600
1601     pub fn universe(&self) -> ty::UniverseIndex {
1602         self.universe.get()
1603     }
1604
1605     /// Creates and return a fresh universe that extends all previous
1606     /// universes. Updates `self.universe` to that new universe.
1607     pub fn create_next_universe(&self) -> ty::UniverseIndex {
1608         let u = self.universe.get().next_universe();
1609         self.universe.set(u);
1610         u
1611     }
1612
1613     pub fn try_const_eval_resolve(
1614         &self,
1615         param_env: ty::ParamEnv<'tcx>,
1616         unevaluated: ty::Unevaluated<'tcx>,
1617         ty: Ty<'tcx>,
1618         span: Option<Span>,
1619     ) -> Result<ty::Const<'tcx>, ErrorHandled> {
1620         match self.const_eval_resolve(param_env, unevaluated, span) {
1621             Ok(Some(val)) => Ok(ty::Const::from_value(self.tcx, val, ty)),
1622             Ok(None) => {
1623                 let tcx = self.tcx;
1624                 let def_id = unevaluated.def.did;
1625                 span_bug!(
1626                     tcx.def_span(def_id),
1627                     "unable to construct a constant value for the unevaluated constant {:?}",
1628                     unevaluated
1629                 );
1630             }
1631             Err(err) => Err(err),
1632         }
1633     }
1634
1635     /// Resolves and evaluates a constant.
1636     ///
1637     /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1638     /// substitutions and environment are used to resolve the constant. Alternatively if the
1639     /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1640     /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1641     /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1642     /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1643     /// returned.
1644     ///
1645     /// This handles inferences variables within both `param_env` and `substs` by
1646     /// performing the operation on their respective canonical forms.
1647     #[instrument(skip(self), level = "debug")]
1648     pub fn const_eval_resolve(
1649         &self,
1650         param_env: ty::ParamEnv<'tcx>,
1651         unevaluated: ty::Unevaluated<'tcx>,
1652         span: Option<Span>,
1653     ) -> EvalToValTreeResult<'tcx> {
1654         let substs = self.resolve_vars_if_possible(unevaluated.substs);
1655         debug!(?substs);
1656
1657         // Postpone the evaluation of constants whose substs depend on inference
1658         // variables
1659         if substs.has_infer_types_or_consts() {
1660             debug!("substs have infer types or consts: {:?}", substs);
1661             return Err(ErrorHandled::TooGeneric);
1662         }
1663
1664         let param_env_erased = self.tcx.erase_regions(param_env);
1665         let substs_erased = self.tcx.erase_regions(substs);
1666         debug!(?param_env_erased);
1667         debug!(?substs_erased);
1668
1669         let unevaluated = ty::Unevaluated {
1670             def: unevaluated.def,
1671             substs: substs_erased,
1672             promoted: unevaluated.promoted,
1673         };
1674
1675         // The return value is the evaluated value which doesn't contain any reference to inference
1676         // variables, thus we don't need to substitute back the original values.
1677         self.tcx.const_eval_resolve_for_typeck(param_env_erased, unevaluated, span)
1678     }
1679
1680     /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1681     ///   * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1682     ///   * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1683     ///
1684     /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1685     /// inlined, despite being large, because it has only two call sites that
1686     /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1687     /// inference variables), and it handles both `Ty` and `ty::Const` without
1688     /// having to resort to storing full `GenericArg`s in `stalled_on`.
1689     #[inline(always)]
1690     pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1691         match infer_var {
1692             TyOrConstInferVar::Ty(v) => {
1693                 use self::type_variable::TypeVariableValue;
1694
1695                 // If `inlined_probe` returns a `Known` value, it never equals
1696                 // `ty::Infer(ty::TyVar(v))`.
1697                 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1698                     TypeVariableValue::Unknown { .. } => false,
1699                     TypeVariableValue::Known { .. } => true,
1700                 }
1701             }
1702
1703             TyOrConstInferVar::TyInt(v) => {
1704                 // If `inlined_probe_value` returns a value it's always a
1705                 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1706                 // `ty::Infer(_)`.
1707                 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1708             }
1709
1710             TyOrConstInferVar::TyFloat(v) => {
1711                 // If `probe_value` returns a value it's always a
1712                 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1713                 //
1714                 // Not `inlined_probe_value(v)` because this call site is colder.
1715                 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1716             }
1717
1718             TyOrConstInferVar::Const(v) => {
1719                 // If `probe_value` returns a `Known` value, it never equals
1720                 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1721                 //
1722                 // Not `inlined_probe_value(v)` because this call site is colder.
1723                 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1724                     ConstVariableValue::Unknown { .. } => false,
1725                     ConstVariableValue::Known { .. } => true,
1726                 }
1727             }
1728         }
1729     }
1730 }
1731
1732 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1733 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1734 #[derive(Copy, Clone, Debug)]
1735 pub enum TyOrConstInferVar<'tcx> {
1736     /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1737     Ty(TyVid),
1738     /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1739     TyInt(IntVid),
1740     /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1741     TyFloat(FloatVid),
1742
1743     /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1744     Const(ConstVid<'tcx>),
1745 }
1746
1747 impl<'tcx> TyOrConstInferVar<'tcx> {
1748     /// Tries to extract an inference variable from a type or a constant, returns `None`
1749     /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1750     /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1751     pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1752         match arg.unpack() {
1753             GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1754             GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1755             GenericArgKind::Lifetime(_) => None,
1756         }
1757     }
1758
1759     /// Tries to extract an inference variable from a type, returns `None`
1760     /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1761     pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1762         match *ty.kind() {
1763             ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1764             ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1765             ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1766             _ => None,
1767         }
1768     }
1769
1770     /// Tries to extract an inference variable from a constant, returns `None`
1771     /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1772     pub fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1773         match ct.kind() {
1774             ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1775             _ => None,
1776         }
1777     }
1778 }
1779
1780 /// Replace `{integer}` with `i32` and `{float}` with `f64`.
1781 /// Used only for diagnostics.
1782 struct InferenceLiteralEraser<'tcx> {
1783     tcx: TyCtxt<'tcx>,
1784 }
1785
1786 impl<'tcx> TypeFolder<'tcx> for InferenceLiteralEraser<'tcx> {
1787     fn tcx(&self) -> TyCtxt<'tcx> {
1788         self.tcx
1789     }
1790
1791     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1792         match ty.kind() {
1793             ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1794             ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1795             _ => ty.super_fold_with(self),
1796         }
1797     }
1798 }
1799
1800 struct ShallowResolver<'a, 'tcx> {
1801     infcx: &'a InferCtxt<'a, 'tcx>,
1802 }
1803
1804 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1805     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1806         self.infcx.tcx
1807     }
1808
1809     /// If `ty` is a type variable of some kind, resolve it one level
1810     /// (but do not resolve types found in the result). If `typ` is
1811     /// not a type variable, just return it unmodified.
1812     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1813         match *ty.kind() {
1814             ty::Infer(ty::TyVar(v)) => {
1815                 // Not entirely obvious: if `typ` is a type variable,
1816                 // it can be resolved to an int/float variable, which
1817                 // can then be recursively resolved, hence the
1818                 // recursion. Note though that we prevent type
1819                 // variables from unifying to other type variables
1820                 // directly (though they may be embedded
1821                 // structurally), and we prevent cycles in any case,
1822                 // so this recursion should always be of very limited
1823                 // depth.
1824                 //
1825                 // Note: if these two lines are combined into one we get
1826                 // dynamic borrow errors on `self.inner`.
1827                 let known = self.infcx.inner.borrow_mut().type_variables().probe(v).known();
1828                 known.map_or(ty, |t| self.fold_ty(t))
1829             }
1830
1831             ty::Infer(ty::IntVar(v)) => self
1832                 .infcx
1833                 .inner
1834                 .borrow_mut()
1835                 .int_unification_table()
1836                 .probe_value(v)
1837                 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1838
1839             ty::Infer(ty::FloatVar(v)) => self
1840                 .infcx
1841                 .inner
1842                 .borrow_mut()
1843                 .float_unification_table()
1844                 .probe_value(v)
1845                 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1846
1847             _ => ty,
1848         }
1849     }
1850
1851     fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1852         if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
1853             self.infcx
1854                 .inner
1855                 .borrow_mut()
1856                 .const_unification_table()
1857                 .probe_value(vid)
1858                 .val
1859                 .known()
1860                 .unwrap_or(ct)
1861         } else {
1862             ct
1863         }
1864     }
1865 }
1866
1867 impl<'tcx> TypeTrace<'tcx> {
1868     pub fn span(&self) -> Span {
1869         self.cause.span
1870     }
1871
1872     pub fn types(
1873         cause: &ObligationCause<'tcx>,
1874         a_is_expected: bool,
1875         a: Ty<'tcx>,
1876         b: Ty<'tcx>,
1877     ) -> TypeTrace<'tcx> {
1878         TypeTrace {
1879             cause: cause.clone(),
1880             values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1881         }
1882     }
1883
1884     pub fn consts(
1885         cause: &ObligationCause<'tcx>,
1886         a_is_expected: bool,
1887         a: ty::Const<'tcx>,
1888         b: ty::Const<'tcx>,
1889     ) -> TypeTrace<'tcx> {
1890         TypeTrace {
1891             cause: cause.clone(),
1892             values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1893         }
1894     }
1895 }
1896
1897 impl<'tcx> SubregionOrigin<'tcx> {
1898     pub fn span(&self) -> Span {
1899         match *self {
1900             Subtype(ref a) => a.span(),
1901             RelateObjectBound(a) => a,
1902             RelateParamBound(a, ..) => a,
1903             RelateRegionParamBound(a) => a,
1904             Reborrow(a) => a,
1905             ReborrowUpvar(a, _) => a,
1906             DataBorrowed(_, a) => a,
1907             ReferenceOutlivesReferent(_, a) => a,
1908             CompareImplMethodObligation { span, .. } => span,
1909             CompareImplTypeObligation { span, .. } => span,
1910             CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1911         }
1912     }
1913
1914     pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1915     where
1916         F: FnOnce() -> Self,
1917     {
1918         match *cause.code() {
1919             traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1920                 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1921             }
1922
1923             traits::ObligationCauseCode::CompareImplMethodObligation {
1924                 impl_item_def_id,
1925                 trait_item_def_id,
1926             } => SubregionOrigin::CompareImplMethodObligation {
1927                 span: cause.span,
1928                 impl_item_def_id,
1929                 trait_item_def_id,
1930             },
1931
1932             traits::ObligationCauseCode::CompareImplTypeObligation {
1933                 impl_item_def_id,
1934                 trait_item_def_id,
1935             } => SubregionOrigin::CompareImplTypeObligation {
1936                 span: cause.span,
1937                 impl_item_def_id,
1938                 trait_item_def_id,
1939             },
1940
1941             traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1942                 impl_item_def_id,
1943                 trait_item_def_id,
1944             } => SubregionOrigin::CheckAssociatedTypeBounds {
1945                 impl_item_def_id,
1946                 trait_item_def_id,
1947                 parent: Box::new(default()),
1948             },
1949
1950             _ => default(),
1951         }
1952     }
1953 }
1954
1955 impl RegionVariableOrigin {
1956     pub fn span(&self) -> Span {
1957         match *self {
1958             MiscVariable(a)
1959             | PatternRegion(a)
1960             | AddrOfRegion(a)
1961             | Autoref(a)
1962             | Coercion(a)
1963             | EarlyBoundRegion(a, ..)
1964             | LateBoundRegion(a, ..)
1965             | UpvarRegion(_, a) => a,
1966             Nll(..) => bug!("NLL variable used with `span`"),
1967         }
1968     }
1969 }
1970
1971 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1972     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1973         write!(
1974             f,
1975             "RegionObligation(sub_region={:?}, sup_type={:?})",
1976             self.sub_region, self.sup_type
1977         )
1978     }
1979 }