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