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