1 pub use self::freshen::TypeFreshener;
2 pub use self::lexical_region_resolve::RegionResolutionError;
3 pub use self::LateBoundRegionConversionTime::*;
4 pub use self::RegionVariableOrigin::*;
5 pub use self::SubregionOrigin::*;
6 pub use self::ValuePairs::*;
8 use self::opaque_types::OpaqueTypeMap;
9 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
11 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_data_structures::sync::Lrc;
15 use rustc_data_structures::undo_log::Rollback;
16 use rustc_data_structures::unify as ut;
17 use rustc_errors::DiagnosticBuilder;
19 use rustc_hir::def_id::{DefId, LocalDefId};
20 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
21 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
22 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
23 use rustc_middle::mir::interpret::ErrorHandled;
24 use rustc_middle::mir::interpret::EvalToConstValueResult;
25 use rustc_middle::traits::select;
26 use rustc_middle::ty::error::{ExpectedFound, TypeError};
27 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
28 use rustc_middle::ty::relate::RelateResult;
29 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
30 pub use rustc_middle::ty::IntVarValue;
31 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
32 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
33 use rustc_session::config::BorrowckMode;
34 use rustc_span::symbol::Symbol;
37 use std::cell::{Cell, Ref, RefCell};
38 use std::collections::BTreeMap;
41 use self::combine::CombineFields;
42 use self::free_regions::RegionRelations;
43 use self::lexical_region_resolve::LexicalRegionResolutions;
44 use self::outlives::env::OutlivesEnvironment;
45 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
46 use self::region_constraints::{
47 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
49 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
55 pub mod error_reporting;
62 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, Default)]
99 pub enum RegionckMode {
100 /// 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,
113 /// Indicates that the MIR borrowck will repeat these region
114 /// checks, so we should ignore errors if NLL is (unconditionally)
116 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
117 // FIXME(Centril): Once we actually remove `::Migrate` also make
118 // this always `true` and then proceed to eliminate the dead code.
119 match tcx.borrowck_mode() {
120 // If we're on Migrate mode, report AST region errors
121 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
123 // If we're on MIR, don't report AST region errors as they should be reported by NLL
124 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
129 /// This type contains all the things within `InferCtxt` that sit within a
130 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
131 /// operations are hot enough that we want only one call to `borrow_mut` per
132 /// call to `start_snapshot` and `rollback_to`.
134 pub struct InferCtxtInner<'tcx> {
135 /// Cache for projections. This cache is snapshotted along with the infcx.
137 /// Public so that `traits::project` can use it.
138 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
140 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
141 /// that might instantiate a general type variable have an order,
142 /// represented by its upper and lower bounds.
143 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
145 /// Map from const parameter variable to the kind of const it represents.
146 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
148 /// Map from integral variable to the kind of integer it represents.
149 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
151 /// Map from floating variable to the kind of float it represents.
152 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
154 /// Tracks the set of region variables and the constraints between them.
155 /// This is initially `Some(_)` but when
156 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
157 /// -- further attempts to perform unification, etc., may fail if new
158 /// region constraints would've been added.
159 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
161 /// A set of constraints that regionck must validate. Each
162 /// constraint has the form `T:'a`, meaning "some type `T` must
163 /// outlive the lifetime 'a". These constraints derive from
164 /// instantiated type parameters. So if you had a struct defined
167 /// struct Foo<T:'static> { ... }
169 /// then in some expression `let x = Foo { ... }` it will
170 /// instantiate the type parameter `T` with a fresh type `$0`. At
171 /// the same time, it will record a region obligation of
172 /// `$0:'static`. This will get checked later by regionck. (We
173 /// can't generally check these things right away because we have
174 /// to wait until types are resolved.)
176 /// These are stored in a map keyed to the id of the innermost
177 /// enclosing fn body / static initializer expression. This is
178 /// because the location where the obligation was incurred can be
179 /// relevant with respect to which sublifetime assumptions are in
180 /// place. The reason that we store under the fn-id, and not
181 /// something more fine-grained, is so that it is easier for
182 /// regionck to be sure that it has found *all* the region
183 /// obligations (otherwise, it's easy to fail to walk to a
184 /// particular node-id).
186 /// Before running `resolve_regions_and_report_errors`, the creator
187 /// of the inference context is expected to invoke
188 /// `process_region_obligations` (defined in `self::region_obligations`)
189 /// for each body-id in this map, which will process the
190 /// obligations within. This is expected to be done 'late enough'
191 /// that all type inference variables have been bound and so forth.
192 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
194 undo_log: InferCtxtUndoLogs<'tcx>,
196 // Opaque types found in explicit return types and their
197 // associated fresh inference variable. Writeback resolves these
198 // variables to get the concrete type, which can be used to
199 // 'de-opaque' OpaqueTypeDecl outside of type inference.
200 pub opaque_types: OpaqueTypeMap<'tcx>,
202 /// A map from inference variables created from opaque
203 /// type instantiations (`ty::Infer`) to the actual opaque
204 /// type (`ty::Opaque`). Used during fallback to map unconstrained
205 /// opaque type inference variables to their corresponding
207 pub opaque_types_vars: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
210 impl<'tcx> InferCtxtInner<'tcx> {
211 fn new() -> InferCtxtInner<'tcx> {
213 projection_cache: Default::default(),
214 type_variable_storage: type_variable::TypeVariableStorage::new(),
215 undo_log: InferCtxtUndoLogs::default(),
216 const_unification_storage: ut::UnificationTableStorage::new(),
217 int_unification_storage: ut::UnificationTableStorage::new(),
218 float_unification_storage: ut::UnificationTableStorage::new(),
219 region_constraint_storage: Some(RegionConstraintStorage::new()),
220 region_obligations: vec![],
221 opaque_types: Default::default(),
222 opaque_types_vars: Default::default(),
227 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
228 &self.region_obligations
232 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
233 self.projection_cache.with_log(&mut self.undo_log)
237 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
238 self.type_variable_storage.with_log(&mut self.undo_log)
242 fn int_unification_table(
244 ) -> ut::UnificationTable<
247 &mut ut::UnificationStorage<ty::IntVid>,
248 &mut InferCtxtUndoLogs<'tcx>,
251 self.int_unification_storage.with_log(&mut self.undo_log)
255 fn float_unification_table(
257 ) -> ut::UnificationTable<
260 &mut ut::UnificationStorage<ty::FloatVid>,
261 &mut InferCtxtUndoLogs<'tcx>,
264 self.float_unification_storage.with_log(&mut self.undo_log)
268 fn const_unification_table(
270 ) -> ut::UnificationTable<
273 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
274 &mut InferCtxtUndoLogs<'tcx>,
277 self.const_unification_storage.with_log(&mut self.undo_log)
281 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
282 self.region_constraint_storage
284 .expect("region constraints already solved")
285 .with_log(&mut self.undo_log)
289 pub struct InferCtxt<'a, 'tcx> {
290 pub tcx: TyCtxt<'tcx>,
292 /// The `DefId` of the item in whose context we are performing inference or typeck.
293 /// It is used to check whether an opaque type use is a defining use.
295 /// If it is `None`, we can't resolve opaque types here and need to bubble up
296 /// the obligation. This frequently happens for
297 /// short lived InferCtxt within queries. The opaque type obligations are forwarded
298 /// to the outside until the end up in an `InferCtxt` for typeck or borrowck.
299 pub defining_use_anchor: Option<LocalDefId>,
301 /// During type-checking/inference of a body, `in_progress_typeck_results`
302 /// contains a reference to the typeck results being built up, which are
303 /// used for reading closure kinds/signatures as they are inferred,
304 /// and for error reporting logic to read arbitrary node types.
305 pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
307 pub inner: RefCell<InferCtxtInner<'tcx>>,
309 /// If set, this flag causes us to skip the 'leak check' during
310 /// higher-ranked subtyping operations. This flag is a temporary one used
311 /// to manage the removal of the leak-check: for the time being, we still run the
312 /// leak-check, but we issue warnings. This flag can only be set to true
313 /// when entering a snapshot.
314 skip_leak_check: Cell<bool>,
316 /// Once region inference is done, the values for each variable.
317 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
319 /// Caches the results of trait selection. This cache is used
320 /// for things that have to do with the parameters in scope.
321 pub selection_cache: select::SelectionCache<'tcx>,
323 /// Caches the results of trait evaluation.
324 pub evaluation_cache: select::EvaluationCache<'tcx>,
326 /// the set of predicates on which errors have been reported, to
327 /// avoid reporting the same error twice.
328 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
330 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
332 /// When an error occurs, we want to avoid reporting "derived"
333 /// errors that are due to this original failure. Normally, we
334 /// handle this with the `err_count_on_creation` count, which
335 /// basically just tracks how many errors were reported when we
336 /// started type-checking a fn and checks to see if any new errors
337 /// have been reported since then. Not great, but it works.
339 /// However, when errors originated in other passes -- notably
340 /// resolve -- this heuristic breaks down. Therefore, we have this
341 /// auxiliary flag that one can set whenever one creates a
342 /// type-error that is due to an error in a prior pass.
344 /// Don't read this flag directly, call `is_tainted_by_errors()`
345 /// and `set_tainted_by_errors()`.
346 tainted_by_errors_flag: Cell<bool>,
348 /// Track how many errors were reported when this infcx is created.
349 /// If the number of errors increases, that's also a sign (line
350 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
351 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
352 err_count_on_creation: usize,
354 /// This flag is true while there is an active snapshot.
355 in_snapshot: Cell<bool>,
357 /// What is the innermost universe we have created? Starts out as
358 /// `UniverseIndex::root()` but grows from there as we enter
359 /// universal quantifiers.
361 /// N.B., at present, we exclude the universal quantifiers on the
362 /// item we are type-checking, and just consider those names as
363 /// part of the root universe. So this would only get incremented
364 /// when we enter into a higher-ranked (`for<..>`) type or trait
366 universe: Cell<ty::UniverseIndex>,
369 /// See the `error_reporting` module for more details.
370 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
371 pub enum ValuePairs<'tcx> {
372 Regions(ExpectedFound<ty::Region<'tcx>>),
373 Terms(ExpectedFound<ty::Term<'tcx>>),
374 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
375 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
378 impl<'tcx> ValuePairs<'tcx> {
379 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
380 if let ValuePairs::Terms(ExpectedFound {
381 expected: ty::Term::Ty(expected),
382 found: ty::Term::Ty(found),
385 Some((*expected, *found))
392 /// The trace designates the path through inference that we took to
393 /// encounter an error or subtyping constraint.
395 /// See the `error_reporting` module for more details.
396 #[derive(Clone, Debug)]
397 pub struct TypeTrace<'tcx> {
398 cause: ObligationCause<'tcx>,
399 values: ValuePairs<'tcx>,
402 /// The origin of a `r1 <= r2` constraint.
404 /// See `error_reporting` module for more details
405 #[derive(Clone, Debug)]
406 pub enum SubregionOrigin<'tcx> {
407 /// Arose from a subtyping relation
408 Subtype(Box<TypeTrace<'tcx>>),
410 /// When casting `&'a T` to an `&'b Trait` object,
411 /// relating `'a` to `'b`
412 RelateObjectBound(Span),
414 /// Some type parameter was instantiated with the given type,
415 /// and that type must outlive some region.
416 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
418 /// The given region parameter was instantiated with a region
419 /// that must outlive some other region.
420 RelateRegionParamBound(Span),
422 /// Creating a pointer `b` to contents of another reference
425 /// Creating a pointer `b` to contents of an upvar
426 ReborrowUpvar(Span, ty::UpvarId),
428 /// Data with type `Ty<'tcx>` was borrowed
429 DataBorrowed(Ty<'tcx>, Span),
431 /// (&'a &'b T) where a >= b
432 ReferenceOutlivesReferent(Ty<'tcx>, Span),
434 /// Comparing the signature and requirements of an impl method against
435 /// the containing trait.
436 CompareImplMethodObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId },
438 /// Comparing the signature and requirements of an impl associated type
439 /// against the containing trait
440 CompareImplTypeObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId },
442 /// Checking that the bounds of a trait's associated type hold for a given impl
443 CheckAssociatedTypeBounds {
444 parent: Box<SubregionOrigin<'tcx>>,
445 impl_item_def_id: DefId,
446 trait_item_def_id: DefId,
450 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
451 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
452 static_assert_size!(SubregionOrigin<'_>, 32);
454 /// Times when we replace late-bound regions with variables:
455 #[derive(Clone, Copy, Debug)]
456 pub enum LateBoundRegionConversionTime {
457 /// when a fn is called
460 /// when two higher-ranked types are compared
463 /// when projecting an associated type
464 AssocTypeProjection(DefId),
467 /// Reasons to create a region inference variable
469 /// See `error_reporting` module for more details
470 #[derive(Copy, Clone, Debug)]
471 pub enum RegionVariableOrigin {
472 /// Region variables created for ill-categorized reasons,
473 /// mostly indicates places in need of refactoring
476 /// Regions created by a `&P` or `[...]` pattern
479 /// Regions created by `&` operator
482 /// Regions created as part of an autoref of a method receiver
485 /// Regions created as part of an automatic coercion
488 /// Region variables created as the values for early-bound regions
489 EarlyBoundRegion(Span, Symbol),
491 /// Region variables created for bound regions
492 /// in a function or method that is called
493 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
495 UpvarRegion(ty::UpvarId, Span),
497 /// This origin is used for the inference variables that we create
498 /// during NLL region processing.
499 Nll(NllRegionVariableOrigin),
502 #[derive(Copy, Clone, Debug)]
503 pub enum NllRegionVariableOrigin {
504 /// During NLL region processing, we create variables for free
505 /// regions that we encounter in the function signature and
506 /// elsewhere. This origin indices we've got one of those.
509 /// "Universal" instantiation of a higher-ranked region (e.g.,
510 /// from a `for<'a> T` binder). Meant to represent "any region".
511 Placeholder(ty::PlaceholderRegion),
513 /// The variable we create to represent `'empty(U0)`.
517 /// If this is true, then this variable was created to represent a lifetime
518 /// bound in a `for` binder. For example, it might have been created to
519 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
520 /// Such variables are created when we are trying to figure out if there
521 /// is any valid instantiation of `'a` that could fit into some scenario.
523 /// This is used to inform error reporting: in the case that we are trying to
524 /// determine whether there is any valid instantiation of a `'a` variable that meets
525 /// some constraint C, we want to blame the "source" of that `for` type,
526 /// rather than blaming the source of the constraint C.
531 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
532 #[derive(Copy, Clone, Debug)]
533 pub enum FixupError<'tcx> {
534 UnresolvedIntTy(IntVid),
535 UnresolvedFloatTy(FloatVid),
537 UnresolvedConst(ConstVid<'tcx>),
540 /// See the `region_obligations` field for more information.
542 pub struct RegionObligation<'tcx> {
543 pub sub_region: ty::Region<'tcx>,
544 pub sup_type: Ty<'tcx>,
545 pub origin: SubregionOrigin<'tcx>,
548 impl<'tcx> fmt::Display for FixupError<'tcx> {
549 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550 use self::FixupError::*;
553 UnresolvedIntTy(_) => write!(
555 "cannot determine the type of this integer; \
556 add a suffix to specify the type explicitly"
558 UnresolvedFloatTy(_) => write!(
560 "cannot determine the type of this number; \
561 add a suffix to specify the type explicitly"
563 UnresolvedTy(_) => write!(f, "unconstrained type"),
564 UnresolvedConst(_) => write!(f, "unconstrained const value"),
569 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
570 /// Necessary because we can't write the following bound:
571 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
572 pub struct InferCtxtBuilder<'tcx> {
574 fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
575 defining_use_anchor: Option<LocalDefId>,
578 pub trait TyCtxtInferExt<'tcx> {
579 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
582 impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
583 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
584 InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None }
588 impl<'tcx> InferCtxtBuilder<'tcx> {
589 /// Used only by `rustc_typeck` during body type-checking/inference,
590 /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
591 /// Will also change the scope for opaque type defining use checks to the given owner.
592 pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
593 self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
594 self.with_opaque_type_inference(table_owner)
597 /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
598 /// you need to call this function. Otherwise the opaque type will be treated opaquely.
600 /// It is only meant to be called in two places, for typeck
601 /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used
603 pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self {
604 self.defining_use_anchor = Some(defining_use_anchor);
608 /// Given a canonical value `C` as a starting point, create an
609 /// inference context that contains each of the bound values
610 /// within instantiated as a fresh variable. The `f` closure is
611 /// invoked with the new infcx, along with the instantiated value
612 /// `V` and a substitution `S`. This substitution `S` maps from
613 /// the bound values in `C` to their instantiated values in `V`
614 /// (in other words, `S(C) = V`).
615 pub fn enter_with_canonical<T, R>(
618 canonical: &Canonical<'tcx, T>,
619 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
622 T: TypeFoldable<'tcx>,
626 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
627 f(infcx, value, subst)
631 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
632 let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self;
633 let in_progress_typeck_results = fresh_typeck_results.as_ref();
637 in_progress_typeck_results,
638 inner: RefCell::new(InferCtxtInner::new()),
639 lexical_region_resolutions: RefCell::new(None),
640 selection_cache: Default::default(),
641 evaluation_cache: Default::default(),
642 reported_trait_errors: Default::default(),
643 reported_closure_mismatch: Default::default(),
644 tainted_by_errors_flag: Cell::new(false),
645 err_count_on_creation: tcx.sess.err_count(),
646 in_snapshot: Cell::new(false),
647 skip_leak_check: Cell::new(false),
648 universe: Cell::new(ty::UniverseIndex::ROOT),
653 impl<'tcx, T> InferOk<'tcx, T> {
654 pub fn unit(self) -> InferOk<'tcx, ()> {
655 InferOk { value: (), obligations: self.obligations }
658 /// Extracts `value`, registering any obligations into `fulfill_cx`.
659 pub fn into_value_registering_obligations(
661 infcx: &InferCtxt<'_, 'tcx>,
662 fulfill_cx: &mut dyn TraitEngine<'tcx>,
664 let InferOk { value, obligations } = self;
665 for obligation in obligations {
666 fulfill_cx.register_predicate_obligation(infcx, obligation);
672 impl<'tcx> InferOk<'tcx, ()> {
673 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
678 #[must_use = "once you start a snapshot, you should always consume it"]
679 pub struct CombinedSnapshot<'a, 'tcx> {
680 undo_snapshot: Snapshot<'tcx>,
681 region_constraints_snapshot: RegionSnapshot,
682 universe: ty::UniverseIndex,
683 was_in_snapshot: bool,
684 _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
687 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
688 /// calls `tcx.try_unify_abstract_consts` after
689 /// canonicalizing the consts.
690 pub fn try_unify_abstract_consts(
692 a: ty::Unevaluated<'tcx, ()>,
693 b: ty::Unevaluated<'tcx, ()>,
695 let canonical = self.canonicalize_query((a, b), &mut OriginalQueryValues::default());
696 debug!("canonical consts: {:?}", &canonical.value);
698 self.tcx.try_unify_abstract_consts(canonical.value)
701 pub fn is_in_snapshot(&self) -> bool {
702 self.in_snapshot.get()
705 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
706 t.fold_with(&mut self.freshener())
709 /// Returns the origin of the type variable identified by `vid`, or `None`
710 /// if this is not a type variable.
712 /// No attempt is made to resolve `ty`.
713 pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
715 ty::Infer(ty::TyVar(vid)) => {
716 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
722 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
723 freshen::TypeFreshener::new(self, false)
726 /// Like `freshener`, but does not replace `'static` regions.
727 pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
728 freshen::TypeFreshener::new(self, true)
731 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
732 let mut inner = self.inner.borrow_mut();
733 let mut vars: Vec<Ty<'_>> = inner
735 .unsolved_variables()
737 .map(|t| self.tcx.mk_ty_var(t))
740 (0..inner.int_unification_table().len())
741 .map(|i| ty::IntVid { index: i as u32 })
742 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
743 .map(|v| self.tcx.mk_int_var(v)),
746 (0..inner.float_unification_table().len())
747 .map(|i| ty::FloatVid { index: i as u32 })
748 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
749 .map(|v| self.tcx.mk_float_var(v)),
756 trace: TypeTrace<'tcx>,
757 param_env: ty::ParamEnv<'tcx>,
758 ) -> CombineFields<'a, 'tcx> {
764 obligations: PredicateObligations::new(),
768 /// Clear the "currently in a snapshot" flag, invoke the closure,
769 /// then restore the flag to its original value. This flag is a
770 /// debugging measure designed to detect cases where we start a
771 /// snapshot, create type variables, and register obligations
772 /// which may involve those type variables in the fulfillment cx,
773 /// potentially leaving "dangling type variables" behind.
774 /// In such cases, an assertion will fail when attempting to
775 /// register obligations, within a snapshot. Very useful, much
776 /// better than grovelling through megabytes of `RUSTC_LOG` output.
778 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
779 /// sometimes create a "mini-fulfilment-cx" in which we enroll
780 /// obligations. As long as this fulfillment cx is fully drained
781 /// before we return, this is not a problem, as there won't be any
782 /// escaping obligations in the main cx. In those cases, you can
783 /// use this function.
784 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
786 F: FnOnce(&Self) -> R,
788 let flag = self.in_snapshot.replace(false);
789 let result = func(self);
790 self.in_snapshot.set(flag);
794 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
795 debug!("start_snapshot()");
797 let in_snapshot = self.in_snapshot.replace(true);
799 let mut inner = self.inner.borrow_mut();
802 undo_snapshot: inner.undo_log.start_snapshot(),
803 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
804 universe: self.universe(),
805 was_in_snapshot: in_snapshot,
806 // Borrow typeck results "in progress" (i.e., during typeck)
807 // to ban writes from within a snapshot to them.
808 _in_progress_typeck_results: self
809 .in_progress_typeck_results
810 .map(|typeck_results| typeck_results.borrow()),
814 #[instrument(skip(self, snapshot), level = "debug")]
815 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
816 let CombinedSnapshot {
818 region_constraints_snapshot,
821 _in_progress_typeck_results,
824 self.in_snapshot.set(was_in_snapshot);
825 self.universe.set(universe);
827 let mut inner = self.inner.borrow_mut();
828 inner.rollback_to(undo_snapshot);
829 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
832 #[instrument(skip(self, snapshot), level = "debug")]
833 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
834 let CombinedSnapshot {
836 region_constraints_snapshot: _,
839 _in_progress_typeck_results,
842 self.in_snapshot.set(was_in_snapshot);
844 self.inner.borrow_mut().commit(undo_snapshot);
847 /// Executes `f` and commit the bindings.
848 #[instrument(skip(self, f), level = "debug")]
849 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
851 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
853 let snapshot = self.start_snapshot();
854 let r = f(&snapshot);
855 self.commit_from(snapshot);
859 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
860 #[instrument(skip(self, f), level = "debug")]
861 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
863 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
865 let snapshot = self.start_snapshot();
866 let r = f(&snapshot);
867 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
870 self.commit_from(snapshot);
873 self.rollback_to("commit_if_ok -- error", snapshot);
879 /// Execute `f` then unroll any bindings it creates.
880 #[instrument(skip(self, f), level = "debug")]
881 pub fn probe<R, F>(&self, f: F) -> R
883 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
885 let snapshot = self.start_snapshot();
886 let r = f(&snapshot);
887 self.rollback_to("probe", snapshot);
891 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
892 #[instrument(skip(self, f), level = "debug")]
893 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
895 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
897 let snapshot = self.start_snapshot();
898 let was_skip_leak_check = self.skip_leak_check.get();
900 self.skip_leak_check.set(true);
902 let r = f(&snapshot);
903 self.rollback_to("probe", snapshot);
904 self.skip_leak_check.set(was_skip_leak_check);
908 /// Scan the constraints produced since `snapshot` began and returns:
910 /// - `None` -- if none of them involve "region outlives" constraints
911 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
912 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
913 pub fn region_constraints_added_in_snapshot(
915 snapshot: &CombinedSnapshot<'a, 'tcx>,
919 .unwrap_region_constraints()
920 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
923 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
924 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
927 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
929 T: at::ToTrace<'tcx>,
931 let origin = &ObligationCause::dummy();
933 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
934 // Ignore obligations, since we are unrolling
935 // everything anyway.
940 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
942 T: at::ToTrace<'tcx>,
944 let origin = &ObligationCause::dummy();
946 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
947 // Ignore obligations, since we are unrolling
948 // everything anyway.
953 #[instrument(skip(self), level = "debug")]
956 origin: SubregionOrigin<'tcx>,
960 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
963 /// Require that the region `r` be equal to one of the regions in
964 /// the set `regions`.
965 #[instrument(skip(self), level = "debug")]
966 pub fn member_constraint(
968 opaque_type_def_id: DefId,
969 definition_span: Span,
971 region: ty::Region<'tcx>,
972 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
974 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
983 /// Processes a `Coerce` predicate from the fulfillment context.
984 /// This is NOT the preferred way to handle coercion, which is to
985 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
987 /// This method here is actually a fallback that winds up being
988 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
989 /// and records a coercion predicate. Presently, this method is equivalent
990 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
991 /// actually requiring `a <: b`. This is of course a valid coercion,
992 /// but it's not as flexible as `FnCtxt::coerce` would be.
994 /// (We may refactor this in the future, but there are a number of
995 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
996 /// records adjustments that are required on the HIR in order to perform
997 /// the coercion, and we don't currently have a way to manage that.)
998 pub fn coerce_predicate(
1000 cause: &ObligationCause<'tcx>,
1001 param_env: ty::ParamEnv<'tcx>,
1002 predicate: ty::PolyCoercePredicate<'tcx>,
1003 ) -> Option<InferResult<'tcx, ()>> {
1004 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
1005 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
1009 self.subtype_predicate(cause, param_env, subtype_predicate)
1012 pub fn subtype_predicate(
1014 cause: &ObligationCause<'tcx>,
1015 param_env: ty::ParamEnv<'tcx>,
1016 predicate: ty::PolySubtypePredicate<'tcx>,
1017 ) -> Option<InferResult<'tcx, ()>> {
1018 // Check for two unresolved inference variables, in which case we can
1019 // make no progress. This is partly a micro-optimization, but it's
1020 // also an opportunity to "sub-unify" the variables. This isn't
1021 // *necessary* to prevent cycles, because they would eventually be sub-unified
1022 // anyhow during generalization, but it helps with diagnostics (we can detect
1023 // earlier that they are sub-unified).
1025 // Note that we can just skip the binders here because
1026 // type variables can't (at present, at
1027 // least) capture any of the things bound by this binder.
1029 // Note that this sub here is not just for diagnostics - it has semantic
1031 let r_a = self.shallow_resolve(predicate.skip_binder().a);
1032 let r_b = self.shallow_resolve(predicate.skip_binder().b);
1033 match (r_a.kind(), r_b.kind()) {
1034 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
1035 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
1041 Some(self.commit_if_ok(|_snapshot| {
1042 let ty::SubtypePredicate { a_is_expected, a, b } =
1043 self.replace_bound_vars_with_placeholders(predicate);
1045 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1051 pub fn region_outlives_predicate(
1053 cause: &traits::ObligationCause<'tcx>,
1054 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1055 ) -> UnitResult<'tcx> {
1056 self.commit_if_ok(|_snapshot| {
1057 let ty::OutlivesPredicate(r_a, r_b) =
1058 self.replace_bound_vars_with_placeholders(predicate);
1059 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1060 RelateRegionParamBound(cause.span)
1062 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1067 /// Number of type variables created so far.
1068 pub fn num_ty_vars(&self) -> usize {
1069 self.inner.borrow_mut().type_variables().num_vars()
1072 pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1073 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1076 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1077 self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1080 pub fn next_ty_var_in_universe(
1082 origin: TypeVariableOrigin,
1083 universe: ty::UniverseIndex,
1085 let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin);
1086 self.tcx.mk_ty_var(vid)
1089 pub fn next_const_var(&self, ty: Ty<'tcx>, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
1090 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1093 pub fn next_const_var_in_universe(
1096 origin: ConstVariableOrigin,
1097 universe: ty::UniverseIndex,
1098 ) -> ty::Const<'tcx> {
1102 .const_unification_table()
1103 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1104 self.tcx.mk_const_var(vid, ty)
1107 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1108 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1110 val: ConstVariableValue::Unknown { universe: self.universe() },
1114 fn next_int_var_id(&self) -> IntVid {
1115 self.inner.borrow_mut().int_unification_table().new_key(None)
1118 pub fn next_int_var(&self) -> Ty<'tcx> {
1119 self.tcx.mk_int_var(self.next_int_var_id())
1122 fn next_float_var_id(&self) -> FloatVid {
1123 self.inner.borrow_mut().float_unification_table().new_key(None)
1126 pub fn next_float_var(&self) -> Ty<'tcx> {
1127 self.tcx.mk_float_var(self.next_float_var_id())
1130 /// Creates a fresh region variable with the next available index.
1131 /// The variable will be created in the maximum universe created
1132 /// thus far, allowing it to name any region created thus far.
1133 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1134 self.next_region_var_in_universe(origin, self.universe())
1137 /// Creates a fresh region variable with the next available index
1138 /// in the given universe; typically, you can use
1139 /// `next_region_var` and just use the maximal universe.
1140 pub fn next_region_var_in_universe(
1142 origin: RegionVariableOrigin,
1143 universe: ty::UniverseIndex,
1144 ) -> ty::Region<'tcx> {
1146 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1147 self.tcx.mk_region(ty::ReVar(region_var))
1150 /// Return the universe that the region `r` was created in. For
1151 /// most regions (e.g., `'static`, named regions from the user,
1152 /// etc) this is the root universe U0. For inference variables or
1153 /// placeholders, however, it will return the universe which which
1154 /// they are associated.
1155 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1156 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1159 /// Number of region variables created so far.
1160 pub fn num_region_vars(&self) -> usize {
1161 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1164 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1165 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1166 self.next_region_var(RegionVariableOrigin::Nll(origin))
1169 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1170 pub fn next_nll_region_var_in_universe(
1172 origin: NllRegionVariableOrigin,
1173 universe: ty::UniverseIndex,
1174 ) -> ty::Region<'tcx> {
1175 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1178 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1180 GenericParamDefKind::Lifetime => {
1181 // Create a region inference variable for the given
1182 // region parameter definition.
1183 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1185 GenericParamDefKind::Type { .. } => {
1186 // Create a type inference variable for the given
1187 // type parameter definition. The substitutions are
1188 // for actual parameters that may be referred to by
1189 // the default of this type parameter, if it exists.
1190 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1191 // used in a path such as `Foo::<T, U>::new()` will
1192 // use an inference variable for `C` with `[T, U]`
1193 // as the substitutions for the default, `(T, U)`.
1194 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1196 TypeVariableOrigin {
1197 kind: TypeVariableOriginKind::TypeParameterDefinition(
1205 self.tcx.mk_ty_var(ty_var_id).into()
1207 GenericParamDefKind::Const { .. } => {
1208 let origin = ConstVariableOrigin {
1209 kind: ConstVariableOriginKind::ConstParameterDefinition(
1216 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1218 val: ConstVariableValue::Unknown { universe: self.universe() },
1220 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1225 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1226 /// type/region parameter to a fresh inference variable.
1227 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1228 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1231 /// Returns `true` if errors have been reported since this infcx was
1232 /// created. This is sometimes used as a heuristic to skip
1233 /// reporting errors that often occur as a result of earlier
1234 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1235 /// inference variables, regionck errors).
1236 pub fn is_tainted_by_errors(&self) -> bool {
1238 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1239 tainted_by_errors_flag={})",
1240 self.tcx.sess.err_count(),
1241 self.err_count_on_creation,
1242 self.tainted_by_errors_flag.get()
1245 if self.tcx.sess.err_count() > self.err_count_on_creation {
1246 return true; // errors reported since this infcx was made
1248 self.tainted_by_errors_flag.get()
1251 /// Set the "tainted by errors" flag to true. We call this when we
1252 /// observe an error from a prior pass.
1253 pub fn set_tainted_by_errors(&self) {
1254 debug!("set_tainted_by_errors()");
1255 self.tainted_by_errors_flag.set(true)
1258 /// Process the region constraints and return any any errors that
1259 /// result. After this, no more unification operations should be
1260 /// done -- or the compiler will panic -- but it is legal to use
1261 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1262 pub fn resolve_regions(
1264 region_context: DefId,
1265 outlives_env: &OutlivesEnvironment<'tcx>,
1267 ) -> Vec<RegionResolutionError<'tcx>> {
1268 let (var_infos, data) = {
1269 let mut inner = self.inner.borrow_mut();
1270 let inner = &mut *inner;
1272 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1273 "region_obligations not empty: {:#?}",
1274 inner.region_obligations
1277 .region_constraint_storage
1279 .expect("regions already resolved")
1280 .with_log(&mut inner.undo_log)
1281 .into_infos_and_data()
1285 &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1287 let (lexical_region_resolutions, errors) =
1288 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1290 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1291 assert!(old_value.is_none());
1296 /// Process the region constraints and report any errors that
1297 /// result. After this, no more unification operations should be
1298 /// done -- or the compiler will panic -- but it is legal to use
1299 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1300 pub fn resolve_regions_and_report_errors(
1302 region_context: DefId,
1303 outlives_env: &OutlivesEnvironment<'tcx>,
1306 let errors = self.resolve_regions(region_context, outlives_env, mode);
1308 if !self.is_tainted_by_errors() {
1309 // As a heuristic, just skip reporting region errors
1310 // altogether if other errors have been reported while
1311 // this infcx was in use. This is totally hokey but
1312 // otherwise we have a hard time separating legit region
1313 // errors from silly ones.
1314 self.report_region_errors(&errors);
1318 /// Obtains (and clears) the current set of region
1319 /// constraints. The inference context is still usable: further
1320 /// unifications will simply add new constraints.
1322 /// This method is not meant to be used with normal lexical region
1323 /// resolution. Rather, it is used in the NLL mode as a kind of
1324 /// interim hack: basically we run normal type-check and generate
1325 /// region constraints as normal, but then we take them and
1326 /// translate them into the form that the NLL solver
1327 /// understands. See the NLL module for mode details.
1328 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1330 self.inner.borrow().region_obligations.is_empty(),
1331 "region_obligations not empty: {:#?}",
1332 self.inner.borrow().region_obligations
1335 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1338 /// Gives temporary access to the region constraint data.
1339 pub fn with_region_constraints<R>(
1341 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1343 let mut inner = self.inner.borrow_mut();
1344 op(inner.unwrap_region_constraints().data())
1347 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1348 let mut inner = self.inner.borrow_mut();
1349 let inner = &mut *inner;
1351 .region_constraint_storage
1353 .expect("regions already resolved")
1354 .with_log(&mut inner.undo_log)
1358 /// Takes ownership of the list of variable regions. This implies
1359 /// that all the region constraints have already been taken, and
1360 /// hence that `resolve_regions_and_report_errors` can never be
1361 /// called. This is used only during NLL processing to "hand off" ownership
1362 /// of the set of region variables into the NLL region context.
1363 pub fn take_region_var_origins(&self) -> VarInfos {
1364 let mut inner = self.inner.borrow_mut();
1365 let (var_infos, data) = inner
1366 .region_constraint_storage
1368 .expect("regions already resolved")
1369 .with_log(&mut inner.undo_log)
1370 .into_infos_and_data();
1371 assert!(data.is_empty());
1375 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1376 self.resolve_vars_if_possible(t).to_string()
1379 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1380 /// universe index of `TyVar(vid)`.
1381 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1382 use self::type_variable::TypeVariableValue;
1384 match self.inner.borrow_mut().type_variables().probe(vid) {
1385 TypeVariableValue::Known { value } => Ok(value),
1386 TypeVariableValue::Unknown { universe } => Err(universe),
1390 /// Resolve any type variables found in `value` -- but only one
1391 /// level. So, if the variable `?X` is bound to some type
1392 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1393 /// itself be bound to a type).
1395 /// Useful when you only need to inspect the outermost level of
1396 /// the type and don't care about nested types (or perhaps you
1397 /// will be resolving them as well, e.g. in a loop).
1398 pub fn shallow_resolve<T>(&self, value: T) -> T
1400 T: TypeFoldable<'tcx>,
1402 value.fold_with(&mut ShallowResolver { infcx: self })
1405 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1406 self.inner.borrow_mut().type_variables().root_var(var)
1409 /// Where possible, replaces type/const variables in
1410 /// `value` with their final value. Note that region variables
1411 /// are unaffected. If a type/const variable has not been unified, it
1412 /// is left as is. This is an idempotent operation that does
1413 /// not affect inference state in any way and so you can do it
1415 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1417 T: TypeFoldable<'tcx>,
1419 if !value.needs_infer() {
1420 return value; // Avoid duplicated subst-folding.
1422 let mut r = resolve::OpportunisticVarResolver::new(self);
1423 value.fold_with(&mut r)
1426 /// Returns the first unresolved variable contained in `T`. In the
1427 /// process of visiting `T`, this will resolve (where possible)
1428 /// type variables in `T`, but it never constructs the final,
1429 /// resolved type, so it's more efficient than
1430 /// `resolve_vars_if_possible()`.
1431 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1433 T: TypeFoldable<'tcx>,
1435 value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1438 pub fn probe_const_var(
1440 vid: ty::ConstVid<'tcx>,
1441 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1442 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1443 ConstVariableValue::Known { value } => Ok(value),
1444 ConstVariableValue::Unknown { universe } => Err(universe),
1448 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1450 * Attempts to resolve all type/region/const variables in
1451 * `value`. Region inference must have been run already (e.g.,
1452 * by calling `resolve_regions_and_report_errors`). If some
1453 * variable was never unified, an `Err` results.
1455 * This method is idempotent, but it not typically not invoked
1456 * except during the writeback phase.
1459 resolve::fully_resolve(self, value)
1462 // [Note-Type-error-reporting]
1463 // An invariant is that anytime the expected or actual type is Error (the special
1464 // error type, meaning that an error occurred when typechecking this expression),
1465 // this is a derived error. The error cascaded from another error (that was already
1466 // reported), so it's not useful to display it to the user.
1467 // The following methods implement this logic.
1468 // They check if either the actual or expected type is Error, and don't print the error
1469 // in this case. The typechecker should only ever report type errors involving mismatched
1470 // types using one of these methods, and should not call span_err directly for such
1473 pub fn type_error_struct_with_diag<M>(
1477 actual_ty: Ty<'tcx>,
1478 ) -> DiagnosticBuilder<'tcx>
1480 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1482 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1483 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1485 // Don't report an error if actual type is `Error`.
1486 if actual_ty.references_error() {
1487 return self.tcx.sess.diagnostic().struct_dummy();
1490 mk_diag(self.ty_to_string(actual_ty))
1493 pub fn report_mismatched_types(
1495 cause: &ObligationCause<'tcx>,
1498 err: TypeError<'tcx>,
1499 ) -> DiagnosticBuilder<'tcx> {
1500 let trace = TypeTrace::types(cause, true, expected, actual);
1501 self.report_and_explain_type_error(trace, &err)
1504 pub fn report_mismatched_consts(
1506 cause: &ObligationCause<'tcx>,
1507 expected: ty::Const<'tcx>,
1508 actual: ty::Const<'tcx>,
1509 err: TypeError<'tcx>,
1510 ) -> DiagnosticBuilder<'tcx> {
1511 let trace = TypeTrace::consts(cause, true, expected, actual);
1512 self.report_and_explain_type_error(trace, &err)
1515 pub fn replace_bound_vars_with_fresh_vars<T>(
1518 lbrct: LateBoundRegionConversionTime,
1519 value: ty::Binder<'tcx, T>,
1520 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1522 T: TypeFoldable<'tcx>,
1525 |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct));
1527 self.next_ty_var(TypeVariableOrigin {
1528 kind: TypeVariableOriginKind::MiscVariable,
1532 let fld_c = |_, ty| {
1533 self.next_const_var(
1535 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1538 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1541 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1542 pub fn verify_generic_bound(
1544 origin: SubregionOrigin<'tcx>,
1545 kind: GenericKind<'tcx>,
1546 a: ty::Region<'tcx>,
1547 bound: VerifyBound<'tcx>,
1549 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1553 .unwrap_region_constraints()
1554 .verify_generic_bound(origin, kind, a, bound);
1557 /// Obtains the latest type of the given closure; this may be a
1558 /// closure in the current function, in which case its
1559 /// `ClosureKind` may not yet be known.
1560 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1561 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1562 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1563 closure_kind_ty.to_opt_closure_kind()
1566 /// Clears the selection, evaluation, and projection caches. This is useful when
1567 /// repeatedly attempting to select an `Obligation` while changing only
1568 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1569 pub fn clear_caches(&self) {
1570 self.selection_cache.clear();
1571 self.evaluation_cache.clear();
1572 self.inner.borrow_mut().projection_cache().clear();
1575 pub fn universe(&self) -> ty::UniverseIndex {
1579 /// Creates and return a fresh universe that extends all previous
1580 /// universes. Updates `self.universe` to that new universe.
1581 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1582 let u = self.universe.get().next_universe();
1583 self.universe.set(u);
1587 /// Resolves and evaluates a constant.
1589 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1590 /// substitutions and environment are used to resolve the constant. Alternatively if the
1591 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1592 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1593 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1594 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1597 /// This handles inferences variables within both `param_env` and `substs` by
1598 /// performing the operation on their respective canonical forms.
1599 pub fn const_eval_resolve(
1601 param_env: ty::ParamEnv<'tcx>,
1602 unevaluated: ty::Unevaluated<'tcx>,
1604 ) -> EvalToConstValueResult<'tcx> {
1605 let substs = self.resolve_vars_if_possible(unevaluated.substs);
1607 // Postpone the evaluation of constants whose substs depend on inference
1609 if substs.has_infer_types_or_consts() {
1610 return Err(ErrorHandled::TooGeneric);
1613 let param_env_erased = self.tcx.erase_regions(param_env);
1614 let substs_erased = self.tcx.erase_regions(substs);
1616 let unevaluated = ty::Unevaluated {
1617 def: unevaluated.def,
1618 substs: substs_erased,
1619 promoted: unevaluated.promoted,
1622 // The return value is the evaluated value which doesn't contain any reference to inference
1623 // variables, thus we don't need to substitute back the original values.
1624 self.tcx.const_eval_resolve(param_env_erased, unevaluated, span)
1627 /// If `typ` is a type variable of some kind, resolve it one level
1628 /// (but do not resolve types found in the result). If `typ` is
1629 /// not a type variable, just return it unmodified.
1630 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1631 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1633 ty::Infer(ty::TyVar(v)) => {
1634 // Not entirely obvious: if `typ` is a type variable,
1635 // it can be resolved to an int/float variable, which
1636 // can then be recursively resolved, hence the
1637 // recursion. Note though that we prevent type
1638 // variables from unifying to other type variables
1639 // directly (though they may be embedded
1640 // structurally), and we prevent cycles in any case,
1641 // so this recursion should always be of very limited
1644 // Note: if these two lines are combined into one we get
1645 // dynamic borrow errors on `self.inner`.
1646 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1647 known.map_or(typ, |t| self.shallow_resolve_ty(t))
1650 ty::Infer(ty::IntVar(v)) => self
1653 .int_unification_table()
1655 .map(|v| v.to_type(self.tcx))
1658 ty::Infer(ty::FloatVar(v)) => self
1661 .float_unification_table()
1663 .map(|v| v.to_type(self.tcx))
1670 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1671 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1672 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1674 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1675 /// inlined, despite being large, because it has only two call sites that
1676 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1677 /// inference variables), and it handles both `Ty` and `ty::Const` without
1678 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1680 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1682 TyOrConstInferVar::Ty(v) => {
1683 use self::type_variable::TypeVariableValue;
1685 // If `inlined_probe` returns a `Known` value, it never equals
1686 // `ty::Infer(ty::TyVar(v))`.
1687 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1688 TypeVariableValue::Unknown { .. } => false,
1689 TypeVariableValue::Known { .. } => true,
1693 TyOrConstInferVar::TyInt(v) => {
1694 // If `inlined_probe_value` returns a value it's always a
1695 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1697 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1700 TyOrConstInferVar::TyFloat(v) => {
1701 // If `probe_value` returns a value it's always a
1702 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1704 // Not `inlined_probe_value(v)` because this call site is colder.
1705 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1708 TyOrConstInferVar::Const(v) => {
1709 // If `probe_value` returns a `Known` value, it never equals
1710 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1712 // Not `inlined_probe_value(v)` because this call site is colder.
1713 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1714 ConstVariableValue::Unknown { .. } => false,
1715 ConstVariableValue::Known { .. } => true,
1722 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1723 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1724 #[derive(Copy, Clone, Debug)]
1725 pub enum TyOrConstInferVar<'tcx> {
1726 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1728 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1730 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1733 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1734 Const(ConstVid<'tcx>),
1737 impl<'tcx> TyOrConstInferVar<'tcx> {
1738 /// Tries to extract an inference variable from a type or a constant, returns `None`
1739 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1740 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1741 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1742 match arg.unpack() {
1743 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1744 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1745 GenericArgKind::Lifetime(_) => None,
1749 /// Tries to extract an inference variable from a type, returns `None`
1750 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1751 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1753 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1754 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1755 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1760 /// Tries to extract an inference variable from a constant, returns `None`
1761 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1762 pub fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1764 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1770 struct ShallowResolver<'a, 'tcx> {
1771 infcx: &'a InferCtxt<'a, 'tcx>,
1774 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1775 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1779 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1780 self.infcx.shallow_resolve_ty(ty)
1783 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1784 if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.val() {
1788 .const_unification_table()
1799 impl<'tcx> TypeTrace<'tcx> {
1800 pub fn span(&self) -> Span {
1805 cause: &ObligationCause<'tcx>,
1806 a_is_expected: bool,
1809 ) -> TypeTrace<'tcx> {
1811 cause: cause.clone(),
1812 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1817 cause: &ObligationCause<'tcx>,
1818 a_is_expected: bool,
1821 ) -> TypeTrace<'tcx> {
1823 cause: cause.clone(),
1824 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1829 impl<'tcx> SubregionOrigin<'tcx> {
1830 pub fn span(&self) -> Span {
1832 Subtype(ref a) => a.span(),
1833 RelateObjectBound(a) => a,
1834 RelateParamBound(a, ..) => a,
1835 RelateRegionParamBound(a) => a,
1837 ReborrowUpvar(a, _) => a,
1838 DataBorrowed(_, a) => a,
1839 ReferenceOutlivesReferent(_, a) => a,
1840 CompareImplMethodObligation { span, .. } => span,
1841 CompareImplTypeObligation { span, .. } => span,
1842 CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1846 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1848 F: FnOnce() -> Self,
1850 match *cause.code() {
1851 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1852 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1855 traits::ObligationCauseCode::CompareImplMethodObligation {
1858 } => SubregionOrigin::CompareImplMethodObligation {
1864 traits::ObligationCauseCode::CompareImplTypeObligation {
1867 } => SubregionOrigin::CompareImplTypeObligation {
1873 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1876 } => SubregionOrigin::CheckAssociatedTypeBounds {
1879 parent: Box::new(default()),
1887 impl RegionVariableOrigin {
1888 pub fn span(&self) -> Span {
1895 | EarlyBoundRegion(a, ..)
1896 | LateBoundRegion(a, ..)
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