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::OpaqueTypeStorage;
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, ErrorGuaranteed};
18 use rustc_hir::def_id::{DefId, LocalDefId};
19 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
20 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
21 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
22 use rustc_middle::mir::interpret::{ErrorHandled, EvalToValTreeResult};
23 use rustc_middle::traits::select;
24 use rustc_middle::ty::error::{ExpectedFound, TypeError};
25 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
26 use rustc_middle::ty::relate::RelateResult;
27 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
28 use rustc_middle::ty::visit::TypeVisitable;
29 pub use rustc_middle::ty::IntVarValue;
30 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
31 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
32 use rustc_span::symbol::Symbol;
35 use std::cell::{Cell, Ref, RefCell};
38 use self::combine::CombineFields;
39 use self::free_regions::RegionRelations;
40 use self::lexical_region_resolve::LexicalRegionResolutions;
41 use self::outlives::env::OutlivesEnvironment;
42 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
43 use self::region_constraints::{
44 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
46 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
52 pub mod error_reporting;
59 mod lexical_region_resolve;
65 pub mod region_constraints;
68 pub mod type_variable;
73 pub struct InferOk<'tcx, T> {
75 pub obligations: PredicateObligations<'tcx>,
77 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
79 pub type Bound<T> = Option<T>;
80 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
81 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
83 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
84 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
87 /// This type contains all the things within `InferCtxt` that sit within a
88 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
89 /// operations are hot enough that we want only one call to `borrow_mut` per
90 /// call to `start_snapshot` and `rollback_to`.
92 pub struct InferCtxtInner<'tcx> {
93 /// Cache for projections. This cache is snapshotted along with the infcx.
95 /// Public so that `traits::project` can use it.
96 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
98 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
99 /// that might instantiate a general type variable have an order,
100 /// represented by its upper and lower bounds.
101 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
103 /// Map from const parameter variable to the kind of const it represents.
104 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
106 /// Map from integral variable to the kind of integer it represents.
107 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
109 /// Map from floating variable to the kind of float it represents.
110 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
112 /// Tracks the set of region variables and the constraints between them.
113 /// This is initially `Some(_)` but when
114 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
115 /// -- further attempts to perform unification, etc., may fail if new
116 /// region constraints would've been added.
117 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
119 /// A set of constraints that regionck must validate. Each
120 /// constraint has the form `T:'a`, meaning "some type `T` must
121 /// outlive the lifetime 'a". These constraints derive from
122 /// instantiated type parameters. So if you had a struct defined
124 /// ```ignore (illustrative)
125 /// struct Foo<T:'static> { ... }
127 /// then in some expression `let x = Foo { ... }` it will
128 /// instantiate the type parameter `T` with a fresh type `$0`. At
129 /// the same time, it will record a region obligation of
130 /// `$0:'static`. This will get checked later by regionck. (We
131 /// can't generally check these things right away because we have
132 /// to wait until types are resolved.)
134 /// These are stored in a map keyed to the id of the innermost
135 /// enclosing fn body / static initializer expression. This is
136 /// because the location where the obligation was incurred can be
137 /// relevant with respect to which sublifetime assumptions are in
138 /// place. The reason that we store under the fn-id, and not
139 /// something more fine-grained, is so that it is easier for
140 /// regionck to be sure that it has found *all* the region
141 /// obligations (otherwise, it's easy to fail to walk to a
142 /// particular node-id).
144 /// Before running `resolve_regions_and_report_errors`, the creator
145 /// of the inference context is expected to invoke
146 /// [`InferCtxt::process_registered_region_obligations`]
147 /// for each body-id in this map, which will process the
148 /// obligations within. This is expected to be done 'late enough'
149 /// that all type inference variables have been bound and so forth.
150 region_obligations: Vec<RegionObligation<'tcx>>,
152 undo_log: InferCtxtUndoLogs<'tcx>,
154 /// Caches for opaque type inference.
155 pub opaque_type_storage: OpaqueTypeStorage<'tcx>,
158 impl<'tcx> InferCtxtInner<'tcx> {
159 fn new() -> InferCtxtInner<'tcx> {
161 projection_cache: Default::default(),
162 type_variable_storage: type_variable::TypeVariableStorage::new(),
163 undo_log: InferCtxtUndoLogs::default(),
164 const_unification_storage: ut::UnificationTableStorage::new(),
165 int_unification_storage: ut::UnificationTableStorage::new(),
166 float_unification_storage: ut::UnificationTableStorage::new(),
167 region_constraint_storage: Some(RegionConstraintStorage::new()),
168 region_obligations: vec![],
169 opaque_type_storage: Default::default(),
174 pub fn region_obligations(&self) -> &[RegionObligation<'tcx>] {
175 &self.region_obligations
179 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
180 self.projection_cache.with_log(&mut self.undo_log)
184 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
185 self.type_variable_storage.with_log(&mut self.undo_log)
189 pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
190 self.opaque_type_storage.with_log(&mut self.undo_log)
194 fn int_unification_table(
196 ) -> ut::UnificationTable<
199 &mut ut::UnificationStorage<ty::IntVid>,
200 &mut InferCtxtUndoLogs<'tcx>,
203 self.int_unification_storage.with_log(&mut self.undo_log)
207 fn float_unification_table(
209 ) -> ut::UnificationTable<
212 &mut ut::UnificationStorage<ty::FloatVid>,
213 &mut InferCtxtUndoLogs<'tcx>,
216 self.float_unification_storage.with_log(&mut self.undo_log)
220 fn const_unification_table(
222 ) -> ut::UnificationTable<
225 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
226 &mut InferCtxtUndoLogs<'tcx>,
229 self.const_unification_storage.with_log(&mut self.undo_log)
233 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
234 self.region_constraint_storage
236 .expect("region constraints already solved")
237 .with_log(&mut self.undo_log)
241 pub struct InferCtxt<'a, 'tcx> {
242 pub tcx: TyCtxt<'tcx>,
244 /// The `DefId` of the item in whose context we are performing inference or typeck.
245 /// It is used to check whether an opaque type use is a defining use.
247 /// If it is `None`, we can't resolve opaque types here and need to bubble up
248 /// the obligation. This frequently happens for
249 /// short lived InferCtxt within queries. The opaque type obligations are forwarded
250 /// to the outside until the end up in an `InferCtxt` for typeck or borrowck.
251 pub defining_use_anchor: Option<LocalDefId>,
253 /// During type-checking/inference of a body, `in_progress_typeck_results`
254 /// contains a reference to the typeck results being built up, which are
255 /// used for reading closure kinds/signatures as they are inferred,
256 /// and for error reporting logic to read arbitrary node types.
257 pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
259 pub inner: RefCell<InferCtxtInner<'tcx>>,
261 /// If set, this flag causes us to skip the 'leak check' during
262 /// higher-ranked subtyping operations. This flag is a temporary one used
263 /// to manage the removal of the leak-check: for the time being, we still run the
264 /// leak-check, but we issue warnings. This flag can only be set to true
265 /// when entering a snapshot.
266 skip_leak_check: Cell<bool>,
268 /// Once region inference is done, the values for each variable.
269 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
271 /// Caches the results of trait selection. This cache is used
272 /// for things that have to do with the parameters in scope.
273 pub selection_cache: select::SelectionCache<'tcx>,
275 /// Caches the results of trait evaluation.
276 pub evaluation_cache: select::EvaluationCache<'tcx>,
278 /// the set of predicates on which errors have been reported, to
279 /// avoid reporting the same error twice.
280 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
282 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
284 /// When an error occurs, we want to avoid reporting "derived"
285 /// errors that are due to this original failure. Normally, we
286 /// handle this with the `err_count_on_creation` count, which
287 /// basically just tracks how many errors were reported when we
288 /// started type-checking a fn and checks to see if any new errors
289 /// have been reported since then. Not great, but it works.
291 /// However, when errors originated in other passes -- notably
292 /// resolve -- this heuristic breaks down. Therefore, we have this
293 /// auxiliary flag that one can set whenever one creates a
294 /// type-error that is due to an error in a prior pass.
296 /// Don't read this flag directly, call `is_tainted_by_errors()`
297 /// and `set_tainted_by_errors()`.
298 tainted_by_errors_flag: Cell<bool>,
300 /// Track how many errors were reported when this infcx is created.
301 /// If the number of errors increases, that's also a sign (line
302 /// `tainted_by_errors`) to avoid reporting certain kinds of errors.
303 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
304 err_count_on_creation: usize,
306 /// This flag is true while there is an active snapshot.
307 in_snapshot: Cell<bool>,
309 /// What is the innermost universe we have created? Starts out as
310 /// `UniverseIndex::root()` but grows from there as we enter
311 /// universal quantifiers.
313 /// N.B., at present, we exclude the universal quantifiers on the
314 /// item we are type-checking, and just consider those names as
315 /// part of the root universe. So this would only get incremented
316 /// when we enter into a higher-ranked (`for<..>`) type or trait
318 universe: Cell<ty::UniverseIndex>,
321 /// See the `error_reporting` module for more details.
322 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
323 pub enum ValuePairs<'tcx> {
324 Regions(ExpectedFound<ty::Region<'tcx>>),
325 Terms(ExpectedFound<ty::Term<'tcx>>),
326 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
327 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
330 impl<'tcx> ValuePairs<'tcx> {
331 pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
332 if let ValuePairs::Terms(ExpectedFound {
333 expected: ty::Term::Ty(expected),
334 found: ty::Term::Ty(found),
337 Some((*expected, *found))
344 /// The trace designates the path through inference that we took to
345 /// encounter an error or subtyping constraint.
347 /// See the `error_reporting` module for more details.
348 #[derive(Clone, Debug)]
349 pub struct TypeTrace<'tcx> {
350 pub cause: ObligationCause<'tcx>,
351 pub values: ValuePairs<'tcx>,
354 /// The origin of a `r1 <= r2` constraint.
356 /// See `error_reporting` module for more details
357 #[derive(Clone, Debug)]
358 pub enum SubregionOrigin<'tcx> {
359 /// Arose from a subtyping relation
360 Subtype(Box<TypeTrace<'tcx>>),
362 /// When casting `&'a T` to an `&'b Trait` object,
363 /// relating `'a` to `'b`
364 RelateObjectBound(Span),
366 /// Some type parameter was instantiated with the given type,
367 /// and that type must outlive some region.
368 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
370 /// The given region parameter was instantiated with a region
371 /// that must outlive some other region.
372 RelateRegionParamBound(Span),
374 /// Creating a pointer `b` to contents of another reference
377 /// Creating a pointer `b` to contents of an upvar
378 ReborrowUpvar(Span, ty::UpvarId),
380 /// Data with type `Ty<'tcx>` was borrowed
381 DataBorrowed(Ty<'tcx>, Span),
383 /// (&'a &'b T) where a >= b
384 ReferenceOutlivesReferent(Ty<'tcx>, Span),
386 /// Comparing the signature and requirements of an impl method against
387 /// the containing trait.
388 CompareImplMethodObligation {
390 impl_item_def_id: LocalDefId,
391 trait_item_def_id: DefId,
394 /// Comparing the signature and requirements of an impl associated type
395 /// against the containing trait
396 CompareImplTypeObligation { span: Span, impl_item_def_id: LocalDefId, trait_item_def_id: DefId },
398 /// Checking that the bounds of a trait's associated type hold for a given impl
399 CheckAssociatedTypeBounds {
400 parent: Box<SubregionOrigin<'tcx>>,
401 impl_item_def_id: LocalDefId,
402 trait_item_def_id: DefId,
406 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
407 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
408 static_assert_size!(SubregionOrigin<'_>, 32);
410 /// Times when we replace late-bound regions with variables:
411 #[derive(Clone, Copy, Debug)]
412 pub enum LateBoundRegionConversionTime {
413 /// when a fn is called
416 /// when two higher-ranked types are compared
419 /// when projecting an associated type
420 AssocTypeProjection(DefId),
423 /// Reasons to create a region inference variable
425 /// See `error_reporting` module for more details
426 #[derive(Copy, Clone, Debug)]
427 pub enum RegionVariableOrigin {
428 /// Region variables created for ill-categorized reasons,
429 /// mostly indicates places in need of refactoring
432 /// Regions created by a `&P` or `[...]` pattern
435 /// Regions created by `&` operator
438 /// Regions created as part of an autoref of a method receiver
441 /// Regions created as part of an automatic coercion
444 /// Region variables created as the values for early-bound regions
445 EarlyBoundRegion(Span, Symbol),
447 /// Region variables created for bound regions
448 /// in a function or method that is called
449 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
451 UpvarRegion(ty::UpvarId, Span),
453 /// This origin is used for the inference variables that we create
454 /// during NLL region processing.
455 Nll(NllRegionVariableOrigin),
458 #[derive(Copy, Clone, Debug)]
459 pub enum NllRegionVariableOrigin {
460 /// During NLL region processing, we create variables for free
461 /// regions that we encounter in the function signature and
462 /// elsewhere. This origin indices we've got one of those.
465 /// "Universal" instantiation of a higher-ranked region (e.g.,
466 /// from a `for<'a> T` binder). Meant to represent "any region".
467 Placeholder(ty::PlaceholderRegion),
470 /// If this is true, then this variable was created to represent a lifetime
471 /// bound in a `for` binder. For example, it might have been created to
472 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
473 /// Such variables are created when we are trying to figure out if there
474 /// is any valid instantiation of `'a` that could fit into some scenario.
476 /// This is used to inform error reporting: in the case that we are trying to
477 /// determine whether there is any valid instantiation of a `'a` variable that meets
478 /// some constraint C, we want to blame the "source" of that `for` type,
479 /// rather than blaming the source of the constraint C.
484 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
485 #[derive(Copy, Clone, Debug)]
486 pub enum FixupError<'tcx> {
487 UnresolvedIntTy(IntVid),
488 UnresolvedFloatTy(FloatVid),
490 UnresolvedConst(ConstVid<'tcx>),
493 /// See the `region_obligations` field for more information.
495 pub struct RegionObligation<'tcx> {
496 pub sub_region: ty::Region<'tcx>,
497 pub sup_type: Ty<'tcx>,
498 pub origin: SubregionOrigin<'tcx>,
501 impl<'tcx> fmt::Display for FixupError<'tcx> {
502 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503 use self::FixupError::*;
506 UnresolvedIntTy(_) => write!(
508 "cannot determine the type of this integer; \
509 add a suffix to specify the type explicitly"
511 UnresolvedFloatTy(_) => write!(
513 "cannot determine the type of this number; \
514 add a suffix to specify the type explicitly"
516 UnresolvedTy(_) => write!(f, "unconstrained type"),
517 UnresolvedConst(_) => write!(f, "unconstrained const value"),
522 /// A temporary returned by `tcx.infer_ctxt()`. This is necessary
523 /// for multiple `InferCtxt` to share the same `in_progress_typeck_results`
524 /// without using `Rc` or something similar.
525 pub struct InferCtxtBuilder<'tcx> {
527 fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
528 defining_use_anchor: Option<LocalDefId>,
531 pub trait TyCtxtInferExt<'tcx> {
532 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
535 impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
536 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
537 InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None }
541 impl<'tcx> InferCtxtBuilder<'tcx> {
542 /// Used only by `rustc_typeck` during body type-checking/inference,
543 /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
544 /// Will also change the scope for opaque type defining use checks to the given owner.
545 pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
546 self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
547 self.with_opaque_type_inference(table_owner)
550 /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
551 /// you need to call this function. Otherwise the opaque type will be treated opaquely.
553 /// It is only meant to be called in two places, for typeck
554 /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used
556 pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self {
557 self.defining_use_anchor = Some(defining_use_anchor);
561 /// Given a canonical value `C` as a starting point, create an
562 /// inference context that contains each of the bound values
563 /// within instantiated as a fresh variable. The `f` closure is
564 /// invoked with the new infcx, along with the instantiated value
565 /// `V` and a substitution `S`. This substitution `S` maps from
566 /// the bound values in `C` to their instantiated values in `V`
567 /// (in other words, `S(C) = V`).
568 pub fn enter_with_canonical<T, R>(
571 canonical: &Canonical<'tcx, T>,
572 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
575 T: TypeFoldable<'tcx>,
579 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
580 f(infcx, value, subst)
584 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
585 let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self;
586 let in_progress_typeck_results = fresh_typeck_results.as_ref();
590 in_progress_typeck_results,
591 inner: RefCell::new(InferCtxtInner::new()),
592 lexical_region_resolutions: RefCell::new(None),
593 selection_cache: Default::default(),
594 evaluation_cache: Default::default(),
595 reported_trait_errors: Default::default(),
596 reported_closure_mismatch: Default::default(),
597 tainted_by_errors_flag: Cell::new(false),
598 err_count_on_creation: tcx.sess.err_count(),
599 in_snapshot: Cell::new(false),
600 skip_leak_check: Cell::new(false),
601 universe: Cell::new(ty::UniverseIndex::ROOT),
606 impl<'tcx, T> InferOk<'tcx, T> {
607 pub fn unit(self) -> InferOk<'tcx, ()> {
608 InferOk { value: (), obligations: self.obligations }
611 /// Extracts `value`, registering any obligations into `fulfill_cx`.
612 pub fn into_value_registering_obligations(
614 infcx: &InferCtxt<'_, 'tcx>,
615 fulfill_cx: &mut dyn TraitEngine<'tcx>,
617 let InferOk { value, obligations } = self;
618 for obligation in obligations {
619 fulfill_cx.register_predicate_obligation(infcx, obligation);
625 impl<'tcx> InferOk<'tcx, ()> {
626 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
631 #[must_use = "once you start a snapshot, you should always consume it"]
632 pub struct CombinedSnapshot<'a, 'tcx> {
633 undo_snapshot: Snapshot<'tcx>,
634 region_constraints_snapshot: RegionSnapshot,
635 universe: ty::UniverseIndex,
636 was_in_snapshot: bool,
637 _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
640 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
641 /// calls `tcx.try_unify_abstract_consts` after
642 /// canonicalizing the consts.
643 #[instrument(skip(self), level = "debug")]
644 pub fn try_unify_abstract_consts(
646 a: ty::Unevaluated<'tcx, ()>,
647 b: ty::Unevaluated<'tcx, ()>,
648 param_env: ty::ParamEnv<'tcx>,
650 // Reject any attempt to unify two unevaluated constants that contain inference
651 // variables, since inference variables in queries lead to ICEs.
652 if a.substs.has_infer_types_or_consts()
653 || b.substs.has_infer_types_or_consts()
654 || param_env.has_infer_types_or_consts()
656 debug!("a or b or param_env contain infer vars in its substs -> cannot unify");
660 let param_env_and = param_env.and((a, b));
661 let erased = self.tcx.erase_regions(param_env_and);
662 debug!("after erase_regions: {:?}", erased);
664 self.tcx.try_unify_abstract_consts(erased)
667 pub fn is_in_snapshot(&self) -> bool {
668 self.in_snapshot.get()
671 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
672 t.fold_with(&mut self.freshener())
675 /// Returns the origin of the type variable identified by `vid`, or `None`
676 /// if this is not a type variable.
678 /// No attempt is made to resolve `ty`.
679 pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option<TypeVariableOrigin> {
681 ty::Infer(ty::TyVar(vid)) => {
682 Some(*self.inner.borrow_mut().type_variables().var_origin(vid))
688 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
689 freshen::TypeFreshener::new(self, false)
692 /// Like `freshener`, but does not replace `'static` regions.
693 pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
694 freshen::TypeFreshener::new(self, true)
697 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
698 let mut inner = self.inner.borrow_mut();
699 let mut vars: Vec<Ty<'_>> = inner
701 .unsolved_variables()
703 .map(|t| self.tcx.mk_ty_var(t))
706 (0..inner.int_unification_table().len())
707 .map(|i| ty::IntVid { index: i as u32 })
708 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
709 .map(|v| self.tcx.mk_int_var(v)),
712 (0..inner.float_unification_table().len())
713 .map(|i| ty::FloatVid { index: i as u32 })
714 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
715 .map(|v| self.tcx.mk_float_var(v)),
722 trace: TypeTrace<'tcx>,
723 param_env: ty::ParamEnv<'tcx>,
724 define_opaque_types: bool,
725 ) -> CombineFields<'a, 'tcx> {
731 obligations: PredicateObligations::new(),
736 /// Clear the "currently in a snapshot" flag, invoke the closure,
737 /// then restore the flag to its original value. This flag is a
738 /// debugging measure designed to detect cases where we start a
739 /// snapshot, create type variables, and register obligations
740 /// which may involve those type variables in the fulfillment cx,
741 /// potentially leaving "dangling type variables" behind.
742 /// In such cases, an assertion will fail when attempting to
743 /// register obligations, within a snapshot. Very useful, much
744 /// better than grovelling through megabytes of `RUSTC_LOG` output.
746 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
747 /// sometimes create a "mini-fulfilment-cx" in which we enroll
748 /// obligations. As long as this fulfillment cx is fully drained
749 /// before we return, this is not a problem, as there won't be any
750 /// escaping obligations in the main cx. In those cases, you can
751 /// use this function.
752 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
754 F: FnOnce(&Self) -> R,
756 let flag = self.in_snapshot.replace(false);
757 let result = func(self);
758 self.in_snapshot.set(flag);
762 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
763 debug!("start_snapshot()");
765 let in_snapshot = self.in_snapshot.replace(true);
767 let mut inner = self.inner.borrow_mut();
770 undo_snapshot: inner.undo_log.start_snapshot(),
771 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
772 universe: self.universe(),
773 was_in_snapshot: in_snapshot,
774 // Borrow typeck results "in progress" (i.e., during typeck)
775 // to ban writes from within a snapshot to them.
776 _in_progress_typeck_results: self
777 .in_progress_typeck_results
778 .map(|typeck_results| typeck_results.borrow()),
782 #[instrument(skip(self, snapshot), level = "debug")]
783 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
784 let CombinedSnapshot {
786 region_constraints_snapshot,
789 _in_progress_typeck_results,
792 self.in_snapshot.set(was_in_snapshot);
793 self.universe.set(universe);
795 let mut inner = self.inner.borrow_mut();
796 inner.rollback_to(undo_snapshot);
797 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
800 #[instrument(skip(self, snapshot), level = "debug")]
801 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
802 let CombinedSnapshot {
804 region_constraints_snapshot: _,
807 _in_progress_typeck_results,
810 self.in_snapshot.set(was_in_snapshot);
812 self.inner.borrow_mut().commit(undo_snapshot);
815 /// Executes `f` and commit the bindings.
816 #[instrument(skip(self, f), level = "debug")]
817 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
819 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
821 let snapshot = self.start_snapshot();
822 let r = f(&snapshot);
823 self.commit_from(snapshot);
827 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
828 #[instrument(skip(self, f), level = "debug")]
829 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
831 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
833 let snapshot = self.start_snapshot();
834 let r = f(&snapshot);
835 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
838 self.commit_from(snapshot);
841 self.rollback_to("commit_if_ok -- error", snapshot);
847 /// Execute `f` then unroll any bindings it creates.
848 #[instrument(skip(self, f), level = "debug")]
849 pub fn probe<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.rollback_to("probe", snapshot);
859 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
860 #[instrument(skip(self, f), level = "debug")]
861 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
863 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
865 let snapshot = self.start_snapshot();
866 let was_skip_leak_check = self.skip_leak_check.get();
868 self.skip_leak_check.set(true);
870 let r = f(&snapshot);
871 self.rollback_to("probe", snapshot);
872 self.skip_leak_check.set(was_skip_leak_check);
876 /// Scan the constraints produced since `snapshot` began and returns:
878 /// - `None` -- if none of them involve "region outlives" constraints
879 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
880 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
881 pub fn region_constraints_added_in_snapshot(
883 snapshot: &CombinedSnapshot<'a, 'tcx>,
887 .unwrap_region_constraints()
888 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
891 pub fn opaque_types_added_in_snapshot(&self, snapshot: &CombinedSnapshot<'a, 'tcx>) -> bool {
892 self.inner.borrow().undo_log.opaque_types_in_snapshot(&snapshot.undo_snapshot)
895 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
896 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
899 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
901 T: at::ToTrace<'tcx>,
903 let origin = &ObligationCause::dummy();
905 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
906 // Ignore obligations, since we are unrolling
907 // everything anyway.
912 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
914 T: at::ToTrace<'tcx>,
916 let origin = &ObligationCause::dummy();
918 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
919 // Ignore obligations, since we are unrolling
920 // everything anyway.
925 #[instrument(skip(self), level = "debug")]
928 origin: SubregionOrigin<'tcx>,
932 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
935 /// Require that the region `r` be equal to one of the regions in
936 /// the set `regions`.
937 #[instrument(skip(self), level = "debug")]
938 pub fn member_constraint(
940 opaque_type_def_id: DefId,
941 definition_span: Span,
943 region: ty::Region<'tcx>,
944 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
946 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
955 /// Processes a `Coerce` predicate from the fulfillment context.
956 /// This is NOT the preferred way to handle coercion, which is to
957 /// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
959 /// This method here is actually a fallback that winds up being
960 /// invoked when `FnCtxt::coerce` encounters unresolved type variables
961 /// and records a coercion predicate. Presently, this method is equivalent
962 /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
963 /// actually requiring `a <: b`. This is of course a valid coercion,
964 /// but it's not as flexible as `FnCtxt::coerce` would be.
966 /// (We may refactor this in the future, but there are a number of
967 /// practical obstacles. Among other things, `FnCtxt::coerce` presently
968 /// records adjustments that are required on the HIR in order to perform
969 /// the coercion, and we don't currently have a way to manage that.)
970 pub fn coerce_predicate(
972 cause: &ObligationCause<'tcx>,
973 param_env: ty::ParamEnv<'tcx>,
974 predicate: ty::PolyCoercePredicate<'tcx>,
975 ) -> Option<InferResult<'tcx, ()>> {
976 let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
977 a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
981 self.subtype_predicate(cause, param_env, subtype_predicate)
984 pub fn subtype_predicate(
986 cause: &ObligationCause<'tcx>,
987 param_env: ty::ParamEnv<'tcx>,
988 predicate: ty::PolySubtypePredicate<'tcx>,
989 ) -> Option<InferResult<'tcx, ()>> {
990 // Check for two unresolved inference variables, in which case we can
991 // make no progress. This is partly a micro-optimization, but it's
992 // also an opportunity to "sub-unify" the variables. This isn't
993 // *necessary* to prevent cycles, because they would eventually be sub-unified
994 // anyhow during generalization, but it helps with diagnostics (we can detect
995 // earlier that they are sub-unified).
997 // Note that we can just skip the binders here because
998 // type variables can't (at present, at
999 // least) capture any of the things bound by this binder.
1001 // Note that this sub here is not just for diagnostics - it has semantic
1003 let r_a = self.shallow_resolve(predicate.skip_binder().a);
1004 let r_b = self.shallow_resolve(predicate.skip_binder().b);
1005 match (r_a.kind(), r_b.kind()) {
1006 (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
1007 self.inner.borrow_mut().type_variables().sub(a_vid, b_vid);
1013 Some(self.commit_if_ok(|_snapshot| {
1014 let ty::SubtypePredicate { a_is_expected, a, b } =
1015 self.replace_bound_vars_with_placeholders(predicate);
1017 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1023 pub fn region_outlives_predicate(
1025 cause: &traits::ObligationCause<'tcx>,
1026 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1027 ) -> UnitResult<'tcx> {
1028 self.commit_if_ok(|_snapshot| {
1029 let ty::OutlivesPredicate(r_a, r_b) =
1030 self.replace_bound_vars_with_placeholders(predicate);
1031 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1032 RelateRegionParamBound(cause.span)
1034 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1039 /// Number of type variables created so far.
1040 pub fn num_ty_vars(&self) -> usize {
1041 self.inner.borrow_mut().type_variables().num_vars()
1044 pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid {
1045 self.inner.borrow_mut().type_variables().new_var(self.universe(), origin)
1048 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1049 self.tcx.mk_ty_var(self.next_ty_var_id(origin))
1052 pub fn next_ty_var_id_in_universe(
1054 origin: TypeVariableOrigin,
1055 universe: ty::UniverseIndex,
1057 self.inner.borrow_mut().type_variables().new_var(universe, origin)
1060 pub fn next_ty_var_in_universe(
1062 origin: TypeVariableOrigin,
1063 universe: ty::UniverseIndex,
1065 let vid = self.next_ty_var_id_in_universe(origin, universe);
1066 self.tcx.mk_ty_var(vid)
1069 pub fn next_const_var(&self, ty: Ty<'tcx>, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
1070 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1073 pub fn next_const_var_in_universe(
1076 origin: ConstVariableOrigin,
1077 universe: ty::UniverseIndex,
1078 ) -> ty::Const<'tcx> {
1082 .const_unification_table()
1083 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1084 self.tcx.mk_const_var(vid, ty)
1087 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1088 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1090 val: ConstVariableValue::Unknown { universe: self.universe() },
1094 fn next_int_var_id(&self) -> IntVid {
1095 self.inner.borrow_mut().int_unification_table().new_key(None)
1098 pub fn next_int_var(&self) -> Ty<'tcx> {
1099 self.tcx.mk_int_var(self.next_int_var_id())
1102 fn next_float_var_id(&self) -> FloatVid {
1103 self.inner.borrow_mut().float_unification_table().new_key(None)
1106 pub fn next_float_var(&self) -> Ty<'tcx> {
1107 self.tcx.mk_float_var(self.next_float_var_id())
1110 /// Creates a fresh region variable with the next available index.
1111 /// The variable will be created in the maximum universe created
1112 /// thus far, allowing it to name any region created thus far.
1113 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1114 self.next_region_var_in_universe(origin, self.universe())
1117 /// Creates a fresh region variable with the next available index
1118 /// in the given universe; typically, you can use
1119 /// `next_region_var` and just use the maximal universe.
1120 pub fn next_region_var_in_universe(
1122 origin: RegionVariableOrigin,
1123 universe: ty::UniverseIndex,
1124 ) -> ty::Region<'tcx> {
1126 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1127 self.tcx.mk_region(ty::ReVar(region_var))
1130 /// Return the universe that the region `r` was created in. For
1131 /// most regions (e.g., `'static`, named regions from the user,
1132 /// etc) this is the root universe U0. For inference variables or
1133 /// placeholders, however, it will return the universe which which
1134 /// they are associated.
1135 pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1136 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1139 /// Number of region variables created so far.
1140 pub fn num_region_vars(&self) -> usize {
1141 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1144 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1145 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1146 self.next_region_var(RegionVariableOrigin::Nll(origin))
1149 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1150 pub fn next_nll_region_var_in_universe(
1152 origin: NllRegionVariableOrigin,
1153 universe: ty::UniverseIndex,
1154 ) -> ty::Region<'tcx> {
1155 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1158 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1160 GenericParamDefKind::Lifetime => {
1161 // Create a region inference variable for the given
1162 // region parameter definition.
1163 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1165 GenericParamDefKind::Type { .. } => {
1166 // Create a type inference variable for the given
1167 // type parameter definition. The substitutions are
1168 // for actual parameters that may be referred to by
1169 // the default of this type parameter, if it exists.
1170 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1171 // used in a path such as `Foo::<T, U>::new()` will
1172 // use an inference variable for `C` with `[T, U]`
1173 // as the substitutions for the default, `(T, U)`.
1174 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1176 TypeVariableOrigin {
1177 kind: TypeVariableOriginKind::TypeParameterDefinition(
1185 self.tcx.mk_ty_var(ty_var_id).into()
1187 GenericParamDefKind::Const { .. } => {
1188 let origin = ConstVariableOrigin {
1189 kind: ConstVariableOriginKind::ConstParameterDefinition(
1196 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1198 val: ConstVariableValue::Unknown { universe: self.universe() },
1200 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1205 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1206 /// type/region parameter to a fresh inference variable.
1207 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1208 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1211 /// Returns `true` if errors have been reported since this infcx was
1212 /// created. This is sometimes used as a heuristic to skip
1213 /// reporting errors that often occur as a result of earlier
1214 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1215 /// inference variables, regionck errors).
1216 pub fn is_tainted_by_errors(&self) -> bool {
1218 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1219 tainted_by_errors_flag={})",
1220 self.tcx.sess.err_count(),
1221 self.err_count_on_creation,
1222 self.tainted_by_errors_flag.get()
1225 if self.tcx.sess.err_count() > self.err_count_on_creation {
1226 return true; // errors reported since this infcx was made
1228 self.tainted_by_errors_flag.get()
1231 /// Set the "tainted by errors" flag to true. We call this when we
1232 /// observe an error from a prior pass.
1233 pub fn set_tainted_by_errors(&self) {
1234 debug!("set_tainted_by_errors()");
1235 self.tainted_by_errors_flag.set(true)
1238 pub fn skip_region_resolution(&self) {
1239 let (var_infos, _) = {
1240 let mut inner = self.inner.borrow_mut();
1241 let inner = &mut *inner;
1242 // Note: `inner.region_obligations` may not be empty, because we
1243 // didn't necessarily call `process_registered_region_obligations`.
1244 // This is okay, because that doesn't introduce new vars.
1246 .region_constraint_storage
1248 .expect("regions already resolved")
1249 .with_log(&mut inner.undo_log)
1250 .into_infos_and_data()
1253 let lexical_region_resolutions = LexicalRegionResolutions {
1254 values: rustc_index::vec::IndexVec::from_elem_n(
1255 crate::infer::lexical_region_resolve::VarValue::Value(self.tcx.lifetimes.re_erased),
1260 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1261 assert!(old_value.is_none());
1264 /// Process the region constraints and return any any errors that
1265 /// result. After this, no more unification operations should be
1266 /// done -- or the compiler will panic -- but it is legal to use
1267 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1268 pub fn resolve_regions(
1270 outlives_env: &OutlivesEnvironment<'tcx>,
1271 ) -> Vec<RegionResolutionError<'tcx>> {
1272 let (var_infos, data) = {
1273 let mut inner = self.inner.borrow_mut();
1274 let inner = &mut *inner;
1276 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1277 "region_obligations not empty: {:#?}",
1278 inner.region_obligations
1281 .region_constraint_storage
1283 .expect("regions already resolved")
1284 .with_log(&mut inner.undo_log)
1285 .into_infos_and_data()
1288 let region_rels = &RegionRelations::new(self.tcx, outlives_env.free_region_map());
1290 let (lexical_region_resolutions, errors) =
1291 lexical_region_resolve::resolve(outlives_env.param_env, region_rels, var_infos, data);
1293 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1294 assert!(old_value.is_none());
1299 /// Process the region constraints and report any errors that
1300 /// result. After this, no more unification operations should be
1301 /// done -- or the compiler will panic -- but it is legal to use
1302 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1303 pub fn resolve_regions_and_report_errors(&self, outlives_env: &OutlivesEnvironment<'tcx>) {
1304 let errors = self.resolve_regions(outlives_env);
1306 if !self.is_tainted_by_errors() {
1307 // As a heuristic, just skip reporting region errors
1308 // altogether if other errors have been reported while
1309 // this infcx was in use. This is totally hokey but
1310 // otherwise we have a hard time separating legit region
1311 // errors from silly ones.
1312 self.report_region_errors(&errors);
1316 /// Obtains (and clears) the current set of region
1317 /// constraints. The inference context is still usable: further
1318 /// unifications will simply add new constraints.
1320 /// This method is not meant to be used with normal lexical region
1321 /// resolution. Rather, it is used in the NLL mode as a kind of
1322 /// interim hack: basically we run normal type-check and generate
1323 /// region constraints as normal, but then we take them and
1324 /// translate them into the form that the NLL solver
1325 /// understands. See the NLL module for mode details.
1326 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1328 self.inner.borrow().region_obligations.is_empty(),
1329 "region_obligations not empty: {:#?}",
1330 self.inner.borrow().region_obligations
1333 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1336 /// Gives temporary access to the region constraint data.
1337 pub fn with_region_constraints<R>(
1339 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1341 let mut inner = self.inner.borrow_mut();
1342 op(inner.unwrap_region_constraints().data())
1345 pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
1346 let mut inner = self.inner.borrow_mut();
1347 let inner = &mut *inner;
1349 .region_constraint_storage
1351 .expect("regions already resolved")
1352 .with_log(&mut inner.undo_log)
1356 /// Takes ownership of the list of variable regions. This implies
1357 /// that all the region constraints have already been taken, and
1358 /// hence that `resolve_regions_and_report_errors` can never be
1359 /// called. This is used only during NLL processing to "hand off" ownership
1360 /// of the set of region variables into the NLL region context.
1361 pub fn take_region_var_origins(&self) -> VarInfos {
1362 let mut inner = self.inner.borrow_mut();
1363 let (var_infos, data) = inner
1364 .region_constraint_storage
1366 .expect("regions already resolved")
1367 .with_log(&mut inner.undo_log)
1368 .into_infos_and_data();
1369 assert!(data.is_empty());
1373 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1374 self.resolve_vars_if_possible(t).to_string()
1377 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1378 /// universe index of `TyVar(vid)`.
1379 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1380 use self::type_variable::TypeVariableValue;
1382 match self.inner.borrow_mut().type_variables().probe(vid) {
1383 TypeVariableValue::Known { value } => Ok(value),
1384 TypeVariableValue::Unknown { universe } => Err(universe),
1388 /// Resolve any type variables found in `value` -- but only one
1389 /// level. So, if the variable `?X` is bound to some type
1390 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1391 /// itself be bound to a type).
1393 /// Useful when you only need to inspect the outermost level of
1394 /// the type and don't care about nested types (or perhaps you
1395 /// will be resolving them as well, e.g. in a loop).
1396 pub fn shallow_resolve<T>(&self, value: T) -> T
1398 T: TypeFoldable<'tcx>,
1400 value.fold_with(&mut ShallowResolver { infcx: self })
1403 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1404 self.inner.borrow_mut().type_variables().root_var(var)
1407 /// Where possible, replaces type/const variables in
1408 /// `value` with their final value. Note that region variables
1409 /// are unaffected. If a type/const variable has not been unified, it
1410 /// is left as is. This is an idempotent operation that does
1411 /// not affect inference state in any way and so you can do it
1413 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1415 T: TypeFoldable<'tcx>,
1417 if !value.needs_infer() {
1418 return value; // Avoid duplicated subst-folding.
1420 let mut r = resolve::OpportunisticVarResolver::new(self);
1421 value.fold_with(&mut r)
1424 pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
1426 T: TypeFoldable<'tcx>,
1428 if !value.needs_infer() {
1429 return value; // Avoid duplicated subst-folding.
1431 let mut r = InferenceLiteralEraser { tcx: self.tcx };
1432 value.fold_with(&mut r)
1435 /// Returns the first unresolved variable contained in `T`. In the
1436 /// process of visiting `T`, this will resolve (where possible)
1437 /// type variables in `T`, but it never constructs the final,
1438 /// resolved type, so it's more efficient than
1439 /// `resolve_vars_if_possible()`.
1440 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1442 T: TypeVisitable<'tcx>,
1444 value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1447 pub fn probe_const_var(
1449 vid: ty::ConstVid<'tcx>,
1450 ) -> Result<ty::Const<'tcx>, ty::UniverseIndex> {
1451 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1452 ConstVariableValue::Known { value } => Ok(value),
1453 ConstVariableValue::Unknown { universe } => Err(universe),
1457 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1459 * Attempts to resolve all type/region/const variables in
1460 * `value`. Region inference must have been run already (e.g.,
1461 * by calling `resolve_regions_and_report_errors`). If some
1462 * variable was never unified, an `Err` results.
1464 * This method is idempotent, but it not typically not invoked
1465 * except during the writeback phase.
1468 resolve::fully_resolve(self, value)
1471 // [Note-Type-error-reporting]
1472 // An invariant is that anytime the expected or actual type is Error (the special
1473 // error type, meaning that an error occurred when typechecking this expression),
1474 // this is a derived error. The error cascaded from another error (that was already
1475 // reported), so it's not useful to display it to the user.
1476 // The following methods implement this logic.
1477 // They check if either the actual or expected type is Error, and don't print the error
1478 // in this case. The typechecker should only ever report type errors involving mismatched
1479 // types using one of these methods, and should not call span_err directly for such
1482 pub fn type_error_struct_with_diag<M>(
1486 actual_ty: Ty<'tcx>,
1487 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>
1489 M: FnOnce(String) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
1491 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1492 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1494 let mut err = mk_diag(self.ty_to_string(actual_ty));
1496 // Don't report an error if actual type is `Error`.
1497 if actual_ty.references_error() {
1498 err.downgrade_to_delayed_bug();
1504 pub fn report_mismatched_types(
1506 cause: &ObligationCause<'tcx>,
1509 err: TypeError<'tcx>,
1510 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1511 let trace = TypeTrace::types(cause, true, expected, actual);
1512 self.report_and_explain_type_error(trace, &err)
1515 pub fn report_mismatched_consts(
1517 cause: &ObligationCause<'tcx>,
1518 expected: ty::Const<'tcx>,
1519 actual: ty::Const<'tcx>,
1520 err: TypeError<'tcx>,
1521 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1522 let trace = TypeTrace::consts(cause, true, expected, actual);
1523 self.report_and_explain_type_error(trace, &err)
1526 pub fn replace_bound_vars_with_fresh_vars<T>(
1529 lbrct: LateBoundRegionConversionTime,
1530 value: ty::Binder<'tcx, T>,
1533 T: TypeFoldable<'tcx> + Copy,
1535 if let Some(inner) = value.no_bound_vars() {
1539 let mut region_map = FxHashMap::default();
1540 let fld_r = |br: ty::BoundRegion| {
1543 .or_insert_with(|| self.next_region_var(LateBoundRegion(span, br.kind, lbrct)))
1546 let mut ty_map = FxHashMap::default();
1547 let fld_t = |bt: ty::BoundTy| {
1548 *ty_map.entry(bt).or_insert_with(|| {
1549 self.next_ty_var(TypeVariableOrigin {
1550 kind: TypeVariableOriginKind::MiscVariable,
1555 let mut ct_map = FxHashMap::default();
1556 let fld_c = |bc: ty::BoundVar, ty| {
1557 *ct_map.entry(bc).or_insert_with(|| {
1558 self.next_const_var(
1560 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1564 self.tcx.replace_bound_vars_uncached(value, fld_r, fld_t, fld_c)
1567 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1568 pub fn verify_generic_bound(
1570 origin: SubregionOrigin<'tcx>,
1571 kind: GenericKind<'tcx>,
1572 a: ty::Region<'tcx>,
1573 bound: VerifyBound<'tcx>,
1575 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1579 .unwrap_region_constraints()
1580 .verify_generic_bound(origin, kind, a, bound);
1583 /// Obtains the latest type of the given closure; this may be a
1584 /// closure in the current function, in which case its
1585 /// `ClosureKind` may not yet be known.
1586 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1587 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1588 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1589 closure_kind_ty.to_opt_closure_kind()
1592 /// Clears the selection, evaluation, and projection caches. This is useful when
1593 /// repeatedly attempting to select an `Obligation` while changing only
1594 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1595 pub fn clear_caches(&self) {
1596 self.selection_cache.clear();
1597 self.evaluation_cache.clear();
1598 self.inner.borrow_mut().projection_cache().clear();
1601 pub fn universe(&self) -> ty::UniverseIndex {
1605 /// Creates and return a fresh universe that extends all previous
1606 /// universes. Updates `self.universe` to that new universe.
1607 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1608 let u = self.universe.get().next_universe();
1609 self.universe.set(u);
1613 pub fn try_const_eval_resolve(
1615 param_env: ty::ParamEnv<'tcx>,
1616 unevaluated: ty::Unevaluated<'tcx>,
1619 ) -> Result<ty::Const<'tcx>, ErrorHandled> {
1620 match self.const_eval_resolve(param_env, unevaluated, span) {
1621 Ok(Some(val)) => Ok(ty::Const::from_value(self.tcx, val, ty)),
1624 let def_id = unevaluated.def.did;
1626 tcx.def_span(def_id),
1627 "unable to construct a constant value for the unevaluated constant {:?}",
1631 Err(err) => Err(err),
1635 /// Resolves and evaluates a constant.
1637 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1638 /// substitutions and environment are used to resolve the constant. Alternatively if the
1639 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1640 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1641 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1642 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1645 /// This handles inferences variables within both `param_env` and `substs` by
1646 /// performing the operation on their respective canonical forms.
1647 #[instrument(skip(self), level = "debug")]
1648 pub fn const_eval_resolve(
1650 param_env: ty::ParamEnv<'tcx>,
1651 unevaluated: ty::Unevaluated<'tcx>,
1653 ) -> EvalToValTreeResult<'tcx> {
1654 let substs = self.resolve_vars_if_possible(unevaluated.substs);
1657 // Postpone the evaluation of constants whose substs depend on inference
1659 if substs.has_infer_types_or_consts() {
1660 debug!("substs have infer types or consts: {:?}", substs);
1661 return Err(ErrorHandled::TooGeneric);
1664 let param_env_erased = self.tcx.erase_regions(param_env);
1665 let substs_erased = self.tcx.erase_regions(substs);
1666 debug!(?param_env_erased);
1667 debug!(?substs_erased);
1669 let unevaluated = ty::Unevaluated {
1670 def: unevaluated.def,
1671 substs: substs_erased,
1672 promoted: unevaluated.promoted,
1675 // The return value is the evaluated value which doesn't contain any reference to inference
1676 // variables, thus we don't need to substitute back the original values.
1677 self.tcx.const_eval_resolve_for_typeck(param_env_erased, unevaluated, span)
1680 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1681 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1682 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1684 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1685 /// inlined, despite being large, because it has only two call sites that
1686 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1687 /// inference variables), and it handles both `Ty` and `ty::Const` without
1688 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1690 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1692 TyOrConstInferVar::Ty(v) => {
1693 use self::type_variable::TypeVariableValue;
1695 // If `inlined_probe` returns a `Known` value, it never equals
1696 // `ty::Infer(ty::TyVar(v))`.
1697 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1698 TypeVariableValue::Unknown { .. } => false,
1699 TypeVariableValue::Known { .. } => true,
1703 TyOrConstInferVar::TyInt(v) => {
1704 // If `inlined_probe_value` returns a value it's always a
1705 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1707 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1710 TyOrConstInferVar::TyFloat(v) => {
1711 // If `probe_value` returns a value it's always a
1712 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1714 // Not `inlined_probe_value(v)` because this call site is colder.
1715 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1718 TyOrConstInferVar::Const(v) => {
1719 // If `probe_value` returns a `Known` value, it never equals
1720 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1722 // Not `inlined_probe_value(v)` because this call site is colder.
1723 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1724 ConstVariableValue::Unknown { .. } => false,
1725 ConstVariableValue::Known { .. } => true,
1732 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1733 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1734 #[derive(Copy, Clone, Debug)]
1735 pub enum TyOrConstInferVar<'tcx> {
1736 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1738 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1740 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1743 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1744 Const(ConstVid<'tcx>),
1747 impl<'tcx> TyOrConstInferVar<'tcx> {
1748 /// Tries to extract an inference variable from a type or a constant, returns `None`
1749 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1750 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1751 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1752 match arg.unpack() {
1753 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1754 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1755 GenericArgKind::Lifetime(_) => None,
1759 /// Tries to extract an inference variable from a type, returns `None`
1760 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1761 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1763 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1764 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1765 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1770 /// Tries to extract an inference variable from a constant, returns `None`
1771 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1772 pub fn maybe_from_const(ct: ty::Const<'tcx>) -> Option<Self> {
1774 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1780 /// Replace `{integer}` with `i32` and `{float}` with `f64`.
1781 /// Used only for diagnostics.
1782 struct InferenceLiteralEraser<'tcx> {
1786 impl<'tcx> TypeFolder<'tcx> for InferenceLiteralEraser<'tcx> {
1787 fn tcx(&self) -> TyCtxt<'tcx> {
1791 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1793 ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => self.tcx.types.i32,
1794 ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => self.tcx.types.f64,
1795 _ => ty.super_fold_with(self),
1800 struct ShallowResolver<'a, 'tcx> {
1801 infcx: &'a InferCtxt<'a, 'tcx>,
1804 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1805 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1809 /// If `ty` is a type variable of some kind, resolve it one level
1810 /// (but do not resolve types found in the result). If `typ` is
1811 /// not a type variable, just return it unmodified.
1812 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1814 ty::Infer(ty::TyVar(v)) => {
1815 // Not entirely obvious: if `typ` is a type variable,
1816 // it can be resolved to an int/float variable, which
1817 // can then be recursively resolved, hence the
1818 // recursion. Note though that we prevent type
1819 // variables from unifying to other type variables
1820 // directly (though they may be embedded
1821 // structurally), and we prevent cycles in any case,
1822 // so this recursion should always be of very limited
1825 // Note: if these two lines are combined into one we get
1826 // dynamic borrow errors on `self.inner`.
1827 let known = self.infcx.inner.borrow_mut().type_variables().probe(v).known();
1828 known.map_or(ty, |t| self.fold_ty(t))
1831 ty::Infer(ty::IntVar(v)) => self
1835 .int_unification_table()
1837 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1839 ty::Infer(ty::FloatVar(v)) => self
1843 .float_unification_table()
1845 .map_or(ty, |v| v.to_type(self.infcx.tcx)),
1851 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1852 if let ty::ConstKind::Infer(InferConst::Var(vid)) = ct.kind() {
1856 .const_unification_table()
1867 impl<'tcx> TypeTrace<'tcx> {
1868 pub fn span(&self) -> Span {
1873 cause: &ObligationCause<'tcx>,
1874 a_is_expected: bool,
1877 ) -> TypeTrace<'tcx> {
1879 cause: cause.clone(),
1880 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1885 cause: &ObligationCause<'tcx>,
1886 a_is_expected: bool,
1889 ) -> TypeTrace<'tcx> {
1891 cause: cause.clone(),
1892 values: Terms(ExpectedFound::new(a_is_expected, a.into(), b.into())),
1897 impl<'tcx> SubregionOrigin<'tcx> {
1898 pub fn span(&self) -> Span {
1900 Subtype(ref a) => a.span(),
1901 RelateObjectBound(a) => a,
1902 RelateParamBound(a, ..) => a,
1903 RelateRegionParamBound(a) => a,
1905 ReborrowUpvar(a, _) => a,
1906 DataBorrowed(_, a) => a,
1907 ReferenceOutlivesReferent(_, a) => a,
1908 CompareImplMethodObligation { span, .. } => span,
1909 CompareImplTypeObligation { span, .. } => span,
1910 CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
1914 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1916 F: FnOnce() -> Self,
1918 match *cause.code() {
1919 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1920 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1923 traits::ObligationCauseCode::CompareImplMethodObligation {
1926 } => SubregionOrigin::CompareImplMethodObligation {
1932 traits::ObligationCauseCode::CompareImplTypeObligation {
1935 } => SubregionOrigin::CompareImplTypeObligation {
1941 traits::ObligationCauseCode::CheckAssociatedTypeBounds {
1944 } => SubregionOrigin::CheckAssociatedTypeBounds {
1947 parent: Box::new(default()),
1955 impl RegionVariableOrigin {
1956 pub fn span(&self) -> Span {
1963 | EarlyBoundRegion(a, ..)
1964 | LateBoundRegion(a, ..)
1965 | UpvarRegion(_, a) => a,
1966 Nll(..) => bug!("NLL variable used with `span`"),
1971 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1972 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1975 "RegionObligation(sub_region={:?}, sup_type={:?})",
1976 self.sub_region, self.sup_type