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