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