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