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