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