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