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;
68 pub struct InferOk<'tcx, T> {
70 pub obligations: PredicateObligations<'tcx>,
72 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
74 pub type Bound<T> = Option<T>;
75 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
76 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
78 /// A flag that is used to suppress region errors. This is normally
79 /// false, but sometimes -- when we are doing region checks that the
80 /// NLL borrow checker will also do -- it might be set to true.
81 #[derive(Copy, Clone, Default, Debug)]
82 pub struct SuppressRegionErrors {
86 impl SuppressRegionErrors {
87 pub fn suppressed(self) -> bool {
91 /// Indicates that the MIR borrowck will repeat these region
92 /// checks, so we should ignore errors if NLL is (unconditionally)
94 pub fn when_nll_is_enabled(tcx: TyCtxt<'_>) -> Self {
95 // FIXME(Centril): Once we actually remove `::Migrate` also make
96 // this always `true` and then proceed to eliminate the dead code.
97 match tcx.borrowck_mode() {
98 // If we're on Migrate mode, report AST region errors
99 BorrowckMode::Migrate => SuppressRegionErrors { suppressed: false },
101 // If we're on MIR, don't report AST region errors as they should be reported by NLL
102 BorrowckMode::Mir => SuppressRegionErrors { suppressed: true },
107 pub struct InferCtxt<'a, 'tcx> {
108 pub tcx: TyCtxt<'tcx>,
110 /// During type-checking/inference of a body, `in_progress_tables`
111 /// contains a reference to the tables being built up, which are
112 /// used for reading closure kinds/signatures as they are inferred,
113 /// and for error reporting logic to read arbitrary node types.
114 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
116 /// Cache for projections. This cache is snapshotted along with the
119 /// Public so that `traits::project` can use it.
120 pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
122 /// We instantiate `UnificationTable` with `bounds<Ty>` because the
123 /// types that might instantiate a general type variable have an
124 /// order, represented by its upper and lower bounds.
125 pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
127 /// Map from const parameter variable to the kind of const it represents.
128 const_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::ConstVid<'tcx>>>>,
130 /// Map from integral variable to the kind of integer it represents.
131 int_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::IntVid>>>,
133 /// Map from floating variable to the kind of float it represents
134 float_unification_table: RefCell<ut::UnificationTable<ut::InPlace<ty::FloatVid>>>,
136 /// Tracks the set of region variables and the constraints between
137 /// them. This is initially `Some(_)` but when
138 /// `resolve_regions_and_report_errors` is invoked, this gets set
139 /// to `None` -- further attempts to perform unification etc may
140 /// fail if new region constraints would've been added.
141 region_constraints: RefCell<Option<RegionConstraintCollector<'tcx>>>,
143 /// Once region inference is done, the values for each variable.
144 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
146 /// Caches the results of trait selection. This cache is used
147 /// for things that have to do with the parameters in scope.
148 pub selection_cache: traits::SelectionCache<'tcx>,
150 /// Caches the results of trait evaluation.
151 pub evaluation_cache: traits::EvaluationCache<'tcx>,
153 /// the set of predicates on which errors have been reported, to
154 /// avoid reporting the same error twice.
155 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
157 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
159 /// When an error occurs, we want to avoid reporting "derived"
160 /// errors that are due to this original failure. Normally, we
161 /// handle this with the `err_count_on_creation` count, which
162 /// basically just tracks how many errors were reported when we
163 /// started type-checking a fn and checks to see if any new errors
164 /// have been reported since then. Not great, but it works.
166 /// However, when errors originated in other passes -- notably
167 /// resolve -- this heuristic breaks down. Therefore, we have this
168 /// auxiliary flag that one can set whenever one creates a
169 /// type-error that is due to an error in a prior pass.
171 /// Don't read this flag directly, call `is_tainted_by_errors()`
172 /// and `set_tainted_by_errors()`.
173 tainted_by_errors_flag: Cell<bool>,
175 /// Track how many errors were reported when this infcx is created.
176 /// If the number of errors increases, that's also a sign (line
177 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
178 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
179 err_count_on_creation: usize,
181 /// This flag is true while there is an active snapshot.
182 in_snapshot: Cell<bool>,
184 /// A set of constraints that regionck must validate. Each
185 /// constraint has the form `T:'a`, meaning "some type `T` must
186 /// outlive the lifetime 'a". These constraints derive from
187 /// instantiated type parameters. So if you had a struct defined
190 /// struct Foo<T:'static> { ... }
192 /// then in some expression `let x = Foo { ... }` it will
193 /// instantiate the type parameter `T` with a fresh type `$0`. At
194 /// the same time, it will record a region obligation of
195 /// `$0:'static`. This will get checked later by regionck. (We
196 /// can't generally check these things right away because we have
197 /// to wait until types are resolved.)
199 /// These are stored in a map keyed to the id of the innermost
200 /// enclosing fn body / static initializer expression. This is
201 /// because the location where the obligation was incurred can be
202 /// relevant with respect to which sublifetime assumptions are in
203 /// place. The reason that we store under the fn-id, and not
204 /// something more fine-grained, is so that it is easier for
205 /// regionck to be sure that it has found *all* the region
206 /// obligations (otherwise, it's easy to fail to walk to a
207 /// particular node-id).
209 /// Before running `resolve_regions_and_report_errors`, the creator
210 /// of the inference context is expected to invoke
211 /// `process_region_obligations` (defined in `self::region_obligations`)
212 /// for each body-id in this map, which will process the
213 /// obligations within. This is expected to be done 'late enough'
214 /// that all type inference variables have been bound and so forth.
215 pub region_obligations: RefCell<Vec<(hir::HirId, RegionObligation<'tcx>)>>,
217 /// What is the innermost universe we have created? Starts out as
218 /// `UniverseIndex::root()` but grows from there as we enter
219 /// universal quantifiers.
221 /// N.B., at present, we exclude the universal quantifiers on the
222 /// item we are type-checking, and just consider those names as
223 /// part of the root universe. So this would only get incremented
224 /// when we enter into a higher-ranked (`for<..>`) type or trait
226 universe: Cell<ty::UniverseIndex>,
229 /// A map returned by `replace_bound_vars_with_placeholders()`
230 /// indicating the placeholder region that each late-bound region was
232 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
234 /// See the `error_reporting` module for more details.
235 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
236 pub enum ValuePairs<'tcx> {
237 Types(ExpectedFound<Ty<'tcx>>),
238 Regions(ExpectedFound<ty::Region<'tcx>>),
239 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
240 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
241 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
244 /// The trace designates the path through inference that we took to
245 /// encounter an error or subtyping constraint.
247 /// See the `error_reporting` module for more details.
249 pub struct TypeTrace<'tcx> {
250 cause: ObligationCause<'tcx>,
251 values: ValuePairs<'tcx>,
254 /// The origin of a `r1 <= r2` constraint.
256 /// See `error_reporting` module for more details
257 #[derive(Clone, Debug)]
258 pub enum SubregionOrigin<'tcx> {
259 /// Arose from a subtyping relation
260 Subtype(Box<TypeTrace<'tcx>>),
262 /// Stack-allocated closures cannot outlive innermost loop
263 /// or function so as to ensure we only require finite stack
264 InfStackClosure(Span),
266 /// Invocation of closure must be within its lifetime
269 /// Dereference of reference must be within its lifetime
272 /// Closure bound must not outlive captured variables
273 ClosureCapture(Span, hir::HirId),
275 /// Index into slice must be within its lifetime
278 /// When casting `&'a T` to an `&'b Trait` object,
279 /// relating `'a` to `'b`
280 RelateObjectBound(Span),
282 /// Some type parameter was instantiated with the given type,
283 /// and that type must outlive some region.
284 RelateParamBound(Span, Ty<'tcx>),
286 /// The given region parameter was instantiated with a region
287 /// that must outlive some other region.
288 RelateRegionParamBound(Span),
290 /// A bound placed on type parameters that states that must outlive
291 /// the moment of their instantiation.
292 RelateDefaultParamBound(Span, Ty<'tcx>),
294 /// Creating a pointer `b` to contents of another reference
297 /// Creating a pointer `b` to contents of an upvar
298 ReborrowUpvar(Span, ty::UpvarId),
300 /// Data with type `Ty<'tcx>` was borrowed
301 DataBorrowed(Ty<'tcx>, Span),
303 /// (&'a &'b T) where a >= b
304 ReferenceOutlivesReferent(Ty<'tcx>, Span),
306 /// Type or region parameters must be in scope.
307 ParameterInScope(ParameterOrigin, Span),
309 /// The type T of an expression E must outlive the lifetime for E.
310 ExprTypeIsNotInScope(Ty<'tcx>, Span),
312 /// A `ref b` whose region does not enclose the decl site
313 BindingTypeIsNotValidAtDecl(Span),
315 /// Regions appearing in a method receiver must outlive method call
318 /// Regions appearing in a function argument must outlive func call
321 /// Region in return type of invoked fn must enclose call
324 /// Operands must be in scope
327 /// Region resulting from a `&` expr must enclose the `&` expr
330 /// An auto-borrow that does not enclose the expr where it occurs
333 /// Region constraint arriving from destructor safety
334 SafeDestructor(Span),
336 /// Comparing the signature and requirements of an impl method against
337 /// the containing trait.
338 CompareImplMethodObligation {
340 item_name: ast::Name,
341 impl_item_def_id: DefId,
342 trait_item_def_id: DefId,
346 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
347 #[cfg(target_arch = "x86_64")]
348 static_assert_size!(SubregionOrigin<'_>, 32);
350 /// Places that type/region parameters can appear.
351 #[derive(Clone, Copy, Debug)]
352 pub enum ParameterOrigin {
354 MethodCall, // foo.bar() <-- parameters on impl providing bar()
355 OverloadedOperator, // a + b when overloaded
356 OverloadedDeref, // *a when overloaded
359 /// Times when we replace late-bound regions with variables:
360 #[derive(Clone, Copy, Debug)]
361 pub enum LateBoundRegionConversionTime {
362 /// when a fn is called
365 /// when two higher-ranked types are compared
368 /// when projecting an associated type
369 AssocTypeProjection(DefId),
372 /// Reasons to create a region inference variable
374 /// See `error_reporting` module for more details
375 #[derive(Copy, Clone, Debug)]
376 pub enum RegionVariableOrigin {
377 /// Region variables created for ill-categorized reasons,
378 /// mostly indicates places in need of refactoring
381 /// Regions created by a `&P` or `[...]` pattern
384 /// Regions created by `&` operator
387 /// Regions created as part of an autoref of a method receiver
390 /// Regions created as part of an automatic coercion
393 /// Region variables created as the values for early-bound regions
394 EarlyBoundRegion(Span, Symbol),
396 /// Region variables created for bound regions
397 /// in a function or method that is called
398 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
400 UpvarRegion(ty::UpvarId, Span),
402 BoundRegionInCoherence(ast::Name),
404 /// This origin is used for the inference variables that we create
405 /// during NLL region processing.
406 NLL(NLLRegionVariableOrigin),
409 #[derive(Copy, Clone, Debug)]
410 pub enum NLLRegionVariableOrigin {
411 /// During NLL region processing, we create variables for free
412 /// regions that we encounter in the function signature and
413 /// elsewhere. This origin indices we've got one of those.
416 /// "Universal" instantiation of a higher-ranked region (e.g.,
417 /// from a `for<'a> T` binder). Meant to represent "any region".
418 Placeholder(ty::PlaceholderRegion),
421 /// If this is true, then this variable was created to represent a lifetime
422 /// bound in a `for` binder. For example, it might have been created to
423 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
424 /// Such variables are created when we are trying to figure out if there
425 /// is any valid instantiation of `'a` that could fit into some scenario.
427 /// This is used to inform error reporting: in the case that we are trying to
428 /// determine whether there is any valid instantiation of a `'a` variable that meets
429 /// some constraint C, we want to blame the "source" of that `for` type,
430 /// rather than blaming the source of the constraint C.
435 impl NLLRegionVariableOrigin {
436 pub fn is_universal(self) -> bool {
438 NLLRegionVariableOrigin::FreeRegion => true,
439 NLLRegionVariableOrigin::Placeholder(..) => true,
440 NLLRegionVariableOrigin::Existential { .. } => false,
444 pub fn is_existential(self) -> bool {
449 #[derive(Copy, Clone, Debug)]
450 pub enum FixupError<'tcx> {
451 UnresolvedIntTy(IntVid),
452 UnresolvedFloatTy(FloatVid),
454 UnresolvedConst(ConstVid<'tcx>),
457 /// See the `region_obligations` field for more information.
459 pub struct RegionObligation<'tcx> {
460 pub sub_region: ty::Region<'tcx>,
461 pub sup_type: Ty<'tcx>,
462 pub origin: SubregionOrigin<'tcx>,
465 impl<'tcx> fmt::Display for FixupError<'tcx> {
466 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
467 use self::FixupError::*;
470 UnresolvedIntTy(_) => write!(
472 "cannot determine the type of this integer; \
473 add a suffix to specify the type explicitly"
475 UnresolvedFloatTy(_) => write!(
477 "cannot determine the type of this number; \
478 add a suffix to specify the type explicitly"
480 UnresolvedTy(_) => write!(f, "unconstrained type"),
481 UnresolvedConst(_) => write!(f, "unconstrained const value"),
486 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
487 /// Necessary because we can't write the following bound:
488 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
489 pub struct InferCtxtBuilder<'tcx> {
490 global_tcx: TyCtxt<'tcx>,
491 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
495 pub fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
496 InferCtxtBuilder { global_tcx: self, fresh_tables: None }
500 impl<'tcx> InferCtxtBuilder<'tcx> {
501 /// Used only by `rustc_typeck` during body type-checking/inference,
502 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
503 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
504 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
508 /// Given a canonical value `C` as a starting point, create an
509 /// inference context that contains each of the bound values
510 /// within instantiated as a fresh variable. The `f` closure is
511 /// invoked with the new infcx, along with the instantiated value
512 /// `V` and a substitution `S`. This substitution `S` maps from
513 /// the bound values in `C` to their instantiated values in `V`
514 /// (in other words, `S(C) = V`).
515 pub fn enter_with_canonical<T, R>(
518 canonical: &Canonical<'tcx, T>,
519 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
522 T: TypeFoldable<'tcx>,
526 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
527 f(infcx, value, subst)
531 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
532 let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
533 let in_progress_tables = fresh_tables.as_ref();
534 global_tcx.enter_local(|tcx| {
538 projection_cache: Default::default(),
539 type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
540 const_unification_table: RefCell::new(ut::UnificationTable::new()),
541 int_unification_table: RefCell::new(ut::UnificationTable::new()),
542 float_unification_table: RefCell::new(ut::UnificationTable::new()),
543 region_constraints: RefCell::new(Some(RegionConstraintCollector::new())),
544 lexical_region_resolutions: RefCell::new(None),
545 selection_cache: Default::default(),
546 evaluation_cache: Default::default(),
547 reported_trait_errors: Default::default(),
548 reported_closure_mismatch: Default::default(),
549 tainted_by_errors_flag: Cell::new(false),
550 err_count_on_creation: tcx.sess.err_count(),
551 in_snapshot: Cell::new(false),
552 region_obligations: RefCell::new(vec![]),
553 universe: Cell::new(ty::UniverseIndex::ROOT),
559 impl<T> ExpectedFound<T> {
560 pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
562 ExpectedFound { expected: a, found: b }
564 ExpectedFound { expected: b, found: a }
569 impl<'tcx, T> InferOk<'tcx, T> {
570 pub fn unit(self) -> InferOk<'tcx, ()> {
571 InferOk { value: (), obligations: self.obligations }
574 /// Extracts `value`, registering any obligations into `fulfill_cx`.
575 pub fn into_value_registering_obligations(
577 infcx: &InferCtxt<'_, 'tcx>,
578 fulfill_cx: &mut dyn TraitEngine<'tcx>,
580 let InferOk { value, obligations } = self;
581 for obligation in obligations {
582 fulfill_cx.register_predicate_obligation(infcx, obligation);
588 impl<'tcx> InferOk<'tcx, ()> {
589 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
594 #[must_use = "once you start a snapshot, you should always consume it"]
595 pub struct CombinedSnapshot<'a, 'tcx> {
596 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
597 type_snapshot: type_variable::Snapshot<'tcx>,
598 const_snapshot: ut::Snapshot<ut::InPlace<ty::ConstVid<'tcx>>>,
599 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
600 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
601 region_constraints_snapshot: RegionSnapshot,
602 region_obligations_snapshot: usize,
603 universe: ty::UniverseIndex,
604 was_in_snapshot: 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 // Borrow tables "in progress" (i.e., during typeck)
733 // to ban writes from within a snapshot to them.
734 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
738 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
739 debug!("rollback_to(cause={})", cause);
740 let CombinedSnapshot {
741 projection_cache_snapshot,
746 region_constraints_snapshot,
747 region_obligations_snapshot,
753 self.in_snapshot.set(was_in_snapshot);
754 self.universe.set(universe);
756 self.projection_cache.borrow_mut().rollback_to(projection_cache_snapshot);
757 self.type_variables.borrow_mut().rollback_to(type_snapshot);
758 self.const_unification_table.borrow_mut().rollback_to(const_snapshot);
759 self.int_unification_table.borrow_mut().rollback_to(int_snapshot);
760 self.float_unification_table.borrow_mut().rollback_to(float_snapshot);
761 self.region_obligations.borrow_mut().truncate(region_obligations_snapshot);
762 self.borrow_region_constraints().rollback_to(region_constraints_snapshot);
765 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
766 debug!("commit_from()");
767 let CombinedSnapshot {
768 projection_cache_snapshot,
773 region_constraints_snapshot,
774 region_obligations_snapshot: _,
780 self.in_snapshot.set(was_in_snapshot);
782 self.projection_cache.borrow_mut().commit(projection_cache_snapshot);
783 self.type_variables.borrow_mut().commit(type_snapshot);
784 self.const_unification_table.borrow_mut().commit(const_snapshot);
785 self.int_unification_table.borrow_mut().commit(int_snapshot);
786 self.float_unification_table.borrow_mut().commit(float_snapshot);
787 self.borrow_region_constraints().commit(region_constraints_snapshot);
790 /// Executes `f` and commit the bindings.
791 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
793 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
795 debug!("commit_unconditionally()");
796 let snapshot = self.start_snapshot();
797 let r = f(&snapshot);
798 self.commit_from(snapshot);
802 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
803 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
805 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
807 debug!("commit_if_ok()");
808 let snapshot = self.start_snapshot();
809 let r = f(&snapshot);
810 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
813 self.commit_from(snapshot);
816 self.rollback_to("commit_if_ok -- error", snapshot);
822 /// Execute `f` then unroll any bindings it creates.
823 pub fn probe<R, F>(&self, f: F) -> R
825 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
828 let snapshot = self.start_snapshot();
829 let r = f(&snapshot);
830 self.rollback_to("probe", snapshot);
834 /// Scan the constraints produced since `snapshot` began and returns:
836 /// - `None` -- if none of them involve "region outlives" constraints
837 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
838 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
839 pub fn region_constraints_added_in_snapshot(
841 snapshot: &CombinedSnapshot<'a, 'tcx>,
843 self.borrow_region_constraints()
844 .region_constraints_added_in_snapshot(&snapshot.region_constraints_snapshot)
847 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
848 self.borrow_region_constraints().add_given(sub, sup);
851 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
853 T: at::ToTrace<'tcx>,
855 let origin = &ObligationCause::dummy();
857 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
858 // Ignore obligations, since we are unrolling
859 // everything anyway.
864 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
866 T: at::ToTrace<'tcx>,
868 let origin = &ObligationCause::dummy();
870 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
871 // Ignore obligations, since we are unrolling
872 // everything anyway.
879 origin: SubregionOrigin<'tcx>,
883 debug!("sub_regions({:?} <: {:?})", a, b);
884 self.borrow_region_constraints().make_subregion(origin, a, b);
887 /// Require that the region `r` be equal to one of the regions in
888 /// the set `regions`.
889 pub fn member_constraint(
891 opaque_type_def_id: DefId,
892 definition_span: Span,
894 region: ty::Region<'tcx>,
895 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
897 debug!("member_constraint({:?} <: {:?})", region, in_regions);
898 self.borrow_region_constraints().member_constraint(
907 pub fn subtype_predicate(
909 cause: &ObligationCause<'tcx>,
910 param_env: ty::ParamEnv<'tcx>,
911 predicate: &ty::PolySubtypePredicate<'tcx>,
912 ) -> Option<InferResult<'tcx, ()>> {
913 // Subtle: it's ok to skip the binder here and resolve because
914 // `shallow_resolve` just ignores anything that is not a type
915 // variable, and because type variable's can't (at present, at
916 // least) capture any of the things bound by this binder.
918 // NOTE(nmatsakis): really, there is no *particular* reason to do this
919 // `shallow_resolve` here except as a micro-optimization.
920 // Naturally I could not resist.
921 let two_unbound_type_vars = {
922 let a = self.shallow_resolve(predicate.skip_binder().a);
923 let b = self.shallow_resolve(predicate.skip_binder().b);
924 a.is_ty_var() && b.is_ty_var()
927 if two_unbound_type_vars {
928 // Two unbound type variables? Can't make progress.
932 Some(self.commit_if_ok(|snapshot| {
933 let (ty::SubtypePredicate { a_is_expected, a, b }, placeholder_map) =
934 self.replace_bound_vars_with_placeholders(predicate);
936 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
938 self.leak_check(false, &placeholder_map, snapshot)?;
944 pub fn region_outlives_predicate(
946 cause: &traits::ObligationCause<'tcx>,
947 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
948 ) -> UnitResult<'tcx> {
949 self.commit_if_ok(|snapshot| {
950 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
951 self.replace_bound_vars_with_placeholders(predicate);
952 let origin = SubregionOrigin::from_obligation_cause(cause, || {
953 RelateRegionParamBound(cause.span)
955 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
956 self.leak_check(false, &placeholder_map, snapshot)?;
961 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
962 self.type_variables.borrow_mut().new_var(self.universe(), diverging, origin)
965 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
966 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
969 pub fn next_ty_var_in_universe(
971 origin: TypeVariableOrigin,
972 universe: ty::UniverseIndex,
974 let vid = self.type_variables.borrow_mut().new_var(universe, false, origin);
975 self.tcx.mk_ty_var(vid)
978 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
979 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
982 pub fn next_const_var(
985 origin: ConstVariableOrigin,
986 ) -> &'tcx ty::Const<'tcx> {
987 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
990 pub fn next_const_var_in_universe(
993 origin: ConstVariableOrigin,
994 universe: ty::UniverseIndex,
995 ) -> &'tcx ty::Const<'tcx> {
997 .const_unification_table
999 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1000 self.tcx.mk_const_var(vid, ty)
1003 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1004 self.const_unification_table.borrow_mut().new_key(ConstVarValue {
1006 val: ConstVariableValue::Unknown { universe: self.universe() },
1010 fn next_int_var_id(&self) -> IntVid {
1011 self.int_unification_table.borrow_mut().new_key(None)
1014 pub fn next_int_var(&self) -> Ty<'tcx> {
1015 self.tcx.mk_int_var(self.next_int_var_id())
1018 fn next_float_var_id(&self) -> FloatVid {
1019 self.float_unification_table.borrow_mut().new_key(None)
1022 pub fn next_float_var(&self) -> Ty<'tcx> {
1023 self.tcx.mk_float_var(self.next_float_var_id())
1026 /// Creates a fresh region variable with the next available index.
1027 /// The variable will be created in the maximum universe created
1028 /// thus far, allowing it to name any region created thus far.
1029 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1030 self.next_region_var_in_universe(origin, self.universe())
1033 /// Creates a fresh region variable with the next available index
1034 /// in the given universe; typically, you can use
1035 /// `next_region_var` and just use the maximal universe.
1036 pub fn next_region_var_in_universe(
1038 origin: RegionVariableOrigin,
1039 universe: ty::UniverseIndex,
1040 ) -> ty::Region<'tcx> {
1041 let region_var = self.borrow_region_constraints().new_region_var(universe, origin);
1042 self.tcx.mk_region(ty::ReVar(region_var))
1045 /// Return the universe that the region `r` was created in. For
1046 /// most regions (e.g., `'static`, named regions from the user,
1047 /// etc) this is the root universe U0. For inference variables or
1048 /// placeholders, however, it will return the universe which which
1049 /// they are associated.
1050 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1051 self.borrow_region_constraints().universe(r)
1054 /// Number of region variables created so far.
1055 pub fn num_region_vars(&self) -> usize {
1056 self.borrow_region_constraints().num_region_vars()
1059 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1060 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1061 self.next_region_var(RegionVariableOrigin::NLL(origin))
1064 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1065 pub fn next_nll_region_var_in_universe(
1067 origin: NLLRegionVariableOrigin,
1068 universe: ty::UniverseIndex,
1069 ) -> ty::Region<'tcx> {
1070 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1073 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1075 GenericParamDefKind::Lifetime => {
1076 // Create a region inference variable for the given
1077 // region parameter definition.
1078 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1080 GenericParamDefKind::Type { .. } => {
1081 // Create a type inference variable for the given
1082 // type parameter definition. The substitutions are
1083 // for actual parameters that may be referred to by
1084 // the default of this type parameter, if it exists.
1085 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1086 // used in a path such as `Foo::<T, U>::new()` will
1087 // use an inference variable for `C` with `[T, U]`
1088 // as the substitutions for the default, `(T, U)`.
1089 let ty_var_id = self.type_variables.borrow_mut().new_var(
1092 TypeVariableOrigin {
1093 kind: TypeVariableOriginKind::TypeParameterDefinition(
1101 self.tcx.mk_ty_var(ty_var_id).into()
1103 GenericParamDefKind::Const { .. } => {
1104 let origin = ConstVariableOrigin {
1105 kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1109 self.const_unification_table.borrow_mut().new_key(ConstVarValue {
1111 val: ConstVariableValue::Unknown { universe: self.universe() },
1113 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1118 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1119 /// type/region parameter to a fresh inference variable.
1120 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1121 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1124 /// Returns `true` if errors have been reported since this infcx was
1125 /// created. This is sometimes used as a heuristic to skip
1126 /// reporting errors that often occur as a result of earlier
1127 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1128 /// inference variables, regionck errors).
1129 pub fn is_tainted_by_errors(&self) -> bool {
1131 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1132 tainted_by_errors_flag={})",
1133 self.tcx.sess.err_count(),
1134 self.err_count_on_creation,
1135 self.tainted_by_errors_flag.get()
1138 if self.tcx.sess.err_count() > self.err_count_on_creation {
1139 return true; // errors reported since this infcx was made
1141 self.tainted_by_errors_flag.get()
1144 /// Set the "tainted by errors" flag to true. We call this when we
1145 /// observe an error from a prior pass.
1146 pub fn set_tainted_by_errors(&self) {
1147 debug!("set_tainted_by_errors()");
1148 self.tainted_by_errors_flag.set(true)
1151 /// Process the region constraints and report any errors that
1152 /// result. After this, no more unification operations should be
1153 /// done -- or the compiler will panic -- but it is legal to use
1154 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1155 pub fn resolve_regions_and_report_errors(
1157 region_context: DefId,
1158 region_map: ®ion::ScopeTree,
1159 outlives_env: &OutlivesEnvironment<'tcx>,
1160 suppress: SuppressRegionErrors,
1163 self.is_tainted_by_errors() || self.region_obligations.borrow().is_empty(),
1164 "region_obligations not empty: {:#?}",
1165 self.region_obligations.borrow()
1168 let region_rels = &RegionRelations::new(
1172 outlives_env.free_region_map(),
1174 let (var_infos, data) = self
1178 .expect("regions already resolved")
1179 .into_infos_and_data();
1180 let (lexical_region_resolutions, errors) =
1181 lexical_region_resolve::resolve(region_rels, var_infos, data);
1183 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1184 assert!(old_value.is_none());
1186 if !self.is_tainted_by_errors() {
1187 // As a heuristic, just skip reporting region errors
1188 // altogether if other errors have been reported while
1189 // this infcx was in use. This is totally hokey but
1190 // otherwise we have a hard time separating legit region
1191 // errors from silly ones.
1192 self.report_region_errors(region_map, &errors, suppress);
1196 /// Obtains (and clears) the current set of region
1197 /// constraints. The inference context is still usable: further
1198 /// unifications will simply add new constraints.
1200 /// This method is not meant to be used with normal lexical region
1201 /// resolution. Rather, it is used in the NLL mode as a kind of
1202 /// interim hack: basically we run normal type-check and generate
1203 /// region constraints as normal, but then we take them and
1204 /// translate them into the form that the NLL solver
1205 /// understands. See the NLL module for mode details.
1206 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1208 self.region_obligations.borrow().is_empty(),
1209 "region_obligations not empty: {:#?}",
1210 self.region_obligations.borrow()
1213 self.borrow_region_constraints().take_and_reset_data()
1216 /// Gives temporary access to the region constraint data.
1217 #[allow(non_camel_case_types)] // bug with impl trait
1218 pub fn with_region_constraints<R>(
1220 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1222 let region_constraints = self.borrow_region_constraints();
1223 op(region_constraints.data())
1226 /// Takes ownership of the list of variable regions. This implies
1227 /// that all the region constraints have already been taken, and
1228 /// hence that `resolve_regions_and_report_errors` can never be
1229 /// called. This is used only during NLL processing to "hand off" ownership
1230 /// of the set of region variables into the NLL region context.
1231 pub fn take_region_var_origins(&self) -> VarInfos {
1232 let (var_infos, data) = self
1236 .expect("regions already resolved")
1237 .into_infos_and_data();
1238 assert!(data.is_empty());
1242 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1243 self.resolve_vars_if_possible(&t).to_string()
1246 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1247 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1248 format!("({})", tstrs.join(", "))
1251 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1252 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1255 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1256 /// universe index of `TyVar(vid)`.
1257 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1258 use self::type_variable::TypeVariableValue;
1260 match self.type_variables.borrow_mut().probe(vid) {
1261 TypeVariableValue::Known { value } => Ok(value),
1262 TypeVariableValue::Unknown { universe } => Err(universe),
1266 /// Resolve any type variables found in `value` -- but only one
1267 /// level. So, if the variable `?X` is bound to some type
1268 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1269 /// itself be bound to a type).
1271 /// Useful when you only need to inspect the outermost level of
1272 /// the type and don't care about nested types (or perhaps you
1273 /// will be resolving them as well, e.g. in a loop).
1274 pub fn shallow_resolve<T>(&self, value: T) -> T
1276 T: TypeFoldable<'tcx>,
1278 let mut r = ShallowResolver::new(self);
1279 value.fold_with(&mut r)
1282 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1283 self.type_variables.borrow_mut().root_var(var)
1286 /// Where possible, replaces type/const variables in
1287 /// `value` with their final value. Note that region variables
1288 /// are unaffected. If a type/const variable has not been unified, it
1289 /// is left as is. This is an idempotent operation that does
1290 /// not affect inference state in any way and so you can do it
1292 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1294 T: TypeFoldable<'tcx>,
1296 if !value.needs_infer() {
1297 return value.clone(); // Avoid duplicated subst-folding.
1299 let mut r = resolve::OpportunisticVarResolver::new(self);
1300 value.fold_with(&mut r)
1303 /// Returns the first unresolved variable contained in `T`. In the
1304 /// process of visiting `T`, this will resolve (where possible)
1305 /// type variables in `T`, but it never constructs the final,
1306 /// resolved type, so it's more efficient than
1307 /// `resolve_vars_if_possible()`.
1308 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1310 T: TypeFoldable<'tcx>,
1312 let mut r = resolve::UnresolvedTypeFinder::new(self);
1313 value.visit_with(&mut r);
1317 pub fn probe_const_var(
1319 vid: ty::ConstVid<'tcx>,
1320 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1321 match self.const_unification_table.borrow_mut().probe_value(vid).val {
1322 ConstVariableValue::Known { value } => Ok(value),
1323 ConstVariableValue::Unknown { universe } => Err(universe),
1327 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1329 * Attempts to resolve all type/region/const variables in
1330 * `value`. Region inference must have been run already (e.g.,
1331 * by calling `resolve_regions_and_report_errors`). If some
1332 * variable was never unified, an `Err` results.
1334 * This method is idempotent, but it not typically not invoked
1335 * except during the writeback phase.
1338 resolve::fully_resolve(self, value)
1341 // [Note-Type-error-reporting]
1342 // An invariant is that anytime the expected or actual type is Error (the special
1343 // error type, meaning that an error occurred when typechecking this expression),
1344 // this is a derived error. The error cascaded from another error (that was already
1345 // reported), so it's not useful to display it to the user.
1346 // The following methods implement this logic.
1347 // They check if either the actual or expected type is Error, and don't print the error
1348 // in this case. The typechecker should only ever report type errors involving mismatched
1349 // types using one of these methods, and should not call span_err directly for such
1352 pub fn type_error_struct_with_diag<M>(
1356 actual_ty: Ty<'tcx>,
1357 ) -> DiagnosticBuilder<'tcx>
1359 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1361 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1362 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1364 // Don't report an error if actual type is `Error`.
1365 if actual_ty.references_error() {
1366 return self.tcx.sess.diagnostic().struct_dummy();
1369 mk_diag(self.ty_to_string(actual_ty))
1372 pub fn report_mismatched_types(
1374 cause: &ObligationCause<'tcx>,
1377 err: TypeError<'tcx>,
1378 ) -> DiagnosticBuilder<'tcx> {
1379 let trace = TypeTrace::types(cause, true, expected, actual);
1380 self.report_and_explain_type_error(trace, &err)
1383 pub fn replace_bound_vars_with_fresh_vars<T>(
1386 lbrct: LateBoundRegionConversionTime,
1387 value: &ty::Binder<T>,
1388 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1390 T: TypeFoldable<'tcx>,
1392 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1394 self.next_ty_var(TypeVariableOrigin {
1395 kind: TypeVariableOriginKind::MiscVariable,
1399 let fld_c = |_, ty| {
1400 self.next_const_var(
1402 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1405 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1408 /// See the [`region_constraints::verify_generic_bound`] method.
1409 pub fn verify_generic_bound(
1411 origin: SubregionOrigin<'tcx>,
1412 kind: GenericKind<'tcx>,
1413 a: ty::Region<'tcx>,
1414 bound: VerifyBound<'tcx>,
1416 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1418 self.borrow_region_constraints().verify_generic_bound(origin, kind, a, bound);
1421 pub fn type_is_copy_modulo_regions(
1423 param_env: ty::ParamEnv<'tcx>,
1427 let ty = self.resolve_vars_if_possible(&ty);
1429 // Even if the type may have no inference variables, during
1430 // type-checking closure types are in local tables only.
1431 if !self.in_progress_tables.is_some() || !ty.has_closure_types() {
1432 if !(param_env, ty).has_local_value() {
1433 return ty.is_copy_modulo_regions(self.tcx, param_env, span);
1437 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem, None);
1439 // This can get called from typeck (by euv), and `moves_by_default`
1440 // rightly refuses to work with inference variables, but
1441 // moves_by_default has a cache, which we want to use in other
1443 traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id, span)
1446 /// Obtains the latest type of the given closure; this may be a
1447 /// closure in the current function, in which case its
1448 /// `ClosureKind` may not yet be known.
1449 pub fn closure_kind(
1451 closure_def_id: DefId,
1452 closure_substs: SubstsRef<'tcx>,
1453 ) -> Option<ty::ClosureKind> {
1454 let closure_kind_ty = closure_substs.as_closure().kind_ty(closure_def_id, self.tcx);
1455 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1456 closure_kind_ty.to_opt_closure_kind()
1459 /// Obtains the signature of a closure. For closures, unlike
1460 /// `tcx.fn_sig(def_id)`, this method will work during the
1461 /// type-checking of the enclosing function and return the closure
1462 /// signature in its partially inferred state.
1463 pub fn closure_sig(&self, def_id: DefId, substs: SubstsRef<'tcx>) -> ty::PolyFnSig<'tcx> {
1464 let closure_sig_ty = substs.as_closure().sig_ty(def_id, self.tcx);
1465 let closure_sig_ty = self.shallow_resolve(closure_sig_ty);
1466 closure_sig_ty.fn_sig(self.tcx)
1469 /// Normalizes associated types in `value`, potentially returning
1470 /// new obligations that must further be processed.
1471 pub fn partially_normalize_associated_types_in<T>(
1474 body_id: hir::HirId,
1475 param_env: ty::ParamEnv<'tcx>,
1477 ) -> InferOk<'tcx, T>
1479 T: TypeFoldable<'tcx>,
1481 debug!("partially_normalize_associated_types_in(value={:?})", value);
1482 let mut selcx = traits::SelectionContext::new(self);
1483 let cause = ObligationCause::misc(span, body_id);
1484 let traits::Normalized { value, obligations } =
1485 traits::normalize(&mut selcx, param_env, cause, value);
1487 "partially_normalize_associated_types_in: result={:?} predicates={:?}",
1490 InferOk { value, obligations }
1493 pub fn borrow_region_constraints(&self) -> RefMut<'_, RegionConstraintCollector<'tcx>> {
1494 RefMut::map(self.region_constraints.borrow_mut(), |c| {
1495 c.as_mut().expect("region constraints already solved")
1499 /// Clears the selection, evaluation, and projection caches. This is useful when
1500 /// repeatedly attempting to select an `Obligation` while changing only
1501 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1502 pub fn clear_caches(&self) {
1503 self.selection_cache.clear();
1504 self.evaluation_cache.clear();
1505 self.projection_cache.borrow_mut().clear();
1508 fn universe(&self) -> ty::UniverseIndex {
1512 /// Creates and return a fresh universe that extends all previous
1513 /// universes. Updates `self.universe` to that new universe.
1514 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1515 let u = self.universe.get().next_universe();
1516 self.universe.set(u);
1521 pub struct ShallowResolver<'a, 'tcx> {
1522 infcx: &'a InferCtxt<'a, 'tcx>,
1525 impl<'a, 'tcx> ShallowResolver<'a, 'tcx> {
1527 pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self {
1528 ShallowResolver { infcx }
1531 /// If `typ` is a type variable of some kind, resolve it one level
1532 /// (but do not resolve types found in the result). If `typ` is
1533 /// not a type variable, just return it unmodified.
1534 pub fn shallow_resolve(&mut self, typ: Ty<'tcx>) -> Ty<'tcx> {
1536 ty::Infer(ty::TyVar(v)) => {
1537 // Not entirely obvious: if `typ` is a type variable,
1538 // it can be resolved to an int/float variable, which
1539 // can then be recursively resolved, hence the
1540 // recursion. Note though that we prevent type
1541 // variables from unifying to other type variables
1542 // directly (though they may be embedded
1543 // structurally), and we prevent cycles in any case,
1544 // so this recursion should always be of very limited
1551 .map(|t| self.fold_ty(t))
1555 ty::Infer(ty::IntVar(v)) => self
1557 .int_unification_table
1560 .map(|v| v.to_type(self.infcx.tcx))
1563 ty::Infer(ty::FloatVar(v)) => self
1565 .float_unification_table
1568 .map(|v| v.to_type(self.infcx.tcx))
1575 // `resolver.shallow_resolve_changed(ty)` is equivalent to
1576 // `resolver.shallow_resolve(ty) != ty`, but more efficient. It's always
1577 // inlined, despite being large, because it has only two call sites that
1578 // are extremely hot.
1580 pub fn shallow_resolve_changed(&self, infer: ty::InferTy) -> bool {
1583 use self::type_variable::TypeVariableValue;
1585 // If `inlined_probe` returns a `Known` value its `kind` never
1587 match self.infcx.type_variables.borrow_mut().inlined_probe(v) {
1588 TypeVariableValue::Unknown { .. } => false,
1589 TypeVariableValue::Known { .. } => true,
1594 // If inlined_probe_value returns a value it's always a
1595 // `ty::Int(_)` or `ty::UInt(_)`, which nevers matches a
1597 self.infcx.int_unification_table.borrow_mut().inlined_probe_value(v).is_some()
1600 ty::FloatVar(v) => {
1601 // If inlined_probe_value returns a value it's always a
1602 // `ty::Float(_)`, which nevers matches a `ty::Infer(_)`.
1604 // Not `inlined_probe_value(v)` because this call site is colder.
1605 self.infcx.float_unification_table.borrow_mut().probe_value(v).is_some()
1608 _ => unreachable!(),
1613 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1614 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1618 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1619 self.shallow_resolve(ty)
1622 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1623 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1625 .const_unification_table
1637 impl<'tcx> TypeTrace<'tcx> {
1638 pub fn span(&self) -> Span {
1643 cause: &ObligationCause<'tcx>,
1644 a_is_expected: bool,
1647 ) -> TypeTrace<'tcx> {
1648 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1651 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1653 cause: ObligationCause::dummy(),
1654 values: Types(ExpectedFound { expected: tcx.types.err, found: tcx.types.err }),
1659 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1660 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1661 write!(f, "TypeTrace({:?})", self.cause)
1665 impl<'tcx> SubregionOrigin<'tcx> {
1666 pub fn span(&self) -> Span {
1668 Subtype(ref a) => a.span(),
1669 InfStackClosure(a) => a,
1670 InvokeClosure(a) => a,
1671 DerefPointer(a) => a,
1672 ClosureCapture(a, _) => a,
1674 RelateObjectBound(a) => a,
1675 RelateParamBound(a, _) => a,
1676 RelateRegionParamBound(a) => a,
1677 RelateDefaultParamBound(a, _) => a,
1679 ReborrowUpvar(a, _) => a,
1680 DataBorrowed(_, a) => a,
1681 ReferenceOutlivesReferent(_, a) => a,
1682 ParameterInScope(_, a) => a,
1683 ExprTypeIsNotInScope(_, a) => a,
1684 BindingTypeIsNotValidAtDecl(a) => a,
1691 SafeDestructor(a) => a,
1692 CompareImplMethodObligation { span, .. } => span,
1696 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1698 F: FnOnce() -> Self,
1701 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1702 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1705 traits::ObligationCauseCode::CompareImplMethodObligation {
1709 } => SubregionOrigin::CompareImplMethodObligation {
1721 impl RegionVariableOrigin {
1722 pub fn span(&self) -> Span {
1724 MiscVariable(a) => a,
1725 PatternRegion(a) => a,
1726 AddrOfRegion(a) => a,
1729 EarlyBoundRegion(a, ..) => a,
1730 LateBoundRegion(a, ..) => a,
1731 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1732 UpvarRegion(_, a) => a,
1733 NLL(..) => bug!("NLL variable used with `span`"),
1738 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1739 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1742 "RegionObligation(sub_region={:?}, sup_type={:?})",
1743 self.sub_region, self.sup_type