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::*;
8 pub use crate::ty::IntVarValue;
10 use crate::infer::canonical::{Canonical, CanonicalVarValues};
11 use crate::infer::unify_key::{ConstVarValue, ConstVariableValue};
12 use crate::middle::free_region::RegionRelations;
13 use crate::middle::lang_items;
14 use crate::middle::region;
15 use crate::session::config::BorrowckMode;
16 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
17 use crate::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
18 use crate::ty::fold::{TypeFoldable, TypeFolder};
19 use crate::ty::relate::RelateResult;
20 use crate::ty::subst::{GenericArg, InternalSubsts, SubstsRef};
21 use crate::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
22 use crate::ty::{ConstVid, FloatVid, IntVid, TyVid};
24 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
25 use rustc_data_structures::sync::Lrc;
26 use rustc_data_structures::unify as ut;
27 use rustc_errors::DiagnosticBuilder;
29 use rustc_hir::def_id::DefId;
30 use rustc_span::symbol::Symbol;
32 use std::cell::{Cell, Ref, RefCell, RefMut};
33 use std::collections::BTreeMap;
37 use self::combine::CombineFields;
38 use self::lexical_region_resolve::LexicalRegionResolutions;
39 use self::outlives::env::OutlivesEnvironment;
40 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
41 use self::region_constraints::{RegionConstraintCollector, RegionSnapshot};
42 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
43 use self::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
49 pub mod error_reporting;
55 mod lexical_region_resolve;
60 pub mod region_constraints;
63 pub mod type_variable;
69 pub struct InferOk<'tcx, T> {
71 pub obligations: PredicateObligations<'tcx>,
73 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
75 pub type Bound<T> = Option<T>;
76 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
77 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
79 /// A flag that is used to suppress region errors. This is normally
80 /// false, but sometimes -- when we are doing region checks that the
81 /// NLL borrow checker will also do -- it might be set to true.
82 #[derive(Copy, Clone, Default, Debug)]
83 pub struct SuppressRegionErrors {
87 impl SuppressRegionErrors {
88 pub fn suppressed(self) -> bool {
92 /// Indicates that the MIR borrowck will repeat these region
93 /// checks, so we should ignore errors if NLL is (unconditionally)
95 pub fn when_nll_is_enabled(tcx: TyCtxt<'_>) -> Self {
96 // FIXME(Centril): Once we actually remove `::Migrate` also make
97 // this always `true` and then proceed to eliminate the dead code.
98 match tcx.borrowck_mode() {
99 // If we're on Migrate mode, report AST region errors
100 BorrowckMode::Migrate => SuppressRegionErrors { suppressed: false },
102 // If we're on MIR, don't report AST region errors as they should be reported by NLL
103 BorrowckMode::Mir => SuppressRegionErrors { suppressed: true },
108 pub struct InferCtxt<'a, 'tcx> {
109 pub tcx: TyCtxt<'tcx>,
111 /// During type-checking/inference of a body, `in_progress_tables`
112 /// contains a reference to the tables being built up, which are
113 /// used for reading closure kinds/signatures as they are inferred,
114 /// and for error reporting logic to read arbitrary node types.
115 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
117 /// Cache for projections. This cache is snapshotted along with the
120 /// Public so that `traits::project` can use it.
121 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
123 /// We instantiate `UnificationTable` with `bounds<Ty>` because the
124 /// types that might instantiate a general type variable have an
125 /// order, represented by its upper and lower bounds.
126 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
128 /// If set, this flag causes us to skip the 'leak check' during
129 /// higher-ranked subtyping operations. This flag is a temporary one used
130 /// to manage the removal of the leak-check: for the time being, we still run the
131 /// leak-check, but we issue warnings. This flag can only be set to true
132 /// when entering a snapshot.
133 skip_leak_check: Cell<bool>,
135 /// Map from const parameter variable to the kind of const it represents.
136 const_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::ConstVid<'tcx>>>>,
138 /// Map from integral variable to the kind of integer it represents.
139 int_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::IntVid>>>,
141 /// Map from floating variable to the kind of float it represents
142 float_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::FloatVid>>>,
144 /// Tracks the set of region variables and the constraints between
145 /// them. This is initially `Some(_)` but when
146 /// `resolve_regions_and_report_errors` is invoked, this gets set
147 /// to `None` -- further attempts to perform unification etc may
148 /// fail if new region constraints would've been added.
149 region_constraints: RefCell<Option<RegionConstraintCollector<'tcx>>>,
151 /// Once region inference is done, the values for each variable.
152 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
154 /// Caches the results of trait selection. This cache is used
155 /// for things that have to do with the parameters in scope.
156 pub selection_cache: traits::SelectionCache<'tcx>,
158 /// Caches the results of trait evaluation.
159 pub evaluation_cache: traits::EvaluationCache<'tcx>,
161 /// the set of predicates on which errors have been reported, to
162 /// avoid reporting the same error twice.
163 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
165 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
167 /// When an error occurs, we want to avoid reporting "derived"
168 /// errors that are due to this original failure. Normally, we
169 /// handle this with the `err_count_on_creation` count, which
170 /// basically just tracks how many errors were reported when we
171 /// started type-checking a fn and checks to see if any new errors
172 /// have been reported since then. Not great, but it works.
174 /// However, when errors originated in other passes -- notably
175 /// resolve -- this heuristic breaks down. Therefore, we have this
176 /// auxiliary flag that one can set whenever one creates a
177 /// type-error that is due to an error in a prior pass.
179 /// Don't read this flag directly, call `is_tainted_by_errors()`
180 /// and `set_tainted_by_errors()`.
181 tainted_by_errors_flag: Cell<bool>,
183 /// Track how many errors were reported when this infcx is created.
184 /// If the number of errors increases, that's also a sign (line
185 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
186 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
187 err_count_on_creation: usize,
189 /// This flag is true while there is an active snapshot.
190 in_snapshot: Cell<bool>,
192 /// A set of constraints that regionck must validate. Each
193 /// constraint has the form `T:'a`, meaning "some type `T` must
194 /// outlive the lifetime 'a". These constraints derive from
195 /// instantiated type parameters. So if you had a struct defined
198 /// struct Foo<T:'static> { ... }
200 /// then in some expression `let x = Foo { ... }` it will
201 /// instantiate the type parameter `T` with a fresh type `$0`. At
202 /// the same time, it will record a region obligation of
203 /// `$0:'static`. This will get checked later by regionck. (We
204 /// can't generally check these things right away because we have
205 /// to wait until types are resolved.)
207 /// These are stored in a map keyed to the id of the innermost
208 /// enclosing fn body / static initializer expression. This is
209 /// because the location where the obligation was incurred can be
210 /// relevant with respect to which sublifetime assumptions are in
211 /// place. The reason that we store under the fn-id, and not
212 /// something more fine-grained, is so that it is easier for
213 /// regionck to be sure that it has found *all* the region
214 /// obligations (otherwise, it's easy to fail to walk to a
215 /// particular node-id).
217 /// Before running `resolve_regions_and_report_errors`, the creator
218 /// of the inference context is expected to invoke
219 /// `process_region_obligations` (defined in `self::region_obligations`)
220 /// for each body-id in this map, which will process the
221 /// obligations within. This is expected to be done 'late enough'
222 /// that all type inference variables have been bound and so forth.
223 pub region_obligations: RefCell<Vec<(hir::HirId, RegionObligation<'tcx>)>>,
225 /// What is the innermost universe we have created? Starts out as
226 /// `UniverseIndex::root()` but grows from there as we enter
227 /// universal quantifiers.
229 /// N.B., at present, we exclude the universal quantifiers on the
230 /// item we are type-checking, and just consider those names as
231 /// part of the root universe. So this would only get incremented
232 /// when we enter into a higher-ranked (`for<..>`) type or trait
234 universe: Cell<ty::UniverseIndex>,
237 /// A map returned by `replace_bound_vars_with_placeholders()`
238 /// indicating the placeholder region that each late-bound region was
240 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
242 /// See the `error_reporting` module for more details.
243 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
244 pub enum ValuePairs<'tcx> {
245 Types(ExpectedFound<Ty<'tcx>>),
246 Regions(ExpectedFound<ty::Region<'tcx>>),
247 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
248 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
249 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
252 /// The trace designates the path through inference that we took to
253 /// encounter an error or subtyping constraint.
255 /// See the `error_reporting` module for more details.
256 #[derive(Clone, Debug)]
257 pub struct TypeTrace<'tcx> {
258 cause: ObligationCause<'tcx>,
259 values: ValuePairs<'tcx>,
262 /// The origin of a `r1 <= r2` constraint.
264 /// See `error_reporting` module for more details
265 #[derive(Clone, Debug)]
266 pub enum SubregionOrigin<'tcx> {
267 /// Arose from a subtyping relation
268 Subtype(Box<TypeTrace<'tcx>>),
270 /// Stack-allocated closures cannot outlive innermost loop
271 /// or function so as to ensure we only require finite stack
272 InfStackClosure(Span),
274 /// Invocation of closure must be within its lifetime
277 /// Dereference of reference must be within its lifetime
280 /// Closure bound must not outlive captured variables
281 ClosureCapture(Span, hir::HirId),
283 /// Index into slice must be within its lifetime
286 /// When casting `&'a T` to an `&'b Trait` object,
287 /// relating `'a` to `'b`
288 RelateObjectBound(Span),
290 /// Some type parameter was instantiated with the given type,
291 /// and that type must outlive some region.
292 RelateParamBound(Span, Ty<'tcx>),
294 /// The given region parameter was instantiated with a region
295 /// that must outlive some other region.
296 RelateRegionParamBound(Span),
298 /// A bound placed on type parameters that states that must outlive
299 /// the moment of their instantiation.
300 RelateDefaultParamBound(Span, Ty<'tcx>),
302 /// Creating a pointer `b` to contents of another reference
305 /// Creating a pointer `b` to contents of an upvar
306 ReborrowUpvar(Span, ty::UpvarId),
308 /// Data with type `Ty<'tcx>` was borrowed
309 DataBorrowed(Ty<'tcx>, Span),
311 /// (&'a &'b T) where a >= b
312 ReferenceOutlivesReferent(Ty<'tcx>, Span),
314 /// Type or region parameters must be in scope.
315 ParameterInScope(ParameterOrigin, Span),
317 /// The type T of an expression E must outlive the lifetime for E.
318 ExprTypeIsNotInScope(Ty<'tcx>, Span),
320 /// A `ref b` whose region does not enclose the decl site
321 BindingTypeIsNotValidAtDecl(Span),
323 /// Regions appearing in a method receiver must outlive method call
326 /// Regions appearing in a function argument must outlive func call
329 /// Region in return type of invoked fn must enclose call
332 /// Operands must be in scope
335 /// Region resulting from a `&` expr must enclose the `&` expr
338 /// An auto-borrow that does not enclose the expr where it occurs
341 /// Region constraint arriving from destructor safety
342 SafeDestructor(Span),
344 /// Comparing the signature and requirements of an impl method against
345 /// the containing trait.
346 CompareImplMethodObligation {
348 item_name: ast::Name,
349 impl_item_def_id: DefId,
350 trait_item_def_id: DefId,
354 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
355 #[cfg(target_arch = "x86_64")]
356 static_assert_size!(SubregionOrigin<'_>, 32);
358 /// Places that type/region parameters can appear.
359 #[derive(Clone, Copy, Debug)]
360 pub enum ParameterOrigin {
362 MethodCall, // foo.bar() <-- parameters on impl providing bar()
363 OverloadedOperator, // a + b when overloaded
364 OverloadedDeref, // *a when overloaded
367 /// Times when we replace late-bound regions with variables:
368 #[derive(Clone, Copy, Debug)]
369 pub enum LateBoundRegionConversionTime {
370 /// when a fn is called
373 /// when two higher-ranked types are compared
376 /// when projecting an associated type
377 AssocTypeProjection(DefId),
380 /// Reasons to create a region inference variable
382 /// See `error_reporting` module for more details
383 #[derive(Copy, Clone, Debug)]
384 pub enum RegionVariableOrigin {
385 /// Region variables created for ill-categorized reasons,
386 /// mostly indicates places in need of refactoring
389 /// Regions created by a `&P` or `[...]` pattern
392 /// Regions created by `&` operator
395 /// Regions created as part of an autoref of a method receiver
398 /// Regions created as part of an automatic coercion
401 /// Region variables created as the values for early-bound regions
402 EarlyBoundRegion(Span, Symbol),
404 /// Region variables created for bound regions
405 /// in a function or method that is called
406 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
408 UpvarRegion(ty::UpvarId, Span),
410 BoundRegionInCoherence(ast::Name),
412 /// This origin is used for the inference variables that we create
413 /// during NLL region processing.
414 NLL(NLLRegionVariableOrigin),
417 #[derive(Copy, Clone, Debug)]
418 pub enum NLLRegionVariableOrigin {
419 /// During NLL region processing, we create variables for free
420 /// regions that we encounter in the function signature and
421 /// elsewhere. This origin indices we've got one of those.
424 /// "Universal" instantiation of a higher-ranked region (e.g.,
425 /// from a `for<'a> T` binder). Meant to represent "any region".
426 Placeholder(ty::PlaceholderRegion),
429 /// If this is true, then this variable was created to represent a lifetime
430 /// bound in a `for` binder. For example, it might have been created to
431 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
432 /// Such variables are created when we are trying to figure out if there
433 /// is any valid instantiation of `'a` that could fit into some scenario.
435 /// This is used to inform error reporting: in the case that we are trying to
436 /// determine whether there is any valid instantiation of a `'a` variable that meets
437 /// some constraint C, we want to blame the "source" of that `for` type,
438 /// rather than blaming the source of the constraint C.
443 impl NLLRegionVariableOrigin {
444 pub fn is_universal(self) -> bool {
446 NLLRegionVariableOrigin::FreeRegion => true,
447 NLLRegionVariableOrigin::Placeholder(..) => true,
448 NLLRegionVariableOrigin::Existential { .. } => false,
452 pub fn is_existential(self) -> bool {
457 #[derive(Copy, Clone, Debug)]
458 pub enum FixupError<'tcx> {
459 UnresolvedIntTy(IntVid),
460 UnresolvedFloatTy(FloatVid),
462 UnresolvedConst(ConstVid<'tcx>),
465 /// See the `region_obligations` field for more information.
467 pub struct RegionObligation<'tcx> {
468 pub sub_region: ty::Region<'tcx>,
469 pub sup_type: Ty<'tcx>,
470 pub origin: SubregionOrigin<'tcx>,
473 impl<'tcx> fmt::Display for FixupError<'tcx> {
474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475 use self::FixupError::*;
478 UnresolvedIntTy(_) => write!(
480 "cannot determine the type of this integer; \
481 add a suffix to specify the type explicitly"
483 UnresolvedFloatTy(_) => write!(
485 "cannot determine the type of this number; \
486 add a suffix to specify the type explicitly"
488 UnresolvedTy(_) => write!(f, "unconstrained type"),
489 UnresolvedConst(_) => write!(f, "unconstrained const value"),
494 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
495 /// Necessary because we can't write the following bound:
496 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
497 pub struct InferCtxtBuilder<'tcx> {
498 global_tcx: TyCtxt<'tcx>,
499 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
503 pub fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
504 InferCtxtBuilder { global_tcx: self, fresh_tables: None }
508 impl<'tcx> InferCtxtBuilder<'tcx> {
509 /// Used only by `rustc_typeck` during body type-checking/inference,
510 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
511 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
512 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
516 /// Given a canonical value `C` as a starting point, create an
517 /// inference context that contains each of the bound values
518 /// within instantiated as a fresh variable. The `f` closure is
519 /// invoked with the new infcx, along with the instantiated value
520 /// `V` and a substitution `S`. This substitution `S` maps from
521 /// the bound values in `C` to their instantiated values in `V`
522 /// (in other words, `S(C) = V`).
523 pub fn enter_with_canonical<T, R>(
526 canonical: &Canonical<'tcx, T>,
527 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
530 T: TypeFoldable<'tcx>,
534 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
535 f(infcx, value, subst)
539 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
540 let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
541 let in_progress_tables = fresh_tables.as_ref();
542 global_tcx.enter_local(|tcx| {
546 projection_cache: Default::default(),
547 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
548 const_unification_table: RefCell::new(ut::UnificationTable::new()),
549 int_unification_table: RefCell::new(ut::UnificationTable::new()),
550 float_unification_table: RefCell::new(ut::UnificationTable::new()),
551 region_constraints: RefCell::new(Some(RegionConstraintCollector::new())),
552 lexical_region_resolutions: RefCell::new(None),
553 selection_cache: Default::default(),
554 evaluation_cache: Default::default(),
555 reported_trait_errors: Default::default(),
556 reported_closure_mismatch: Default::default(),
557 tainted_by_errors_flag: Cell::new(false),
558 err_count_on_creation: tcx.sess.err_count(),
559 in_snapshot: Cell::new(false),
560 skip_leak_check: Cell::new(false),
561 region_obligations: RefCell::new(vec![]),
562 universe: Cell::new(ty::UniverseIndex::ROOT),
568 impl<'tcx, T> InferOk<'tcx, T> {
569 pub fn unit(self) -> InferOk<'tcx, ()> {
570 InferOk { value: (), obligations: self.obligations }
573 /// Extracts `value`, registering any obligations into `fulfill_cx`.
574 pub fn into_value_registering_obligations(
576 infcx: &InferCtxt<'_, 'tcx>,
577 fulfill_cx: &mut dyn TraitEngine<'tcx>,
579 let InferOk { value, obligations } = self;
580 for obligation in obligations {
581 fulfill_cx.register_predicate_obligation(infcx, obligation);
587 impl<'tcx> InferOk<'tcx, ()> {
588 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
593 #[must_use = "once you start a snapshot, you should always consume it"]
594 pub struct CombinedSnapshot<'a, 'tcx> {
595 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
596 type_snapshot: type_variable::Snapshot<'tcx>,
597 const_snapshot: ut::Snapshot<ut::InPlace<ty::ConstVid<'tcx>>>,
598 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
599 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
600 region_constraints_snapshot: RegionSnapshot,
601 region_obligations_snapshot: usize,
602 universe: ty::UniverseIndex,
603 was_in_snapshot: bool,
604 was_skip_leak_check: bool,
605 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
608 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
609 pub fn is_in_snapshot(&self) -> bool {
610 self.in_snapshot.get()
613 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
614 t.fold_with(&mut self.freshener())
617 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
619 ty::Infer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
624 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
625 freshen::TypeFreshener::new(self)
628 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
629 use crate::ty::error::UnconstrainedNumeric::Neither;
630 use crate::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
632 ty::Infer(ty::IntVar(vid)) => {
633 if self.int_unification_table.borrow_mut().probe_value(vid).is_some() {
639 ty::Infer(ty::FloatVar(vid)) => {
640 if self.float_unification_table.borrow_mut().probe_value(vid).is_some() {
650 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
651 let mut type_variables = self.type_variables.borrow_mut();
652 let mut int_unification_table = self.int_unification_table.borrow_mut();
653 let mut float_unification_table = self.float_unification_table.borrow_mut();
654 // FIXME(const_generics): should there be an equivalent function for const variables?
657 .unsolved_variables()
659 .map(|t| self.tcx.mk_ty_var(t))
661 (0..int_unification_table.len())
662 .map(|i| ty::IntVid { index: i as u32 })
663 .filter(|&vid| int_unification_table.probe_value(vid).is_none())
664 .map(|v| self.tcx.mk_int_var(v)),
667 (0..float_unification_table.len())
668 .map(|i| ty::FloatVid { index: i as u32 })
669 .filter(|&vid| float_unification_table.probe_value(vid).is_none())
670 .map(|v| self.tcx.mk_float_var(v)),
677 trace: TypeTrace<'tcx>,
678 param_env: ty::ParamEnv<'tcx>,
679 ) -> CombineFields<'a, 'tcx> {
685 obligations: PredicateObligations::new(),
689 /// Clear the "currently in a snapshot" flag, invoke the closure,
690 /// then restore the flag to its original value. This flag is a
691 /// debugging measure designed to detect cases where we start a
692 /// snapshot, create type variables, and register obligations
693 /// which may involve those type variables in the fulfillment cx,
694 /// potentially leaving "dangling type variables" behind.
695 /// In such cases, an assertion will fail when attempting to
696 /// register obligations, within a snapshot. Very useful, much
697 /// better than grovelling through megabytes of `RUSTC_LOG` output.
699 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
700 /// sometimes create a "mini-fulfilment-cx" in which we enroll
701 /// obligations. As long as this fulfillment cx is fully drained
702 /// before we return, this is not a problem, as there won't be any
703 /// escaping obligations in the main cx. In those cases, you can
704 /// use this function.
705 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
707 F: FnOnce(&Self) -> R,
709 let flag = self.in_snapshot.get();
710 self.in_snapshot.set(false);
711 let result = func(self);
712 self.in_snapshot.set(flag);
716 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
717 debug!("start_snapshot()");
719 let in_snapshot = self.in_snapshot.get();
720 self.in_snapshot.set(true);
723 projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
724 type_snapshot: self.type_variables.borrow_mut().snapshot(),
725 const_snapshot: self.const_unification_table.borrow_mut().snapshot(),
726 int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
727 float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
728 region_constraints_snapshot: self.borrow_region_constraints().start_snapshot(),
729 region_obligations_snapshot: self.region_obligations.borrow().len(),
730 universe: self.universe(),
731 was_in_snapshot: in_snapshot,
732 was_skip_leak_check: self.skip_leak_check.get(),
733 // Borrow tables "in progress" (i.e., during typeck)
734 // to ban writes from within a snapshot to them.
735 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
739 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
740 debug!("rollback_to(cause={})", cause);
741 let CombinedSnapshot {
742 projection_cache_snapshot,
747 region_constraints_snapshot,
748 region_obligations_snapshot,
755 self.in_snapshot.set(was_in_snapshot);
756 self.universe.set(universe);
757 self.skip_leak_check.set(was_skip_leak_check);
759 self.projection_cache.borrow_mut().rollback_to(projection_cache_snapshot);
760 self.type_variables.borrow_mut().rollback_to(type_snapshot);
761 self.const_unification_table.borrow_mut().rollback_to(const_snapshot);
762 self.int_unification_table.borrow_mut().rollback_to(int_snapshot);
763 self.float_unification_table.borrow_mut().rollback_to(float_snapshot);
764 self.region_obligations.borrow_mut().truncate(region_obligations_snapshot);
765 self.borrow_region_constraints().rollback_to(region_constraints_snapshot);
768 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
769 debug!("commit_from()");
770 let CombinedSnapshot {
771 projection_cache_snapshot,
776 region_constraints_snapshot,
777 region_obligations_snapshot: _,
784 self.in_snapshot.set(was_in_snapshot);
785 self.skip_leak_check.set(was_skip_leak_check);
787 self.projection_cache.borrow_mut().commit(projection_cache_snapshot);
788 self.type_variables.borrow_mut().commit(type_snapshot);
789 self.const_unification_table.borrow_mut().commit(const_snapshot);
790 self.int_unification_table.borrow_mut().commit(int_snapshot);
791 self.float_unification_table.borrow_mut().commit(float_snapshot);
792 self.borrow_region_constraints().commit(region_constraints_snapshot);
795 /// Executes `f` and commit the bindings.
796 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
798 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
800 debug!("commit_unconditionally()");
801 let snapshot = self.start_snapshot();
802 let r = f(&snapshot);
803 self.commit_from(snapshot);
807 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
808 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
810 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
812 debug!("commit_if_ok()");
813 let snapshot = self.start_snapshot();
814 let r = f(&snapshot);
815 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
818 self.commit_from(snapshot);
821 self.rollback_to("commit_if_ok -- error", snapshot);
827 /// Execute `f` then unroll any bindings it creates.
828 pub fn probe<R, F>(&self, f: F) -> R
830 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
833 let snapshot = self.start_snapshot();
834 let r = f(&snapshot);
835 self.rollback_to("probe", snapshot);
839 /// Execute `f` then unroll any bindings it creates.
840 pub fn skip_leak_check<R, F>(&self, f: F) -> R
842 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
845 let snapshot = self.start_snapshot();
846 self.skip_leak_check.set(true);
847 let r = f(&snapshot);
848 self.rollback_to("probe", snapshot);
852 /// Scan the constraints produced since `snapshot` began and returns:
854 /// - `None` -- if none of them involve "region outlives" constraints
855 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
856 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
857 pub fn region_constraints_added_in_snapshot(
859 snapshot: &CombinedSnapshot<'a, 'tcx>,
861 self.borrow_region_constraints()
862 .region_constraints_added_in_snapshot(&snapshot.region_constraints_snapshot)
865 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
866 self.borrow_region_constraints().add_given(sub, sup);
869 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
871 T: at::ToTrace<'tcx>,
873 let origin = &ObligationCause::dummy();
875 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
876 // Ignore obligations, since we are unrolling
877 // everything anyway.
882 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
884 T: at::ToTrace<'tcx>,
886 let origin = &ObligationCause::dummy();
888 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
889 // Ignore obligations, since we are unrolling
890 // everything anyway.
897 origin: SubregionOrigin<'tcx>,
901 debug!("sub_regions({:?} <: {:?})", a, b);
902 self.borrow_region_constraints().make_subregion(origin, a, b);
905 /// Require that the region `r` be equal to one of the regions in
906 /// the set `regions`.
907 pub fn member_constraint(
909 opaque_type_def_id: DefId,
910 definition_span: Span,
912 region: ty::Region<'tcx>,
913 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
915 debug!("member_constraint({:?} <: {:?})", region, in_regions);
916 self.borrow_region_constraints().member_constraint(
925 pub fn subtype_predicate(
927 cause: &ObligationCause<'tcx>,
928 param_env: ty::ParamEnv<'tcx>,
929 predicate: &ty::PolySubtypePredicate<'tcx>,
930 ) -> Option<InferResult<'tcx, ()>> {
931 // Subtle: it's ok to skip the binder here and resolve because
932 // `shallow_resolve` just ignores anything that is not a type
933 // variable, and because type variable's can't (at present, at
934 // least) capture any of the things bound by this binder.
936 // NOTE(nmatsakis): really, there is no *particular* reason to do this
937 // `shallow_resolve` here except as a micro-optimization.
938 // Naturally I could not resist.
939 let two_unbound_type_vars = {
940 let a = self.shallow_resolve(predicate.skip_binder().a);
941 let b = self.shallow_resolve(predicate.skip_binder().b);
942 a.is_ty_var() && b.is_ty_var()
945 if two_unbound_type_vars {
946 // Two unbound type variables? Can't make progress.
950 Some(self.commit_if_ok(|snapshot| {
951 let (ty::SubtypePredicate { a_is_expected, a, b }, placeholder_map) =
952 self.replace_bound_vars_with_placeholders(predicate);
954 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
956 self.leak_check(false, &placeholder_map, snapshot)?;
962 pub fn region_outlives_predicate(
964 cause: &traits::ObligationCause<'tcx>,
965 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
966 ) -> UnitResult<'tcx> {
967 self.commit_if_ok(|snapshot| {
968 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
969 self.replace_bound_vars_with_placeholders(predicate);
970 let origin = SubregionOrigin::from_obligation_cause(cause, || {
971 RelateRegionParamBound(cause.span)
973 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
974 self.leak_check(false, &placeholder_map, snapshot)?;
979 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
980 self.type_variables.borrow_mut().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.type_variables.borrow_mut().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> {
1015 .const_unification_table
1017 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1018 self.tcx.mk_const_var(vid, ty)
1021 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1022 self.const_unification_table.borrow_mut().new_key(ConstVarValue {
1024 val: ConstVariableValue::Unknown { universe: self.universe() },
1028 fn next_int_var_id(&self) -> IntVid {
1029 self.int_unification_table.borrow_mut().new_key(None)
1032 pub fn next_int_var(&self) -> Ty<'tcx> {
1033 self.tcx.mk_int_var(self.next_int_var_id())
1036 fn next_float_var_id(&self) -> FloatVid {
1037 self.float_unification_table.borrow_mut().new_key(None)
1040 pub fn next_float_var(&self) -> Ty<'tcx> {
1041 self.tcx.mk_float_var(self.next_float_var_id())
1044 /// Creates a fresh region variable with the next available index.
1045 /// The variable will be created in the maximum universe created
1046 /// thus far, allowing it to name any region created thus far.
1047 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1048 self.next_region_var_in_universe(origin, self.universe())
1051 /// Creates a fresh region variable with the next available index
1052 /// in the given universe; typically, you can use
1053 /// `next_region_var` and just use the maximal universe.
1054 pub fn next_region_var_in_universe(
1056 origin: RegionVariableOrigin,
1057 universe: ty::UniverseIndex,
1058 ) -> ty::Region<'tcx> {
1059 let region_var = self.borrow_region_constraints().new_region_var(universe, origin);
1060 self.tcx.mk_region(ty::ReVar(region_var))
1063 /// Return the universe that the region `r` was created in. For
1064 /// most regions (e.g., `'static`, named regions from the user,
1065 /// etc) this is the root universe U0. For inference variables or
1066 /// placeholders, however, it will return the universe which which
1067 /// they are associated.
1068 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1069 self.borrow_region_constraints().universe(r)
1072 /// Number of region variables created so far.
1073 pub fn num_region_vars(&self) -> usize {
1074 self.borrow_region_constraints().num_region_vars()
1077 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1078 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1079 self.next_region_var(RegionVariableOrigin::NLL(origin))
1082 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1083 pub fn next_nll_region_var_in_universe(
1085 origin: NLLRegionVariableOrigin,
1086 universe: ty::UniverseIndex,
1087 ) -> ty::Region<'tcx> {
1088 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1091 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1093 GenericParamDefKind::Lifetime => {
1094 // Create a region inference variable for the given
1095 // region parameter definition.
1096 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1098 GenericParamDefKind::Type { .. } => {
1099 // Create a type inference variable for the given
1100 // type parameter definition. The substitutions are
1101 // for actual parameters that may be referred to by
1102 // the default of this type parameter, if it exists.
1103 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1104 // used in a path such as `Foo::<T, U>::new()` will
1105 // use an inference variable for `C` with `[T, U]`
1106 // as the substitutions for the default, `(T, U)`.
1107 let ty_var_id = self.type_variables.borrow_mut().new_var(
1110 TypeVariableOrigin {
1111 kind: TypeVariableOriginKind::TypeParameterDefinition(
1119 self.tcx.mk_ty_var(ty_var_id).into()
1121 GenericParamDefKind::Const { .. } => {
1122 let origin = ConstVariableOrigin {
1123 kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1127 self.const_unification_table.borrow_mut().new_key(ConstVarValue {
1129 val: ConstVariableValue::Unknown { universe: self.universe() },
1131 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1136 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1137 /// type/region parameter to a fresh inference variable.
1138 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1139 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1142 /// Returns `true` if errors have been reported since this infcx was
1143 /// created. This is sometimes used as a heuristic to skip
1144 /// reporting errors that often occur as a result of earlier
1145 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1146 /// inference variables, regionck errors).
1147 pub fn is_tainted_by_errors(&self) -> bool {
1149 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1150 tainted_by_errors_flag={})",
1151 self.tcx.sess.err_count(),
1152 self.err_count_on_creation,
1153 self.tainted_by_errors_flag.get()
1156 if self.tcx.sess.err_count() > self.err_count_on_creation {
1157 return true; // errors reported since this infcx was made
1159 self.tainted_by_errors_flag.get()
1162 /// Set the "tainted by errors" flag to true. We call this when we
1163 /// observe an error from a prior pass.
1164 pub fn set_tainted_by_errors(&self) {
1165 debug!("set_tainted_by_errors()");
1166 self.tainted_by_errors_flag.set(true)
1169 /// Process the region constraints and report any errors that
1170 /// result. After this, no more unification operations should be
1171 /// done -- or the compiler will panic -- but it is legal to use
1172 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1173 pub fn resolve_regions_and_report_errors(
1175 region_context: DefId,
1176 region_map: ®ion::ScopeTree,
1177 outlives_env: &OutlivesEnvironment<'tcx>,
1178 suppress: SuppressRegionErrors,
1181 self.is_tainted_by_errors() || self.region_obligations.borrow().is_empty(),
1182 "region_obligations not empty: {:#?}",
1183 self.region_obligations.borrow()
1186 let region_rels = &RegionRelations::new(
1190 outlives_env.free_region_map(),
1192 let (var_infos, data) = self
1196 .expect("regions already resolved")
1197 .into_infos_and_data();
1198 let (lexical_region_resolutions, errors) =
1199 lexical_region_resolve::resolve(region_rels, var_infos, data);
1201 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1202 assert!(old_value.is_none());
1204 if !self.is_tainted_by_errors() {
1205 // As a heuristic, just skip reporting region errors
1206 // altogether if other errors have been reported while
1207 // this infcx was in use. This is totally hokey but
1208 // otherwise we have a hard time separating legit region
1209 // errors from silly ones.
1210 self.report_region_errors(region_map, &errors, suppress);
1214 /// Obtains (and clears) the current set of region
1215 /// constraints. The inference context is still usable: further
1216 /// unifications will simply add new constraints.
1218 /// This method is not meant to be used with normal lexical region
1219 /// resolution. Rather, it is used in the NLL mode as a kind of
1220 /// interim hack: basically we run normal type-check and generate
1221 /// region constraints as normal, but then we take them and
1222 /// translate them into the form that the NLL solver
1223 /// understands. See the NLL module for mode details.
1224 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1226 self.region_obligations.borrow().is_empty(),
1227 "region_obligations not empty: {:#?}",
1228 self.region_obligations.borrow()
1231 self.borrow_region_constraints().take_and_reset_data()
1234 /// Gives temporary access to the region constraint data.
1235 #[allow(non_camel_case_types)] // bug with impl trait
1236 pub fn with_region_constraints<R>(
1238 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1240 let region_constraints = self.borrow_region_constraints();
1241 op(region_constraints.data())
1244 /// Takes ownership of the list of variable regions. This implies
1245 /// that all the region constraints have already been taken, and
1246 /// hence that `resolve_regions_and_report_errors` can never be
1247 /// called. This is used only during NLL processing to "hand off" ownership
1248 /// of the set of region variables into the NLL region context.
1249 pub fn take_region_var_origins(&self) -> VarInfos {
1250 let (var_infos, data) = self
1254 .expect("regions already resolved")
1255 .into_infos_and_data();
1256 assert!(data.is_empty());
1260 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1261 self.resolve_vars_if_possible(&t).to_string()
1264 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1265 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1266 format!("({})", tstrs.join(", "))
1269 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1270 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1273 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1274 /// universe index of `TyVar(vid)`.
1275 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1276 use self::type_variable::TypeVariableValue;
1278 match self.type_variables.borrow_mut().probe(vid) {
1279 TypeVariableValue::Known { value } => Ok(value),
1280 TypeVariableValue::Unknown { universe } => Err(universe),
1284 /// Resolve any type variables found in `value` -- but only one
1285 /// level. So, if the variable `?X` is bound to some type
1286 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1287 /// itself be bound to a type).
1289 /// Useful when you only need to inspect the outermost level of
1290 /// the type and don't care about nested types (or perhaps you
1291 /// will be resolving them as well, e.g. in a loop).
1292 pub fn shallow_resolve<T>(&self, value: T) -> T
1294 T: TypeFoldable<'tcx>,
1296 let mut r = ShallowResolver::new(self);
1297 value.fold_with(&mut r)
1300 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1301 self.type_variables.borrow_mut().root_var(var)
1304 /// Where possible, replaces type/const variables in
1305 /// `value` with their final value. Note that region variables
1306 /// are unaffected. If a type/const variable has not been unified, it
1307 /// is left as is. This is an idempotent operation that does
1308 /// not affect inference state in any way and so you can do it
1310 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1312 T: TypeFoldable<'tcx>,
1314 if !value.needs_infer() {
1315 return value.clone(); // Avoid duplicated subst-folding.
1317 let mut r = resolve::OpportunisticVarResolver::new(self);
1318 value.fold_with(&mut r)
1321 /// Returns the first unresolved variable contained in `T`. In the
1322 /// process of visiting `T`, this will resolve (where possible)
1323 /// type variables in `T`, but it never constructs the final,
1324 /// resolved type, so it's more efficient than
1325 /// `resolve_vars_if_possible()`.
1326 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1328 T: TypeFoldable<'tcx>,
1330 let mut r = resolve::UnresolvedTypeFinder::new(self);
1331 value.visit_with(&mut r);
1335 pub fn probe_const_var(
1337 vid: ty::ConstVid<'tcx>,
1338 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1339 match self.const_unification_table.borrow_mut().probe_value(vid).val {
1340 ConstVariableValue::Known { value } => Ok(value),
1341 ConstVariableValue::Unknown { universe } => Err(universe),
1345 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1347 * Attempts to resolve all type/region/const variables in
1348 * `value`. Region inference must have been run already (e.g.,
1349 * by calling `resolve_regions_and_report_errors`). If some
1350 * variable was never unified, an `Err` results.
1352 * This method is idempotent, but it not typically not invoked
1353 * except during the writeback phase.
1356 resolve::fully_resolve(self, value)
1359 // [Note-Type-error-reporting]
1360 // An invariant is that anytime the expected or actual type is Error (the special
1361 // error type, meaning that an error occurred when typechecking this expression),
1362 // this is a derived error. The error cascaded from another error (that was already
1363 // reported), so it's not useful to display it to the user.
1364 // The following methods implement this logic.
1365 // They check if either the actual or expected type is Error, and don't print the error
1366 // in this case. The typechecker should only ever report type errors involving mismatched
1367 // types using one of these methods, and should not call span_err directly for such
1370 pub fn type_error_struct_with_diag<M>(
1374 actual_ty: Ty<'tcx>,
1375 ) -> DiagnosticBuilder<'tcx>
1377 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1379 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1380 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1382 // Don't report an error if actual type is `Error`.
1383 if actual_ty.references_error() {
1384 return self.tcx.sess.diagnostic().struct_dummy();
1387 mk_diag(self.ty_to_string(actual_ty))
1390 pub fn report_mismatched_types(
1392 cause: &ObligationCause<'tcx>,
1395 err: TypeError<'tcx>,
1396 ) -> DiagnosticBuilder<'tcx> {
1397 let trace = TypeTrace::types(cause, true, expected, actual);
1398 self.report_and_explain_type_error(trace, &err)
1401 pub fn replace_bound_vars_with_fresh_vars<T>(
1404 lbrct: LateBoundRegionConversionTime,
1405 value: &ty::Binder<T>,
1406 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1408 T: TypeFoldable<'tcx>,
1410 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1412 self.next_ty_var(TypeVariableOrigin {
1413 kind: TypeVariableOriginKind::MiscVariable,
1417 let fld_c = |_, ty| {
1418 self.next_const_var(
1420 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1423 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1426 /// See the [`region_constraints::verify_generic_bound`] method.
1427 pub fn verify_generic_bound(
1429 origin: SubregionOrigin<'tcx>,
1430 kind: GenericKind<'tcx>,
1431 a: ty::Region<'tcx>,
1432 bound: VerifyBound<'tcx>,
1434 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1436 self.borrow_region_constraints().verify_generic_bound(origin, kind, a, bound);
1439 pub fn type_is_copy_modulo_regions(
1441 param_env: ty::ParamEnv<'tcx>,
1445 let ty = self.resolve_vars_if_possible(&ty);
1447 // Even if the type may have no inference variables, during
1448 // type-checking closure types are in local tables only.
1449 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1450 if !(param_env, ty).has_local_value() {
1451 return ty.is_copy_modulo_regions(self.tcx, param_env, span);
1455 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem, None);
1457 // This can get called from typeck (by euv), and `moves_by_default`
1458 // rightly refuses to work with inference variables, but
1459 // moves_by_default has a cache, which we want to use in other
1461 traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id, span)
1464 /// Obtains the latest type of the given closure; this may be a
1465 /// closure in the current function, in which case its
1466 /// `ClosureKind` may not yet be known.
1467 pub fn closure_kind(
1469 closure_def_id: DefId,
1470 closure_substs: SubstsRef<'tcx>,
1471 ) -> Option<ty::ClosureKind> {
1472 let closure_kind_ty = closure_substs.as_closure().kind_ty(closure_def_id, self.tcx);
1473 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1474 closure_kind_ty.to_opt_closure_kind()
1477 /// Obtains the signature of a closure. For closures, unlike
1478 /// `tcx.fn_sig(def_id)`, this method will work during the
1479 /// type-checking of the enclosing function and return the closure
1480 /// signature in its partially inferred state.
1481 pub fn closure_sig(&self, def_id: DefId, substs: SubstsRef<'tcx>) -> ty::PolyFnSig<'tcx> {
1482 let closure_sig_ty = substs.as_closure().sig_ty(def_id, self.tcx);
1483 let closure_sig_ty = self.shallow_resolve(closure_sig_ty);
1484 closure_sig_ty.fn_sig(self.tcx)
1487 /// Normalizes associated types in `value`, potentially returning
1488 /// new obligations that must further be processed.
1489 pub fn partially_normalize_associated_types_in<T>(
1492 body_id: hir::HirId,
1493 param_env: ty::ParamEnv<'tcx>,
1495 ) -> InferOk<'tcx, T>
1497 T: TypeFoldable<'tcx>,
1499 debug!("partially_normalize_associated_types_in(value={:?})", value);
1500 let mut selcx = traits::SelectionContext::new(self);
1501 let cause = ObligationCause::misc(span, body_id);
1502 let traits::Normalized { value, obligations } =
1503 traits::normalize(&mut selcx, param_env, cause, value);
1505 "partially_normalize_associated_types_in: result={:?} predicates={:?}",
1508 InferOk { value, obligations }
1511 pub fn borrow_region_constraints(&self) -> RefMut<'_, RegionConstraintCollector<'tcx>> {
1512 RefMut::map(self.region_constraints.borrow_mut(), |c| {
1513 c.as_mut().expect("region constraints already solved")
1517 /// Clears the selection, evaluation, and projection caches. This is useful when
1518 /// repeatedly attempting to select an `Obligation` while changing only
1519 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1520 pub fn clear_caches(&self) {
1521 self.selection_cache.clear();
1522 self.evaluation_cache.clear();
1523 self.projection_cache.borrow_mut().clear();
1526 fn universe(&self) -> ty::UniverseIndex {
1530 /// Creates and return a fresh universe that extends all previous
1531 /// universes. Updates `self.universe` to that new universe.
1532 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1533 let u = self.universe.get().next_universe();
1534 self.universe.set(u);
1539 pub struct ShallowResolver<'a, 'tcx> {
1540 infcx: &'a InferCtxt<'a, 'tcx>,
1543 impl<'a, 'tcx> ShallowResolver<'a, 'tcx> {
1545 pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self {
1546 ShallowResolver { infcx }
1549 /// If `typ` is a type variable of some kind, resolve it one level
1550 /// (but do not resolve types found in the result). If `typ` is
1551 /// not a type variable, just return it unmodified.
1552 pub fn shallow_resolve(&mut self, typ: Ty<'tcx>) -> Ty<'tcx> {
1554 ty::Infer(ty::TyVar(v)) => {
1555 // Not entirely obvious: if `typ` is a type variable,
1556 // it can be resolved to an int/float variable, which
1557 // can then be recursively resolved, hence the
1558 // recursion. Note though that we prevent type
1559 // variables from unifying to other type variables
1560 // directly (though they may be embedded
1561 // structurally), and we prevent cycles in any case,
1562 // so this recursion should always be of very limited
1569 .map(|t| self.fold_ty(t))
1573 ty::Infer(ty::IntVar(v)) => self
1575 .int_unification_table
1578 .map(|v| v.to_type(self.infcx.tcx))
1581 ty::Infer(ty::FloatVar(v)) => self
1583 .float_unification_table
1586 .map(|v| v.to_type(self.infcx.tcx))
1593 // `resolver.shallow_resolve_changed(ty)` is equivalent to
1594 // `resolver.shallow_resolve(ty) != ty`, but more efficient. It's always
1595 // inlined, despite being large, because it has only two call sites that
1596 // are extremely hot.
1598 pub fn shallow_resolve_changed(&self, infer: ty::InferTy) -> bool {
1601 use self::type_variable::TypeVariableValue;
1603 // If `inlined_probe` returns a `Known` value its `kind` never
1605 match self.infcx.type_variables.borrow_mut().inlined_probe(v) {
1606 TypeVariableValue::Unknown { .. } => false,
1607 TypeVariableValue::Known { .. } => true,
1612 // If inlined_probe_value returns a value it's always a
1613 // `ty::Int(_)` or `ty::UInt(_)`, which nevers matches a
1615 self.infcx.int_unification_table.borrow_mut().inlined_probe_value(v).is_some()
1618 ty::FloatVar(v) => {
1619 // If inlined_probe_value returns a value it's always a
1620 // `ty::Float(_)`, which nevers matches a `ty::Infer(_)`.
1622 // Not `inlined_probe_value(v)` because this call site is colder.
1623 self.infcx.float_unification_table.borrow_mut().probe_value(v).is_some()
1626 _ => unreachable!(),
1631 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1632 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1636 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1637 self.shallow_resolve(ty)
1640 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1641 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1643 .const_unification_table
1655 impl<'tcx> TypeTrace<'tcx> {
1656 pub fn span(&self) -> Span {
1661 cause: &ObligationCause<'tcx>,
1662 a_is_expected: bool,
1665 ) -> TypeTrace<'tcx> {
1666 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1669 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1671 cause: ObligationCause::dummy(),
1672 values: Types(ExpectedFound { expected: tcx.types.err, found: tcx.types.err }),
1677 impl<'tcx> SubregionOrigin<'tcx> {
1678 pub fn span(&self) -> Span {
1680 Subtype(ref a) => a.span(),
1681 InfStackClosure(a) => a,
1682 InvokeClosure(a) => a,
1683 DerefPointer(a) => a,
1684 ClosureCapture(a, _) => a,
1686 RelateObjectBound(a) => a,
1687 RelateParamBound(a, _) => a,
1688 RelateRegionParamBound(a) => a,
1689 RelateDefaultParamBound(a, _) => a,
1691 ReborrowUpvar(a, _) => a,
1692 DataBorrowed(_, a) => a,
1693 ReferenceOutlivesReferent(_, a) => a,
1694 ParameterInScope(_, a) => a,
1695 ExprTypeIsNotInScope(_, a) => a,
1696 BindingTypeIsNotValidAtDecl(a) => a,
1703 SafeDestructor(a) => a,
1704 CompareImplMethodObligation { span, .. } => span,
1708 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1710 F: FnOnce() -> Self,
1713 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1714 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1717 traits::ObligationCauseCode::CompareImplMethodObligation {
1721 } => SubregionOrigin::CompareImplMethodObligation {
1733 impl RegionVariableOrigin {
1734 pub fn span(&self) -> Span {
1736 MiscVariable(a) => a,
1737 PatternRegion(a) => a,
1738 AddrOfRegion(a) => a,
1741 EarlyBoundRegion(a, ..) => a,
1742 LateBoundRegion(a, ..) => a,
1743 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1744 UpvarRegion(_, a) => a,
1745 NLL(..) => bug!("NLL variable used with `span`"),
1750 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1751 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1754 "RegionObligation(sub_region={:?}, sup_type={:?})",
1755 self.sub_region, self.sup_type