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;
43 use self::combine::CombineFields;
44 use self::free_regions::RegionRelations;
45 use self::lexical_region_resolve::LexicalRegionResolutions;
46 use self::outlives::env::OutlivesEnvironment;
47 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
48 use self::region_constraints::{
49 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
51 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
57 pub mod error_reporting;
64 mod lexical_region_resolve;
68 pub mod region_constraints;
71 pub mod type_variable;
74 use crate::infer::canonical::OriginalQueryValues;
75 pub use rustc_middle::infer::unify_key;
79 pub struct InferOk<'tcx, T> {
81 pub obligations: PredicateObligations<'tcx>,
83 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
85 pub type Bound<T> = Option<T>;
86 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
87 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
89 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
90 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
93 /// How we should handle region solving.
95 /// This is used so that the region values inferred by HIR region solving are
96 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
97 /// typeck will also do.
98 #[derive(Copy, Clone, Debug)]
99 pub enum RegionckMode {
100 /// The default mode: report region errors, don't erase regions.
102 /// Erase the results of region after solving.
104 /// A flag that is used to suppress region errors, when we are doing
105 /// region checks that the NLL borrow checker will also do -- it might
107 suppress_errors: bool,
111 impl Default for RegionckMode {
112 fn default() -> Self {
118 pub fn suppressed(self) -> bool {
120 Self::Solve => false,
121 Self::Erase { suppress_errors } => suppress_errors,
125 /// Indicates that the MIR borrowck will repeat these region
126 /// checks, so we should ignore errors if NLL is (unconditionally)
128 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
129 // FIXME(Centril): Once we actually remove `::Migrate` also make
130 // this always `true` and then proceed to eliminate the dead code.
131 match tcx.borrowck_mode() {
132 // If we're on Migrate mode, report AST region errors
133 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
135 // If we're on MIR, don't report AST region errors as they should be reported by NLL
136 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
141 /// This type contains all the things within `InferCtxt` that sit within a
142 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
143 /// operations are hot enough that we want only one call to `borrow_mut` per
144 /// call to `start_snapshot` and `rollback_to`.
145 pub struct InferCtxtInner<'tcx> {
146 /// Cache for projections. This cache is snapshotted along with the infcx.
148 /// Public so that `traits::project` can use it.
149 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
151 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
152 /// that might instantiate a general type variable have an order,
153 /// represented by its upper and lower bounds.
154 type_variables: type_variable::TypeVariableStorage<'tcx>,
156 /// Map from const parameter variable to the kind of const it represents.
157 const_unification_table: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
159 /// Map from integral variable to the kind of integer it represents.
160 int_unification_table: ut::UnificationTableStorage<ty::IntVid>,
162 /// Map from floating variable to the kind of float it represents.
163 float_unification_table: ut::UnificationTableStorage<ty::FloatVid>,
165 /// Tracks the set of region variables and the constraints between them.
166 /// This is initially `Some(_)` but when
167 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
168 /// -- further attempts to perform unification, etc., may fail if new
169 /// region constraints would've been added.
170 region_constraints: Option<RegionConstraintStorage<'tcx>>,
172 /// A set of constraints that regionck must validate. Each
173 /// constraint has the form `T:'a`, meaning "some type `T` must
174 /// outlive the lifetime 'a". These constraints derive from
175 /// instantiated type parameters. So if you had a struct defined
178 /// struct Foo<T:'static> { ... }
180 /// then in some expression `let x = Foo { ... }` it will
181 /// instantiate the type parameter `T` with a fresh type `$0`. At
182 /// the same time, it will record a region obligation of
183 /// `$0:'static`. This will get checked later by regionck. (We
184 /// can't generally check these things right away because we have
185 /// to wait until types are resolved.)
187 /// These are stored in a map keyed to the id of the innermost
188 /// enclosing fn body / static initializer expression. This is
189 /// because the location where the obligation was incurred can be
190 /// relevant with respect to which sublifetime assumptions are in
191 /// place. The reason that we store under the fn-id, and not
192 /// something more fine-grained, is so that it is easier for
193 /// regionck to be sure that it has found *all* the region
194 /// obligations (otherwise, it's easy to fail to walk to a
195 /// particular node-id).
197 /// Before running `resolve_regions_and_report_errors`, the creator
198 /// of the inference context is expected to invoke
199 /// `process_region_obligations` (defined in `self::region_obligations`)
200 /// for each body-id in this map, which will process the
201 /// obligations within. This is expected to be done 'late enough'
202 /// that all type inference variables have been bound and so forth.
203 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
205 undo_log: InferCtxtUndoLogs<'tcx>,
208 impl<'tcx> InferCtxtInner<'tcx> {
209 fn new() -> InferCtxtInner<'tcx> {
211 projection_cache: Default::default(),
212 type_variables: type_variable::TypeVariableStorage::new(),
213 undo_log: InferCtxtUndoLogs::default(),
214 const_unification_table: ut::UnificationTableStorage::new(),
215 int_unification_table: ut::UnificationTableStorage::new(),
216 float_unification_table: ut::UnificationTableStorage::new(),
217 region_constraints: Some(RegionConstraintStorage::new()),
218 region_obligations: vec![],
222 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
223 &self.region_obligations
226 pub(crate) fn projection_cache(&mut self) -> traits::ProjectionCache<'tcx, '_> {
227 self.projection_cache.with_log(&mut self.undo_log)
230 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'tcx, '_> {
231 self.type_variables.with_log(&mut self.undo_log)
234 fn int_unification_table(
236 ) -> ut::UnificationTable<
239 &mut ut::UnificationStorage<ty::IntVid>,
240 &mut InferCtxtUndoLogs<'tcx>,
243 self.int_unification_table.with_log(&mut self.undo_log)
246 fn float_unification_table(
248 ) -> ut::UnificationTable<
251 &mut ut::UnificationStorage<ty::FloatVid>,
252 &mut InferCtxtUndoLogs<'tcx>,
255 self.float_unification_table.with_log(&mut self.undo_log)
258 fn const_unification_table(
260 ) -> ut::UnificationTable<
263 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
264 &mut InferCtxtUndoLogs<'tcx>,
267 self.const_unification_table.with_log(&mut self.undo_log)
270 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'tcx, '_> {
271 self.region_constraints
273 .expect("region constraints already solved")
274 .with_log(&mut self.undo_log)
278 pub struct InferCtxt<'a, 'tcx> {
279 pub tcx: TyCtxt<'tcx>,
281 /// During type-checking/inference of a body, `in_progress_tables`
282 /// contains a reference to the tables being built up, which are
283 /// used for reading closure kinds/signatures as they are inferred,
284 /// and for error reporting logic to read arbitrary node types.
285 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
287 pub inner: RefCell<InferCtxtInner<'tcx>>,
289 /// If set, this flag causes us to skip the 'leak check' during
290 /// higher-ranked subtyping operations. This flag is a temporary one used
291 /// to manage the removal of the leak-check: for the time being, we still run the
292 /// leak-check, but we issue warnings. This flag can only be set to true
293 /// when entering a snapshot.
294 skip_leak_check: Cell<bool>,
296 /// Once region inference is done, the values for each variable.
297 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
299 /// Caches the results of trait selection. This cache is used
300 /// for things that have to do with the parameters in scope.
301 pub selection_cache: select::SelectionCache<'tcx>,
303 /// Caches the results of trait evaluation.
304 pub evaluation_cache: select::EvaluationCache<'tcx>,
306 /// the set of predicates on which errors have been reported, to
307 /// avoid reporting the same error twice.
308 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
310 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
312 /// When an error occurs, we want to avoid reporting "derived"
313 /// errors that are due to this original failure. Normally, we
314 /// handle this with the `err_count_on_creation` count, which
315 /// basically just tracks how many errors were reported when we
316 /// started type-checking a fn and checks to see if any new errors
317 /// have been reported since then. Not great, but it works.
319 /// However, when errors originated in other passes -- notably
320 /// resolve -- this heuristic breaks down. Therefore, we have this
321 /// auxiliary flag that one can set whenever one creates a
322 /// type-error that is due to an error in a prior pass.
324 /// Don't read this flag directly, call `is_tainted_by_errors()`
325 /// and `set_tainted_by_errors()`.
326 tainted_by_errors_flag: Cell<bool>,
328 /// Track how many errors were reported when this infcx is created.
329 /// If the number of errors increases, that's also a sign (line
330 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
331 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
332 err_count_on_creation: usize,
334 /// This flag is true while there is an active snapshot.
335 in_snapshot: Cell<bool>,
337 /// What is the innermost universe we have created? Starts out as
338 /// `UniverseIndex::root()` but grows from there as we enter
339 /// universal quantifiers.
341 /// N.B., at present, we exclude the universal quantifiers on the
342 /// item we are type-checking, and just consider those names as
343 /// part of the root universe. So this would only get incremented
344 /// when we enter into a higher-ranked (`for<..>`) type or trait
346 universe: Cell<ty::UniverseIndex>,
349 /// A map returned by `replace_bound_vars_with_placeholders()`
350 /// indicating the placeholder region that each late-bound region was
352 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
354 /// See the `error_reporting` module for more details.
355 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
356 pub enum ValuePairs<'tcx> {
357 Types(ExpectedFound<Ty<'tcx>>),
358 Regions(ExpectedFound<ty::Region<'tcx>>),
359 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
360 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
361 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
364 /// The trace designates the path through inference that we took to
365 /// encounter an error or subtyping constraint.
367 /// See the `error_reporting` module for more details.
368 #[derive(Clone, Debug)]
369 pub struct TypeTrace<'tcx> {
370 cause: ObligationCause<'tcx>,
371 values: ValuePairs<'tcx>,
374 /// The origin of a `r1 <= r2` constraint.
376 /// See `error_reporting` module for more details
377 #[derive(Clone, Debug)]
378 pub enum SubregionOrigin<'tcx> {
379 /// Arose from a subtyping relation
380 Subtype(Box<TypeTrace<'tcx>>),
382 /// Stack-allocated closures cannot outlive innermost loop
383 /// or function so as to ensure we only require finite stack
384 InfStackClosure(Span),
386 /// Invocation of closure must be within its lifetime
389 /// Dereference of reference must be within its lifetime
392 /// Closure bound must not outlive captured variables
393 ClosureCapture(Span, hir::HirId),
395 /// Index into slice must be within its lifetime
398 /// When casting `&'a T` to an `&'b Trait` object,
399 /// relating `'a` to `'b`
400 RelateObjectBound(Span),
402 /// Some type parameter was instantiated with the given type,
403 /// and that type must outlive some region.
404 RelateParamBound(Span, Ty<'tcx>),
406 /// The given region parameter was instantiated with a region
407 /// that must outlive some other region.
408 RelateRegionParamBound(Span),
410 /// A bound placed on type parameters that states that must outlive
411 /// the moment of their instantiation.
412 RelateDefaultParamBound(Span, Ty<'tcx>),
414 /// Creating a pointer `b` to contents of another reference
417 /// Creating a pointer `b` to contents of an upvar
418 ReborrowUpvar(Span, ty::UpvarId),
420 /// Data with type `Ty<'tcx>` was borrowed
421 DataBorrowed(Ty<'tcx>, Span),
423 /// (&'a &'b T) where a >= b
424 ReferenceOutlivesReferent(Ty<'tcx>, Span),
426 /// Type or region parameters must be in scope.
427 ParameterInScope(ParameterOrigin, Span),
429 /// The type T of an expression E must outlive the lifetime for E.
430 ExprTypeIsNotInScope(Ty<'tcx>, Span),
432 /// A `ref b` whose region does not enclose the decl site
433 BindingTypeIsNotValidAtDecl(Span),
435 /// Regions appearing in a method receiver must outlive method call
438 /// Regions appearing in a function argument must outlive func call
441 /// Region in return type of invoked fn must enclose call
444 /// Operands must be in scope
447 /// Region resulting from a `&` expr must enclose the `&` expr
450 /// An auto-borrow that does not enclose the expr where it occurs
453 /// Region constraint arriving from destructor safety
454 SafeDestructor(Span),
456 /// Comparing the signature and requirements of an impl method against
457 /// the containing trait.
458 CompareImplMethodObligation {
460 item_name: ast::Name,
461 impl_item_def_id: DefId,
462 trait_item_def_id: DefId,
466 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
467 #[cfg(target_arch = "x86_64")]
468 static_assert_size!(SubregionOrigin<'_>, 32);
470 /// Places that type/region parameters can appear.
471 #[derive(Clone, Copy, Debug)]
472 pub enum ParameterOrigin {
474 MethodCall, // foo.bar() <-- parameters on impl providing bar()
475 OverloadedOperator, // a + b when overloaded
476 OverloadedDeref, // *a when overloaded
479 /// Times when we replace late-bound regions with variables:
480 #[derive(Clone, Copy, Debug)]
481 pub enum LateBoundRegionConversionTime {
482 /// when a fn is called
485 /// when two higher-ranked types are compared
488 /// when projecting an associated type
489 AssocTypeProjection(DefId),
492 /// Reasons to create a region inference variable
494 /// See `error_reporting` module for more details
495 #[derive(Copy, Clone, Debug)]
496 pub enum RegionVariableOrigin {
497 /// Region variables created for ill-categorized reasons,
498 /// mostly indicates places in need of refactoring
501 /// Regions created by a `&P` or `[...]` pattern
504 /// Regions created by `&` operator
507 /// Regions created as part of an autoref of a method receiver
510 /// Regions created as part of an automatic coercion
513 /// Region variables created as the values for early-bound regions
514 EarlyBoundRegion(Span, Symbol),
516 /// Region variables created for bound regions
517 /// in a function or method that is called
518 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
520 UpvarRegion(ty::UpvarId, Span),
522 BoundRegionInCoherence(ast::Name),
524 /// This origin is used for the inference variables that we create
525 /// during NLL region processing.
526 NLL(NLLRegionVariableOrigin),
529 #[derive(Copy, Clone, Debug)]
530 pub enum NLLRegionVariableOrigin {
531 /// During NLL region processing, we create variables for free
532 /// regions that we encounter in the function signature and
533 /// elsewhere. This origin indices we've got one of those.
536 /// "Universal" instantiation of a higher-ranked region (e.g.,
537 /// from a `for<'a> T` binder). Meant to represent "any region".
538 Placeholder(ty::PlaceholderRegion),
540 /// The variable we create to represent `'empty(U0)`.
544 /// If this is true, then this variable was created to represent a lifetime
545 /// bound in a `for` binder. For example, it might have been created to
546 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
547 /// Such variables are created when we are trying to figure out if there
548 /// is any valid instantiation of `'a` that could fit into some scenario.
550 /// This is used to inform error reporting: in the case that we are trying to
551 /// determine whether there is any valid instantiation of a `'a` variable that meets
552 /// some constraint C, we want to blame the "source" of that `for` type,
553 /// rather than blaming the source of the constraint C.
558 impl NLLRegionVariableOrigin {
559 pub fn is_universal(self) -> bool {
561 NLLRegionVariableOrigin::FreeRegion => true,
562 NLLRegionVariableOrigin::Placeholder(..) => true,
563 NLLRegionVariableOrigin::Existential { .. } => false,
564 NLLRegionVariableOrigin::RootEmptyRegion => false,
568 pub fn is_existential(self) -> bool {
573 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
574 #[derive(Copy, Clone, Debug)]
575 pub enum FixupError<'tcx> {
576 UnresolvedIntTy(IntVid),
577 UnresolvedFloatTy(FloatVid),
579 UnresolvedConst(ConstVid<'tcx>),
582 /// See the `region_obligations` field for more information.
584 pub struct RegionObligation<'tcx> {
585 pub sub_region: ty::Region<'tcx>,
586 pub sup_type: Ty<'tcx>,
587 pub origin: SubregionOrigin<'tcx>,
590 impl<'tcx> fmt::Display for FixupError<'tcx> {
591 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592 use self::FixupError::*;
595 UnresolvedIntTy(_) => write!(
597 "cannot determine the type of this integer; \
598 add a suffix to specify the type explicitly"
600 UnresolvedFloatTy(_) => write!(
602 "cannot determine the type of this number; \
603 add a suffix to specify the type explicitly"
605 UnresolvedTy(_) => write!(f, "unconstrained type"),
606 UnresolvedConst(_) => write!(f, "unconstrained const value"),
611 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
612 /// Necessary because we can't write the following bound:
613 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
614 pub struct InferCtxtBuilder<'tcx> {
615 global_tcx: TyCtxt<'tcx>,
616 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
619 pub trait TyCtxtInferExt<'tcx> {
620 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
623 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
624 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
625 InferCtxtBuilder { global_tcx: self, fresh_tables: None }
629 impl<'tcx> InferCtxtBuilder<'tcx> {
630 /// Used only by `rustc_typeck` during body type-checking/inference,
631 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
632 pub fn with_fresh_in_progress_tables(mut self, table_owner: LocalDefId) -> Self {
633 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
637 /// Given a canonical value `C` as a starting point, create an
638 /// inference context that contains each of the bound values
639 /// within instantiated as a fresh variable. The `f` closure is
640 /// invoked with the new infcx, along with the instantiated value
641 /// `V` and a substitution `S`. This substitution `S` maps from
642 /// the bound values in `C` to their instantiated values in `V`
643 /// (in other words, `S(C) = V`).
644 pub fn enter_with_canonical<T, R>(
647 canonical: &Canonical<'tcx, T>,
648 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
651 T: TypeFoldable<'tcx>,
655 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
656 f(infcx, value, subst)
660 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
661 let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
662 let in_progress_tables = fresh_tables.as_ref();
663 global_tcx.enter_local(|tcx| {
667 inner: RefCell::new(InferCtxtInner::new()),
668 lexical_region_resolutions: RefCell::new(None),
669 selection_cache: Default::default(),
670 evaluation_cache: Default::default(),
671 reported_trait_errors: Default::default(),
672 reported_closure_mismatch: Default::default(),
673 tainted_by_errors_flag: Cell::new(false),
674 err_count_on_creation: tcx.sess.err_count(),
675 in_snapshot: Cell::new(false),
676 skip_leak_check: Cell::new(false),
677 universe: Cell::new(ty::UniverseIndex::ROOT),
683 impl<'tcx, T> InferOk<'tcx, T> {
684 pub fn unit(self) -> InferOk<'tcx, ()> {
685 InferOk { value: (), obligations: self.obligations }
688 /// Extracts `value`, registering any obligations into `fulfill_cx`.
689 pub fn into_value_registering_obligations(
691 infcx: &InferCtxt<'_, 'tcx>,
692 fulfill_cx: &mut dyn TraitEngine<'tcx>,
694 let InferOk { value, obligations } = self;
695 for obligation in obligations {
696 fulfill_cx.register_predicate_obligation(infcx, obligation);
702 impl<'tcx> InferOk<'tcx, ()> {
703 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
708 #[must_use = "once you start a snapshot, you should always consume it"]
709 pub struct FullSnapshot<'a, 'tcx> {
710 snapshot: CombinedSnapshot<'a, 'tcx>,
711 region_constraints_snapshot: RegionSnapshot,
712 type_snapshot: type_variable::Snapshot<'tcx>,
713 const_var_len: usize,
715 float_var_len: usize,
718 #[must_use = "once you start a snapshot, you should always consume it"]
719 pub struct CombinedSnapshot<'a, 'tcx> {
720 undo_snapshot: Snapshot<'tcx>,
721 universe: ty::UniverseIndex,
722 was_in_snapshot: bool,
723 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
726 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
727 pub fn is_in_snapshot(&self) -> bool {
728 self.in_snapshot.get()
731 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
732 t.fold_with(&mut self.freshener())
735 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
737 ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
742 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
743 freshen::TypeFreshener::new(self)
746 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
747 use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
748 use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
750 ty::Infer(ty::IntVar(vid)) => {
751 if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
757 ty::Infer(ty::FloatVar(vid)) => {
758 if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
768 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
769 let mut inner = self.inner.borrow_mut();
770 // FIXME(const_generics): should there be an equivalent function for const variables?
772 let mut vars: Vec<Ty<'_>> = inner
774 .unsolved_variables()
776 .map(|t| self.tcx.mk_ty_var(t))
779 (0..inner.int_unification_table().len())
780 .map(|i| ty::IntVid { index: i as u32 })
781 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
782 .map(|v| self.tcx.mk_int_var(v)),
785 (0..inner.float_unification_table().len())
786 .map(|i| ty::FloatVid { index: i as u32 })
787 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
788 .map(|v| self.tcx.mk_float_var(v)),
795 trace: TypeTrace<'tcx>,
796 param_env: ty::ParamEnv<'tcx>,
797 ) -> CombineFields<'a, 'tcx> {
803 obligations: PredicateObligations::new(),
807 /// Clear the "currently in a snapshot" flag, invoke the closure,
808 /// then restore the flag to its original value. This flag is a
809 /// debugging measure designed to detect cases where we start a
810 /// snapshot, create type variables, and register obligations
811 /// which may involve those type variables in the fulfillment cx,
812 /// potentially leaving "dangling type variables" behind.
813 /// In such cases, an assertion will fail when attempting to
814 /// register obligations, within a snapshot. Very useful, much
815 /// better than grovelling through megabytes of `RUSTC_LOG` output.
817 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
818 /// sometimes create a "mini-fulfilment-cx" in which we enroll
819 /// obligations. As long as this fulfillment cx is fully drained
820 /// before we return, this is not a problem, as there won't be any
821 /// escaping obligations in the main cx. In those cases, you can
822 /// use this function.
823 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
825 F: FnOnce(&Self) -> R,
827 let flag = self.in_snapshot.replace(false);
828 let result = func(self);
829 self.in_snapshot.set(flag);
833 fn start_full_snapshot(&self) -> FullSnapshot<'a, 'tcx> {
834 let snapshot = self.start_snapshot();
835 let mut inner = self.inner.borrow_mut();
838 type_snapshot: inner.type_variables().snapshot(),
839 const_var_len: inner.const_unification_table().len(),
840 int_var_len: inner.int_unification_table().len(),
841 float_var_len: inner.float_unification_table().len(),
842 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
846 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
847 debug!("start_snapshot()");
849 let in_snapshot = self.in_snapshot.replace(true);
851 let mut inner = self.inner.borrow_mut();
854 undo_snapshot: inner.undo_log.start_snapshot(),
855 universe: self.universe(),
856 was_in_snapshot: in_snapshot,
857 // Borrow tables "in progress" (i.e., during typeck)
858 // to ban writes from within a snapshot to them.
859 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
863 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
864 debug!("rollback_to(cause={})", cause);
865 let CombinedSnapshot { undo_snapshot, universe, was_in_snapshot, _in_progress_tables } =
868 self.in_snapshot.set(was_in_snapshot);
869 self.universe.set(universe);
873 const_unification_table,
874 int_unification_table,
875 float_unification_table,
881 } = &mut *self.inner.borrow_mut();
882 undo_log.rollback_to(
883 || undo_log::RollbackView {
885 const_unification_table,
886 int_unification_table,
887 float_unification_table,
888 region_constraints: region_constraints.as_mut().unwrap(),
896 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
897 debug!("commit_from()");
898 let CombinedSnapshot { undo_snapshot, universe: _, was_in_snapshot, _in_progress_tables } =
901 self.in_snapshot.set(was_in_snapshot);
903 let mut inner = self.inner.borrow_mut();
904 inner.undo_log.commit(undo_snapshot);
907 /// Executes `f` and commit the bindings.
908 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
910 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
912 debug!("commit_unconditionally()");
913 let snapshot = self.start_snapshot();
914 let r = f(&snapshot);
915 self.commit_from(snapshot);
919 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
920 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
922 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
924 debug!("commit_if_ok()");
925 let snapshot = self.start_snapshot();
926 let r = f(&snapshot);
927 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
930 self.commit_from(snapshot);
933 self.rollback_to("commit_if_ok -- error", snapshot);
939 /// Execute `f` then unroll any bindings it creates.
940 pub fn probe<R, F>(&self, f: F) -> R
942 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
945 let snapshot = self.start_snapshot();
946 let r = f(&snapshot);
947 self.rollback_to("probe", snapshot);
951 pub fn probe_full<R, F>(&self, f: F) -> R
953 F: FnOnce(&FullSnapshot<'a, 'tcx>) -> R,
956 let snapshot = self.start_full_snapshot();
957 let r = f(&snapshot);
958 self.rollback_to("probe", snapshot.snapshot);
962 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
963 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
965 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
968 let snapshot = self.start_snapshot();
969 let was_skip_leak_check = self.skip_leak_check.get();
971 self.skip_leak_check.set(true);
973 let r = f(&snapshot);
974 self.rollback_to("probe", snapshot);
975 self.skip_leak_check.set(was_skip_leak_check);
979 /// Scan the constraints produced since `snapshot` began and returns:
981 /// - `None` -- if none of them involve "region outlives" constraints
982 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
983 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
984 pub fn region_constraints_added_in_snapshot(
986 snapshot: &CombinedSnapshot<'a, 'tcx>,
990 .unwrap_region_constraints()
991 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
994 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
995 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
998 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
1000 T: at::ToTrace<'tcx>,
1002 let origin = &ObligationCause::dummy();
1004 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
1005 // Ignore obligations, since we are unrolling
1006 // everything anyway.
1011 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
1013 T: at::ToTrace<'tcx>,
1015 let origin = &ObligationCause::dummy();
1017 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
1018 // Ignore obligations, since we are unrolling
1019 // everything anyway.
1026 origin: SubregionOrigin<'tcx>,
1027 a: ty::Region<'tcx>,
1028 b: ty::Region<'tcx>,
1030 debug!("sub_regions({:?} <: {:?})", a, b);
1031 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
1034 /// Require that the region `r` be equal to one of the regions in
1035 /// the set `regions`.
1036 pub fn member_constraint(
1038 opaque_type_def_id: DefId,
1039 definition_span: Span,
1040 hidden_ty: Ty<'tcx>,
1041 region: ty::Region<'tcx>,
1042 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
1044 debug!("member_constraint({:?} <: {:?})", region, in_regions);
1045 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
1054 pub fn subtype_predicate(
1056 cause: &ObligationCause<'tcx>,
1057 param_env: ty::ParamEnv<'tcx>,
1058 predicate: &ty::PolySubtypePredicate<'tcx>,
1059 ) -> Option<InferResult<'tcx, ()>> {
1060 // Subtle: it's ok to skip the binder here and resolve because
1061 // `shallow_resolve` just ignores anything that is not a type
1062 // variable, and because type variable's can't (at present, at
1063 // least) capture any of the things bound by this binder.
1065 // NOTE(nmatsakis): really, there is no *particular* reason to do this
1066 // `shallow_resolve` here except as a micro-optimization.
1067 // Naturally I could not resist.
1068 let two_unbound_type_vars = {
1069 let a = self.shallow_resolve(predicate.skip_binder().a);
1070 let b = self.shallow_resolve(predicate.skip_binder().b);
1071 a.is_ty_var() && b.is_ty_var()
1074 if two_unbound_type_vars {
1075 // Two unbound type variables? Can't make progress.
1079 Some(self.commit_if_ok(|snapshot| {
1080 let (ty::SubtypePredicate { a_is_expected, a, b }, placeholder_map) =
1081 self.replace_bound_vars_with_placeholders(predicate);
1083 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1085 self.leak_check(false, &placeholder_map, snapshot)?;
1091 pub fn region_outlives_predicate(
1093 cause: &traits::ObligationCause<'tcx>,
1094 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
1095 ) -> UnitResult<'tcx> {
1096 self.commit_if_ok(|snapshot| {
1097 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
1098 self.replace_bound_vars_with_placeholders(predicate);
1099 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1100 RelateRegionParamBound(cause.span)
1102 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1103 self.leak_check(false, &placeholder_map, snapshot)?;
1108 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1109 self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
1112 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1113 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1116 pub fn next_ty_var_in_universe(
1118 origin: TypeVariableOrigin,
1119 universe: ty::UniverseIndex,
1121 let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
1122 self.tcx.mk_ty_var(vid)
1125 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1126 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1129 pub fn next_const_var(
1132 origin: ConstVariableOrigin,
1133 ) -> &'tcx ty::Const<'tcx> {
1134 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1137 pub fn next_const_var_in_universe(
1140 origin: ConstVariableOrigin,
1141 universe: ty::UniverseIndex,
1142 ) -> &'tcx ty::Const<'tcx> {
1146 .const_unification_table()
1147 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1148 self.tcx.mk_const_var(vid, ty)
1151 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1152 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1154 val: ConstVariableValue::Unknown { universe: self.universe() },
1158 fn next_int_var_id(&self) -> IntVid {
1159 self.inner.borrow_mut().int_unification_table().new_key(None)
1162 pub fn next_int_var(&self) -> Ty<'tcx> {
1163 self.tcx.mk_int_var(self.next_int_var_id())
1166 fn next_float_var_id(&self) -> FloatVid {
1167 self.inner.borrow_mut().float_unification_table().new_key(None)
1170 pub fn next_float_var(&self) -> Ty<'tcx> {
1171 self.tcx.mk_float_var(self.next_float_var_id())
1174 /// Creates a fresh region variable with the next available index.
1175 /// The variable will be created in the maximum universe created
1176 /// thus far, allowing it to name any region created thus far.
1177 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1178 self.next_region_var_in_universe(origin, self.universe())
1181 /// Creates a fresh region variable with the next available index
1182 /// in the given universe; typically, you can use
1183 /// `next_region_var` and just use the maximal universe.
1184 pub fn next_region_var_in_universe(
1186 origin: RegionVariableOrigin,
1187 universe: ty::UniverseIndex,
1188 ) -> ty::Region<'tcx> {
1190 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1191 self.tcx.mk_region(ty::ReVar(region_var))
1194 /// Return the universe that the region `r` was created in. For
1195 /// most regions (e.g., `'static`, named regions from the user,
1196 /// etc) this is the root universe U0. For inference variables or
1197 /// placeholders, however, it will return the universe which which
1198 /// they are associated.
1199 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1200 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1203 /// Number of region variables created so far.
1204 pub fn num_region_vars(&self) -> usize {
1205 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1208 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1209 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1210 self.next_region_var(RegionVariableOrigin::NLL(origin))
1213 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1214 pub fn next_nll_region_var_in_universe(
1216 origin: NLLRegionVariableOrigin,
1217 universe: ty::UniverseIndex,
1218 ) -> ty::Region<'tcx> {
1219 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1222 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1224 GenericParamDefKind::Lifetime => {
1225 // Create a region inference variable for the given
1226 // region parameter definition.
1227 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1229 GenericParamDefKind::Type { .. } => {
1230 // Create a type inference variable for the given
1231 // type parameter definition. The substitutions are
1232 // for actual parameters that may be referred to by
1233 // the default of this type parameter, if it exists.
1234 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1235 // used in a path such as `Foo::<T, U>::new()` will
1236 // use an inference variable for `C` with `[T, U]`
1237 // as the substitutions for the default, `(T, U)`.
1238 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1241 TypeVariableOrigin {
1242 kind: TypeVariableOriginKind::TypeParameterDefinition(
1250 self.tcx.mk_ty_var(ty_var_id).into()
1252 GenericParamDefKind::Const { .. } => {
1253 let origin = ConstVariableOrigin {
1254 kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1258 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1260 val: ConstVariableValue::Unknown { universe: self.universe() },
1262 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1267 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1268 /// type/region parameter to a fresh inference variable.
1269 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1270 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1273 /// Returns `true` if errors have been reported since this infcx was
1274 /// created. This is sometimes used as a heuristic to skip
1275 /// reporting errors that often occur as a result of earlier
1276 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1277 /// inference variables, regionck errors).
1278 pub fn is_tainted_by_errors(&self) -> bool {
1280 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1281 tainted_by_errors_flag={})",
1282 self.tcx.sess.err_count(),
1283 self.err_count_on_creation,
1284 self.tainted_by_errors_flag.get()
1287 if self.tcx.sess.err_count() > self.err_count_on_creation {
1288 return true; // errors reported since this infcx was made
1290 self.tainted_by_errors_flag.get()
1293 /// Set the "tainted by errors" flag to true. We call this when we
1294 /// observe an error from a prior pass.
1295 pub fn set_tainted_by_errors(&self) {
1296 debug!("set_tainted_by_errors()");
1297 self.tainted_by_errors_flag.set(true)
1300 /// Process the region constraints and report any errors that
1301 /// result. After this, no more unification operations should be
1302 /// done -- or the compiler will panic -- but it is legal to use
1303 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1304 pub fn resolve_regions_and_report_errors(
1306 region_context: DefId,
1307 region_map: ®ion::ScopeTree,
1308 outlives_env: &OutlivesEnvironment<'tcx>,
1312 self.is_tainted_by_errors() || self.inner.borrow().region_obligations.is_empty(),
1313 "region_obligations not empty: {:#?}",
1314 self.inner.borrow().region_obligations
1316 let (var_infos, data) = self
1321 .expect("regions already resolved")
1322 .with_log(&mut inner.undo_log)
1323 .into_infos_and_data();
1325 let region_rels = &RegionRelations::new(
1329 outlives_env.free_region_map(),
1332 let (lexical_region_resolutions, errors) =
1333 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1335 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1336 assert!(old_value.is_none());
1338 if !self.is_tainted_by_errors() {
1339 // As a heuristic, just skip reporting region errors
1340 // altogether if other errors have been reported while
1341 // this infcx was in use. This is totally hokey but
1342 // otherwise we have a hard time separating legit region
1343 // errors from silly ones.
1344 self.report_region_errors(region_map, &errors);
1348 /// Obtains (and clears) the current set of region
1349 /// constraints. The inference context is still usable: further
1350 /// unifications will simply add new constraints.
1352 /// This method is not meant to be used with normal lexical region
1353 /// resolution. Rather, it is used in the NLL mode as a kind of
1354 /// interim hack: basically we run normal type-check and generate
1355 /// region constraints as normal, but then we take them and
1356 /// translate them into the form that the NLL solver
1357 /// understands. See the NLL module for mode details.
1358 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1360 self.inner.borrow().region_obligations.is_empty(),
1361 "region_obligations not empty: {:#?}",
1362 self.inner.borrow().region_obligations
1365 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1368 /// Gives temporary access to the region constraint data.
1369 #[allow(non_camel_case_types)] // bug with impl trait
1370 pub fn with_region_constraints<R>(
1372 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1374 let mut inner = self.inner.borrow_mut();
1375 op(inner.unwrap_region_constraints().data())
1378 /// Takes ownership of the list of variable regions. This implies
1379 /// that all the region constraints have already been taken, and
1380 /// hence that `resolve_regions_and_report_errors` can never be
1381 /// called. This is used only during NLL processing to "hand off" ownership
1382 /// of the set of region variables into the NLL region context.
1383 pub fn take_region_var_origins(&self) -> VarInfos {
1384 let mut inner = self.inner.borrow_mut();
1385 let (var_infos, data) = inner
1388 .expect("regions already resolved")
1389 .with_log(&mut inner.undo_log)
1390 .into_infos_and_data();
1391 assert!(data.is_empty());
1395 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1396 self.resolve_vars_if_possible(&t).to_string()
1399 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1400 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1401 format!("({})", tstrs.join(", "))
1404 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1405 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1408 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1409 /// universe index of `TyVar(vid)`.
1410 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1411 use self::type_variable::TypeVariableValue;
1413 match self.inner.borrow_mut().type_variables().probe(vid) {
1414 TypeVariableValue::Known { value } => Ok(value),
1415 TypeVariableValue::Unknown { universe } => Err(universe),
1419 /// Resolve any type variables found in `value` -- but only one
1420 /// level. So, if the variable `?X` is bound to some type
1421 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1422 /// itself be bound to a type).
1424 /// Useful when you only need to inspect the outermost level of
1425 /// the type and don't care about nested types (or perhaps you
1426 /// will be resolving them as well, e.g. in a loop).
1427 pub fn shallow_resolve<T>(&self, value: T) -> T
1429 T: TypeFoldable<'tcx>,
1431 value.fold_with(&mut ShallowResolver { infcx: self })
1434 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1435 self.inner.borrow_mut().type_variables().root_var(var)
1438 /// Where possible, replaces type/const variables in
1439 /// `value` with their final value. Note that region variables
1440 /// are unaffected. If a type/const variable has not been unified, it
1441 /// is left as is. This is an idempotent operation that does
1442 /// not affect inference state in any way and so you can do it
1444 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1446 T: TypeFoldable<'tcx>,
1448 if !value.needs_infer() {
1449 return value.clone(); // Avoid duplicated subst-folding.
1451 let mut r = resolve::OpportunisticVarResolver::new(self);
1452 value.fold_with(&mut r)
1455 /// Returns the first unresolved variable contained in `T`. In the
1456 /// process of visiting `T`, this will resolve (where possible)
1457 /// type variables in `T`, but it never constructs the final,
1458 /// resolved type, so it's more efficient than
1459 /// `resolve_vars_if_possible()`.
1460 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1462 T: TypeFoldable<'tcx>,
1464 let mut r = resolve::UnresolvedTypeFinder::new(self);
1465 value.visit_with(&mut r);
1469 pub fn probe_const_var(
1471 vid: ty::ConstVid<'tcx>,
1472 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1473 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1474 ConstVariableValue::Known { value } => Ok(value),
1475 ConstVariableValue::Unknown { universe } => Err(universe),
1479 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1481 * Attempts to resolve all type/region/const variables in
1482 * `value`. Region inference must have been run already (e.g.,
1483 * by calling `resolve_regions_and_report_errors`). If some
1484 * variable was never unified, an `Err` results.
1486 * This method is idempotent, but it not typically not invoked
1487 * except during the writeback phase.
1490 resolve::fully_resolve(self, value)
1493 // [Note-Type-error-reporting]
1494 // An invariant is that anytime the expected or actual type is Error (the special
1495 // error type, meaning that an error occurred when typechecking this expression),
1496 // this is a derived error. The error cascaded from another error (that was already
1497 // reported), so it's not useful to display it to the user.
1498 // The following methods implement this logic.
1499 // They check if either the actual or expected type is Error, and don't print the error
1500 // in this case. The typechecker should only ever report type errors involving mismatched
1501 // types using one of these methods, and should not call span_err directly for such
1504 pub fn type_error_struct_with_diag<M>(
1508 actual_ty: Ty<'tcx>,
1509 ) -> DiagnosticBuilder<'tcx>
1511 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1513 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1514 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1516 // Don't report an error if actual type is `Error`.
1517 if actual_ty.references_error() {
1518 return self.tcx.sess.diagnostic().struct_dummy();
1521 mk_diag(self.ty_to_string(actual_ty))
1524 pub fn report_mismatched_types(
1526 cause: &ObligationCause<'tcx>,
1529 err: TypeError<'tcx>,
1530 ) -> DiagnosticBuilder<'tcx> {
1531 let trace = TypeTrace::types(cause, true, expected, actual);
1532 self.report_and_explain_type_error(trace, &err)
1535 pub fn replace_bound_vars_with_fresh_vars<T>(
1538 lbrct: LateBoundRegionConversionTime,
1539 value: &ty::Binder<T>,
1540 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1542 T: TypeFoldable<'tcx>,
1544 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1546 self.next_ty_var(TypeVariableOrigin {
1547 kind: TypeVariableOriginKind::MiscVariable,
1551 let fld_c = |_, ty| {
1552 self.next_const_var(
1554 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1557 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1560 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1561 pub fn verify_generic_bound(
1563 origin: SubregionOrigin<'tcx>,
1564 kind: GenericKind<'tcx>,
1565 a: ty::Region<'tcx>,
1566 bound: VerifyBound<'tcx>,
1568 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1572 .unwrap_region_constraints()
1573 .verify_generic_bound(origin, kind, a, bound);
1576 /// Obtains the latest type of the given closure; this may be a
1577 /// closure in the current function, in which case its
1578 /// `ClosureKind` may not yet be known.
1579 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1580 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1581 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1582 closure_kind_ty.to_opt_closure_kind()
1585 /// Clears the selection, evaluation, and projection caches. This is useful when
1586 /// repeatedly attempting to select an `Obligation` while changing only
1587 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1588 pub fn clear_caches(&self) {
1589 self.selection_cache.clear();
1590 self.evaluation_cache.clear();
1591 self.inner.borrow_mut().projection_cache().clear();
1594 fn universe(&self) -> ty::UniverseIndex {
1598 /// Creates and return a fresh universe that extends all previous
1599 /// universes. Updates `self.universe` to that new universe.
1600 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1601 let u = self.universe.get().next_universe();
1602 self.universe.set(u);
1606 /// Resolves and evaluates a constant.
1608 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1609 /// substitutions and environment are used to resolve the constant. Alternatively if the
1610 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1611 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1612 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1613 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1616 /// This handles inferences variables within both `param_env` and `substs` by
1617 /// performing the operation on their respective canonical forms.
1618 pub fn const_eval_resolve(
1620 param_env: ty::ParamEnv<'tcx>,
1622 substs: SubstsRef<'tcx>,
1623 promoted: Option<mir::Promoted>,
1625 ) -> ConstEvalResult<'tcx> {
1626 let mut original_values = OriginalQueryValues::default();
1627 let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1629 let (param_env, substs) = canonical.value;
1630 // The return value is the evaluated value which doesn't contain any reference to inference
1631 // variables, thus we don't need to substitute back the original values.
1632 self.tcx.const_eval_resolve(param_env, def_id, substs, promoted, span)
1635 /// If `typ` is a type variable of some kind, resolve it one level
1636 /// (but do not resolve types found in the result). If `typ` is
1637 /// not a type variable, just return it unmodified.
1638 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1639 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1641 ty::Infer(ty::TyVar(v)) => {
1642 // Not entirely obvious: if `typ` is a type variable,
1643 // it can be resolved to an int/float variable, which
1644 // can then be recursively resolved, hence the
1645 // recursion. Note though that we prevent type
1646 // variables from unifying to other type variables
1647 // directly (though they may be embedded
1648 // structurally), and we prevent cycles in any case,
1649 // so this recursion should always be of very limited
1652 // Note: if these two lines are combined into one we get
1653 // dynamic borrow errors on `self.inner`.
1654 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1655 known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
1658 ty::Infer(ty::IntVar(v)) => self
1661 .int_unification_table()
1663 .map(|v| v.to_type(self.tcx))
1666 ty::Infer(ty::FloatVar(v)) => self
1669 .float_unification_table()
1671 .map(|v| v.to_type(self.tcx))
1678 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1679 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1680 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1682 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1683 /// inlined, despite being large, because it has only two call sites that
1684 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1685 /// inference variables), and it handles both `Ty` and `ty::Const` without
1686 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1688 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1690 TyOrConstInferVar::Ty(v) => {
1691 use self::type_variable::TypeVariableValue;
1693 // If `inlined_probe` returns a `Known` value, it never equals
1694 // `ty::Infer(ty::TyVar(v))`.
1695 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1696 TypeVariableValue::Unknown { .. } => false,
1697 TypeVariableValue::Known { .. } => true,
1701 TyOrConstInferVar::TyInt(v) => {
1702 // If `inlined_probe_value` returns a value it's always a
1703 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1705 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1708 TyOrConstInferVar::TyFloat(v) => {
1709 // If `probe_value` returns a value it's always a
1710 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1712 // Not `inlined_probe_value(v)` because this call site is colder.
1713 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1716 TyOrConstInferVar::Const(v) => {
1717 // If `probe_value` returns a `Known` value, it never equals
1718 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1720 // Not `inlined_probe_value(v)` because this call site is colder.
1721 match self.inner.borrow_mut().const_unification_table.probe_value(v).val {
1722 ConstVariableValue::Unknown { .. } => false,
1723 ConstVariableValue::Known { .. } => true,
1730 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1731 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1732 #[derive(Copy, Clone, Debug)]
1733 pub enum TyOrConstInferVar<'tcx> {
1734 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1736 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1738 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1741 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1742 Const(ConstVid<'tcx>),
1745 impl TyOrConstInferVar<'tcx> {
1746 /// Tries to extract an inference variable from a type or a constant, returns `None`
1747 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1748 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1749 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1750 match arg.unpack() {
1751 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1752 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1753 GenericArgKind::Lifetime(_) => None,
1757 /// Tries to extract an inference variable from a type, returns `None`
1758 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1759 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1761 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1762 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1763 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1768 /// Tries to extract an inference variable from a constant, returns `None`
1769 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1770 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1772 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1778 struct ShallowResolver<'a, 'tcx> {
1779 infcx: &'a InferCtxt<'a, 'tcx>,
1782 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1783 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1787 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1788 self.infcx.shallow_resolve_ty(ty)
1791 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1792 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1796 .const_unification_table()
1807 impl<'tcx> TypeTrace<'tcx> {
1808 pub fn span(&self) -> Span {
1813 cause: &ObligationCause<'tcx>,
1814 a_is_expected: bool,
1817 ) -> TypeTrace<'tcx> {
1818 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1821 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1823 cause: ObligationCause::dummy(),
1824 values: Types(ExpectedFound { expected: tcx.types.err, found: tcx.types.err }),
1829 impl<'tcx> SubregionOrigin<'tcx> {
1830 pub fn span(&self) -> Span {
1832 Subtype(ref a) => a.span(),
1833 InfStackClosure(a) => a,
1834 InvokeClosure(a) => a,
1835 DerefPointer(a) => a,
1836 ClosureCapture(a, _) => a,
1838 RelateObjectBound(a) => a,
1839 RelateParamBound(a, _) => a,
1840 RelateRegionParamBound(a) => a,
1841 RelateDefaultParamBound(a, _) => a,
1843 ReborrowUpvar(a, _) => a,
1844 DataBorrowed(_, a) => a,
1845 ReferenceOutlivesReferent(_, a) => a,
1846 ParameterInScope(_, a) => a,
1847 ExprTypeIsNotInScope(_, a) => a,
1848 BindingTypeIsNotValidAtDecl(a) => a,
1855 SafeDestructor(a) => a,
1856 CompareImplMethodObligation { span, .. } => span,
1860 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1862 F: FnOnce() -> Self,
1865 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1866 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1869 traits::ObligationCauseCode::CompareImplMethodObligation {
1873 } => SubregionOrigin::CompareImplMethodObligation {
1885 impl RegionVariableOrigin {
1886 pub fn span(&self) -> Span {
1888 MiscVariable(a) => a,
1889 PatternRegion(a) => a,
1890 AddrOfRegion(a) => a,
1893 EarlyBoundRegion(a, ..) => a,
1894 LateBoundRegion(a, ..) => a,
1895 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1896 UpvarRegion(_, a) => a,
1897 NLL(..) => bug!("NLL variable used with `span`"),
1902 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1903 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1906 "RegionObligation(sub_region={:?}, sup_type={:?})",
1907 self.sub_region, self.sup_type