1 //! See the Book for more information.
3 pub use self::freshen::TypeFreshener;
4 pub use self::LateBoundRegionConversionTime::*;
5 pub use self::RegionVariableOrigin::*;
6 pub use self::SubregionOrigin::*;
7 pub use self::ValuePairs::*;
9 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
11 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
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::middle::region;
24 use rustc_middle::mir;
25 use rustc_middle::mir::interpret::ConstEvalResult;
26 use rustc_middle::traits::select;
27 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
28 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
29 use rustc_middle::ty::relate::RelateResult;
30 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
31 pub use rustc_middle::ty::IntVarValue;
32 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
33 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
34 use rustc_session::config::BorrowckMode;
35 use rustc_span::symbol::Symbol;
38 use std::cell::{Cell, Ref, RefCell};
39 use std::collections::BTreeMap;
42 use self::combine::CombineFields;
43 use self::free_regions::RegionRelations;
44 use self::lexical_region_resolve::LexicalRegionResolutions;
45 use self::outlives::env::OutlivesEnvironment;
46 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
47 use self::region_constraints::{
48 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
50 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
56 pub mod error_reporting;
63 mod lexical_region_resolve;
67 pub mod region_constraints;
70 pub mod type_variable;
73 use crate::infer::canonical::OriginalQueryValues;
74 pub use rustc_middle::infer::unify_key;
78 pub struct InferOk<'tcx, T> {
80 pub obligations: PredicateObligations<'tcx>,
82 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
84 pub type Bound<T> = Option<T>;
85 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
86 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
88 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
89 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
92 /// How we should handle region solving.
94 /// This is used so that the region values inferred by HIR region solving are
95 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
96 /// typeck will also do.
97 #[derive(Copy, Clone, Debug)]
98 pub enum RegionckMode {
99 /// The default mode: report region errors, don't erase regions.
101 /// Erase the results of region after solving.
103 /// A flag that is used to suppress region errors, when we are doing
104 /// region checks that the NLL borrow checker will also do -- it might
106 suppress_errors: bool,
110 impl Default for RegionckMode {
111 fn default() -> Self {
117 pub fn suppressed(self) -> bool {
119 Self::Solve => false,
120 Self::Erase { suppress_errors } => suppress_errors,
124 /// Indicates that the MIR borrowck will repeat these region
125 /// checks, so we should ignore errors if NLL is (unconditionally)
127 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
128 // FIXME(Centril): Once we actually remove `::Migrate` also make
129 // this always `true` and then proceed to eliminate the dead code.
130 match tcx.borrowck_mode() {
131 // If we're on Migrate mode, report AST region errors
132 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
134 // If we're on MIR, don't report AST region errors as they should be reported by NLL
135 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
140 /// This type contains all the things within `InferCtxt` that sit within a
141 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
142 /// operations are hot enough that we want only one call to `borrow_mut` per
143 /// call to `start_snapshot` and `rollback_to`.
144 pub struct InferCtxtInner<'tcx> {
145 /// Cache for projections. This cache is snapshotted along with the infcx.
147 /// Public so that `traits::project` can use it.
148 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
150 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
151 /// that might instantiate a general type variable have an order,
152 /// represented by its upper and lower bounds.
153 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
155 /// Map from const parameter variable to the kind of const it represents.
156 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
158 /// Map from integral variable to the kind of integer it represents.
159 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
161 /// Map from floating variable to the kind of float it represents.
162 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
164 /// Tracks the set of region variables and the constraints between them.
165 /// This is initially `Some(_)` but when
166 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
167 /// -- further attempts to perform unification, etc., may fail if new
168 /// region constraints would've been added.
169 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
171 /// A set of constraints that regionck must validate. Each
172 /// constraint has the form `T:'a`, meaning "some type `T` must
173 /// outlive the lifetime 'a". These constraints derive from
174 /// instantiated type parameters. So if you had a struct defined
177 /// struct Foo<T:'static> { ... }
179 /// then in some expression `let x = Foo { ... }` it will
180 /// instantiate the type parameter `T` with a fresh type `$0`. At
181 /// the same time, it will record a region obligation of
182 /// `$0:'static`. This will get checked later by regionck. (We
183 /// can't generally check these things right away because we have
184 /// to wait until types are resolved.)
186 /// These are stored in a map keyed to the id of the innermost
187 /// enclosing fn body / static initializer expression. This is
188 /// because the location where the obligation was incurred can be
189 /// relevant with respect to which sublifetime assumptions are in
190 /// place. The reason that we store under the fn-id, and not
191 /// something more fine-grained, is so that it is easier for
192 /// regionck to be sure that it has found *all* the region
193 /// obligations (otherwise, it's easy to fail to walk to a
194 /// particular node-id).
196 /// Before running `resolve_regions_and_report_errors`, the creator
197 /// of the inference context is expected to invoke
198 /// `process_region_obligations` (defined in `self::region_obligations`)
199 /// for each body-id in this map, which will process the
200 /// obligations within. This is expected to be done 'late enough'
201 /// that all type inference variables have been bound and so forth.
202 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
204 undo_log: InferCtxtUndoLogs<'tcx>,
207 impl<'tcx> InferCtxtInner<'tcx> {
208 fn new() -> InferCtxtInner<'tcx> {
210 projection_cache: Default::default(),
211 type_variable_storage: type_variable::TypeVariableStorage::new(),
212 undo_log: InferCtxtUndoLogs::default(),
213 const_unification_storage: ut::UnificationTableStorage::new(),
214 int_unification_storage: ut::UnificationTableStorage::new(),
215 float_unification_storage: ut::UnificationTableStorage::new(),
216 region_constraint_storage: Some(RegionConstraintStorage::new()),
217 region_obligations: vec![],
221 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
222 &self.region_obligations
225 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
226 self.projection_cache.with_log(&mut self.undo_log)
229 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
230 self.type_variable_storage.with_log(&mut self.undo_log)
233 fn int_unification_table(
235 ) -> ut::UnificationTable<
238 &mut ut::UnificationStorage<ty::IntVid>,
239 &mut InferCtxtUndoLogs<'tcx>,
242 self.int_unification_storage.with_log(&mut self.undo_log)
245 fn float_unification_table(
247 ) -> ut::UnificationTable<
250 &mut ut::UnificationStorage<ty::FloatVid>,
251 &mut InferCtxtUndoLogs<'tcx>,
254 self.float_unification_storage.with_log(&mut self.undo_log)
257 fn const_unification_table(
259 ) -> ut::UnificationTable<
262 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
263 &mut InferCtxtUndoLogs<'tcx>,
266 self.const_unification_storage.with_log(&mut self.undo_log)
269 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
270 self.region_constraint_storage
272 .expect("region constraints already solved")
273 .with_log(&mut self.undo_log)
277 pub struct InferCtxt<'a, 'tcx> {
278 pub tcx: TyCtxt<'tcx>,
280 /// During type-checking/inference of a body, `in_progress_tables`
281 /// contains a reference to the tables being built up, which are
282 /// used for reading closure kinds/signatures as they are inferred,
283 /// and for error reporting logic to read arbitrary node types.
284 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
286 pub inner: RefCell<InferCtxtInner<'tcx>>,
288 /// If set, this flag causes us to skip the 'leak check' during
289 /// higher-ranked subtyping operations. This flag is a temporary one used
290 /// to manage the removal of the leak-check: for the time being, we still run the
291 /// leak-check, but we issue warnings. This flag can only be set to true
292 /// when entering a snapshot.
293 skip_leak_check: Cell<bool>,
295 /// Once region inference is done, the values for each variable.
296 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
298 /// Caches the results of trait selection. This cache is used
299 /// for things that have to do with the parameters in scope.
300 pub selection_cache: select::SelectionCache<'tcx>,
302 /// Caches the results of trait evaluation.
303 pub evaluation_cache: select::EvaluationCache<'tcx>,
305 /// the set of predicates on which errors have been reported, to
306 /// avoid reporting the same error twice.
307 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
309 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
311 /// When an error occurs, we want to avoid reporting "derived"
312 /// errors that are due to this original failure. Normally, we
313 /// handle this with the `err_count_on_creation` count, which
314 /// basically just tracks how many errors were reported when we
315 /// started type-checking a fn and checks to see if any new errors
316 /// have been reported since then. Not great, but it works.
318 /// However, when errors originated in other passes -- notably
319 /// resolve -- this heuristic breaks down. Therefore, we have this
320 /// auxiliary flag that one can set whenever one creates a
321 /// type-error that is due to an error in a prior pass.
323 /// Don't read this flag directly, call `is_tainted_by_errors()`
324 /// and `set_tainted_by_errors()`.
325 tainted_by_errors_flag: Cell<bool>,
327 /// Track how many errors were reported when this infcx is created.
328 /// If the number of errors increases, that's also a sign (line
329 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
330 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
331 err_count_on_creation: usize,
333 /// This flag is true while there is an active snapshot.
334 in_snapshot: Cell<bool>,
336 /// What is the innermost universe we have created? Starts out as
337 /// `UniverseIndex::root()` but grows from there as we enter
338 /// universal quantifiers.
340 /// N.B., at present, we exclude the universal quantifiers on the
341 /// item we are type-checking, and just consider those names as
342 /// part of the root universe. So this would only get incremented
343 /// when we enter into a higher-ranked (`for<..>`) type or trait
345 universe: Cell<ty::UniverseIndex>,
348 /// A map returned by `replace_bound_vars_with_placeholders()`
349 /// indicating the placeholder region that each late-bound region was
351 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
353 /// See the `error_reporting` module for more details.
354 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
355 pub enum ValuePairs<'tcx> {
356 Types(ExpectedFound<Ty<'tcx>>),
357 Regions(ExpectedFound<ty::Region<'tcx>>),
358 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
359 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
360 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
363 /// The trace designates the path through inference that we took to
364 /// encounter an error or subtyping constraint.
366 /// See the `error_reporting` module for more details.
367 #[derive(Clone, Debug)]
368 pub struct TypeTrace<'tcx> {
369 cause: ObligationCause<'tcx>,
370 values: ValuePairs<'tcx>,
373 /// The origin of a `r1 <= r2` constraint.
375 /// See `error_reporting` module for more details
376 #[derive(Clone, Debug)]
377 pub enum SubregionOrigin<'tcx> {
378 /// Arose from a subtyping relation
379 Subtype(Box<TypeTrace<'tcx>>),
381 /// Stack-allocated closures cannot outlive innermost loop
382 /// or function so as to ensure we only require finite stack
383 InfStackClosure(Span),
385 /// Invocation of closure must be within its lifetime
388 /// Dereference of reference must be within its lifetime
391 /// Closure bound must not outlive captured variables
392 ClosureCapture(Span, hir::HirId),
394 /// Index into slice must be within its lifetime
397 /// When casting `&'a T` to an `&'b Trait` object,
398 /// relating `'a` to `'b`
399 RelateObjectBound(Span),
401 /// Some type parameter was instantiated with the given type,
402 /// and that type must outlive some region.
403 RelateParamBound(Span, Ty<'tcx>),
405 /// The given region parameter was instantiated with a region
406 /// that must outlive some other region.
407 RelateRegionParamBound(Span),
409 /// A bound placed on type parameters that states that must outlive
410 /// the moment of their instantiation.
411 RelateDefaultParamBound(Span, Ty<'tcx>),
413 /// Creating a pointer `b` to contents of another reference
416 /// Creating a pointer `b` to contents of an upvar
417 ReborrowUpvar(Span, ty::UpvarId),
419 /// Data with type `Ty<'tcx>` was borrowed
420 DataBorrowed(Ty<'tcx>, Span),
422 /// (&'a &'b T) where a >= b
423 ReferenceOutlivesReferent(Ty<'tcx>, Span),
425 /// Type or region parameters must be in scope.
426 ParameterInScope(ParameterOrigin, Span),
428 /// The type T of an expression E must outlive the lifetime for E.
429 ExprTypeIsNotInScope(Ty<'tcx>, Span),
431 /// A `ref b` whose region does not enclose the decl site
432 BindingTypeIsNotValidAtDecl(Span),
434 /// Regions appearing in a method receiver must outlive method call
437 /// Regions appearing in a function argument must outlive func call
440 /// Region in return type of invoked fn must enclose call
443 /// Operands must be in scope
446 /// Region resulting from a `&` expr must enclose the `&` expr
449 /// An auto-borrow that does not enclose the expr where it occurs
452 /// Region constraint arriving from destructor safety
453 SafeDestructor(Span),
455 /// Comparing the signature and requirements of an impl method against
456 /// the containing trait.
457 CompareImplMethodObligation {
460 impl_item_def_id: DefId,
461 trait_item_def_id: DefId,
465 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
466 #[cfg(target_arch = "x86_64")]
467 static_assert_size!(SubregionOrigin<'_>, 32);
469 /// Places that type/region parameters can appear.
470 #[derive(Clone, Copy, Debug)]
471 pub enum ParameterOrigin {
473 MethodCall, // foo.bar() <-- parameters on impl providing bar()
474 OverloadedOperator, // a + b when overloaded
475 OverloadedDeref, // *a when overloaded
478 /// Times when we replace late-bound regions with variables:
479 #[derive(Clone, Copy, Debug)]
480 pub enum LateBoundRegionConversionTime {
481 /// when a fn is called
484 /// when two higher-ranked types are compared
487 /// when projecting an associated type
488 AssocTypeProjection(DefId),
491 /// Reasons to create a region inference variable
493 /// See `error_reporting` module for more details
494 #[derive(Copy, Clone, Debug)]
495 pub enum RegionVariableOrigin {
496 /// Region variables created for ill-categorized reasons,
497 /// mostly indicates places in need of refactoring
500 /// Regions created by a `&P` or `[...]` pattern
503 /// Regions created by `&` operator
506 /// Regions created as part of an autoref of a method receiver
509 /// Regions created as part of an automatic coercion
512 /// Region variables created as the values for early-bound regions
513 EarlyBoundRegion(Span, Symbol),
515 /// Region variables created for bound regions
516 /// in a function or method that is called
517 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
519 UpvarRegion(ty::UpvarId, Span),
521 BoundRegionInCoherence(Symbol),
523 /// This origin is used for the inference variables that we create
524 /// during NLL region processing.
525 NLL(NLLRegionVariableOrigin),
528 #[derive(Copy, Clone, Debug)]
529 pub enum NLLRegionVariableOrigin {
530 /// During NLL region processing, we create variables for free
531 /// regions that we encounter in the function signature and
532 /// elsewhere. This origin indices we've got one of those.
535 /// "Universal" instantiation of a higher-ranked region (e.g.,
536 /// from a `for<'a> T` binder). Meant to represent "any region".
537 Placeholder(ty::PlaceholderRegion),
539 /// The variable we create to represent `'empty(U0)`.
543 /// If this is true, then this variable was created to represent a lifetime
544 /// bound in a `for` binder. For example, it might have been created to
545 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
546 /// Such variables are created when we are trying to figure out if there
547 /// is any valid instantiation of `'a` that could fit into some scenario.
549 /// This is used to inform error reporting: in the case that we are trying to
550 /// determine whether there is any valid instantiation of a `'a` variable that meets
551 /// some constraint C, we want to blame the "source" of that `for` type,
552 /// rather than blaming the source of the constraint C.
557 impl NLLRegionVariableOrigin {
558 pub fn is_universal(self) -> bool {
560 NLLRegionVariableOrigin::FreeRegion => true,
561 NLLRegionVariableOrigin::Placeholder(..) => true,
562 NLLRegionVariableOrigin::Existential { .. } => false,
563 NLLRegionVariableOrigin::RootEmptyRegion => false,
567 pub fn is_existential(self) -> bool {
572 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
573 #[derive(Copy, Clone, Debug)]
574 pub enum FixupError<'tcx> {
575 UnresolvedIntTy(IntVid),
576 UnresolvedFloatTy(FloatVid),
578 UnresolvedConst(ConstVid<'tcx>),
581 /// See the `region_obligations` field for more information.
583 pub struct RegionObligation<'tcx> {
584 pub sub_region: ty::Region<'tcx>,
585 pub sup_type: Ty<'tcx>,
586 pub origin: SubregionOrigin<'tcx>,
589 impl<'tcx> fmt::Display for FixupError<'tcx> {
590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
591 use self::FixupError::*;
594 UnresolvedIntTy(_) => write!(
596 "cannot determine the type of this integer; \
597 add a suffix to specify the type explicitly"
599 UnresolvedFloatTy(_) => write!(
601 "cannot determine the type of this number; \
602 add a suffix to specify the type explicitly"
604 UnresolvedTy(_) => write!(f, "unconstrained type"),
605 UnresolvedConst(_) => write!(f, "unconstrained const value"),
610 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
611 /// Necessary because we can't write the following bound:
612 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
613 pub struct InferCtxtBuilder<'tcx> {
614 global_tcx: TyCtxt<'tcx>,
615 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
618 pub trait TyCtxtInferExt<'tcx> {
619 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
622 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
623 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
624 InferCtxtBuilder { global_tcx: self, fresh_tables: None }
628 impl<'tcx> InferCtxtBuilder<'tcx> {
629 /// Used only by `rustc_typeck` during body type-checking/inference,
630 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
631 pub fn with_fresh_in_progress_tables(mut self, table_owner: LocalDefId) -> Self {
632 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
636 /// Given a canonical value `C` as a starting point, create an
637 /// inference context that contains each of the bound values
638 /// within instantiated as a fresh variable. The `f` closure is
639 /// invoked with the new infcx, along with the instantiated value
640 /// `V` and a substitution `S`. This substitution `S` maps from
641 /// the bound values in `C` to their instantiated values in `V`
642 /// (in other words, `S(C) = V`).
643 pub fn enter_with_canonical<T, R>(
646 canonical: &Canonical<'tcx, T>,
647 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
650 T: TypeFoldable<'tcx>,
654 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
655 f(infcx, value, subst)
659 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
660 let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
661 let in_progress_tables = fresh_tables.as_ref();
662 global_tcx.enter_local(|tcx| {
666 inner: RefCell::new(InferCtxtInner::new()),
667 lexical_region_resolutions: RefCell::new(None),
668 selection_cache: Default::default(),
669 evaluation_cache: Default::default(),
670 reported_trait_errors: Default::default(),
671 reported_closure_mismatch: Default::default(),
672 tainted_by_errors_flag: Cell::new(false),
673 err_count_on_creation: tcx.sess.err_count(),
674 in_snapshot: Cell::new(false),
675 skip_leak_check: Cell::new(false),
676 universe: Cell::new(ty::UniverseIndex::ROOT),
682 impl<'tcx, T> InferOk<'tcx, T> {
683 pub fn unit(self) -> InferOk<'tcx, ()> {
684 InferOk { value: (), obligations: self.obligations }
687 /// Extracts `value`, registering any obligations into `fulfill_cx`.
688 pub fn into_value_registering_obligations(
690 infcx: &InferCtxt<'_, 'tcx>,
691 fulfill_cx: &mut dyn TraitEngine<'tcx>,
693 let InferOk { value, obligations } = self;
694 for obligation in obligations {
695 fulfill_cx.register_predicate_obligation(infcx, obligation);
701 impl<'tcx> InferOk<'tcx, ()> {
702 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
707 #[must_use = "once you start a snapshot, you should always consume it"]
708 pub struct CombinedSnapshot<'a, 'tcx> {
709 undo_snapshot: Snapshot<'tcx>,
710 region_constraints_snapshot: RegionSnapshot,
711 universe: ty::UniverseIndex,
712 was_in_snapshot: bool,
713 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
716 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
717 pub fn is_in_snapshot(&self) -> bool {
718 self.in_snapshot.get()
721 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
722 t.fold_with(&mut self.freshener())
725 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
727 ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
732 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
733 freshen::TypeFreshener::new(self)
736 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
737 use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
738 use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
740 ty::Infer(ty::IntVar(vid)) => {
741 if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
747 ty::Infer(ty::FloatVar(vid)) => {
748 if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
758 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
759 let mut inner = self.inner.borrow_mut();
760 // FIXME(const_generics): should there be an equivalent function for const variables?
762 let mut vars: Vec<Ty<'_>> = inner
764 .unsolved_variables()
766 .map(|t| self.tcx.mk_ty_var(t))
769 (0..inner.int_unification_table().len())
770 .map(|i| ty::IntVid { index: i as u32 })
771 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
772 .map(|v| self.tcx.mk_int_var(v)),
775 (0..inner.float_unification_table().len())
776 .map(|i| ty::FloatVid { index: i as u32 })
777 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
778 .map(|v| self.tcx.mk_float_var(v)),
785 trace: TypeTrace<'tcx>,
786 param_env: ty::ParamEnv<'tcx>,
787 ) -> CombineFields<'a, 'tcx> {
793 obligations: PredicateObligations::new(),
797 /// Clear the "currently in a snapshot" flag, invoke the closure,
798 /// then restore the flag to its original value. This flag is a
799 /// debugging measure designed to detect cases where we start a
800 /// snapshot, create type variables, and register obligations
801 /// which may involve those type variables in the fulfillment cx,
802 /// potentially leaving "dangling type variables" behind.
803 /// In such cases, an assertion will fail when attempting to
804 /// register obligations, within a snapshot. Very useful, much
805 /// better than grovelling through megabytes of `RUSTC_LOG` output.
807 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
808 /// sometimes create a "mini-fulfilment-cx" in which we enroll
809 /// obligations. As long as this fulfillment cx is fully drained
810 /// before we return, this is not a problem, as there won't be any
811 /// escaping obligations in the main cx. In those cases, you can
812 /// use this function.
813 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
815 F: FnOnce(&Self) -> R,
817 let flag = self.in_snapshot.replace(false);
818 let result = func(self);
819 self.in_snapshot.set(flag);
823 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
824 debug!("start_snapshot()");
826 let in_snapshot = self.in_snapshot.replace(true);
828 let mut inner = self.inner.borrow_mut();
831 undo_snapshot: inner.undo_log.start_snapshot(),
832 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
833 universe: self.universe(),
834 was_in_snapshot: in_snapshot,
835 // Borrow tables "in progress" (i.e., during typeck)
836 // to ban writes from within a snapshot to them.
837 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
841 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
842 debug!("rollback_to(cause={})", cause);
843 let CombinedSnapshot {
845 region_constraints_snapshot,
851 self.in_snapshot.set(was_in_snapshot);
852 self.universe.set(universe);
854 let mut inner = self.inner.borrow_mut();
855 inner.rollback_to(undo_snapshot);
856 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
859 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
860 debug!("commit_from()");
861 let CombinedSnapshot {
863 region_constraints_snapshot: _,
869 self.in_snapshot.set(was_in_snapshot);
871 self.inner.borrow_mut().commit(undo_snapshot);
874 /// Executes `f` and commit the bindings.
875 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
877 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
879 debug!("commit_unconditionally()");
880 let snapshot = self.start_snapshot();
881 let r = f(&snapshot);
882 self.commit_from(snapshot);
886 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
887 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
889 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
891 debug!("commit_if_ok()");
892 let snapshot = self.start_snapshot();
893 let r = f(&snapshot);
894 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
897 self.commit_from(snapshot);
900 self.rollback_to("commit_if_ok -- error", snapshot);
906 /// Execute `f` then unroll any bindings it creates.
907 pub fn probe<R, F>(&self, f: F) -> R
909 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
912 let snapshot = self.start_snapshot();
913 let r = f(&snapshot);
914 self.rollback_to("probe", snapshot);
918 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
919 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
921 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
924 let snapshot = self.start_snapshot();
925 let was_skip_leak_check = self.skip_leak_check.get();
927 self.skip_leak_check.set(true);
929 let r = f(&snapshot);
930 self.rollback_to("probe", snapshot);
931 self.skip_leak_check.set(was_skip_leak_check);
935 /// Scan the constraints produced since `snapshot` began and returns:
937 /// - `None` -- if none of them involve "region outlives" constraints
938 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
939 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
940 pub fn region_constraints_added_in_snapshot(
942 snapshot: &CombinedSnapshot<'a, 'tcx>,
946 .unwrap_region_constraints()
947 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
950 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
951 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
954 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
956 T: at::ToTrace<'tcx>,
958 let origin = &ObligationCause::dummy();
960 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
961 // Ignore obligations, since we are unrolling
962 // everything anyway.
967 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
969 T: at::ToTrace<'tcx>,
971 let origin = &ObligationCause::dummy();
973 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
974 // Ignore obligations, since we are unrolling
975 // everything anyway.
982 origin: SubregionOrigin<'tcx>,
986 debug!("sub_regions({:?} <: {:?})", a, b);
987 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
990 /// Require that the region `r` be equal to one of the regions in
991 /// the set `regions`.
992 pub fn member_constraint(
994 opaque_type_def_id: DefId,
995 definition_span: Span,
997 region: ty::Region<'tcx>,
998 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
1000 debug!("member_constraint({:?} <: {:?})", region, in_regions);
1001 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
1010 pub fn subtype_predicate(
1012 cause: &ObligationCause<'tcx>,
1013 param_env: ty::ParamEnv<'tcx>,
1014 predicate: &ty::PolySubtypePredicate<'tcx>,
1015 ) -> Option<InferResult<'tcx, ()>> {
1016 // Subtle: it's ok to skip the binder here and resolve because
1017 // `shallow_resolve` just ignores anything that is not a type
1018 // variable, and because type variable's can't (at present, at
1019 // least) capture any of the things bound by this binder.
1021 // NOTE(nmatsakis): really, there is no *particular* reason to do this
1022 // `shallow_resolve` here except as a micro-optimization.
1023 // Naturally I could not resist.
1024 let two_unbound_type_vars = {
1025 let a = self.shallow_resolve(predicate.skip_binder().a);
1026 let b = self.shallow_resolve(predicate.skip_binder().b);
1027 a.is_ty_var() && b.is_ty_var()
1030 if two_unbound_type_vars {
1031 // Two unbound type variables? Can't make progress.
1035 Some(self.commit_if_ok(|snapshot| {
1036 let (ty::SubtypePredicate { a_is_expected, a, b }, placeholder_map) =
1037 self.replace_bound_vars_with_placeholders(predicate);
1039 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1041 self.leak_check(false, &placeholder_map, snapshot)?;
1047 pub fn region_outlives_predicate(
1049 cause: &traits::ObligationCause<'tcx>,
1050 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
1051 ) -> UnitResult<'tcx> {
1052 self.commit_if_ok(|snapshot| {
1053 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
1054 self.replace_bound_vars_with_placeholders(predicate);
1055 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1056 RelateRegionParamBound(cause.span)
1058 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1059 self.leak_check(false, &placeholder_map, snapshot)?;
1064 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1065 self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
1068 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1069 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1072 pub fn next_ty_var_in_universe(
1074 origin: TypeVariableOrigin,
1075 universe: ty::UniverseIndex,
1077 let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
1078 self.tcx.mk_ty_var(vid)
1081 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1082 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1085 pub fn next_const_var(
1088 origin: ConstVariableOrigin,
1089 ) -> &'tcx 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 ) -> &'tcx 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 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(
1197 TypeVariableOrigin {
1198 kind: TypeVariableOriginKind::TypeParameterDefinition(
1206 self.tcx.mk_ty_var(ty_var_id).into()
1208 GenericParamDefKind::Const { .. } => {
1209 let origin = ConstVariableOrigin {
1210 kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1214 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1216 val: ConstVariableValue::Unknown { universe: self.universe() },
1218 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1223 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1224 /// type/region parameter to a fresh inference variable.
1225 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1226 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1229 /// Returns `true` if errors have been reported since this infcx was
1230 /// created. This is sometimes used as a heuristic to skip
1231 /// reporting errors that often occur as a result of earlier
1232 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1233 /// inference variables, regionck errors).
1234 pub fn is_tainted_by_errors(&self) -> bool {
1236 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1237 tainted_by_errors_flag={})",
1238 self.tcx.sess.err_count(),
1239 self.err_count_on_creation,
1240 self.tainted_by_errors_flag.get()
1243 if self.tcx.sess.err_count() > self.err_count_on_creation {
1244 return true; // errors reported since this infcx was made
1246 self.tainted_by_errors_flag.get()
1249 /// Set the "tainted by errors" flag to true. We call this when we
1250 /// observe an error from a prior pass.
1251 pub fn set_tainted_by_errors(&self) {
1252 debug!("set_tainted_by_errors()");
1253 self.tainted_by_errors_flag.set(true)
1256 /// Process the region constraints and report any errors that
1257 /// result. After this, no more unification operations should be
1258 /// done -- or the compiler will panic -- but it is legal to use
1259 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1260 pub fn resolve_regions_and_report_errors(
1262 region_context: DefId,
1263 region_map: ®ion::ScopeTree,
1264 outlives_env: &OutlivesEnvironment<'tcx>,
1267 let (var_infos, data) = {
1268 let mut inner = self.inner.borrow_mut();
1269 let inner = &mut *inner;
1271 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1272 "region_obligations not empty: {:#?}",
1273 inner.region_obligations
1276 .region_constraint_storage
1278 .expect("regions already resolved")
1279 .with_log(&mut inner.undo_log)
1280 .into_infos_and_data()
1283 let region_rels = &RegionRelations::new(
1287 outlives_env.free_region_map(),
1290 let (lexical_region_resolutions, errors) =
1291 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1293 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1294 assert!(old_value.is_none());
1296 if !self.is_tainted_by_errors() {
1297 // As a heuristic, just skip reporting region errors
1298 // altogether if other errors have been reported while
1299 // this infcx was in use. This is totally hokey but
1300 // otherwise we have a hard time separating legit region
1301 // errors from silly ones.
1302 self.report_region_errors(region_map, &errors);
1306 /// Obtains (and clears) the current set of region
1307 /// constraints. The inference context is still usable: further
1308 /// unifications will simply add new constraints.
1310 /// This method is not meant to be used with normal lexical region
1311 /// resolution. Rather, it is used in the NLL mode as a kind of
1312 /// interim hack: basically we run normal type-check and generate
1313 /// region constraints as normal, but then we take them and
1314 /// translate them into the form that the NLL solver
1315 /// understands. See the NLL module for mode details.
1316 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1318 self.inner.borrow().region_obligations.is_empty(),
1319 "region_obligations not empty: {:#?}",
1320 self.inner.borrow().region_obligations
1323 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1326 /// Gives temporary access to the region constraint data.
1327 #[allow(non_camel_case_types)] // bug with impl trait
1328 pub fn with_region_constraints<R>(
1330 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1332 let mut inner = self.inner.borrow_mut();
1333 op(inner.unwrap_region_constraints().data())
1336 /// Takes ownership of the list of variable regions. This implies
1337 /// that all the region constraints have already been taken, and
1338 /// hence that `resolve_regions_and_report_errors` can never be
1339 /// called. This is used only during NLL processing to "hand off" ownership
1340 /// of the set of region variables into the NLL region context.
1341 pub fn take_region_var_origins(&self) -> VarInfos {
1342 let mut inner = self.inner.borrow_mut();
1343 let (var_infos, data) = inner
1344 .region_constraint_storage
1346 .expect("regions already resolved")
1347 .with_log(&mut inner.undo_log)
1348 .into_infos_and_data();
1349 assert!(data.is_empty());
1353 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1354 self.resolve_vars_if_possible(&t).to_string()
1357 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1358 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1359 format!("({})", tstrs.join(", "))
1362 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1363 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1366 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1367 /// universe index of `TyVar(vid)`.
1368 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1369 use self::type_variable::TypeVariableValue;
1371 match self.inner.borrow_mut().type_variables().probe(vid) {
1372 TypeVariableValue::Known { value } => Ok(value),
1373 TypeVariableValue::Unknown { universe } => Err(universe),
1377 /// Resolve any type variables found in `value` -- but only one
1378 /// level. So, if the variable `?X` is bound to some type
1379 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1380 /// itself be bound to a type).
1382 /// Useful when you only need to inspect the outermost level of
1383 /// the type and don't care about nested types (or perhaps you
1384 /// will be resolving them as well, e.g. in a loop).
1385 pub fn shallow_resolve<T>(&self, value: T) -> T
1387 T: TypeFoldable<'tcx>,
1389 value.fold_with(&mut ShallowResolver { infcx: self })
1392 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1393 self.inner.borrow_mut().type_variables().root_var(var)
1396 /// Where possible, replaces type/const variables in
1397 /// `value` with their final value. Note that region variables
1398 /// are unaffected. If a type/const variable has not been unified, it
1399 /// is left as is. This is an idempotent operation that does
1400 /// not affect inference state in any way and so you can do it
1402 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1404 T: TypeFoldable<'tcx>,
1406 if !value.needs_infer() {
1407 return value.clone(); // Avoid duplicated subst-folding.
1409 let mut r = resolve::OpportunisticVarResolver::new(self);
1410 value.fold_with(&mut r)
1413 /// Returns the first unresolved variable contained in `T`. In the
1414 /// process of visiting `T`, this will resolve (where possible)
1415 /// type variables in `T`, but it never constructs the final,
1416 /// resolved type, so it's more efficient than
1417 /// `resolve_vars_if_possible()`.
1418 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1420 T: TypeFoldable<'tcx>,
1422 let mut r = resolve::UnresolvedTypeFinder::new(self);
1423 value.visit_with(&mut r);
1427 pub fn probe_const_var(
1429 vid: ty::ConstVid<'tcx>,
1430 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1431 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1432 ConstVariableValue::Known { value } => Ok(value),
1433 ConstVariableValue::Unknown { universe } => Err(universe),
1437 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1439 * Attempts to resolve all type/region/const variables in
1440 * `value`. Region inference must have been run already (e.g.,
1441 * by calling `resolve_regions_and_report_errors`). If some
1442 * variable was never unified, an `Err` results.
1444 * This method is idempotent, but it not typically not invoked
1445 * except during the writeback phase.
1448 resolve::fully_resolve(self, value)
1451 // [Note-Type-error-reporting]
1452 // An invariant is that anytime the expected or actual type is Error (the special
1453 // error type, meaning that an error occurred when typechecking this expression),
1454 // this is a derived error. The error cascaded from another error (that was already
1455 // reported), so it's not useful to display it to the user.
1456 // The following methods implement this logic.
1457 // They check if either the actual or expected type is Error, and don't print the error
1458 // in this case. The typechecker should only ever report type errors involving mismatched
1459 // types using one of these methods, and should not call span_err directly for such
1462 pub fn type_error_struct_with_diag<M>(
1466 actual_ty: Ty<'tcx>,
1467 ) -> DiagnosticBuilder<'tcx>
1469 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1471 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1472 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1474 // Don't report an error if actual type is `Error`.
1475 if actual_ty.references_error() {
1476 return self.tcx.sess.diagnostic().struct_dummy();
1479 mk_diag(self.ty_to_string(actual_ty))
1482 pub fn report_mismatched_types(
1484 cause: &ObligationCause<'tcx>,
1487 err: TypeError<'tcx>,
1488 ) -> DiagnosticBuilder<'tcx> {
1489 let trace = TypeTrace::types(cause, true, expected, actual);
1490 self.report_and_explain_type_error(trace, &err)
1493 pub fn report_mismatched_consts(
1495 cause: &ObligationCause<'tcx>,
1496 expected: &'tcx ty::Const<'tcx>,
1497 actual: &'tcx ty::Const<'tcx>,
1498 err: TypeError<'tcx>,
1499 ) -> DiagnosticBuilder<'tcx> {
1500 let trace = TypeTrace::consts(cause, true, expected, actual);
1501 self.report_and_explain_type_error(trace, &err)
1504 pub fn replace_bound_vars_with_fresh_vars<T>(
1507 lbrct: LateBoundRegionConversionTime,
1508 value: &ty::Binder<T>,
1509 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1511 T: TypeFoldable<'tcx>,
1513 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1515 self.next_ty_var(TypeVariableOrigin {
1516 kind: TypeVariableOriginKind::MiscVariable,
1520 let fld_c = |_, ty| {
1521 self.next_const_var(
1523 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1526 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1529 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1530 pub fn verify_generic_bound(
1532 origin: SubregionOrigin<'tcx>,
1533 kind: GenericKind<'tcx>,
1534 a: ty::Region<'tcx>,
1535 bound: VerifyBound<'tcx>,
1537 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1541 .unwrap_region_constraints()
1542 .verify_generic_bound(origin, kind, a, bound);
1545 /// Obtains the latest type of the given closure; this may be a
1546 /// closure in the current function, in which case its
1547 /// `ClosureKind` may not yet be known.
1548 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1549 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1550 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1551 closure_kind_ty.to_opt_closure_kind()
1554 /// Clears the selection, evaluation, and projection caches. This is useful when
1555 /// repeatedly attempting to select an `Obligation` while changing only
1556 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1557 pub fn clear_caches(&self) {
1558 self.selection_cache.clear();
1559 self.evaluation_cache.clear();
1560 self.inner.borrow_mut().projection_cache().clear();
1563 fn universe(&self) -> ty::UniverseIndex {
1567 /// Creates and return a fresh universe that extends all previous
1568 /// universes. Updates `self.universe` to that new universe.
1569 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1570 let u = self.universe.get().next_universe();
1571 self.universe.set(u);
1575 /// Resolves and evaluates a constant.
1577 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1578 /// substitutions and environment are used to resolve the constant. Alternatively if the
1579 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1580 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1581 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1582 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1585 /// This handles inferences variables within both `param_env` and `substs` by
1586 /// performing the operation on their respective canonical forms.
1587 pub fn const_eval_resolve(
1589 param_env: ty::ParamEnv<'tcx>,
1591 substs: SubstsRef<'tcx>,
1592 promoted: Option<mir::Promoted>,
1594 ) -> ConstEvalResult<'tcx> {
1595 let mut original_values = OriginalQueryValues::default();
1596 let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1598 let (param_env, substs) = canonical.value;
1599 // The return value is the evaluated value which doesn't contain any reference to inference
1600 // variables, thus we don't need to substitute back the original values.
1601 self.tcx.const_eval_resolve(param_env, def_id, substs, promoted, span)
1604 /// If `typ` is a type variable of some kind, resolve it one level
1605 /// (but do not resolve types found in the result). If `typ` is
1606 /// not a type variable, just return it unmodified.
1607 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1608 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1610 ty::Infer(ty::TyVar(v)) => {
1611 // Not entirely obvious: if `typ` is a type variable,
1612 // it can be resolved to an int/float variable, which
1613 // can then be recursively resolved, hence the
1614 // recursion. Note though that we prevent type
1615 // variables from unifying to other type variables
1616 // directly (though they may be embedded
1617 // structurally), and we prevent cycles in any case,
1618 // so this recursion should always be of very limited
1621 // Note: if these two lines are combined into one we get
1622 // dynamic borrow errors on `self.inner`.
1623 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1624 known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
1627 ty::Infer(ty::IntVar(v)) => self
1630 .int_unification_table()
1632 .map(|v| v.to_type(self.tcx))
1635 ty::Infer(ty::FloatVar(v)) => self
1638 .float_unification_table()
1640 .map(|v| v.to_type(self.tcx))
1647 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1648 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1649 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1651 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1652 /// inlined, despite being large, because it has only two call sites that
1653 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1654 /// inference variables), and it handles both `Ty` and `ty::Const` without
1655 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1657 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1658 let mut inner = self.inner.borrow_mut();
1660 TyOrConstInferVar::Ty(v) => {
1661 use self::type_variable::TypeVariableValue;
1663 // If `inlined_probe` returns a `Known` value, it never equals
1664 // `ty::Infer(ty::TyVar(v))`.
1665 match inner.type_variables().inlined_probe(v) {
1666 TypeVariableValue::Unknown { .. } => false,
1667 TypeVariableValue::Known { .. } => true,
1671 TyOrConstInferVar::TyInt(v) => {
1672 // If `inlined_probe_value` returns a value it's always a
1673 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1675 inner.int_unification_table().inlined_probe_value(v).is_some()
1678 TyOrConstInferVar::TyFloat(v) => {
1679 // If `probe_value` returns a value it's always a
1680 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1682 // Not `inlined_probe_value(v)` because this call site is colder.
1683 inner.float_unification_table().probe_value(v).is_some()
1686 TyOrConstInferVar::Const(v) => {
1687 // If `probe_value` returns a `Known` value, it never equals
1688 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1690 // Not `inlined_probe_value(v)` because this call site is colder.
1691 match inner.const_unification_table().probe_value(v).val {
1692 ConstVariableValue::Unknown { .. } => false,
1693 ConstVariableValue::Known { .. } => true,
1700 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1701 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1702 #[derive(Copy, Clone, Debug)]
1703 pub enum TyOrConstInferVar<'tcx> {
1704 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1706 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1708 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1711 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1712 Const(ConstVid<'tcx>),
1715 impl TyOrConstInferVar<'tcx> {
1716 /// Tries to extract an inference variable from a type or a constant, returns `None`
1717 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1718 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1719 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1720 match arg.unpack() {
1721 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1722 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1723 GenericArgKind::Lifetime(_) => None,
1727 /// Tries to extract an inference variable from a type, returns `None`
1728 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1729 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1731 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1732 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1733 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1738 /// Tries to extract an inference variable from a constant, returns `None`
1739 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1740 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1742 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1748 struct ShallowResolver<'a, 'tcx> {
1749 infcx: &'a InferCtxt<'a, 'tcx>,
1752 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1753 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1757 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1758 self.infcx.shallow_resolve_ty(ty)
1761 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1762 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1766 .const_unification_table()
1777 impl<'tcx> TypeTrace<'tcx> {
1778 pub fn span(&self) -> Span {
1783 cause: &ObligationCause<'tcx>,
1784 a_is_expected: bool,
1787 ) -> TypeTrace<'tcx> {
1788 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1792 cause: &ObligationCause<'tcx>,
1793 a_is_expected: bool,
1794 a: &'tcx ty::Const<'tcx>,
1795 b: &'tcx ty::Const<'tcx>,
1796 ) -> TypeTrace<'tcx> {
1797 TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
1800 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1802 cause: ObligationCause::dummy(),
1803 values: Types(ExpectedFound { expected: tcx.types.err, found: tcx.types.err }),
1808 impl<'tcx> SubregionOrigin<'tcx> {
1809 pub fn span(&self) -> Span {
1811 Subtype(ref a) => a.span(),
1812 InfStackClosure(a) => a,
1813 InvokeClosure(a) => a,
1814 DerefPointer(a) => a,
1815 ClosureCapture(a, _) => a,
1817 RelateObjectBound(a) => a,
1818 RelateParamBound(a, _) => a,
1819 RelateRegionParamBound(a) => a,
1820 RelateDefaultParamBound(a, _) => a,
1822 ReborrowUpvar(a, _) => a,
1823 DataBorrowed(_, a) => a,
1824 ReferenceOutlivesReferent(_, a) => a,
1825 ParameterInScope(_, a) => a,
1826 ExprTypeIsNotInScope(_, a) => a,
1827 BindingTypeIsNotValidAtDecl(a) => a,
1834 SafeDestructor(a) => a,
1835 CompareImplMethodObligation { span, .. } => span,
1839 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1841 F: FnOnce() -> Self,
1844 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1845 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1848 traits::ObligationCauseCode::CompareImplMethodObligation {
1852 } => SubregionOrigin::CompareImplMethodObligation {
1864 impl RegionVariableOrigin {
1865 pub fn span(&self) -> Span {
1867 MiscVariable(a) => a,
1868 PatternRegion(a) => a,
1869 AddrOfRegion(a) => a,
1872 EarlyBoundRegion(a, ..) => a,
1873 LateBoundRegion(a, ..) => a,
1874 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1875 UpvarRegion(_, a) => a,
1876 NLL(..) => bug!("NLL variable used with `span`"),
1881 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1882 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1885 "RegionObligation(sub_region={:?}, sup_type={:?})",
1886 self.sub_region, self.sup_type