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