1 pub use self::freshen::TypeFreshener;
2 pub use self::LateBoundRegionConversionTime::*;
3 pub use self::RegionVariableOrigin::*;
4 pub use self::SubregionOrigin::*;
5 pub use self::ValuePairs::*;
7 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
9 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_data_structures::sync::Lrc;
13 use rustc_data_structures::undo_log::Rollback;
14 use rustc_data_structures::unify as ut;
15 use rustc_errors::DiagnosticBuilder;
17 use rustc_hir::def_id::{DefId, LocalDefId};
18 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
19 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
20 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
21 use rustc_middle::mir::interpret::EvalToConstValueResult;
22 use rustc_middle::traits::select;
23 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
24 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
25 use rustc_middle::ty::relate::RelateResult;
26 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
27 pub use rustc_middle::ty::IntVarValue;
28 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
29 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
30 use rustc_session::config::BorrowckMode;
31 use rustc_span::symbol::Symbol;
34 use std::cell::{Cell, Ref, RefCell};
35 use std::collections::BTreeMap;
38 use self::combine::CombineFields;
39 use self::free_regions::RegionRelations;
40 use self::lexical_region_resolve::LexicalRegionResolutions;
41 use self::outlives::env::OutlivesEnvironment;
42 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
43 use self::region_constraints::{
44 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
46 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
52 pub mod error_reporting;
59 mod lexical_region_resolve;
63 pub mod region_constraints;
66 pub mod type_variable;
69 use crate::infer::canonical::OriginalQueryValues;
70 pub use rustc_middle::infer::unify_key;
74 pub struct InferOk<'tcx, T> {
76 pub obligations: PredicateObligations<'tcx>,
78 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
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"
84 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
85 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
88 /// How we should handle region solving.
90 /// This is used so that the region values inferred by HIR region solving are
91 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
92 /// typeck will also do.
93 #[derive(Copy, Clone, Debug)]
94 pub enum RegionckMode {
95 /// The default mode: report region errors, don't erase regions.
97 /// Erase the results of region after solving.
99 /// A flag that is used to suppress region errors, when we are doing
100 /// region checks that the NLL borrow checker will also do -- it might
102 suppress_errors: bool,
106 impl Default for RegionckMode {
107 fn default() -> Self {
113 /// Indicates that the MIR borrowck will repeat these region
114 /// checks, so we should ignore errors if NLL is (unconditionally)
116 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
117 // FIXME(Centril): Once we actually remove `::Migrate` also make
118 // this always `true` and then proceed to eliminate the dead code.
119 match tcx.borrowck_mode() {
120 // If we're on Migrate mode, report AST region errors
121 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
123 // If we're on MIR, don't report AST region errors as they should be reported by NLL
124 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
129 /// This type contains all the things within `InferCtxt` that sit within a
130 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
131 /// operations are hot enough that we want only one call to `borrow_mut` per
132 /// call to `start_snapshot` and `rollback_to`.
133 pub struct InferCtxtInner<'tcx> {
134 /// Cache for projections. This cache is snapshotted along with the infcx.
136 /// Public so that `traits::project` can use it.
137 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
139 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
140 /// that might instantiate a general type variable have an order,
141 /// represented by its upper and lower bounds.
142 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
144 /// Map from const parameter variable to the kind of const it represents.
145 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
147 /// Map from integral variable to the kind of integer it represents.
148 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
150 /// Map from floating variable to the kind of float it represents.
151 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
153 /// Tracks the set of region variables and the constraints between them.
154 /// This is initially `Some(_)` but when
155 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
156 /// -- further attempts to perform unification, etc., may fail if new
157 /// region constraints would've been added.
158 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
160 /// A set of constraints that regionck must validate. Each
161 /// constraint has the form `T:'a`, meaning "some type `T` must
162 /// outlive the lifetime 'a". These constraints derive from
163 /// instantiated type parameters. So if you had a struct defined
166 /// struct Foo<T:'static> { ... }
168 /// then in some expression `let x = Foo { ... }` it will
169 /// instantiate the type parameter `T` with a fresh type `$0`. At
170 /// the same time, it will record a region obligation of
171 /// `$0:'static`. This will get checked later by regionck. (We
172 /// can't generally check these things right away because we have
173 /// to wait until types are resolved.)
175 /// These are stored in a map keyed to the id of the innermost
176 /// enclosing fn body / static initializer expression. This is
177 /// because the location where the obligation was incurred can be
178 /// relevant with respect to which sublifetime assumptions are in
179 /// place. The reason that we store under the fn-id, and not
180 /// something more fine-grained, is so that it is easier for
181 /// regionck to be sure that it has found *all* the region
182 /// obligations (otherwise, it's easy to fail to walk to a
183 /// particular node-id).
185 /// Before running `resolve_regions_and_report_errors`, the creator
186 /// of the inference context is expected to invoke
187 /// `process_region_obligations` (defined in `self::region_obligations`)
188 /// for each body-id in this map, which will process the
189 /// obligations within. This is expected to be done 'late enough'
190 /// that all type inference variables have been bound and so forth.
191 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
193 undo_log: InferCtxtUndoLogs<'tcx>,
196 impl<'tcx> InferCtxtInner<'tcx> {
197 fn new() -> InferCtxtInner<'tcx> {
199 projection_cache: Default::default(),
200 type_variable_storage: type_variable::TypeVariableStorage::new(),
201 undo_log: InferCtxtUndoLogs::default(),
202 const_unification_storage: ut::UnificationTableStorage::new(),
203 int_unification_storage: ut::UnificationTableStorage::new(),
204 float_unification_storage: ut::UnificationTableStorage::new(),
205 region_constraint_storage: Some(RegionConstraintStorage::new()),
206 region_obligations: vec![],
211 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
212 &self.region_obligations
216 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
217 self.projection_cache.with_log(&mut self.undo_log)
221 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
222 self.type_variable_storage.with_log(&mut self.undo_log)
226 fn int_unification_table(
228 ) -> ut::UnificationTable<
231 &mut ut::UnificationStorage<ty::IntVid>,
232 &mut InferCtxtUndoLogs<'tcx>,
235 self.int_unification_storage.with_log(&mut self.undo_log)
239 fn float_unification_table(
241 ) -> ut::UnificationTable<
244 &mut ut::UnificationStorage<ty::FloatVid>,
245 &mut InferCtxtUndoLogs<'tcx>,
248 self.float_unification_storage.with_log(&mut self.undo_log)
252 fn const_unification_table(
254 ) -> ut::UnificationTable<
257 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
258 &mut InferCtxtUndoLogs<'tcx>,
261 self.const_unification_storage.with_log(&mut self.undo_log)
265 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
266 self.region_constraint_storage
268 .expect("region constraints already solved")
269 .with_log(&mut self.undo_log)
273 pub struct InferCtxt<'a, 'tcx> {
274 pub tcx: TyCtxt<'tcx>,
276 /// During type-checking/inference of a body, `in_progress_typeck_results`
277 /// contains a reference to the typeck results being built up, which are
278 /// used for reading closure kinds/signatures as they are inferred,
279 /// and for error reporting logic to read arbitrary node types.
280 pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
282 pub inner: RefCell<InferCtxtInner<'tcx>>,
284 /// If set, this flag causes us to skip the 'leak check' during
285 /// higher-ranked subtyping operations. This flag is a temporary one used
286 /// to manage the removal of the leak-check: for the time being, we still run the
287 /// leak-check, but we issue warnings. This flag can only be set to true
288 /// when entering a snapshot.
289 skip_leak_check: Cell<bool>,
291 /// Once region inference is done, the values for each variable.
292 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
294 /// Caches the results of trait selection. This cache is used
295 /// for things that have to do with the parameters in scope.
296 pub selection_cache: select::SelectionCache<'tcx>,
298 /// Caches the results of trait evaluation.
299 pub evaluation_cache: select::EvaluationCache<'tcx>,
301 /// the set of predicates on which errors have been reported, to
302 /// avoid reporting the same error twice.
303 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
305 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
307 /// When an error occurs, we want to avoid reporting "derived"
308 /// errors that are due to this original failure. Normally, we
309 /// handle this with the `err_count_on_creation` count, which
310 /// basically just tracks how many errors were reported when we
311 /// started type-checking a fn and checks to see if any new errors
312 /// have been reported since then. Not great, but it works.
314 /// However, when errors originated in other passes -- notably
315 /// resolve -- this heuristic breaks down. Therefore, we have this
316 /// auxiliary flag that one can set whenever one creates a
317 /// type-error that is due to an error in a prior pass.
319 /// Don't read this flag directly, call `is_tainted_by_errors()`
320 /// and `set_tainted_by_errors()`.
321 tainted_by_errors_flag: Cell<bool>,
323 /// Track how many errors were reported when this infcx is created.
324 /// If the number of errors increases, that's also a sign (line
325 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
326 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
327 err_count_on_creation: usize,
329 /// This flag is true while there is an active snapshot.
330 in_snapshot: Cell<bool>,
332 /// What is the innermost universe we have created? Starts out as
333 /// `UniverseIndex::root()` but grows from there as we enter
334 /// universal quantifiers.
336 /// N.B., at present, we exclude the universal quantifiers on the
337 /// item we are type-checking, and just consider those names as
338 /// part of the root universe. So this would only get incremented
339 /// when we enter into a higher-ranked (`for<..>`) type or trait
341 universe: Cell<ty::UniverseIndex>,
344 /// See the `error_reporting` module for more details.
345 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
346 pub enum ValuePairs<'tcx> {
347 Types(ExpectedFound<Ty<'tcx>>),
348 Regions(ExpectedFound<ty::Region<'tcx>>),
349 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
350 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
351 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
354 /// The trace designates the path through inference that we took to
355 /// encounter an error or subtyping constraint.
357 /// See the `error_reporting` module for more details.
358 #[derive(Clone, Debug)]
359 pub struct TypeTrace<'tcx> {
360 cause: ObligationCause<'tcx>,
361 values: ValuePairs<'tcx>,
364 /// The origin of a `r1 <= r2` constraint.
366 /// See `error_reporting` module for more details
367 #[derive(Clone, Debug)]
368 pub enum SubregionOrigin<'tcx> {
369 /// Arose from a subtyping relation
370 Subtype(Box<TypeTrace<'tcx>>),
372 /// When casting `&'a T` to an `&'b Trait` object,
373 /// relating `'a` to `'b`
374 RelateObjectBound(Span),
376 /// Some type parameter was instantiated with the given type,
377 /// and that type must outlive some region.
378 RelateParamBound(Span, Ty<'tcx>),
380 /// The given region parameter was instantiated with a region
381 /// that must outlive some other region.
382 RelateRegionParamBound(Span),
384 /// Creating a pointer `b` to contents of another reference
387 /// Creating a pointer `b` to contents of an upvar
388 ReborrowUpvar(Span, ty::UpvarId),
390 /// Data with type `Ty<'tcx>` was borrowed
391 DataBorrowed(Ty<'tcx>, Span),
393 /// (&'a &'b T) where a >= b
394 ReferenceOutlivesReferent(Ty<'tcx>, Span),
396 /// Region in return type of invoked fn must enclose call
399 /// Comparing the signature and requirements of an impl method against
400 /// the containing trait.
401 CompareImplMethodObligation {
404 impl_item_def_id: DefId,
405 trait_item_def_id: DefId,
409 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
410 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
411 static_assert_size!(SubregionOrigin<'_>, 32);
413 /// Times when we replace late-bound regions with variables:
414 #[derive(Clone, Copy, Debug)]
415 pub enum LateBoundRegionConversionTime {
416 /// when a fn is called
419 /// when two higher-ranked types are compared
422 /// when projecting an associated type
423 AssocTypeProjection(DefId),
426 /// Reasons to create a region inference variable
428 /// See `error_reporting` module for more details
429 #[derive(Copy, Clone, Debug)]
430 pub enum RegionVariableOrigin {
431 /// Region variables created for ill-categorized reasons,
432 /// mostly indicates places in need of refactoring
435 /// Regions created by a `&P` or `[...]` pattern
438 /// Regions created by `&` operator
441 /// Regions created as part of an autoref of a method receiver
442 Autoref(Span, ty::AssocItem),
444 /// Regions created as part of an automatic coercion
447 /// Region variables created as the values for early-bound regions
448 EarlyBoundRegion(Span, Symbol),
450 /// Region variables created for bound regions
451 /// in a function or method that is called
452 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
454 UpvarRegion(ty::UpvarId, Span),
456 BoundRegionInCoherence(Symbol),
458 /// This origin is used for the inference variables that we create
459 /// during NLL region processing.
460 Nll(NllRegionVariableOrigin),
463 #[derive(Copy, Clone, Debug)]
464 pub enum NllRegionVariableOrigin {
465 /// During NLL region processing, we create variables for free
466 /// regions that we encounter in the function signature and
467 /// elsewhere. This origin indices we've got one of those.
470 /// "Universal" instantiation of a higher-ranked region (e.g.,
471 /// from a `for<'a> T` binder). Meant to represent "any region".
472 Placeholder(ty::PlaceholderRegion),
474 /// The variable we create to represent `'empty(U0)`.
478 /// If this is true, then this variable was created to represent a lifetime
479 /// bound in a `for` binder. For example, it might have been created to
480 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
481 /// Such variables are created when we are trying to figure out if there
482 /// is any valid instantiation of `'a` that could fit into some scenario.
484 /// This is used to inform error reporting: in the case that we are trying to
485 /// determine whether there is any valid instantiation of a `'a` variable that meets
486 /// some constraint C, we want to blame the "source" of that `for` type,
487 /// rather than blaming the source of the constraint C.
492 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
493 #[derive(Copy, Clone, Debug)]
494 pub enum FixupError<'tcx> {
495 UnresolvedIntTy(IntVid),
496 UnresolvedFloatTy(FloatVid),
498 UnresolvedConst(ConstVid<'tcx>),
501 /// See the `region_obligations` field for more information.
503 pub struct RegionObligation<'tcx> {
504 pub sub_region: ty::Region<'tcx>,
505 pub sup_type: Ty<'tcx>,
506 pub origin: SubregionOrigin<'tcx>,
509 impl<'tcx> fmt::Display for FixupError<'tcx> {
510 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511 use self::FixupError::*;
514 UnresolvedIntTy(_) => write!(
516 "cannot determine the type of this integer; \
517 add a suffix to specify the type explicitly"
519 UnresolvedFloatTy(_) => write!(
521 "cannot determine the type of this number; \
522 add a suffix to specify the type explicitly"
524 UnresolvedTy(_) => write!(f, "unconstrained type"),
525 UnresolvedConst(_) => write!(f, "unconstrained const value"),
530 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
531 /// Necessary because we can't write the following bound:
532 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
533 pub struct InferCtxtBuilder<'tcx> {
535 fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
538 pub trait TyCtxtInferExt<'tcx> {
539 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
542 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
543 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
544 InferCtxtBuilder { tcx: self, fresh_typeck_results: None }
548 impl<'tcx> InferCtxtBuilder<'tcx> {
549 /// Used only by `rustc_typeck` during body type-checking/inference,
550 /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
551 pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
552 self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
556 /// Given a canonical value `C` as a starting point, create an
557 /// inference context that contains each of the bound values
558 /// within instantiated as a fresh variable. The `f` closure is
559 /// invoked with the new infcx, along with the instantiated value
560 /// `V` and a substitution `S`. This substitution `S` maps from
561 /// the bound values in `C` to their instantiated values in `V`
562 /// (in other words, `S(C) = V`).
563 pub fn enter_with_canonical<T, R>(
566 canonical: &Canonical<'tcx, T>,
567 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
570 T: TypeFoldable<'tcx>,
574 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
575 f(infcx, value, subst)
579 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
580 let InferCtxtBuilder { tcx, ref fresh_typeck_results } = *self;
581 let in_progress_typeck_results = fresh_typeck_results.as_ref();
584 in_progress_typeck_results,
585 inner: RefCell::new(InferCtxtInner::new()),
586 lexical_region_resolutions: RefCell::new(None),
587 selection_cache: Default::default(),
588 evaluation_cache: Default::default(),
589 reported_trait_errors: Default::default(),
590 reported_closure_mismatch: Default::default(),
591 tainted_by_errors_flag: Cell::new(false),
592 err_count_on_creation: tcx.sess.err_count(),
593 in_snapshot: Cell::new(false),
594 skip_leak_check: Cell::new(false),
595 universe: Cell::new(ty::UniverseIndex::ROOT),
600 impl<'tcx, T> InferOk<'tcx, T> {
601 pub fn unit(self) -> InferOk<'tcx, ()> {
602 InferOk { value: (), obligations: self.obligations }
605 /// Extracts `value`, registering any obligations into `fulfill_cx`.
606 pub fn into_value_registering_obligations(
608 infcx: &InferCtxt<'_, 'tcx>,
609 fulfill_cx: &mut dyn TraitEngine<'tcx>,
611 let InferOk { value, obligations } = self;
612 for obligation in obligations {
613 fulfill_cx.register_predicate_obligation(infcx, obligation);
619 impl<'tcx> InferOk<'tcx, ()> {
620 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
625 #[must_use = "once you start a snapshot, you should always consume it"]
626 pub struct CombinedSnapshot<'a, 'tcx> {
627 undo_snapshot: Snapshot<'tcx>,
628 region_constraints_snapshot: RegionSnapshot,
629 universe: ty::UniverseIndex,
630 was_in_snapshot: bool,
631 _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
634 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
635 pub fn is_in_snapshot(&self) -> bool {
636 self.in_snapshot.get()
639 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
640 t.fold_with(&mut self.freshener())
643 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
645 ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
650 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
651 freshen::TypeFreshener::new(self)
654 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
655 use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
656 use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
658 ty::Infer(ty::IntVar(vid)) => {
659 if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
665 ty::Infer(ty::FloatVar(vid)) => {
666 if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
676 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
677 let mut inner = self.inner.borrow_mut();
678 let mut vars: Vec<Ty<'_>> = inner
680 .unsolved_variables()
682 .map(|t| self.tcx.mk_ty_var(t))
685 (0..inner.int_unification_table().len())
686 .map(|i| ty::IntVid { index: i as u32 })
687 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
688 .map(|v| self.tcx.mk_int_var(v)),
691 (0..inner.float_unification_table().len())
692 .map(|i| ty::FloatVid { index: i as u32 })
693 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
694 .map(|v| self.tcx.mk_float_var(v)),
701 trace: TypeTrace<'tcx>,
702 param_env: ty::ParamEnv<'tcx>,
703 ) -> CombineFields<'a, 'tcx> {
709 obligations: PredicateObligations::new(),
713 /// Clear the "currently in a snapshot" flag, invoke the closure,
714 /// then restore the flag to its original value. This flag is a
715 /// debugging measure designed to detect cases where we start a
716 /// snapshot, create type variables, and register obligations
717 /// which may involve those type variables in the fulfillment cx,
718 /// potentially leaving "dangling type variables" behind.
719 /// In such cases, an assertion will fail when attempting to
720 /// register obligations, within a snapshot. Very useful, much
721 /// better than grovelling through megabytes of `RUSTC_LOG` output.
723 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
724 /// sometimes create a "mini-fulfilment-cx" in which we enroll
725 /// obligations. As long as this fulfillment cx is fully drained
726 /// before we return, this is not a problem, as there won't be any
727 /// escaping obligations in the main cx. In those cases, you can
728 /// use this function.
729 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
731 F: FnOnce(&Self) -> R,
733 let flag = self.in_snapshot.replace(false);
734 let result = func(self);
735 self.in_snapshot.set(flag);
739 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
740 debug!("start_snapshot()");
742 let in_snapshot = self.in_snapshot.replace(true);
744 let mut inner = self.inner.borrow_mut();
747 undo_snapshot: inner.undo_log.start_snapshot(),
748 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
749 universe: self.universe(),
750 was_in_snapshot: in_snapshot,
751 // Borrow typeck results "in progress" (i.e., during typeck)
752 // to ban writes from within a snapshot to them.
753 _in_progress_typeck_results: self
754 .in_progress_typeck_results
755 .map(|typeck_results| typeck_results.borrow()),
759 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
760 debug!("rollback_to(cause={})", cause);
761 let CombinedSnapshot {
763 region_constraints_snapshot,
766 _in_progress_typeck_results,
769 self.in_snapshot.set(was_in_snapshot);
770 self.universe.set(universe);
772 let mut inner = self.inner.borrow_mut();
773 inner.rollback_to(undo_snapshot);
774 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
777 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
778 debug!("commit_from()");
779 let CombinedSnapshot {
781 region_constraints_snapshot: _,
784 _in_progress_typeck_results,
787 self.in_snapshot.set(was_in_snapshot);
789 self.inner.borrow_mut().commit(undo_snapshot);
792 /// Executes `f` and commit the bindings.
793 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
795 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
797 debug!("commit_unconditionally()");
798 let snapshot = self.start_snapshot();
799 let r = f(&snapshot);
800 self.commit_from(snapshot);
804 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
805 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
807 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
809 debug!("commit_if_ok()");
810 let snapshot = self.start_snapshot();
811 let r = f(&snapshot);
812 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
815 self.commit_from(snapshot);
818 self.rollback_to("commit_if_ok -- error", snapshot);
824 /// Execute `f` then unroll any bindings it creates.
825 pub fn probe<R, F>(&self, f: F) -> R
827 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
830 let snapshot = self.start_snapshot();
831 let r = f(&snapshot);
832 self.rollback_to("probe", snapshot);
836 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
837 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
839 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
842 let snapshot = self.start_snapshot();
843 let was_skip_leak_check = self.skip_leak_check.get();
845 self.skip_leak_check.set(true);
847 let r = f(&snapshot);
848 self.rollback_to("probe", snapshot);
849 self.skip_leak_check.set(was_skip_leak_check);
853 /// Scan the constraints produced since `snapshot` began and returns:
855 /// - `None` -- if none of them involve "region outlives" constraints
856 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
857 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
858 pub fn region_constraints_added_in_snapshot(
860 snapshot: &CombinedSnapshot<'a, 'tcx>,
864 .unwrap_region_constraints()
865 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
868 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
869 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
872 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
874 T: at::ToTrace<'tcx>,
876 let origin = &ObligationCause::dummy();
878 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
879 // Ignore obligations, since we are unrolling
880 // everything anyway.
885 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
887 T: at::ToTrace<'tcx>,
889 let origin = &ObligationCause::dummy();
891 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
892 // Ignore obligations, since we are unrolling
893 // everything anyway.
900 origin: SubregionOrigin<'tcx>,
904 debug!("sub_regions({:?} <: {:?})", a, b);
905 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
908 /// Require that the region `r` be equal to one of the regions in
909 /// the set `regions`.
910 pub fn member_constraint(
912 opaque_type_def_id: DefId,
913 definition_span: Span,
915 region: ty::Region<'tcx>,
916 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
918 debug!("member_constraint({:?} <: {:?})", region, in_regions);
919 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
928 pub fn subtype_predicate(
930 cause: &ObligationCause<'tcx>,
931 param_env: ty::ParamEnv<'tcx>,
932 predicate: ty::PolySubtypePredicate<'tcx>,
933 ) -> Option<InferResult<'tcx, ()>> {
934 // Subtle: it's ok to skip the binder here and resolve because
935 // `shallow_resolve` just ignores anything that is not a type
936 // variable, and because type variable's can't (at present, at
937 // least) capture any of the things bound by this binder.
939 // NOTE(nmatsakis): really, there is no *particular* reason to do this
940 // `shallow_resolve` here except as a micro-optimization.
941 // Naturally I could not resist.
942 let two_unbound_type_vars = {
943 let a = self.shallow_resolve(predicate.skip_binder().a);
944 let b = self.shallow_resolve(predicate.skip_binder().b);
945 a.is_ty_var() && b.is_ty_var()
948 if two_unbound_type_vars {
949 // Two unbound type variables? Can't make progress.
953 Some(self.commit_if_ok(|_snapshot| {
954 let ty::SubtypePredicate { a_is_expected, a, b } =
955 self.replace_bound_vars_with_placeholders(predicate);
957 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
963 pub fn region_outlives_predicate(
965 cause: &traits::ObligationCause<'tcx>,
966 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
967 ) -> UnitResult<'tcx> {
968 self.commit_if_ok(|_snapshot| {
969 let ty::OutlivesPredicate(r_a, r_b) =
970 self.replace_bound_vars_with_placeholders(predicate);
971 let origin = SubregionOrigin::from_obligation_cause(cause, || {
972 RelateRegionParamBound(cause.span)
974 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
979 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
980 self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
983 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
984 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
987 pub fn next_ty_var_in_universe(
989 origin: TypeVariableOrigin,
990 universe: ty::UniverseIndex,
992 let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
993 self.tcx.mk_ty_var(vid)
996 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
997 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1000 pub fn next_const_var(
1003 origin: ConstVariableOrigin,
1004 ) -> &'tcx ty::Const<'tcx> {
1005 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1008 pub fn next_const_var_in_universe(
1011 origin: ConstVariableOrigin,
1012 universe: ty::UniverseIndex,
1013 ) -> &'tcx ty::Const<'tcx> {
1017 .const_unification_table()
1018 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1019 self.tcx.mk_const_var(vid, ty)
1022 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1023 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1025 val: ConstVariableValue::Unknown { universe: self.universe() },
1029 fn next_int_var_id(&self) -> IntVid {
1030 self.inner.borrow_mut().int_unification_table().new_key(None)
1033 pub fn next_int_var(&self) -> Ty<'tcx> {
1034 self.tcx.mk_int_var(self.next_int_var_id())
1037 fn next_float_var_id(&self) -> FloatVid {
1038 self.inner.borrow_mut().float_unification_table().new_key(None)
1041 pub fn next_float_var(&self) -> Ty<'tcx> {
1042 self.tcx.mk_float_var(self.next_float_var_id())
1045 /// Creates a fresh region variable with the next available index.
1046 /// The variable will be created in the maximum universe created
1047 /// thus far, allowing it to name any region created thus far.
1048 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1049 self.next_region_var_in_universe(origin, self.universe())
1052 /// Creates a fresh region variable with the next available index
1053 /// in the given universe; typically, you can use
1054 /// `next_region_var` and just use the maximal universe.
1055 pub fn next_region_var_in_universe(
1057 origin: RegionVariableOrigin,
1058 universe: ty::UniverseIndex,
1059 ) -> ty::Region<'tcx> {
1061 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1062 self.tcx.mk_region(ty::ReVar(region_var))
1065 /// Return the universe that the region `r` was created in. For
1066 /// most regions (e.g., `'static`, named regions from the user,
1067 /// etc) this is the root universe U0. For inference variables or
1068 /// placeholders, however, it will return the universe which which
1069 /// they are associated.
1070 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1071 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1074 /// Number of region variables created so far.
1075 pub fn num_region_vars(&self) -> usize {
1076 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1079 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1080 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1081 self.next_region_var(RegionVariableOrigin::Nll(origin))
1084 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1085 pub fn next_nll_region_var_in_universe(
1087 origin: NllRegionVariableOrigin,
1088 universe: ty::UniverseIndex,
1089 ) -> ty::Region<'tcx> {
1090 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1093 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1095 GenericParamDefKind::Lifetime => {
1096 // Create a region inference variable for the given
1097 // region parameter definition.
1098 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1100 GenericParamDefKind::Type { .. } => {
1101 // Create a type inference variable for the given
1102 // type parameter definition. The substitutions are
1103 // for actual parameters that may be referred to by
1104 // the default of this type parameter, if it exists.
1105 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1106 // used in a path such as `Foo::<T, U>::new()` will
1107 // use an inference variable for `C` with `[T, U]`
1108 // as the substitutions for the default, `(T, U)`.
1109 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1112 TypeVariableOrigin {
1113 kind: TypeVariableOriginKind::TypeParameterDefinition(
1121 self.tcx.mk_ty_var(ty_var_id).into()
1123 GenericParamDefKind::Const { .. } => {
1124 let origin = ConstVariableOrigin {
1125 kind: ConstVariableOriginKind::ConstParameterDefinition(
1132 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1134 val: ConstVariableValue::Unknown { universe: self.universe() },
1136 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1141 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1142 /// type/region parameter to a fresh inference variable.
1143 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1144 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1147 /// Returns `true` if errors have been reported since this infcx was
1148 /// created. This is sometimes used as a heuristic to skip
1149 /// reporting errors that often occur as a result of earlier
1150 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1151 /// inference variables, regionck errors).
1152 pub fn is_tainted_by_errors(&self) -> bool {
1154 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1155 tainted_by_errors_flag={})",
1156 self.tcx.sess.err_count(),
1157 self.err_count_on_creation,
1158 self.tainted_by_errors_flag.get()
1161 if self.tcx.sess.err_count() > self.err_count_on_creation {
1162 return true; // errors reported since this infcx was made
1164 self.tainted_by_errors_flag.get()
1167 /// Set the "tainted by errors" flag to true. We call this when we
1168 /// observe an error from a prior pass.
1169 pub fn set_tainted_by_errors(&self) {
1170 debug!("set_tainted_by_errors()");
1171 self.tainted_by_errors_flag.set(true)
1174 /// Process the region constraints and report any errors that
1175 /// result. After this, no more unification operations should be
1176 /// done -- or the compiler will panic -- but it is legal to use
1177 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1178 pub fn resolve_regions_and_report_errors(
1180 region_context: DefId,
1181 outlives_env: &OutlivesEnvironment<'tcx>,
1184 let (var_infos, data) = {
1185 let mut inner = self.inner.borrow_mut();
1186 let inner = &mut *inner;
1188 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1189 "region_obligations not empty: {:#?}",
1190 inner.region_obligations
1193 .region_constraint_storage
1195 .expect("regions already resolved")
1196 .with_log(&mut inner.undo_log)
1197 .into_infos_and_data()
1201 &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1203 let (lexical_region_resolutions, errors) =
1204 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1206 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1207 assert!(old_value.is_none());
1209 if !self.is_tainted_by_errors() {
1210 // As a heuristic, just skip reporting region errors
1211 // altogether if other errors have been reported while
1212 // this infcx was in use. This is totally hokey but
1213 // otherwise we have a hard time separating legit region
1214 // errors from silly ones.
1215 self.report_region_errors(&errors);
1219 /// Obtains (and clears) the current set of region
1220 /// constraints. The inference context is still usable: further
1221 /// unifications will simply add new constraints.
1223 /// This method is not meant to be used with normal lexical region
1224 /// resolution. Rather, it is used in the NLL mode as a kind of
1225 /// interim hack: basically we run normal type-check and generate
1226 /// region constraints as normal, but then we take them and
1227 /// translate them into the form that the NLL solver
1228 /// understands. See the NLL module for mode details.
1229 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1231 self.inner.borrow().region_obligations.is_empty(),
1232 "region_obligations not empty: {:#?}",
1233 self.inner.borrow().region_obligations
1236 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1239 /// Gives temporary access to the region constraint data.
1240 pub fn with_region_constraints<R>(
1242 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1244 let mut inner = self.inner.borrow_mut();
1245 op(inner.unwrap_region_constraints().data())
1248 /// Takes ownership of the list of variable regions. This implies
1249 /// that all the region constraints have already been taken, and
1250 /// hence that `resolve_regions_and_report_errors` can never be
1251 /// called. This is used only during NLL processing to "hand off" ownership
1252 /// of the set of region variables into the NLL region context.
1253 pub fn take_region_var_origins(&self) -> VarInfos {
1254 let mut inner = self.inner.borrow_mut();
1255 let (var_infos, data) = inner
1256 .region_constraint_storage
1258 .expect("regions already resolved")
1259 .with_log(&mut inner.undo_log)
1260 .into_infos_and_data();
1261 assert!(data.is_empty());
1265 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1266 self.resolve_vars_if_possible(t).to_string()
1269 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1270 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1271 format!("({})", tstrs.join(", "))
1274 pub fn trait_ref_to_string(&self, t: ty::TraitRef<'tcx>) -> String {
1275 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1278 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1279 /// universe index of `TyVar(vid)`.
1280 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1281 use self::type_variable::TypeVariableValue;
1283 match self.inner.borrow_mut().type_variables().probe(vid) {
1284 TypeVariableValue::Known { value } => Ok(value),
1285 TypeVariableValue::Unknown { universe } => Err(universe),
1289 /// Resolve any type variables found in `value` -- but only one
1290 /// level. So, if the variable `?X` is bound to some type
1291 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1292 /// itself be bound to a type).
1294 /// Useful when you only need to inspect the outermost level of
1295 /// the type and don't care about nested types (or perhaps you
1296 /// will be resolving them as well, e.g. in a loop).
1297 pub fn shallow_resolve<T>(&self, value: T) -> T
1299 T: TypeFoldable<'tcx>,
1301 value.fold_with(&mut ShallowResolver { infcx: self })
1304 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1305 self.inner.borrow_mut().type_variables().root_var(var)
1308 /// Where possible, replaces type/const variables in
1309 /// `value` with their final value. Note that region variables
1310 /// are unaffected. If a type/const variable has not been unified, it
1311 /// is left as is. This is an idempotent operation that does
1312 /// not affect inference state in any way and so you can do it
1314 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1316 T: TypeFoldable<'tcx>,
1318 if !value.needs_infer() {
1319 return value; // Avoid duplicated subst-folding.
1321 let mut r = resolve::OpportunisticVarResolver::new(self);
1322 value.fold_with(&mut r)
1325 /// Returns the first unresolved variable contained in `T`. In the
1326 /// process of visiting `T`, this will resolve (where possible)
1327 /// type variables in `T`, but it never constructs the final,
1328 /// resolved type, so it's more efficient than
1329 /// `resolve_vars_if_possible()`.
1330 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1332 T: TypeFoldable<'tcx>,
1334 value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1337 pub fn probe_const_var(
1339 vid: ty::ConstVid<'tcx>,
1340 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1341 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1342 ConstVariableValue::Known { value } => Ok(value),
1343 ConstVariableValue::Unknown { universe } => Err(universe),
1347 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1349 * Attempts to resolve all type/region/const variables in
1350 * `value`. Region inference must have been run already (e.g.,
1351 * by calling `resolve_regions_and_report_errors`). If some
1352 * variable was never unified, an `Err` results.
1354 * This method is idempotent, but it not typically not invoked
1355 * except during the writeback phase.
1358 resolve::fully_resolve(self, value)
1361 // [Note-Type-error-reporting]
1362 // An invariant is that anytime the expected or actual type is Error (the special
1363 // error type, meaning that an error occurred when typechecking this expression),
1364 // this is a derived error. The error cascaded from another error (that was already
1365 // reported), so it's not useful to display it to the user.
1366 // The following methods implement this logic.
1367 // They check if either the actual or expected type is Error, and don't print the error
1368 // in this case. The typechecker should only ever report type errors involving mismatched
1369 // types using one of these methods, and should not call span_err directly for such
1372 pub fn type_error_struct_with_diag<M>(
1376 actual_ty: Ty<'tcx>,
1377 ) -> DiagnosticBuilder<'tcx>
1379 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1381 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1382 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1384 // Don't report an error if actual type is `Error`.
1385 if actual_ty.references_error() {
1386 return self.tcx.sess.diagnostic().struct_dummy();
1389 mk_diag(self.ty_to_string(actual_ty))
1392 pub fn report_mismatched_types(
1394 cause: &ObligationCause<'tcx>,
1397 err: TypeError<'tcx>,
1398 ) -> DiagnosticBuilder<'tcx> {
1399 let trace = TypeTrace::types(cause, true, expected, actual);
1400 self.report_and_explain_type_error(trace, &err)
1403 pub fn report_mismatched_consts(
1405 cause: &ObligationCause<'tcx>,
1406 expected: &'tcx ty::Const<'tcx>,
1407 actual: &'tcx ty::Const<'tcx>,
1408 err: TypeError<'tcx>,
1409 ) -> DiagnosticBuilder<'tcx> {
1410 let trace = TypeTrace::consts(cause, true, expected, actual);
1411 self.report_and_explain_type_error(trace, &err)
1414 pub fn replace_bound_vars_with_fresh_vars<T>(
1417 lbrct: LateBoundRegionConversionTime,
1418 value: ty::Binder<T>,
1419 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1421 T: TypeFoldable<'tcx>,
1424 |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct));
1426 self.next_ty_var(TypeVariableOrigin {
1427 kind: TypeVariableOriginKind::MiscVariable,
1431 let fld_c = |_, ty| {
1432 self.next_const_var(
1434 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1437 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1440 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1441 pub fn verify_generic_bound(
1443 origin: SubregionOrigin<'tcx>,
1444 kind: GenericKind<'tcx>,
1445 a: ty::Region<'tcx>,
1446 bound: VerifyBound<'tcx>,
1448 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1452 .unwrap_region_constraints()
1453 .verify_generic_bound(origin, kind, a, bound);
1456 /// Obtains the latest type of the given closure; this may be a
1457 /// closure in the current function, in which case its
1458 /// `ClosureKind` may not yet be known.
1459 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1460 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1461 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1462 closure_kind_ty.to_opt_closure_kind()
1465 /// Clears the selection, evaluation, and projection caches. This is useful when
1466 /// repeatedly attempting to select an `Obligation` while changing only
1467 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1468 pub fn clear_caches(&self) {
1469 self.selection_cache.clear();
1470 self.evaluation_cache.clear();
1471 self.inner.borrow_mut().projection_cache().clear();
1474 fn universe(&self) -> ty::UniverseIndex {
1478 /// Creates and return a fresh universe that extends all previous
1479 /// universes. Updates `self.universe` to that new universe.
1480 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1481 let u = self.universe.get().next_universe();
1482 self.universe.set(u);
1486 /// Resolves and evaluates a constant.
1488 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1489 /// substitutions and environment are used to resolve the constant. Alternatively if the
1490 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1491 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1492 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1493 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1496 /// This handles inferences variables within both `param_env` and `substs` by
1497 /// performing the operation on their respective canonical forms.
1498 pub fn const_eval_resolve(
1500 param_env: ty::ParamEnv<'tcx>,
1501 ty::Unevaluated { def, substs, promoted }: ty::Unevaluated<'tcx>,
1503 ) -> EvalToConstValueResult<'tcx> {
1504 let mut original_values = OriginalQueryValues::default();
1505 let canonical = self.canonicalize_query((param_env, substs), &mut original_values);
1507 let (param_env, substs) = canonical.value;
1508 // The return value is the evaluated value which doesn't contain any reference to inference
1509 // variables, thus we don't need to substitute back the original values.
1510 self.tcx.const_eval_resolve(param_env, ty::Unevaluated { def, substs, promoted }, span)
1513 /// If `typ` is a type variable of some kind, resolve it one level
1514 /// (but do not resolve types found in the result). If `typ` is
1515 /// not a type variable, just return it unmodified.
1516 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1517 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1519 ty::Infer(ty::TyVar(v)) => {
1520 // Not entirely obvious: if `typ` is a type variable,
1521 // it can be resolved to an int/float variable, which
1522 // can then be recursively resolved, hence the
1523 // recursion. Note though that we prevent type
1524 // variables from unifying to other type variables
1525 // directly (though they may be embedded
1526 // structurally), and we prevent cycles in any case,
1527 // so this recursion should always be of very limited
1530 // Note: if these two lines are combined into one we get
1531 // dynamic borrow errors on `self.inner`.
1532 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1533 known.map_or(typ, |t| self.shallow_resolve_ty(t))
1536 ty::Infer(ty::IntVar(v)) => self
1539 .int_unification_table()
1541 .map(|v| v.to_type(self.tcx))
1544 ty::Infer(ty::FloatVar(v)) => self
1547 .float_unification_table()
1549 .map(|v| v.to_type(self.tcx))
1556 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1557 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1558 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1560 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1561 /// inlined, despite being large, because it has only two call sites that
1562 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1563 /// inference variables), and it handles both `Ty` and `ty::Const` without
1564 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1566 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1568 TyOrConstInferVar::Ty(v) => {
1569 use self::type_variable::TypeVariableValue;
1571 // If `inlined_probe` returns a `Known` value, it never equals
1572 // `ty::Infer(ty::TyVar(v))`.
1573 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1574 TypeVariableValue::Unknown { .. } => false,
1575 TypeVariableValue::Known { .. } => true,
1579 TyOrConstInferVar::TyInt(v) => {
1580 // If `inlined_probe_value` returns a value it's always a
1581 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1583 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1586 TyOrConstInferVar::TyFloat(v) => {
1587 // If `probe_value` returns a value it's always a
1588 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1590 // Not `inlined_probe_value(v)` because this call site is colder.
1591 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1594 TyOrConstInferVar::Const(v) => {
1595 // If `probe_value` returns a `Known` value, it never equals
1596 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1598 // Not `inlined_probe_value(v)` because this call site is colder.
1599 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1600 ConstVariableValue::Unknown { .. } => false,
1601 ConstVariableValue::Known { .. } => true,
1608 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1609 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1610 #[derive(Copy, Clone, Debug)]
1611 pub enum TyOrConstInferVar<'tcx> {
1612 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1614 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1616 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1619 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1620 Const(ConstVid<'tcx>),
1623 impl TyOrConstInferVar<'tcx> {
1624 /// Tries to extract an inference variable from a type or a constant, returns `None`
1625 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1626 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1627 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1628 match arg.unpack() {
1629 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1630 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1631 GenericArgKind::Lifetime(_) => None,
1635 /// Tries to extract an inference variable from a type, returns `None`
1636 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1637 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1639 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1640 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1641 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1646 /// Tries to extract an inference variable from a constant, returns `None`
1647 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1648 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1650 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1656 struct ShallowResolver<'a, 'tcx> {
1657 infcx: &'a InferCtxt<'a, 'tcx>,
1660 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1661 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1665 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1666 self.infcx.shallow_resolve_ty(ty)
1669 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1670 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1674 .const_unification_table()
1685 impl<'tcx> TypeTrace<'tcx> {
1686 pub fn span(&self) -> Span {
1691 cause: &ObligationCause<'tcx>,
1692 a_is_expected: bool,
1695 ) -> TypeTrace<'tcx> {
1696 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1700 cause: &ObligationCause<'tcx>,
1701 a_is_expected: bool,
1702 a: &'tcx ty::Const<'tcx>,
1703 b: &'tcx ty::Const<'tcx>,
1704 ) -> TypeTrace<'tcx> {
1705 TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
1708 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1709 let err = tcx.ty_error();
1711 cause: ObligationCause::dummy(),
1712 values: Types(ExpectedFound { expected: err, found: err }),
1717 impl<'tcx> SubregionOrigin<'tcx> {
1718 pub fn span(&self) -> Span {
1720 Subtype(ref a) => a.span(),
1721 RelateObjectBound(a) => a,
1722 RelateParamBound(a, _) => a,
1723 RelateRegionParamBound(a) => a,
1725 ReborrowUpvar(a, _) => a,
1726 DataBorrowed(_, a) => a,
1727 ReferenceOutlivesReferent(_, a) => a,
1729 CompareImplMethodObligation { span, .. } => span,
1733 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1735 F: FnOnce() -> Self,
1738 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1739 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1742 traits::ObligationCauseCode::CompareImplMethodObligation {
1746 } => SubregionOrigin::CompareImplMethodObligation {
1758 impl RegionVariableOrigin {
1759 pub fn span(&self) -> Span {
1766 | EarlyBoundRegion(a, ..)
1767 | LateBoundRegion(a, ..)
1768 | UpvarRegion(_, a) => a,
1769 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1770 Nll(..) => bug!("NLL variable used with `span`"),
1775 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1776 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1779 "RegionObligation(sub_region={:?}, sup_type={:?})",
1780 self.sub_region, self.sup_type