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