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