1 //! See the Book for more information.
3 pub use self::freshen::TypeFreshener;
4 pub use self::LateBoundRegionConversionTime::*;
5 pub use self::RegionVariableOrigin::*;
6 pub use self::SubregionOrigin::*;
7 pub use self::ValuePairs::*;
9 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
11 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
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;
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;
24 use rustc_middle::mir::interpret::EvalToConstValueResult;
25 use rustc_middle::traits::select;
26 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
27 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
28 use rustc_middle::ty::relate::RelateResult;
29 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
30 pub use rustc_middle::ty::IntVarValue;
31 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
32 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
33 use rustc_session::config::BorrowckMode;
34 use rustc_span::symbol::Symbol;
37 use std::cell::{Cell, Ref, RefCell};
38 use std::collections::BTreeMap;
41 use self::combine::CombineFields;
42 use self::free_regions::RegionRelations;
43 use self::lexical_region_resolve::LexicalRegionResolutions;
44 use self::outlives::env::OutlivesEnvironment;
45 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
46 use self::region_constraints::{
47 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
49 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
55 pub mod error_reporting;
62 mod lexical_region_resolve;
66 pub mod region_constraints;
69 pub mod type_variable;
72 use crate::infer::canonical::OriginalQueryValues;
73 pub use rustc_middle::infer::unify_key;
77 pub struct InferOk<'tcx, T> {
79 pub obligations: PredicateObligations<'tcx>,
81 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
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"
87 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
88 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
91 /// How we should handle region solving.
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)]
97 pub enum RegionckMode {
98 /// The default mode: report region errors, don't erase regions.
100 /// Erase the results of region after solving.
102 /// A flag that is used to suppress region errors, when we are doing
103 /// region checks that the NLL borrow checker will also do -- it might
105 suppress_errors: bool,
109 impl Default for RegionckMode {
110 fn default() -> Self {
116 /// Indicates that the MIR borrowck will repeat these region
117 /// checks, so we should ignore errors if NLL is (unconditionally)
119 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
120 // FIXME(Centril): Once we actually remove `::Migrate` also make
121 // this always `true` and then proceed to eliminate the dead code.
122 match tcx.borrowck_mode() {
123 // If we're on Migrate mode, report AST region errors
124 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
126 // If we're on MIR, don't report AST region errors as they should be reported by NLL
127 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
132 /// This type contains all the things within `InferCtxt` that sit within a
133 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
134 /// operations are hot enough that we want only one call to `borrow_mut` per
135 /// call to `start_snapshot` and `rollback_to`.
136 pub struct InferCtxtInner<'tcx> {
137 /// Cache for projections. This cache is snapshotted along with the infcx.
139 /// Public so that `traits::project` can use it.
140 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
142 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
143 /// that might instantiate a general type variable have an order,
144 /// represented by its upper and lower bounds.
145 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
147 /// Map from const parameter variable to the kind of const it represents.
148 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
150 /// Map from integral variable to the kind of integer it represents.
151 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
153 /// Map from floating variable to the kind of float it represents.
154 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
156 /// Tracks the set of region variables and the constraints between them.
157 /// This is initially `Some(_)` but when
158 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
159 /// -- further attempts to perform unification, etc., may fail if new
160 /// region constraints would've been added.
161 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
163 /// A set of constraints that regionck must validate. Each
164 /// constraint has the form `T:'a`, meaning "some type `T` must
165 /// outlive the lifetime 'a". These constraints derive from
166 /// instantiated type parameters. So if you had a struct defined
169 /// struct Foo<T:'static> { ... }
171 /// then in some expression `let x = Foo { ... }` it will
172 /// instantiate the type parameter `T` with a fresh type `$0`. At
173 /// the same time, it will record a region obligation of
174 /// `$0:'static`. This will get checked later by regionck. (We
175 /// can't generally check these things right away because we have
176 /// to wait until types are resolved.)
178 /// These are stored in a map keyed to the id of the innermost
179 /// enclosing fn body / static initializer expression. This is
180 /// because the location where the obligation was incurred can be
181 /// relevant with respect to which sublifetime assumptions are in
182 /// place. The reason that we store under the fn-id, and not
183 /// something more fine-grained, is so that it is easier for
184 /// regionck to be sure that it has found *all* the region
185 /// obligations (otherwise, it's easy to fail to walk to a
186 /// particular node-id).
188 /// Before running `resolve_regions_and_report_errors`, the creator
189 /// of the inference context is expected to invoke
190 /// `process_region_obligations` (defined in `self::region_obligations`)
191 /// for each body-id in this map, which will process the
192 /// obligations within. This is expected to be done 'late enough'
193 /// that all type inference variables have been bound and so forth.
194 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
196 undo_log: InferCtxtUndoLogs<'tcx>,
199 impl<'tcx> InferCtxtInner<'tcx> {
200 fn new() -> InferCtxtInner<'tcx> {
202 projection_cache: Default::default(),
203 type_variable_storage: type_variable::TypeVariableStorage::new(),
204 undo_log: InferCtxtUndoLogs::default(),
205 const_unification_storage: ut::UnificationTableStorage::new(),
206 int_unification_storage: ut::UnificationTableStorage::new(),
207 float_unification_storage: ut::UnificationTableStorage::new(),
208 region_constraint_storage: Some(RegionConstraintStorage::new()),
209 region_obligations: vec![],
214 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
215 &self.region_obligations
219 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
220 self.projection_cache.with_log(&mut self.undo_log)
224 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
225 self.type_variable_storage.with_log(&mut self.undo_log)
229 fn int_unification_table(
231 ) -> ut::UnificationTable<
234 &mut ut::UnificationStorage<ty::IntVid>,
235 &mut InferCtxtUndoLogs<'tcx>,
238 self.int_unification_storage.with_log(&mut self.undo_log)
242 fn float_unification_table(
244 ) -> ut::UnificationTable<
247 &mut ut::UnificationStorage<ty::FloatVid>,
248 &mut InferCtxtUndoLogs<'tcx>,
251 self.float_unification_storage.with_log(&mut self.undo_log)
255 fn const_unification_table(
257 ) -> ut::UnificationTable<
260 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
261 &mut InferCtxtUndoLogs<'tcx>,
264 self.const_unification_storage.with_log(&mut self.undo_log)
268 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
269 self.region_constraint_storage
271 .expect("region constraints already solved")
272 .with_log(&mut self.undo_log)
276 pub struct InferCtxt<'a, 'tcx> {
277 pub tcx: TyCtxt<'tcx>,
279 /// During type-checking/inference of a body, `in_progress_typeck_results`
280 /// contains a reference to the typeck results being built up, which are
281 /// used for reading closure kinds/signatures as they are inferred,
282 /// and for error reporting logic to read arbitrary node types.
283 pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
285 pub inner: RefCell<InferCtxtInner<'tcx>>,
287 /// If set, this flag causes us to skip the 'leak check' during
288 /// higher-ranked subtyping operations. This flag is a temporary one used
289 /// to manage the removal of the leak-check: for the time being, we still run the
290 /// leak-check, but we issue warnings. This flag can only be set to true
291 /// when entering a snapshot.
292 skip_leak_check: Cell<bool>,
294 /// Once region inference is done, the values for each variable.
295 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
297 /// Caches the results of trait selection. This cache is used
298 /// for things that have to do with the parameters in scope.
299 pub selection_cache: select::SelectionCache<'tcx>,
301 /// Caches the results of trait evaluation.
302 pub evaluation_cache: select::EvaluationCache<'tcx>,
304 /// the set of predicates on which errors have been reported, to
305 /// avoid reporting the same error twice.
306 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
308 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
310 /// When an error occurs, we want to avoid reporting "derived"
311 /// errors that are due to this original failure. Normally, we
312 /// handle this with the `err_count_on_creation` count, which
313 /// basically just tracks how many errors were reported when we
314 /// started type-checking a fn and checks to see if any new errors
315 /// have been reported since then. Not great, but it works.
317 /// However, when errors originated in other passes -- notably
318 /// resolve -- this heuristic breaks down. Therefore, we have this
319 /// auxiliary flag that one can set whenever one creates a
320 /// type-error that is due to an error in a prior pass.
322 /// Don't read this flag directly, call `is_tainted_by_errors()`
323 /// and `set_tainted_by_errors()`.
324 tainted_by_errors_flag: Cell<bool>,
326 /// Track how many errors were reported when this infcx is created.
327 /// If the number of errors increases, that's also a sign (line
328 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
329 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
330 err_count_on_creation: usize,
332 /// This flag is true while there is an active snapshot.
333 in_snapshot: Cell<bool>,
335 /// What is the innermost universe we have created? Starts out as
336 /// `UniverseIndex::root()` but grows from there as we enter
337 /// universal quantifiers.
339 /// N.B., at present, we exclude the universal quantifiers on the
340 /// item we are type-checking, and just consider those names as
341 /// part of the root universe. So this would only get incremented
342 /// when we enter into a higher-ranked (`for<..>`) type or trait
344 universe: Cell<ty::UniverseIndex>,
347 /// See the `error_reporting` module for more details.
348 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
349 pub enum ValuePairs<'tcx> {
350 Types(ExpectedFound<Ty<'tcx>>),
351 Regions(ExpectedFound<ty::Region<'tcx>>),
352 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
353 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
354 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
357 /// The trace designates the path through inference that we took to
358 /// encounter an error or subtyping constraint.
360 /// See the `error_reporting` module for more details.
361 #[derive(Clone, Debug)]
362 pub struct TypeTrace<'tcx> {
363 cause: ObligationCause<'tcx>,
364 values: ValuePairs<'tcx>,
367 /// The origin of a `r1 <= r2` constraint.
369 /// See `error_reporting` module for more details
370 #[derive(Clone, Debug)]
371 pub enum SubregionOrigin<'tcx> {
372 /// Arose from a subtyping relation
373 Subtype(Box<TypeTrace<'tcx>>),
375 /// When casting `&'a T` to an `&'b Trait` object,
376 /// relating `'a` to `'b`
377 RelateObjectBound(Span),
379 /// Some type parameter was instantiated with the given type,
380 /// and that type must outlive some region.
381 RelateParamBound(Span, Ty<'tcx>),
383 /// The given region parameter was instantiated with a region
384 /// that must outlive some other region.
385 RelateRegionParamBound(Span),
387 /// Creating a pointer `b` to contents of another reference
390 /// Creating a pointer `b` to contents of an upvar
391 ReborrowUpvar(Span, ty::UpvarId),
393 /// Data with type `Ty<'tcx>` was borrowed
394 DataBorrowed(Ty<'tcx>, Span),
396 /// (&'a &'b T) where a >= b
397 ReferenceOutlivesReferent(Ty<'tcx>, Span),
399 /// Region in return type of invoked fn must enclose call
402 /// Comparing the signature and requirements of an impl method against
403 /// the containing trait.
404 CompareImplMethodObligation {
407 impl_item_def_id: DefId,
408 trait_item_def_id: DefId,
412 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
413 #[cfg(target_arch = "x86_64")]
414 static_assert_size!(SubregionOrigin<'_>, 32);
416 /// Times when we replace late-bound regions with variables:
417 #[derive(Clone, Copy, Debug)]
418 pub enum LateBoundRegionConversionTime {
419 /// when a fn is called
422 /// when two higher-ranked types are compared
425 /// when projecting an associated type
426 AssocTypeProjection(DefId),
429 /// Reasons to create a region inference variable
431 /// See `error_reporting` module for more details
432 #[derive(Copy, Clone, Debug)]
433 pub enum RegionVariableOrigin {
434 /// Region variables created for ill-categorized reasons,
435 /// mostly indicates places in need of refactoring
438 /// Regions created by a `&P` or `[...]` pattern
441 /// Regions created by `&` operator
444 /// Regions created as part of an autoref of a method receiver
445 Autoref(Span, ty::AssocItem),
447 /// Regions created as part of an automatic coercion
450 /// Region variables created as the values for early-bound regions
451 EarlyBoundRegion(Span, Symbol),
453 /// Region variables created for bound regions
454 /// in a function or method that is called
455 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
457 UpvarRegion(ty::UpvarId, Span),
459 BoundRegionInCoherence(Symbol),
461 /// This origin is used for the inference variables that we create
462 /// during NLL region processing.
463 NLL(NLLRegionVariableOrigin),
466 #[derive(Copy, Clone, Debug)]
467 pub enum NLLRegionVariableOrigin {
468 /// During NLL region processing, we create variables for free
469 /// regions that we encounter in the function signature and
470 /// elsewhere. This origin indices we've got one of those.
473 /// "Universal" instantiation of a higher-ranked region (e.g.,
474 /// from a `for<'a> T` binder). Meant to represent "any region".
475 Placeholder(ty::PlaceholderRegion),
477 /// The variable we create to represent `'empty(U0)`.
481 /// If this is true, then this variable was created to represent a lifetime
482 /// bound in a `for` binder. For example, it might have been created to
483 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
484 /// Such variables are created when we are trying to figure out if there
485 /// is any valid instantiation of `'a` that could fit into some scenario.
487 /// This is used to inform error reporting: in the case that we are trying to
488 /// determine whether there is any valid instantiation of a `'a` variable that meets
489 /// some constraint C, we want to blame the "source" of that `for` type,
490 /// rather than blaming the source of the constraint C.
495 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
496 #[derive(Copy, Clone, Debug)]
497 pub enum FixupError<'tcx> {
498 UnresolvedIntTy(IntVid),
499 UnresolvedFloatTy(FloatVid),
501 UnresolvedConst(ConstVid<'tcx>),
504 /// See the `region_obligations` field for more information.
506 pub struct RegionObligation<'tcx> {
507 pub sub_region: ty::Region<'tcx>,
508 pub sup_type: Ty<'tcx>,
509 pub origin: SubregionOrigin<'tcx>,
512 impl<'tcx> fmt::Display for FixupError<'tcx> {
513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514 use self::FixupError::*;
517 UnresolvedIntTy(_) => write!(
519 "cannot determine the type of this integer; \
520 add a suffix to specify the type explicitly"
522 UnresolvedFloatTy(_) => write!(
524 "cannot determine the type of this number; \
525 add a suffix to specify the type explicitly"
527 UnresolvedTy(_) => write!(f, "unconstrained type"),
528 UnresolvedConst(_) => write!(f, "unconstrained const value"),
533 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
534 /// Necessary because we can't write the following bound:
535 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
536 pub struct InferCtxtBuilder<'tcx> {
538 fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
541 pub trait TyCtxtInferExt<'tcx> {
542 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
545 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
546 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
547 InferCtxtBuilder { tcx: self, fresh_typeck_results: None }
551 impl<'tcx> InferCtxtBuilder<'tcx> {
552 /// Used only by `rustc_typeck` during body type-checking/inference,
553 /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
554 pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
555 self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
559 /// Given a canonical value `C` as a starting point, create an
560 /// inference context that contains each of the bound values
561 /// within instantiated as a fresh variable. The `f` closure is
562 /// invoked with the new infcx, along with the instantiated value
563 /// `V` and a substitution `S`. This substitution `S` maps from
564 /// the bound values in `C` to their instantiated values in `V`
565 /// (in other words, `S(C) = V`).
566 pub fn enter_with_canonical<T, R>(
569 canonical: &Canonical<'tcx, T>,
570 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
573 T: TypeFoldable<'tcx>,
577 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
578 f(infcx, value, subst)
582 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
583 let InferCtxtBuilder { tcx, ref fresh_typeck_results } = *self;
584 let in_progress_typeck_results = fresh_typeck_results.as_ref();
587 in_progress_typeck_results,
588 inner: RefCell::new(InferCtxtInner::new()),
589 lexical_region_resolutions: RefCell::new(None),
590 selection_cache: Default::default(),
591 evaluation_cache: Default::default(),
592 reported_trait_errors: Default::default(),
593 reported_closure_mismatch: Default::default(),
594 tainted_by_errors_flag: Cell::new(false),
595 err_count_on_creation: tcx.sess.err_count(),
596 in_snapshot: Cell::new(false),
597 skip_leak_check: Cell::new(false),
598 universe: Cell::new(ty::UniverseIndex::ROOT),
603 impl<'tcx, T> InferOk<'tcx, T> {
604 pub fn unit(self) -> InferOk<'tcx, ()> {
605 InferOk { value: (), obligations: self.obligations }
608 /// Extracts `value`, registering any obligations into `fulfill_cx`.
609 pub fn into_value_registering_obligations(
611 infcx: &InferCtxt<'_, 'tcx>,
612 fulfill_cx: &mut dyn TraitEngine<'tcx>,
614 let InferOk { value, obligations } = self;
615 for obligation in obligations {
616 fulfill_cx.register_predicate_obligation(infcx, obligation);
622 impl<'tcx> InferOk<'tcx, ()> {
623 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
628 #[must_use = "once you start a snapshot, you should always consume it"]
629 pub struct CombinedSnapshot<'a, 'tcx> {
630 undo_snapshot: Snapshot<'tcx>,
631 region_constraints_snapshot: RegionSnapshot,
632 universe: ty::UniverseIndex,
633 was_in_snapshot: bool,
634 _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
637 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
638 pub fn is_in_snapshot(&self) -> bool {
639 self.in_snapshot.get()
642 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
643 t.fold_with(&mut self.freshener())
646 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
648 ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
653 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
654 freshen::TypeFreshener::new(self)
657 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
658 use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
659 use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
661 ty::Infer(ty::IntVar(vid)) => {
662 if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
668 ty::Infer(ty::FloatVar(vid)) => {
669 if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
679 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
680 let mut inner = self.inner.borrow_mut();
681 // FIXME(const_generics): should there be an equivalent function for const variables?
683 let mut vars: Vec<Ty<'_>> = inner
685 .unsolved_variables()
687 .map(|t| self.tcx.mk_ty_var(t))
690 (0..inner.int_unification_table().len())
691 .map(|i| ty::IntVid { index: i as u32 })
692 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
693 .map(|v| self.tcx.mk_int_var(v)),
696 (0..inner.float_unification_table().len())
697 .map(|i| ty::FloatVid { index: i as u32 })
698 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
699 .map(|v| self.tcx.mk_float_var(v)),
706 trace: TypeTrace<'tcx>,
707 param_env: ty::ParamEnv<'tcx>,
708 ) -> CombineFields<'a, 'tcx> {
714 obligations: PredicateObligations::new(),
718 /// Clear the "currently in a snapshot" flag, invoke the closure,
719 /// then restore the flag to its original value. This flag is a
720 /// debugging measure designed to detect cases where we start a
721 /// snapshot, create type variables, and register obligations
722 /// which may involve those type variables in the fulfillment cx,
723 /// potentially leaving "dangling type variables" behind.
724 /// In such cases, an assertion will fail when attempting to
725 /// register obligations, within a snapshot. Very useful, much
726 /// better than grovelling through megabytes of `RUSTC_LOG` output.
728 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
729 /// sometimes create a "mini-fulfilment-cx" in which we enroll
730 /// obligations. As long as this fulfillment cx is fully drained
731 /// before we return, this is not a problem, as there won't be any
732 /// escaping obligations in the main cx. In those cases, you can
733 /// use this function.
734 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
736 F: FnOnce(&Self) -> R,
738 let flag = self.in_snapshot.replace(false);
739 let result = func(self);
740 self.in_snapshot.set(flag);
744 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
745 debug!("start_snapshot()");
747 let in_snapshot = self.in_snapshot.replace(true);
749 let mut inner = self.inner.borrow_mut();
752 undo_snapshot: inner.undo_log.start_snapshot(),
753 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
754 universe: self.universe(),
755 was_in_snapshot: in_snapshot,
756 // Borrow typeck results "in progress" (i.e., during typeck)
757 // to ban writes from within a snapshot to them.
758 _in_progress_typeck_results: self
759 .in_progress_typeck_results
760 .map(|typeck_results| typeck_results.borrow()),
764 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
765 debug!("rollback_to(cause={})", cause);
766 let CombinedSnapshot {
768 region_constraints_snapshot,
771 _in_progress_typeck_results,
774 self.in_snapshot.set(was_in_snapshot);
775 self.universe.set(universe);
777 let mut inner = self.inner.borrow_mut();
778 inner.rollback_to(undo_snapshot);
779 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
782 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
783 debug!("commit_from()");
784 let CombinedSnapshot {
786 region_constraints_snapshot: _,
789 _in_progress_typeck_results,
792 self.in_snapshot.set(was_in_snapshot);
794 self.inner.borrow_mut().commit(undo_snapshot);
797 /// Executes `f` and commit the bindings.
798 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
800 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
802 debug!("commit_unconditionally()");
803 let snapshot = self.start_snapshot();
804 let r = f(&snapshot);
805 self.commit_from(snapshot);
809 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
810 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
812 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
814 debug!("commit_if_ok()");
815 let snapshot = self.start_snapshot();
816 let r = f(&snapshot);
817 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
820 self.commit_from(snapshot);
823 self.rollback_to("commit_if_ok -- error", snapshot);
829 /// Execute `f` then unroll any bindings it creates.
830 pub fn probe<R, F>(&self, f: F) -> R
832 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
835 let snapshot = self.start_snapshot();
836 let r = f(&snapshot);
837 self.rollback_to("probe", snapshot);
841 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
842 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
844 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
847 let snapshot = self.start_snapshot();
848 let was_skip_leak_check = self.skip_leak_check.get();
850 self.skip_leak_check.set(true);
852 let r = f(&snapshot);
853 self.rollback_to("probe", snapshot);
854 self.skip_leak_check.set(was_skip_leak_check);
858 /// Scan the constraints produced since `snapshot` began and returns:
860 /// - `None` -- if none of them involve "region outlives" constraints
861 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
862 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
863 pub fn region_constraints_added_in_snapshot(
865 snapshot: &CombinedSnapshot<'a, 'tcx>,
869 .unwrap_region_constraints()
870 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
873 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
874 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
877 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
879 T: at::ToTrace<'tcx>,
881 let origin = &ObligationCause::dummy();
883 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
884 // Ignore obligations, since we are unrolling
885 // everything anyway.
890 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
892 T: at::ToTrace<'tcx>,
894 let origin = &ObligationCause::dummy();
896 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
897 // Ignore obligations, since we are unrolling
898 // everything anyway.
905 origin: SubregionOrigin<'tcx>,
909 debug!("sub_regions({:?} <: {:?})", a, b);
910 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
913 /// Require that the region `r` be equal to one of the regions in
914 /// the set `regions`.
915 pub fn member_constraint(
917 opaque_type_def_id: DefId,
918 definition_span: Span,
920 region: ty::Region<'tcx>,
921 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
923 debug!("member_constraint({:?} <: {:?})", region, in_regions);
924 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
933 pub fn subtype_predicate(
935 cause: &ObligationCause<'tcx>,
936 param_env: ty::ParamEnv<'tcx>,
937 predicate: ty::PolySubtypePredicate<'tcx>,
938 ) -> Option<InferResult<'tcx, ()>> {
939 // Subtle: it's ok to skip the binder here and resolve because
940 // `shallow_resolve` just ignores anything that is not a type
941 // variable, and because type variable's can't (at present, at
942 // least) capture any of the things bound by this binder.
944 // NOTE(nmatsakis): really, there is no *particular* reason to do this
945 // `shallow_resolve` here except as a micro-optimization.
946 // Naturally I could not resist.
947 let two_unbound_type_vars = {
948 let a = self.shallow_resolve(predicate.skip_binder().a);
949 let b = self.shallow_resolve(predicate.skip_binder().b);
950 a.is_ty_var() && b.is_ty_var()
953 if two_unbound_type_vars {
954 // Two unbound type variables? Can't make progress.
958 Some(self.commit_if_ok(|_snapshot| {
959 let ty::SubtypePredicate { a_is_expected, a, b } =
960 self.replace_bound_vars_with_placeholders(&predicate);
962 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
968 pub fn region_outlives_predicate(
970 cause: &traits::ObligationCause<'tcx>,
971 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
972 ) -> UnitResult<'tcx> {
973 self.commit_if_ok(|_snapshot| {
974 let ty::OutlivesPredicate(r_a, r_b) =
975 self.replace_bound_vars_with_placeholders(&predicate);
976 let origin = SubregionOrigin::from_obligation_cause(cause, || {
977 RelateRegionParamBound(cause.span)
979 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
984 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
985 self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
988 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
989 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
992 pub fn next_ty_var_in_universe(
994 origin: TypeVariableOrigin,
995 universe: ty::UniverseIndex,
997 let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
998 self.tcx.mk_ty_var(vid)
1001 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1002 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1005 pub fn next_const_var(
1008 origin: ConstVariableOrigin,
1009 ) -> &'tcx ty::Const<'tcx> {
1010 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1013 pub fn next_const_var_in_universe(
1016 origin: ConstVariableOrigin,
1017 universe: ty::UniverseIndex,
1018 ) -> &'tcx ty::Const<'tcx> {
1022 .const_unification_table()
1023 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1024 self.tcx.mk_const_var(vid, ty)
1027 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1028 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1030 val: ConstVariableValue::Unknown { universe: self.universe() },
1034 fn next_int_var_id(&self) -> IntVid {
1035 self.inner.borrow_mut().int_unification_table().new_key(None)
1038 pub fn next_int_var(&self) -> Ty<'tcx> {
1039 self.tcx.mk_int_var(self.next_int_var_id())
1042 fn next_float_var_id(&self) -> FloatVid {
1043 self.inner.borrow_mut().float_unification_table().new_key(None)
1046 pub fn next_float_var(&self) -> Ty<'tcx> {
1047 self.tcx.mk_float_var(self.next_float_var_id())
1050 /// Creates a fresh region variable with the next available index.
1051 /// The variable will be created in the maximum universe created
1052 /// thus far, allowing it to name any region created thus far.
1053 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1054 self.next_region_var_in_universe(origin, self.universe())
1057 /// Creates a fresh region variable with the next available index
1058 /// in the given universe; typically, you can use
1059 /// `next_region_var` and just use the maximal universe.
1060 pub fn next_region_var_in_universe(
1062 origin: RegionVariableOrigin,
1063 universe: ty::UniverseIndex,
1064 ) -> ty::Region<'tcx> {
1066 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1067 self.tcx.mk_region(ty::ReVar(region_var))
1070 /// Return the universe that the region `r` was created in. For
1071 /// most regions (e.g., `'static`, named regions from the user,
1072 /// etc) this is the root universe U0. For inference variables or
1073 /// placeholders, however, it will return the universe which which
1074 /// they are associated.
1075 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1076 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1079 /// Number of region variables created so far.
1080 pub fn num_region_vars(&self) -> usize {
1081 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1084 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1085 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1086 self.next_region_var(RegionVariableOrigin::NLL(origin))
1089 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1090 pub fn next_nll_region_var_in_universe(
1092 origin: NLLRegionVariableOrigin,
1093 universe: ty::UniverseIndex,
1094 ) -> ty::Region<'tcx> {
1095 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1098 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1100 GenericParamDefKind::Lifetime => {
1101 // Create a region inference variable for the given
1102 // region parameter definition.
1103 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1105 GenericParamDefKind::Type { .. } => {
1106 // Create a type inference variable for the given
1107 // type parameter definition. The substitutions are
1108 // for actual parameters that may be referred to by
1109 // the default of this type parameter, if it exists.
1110 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1111 // used in a path such as `Foo::<T, U>::new()` will
1112 // use an inference variable for `C` with `[T, U]`
1113 // as the substitutions for the default, `(T, U)`.
1114 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1117 TypeVariableOrigin {
1118 kind: TypeVariableOriginKind::TypeParameterDefinition(
1126 self.tcx.mk_ty_var(ty_var_id).into()
1128 GenericParamDefKind::Const { .. } => {
1129 let origin = ConstVariableOrigin {
1130 kind: ConstVariableOriginKind::ConstParameterDefinition(
1137 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1139 val: ConstVariableValue::Unknown { universe: self.universe() },
1141 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1146 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1147 /// type/region parameter to a fresh inference variable.
1148 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1149 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1152 /// Returns `true` if errors have been reported since this infcx was
1153 /// created. This is sometimes used as a heuristic to skip
1154 /// reporting errors that often occur as a result of earlier
1155 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1156 /// inference variables, regionck errors).
1157 pub fn is_tainted_by_errors(&self) -> bool {
1159 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1160 tainted_by_errors_flag={})",
1161 self.tcx.sess.err_count(),
1162 self.err_count_on_creation,
1163 self.tainted_by_errors_flag.get()
1166 if self.tcx.sess.err_count() > self.err_count_on_creation {
1167 return true; // errors reported since this infcx was made
1169 self.tainted_by_errors_flag.get()
1172 /// Set the "tainted by errors" flag to true. We call this when we
1173 /// observe an error from a prior pass.
1174 pub fn set_tainted_by_errors(&self) {
1175 debug!("set_tainted_by_errors()");
1176 self.tainted_by_errors_flag.set(true)
1179 /// Process the region constraints and report any errors that
1180 /// result. After this, no more unification operations should be
1181 /// done -- or the compiler will panic -- but it is legal to use
1182 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1183 pub fn resolve_regions_and_report_errors(
1185 region_context: DefId,
1186 outlives_env: &OutlivesEnvironment<'tcx>,
1189 let (var_infos, data) = {
1190 let mut inner = self.inner.borrow_mut();
1191 let inner = &mut *inner;
1193 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1194 "region_obligations not empty: {:#?}",
1195 inner.region_obligations
1198 .region_constraint_storage
1200 .expect("regions already resolved")
1201 .with_log(&mut inner.undo_log)
1202 .into_infos_and_data()
1206 &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1208 let (lexical_region_resolutions, errors) =
1209 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1211 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1212 assert!(old_value.is_none());
1214 if !self.is_tainted_by_errors() {
1215 // As a heuristic, just skip reporting region errors
1216 // altogether if other errors have been reported while
1217 // this infcx was in use. This is totally hokey but
1218 // otherwise we have a hard time separating legit region
1219 // errors from silly ones.
1220 self.report_region_errors(&errors);
1224 /// Obtains (and clears) the current set of region
1225 /// constraints. The inference context is still usable: further
1226 /// unifications will simply add new constraints.
1228 /// This method is not meant to be used with normal lexical region
1229 /// resolution. Rather, it is used in the NLL mode as a kind of
1230 /// interim hack: basically we run normal type-check and generate
1231 /// region constraints as normal, but then we take them and
1232 /// translate them into the form that the NLL solver
1233 /// understands. See the NLL module for mode details.
1234 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1236 self.inner.borrow().region_obligations.is_empty(),
1237 "region_obligations not empty: {:#?}",
1238 self.inner.borrow().region_obligations
1241 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1244 /// Gives temporary access to the region constraint data.
1245 pub fn with_region_constraints<R>(
1247 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1249 let mut inner = self.inner.borrow_mut();
1250 op(inner.unwrap_region_constraints().data())
1253 /// Takes ownership of the list of variable regions. This implies
1254 /// that all the region constraints have already been taken, and
1255 /// hence that `resolve_regions_and_report_errors` can never be
1256 /// called. This is used only during NLL processing to "hand off" ownership
1257 /// of the set of region variables into the NLL region context.
1258 pub fn take_region_var_origins(&self) -> VarInfos {
1259 let mut inner = self.inner.borrow_mut();
1260 let (var_infos, data) = inner
1261 .region_constraint_storage
1263 .expect("regions already resolved")
1264 .with_log(&mut inner.undo_log)
1265 .into_infos_and_data();
1266 assert!(data.is_empty());
1270 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1271 self.resolve_vars_if_possible(&t).to_string()
1274 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1275 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1276 format!("({})", tstrs.join(", "))
1279 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1280 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1283 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1284 /// universe index of `TyVar(vid)`.
1285 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1286 use self::type_variable::TypeVariableValue;
1288 match self.inner.borrow_mut().type_variables().probe(vid) {
1289 TypeVariableValue::Known { value } => Ok(value),
1290 TypeVariableValue::Unknown { universe } => Err(universe),
1294 /// Resolve any type variables found in `value` -- but only one
1295 /// level. So, if the variable `?X` is bound to some type
1296 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1297 /// itself be bound to a type).
1299 /// Useful when you only need to inspect the outermost level of
1300 /// the type and don't care about nested types (or perhaps you
1301 /// will be resolving them as well, e.g. in a loop).
1302 pub fn shallow_resolve<T>(&self, value: T) -> T
1304 T: TypeFoldable<'tcx>,
1306 value.fold_with(&mut ShallowResolver { infcx: self })
1309 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1310 self.inner.borrow_mut().type_variables().root_var(var)
1313 /// Where possible, replaces type/const variables in
1314 /// `value` with their final value. Note that region variables
1315 /// are unaffected. If a type/const variable has not been unified, it
1316 /// is left as is. This is an idempotent operation that does
1317 /// not affect inference state in any way and so you can do it
1319 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1321 T: TypeFoldable<'tcx>,
1323 if !value.needs_infer() {
1324 return value.clone(); // Avoid duplicated subst-folding.
1326 let mut r = resolve::OpportunisticVarResolver::new(self);
1327 value.fold_with(&mut r)
1330 /// Returns the first unresolved variable contained in `T`. In the
1331 /// process of visiting `T`, this will resolve (where possible)
1332 /// type variables in `T`, but it never constructs the final,
1333 /// resolved type, so it's more efficient than
1334 /// `resolve_vars_if_possible()`.
1335 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1337 T: TypeFoldable<'tcx>,
1339 let mut r = resolve::UnresolvedTypeFinder::new(self);
1340 value.visit_with(&mut r);
1344 pub fn probe_const_var(
1346 vid: ty::ConstVid<'tcx>,
1347 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1348 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1349 ConstVariableValue::Known { value } => Ok(value),
1350 ConstVariableValue::Unknown { universe } => Err(universe),
1354 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1356 * Attempts to resolve all type/region/const variables in
1357 * `value`. Region inference must have been run already (e.g.,
1358 * by calling `resolve_regions_and_report_errors`). If some
1359 * variable was never unified, an `Err` results.
1361 * This method is idempotent, but it not typically not invoked
1362 * except during the writeback phase.
1365 resolve::fully_resolve(self, value)
1368 // [Note-Type-error-reporting]
1369 // An invariant is that anytime the expected or actual type is Error (the special
1370 // error type, meaning that an error occurred when typechecking this expression),
1371 // this is a derived error. The error cascaded from another error (that was already
1372 // reported), so it's not useful to display it to the user.
1373 // The following methods implement this logic.
1374 // They check if either the actual or expected type is Error, and don't print the error
1375 // in this case. The typechecker should only ever report type errors involving mismatched
1376 // types using one of these methods, and should not call span_err directly for such
1379 pub fn type_error_struct_with_diag<M>(
1383 actual_ty: Ty<'tcx>,
1384 ) -> DiagnosticBuilder<'tcx>
1386 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1388 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1389 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1391 // Don't report an error if actual type is `Error`.
1392 if actual_ty.references_error() {
1393 return self.tcx.sess.diagnostic().struct_dummy();
1396 mk_diag(self.ty_to_string(actual_ty))
1399 pub fn report_mismatched_types(
1401 cause: &ObligationCause<'tcx>,
1404 err: TypeError<'tcx>,
1405 ) -> DiagnosticBuilder<'tcx> {
1406 let trace = TypeTrace::types(cause, true, expected, actual);
1407 self.report_and_explain_type_error(trace, &err)
1410 pub fn report_mismatched_consts(
1412 cause: &ObligationCause<'tcx>,
1413 expected: &'tcx ty::Const<'tcx>,
1414 actual: &'tcx ty::Const<'tcx>,
1415 err: TypeError<'tcx>,
1416 ) -> DiagnosticBuilder<'tcx> {
1417 let trace = TypeTrace::consts(cause, true, expected, actual);
1418 self.report_and_explain_type_error(trace, &err)
1421 pub fn replace_bound_vars_with_fresh_vars<T>(
1424 lbrct: LateBoundRegionConversionTime,
1425 value: &ty::Binder<T>,
1426 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1428 T: TypeFoldable<'tcx>,
1430 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1432 self.next_ty_var(TypeVariableOrigin {
1433 kind: TypeVariableOriginKind::MiscVariable,
1437 let fld_c = |_, ty| {
1438 self.next_const_var(
1440 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1443 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1446 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1447 pub fn verify_generic_bound(
1449 origin: SubregionOrigin<'tcx>,
1450 kind: GenericKind<'tcx>,
1451 a: ty::Region<'tcx>,
1452 bound: VerifyBound<'tcx>,
1454 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1458 .unwrap_region_constraints()
1459 .verify_generic_bound(origin, kind, a, bound);
1462 /// Obtains the latest type of the given closure; this may be a
1463 /// closure in the current function, in which case its
1464 /// `ClosureKind` may not yet be known.
1465 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1466 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1467 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1468 closure_kind_ty.to_opt_closure_kind()
1471 /// Clears the selection, evaluation, and projection caches. This is useful when
1472 /// repeatedly attempting to select an `Obligation` while changing only
1473 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1474 pub fn clear_caches(&self) {
1475 self.selection_cache.clear();
1476 self.evaluation_cache.clear();
1477 self.inner.borrow_mut().projection_cache().clear();
1480 fn universe(&self) -> ty::UniverseIndex {
1484 /// Creates and return a fresh universe that extends all previous
1485 /// universes. Updates `self.universe` to that new universe.
1486 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1487 let u = self.universe.get().next_universe();
1488 self.universe.set(u);
1492 /// Resolves and evaluates a constant.
1494 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1495 /// substitutions and environment are used to resolve the constant. Alternatively if the
1496 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1497 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1498 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1499 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1502 /// This handles inferences variables within both `param_env` and `substs` by
1503 /// performing the operation on their respective canonical forms.
1504 pub fn const_eval_resolve(
1506 param_env: ty::ParamEnv<'tcx>,
1507 def: ty::WithOptConstParam<DefId>,
1508 substs: SubstsRef<'tcx>,
1509 promoted: Option<mir::Promoted>,
1511 ) -> EvalToConstValueResult<'tcx> {
1512 let mut original_values = OriginalQueryValues::default();
1513 let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1515 let (param_env, substs) = canonical.value;
1516 // The return value is the evaluated value which doesn't contain any reference to inference
1517 // variables, thus we don't need to substitute back the original values.
1518 self.tcx.const_eval_resolve(param_env, def, substs, promoted, span)
1521 /// If `typ` is a type variable of some kind, resolve it one level
1522 /// (but do not resolve types found in the result). If `typ` is
1523 /// not a type variable, just return it unmodified.
1524 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1525 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1527 ty::Infer(ty::TyVar(v)) => {
1528 // Not entirely obvious: if `typ` is a type variable,
1529 // it can be resolved to an int/float variable, which
1530 // can then be recursively resolved, hence the
1531 // recursion. Note though that we prevent type
1532 // variables from unifying to other type variables
1533 // directly (though they may be embedded
1534 // structurally), and we prevent cycles in any case,
1535 // so this recursion should always be of very limited
1538 // Note: if these two lines are combined into one we get
1539 // dynamic borrow errors on `self.inner`.
1540 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1541 known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
1544 ty::Infer(ty::IntVar(v)) => self
1547 .int_unification_table()
1549 .map(|v| v.to_type(self.tcx))
1552 ty::Infer(ty::FloatVar(v)) => self
1555 .float_unification_table()
1557 .map(|v| v.to_type(self.tcx))
1564 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1565 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1566 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1568 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1569 /// inlined, despite being large, because it has only two call sites that
1570 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1571 /// inference variables), and it handles both `Ty` and `ty::Const` without
1572 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1574 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1576 TyOrConstInferVar::Ty(v) => {
1577 use self::type_variable::TypeVariableValue;
1579 // If `inlined_probe` returns a `Known` value, it never equals
1580 // `ty::Infer(ty::TyVar(v))`.
1581 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1582 TypeVariableValue::Unknown { .. } => false,
1583 TypeVariableValue::Known { .. } => true,
1587 TyOrConstInferVar::TyInt(v) => {
1588 // If `inlined_probe_value` returns a value it's always a
1589 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1591 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1594 TyOrConstInferVar::TyFloat(v) => {
1595 // If `probe_value` returns a value it's always a
1596 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1598 // Not `inlined_probe_value(v)` because this call site is colder.
1599 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1602 TyOrConstInferVar::Const(v) => {
1603 // If `probe_value` returns a `Known` value, it never equals
1604 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1606 // Not `inlined_probe_value(v)` because this call site is colder.
1607 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1608 ConstVariableValue::Unknown { .. } => false,
1609 ConstVariableValue::Known { .. } => true,
1616 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1617 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1618 #[derive(Copy, Clone, Debug)]
1619 pub enum TyOrConstInferVar<'tcx> {
1620 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1622 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1624 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1627 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1628 Const(ConstVid<'tcx>),
1631 impl TyOrConstInferVar<'tcx> {
1632 /// Tries to extract an inference variable from a type or a constant, returns `None`
1633 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1634 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1635 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1636 match arg.unpack() {
1637 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1638 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1639 GenericArgKind::Lifetime(_) => None,
1643 /// Tries to extract an inference variable from a type, returns `None`
1644 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1645 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1647 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1648 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1649 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1654 /// Tries to extract an inference variable from a constant, returns `None`
1655 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1656 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1658 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1664 struct ShallowResolver<'a, 'tcx> {
1665 infcx: &'a InferCtxt<'a, 'tcx>,
1668 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1669 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1673 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1674 self.infcx.shallow_resolve_ty(ty)
1677 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1678 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1682 .const_unification_table()
1693 impl<'tcx> TypeTrace<'tcx> {
1694 pub fn span(&self) -> Span {
1699 cause: &ObligationCause<'tcx>,
1700 a_is_expected: bool,
1703 ) -> TypeTrace<'tcx> {
1704 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1708 cause: &ObligationCause<'tcx>,
1709 a_is_expected: bool,
1710 a: &'tcx ty::Const<'tcx>,
1711 b: &'tcx ty::Const<'tcx>,
1712 ) -> TypeTrace<'tcx> {
1713 TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
1716 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1717 let err = tcx.ty_error();
1719 cause: ObligationCause::dummy(),
1720 values: Types(ExpectedFound { expected: err, found: err }),
1725 impl<'tcx> SubregionOrigin<'tcx> {
1726 pub fn span(&self) -> Span {
1728 Subtype(ref a) => a.span(),
1729 RelateObjectBound(a) => a,
1730 RelateParamBound(a, _) => a,
1731 RelateRegionParamBound(a) => a,
1733 ReborrowUpvar(a, _) => a,
1734 DataBorrowed(_, a) => a,
1735 ReferenceOutlivesReferent(_, a) => a,
1737 CompareImplMethodObligation { span, .. } => span,
1741 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1743 F: FnOnce() -> Self,
1746 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1747 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1750 traits::ObligationCauseCode::CompareImplMethodObligation {
1754 } => SubregionOrigin::CompareImplMethodObligation {
1766 impl RegionVariableOrigin {
1767 pub fn span(&self) -> Span {
1774 | EarlyBoundRegion(a, ..)
1775 | LateBoundRegion(a, ..)
1776 | UpvarRegion(_, a) => a,
1777 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1778 NLL(..) => bug!("NLL variable used with `span`"),
1783 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1784 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1787 "RegionObligation(sub_region={:?}, sup_type={:?})",
1788 self.sub_region, self.sup_type