1 //! See the Book for more information.
3 pub use self::freshen::TypeFreshener;
4 pub use self::LateBoundRegionConversionTime::*;
5 pub use self::RegionVariableOrigin::*;
6 pub use self::SubregionOrigin::*;
7 pub use self::ValuePairs::*;
9 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
11 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_data_structures::sync::Lrc;
16 use rustc_data_structures::undo_log::{Rollback, Snapshots};
17 use rustc_data_structures::unify as ut;
18 use rustc_errors::DiagnosticBuilder;
20 use rustc_hir::def_id::{DefId, LocalDefId};
21 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
22 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
23 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
24 use rustc_middle::middle::region;
25 use rustc_middle::mir;
26 use rustc_middle::mir::interpret::ConstEvalResult;
27 use rustc_middle::traits::select;
28 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
29 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
30 use rustc_middle::ty::relate::RelateResult;
31 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
32 pub use rustc_middle::ty::IntVarValue;
33 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
34 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
35 use rustc_session::config::BorrowckMode;
36 use rustc_span::symbol::Symbol;
39 use std::cell::{Cell, Ref, RefCell};
40 use std::collections::BTreeMap;
42 use std::marker::PhantomData;
44 use self::combine::CombineFields;
45 use self::free_regions::RegionRelations;
46 use self::lexical_region_resolve::LexicalRegionResolutions;
47 use self::outlives::env::OutlivesEnvironment;
48 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
49 use self::region_constraints::{
50 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
52 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
58 pub mod error_reporting;
65 mod lexical_region_resolve;
69 pub mod region_constraints;
72 pub mod type_variable;
75 use crate::infer::canonical::OriginalQueryValues;
76 pub use rustc_middle::infer::unify_key;
80 pub struct InferOk<'tcx, T> {
82 pub obligations: PredicateObligations<'tcx>,
84 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
86 pub type Bound<T> = Option<T>;
87 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
88 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
90 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
91 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
94 /// How we should handle region solving.
96 /// This is used so that the region values inferred by HIR region solving are
97 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
98 /// typeck will also do.
99 #[derive(Copy, Clone, Debug)]
100 pub enum RegionckMode {
101 /// The default mode: report region errors, don't erase regions.
103 /// Erase the results of region after solving.
105 /// A flag that is used to suppress region errors, when we are doing
106 /// region checks that the NLL borrow checker will also do -- it might
108 suppress_errors: bool,
112 impl Default for RegionckMode {
113 fn default() -> Self {
119 pub fn suppressed(self) -> bool {
121 Self::Solve => false,
122 Self::Erase { suppress_errors } => suppress_errors,
126 /// Indicates that the MIR borrowck will repeat these region
127 /// checks, so we should ignore errors if NLL is (unconditionally)
129 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
130 // FIXME(Centril): Once we actually remove `::Migrate` also make
131 // this always `true` and then proceed to eliminate the dead code.
132 match tcx.borrowck_mode() {
133 // If we're on Migrate mode, report AST region errors
134 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
136 // If we're on MIR, don't report AST region errors as they should be reported by NLL
137 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
142 /// This type contains all the things within `InferCtxt` that sit within a
143 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
144 /// operations are hot enough that we want only one call to `borrow_mut` per
145 /// call to `start_snapshot` and `rollback_to`.
146 pub struct InferCtxtInner<'tcx> {
147 /// Cache for projections. This cache is snapshotted along with the infcx.
149 /// Public so that `traits::project` can use it.
150 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
152 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
153 /// that might instantiate a general type variable have an order,
154 /// represented by its upper and lower bounds.
155 type_variables: type_variable::TypeVariableStorage<'tcx>,
157 /// Map from const parameter variable to the kind of const it represents.
158 const_unification_table: ut::UnificationStorage<ty::ConstVid<'tcx>>,
160 /// Map from integral variable to the kind of integer it represents.
161 int_unification_table: ut::UnificationStorage<ty::IntVid>,
163 /// Map from floating variable to the kind of float it represents.
164 float_unification_table: ut::UnificationStorage<ty::FloatVid>,
166 /// Tracks the set of region variables and the constraints between them.
167 /// This is initially `Some(_)` but when
168 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
169 /// -- further attempts to perform unification, etc., may fail if new
170 /// region constraints would've been added.
171 region_constraints: Option<RegionConstraintStorage<'tcx>>,
173 /// A set of constraints that regionck must validate. Each
174 /// constraint has the form `T:'a`, meaning "some type `T` must
175 /// outlive the lifetime 'a". These constraints derive from
176 /// instantiated type parameters. So if you had a struct defined
179 /// struct Foo<T:'static> { ... }
181 /// then in some expression `let x = Foo { ... }` it will
182 /// instantiate the type parameter `T` with a fresh type `$0`. At
183 /// the same time, it will record a region obligation of
184 /// `$0:'static`. This will get checked later by regionck. (We
185 /// can't generally check these things right away because we have
186 /// to wait until types are resolved.)
188 /// These are stored in a map keyed to the id of the innermost
189 /// enclosing fn body / static initializer expression. This is
190 /// because the location where the obligation was incurred can be
191 /// relevant with respect to which sublifetime assumptions are in
192 /// place. The reason that we store under the fn-id, and not
193 /// something more fine-grained, is so that it is easier for
194 /// regionck to be sure that it has found *all* the region
195 /// obligations (otherwise, it's easy to fail to walk to a
196 /// particular node-id).
198 /// Before running `resolve_regions_and_report_errors`, the creator
199 /// of the inference context is expected to invoke
200 /// `process_region_obligations` (defined in `self::region_obligations`)
201 /// for each body-id in this map, which will process the
202 /// obligations within. This is expected to be done 'late enough'
203 /// that all type inference variables have been bound and so forth.
204 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
206 undo_log: InferCtxtUndoLogs<'tcx>,
209 impl<'tcx> InferCtxtInner<'tcx> {
210 fn new() -> InferCtxtInner<'tcx> {
212 projection_cache: Default::default(),
213 type_variables: type_variable::TypeVariableStorage::new(),
214 undo_log: InferCtxtUndoLogs::default(),
215 const_unification_table: ut::UnificationStorage::new(),
216 int_unification_table: ut::UnificationStorage::new(),
217 float_unification_table: ut::UnificationStorage::new(),
218 region_constraints: Some(RegionConstraintStorage::new()),
219 region_obligations: vec![],
223 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
224 &self.region_obligations
227 pub(crate) fn projection_cache(&mut self) -> traits::ProjectionCache<'tcx, '_> {
228 self.projection_cache.with_log(&mut self.undo_log)
231 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'tcx, '_> {
232 self.type_variables.with_log(&mut self.undo_log)
235 fn int_unification_table(
237 ) -> ut::UnificationTable<
240 &mut ut::UnificationStorage<ty::IntVid>,
241 &mut InferCtxtUndoLogs<'tcx>,
244 ut::UnificationTable::with_log(&mut self.int_unification_table, &mut self.undo_log)
247 fn float_unification_table(
249 ) -> ut::UnificationTable<
252 &mut ut::UnificationStorage<ty::FloatVid>,
253 &mut InferCtxtUndoLogs<'tcx>,
256 ut::UnificationTable::with_log(&mut self.float_unification_table, &mut self.undo_log)
259 fn const_unification_table(
261 ) -> ut::UnificationTable<
264 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
265 &mut InferCtxtUndoLogs<'tcx>,
268 ut::UnificationTable::with_log(&mut self.const_unification_table, &mut self.undo_log)
271 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'tcx, '_> {
272 self.region_constraints
274 .expect("region constraints already solved")
275 .with_log(&mut self.undo_log)
279 pub struct InferCtxt<'a, 'tcx> {
280 pub tcx: TyCtxt<'tcx>,
282 /// During type-checking/inference of a body, `in_progress_tables`
283 /// contains a reference to the tables being built up, which are
284 /// used for reading closure kinds/signatures as they are inferred,
285 /// and for error reporting logic to read arbitrary node types.
286 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
288 pub inner: RefCell<InferCtxtInner<'tcx>>,
290 /// If set, this flag causes us to skip the 'leak check' during
291 /// higher-ranked subtyping operations. This flag is a temporary one used
292 /// to manage the removal of the leak-check: for the time being, we still run the
293 /// leak-check, but we issue warnings. This flag can only be set to true
294 /// when entering a snapshot.
295 skip_leak_check: Cell<bool>,
297 /// Once region inference is done, the values for each variable.
298 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
300 /// Caches the results of trait selection. This cache is used
301 /// for things that have to do with the parameters in scope.
302 pub selection_cache: select::SelectionCache<'tcx>,
304 /// Caches the results of trait evaluation.
305 pub evaluation_cache: select::EvaluationCache<'tcx>,
307 /// the set of predicates on which errors have been reported, to
308 /// avoid reporting the same error twice.
309 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
311 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
313 /// When an error occurs, we want to avoid reporting "derived"
314 /// errors that are due to this original failure. Normally, we
315 /// handle this with the `err_count_on_creation` count, which
316 /// basically just tracks how many errors were reported when we
317 /// started type-checking a fn and checks to see if any new errors
318 /// have been reported since then. Not great, but it works.
320 /// However, when errors originated in other passes -- notably
321 /// resolve -- this heuristic breaks down. Therefore, we have this
322 /// auxiliary flag that one can set whenever one creates a
323 /// type-error that is due to an error in a prior pass.
325 /// Don't read this flag directly, call `is_tainted_by_errors()`
326 /// and `set_tainted_by_errors()`.
327 tainted_by_errors_flag: Cell<bool>,
329 /// Track how many errors were reported when this infcx is created.
330 /// If the number of errors increases, that's also a sign (line
331 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
332 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
333 err_count_on_creation: usize,
335 /// This flag is true while there is an active snapshot.
336 in_snapshot: Cell<bool>,
338 /// What is the innermost universe we have created? Starts out as
339 /// `UniverseIndex::root()` but grows from there as we enter
340 /// universal quantifiers.
342 /// N.B., at present, we exclude the universal quantifiers on the
343 /// item we are type-checking, and just consider those names as
344 /// part of the root universe. So this would only get incremented
345 /// when we enter into a higher-ranked (`for<..>`) type or trait
347 universe: Cell<ty::UniverseIndex>,
350 /// A map returned by `replace_bound_vars_with_placeholders()`
351 /// indicating the placeholder region that each late-bound region was
353 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
355 /// See the `error_reporting` module for more details.
356 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
357 pub enum ValuePairs<'tcx> {
358 Types(ExpectedFound<Ty<'tcx>>),
359 Regions(ExpectedFound<ty::Region<'tcx>>),
360 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
361 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
362 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
365 /// The trace designates the path through inference that we took to
366 /// encounter an error or subtyping constraint.
368 /// See the `error_reporting` module for more details.
369 #[derive(Clone, Debug)]
370 pub struct TypeTrace<'tcx> {
371 cause: ObligationCause<'tcx>,
372 values: ValuePairs<'tcx>,
375 /// The origin of a `r1 <= r2` constraint.
377 /// See `error_reporting` module for more details
378 #[derive(Clone, Debug)]
379 pub enum SubregionOrigin<'tcx> {
380 /// Arose from a subtyping relation
381 Subtype(Box<TypeTrace<'tcx>>),
383 /// Stack-allocated closures cannot outlive innermost loop
384 /// or function so as to ensure we only require finite stack
385 InfStackClosure(Span),
387 /// Invocation of closure must be within its lifetime
390 /// Dereference of reference must be within its lifetime
393 /// Closure bound must not outlive captured variables
394 ClosureCapture(Span, hir::HirId),
396 /// Index into slice must be within its lifetime
399 /// When casting `&'a T` to an `&'b Trait` object,
400 /// relating `'a` to `'b`
401 RelateObjectBound(Span),
403 /// Some type parameter was instantiated with the given type,
404 /// and that type must outlive some region.
405 RelateParamBound(Span, Ty<'tcx>),
407 /// The given region parameter was instantiated with a region
408 /// that must outlive some other region.
409 RelateRegionParamBound(Span),
411 /// A bound placed on type parameters that states that must outlive
412 /// the moment of their instantiation.
413 RelateDefaultParamBound(Span, Ty<'tcx>),
415 /// Creating a pointer `b` to contents of another reference
418 /// Creating a pointer `b` to contents of an upvar
419 ReborrowUpvar(Span, ty::UpvarId),
421 /// Data with type `Ty<'tcx>` was borrowed
422 DataBorrowed(Ty<'tcx>, Span),
424 /// (&'a &'b T) where a >= b
425 ReferenceOutlivesReferent(Ty<'tcx>, Span),
427 /// Type or region parameters must be in scope.
428 ParameterInScope(ParameterOrigin, Span),
430 /// The type T of an expression E must outlive the lifetime for E.
431 ExprTypeIsNotInScope(Ty<'tcx>, Span),
433 /// A `ref b` whose region does not enclose the decl site
434 BindingTypeIsNotValidAtDecl(Span),
436 /// Regions appearing in a method receiver must outlive method call
439 /// Regions appearing in a function argument must outlive func call
442 /// Region in return type of invoked fn must enclose call
445 /// Operands must be in scope
448 /// Region resulting from a `&` expr must enclose the `&` expr
451 /// An auto-borrow that does not enclose the expr where it occurs
454 /// Region constraint arriving from destructor safety
455 SafeDestructor(Span),
457 /// Comparing the signature and requirements of an impl method against
458 /// the containing trait.
459 CompareImplMethodObligation {
461 item_name: ast::Name,
462 impl_item_def_id: DefId,
463 trait_item_def_id: DefId,
467 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
468 #[cfg(target_arch = "x86_64")]
469 static_assert_size!(SubregionOrigin<'_>, 32);
471 /// Places that type/region parameters can appear.
472 #[derive(Clone, Copy, Debug)]
473 pub enum ParameterOrigin {
475 MethodCall, // foo.bar() <-- parameters on impl providing bar()
476 OverloadedOperator, // a + b when overloaded
477 OverloadedDeref, // *a when overloaded
480 /// Times when we replace late-bound regions with variables:
481 #[derive(Clone, Copy, Debug)]
482 pub enum LateBoundRegionConversionTime {
483 /// when a fn is called
486 /// when two higher-ranked types are compared
489 /// when projecting an associated type
490 AssocTypeProjection(DefId),
493 /// Reasons to create a region inference variable
495 /// See `error_reporting` module for more details
496 #[derive(Copy, Clone, Debug)]
497 pub enum RegionVariableOrigin {
498 /// Region variables created for ill-categorized reasons,
499 /// mostly indicates places in need of refactoring
502 /// Regions created by a `&P` or `[...]` pattern
505 /// Regions created by `&` operator
508 /// Regions created as part of an autoref of a method receiver
511 /// Regions created as part of an automatic coercion
514 /// Region variables created as the values for early-bound regions
515 EarlyBoundRegion(Span, Symbol),
517 /// Region variables created for bound regions
518 /// in a function or method that is called
519 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
521 UpvarRegion(ty::UpvarId, Span),
523 BoundRegionInCoherence(ast::Name),
525 /// This origin is used for the inference variables that we create
526 /// during NLL region processing.
527 NLL(NLLRegionVariableOrigin),
530 #[derive(Copy, Clone, Debug)]
531 pub enum NLLRegionVariableOrigin {
532 /// During NLL region processing, we create variables for free
533 /// regions that we encounter in the function signature and
534 /// elsewhere. This origin indices we've got one of those.
537 /// "Universal" instantiation of a higher-ranked region (e.g.,
538 /// from a `for<'a> T` binder). Meant to represent "any region".
539 Placeholder(ty::PlaceholderRegion),
541 /// The variable we create to represent `'empty(U0)`.
545 /// If this is true, then this variable was created to represent a lifetime
546 /// bound in a `for` binder. For example, it might have been created to
547 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
548 /// Such variables are created when we are trying to figure out if there
549 /// is any valid instantiation of `'a` that could fit into some scenario.
551 /// This is used to inform error reporting: in the case that we are trying to
552 /// determine whether there is any valid instantiation of a `'a` variable that meets
553 /// some constraint C, we want to blame the "source" of that `for` type,
554 /// rather than blaming the source of the constraint C.
559 impl NLLRegionVariableOrigin {
560 pub fn is_universal(self) -> bool {
562 NLLRegionVariableOrigin::FreeRegion => true,
563 NLLRegionVariableOrigin::Placeholder(..) => true,
564 NLLRegionVariableOrigin::Existential { .. } => false,
565 NLLRegionVariableOrigin::RootEmptyRegion => false,
569 pub fn is_existential(self) -> bool {
574 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
575 #[derive(Copy, Clone, Debug)]
576 pub enum FixupError<'tcx> {
577 UnresolvedIntTy(IntVid),
578 UnresolvedFloatTy(FloatVid),
580 UnresolvedConst(ConstVid<'tcx>),
583 /// See the `region_obligations` field for more information.
585 pub struct RegionObligation<'tcx> {
586 pub sub_region: ty::Region<'tcx>,
587 pub sup_type: Ty<'tcx>,
588 pub origin: SubregionOrigin<'tcx>,
591 impl<'tcx> fmt::Display for FixupError<'tcx> {
592 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593 use self::FixupError::*;
596 UnresolvedIntTy(_) => write!(
598 "cannot determine the type of this integer; \
599 add a suffix to specify the type explicitly"
601 UnresolvedFloatTy(_) => write!(
603 "cannot determine the type of this number; \
604 add a suffix to specify the type explicitly"
606 UnresolvedTy(_) => write!(f, "unconstrained type"),
607 UnresolvedConst(_) => write!(f, "unconstrained const value"),
612 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
613 /// Necessary because we can't write the following bound:
614 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
615 pub struct InferCtxtBuilder<'tcx> {
616 global_tcx: TyCtxt<'tcx>,
617 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
620 pub trait TyCtxtInferExt<'tcx> {
621 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
624 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
625 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
626 InferCtxtBuilder { global_tcx: self, fresh_tables: None }
630 impl<'tcx> InferCtxtBuilder<'tcx> {
631 /// Used only by `rustc_typeck` during body type-checking/inference,
632 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
633 pub fn with_fresh_in_progress_tables(mut self, table_owner: LocalDefId) -> Self {
634 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
638 /// Given a canonical value `C` as a starting point, create an
639 /// inference context that contains each of the bound values
640 /// within instantiated as a fresh variable. The `f` closure is
641 /// invoked with the new infcx, along with the instantiated value
642 /// `V` and a substitution `S`. This substitution `S` maps from
643 /// the bound values in `C` to their instantiated values in `V`
644 /// (in other words, `S(C) = V`).
645 pub fn enter_with_canonical<T, R>(
648 canonical: &Canonical<'tcx, T>,
649 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
652 T: TypeFoldable<'tcx>,
656 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
657 f(infcx, value, subst)
661 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
662 let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
663 let in_progress_tables = fresh_tables.as_ref();
664 global_tcx.enter_local(|tcx| {
668 inner: RefCell::new(InferCtxtInner::new()),
669 lexical_region_resolutions: RefCell::new(None),
670 selection_cache: Default::default(),
671 evaluation_cache: Default::default(),
672 reported_trait_errors: Default::default(),
673 reported_closure_mismatch: Default::default(),
674 tainted_by_errors_flag: Cell::new(false),
675 err_count_on_creation: tcx.sess.err_count(),
676 in_snapshot: Cell::new(false),
677 skip_leak_check: Cell::new(false),
678 universe: Cell::new(ty::UniverseIndex::ROOT),
684 impl<'tcx, T> InferOk<'tcx, T> {
685 pub fn unit(self) -> InferOk<'tcx, ()> {
686 InferOk { value: (), obligations: self.obligations }
689 /// Extracts `value`, registering any obligations into `fulfill_cx`.
690 pub fn into_value_registering_obligations(
692 infcx: &InferCtxt<'_, 'tcx>,
693 fulfill_cx: &mut dyn TraitEngine<'tcx>,
695 let InferOk { value, obligations } = self;
696 for obligation in obligations {
697 fulfill_cx.register_predicate_obligation(infcx, obligation);
703 impl<'tcx> InferOk<'tcx, ()> {
704 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
709 #[must_use = "once you start a snapshot, you should always consume it"]
710 pub struct FullSnapshot<'a, 'tcx> {
711 snapshot: CombinedSnapshot<'a, 'tcx>,
712 region_constraints_snapshot: RegionSnapshot,
713 type_snapshot: type_variable::Snapshot<'tcx>,
714 const_snapshot: usize,
716 float_snapshot: usize,
719 #[must_use = "once you start a snapshot, you should always consume it"]
720 pub struct CombinedSnapshot<'a, 'tcx> {
721 undo_snapshot: Snapshot<'tcx>,
722 universe: ty::UniverseIndex,
723 was_in_snapshot: bool,
724 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
727 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
728 pub fn is_in_snapshot(&self) -> bool {
729 self.in_snapshot.get()
732 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
733 t.fold_with(&mut self.freshener())
736 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
738 ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
743 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
744 freshen::TypeFreshener::new(self)
747 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
748 use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
749 use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
751 ty::Infer(ty::IntVar(vid)) => {
752 if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
758 ty::Infer(ty::FloatVar(vid)) => {
759 if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
769 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
770 let mut inner = self.inner.borrow_mut();
771 // FIXME(const_generics): should there be an equivalent function for const variables?
773 let mut vars: Vec<Ty<'_>> = inner
775 .unsolved_variables()
777 .map(|t| self.tcx.mk_ty_var(t))
780 (0..inner.int_unification_table().len())
781 .map(|i| ty::IntVid { index: i as u32 })
782 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
783 .map(|v| self.tcx.mk_int_var(v)),
786 (0..inner.float_unification_table().len())
787 .map(|i| ty::FloatVid { index: i as u32 })
788 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
789 .map(|v| self.tcx.mk_float_var(v)),
796 trace: TypeTrace<'tcx>,
797 param_env: ty::ParamEnv<'tcx>,
798 ) -> CombineFields<'a, 'tcx> {
804 obligations: PredicateObligations::new(),
808 /// Clear the "currently in a snapshot" flag, invoke the closure,
809 /// then restore the flag to its original value. This flag is a
810 /// debugging measure designed to detect cases where we start a
811 /// snapshot, create type variables, and register obligations
812 /// which may involve those type variables in the fulfillment cx,
813 /// potentially leaving "dangling type variables" behind.
814 /// In such cases, an assertion will fail when attempting to
815 /// register obligations, within a snapshot. Very useful, much
816 /// better than grovelling through megabytes of `RUSTC_LOG` output.
818 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
819 /// sometimes create a "mini-fulfilment-cx" in which we enroll
820 /// obligations. As long as this fulfillment cx is fully drained
821 /// before we return, this is not a problem, as there won't be any
822 /// escaping obligations in the main cx. In those cases, you can
823 /// use this function.
824 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
826 F: FnOnce(&Self) -> R,
828 let flag = self.in_snapshot.replace(false);
829 let result = func(self);
830 self.in_snapshot.set(flag);
834 fn start_full_snapshot(&self) -> FullSnapshot<'a, 'tcx> {
835 let snapshot = self.start_snapshot();
836 let mut inner = self.inner.borrow_mut();
839 type_snapshot: inner.type_variables().snapshot(),
840 const_snapshot: inner.const_unification_table().len(),
841 int_snapshot: inner.int_unification_table().len(),
842 float_snapshot: inner.float_unification_table().len(),
843 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
847 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
848 debug!("start_snapshot()");
850 let in_snapshot = self.in_snapshot.replace(true);
852 let mut inner = self.inner.borrow_mut();
855 undo_snapshot: inner.undo_log.start_snapshot(),
856 universe: self.universe(),
857 was_in_snapshot: in_snapshot,
858 // Borrow tables "in progress" (i.e., during typeck)
859 // to ban writes from within a snapshot to them.
860 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
864 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
865 debug!("rollback_to(cause={})", cause);
866 let CombinedSnapshot { undo_snapshot, universe, was_in_snapshot, _in_progress_tables } =
869 self.in_snapshot.set(was_in_snapshot);
870 self.universe.set(universe);
874 const_unification_table,
875 int_unification_table,
876 float_unification_table,
882 } = &mut *self.inner.borrow_mut();
883 undo_log.rollback_to(
884 || undo_log::RollbackView {
886 const_unification_table,
887 int_unification_table,
888 float_unification_table,
889 region_constraints: region_constraints.as_mut().unwrap(),
897 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
898 debug!("commit_from()");
899 let CombinedSnapshot { undo_snapshot, universe: _, was_in_snapshot, _in_progress_tables } =
902 self.in_snapshot.set(was_in_snapshot);
904 let mut inner = self.inner.borrow_mut();
905 inner.undo_log.commit(undo_snapshot);
908 /// Executes `f` and commit the bindings.
909 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
911 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
913 debug!("commit_unconditionally()");
914 let snapshot = self.start_snapshot();
915 let r = f(&snapshot);
916 self.commit_from(snapshot);
920 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
921 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
923 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
925 debug!("commit_if_ok()");
926 let snapshot = self.start_snapshot();
927 let r = f(&snapshot);
928 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
931 self.commit_from(snapshot);
934 self.rollback_to("commit_if_ok -- error", snapshot);
940 /// Execute `f` then unroll any bindings it creates.
941 pub fn probe<R, F>(&self, f: F) -> R
943 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
946 let snapshot = self.start_snapshot();
947 let r = f(&snapshot);
948 self.rollback_to("probe", snapshot);
952 pub fn probe_full<R, F>(&self, f: F) -> R
954 F: FnOnce(&FullSnapshot<'a, 'tcx>) -> R,
957 let snapshot = self.start_full_snapshot();
958 let r = f(&snapshot);
959 self.rollback_to("probe", snapshot.snapshot);
963 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
964 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
966 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
969 let snapshot = self.start_snapshot();
970 let was_skip_leak_check = self.skip_leak_check.get();
972 self.skip_leak_check.set(true);
974 let r = f(&snapshot);
975 self.rollback_to("probe", snapshot);
976 self.skip_leak_check.set(was_skip_leak_check);
980 /// Scan the constraints produced since `snapshot` began and returns:
982 /// - `None` -- if none of them involve "region outlives" constraints
983 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
984 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
985 pub fn region_constraints_added_in_snapshot(
987 snapshot: &CombinedSnapshot<'a, 'tcx>,
991 .unwrap_region_constraints()
992 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
995 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
996 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
999 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
1001 T: at::ToTrace<'tcx>,
1003 let origin = &ObligationCause::dummy();
1005 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
1006 // Ignore obligations, since we are unrolling
1007 // everything anyway.
1012 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
1014 T: at::ToTrace<'tcx>,
1016 let origin = &ObligationCause::dummy();
1018 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
1019 // Ignore obligations, since we are unrolling
1020 // everything anyway.
1027 origin: SubregionOrigin<'tcx>,
1028 a: ty::Region<'tcx>,
1029 b: ty::Region<'tcx>,
1031 debug!("sub_regions({:?} <: {:?})", a, b);
1032 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
1035 /// Require that the region `r` be equal to one of the regions in
1036 /// the set `regions`.
1037 pub fn member_constraint(
1039 opaque_type_def_id: DefId,
1040 definition_span: Span,
1041 hidden_ty: Ty<'tcx>,
1042 region: ty::Region<'tcx>,
1043 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
1045 debug!("member_constraint({:?} <: {:?})", region, in_regions);
1046 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
1055 pub fn subtype_predicate(
1057 cause: &ObligationCause<'tcx>,
1058 param_env: ty::ParamEnv<'tcx>,
1059 predicate: &ty::PolySubtypePredicate<'tcx>,
1060 ) -> Option<InferResult<'tcx, ()>> {
1061 // Subtle: it's ok to skip the binder here and resolve because
1062 // `shallow_resolve` just ignores anything that is not a type
1063 // variable, and because type variable's can't (at present, at
1064 // least) capture any of the things bound by this binder.
1066 // NOTE(nmatsakis): really, there is no *particular* reason to do this
1067 // `shallow_resolve` here except as a micro-optimization.
1068 // Naturally I could not resist.
1069 let two_unbound_type_vars = {
1070 let a = self.shallow_resolve(predicate.skip_binder().a);
1071 let b = self.shallow_resolve(predicate.skip_binder().b);
1072 a.is_ty_var() && b.is_ty_var()
1075 if two_unbound_type_vars {
1076 // Two unbound type variables? Can't make progress.
1080 Some(self.commit_if_ok(|snapshot| {
1081 let (ty::SubtypePredicate { a_is_expected, a, b }, placeholder_map) =
1082 self.replace_bound_vars_with_placeholders(predicate);
1084 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1086 self.leak_check(false, &placeholder_map, snapshot)?;
1092 pub fn region_outlives_predicate(
1094 cause: &traits::ObligationCause<'tcx>,
1095 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
1096 ) -> UnitResult<'tcx> {
1097 self.commit_if_ok(|snapshot| {
1098 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
1099 self.replace_bound_vars_with_placeholders(predicate);
1100 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1101 RelateRegionParamBound(cause.span)
1103 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1104 self.leak_check(false, &placeholder_map, snapshot)?;
1109 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1110 self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
1113 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1114 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1117 pub fn next_ty_var_in_universe(
1119 origin: TypeVariableOrigin,
1120 universe: ty::UniverseIndex,
1122 let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
1123 self.tcx.mk_ty_var(vid)
1126 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1127 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1130 pub fn next_const_var(
1133 origin: ConstVariableOrigin,
1134 ) -> &'tcx ty::Const<'tcx> {
1135 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1138 pub fn next_const_var_in_universe(
1141 origin: ConstVariableOrigin,
1142 universe: ty::UniverseIndex,
1143 ) -> &'tcx ty::Const<'tcx> {
1147 .const_unification_table()
1148 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1149 self.tcx.mk_const_var(vid, ty)
1152 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1153 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1155 val: ConstVariableValue::Unknown { universe: self.universe() },
1159 fn next_int_var_id(&self) -> IntVid {
1160 self.inner.borrow_mut().int_unification_table().new_key(None)
1163 pub fn next_int_var(&self) -> Ty<'tcx> {
1164 self.tcx.mk_int_var(self.next_int_var_id())
1167 fn next_float_var_id(&self) -> FloatVid {
1168 self.inner.borrow_mut().float_unification_table().new_key(None)
1171 pub fn next_float_var(&self) -> Ty<'tcx> {
1172 self.tcx.mk_float_var(self.next_float_var_id())
1175 /// Creates a fresh region variable with the next available index.
1176 /// The variable will be created in the maximum universe created
1177 /// thus far, allowing it to name any region created thus far.
1178 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1179 self.next_region_var_in_universe(origin, self.universe())
1182 /// Creates a fresh region variable with the next available index
1183 /// in the given universe; typically, you can use
1184 /// `next_region_var` and just use the maximal universe.
1185 pub fn next_region_var_in_universe(
1187 origin: RegionVariableOrigin,
1188 universe: ty::UniverseIndex,
1189 ) -> ty::Region<'tcx> {
1191 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1192 self.tcx.mk_region(ty::ReVar(region_var))
1195 /// Return the universe that the region `r` was created in. For
1196 /// most regions (e.g., `'static`, named regions from the user,
1197 /// etc) this is the root universe U0. For inference variables or
1198 /// placeholders, however, it will return the universe which which
1199 /// they are associated.
1200 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1201 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1204 /// Number of region variables created so far.
1205 pub fn num_region_vars(&self) -> usize {
1206 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1209 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1210 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1211 self.next_region_var(RegionVariableOrigin::NLL(origin))
1214 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1215 pub fn next_nll_region_var_in_universe(
1217 origin: NLLRegionVariableOrigin,
1218 universe: ty::UniverseIndex,
1219 ) -> ty::Region<'tcx> {
1220 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1223 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1225 GenericParamDefKind::Lifetime => {
1226 // Create a region inference variable for the given
1227 // region parameter definition.
1228 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1230 GenericParamDefKind::Type { .. } => {
1231 // Create a type inference variable for the given
1232 // type parameter definition. The substitutions are
1233 // for actual parameters that may be referred to by
1234 // the default of this type parameter, if it exists.
1235 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1236 // used in a path such as `Foo::<T, U>::new()` will
1237 // use an inference variable for `C` with `[T, U]`
1238 // as the substitutions for the default, `(T, U)`.
1239 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1242 TypeVariableOrigin {
1243 kind: TypeVariableOriginKind::TypeParameterDefinition(
1251 self.tcx.mk_ty_var(ty_var_id).into()
1253 GenericParamDefKind::Const { .. } => {
1254 let origin = ConstVariableOrigin {
1255 kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1259 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1261 val: ConstVariableValue::Unknown { universe: self.universe() },
1263 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1268 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1269 /// type/region parameter to a fresh inference variable.
1270 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1271 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1274 /// Returns `true` if errors have been reported since this infcx was
1275 /// created. This is sometimes used as a heuristic to skip
1276 /// reporting errors that often occur as a result of earlier
1277 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1278 /// inference variables, regionck errors).
1279 pub fn is_tainted_by_errors(&self) -> bool {
1281 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1282 tainted_by_errors_flag={})",
1283 self.tcx.sess.err_count(),
1284 self.err_count_on_creation,
1285 self.tainted_by_errors_flag.get()
1288 if self.tcx.sess.err_count() > self.err_count_on_creation {
1289 return true; // errors reported since this infcx was made
1291 self.tainted_by_errors_flag.get()
1294 /// Set the "tainted by errors" flag to true. We call this when we
1295 /// observe an error from a prior pass.
1296 pub fn set_tainted_by_errors(&self) {
1297 debug!("set_tainted_by_errors()");
1298 self.tainted_by_errors_flag.set(true)
1301 /// Process the region constraints and report any errors that
1302 /// result. After this, no more unification operations should be
1303 /// done -- or the compiler will panic -- but it is legal to use
1304 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1305 pub fn resolve_regions_and_report_errors(
1307 region_context: DefId,
1308 region_map: ®ion::ScopeTree,
1309 outlives_env: &OutlivesEnvironment<'tcx>,
1313 self.is_tainted_by_errors() || self.inner.borrow().region_obligations.is_empty(),
1314 "region_obligations not empty: {:#?}",
1315 self.inner.borrow().region_obligations
1317 let (var_infos, data) = self
1322 .expect("regions already resolved")
1323 .with_log(&mut inner.undo_log)
1324 .into_infos_and_data();
1326 let region_rels = &RegionRelations::new(
1330 outlives_env.free_region_map(),
1333 let (lexical_region_resolutions, errors) =
1334 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1336 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1337 assert!(old_value.is_none());
1339 if !self.is_tainted_by_errors() {
1340 // As a heuristic, just skip reporting region errors
1341 // altogether if other errors have been reported while
1342 // this infcx was in use. This is totally hokey but
1343 // otherwise we have a hard time separating legit region
1344 // errors from silly ones.
1345 self.report_region_errors(region_map, &errors);
1349 /// Obtains (and clears) the current set of region
1350 /// constraints. The inference context is still usable: further
1351 /// unifications will simply add new constraints.
1353 /// This method is not meant to be used with normal lexical region
1354 /// resolution. Rather, it is used in the NLL mode as a kind of
1355 /// interim hack: basically we run normal type-check and generate
1356 /// region constraints as normal, but then we take them and
1357 /// translate them into the form that the NLL solver
1358 /// understands. See the NLL module for mode details.
1359 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1361 self.inner.borrow().region_obligations.is_empty(),
1362 "region_obligations not empty: {:#?}",
1363 self.inner.borrow().region_obligations
1366 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1369 /// Gives temporary access to the region constraint data.
1370 #[allow(non_camel_case_types)] // bug with impl trait
1371 pub fn with_region_constraints<R>(
1373 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1375 let mut inner = self.inner.borrow_mut();
1376 op(inner.unwrap_region_constraints().data())
1379 /// Takes ownership of the list of variable regions. This implies
1380 /// that all the region constraints have already been taken, and
1381 /// hence that `resolve_regions_and_report_errors` can never be
1382 /// called. This is used only during NLL processing to "hand off" ownership
1383 /// of the set of region variables into the NLL region context.
1384 pub fn take_region_var_origins(&self) -> VarInfos {
1385 let mut inner = self.inner.borrow_mut();
1386 let (var_infos, data) = inner
1389 .expect("regions already resolved")
1390 .with_log(&mut inner.undo_log)
1391 .into_infos_and_data();
1392 assert!(data.is_empty());
1396 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1397 self.resolve_vars_if_possible(&t).to_string()
1400 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1401 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1402 format!("({})", tstrs.join(", "))
1405 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1406 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1409 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1410 /// universe index of `TyVar(vid)`.
1411 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1412 use self::type_variable::TypeVariableValue;
1414 match self.inner.borrow_mut().type_variables().probe(vid) {
1415 TypeVariableValue::Known { value } => Ok(value),
1416 TypeVariableValue::Unknown { universe } => Err(universe),
1420 /// Resolve any type variables found in `value` -- but only one
1421 /// level. So, if the variable `?X` is bound to some type
1422 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1423 /// itself be bound to a type).
1425 /// Useful when you only need to inspect the outermost level of
1426 /// the type and don't care about nested types (or perhaps you
1427 /// will be resolving them as well, e.g. in a loop).
1428 pub fn shallow_resolve<T>(&self, value: T) -> T
1430 T: TypeFoldable<'tcx>,
1432 value.fold_with(&mut ShallowResolver { infcx: self })
1435 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1436 self.inner.borrow_mut().type_variables().root_var(var)
1439 /// Where possible, replaces type/const variables in
1440 /// `value` with their final value. Note that region variables
1441 /// are unaffected. If a type/const variable has not been unified, it
1442 /// is left as is. This is an idempotent operation that does
1443 /// not affect inference state in any way and so you can do it
1445 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1447 T: TypeFoldable<'tcx>,
1449 if !value.needs_infer() {
1450 return value.clone(); // Avoid duplicated subst-folding.
1452 let mut r = resolve::OpportunisticVarResolver::new(self);
1453 value.fold_with(&mut r)
1456 /// Returns the first unresolved variable contained in `T`. In the
1457 /// process of visiting `T`, this will resolve (where possible)
1458 /// type variables in `T`, but it never constructs the final,
1459 /// resolved type, so it's more efficient than
1460 /// `resolve_vars_if_possible()`.
1461 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1463 T: TypeFoldable<'tcx>,
1465 let mut r = resolve::UnresolvedTypeFinder::new(self);
1466 value.visit_with(&mut r);
1470 pub fn probe_const_var(
1472 vid: ty::ConstVid<'tcx>,
1473 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1474 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1475 ConstVariableValue::Known { value } => Ok(value),
1476 ConstVariableValue::Unknown { universe } => Err(universe),
1480 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1482 * Attempts to resolve all type/region/const variables in
1483 * `value`. Region inference must have been run already (e.g.,
1484 * by calling `resolve_regions_and_report_errors`). If some
1485 * variable was never unified, an `Err` results.
1487 * This method is idempotent, but it not typically not invoked
1488 * except during the writeback phase.
1491 resolve::fully_resolve(self, value)
1494 // [Note-Type-error-reporting]
1495 // An invariant is that anytime the expected or actual type is Error (the special
1496 // error type, meaning that an error occurred when typechecking this expression),
1497 // this is a derived error. The error cascaded from another error (that was already
1498 // reported), so it's not useful to display it to the user.
1499 // The following methods implement this logic.
1500 // They check if either the actual or expected type is Error, and don't print the error
1501 // in this case. The typechecker should only ever report type errors involving mismatched
1502 // types using one of these methods, and should not call span_err directly for such
1505 pub fn type_error_struct_with_diag<M>(
1509 actual_ty: Ty<'tcx>,
1510 ) -> DiagnosticBuilder<'tcx>
1512 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1514 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1515 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1517 // Don't report an error if actual type is `Error`.
1518 if actual_ty.references_error() {
1519 return self.tcx.sess.diagnostic().struct_dummy();
1522 mk_diag(self.ty_to_string(actual_ty))
1525 pub fn report_mismatched_types(
1527 cause: &ObligationCause<'tcx>,
1530 err: TypeError<'tcx>,
1531 ) -> DiagnosticBuilder<'tcx> {
1532 let trace = TypeTrace::types(cause, true, expected, actual);
1533 self.report_and_explain_type_error(trace, &err)
1536 pub fn replace_bound_vars_with_fresh_vars<T>(
1539 lbrct: LateBoundRegionConversionTime,
1540 value: &ty::Binder<T>,
1541 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1543 T: TypeFoldable<'tcx>,
1545 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1547 self.next_ty_var(TypeVariableOrigin {
1548 kind: TypeVariableOriginKind::MiscVariable,
1552 let fld_c = |_, ty| {
1553 self.next_const_var(
1555 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1558 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1561 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1562 pub fn verify_generic_bound(
1564 origin: SubregionOrigin<'tcx>,
1565 kind: GenericKind<'tcx>,
1566 a: ty::Region<'tcx>,
1567 bound: VerifyBound<'tcx>,
1569 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1573 .unwrap_region_constraints()
1574 .verify_generic_bound(origin, kind, a, bound);
1577 /// Obtains the latest type of the given closure; this may be a
1578 /// closure in the current function, in which case its
1579 /// `ClosureKind` may not yet be known.
1580 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1581 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1582 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1583 closure_kind_ty.to_opt_closure_kind()
1586 /// Clears the selection, evaluation, and projection caches. This is useful when
1587 /// repeatedly attempting to select an `Obligation` while changing only
1588 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1589 pub fn clear_caches(&self) {
1590 self.selection_cache.clear();
1591 self.evaluation_cache.clear();
1592 self.inner.borrow_mut().projection_cache().clear();
1595 fn universe(&self) -> ty::UniverseIndex {
1599 /// Creates and return a fresh universe that extends all previous
1600 /// universes. Updates `self.universe` to that new universe.
1601 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1602 let u = self.universe.get().next_universe();
1603 self.universe.set(u);
1607 /// Resolves and evaluates a constant.
1609 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1610 /// substitutions and environment are used to resolve the constant. Alternatively if the
1611 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1612 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1613 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1614 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1617 /// This handles inferences variables within both `param_env` and `substs` by
1618 /// performing the operation on their respective canonical forms.
1619 pub fn const_eval_resolve(
1621 param_env: ty::ParamEnv<'tcx>,
1623 substs: SubstsRef<'tcx>,
1624 promoted: Option<mir::Promoted>,
1626 ) -> ConstEvalResult<'tcx> {
1627 let mut original_values = OriginalQueryValues::default();
1628 let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1630 let (param_env, substs) = canonical.value;
1631 // The return value is the evaluated value which doesn't contain any reference to inference
1632 // variables, thus we don't need to substitute back the original values.
1633 self.tcx.const_eval_resolve(param_env, def_id, substs, promoted, span)
1636 /// If `typ` is a type variable of some kind, resolve it one level
1637 /// (but do not resolve types found in the result). If `typ` is
1638 /// not a type variable, just return it unmodified.
1639 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1640 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1642 ty::Infer(ty::TyVar(v)) => {
1643 // Not entirely obvious: if `typ` is a type variable,
1644 // it can be resolved to an int/float variable, which
1645 // can then be recursively resolved, hence the
1646 // recursion. Note though that we prevent type
1647 // variables from unifying to other type variables
1648 // directly (though they may be embedded
1649 // structurally), and we prevent cycles in any case,
1650 // so this recursion should always be of very limited
1653 // Note: if these two lines are combined into one we get
1654 // dynamic borrow errors on `self.inner`.
1655 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1656 known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
1659 ty::Infer(ty::IntVar(v)) => self
1662 .int_unification_table()
1664 .map(|v| v.to_type(self.tcx))
1667 ty::Infer(ty::FloatVar(v)) => self
1670 .float_unification_table()
1672 .map(|v| v.to_type(self.tcx))
1679 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1680 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1681 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1683 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1684 /// inlined, despite being large, because it has only two call sites that
1685 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1686 /// inference variables), and it handles both `Ty` and `ty::Const` without
1687 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1689 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1691 TyOrConstInferVar::Ty(v) => {
1692 use self::type_variable::TypeVariableValue;
1694 // If `inlined_probe` returns a `Known` value, it never equals
1695 // `ty::Infer(ty::TyVar(v))`.
1696 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1697 TypeVariableValue::Unknown { .. } => false,
1698 TypeVariableValue::Known { .. } => true,
1702 TyOrConstInferVar::TyInt(v) => {
1703 // If `inlined_probe_value` returns a value it's always a
1704 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1706 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1709 TyOrConstInferVar::TyFloat(v) => {
1710 // If `probe_value` returns a value it's always a
1711 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1713 // Not `inlined_probe_value(v)` because this call site is colder.
1714 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1717 TyOrConstInferVar::Const(v) => {
1718 // If `probe_value` returns a `Known` value, it never equals
1719 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1721 // Not `inlined_probe_value(v)` because this call site is colder.
1722 match self.inner.borrow_mut().const_unification_table.probe_value(v).val {
1723 ConstVariableValue::Unknown { .. } => false,
1724 ConstVariableValue::Known { .. } => true,
1731 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1732 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1733 #[derive(Copy, Clone, Debug)]
1734 pub enum TyOrConstInferVar<'tcx> {
1735 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1737 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1739 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1742 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1743 Const(ConstVid<'tcx>),
1746 impl TyOrConstInferVar<'tcx> {
1747 /// Tries to extract an inference variable from a type or a constant, returns `None`
1748 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1749 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1750 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1751 match arg.unpack() {
1752 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1753 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1754 GenericArgKind::Lifetime(_) => None,
1758 /// Tries to extract an inference variable from a type, returns `None`
1759 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1760 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1762 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1763 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1764 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1769 /// Tries to extract an inference variable from a constant, returns `None`
1770 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1771 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1773 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1779 struct ShallowResolver<'a, 'tcx> {
1780 infcx: &'a InferCtxt<'a, 'tcx>,
1783 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1784 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1788 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1789 self.infcx.shallow_resolve_ty(ty)
1792 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1793 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1797 .const_unification_table()
1808 impl<'tcx> TypeTrace<'tcx> {
1809 pub fn span(&self) -> Span {
1814 cause: &ObligationCause<'tcx>,
1815 a_is_expected: bool,
1818 ) -> TypeTrace<'tcx> {
1819 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1822 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1824 cause: ObligationCause::dummy(),
1825 values: Types(ExpectedFound { expected: tcx.types.err, found: tcx.types.err }),
1830 impl<'tcx> SubregionOrigin<'tcx> {
1831 pub fn span(&self) -> Span {
1833 Subtype(ref a) => a.span(),
1834 InfStackClosure(a) => a,
1835 InvokeClosure(a) => a,
1836 DerefPointer(a) => a,
1837 ClosureCapture(a, _) => a,
1839 RelateObjectBound(a) => a,
1840 RelateParamBound(a, _) => a,
1841 RelateRegionParamBound(a) => a,
1842 RelateDefaultParamBound(a, _) => a,
1844 ReborrowUpvar(a, _) => a,
1845 DataBorrowed(_, a) => a,
1846 ReferenceOutlivesReferent(_, a) => a,
1847 ParameterInScope(_, a) => a,
1848 ExprTypeIsNotInScope(_, a) => a,
1849 BindingTypeIsNotValidAtDecl(a) => a,
1856 SafeDestructor(a) => a,
1857 CompareImplMethodObligation { span, .. } => span,
1861 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1863 F: FnOnce() -> Self,
1866 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1867 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1870 traits::ObligationCauseCode::CompareImplMethodObligation {
1874 } => SubregionOrigin::CompareImplMethodObligation {
1886 impl RegionVariableOrigin {
1887 pub fn span(&self) -> Span {
1889 MiscVariable(a) => a,
1890 PatternRegion(a) => a,
1891 AddrOfRegion(a) => a,
1894 EarlyBoundRegion(a, ..) => a,
1895 LateBoundRegion(a, ..) => a,
1896 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1897 UpvarRegion(_, a) => a,
1898 NLL(..) => bug!("NLL variable used with `span`"),
1903 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1904 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1907 "RegionObligation(sub_region={:?}, sup_type={:?})",
1908 self.sub_region, self.sup_type