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