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