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 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_data_structures::sync::Lrc;
14 use rustc_data_structures::unify as ut;
15 use rustc_errors::DiagnosticBuilder;
17 use rustc_hir::def_id::{DefId, LocalDefId};
18 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
19 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
20 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
21 use rustc_middle::middle::region;
22 use rustc_middle::mir;
23 use rustc_middle::mir::interpret::ConstEvalResult;
24 use rustc_middle::traits::select;
25 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
26 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
27 use rustc_middle::ty::relate::RelateResult;
28 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
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_session::config::BorrowckMode;
33 use rustc_span::symbol::Symbol;
36 use std::cell::{Cell, Ref, RefCell};
37 use std::collections::BTreeMap;
40 use self::combine::CombineFields;
41 use self::free_regions::RegionRelations;
42 use self::lexical_region_resolve::LexicalRegionResolutions;
43 use self::outlives::env::OutlivesEnvironment;
44 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
45 use self::region_constraints::{RegionConstraintCollector, RegionSnapshot};
46 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
52 pub mod error_reporting;
59 mod lexical_region_resolve;
63 pub mod region_constraints;
66 pub mod type_variable;
68 use crate::infer::canonical::OriginalQueryValues;
69 pub use rustc_middle::infer::unify_key;
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 /// How we should handle region solving.
85 /// This is used so that the region values inferred by HIR region solving are
86 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
87 /// typeck will also do.
88 #[derive(Copy, Clone, Debug)]
89 pub enum RegionckMode {
90 /// The default mode: report region errors, don't erase regions.
92 /// Erase the results of region after solving.
94 /// A flag that is used to suppress region errors, when we are doing
95 /// region checks that the NLL borrow checker will also do -- it might
97 suppress_errors: bool,
101 impl Default for RegionckMode {
102 fn default() -> Self {
108 pub fn suppressed(self) -> bool {
110 Self::Solve => false,
111 Self::Erase { suppress_errors } => suppress_errors,
115 /// Indicates that the MIR borrowck will repeat these region
116 /// checks, so we should ignore errors if NLL is (unconditionally)
118 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
119 // FIXME(Centril): Once we actually remove `::Migrate` also make
120 // this always `true` and then proceed to eliminate the dead code.
121 match tcx.borrowck_mode() {
122 // If we're on Migrate mode, report AST region errors
123 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
125 // If we're on MIR, don't report AST region errors as they should be reported by NLL
126 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
131 /// This type contains all the things within `InferCtxt` that sit within a
132 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
133 /// operations are hot enough that we want only one call to `borrow_mut` per
134 /// call to `start_snapshot` and `rollback_to`.
135 pub struct InferCtxtInner<'tcx> {
136 /// Cache for projections. This cache is snapshotted along with the infcx.
138 /// Public so that `traits::project` can use it.
139 pub projection_cache: traits::ProjectionCache<'tcx>,
141 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
142 /// that might instantiate a general type variable have an order,
143 /// represented by its upper and lower bounds.
144 type_variables: type_variable::TypeVariableTable<'tcx>,
146 /// Map from const parameter variable to the kind of const it represents.
147 const_unification_table: ut::UnificationTable<ut::InPlace<ty::ConstVid<'tcx>>>,
149 /// Map from integral variable to the kind of integer it represents.
150 int_unification_table: ut::UnificationTable<ut::InPlace<ty::IntVid>>,
152 /// Map from floating variable to the kind of float it represents.
153 float_unification_table: ut::UnificationTable<ut::InPlace<ty::FloatVid>>,
155 /// Tracks the set of region variables and the constraints between them.
156 /// This is initially `Some(_)` but when
157 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
158 /// -- further attempts to perform unification, etc., may fail if new
159 /// region constraints would've been added.
160 region_constraints: Option<RegionConstraintCollector<'tcx>>,
162 /// A set of constraints that regionck must validate. Each
163 /// constraint has the form `T:'a`, meaning "some type `T` must
164 /// outlive the lifetime 'a". These constraints derive from
165 /// instantiated type parameters. So if you had a struct defined
168 /// struct Foo<T:'static> { ... }
170 /// then in some expression `let x = Foo { ... }` it will
171 /// instantiate the type parameter `T` with a fresh type `$0`. At
172 /// the same time, it will record a region obligation of
173 /// `$0:'static`. This will get checked later by regionck. (We
174 /// can't generally check these things right away because we have
175 /// to wait until types are resolved.)
177 /// These are stored in a map keyed to the id of the innermost
178 /// enclosing fn body / static initializer expression. This is
179 /// because the location where the obligation was incurred can be
180 /// relevant with respect to which sublifetime assumptions are in
181 /// place. The reason that we store under the fn-id, and not
182 /// something more fine-grained, is so that it is easier for
183 /// regionck to be sure that it has found *all* the region
184 /// obligations (otherwise, it's easy to fail to walk to a
185 /// particular node-id).
187 /// Before running `resolve_regions_and_report_errors`, the creator
188 /// of the inference context is expected to invoke
189 /// `process_region_obligations` (defined in `self::region_obligations`)
190 /// for each body-id in this map, which will process the
191 /// obligations within. This is expected to be done 'late enough'
192 /// that all type inference variables have been bound and so forth.
193 pub region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
196 impl<'tcx> InferCtxtInner<'tcx> {
197 fn new() -> InferCtxtInner<'tcx> {
199 projection_cache: Default::default(),
200 type_variables: type_variable::TypeVariableTable::new(),
201 const_unification_table: ut::UnificationTable::new(),
202 int_unification_table: ut::UnificationTable::new(),
203 float_unification_table: ut::UnificationTable::new(),
204 region_constraints: Some(RegionConstraintCollector::new()),
205 region_obligations: vec![],
209 pub fn unwrap_region_constraints(&mut self) -> &mut RegionConstraintCollector<'tcx> {
210 self.region_constraints.as_mut().expect("region constraints already solved")
214 pub struct InferCtxt<'a, 'tcx> {
215 pub tcx: TyCtxt<'tcx>,
217 /// During type-checking/inference of a body, `in_progress_tables`
218 /// contains a reference to the tables being built up, which are
219 /// used for reading closure kinds/signatures as they are inferred,
220 /// and for error reporting logic to read arbitrary node types.
221 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
223 pub inner: RefCell<InferCtxtInner<'tcx>>,
225 /// If set, this flag causes us to skip the 'leak check' during
226 /// higher-ranked subtyping operations. This flag is a temporary one used
227 /// to manage the removal of the leak-check: for the time being, we still run the
228 /// leak-check, but we issue warnings. This flag can only be set to true
229 /// when entering a snapshot.
230 skip_leak_check: Cell<bool>,
232 /// Once region inference is done, the values for each variable.
233 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
235 /// Caches the results of trait selection. This cache is used
236 /// for things that have to do with the parameters in scope.
237 pub selection_cache: select::SelectionCache<'tcx>,
239 /// Caches the results of trait evaluation.
240 pub evaluation_cache: select::EvaluationCache<'tcx>,
242 /// the set of predicates on which errors have been reported, to
243 /// avoid reporting the same error twice.
244 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
246 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
248 /// When an error occurs, we want to avoid reporting "derived"
249 /// errors that are due to this original failure. Normally, we
250 /// handle this with the `err_count_on_creation` count, which
251 /// basically just tracks how many errors were reported when we
252 /// started type-checking a fn and checks to see if any new errors
253 /// have been reported since then. Not great, but it works.
255 /// However, when errors originated in other passes -- notably
256 /// resolve -- this heuristic breaks down. Therefore, we have this
257 /// auxiliary flag that one can set whenever one creates a
258 /// type-error that is due to an error in a prior pass.
260 /// Don't read this flag directly, call `is_tainted_by_errors()`
261 /// and `set_tainted_by_errors()`.
262 tainted_by_errors_flag: Cell<bool>,
264 /// Track how many errors were reported when this infcx is created.
265 /// If the number of errors increases, that's also a sign (line
266 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
267 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
268 err_count_on_creation: usize,
270 /// This flag is true while there is an active snapshot.
271 in_snapshot: Cell<bool>,
273 /// What is the innermost universe we have created? Starts out as
274 /// `UniverseIndex::root()` but grows from there as we enter
275 /// universal quantifiers.
277 /// N.B., at present, we exclude the universal quantifiers on the
278 /// item we are type-checking, and just consider those names as
279 /// part of the root universe. So this would only get incremented
280 /// when we enter into a higher-ranked (`for<..>`) type or trait
282 universe: Cell<ty::UniverseIndex>,
285 /// A map returned by `replace_bound_vars_with_placeholders()`
286 /// indicating the placeholder region that each late-bound region was
288 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
290 /// See the `error_reporting` module for more details.
291 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
292 pub enum ValuePairs<'tcx> {
293 Types(ExpectedFound<Ty<'tcx>>),
294 Regions(ExpectedFound<ty::Region<'tcx>>),
295 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
296 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
297 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
300 /// The trace designates the path through inference that we took to
301 /// encounter an error or subtyping constraint.
303 /// See the `error_reporting` module for more details.
304 #[derive(Clone, Debug)]
305 pub struct TypeTrace<'tcx> {
306 cause: ObligationCause<'tcx>,
307 values: ValuePairs<'tcx>,
310 /// The origin of a `r1 <= r2` constraint.
312 /// See `error_reporting` module for more details
313 #[derive(Clone, Debug)]
314 pub enum SubregionOrigin<'tcx> {
315 /// Arose from a subtyping relation
316 Subtype(Box<TypeTrace<'tcx>>),
318 /// Stack-allocated closures cannot outlive innermost loop
319 /// or function so as to ensure we only require finite stack
320 InfStackClosure(Span),
322 /// Invocation of closure must be within its lifetime
325 /// Dereference of reference must be within its lifetime
328 /// Closure bound must not outlive captured variables
329 ClosureCapture(Span, hir::HirId),
331 /// Index into slice must be within its lifetime
334 /// When casting `&'a T` to an `&'b Trait` object,
335 /// relating `'a` to `'b`
336 RelateObjectBound(Span),
338 /// Some type parameter was instantiated with the given type,
339 /// and that type must outlive some region.
340 RelateParamBound(Span, Ty<'tcx>),
342 /// The given region parameter was instantiated with a region
343 /// that must outlive some other region.
344 RelateRegionParamBound(Span),
346 /// A bound placed on type parameters that states that must outlive
347 /// the moment of their instantiation.
348 RelateDefaultParamBound(Span, Ty<'tcx>),
350 /// Creating a pointer `b` to contents of another reference
353 /// Creating a pointer `b` to contents of an upvar
354 ReborrowUpvar(Span, ty::UpvarId),
356 /// Data with type `Ty<'tcx>` was borrowed
357 DataBorrowed(Ty<'tcx>, Span),
359 /// (&'a &'b T) where a >= b
360 ReferenceOutlivesReferent(Ty<'tcx>, Span),
362 /// Type or region parameters must be in scope.
363 ParameterInScope(ParameterOrigin, Span),
365 /// The type T of an expression E must outlive the lifetime for E.
366 ExprTypeIsNotInScope(Ty<'tcx>, Span),
368 /// A `ref b` whose region does not enclose the decl site
369 BindingTypeIsNotValidAtDecl(Span),
371 /// Regions appearing in a method receiver must outlive method call
374 /// Regions appearing in a function argument must outlive func call
377 /// Region in return type of invoked fn must enclose call
380 /// Operands must be in scope
383 /// Region resulting from a `&` expr must enclose the `&` expr
386 /// An auto-borrow that does not enclose the expr where it occurs
389 /// Region constraint arriving from destructor safety
390 SafeDestructor(Span),
392 /// Comparing the signature and requirements of an impl method against
393 /// the containing trait.
394 CompareImplMethodObligation {
396 item_name: ast::Name,
397 impl_item_def_id: DefId,
398 trait_item_def_id: DefId,
402 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
403 #[cfg(target_arch = "x86_64")]
404 static_assert_size!(SubregionOrigin<'_>, 32);
406 /// Places that type/region parameters can appear.
407 #[derive(Clone, Copy, Debug)]
408 pub enum ParameterOrigin {
410 MethodCall, // foo.bar() <-- parameters on impl providing bar()
411 OverloadedOperator, // a + b when overloaded
412 OverloadedDeref, // *a when overloaded
415 /// Times when we replace late-bound regions with variables:
416 #[derive(Clone, Copy, Debug)]
417 pub enum LateBoundRegionConversionTime {
418 /// when a fn is called
421 /// when two higher-ranked types are compared
424 /// when projecting an associated type
425 AssocTypeProjection(DefId),
428 /// Reasons to create a region inference variable
430 /// See `error_reporting` module for more details
431 #[derive(Copy, Clone, Debug)]
432 pub enum RegionVariableOrigin {
433 /// Region variables created for ill-categorized reasons,
434 /// mostly indicates places in need of refactoring
437 /// Regions created by a `&P` or `[...]` pattern
440 /// Regions created by `&` operator
443 /// Regions created as part of an autoref of a method receiver
446 /// Regions created as part of an automatic coercion
449 /// Region variables created as the values for early-bound regions
450 EarlyBoundRegion(Span, Symbol),
452 /// Region variables created for bound regions
453 /// in a function or method that is called
454 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
456 UpvarRegion(ty::UpvarId, Span),
458 BoundRegionInCoherence(ast::Name),
460 /// This origin is used for the inference variables that we create
461 /// during NLL region processing.
462 NLL(NLLRegionVariableOrigin),
465 #[derive(Copy, Clone, Debug)]
466 pub enum NLLRegionVariableOrigin {
467 /// During NLL region processing, we create variables for free
468 /// regions that we encounter in the function signature and
469 /// elsewhere. This origin indices we've got one of those.
472 /// "Universal" instantiation of a higher-ranked region (e.g.,
473 /// from a `for<'a> T` binder). Meant to represent "any region".
474 Placeholder(ty::PlaceholderRegion),
477 /// If this is true, then this variable was created to represent a lifetime
478 /// bound in a `for` binder. For example, it might have been created to
479 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
480 /// Such variables are created when we are trying to figure out if there
481 /// is any valid instantiation of `'a` that could fit into some scenario.
483 /// This is used to inform error reporting: in the case that we are trying to
484 /// determine whether there is any valid instantiation of a `'a` variable that meets
485 /// some constraint C, we want to blame the "source" of that `for` type,
486 /// rather than blaming the source of the constraint C.
491 impl NLLRegionVariableOrigin {
492 pub fn is_universal(self) -> bool {
494 NLLRegionVariableOrigin::FreeRegion => true,
495 NLLRegionVariableOrigin::Placeholder(..) => true,
496 NLLRegionVariableOrigin::Existential { .. } => false,
500 pub fn is_existential(self) -> bool {
505 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
506 #[derive(Copy, Clone, Debug)]
507 pub enum FixupError<'tcx> {
508 UnresolvedIntTy(IntVid),
509 UnresolvedFloatTy(FloatVid),
511 UnresolvedConst(ConstVid<'tcx>),
514 /// See the `region_obligations` field for more information.
516 pub struct RegionObligation<'tcx> {
517 pub sub_region: ty::Region<'tcx>,
518 pub sup_type: Ty<'tcx>,
519 pub origin: SubregionOrigin<'tcx>,
522 impl<'tcx> fmt::Display for FixupError<'tcx> {
523 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524 use self::FixupError::*;
527 UnresolvedIntTy(_) => write!(
529 "cannot determine the type of this integer; \
530 add a suffix to specify the type explicitly"
532 UnresolvedFloatTy(_) => write!(
534 "cannot determine the type of this number; \
535 add a suffix to specify the type explicitly"
537 UnresolvedTy(_) => write!(f, "unconstrained type"),
538 UnresolvedConst(_) => write!(f, "unconstrained const value"),
543 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
544 /// Necessary because we can't write the following bound:
545 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
546 pub struct InferCtxtBuilder<'tcx> {
547 global_tcx: TyCtxt<'tcx>,
548 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
551 pub trait TyCtxtInferExt<'tcx> {
552 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
555 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
556 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
557 InferCtxtBuilder { global_tcx: self, fresh_tables: None }
561 impl<'tcx> InferCtxtBuilder<'tcx> {
562 /// Used only by `rustc_typeck` during body type-checking/inference,
563 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
564 pub fn with_fresh_in_progress_tables(mut self, table_owner: LocalDefId) -> Self {
565 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
569 /// Given a canonical value `C` as a starting point, create an
570 /// inference context that contains each of the bound values
571 /// within instantiated as a fresh variable. The `f` closure is
572 /// invoked with the new infcx, along with the instantiated value
573 /// `V` and a substitution `S`. This substitution `S` maps from
574 /// the bound values in `C` to their instantiated values in `V`
575 /// (in other words, `S(C) = V`).
576 pub fn enter_with_canonical<T, R>(
579 canonical: &Canonical<'tcx, T>,
580 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
583 T: TypeFoldable<'tcx>,
587 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
588 f(infcx, value, subst)
592 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
593 let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
594 let in_progress_tables = fresh_tables.as_ref();
595 global_tcx.enter_local(|tcx| {
599 inner: RefCell::new(InferCtxtInner::new()),
600 lexical_region_resolutions: RefCell::new(None),
601 selection_cache: Default::default(),
602 evaluation_cache: Default::default(),
603 reported_trait_errors: Default::default(),
604 reported_closure_mismatch: Default::default(),
605 tainted_by_errors_flag: Cell::new(false),
606 err_count_on_creation: tcx.sess.err_count(),
607 in_snapshot: Cell::new(false),
608 skip_leak_check: Cell::new(false),
609 universe: Cell::new(ty::UniverseIndex::ROOT),
615 impl<'tcx, T> InferOk<'tcx, T> {
616 pub fn unit(self) -> InferOk<'tcx, ()> {
617 InferOk { value: (), obligations: self.obligations }
620 /// Extracts `value`, registering any obligations into `fulfill_cx`.
621 pub fn into_value_registering_obligations(
623 infcx: &InferCtxt<'_, 'tcx>,
624 fulfill_cx: &mut dyn TraitEngine<'tcx>,
626 let InferOk { value, obligations } = self;
627 for obligation in obligations {
628 fulfill_cx.register_predicate_obligation(infcx, obligation);
634 impl<'tcx> InferOk<'tcx, ()> {
635 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
640 #[must_use = "once you start a snapshot, you should always consume it"]
641 pub struct CombinedSnapshot<'a, 'tcx> {
642 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
643 type_snapshot: type_variable::Snapshot<'tcx>,
644 const_snapshot: ut::Snapshot<ut::InPlace<ty::ConstVid<'tcx>>>,
645 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
646 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
647 region_constraints_snapshot: RegionSnapshot,
648 region_obligations_snapshot: usize,
649 universe: ty::UniverseIndex,
650 was_in_snapshot: bool,
651 was_skip_leak_check: bool,
652 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
655 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
656 pub fn is_in_snapshot(&self) -> bool {
657 self.in_snapshot.get()
660 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
661 t.fold_with(&mut self.freshener())
664 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
666 ty::Infer(ty::TyVar(vid)) => self.inner.borrow().type_variables.var_diverges(vid),
671 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
672 freshen::TypeFreshener::new(self)
675 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
676 use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
677 use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
679 ty::Infer(ty::IntVar(vid)) => {
680 if self.inner.borrow_mut().int_unification_table.probe_value(vid).is_some() {
686 ty::Infer(ty::FloatVar(vid)) => {
687 if self.inner.borrow_mut().float_unification_table.probe_value(vid).is_some() {
697 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
698 let mut inner = self.inner.borrow_mut();
699 // FIXME(const_generics): should there be an equivalent function for const variables?
701 let mut vars: Vec<Ty<'_>> = inner
703 .unsolved_variables()
705 .map(|t| self.tcx.mk_ty_var(t))
708 (0..inner.int_unification_table.len())
709 .map(|i| ty::IntVid { index: i as u32 })
710 .filter(|&vid| inner.int_unification_table.probe_value(vid).is_none())
711 .map(|v| self.tcx.mk_int_var(v)),
714 (0..inner.float_unification_table.len())
715 .map(|i| ty::FloatVid { index: i as u32 })
716 .filter(|&vid| inner.float_unification_table.probe_value(vid).is_none())
717 .map(|v| self.tcx.mk_float_var(v)),
724 trace: TypeTrace<'tcx>,
725 param_env: ty::ParamEnv<'tcx>,
726 ) -> CombineFields<'a, 'tcx> {
732 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();
769 projection_cache_snapshot: inner.projection_cache.snapshot(),
770 type_snapshot: inner.type_variables.snapshot(),
771 const_snapshot: inner.const_unification_table.snapshot(),
772 int_snapshot: inner.int_unification_table.snapshot(),
773 float_snapshot: inner.float_unification_table.snapshot(),
774 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
775 region_obligations_snapshot: inner.region_obligations.len(),
776 universe: self.universe(),
777 was_in_snapshot: in_snapshot,
778 was_skip_leak_check: self.skip_leak_check.get(),
779 // Borrow tables "in progress" (i.e., during typeck)
780 // to ban writes from within a snapshot to them.
781 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
785 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
786 debug!("rollback_to(cause={})", cause);
787 let CombinedSnapshot {
788 projection_cache_snapshot,
793 region_constraints_snapshot,
794 region_obligations_snapshot,
801 self.in_snapshot.set(was_in_snapshot);
802 self.universe.set(universe);
803 self.skip_leak_check.set(was_skip_leak_check);
805 let mut inner = self.inner.borrow_mut();
806 inner.projection_cache.rollback_to(projection_cache_snapshot);
807 inner.type_variables.rollback_to(type_snapshot);
808 inner.const_unification_table.rollback_to(const_snapshot);
809 inner.int_unification_table.rollback_to(int_snapshot);
810 inner.float_unification_table.rollback_to(float_snapshot);
811 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
812 inner.region_obligations.truncate(region_obligations_snapshot);
815 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
816 debug!("commit_from()");
817 let CombinedSnapshot {
818 projection_cache_snapshot,
823 region_constraints_snapshot,
824 region_obligations_snapshot: _,
831 self.in_snapshot.set(was_in_snapshot);
832 self.skip_leak_check.set(was_skip_leak_check);
834 let mut inner = self.inner.borrow_mut();
835 inner.projection_cache.commit(projection_cache_snapshot);
836 inner.type_variables.commit(type_snapshot);
837 inner.const_unification_table.commit(const_snapshot);
838 inner.int_unification_table.commit(int_snapshot);
839 inner.float_unification_table.commit(float_snapshot);
840 inner.unwrap_region_constraints().commit(region_constraints_snapshot);
843 /// Executes `f` and commit the bindings.
844 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
846 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
848 debug!("commit_unconditionally()");
849 let snapshot = self.start_snapshot();
850 let r = f(&snapshot);
851 self.commit_from(snapshot);
855 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
856 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
858 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
860 debug!("commit_if_ok()");
861 let snapshot = self.start_snapshot();
862 let r = f(&snapshot);
863 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
866 self.commit_from(snapshot);
869 self.rollback_to("commit_if_ok -- error", snapshot);
875 /// Execute `f` then unroll any bindings it creates.
876 pub fn probe<R, F>(&self, f: F) -> R
878 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
881 let snapshot = self.start_snapshot();
882 let r = f(&snapshot);
883 self.rollback_to("probe", snapshot);
887 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
888 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
890 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
893 let snapshot = self.start_snapshot();
894 let skip_leak_check = should_skip || self.skip_leak_check.get();
895 self.skip_leak_check.set(skip_leak_check);
896 let r = f(&snapshot);
897 self.rollback_to("probe", snapshot);
901 /// Scan the constraints produced since `snapshot` began and returns:
903 /// - `None` -- if none of them involve "region outlives" constraints
904 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
905 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
906 pub fn region_constraints_added_in_snapshot(
908 snapshot: &CombinedSnapshot<'a, 'tcx>,
912 .unwrap_region_constraints()
913 .region_constraints_added_in_snapshot(&snapshot.region_constraints_snapshot)
916 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
917 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
920 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
922 T: at::ToTrace<'tcx>,
924 let origin = &ObligationCause::dummy();
926 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
927 // Ignore obligations, since we are unrolling
928 // everything anyway.
933 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
935 T: at::ToTrace<'tcx>,
937 let origin = &ObligationCause::dummy();
939 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
940 // Ignore obligations, since we are unrolling
941 // everything anyway.
948 origin: SubregionOrigin<'tcx>,
952 debug!("sub_regions({:?} <: {:?})", a, b);
953 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
956 /// Require that the region `r` be equal to one of the regions in
957 /// the set `regions`.
958 pub fn member_constraint(
960 opaque_type_def_id: DefId,
961 definition_span: Span,
963 region: ty::Region<'tcx>,
964 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
966 debug!("member_constraint({:?} <: {:?})", region, in_regions);
967 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
976 pub fn subtype_predicate(
978 cause: &ObligationCause<'tcx>,
979 param_env: ty::ParamEnv<'tcx>,
980 predicate: &ty::PolySubtypePredicate<'tcx>,
981 ) -> Option<InferResult<'tcx, ()>> {
982 // Subtle: it's ok to skip the binder here and resolve because
983 // `shallow_resolve` just ignores anything that is not a type
984 // variable, and because type variable's can't (at present, at
985 // least) capture any of the things bound by this binder.
987 // NOTE(nmatsakis): really, there is no *particular* reason to do this
988 // `shallow_resolve` here except as a micro-optimization.
989 // Naturally I could not resist.
990 let two_unbound_type_vars = {
991 let a = self.shallow_resolve(predicate.skip_binder().a);
992 let b = self.shallow_resolve(predicate.skip_binder().b);
993 a.is_ty_var() && b.is_ty_var()
996 if two_unbound_type_vars {
997 // Two unbound type variables? Can't make progress.
1001 Some(self.commit_if_ok(|snapshot| {
1002 let (ty::SubtypePredicate { a_is_expected, a, b }, placeholder_map) =
1003 self.replace_bound_vars_with_placeholders(predicate);
1005 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1007 self.leak_check(false, &placeholder_map, snapshot)?;
1013 pub fn region_outlives_predicate(
1015 cause: &traits::ObligationCause<'tcx>,
1016 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
1017 ) -> UnitResult<'tcx> {
1018 self.commit_if_ok(|snapshot| {
1019 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
1020 self.replace_bound_vars_with_placeholders(predicate);
1021 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1022 RelateRegionParamBound(cause.span)
1024 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1025 self.leak_check(false, &placeholder_map, snapshot)?;
1030 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1031 self.inner.borrow_mut().type_variables.new_var(self.universe(), diverging, origin)
1034 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1035 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1038 pub fn next_ty_var_in_universe(
1040 origin: TypeVariableOrigin,
1041 universe: ty::UniverseIndex,
1043 let vid = self.inner.borrow_mut().type_variables.new_var(universe, false, origin);
1044 self.tcx.mk_ty_var(vid)
1047 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1048 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1051 pub fn next_const_var(
1054 origin: ConstVariableOrigin,
1055 ) -> &'tcx ty::Const<'tcx> {
1056 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1059 pub fn next_const_var_in_universe(
1062 origin: ConstVariableOrigin,
1063 universe: ty::UniverseIndex,
1064 ) -> &'tcx ty::Const<'tcx> {
1068 .const_unification_table
1069 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1070 self.tcx.mk_const_var(vid, ty)
1073 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1074 self.inner.borrow_mut().const_unification_table.new_key(ConstVarValue {
1076 val: ConstVariableValue::Unknown { universe: self.universe() },
1080 fn next_int_var_id(&self) -> IntVid {
1081 self.inner.borrow_mut().int_unification_table.new_key(None)
1084 pub fn next_int_var(&self) -> Ty<'tcx> {
1085 self.tcx.mk_int_var(self.next_int_var_id())
1088 fn next_float_var_id(&self) -> FloatVid {
1089 self.inner.borrow_mut().float_unification_table.new_key(None)
1092 pub fn next_float_var(&self) -> Ty<'tcx> {
1093 self.tcx.mk_float_var(self.next_float_var_id())
1096 /// Creates a fresh region variable with the next available index.
1097 /// The variable will be created in the maximum universe created
1098 /// thus far, allowing it to name any region created thus far.
1099 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1100 self.next_region_var_in_universe(origin, self.universe())
1103 /// Creates a fresh region variable with the next available index
1104 /// in the given universe; typically, you can use
1105 /// `next_region_var` and just use the maximal universe.
1106 pub fn next_region_var_in_universe(
1108 origin: RegionVariableOrigin,
1109 universe: ty::UniverseIndex,
1110 ) -> ty::Region<'tcx> {
1112 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1113 self.tcx.mk_region(ty::ReVar(region_var))
1116 /// Return the universe that the region `r` was created in. For
1117 /// most regions (e.g., `'static`, named regions from the user,
1118 /// etc) this is the root universe U0. For inference variables or
1119 /// placeholders, however, it will return the universe which which
1120 /// they are associated.
1121 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1122 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1125 /// Number of region variables created so far.
1126 pub fn num_region_vars(&self) -> usize {
1127 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1130 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1131 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1132 self.next_region_var(RegionVariableOrigin::NLL(origin))
1135 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1136 pub fn next_nll_region_var_in_universe(
1138 origin: NLLRegionVariableOrigin,
1139 universe: ty::UniverseIndex,
1140 ) -> ty::Region<'tcx> {
1141 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1144 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1146 GenericParamDefKind::Lifetime => {
1147 // Create a region inference variable for the given
1148 // region parameter definition.
1149 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1151 GenericParamDefKind::Type { .. } => {
1152 // Create a type inference variable for the given
1153 // type parameter definition. The substitutions are
1154 // for actual parameters that may be referred to by
1155 // the default of this type parameter, if it exists.
1156 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1157 // used in a path such as `Foo::<T, U>::new()` will
1158 // use an inference variable for `C` with `[T, U]`
1159 // as the substitutions for the default, `(T, U)`.
1160 let ty_var_id = self.inner.borrow_mut().type_variables.new_var(
1163 TypeVariableOrigin {
1164 kind: TypeVariableOriginKind::TypeParameterDefinition(
1172 self.tcx.mk_ty_var(ty_var_id).into()
1174 GenericParamDefKind::Const { .. } => {
1175 let origin = ConstVariableOrigin {
1176 kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1180 self.inner.borrow_mut().const_unification_table.new_key(ConstVarValue {
1182 val: ConstVariableValue::Unknown { universe: self.universe() },
1184 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1189 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1190 /// type/region parameter to a fresh inference variable.
1191 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1192 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1195 /// Returns `true` if errors have been reported since this infcx was
1196 /// created. This is sometimes used as a heuristic to skip
1197 /// reporting errors that often occur as a result of earlier
1198 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1199 /// inference variables, regionck errors).
1200 pub fn is_tainted_by_errors(&self) -> bool {
1202 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1203 tainted_by_errors_flag={})",
1204 self.tcx.sess.err_count(),
1205 self.err_count_on_creation,
1206 self.tainted_by_errors_flag.get()
1209 if self.tcx.sess.err_count() > self.err_count_on_creation {
1210 return true; // errors reported since this infcx was made
1212 self.tainted_by_errors_flag.get()
1215 /// Set the "tainted by errors" flag to true. We call this when we
1216 /// observe an error from a prior pass.
1217 pub fn set_tainted_by_errors(&self) {
1218 debug!("set_tainted_by_errors()");
1219 self.tainted_by_errors_flag.set(true)
1222 /// Process the region constraints and report any errors that
1223 /// result. After this, no more unification operations should be
1224 /// done -- or the compiler will panic -- but it is legal to use
1225 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1226 pub fn resolve_regions_and_report_errors(
1228 region_context: DefId,
1229 region_map: ®ion::ScopeTree,
1230 outlives_env: &OutlivesEnvironment<'tcx>,
1234 self.is_tainted_by_errors() || self.inner.borrow().region_obligations.is_empty(),
1235 "region_obligations not empty: {:#?}",
1236 self.inner.borrow().region_obligations
1238 let (var_infos, data) = self
1243 .expect("regions already resolved")
1244 .into_infos_and_data();
1246 let region_rels = &RegionRelations::new(
1250 outlives_env.free_region_map(),
1253 let (lexical_region_resolutions, errors) =
1254 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1256 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1257 assert!(old_value.is_none());
1259 if !self.is_tainted_by_errors() {
1260 // As a heuristic, just skip reporting region errors
1261 // altogether if other errors have been reported while
1262 // this infcx was in use. This is totally hokey but
1263 // otherwise we have a hard time separating legit region
1264 // errors from silly ones.
1265 self.report_region_errors(region_map, &errors);
1269 /// Obtains (and clears) the current set of region
1270 /// constraints. The inference context is still usable: further
1271 /// unifications will simply add new constraints.
1273 /// This method is not meant to be used with normal lexical region
1274 /// resolution. Rather, it is used in the NLL mode as a kind of
1275 /// interim hack: basically we run normal type-check and generate
1276 /// region constraints as normal, but then we take them and
1277 /// translate them into the form that the NLL solver
1278 /// understands. See the NLL module for mode details.
1279 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1281 self.inner.borrow().region_obligations.is_empty(),
1282 "region_obligations not empty: {:#?}",
1283 self.inner.borrow().region_obligations
1286 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1289 /// Gives temporary access to the region constraint data.
1290 #[allow(non_camel_case_types)] // bug with impl trait
1291 pub fn with_region_constraints<R>(
1293 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1295 let mut inner = self.inner.borrow_mut();
1296 op(inner.unwrap_region_constraints().data())
1299 /// Takes ownership of the list of variable regions. This implies
1300 /// that all the region constraints have already been taken, and
1301 /// hence that `resolve_regions_and_report_errors` can never be
1302 /// called. This is used only during NLL processing to "hand off" ownership
1303 /// of the set of region variables into the NLL region context.
1304 pub fn take_region_var_origins(&self) -> VarInfos {
1305 let (var_infos, data) = self
1310 .expect("regions already resolved")
1311 .into_infos_and_data();
1312 assert!(data.is_empty());
1316 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1317 self.resolve_vars_if_possible(&t).to_string()
1320 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1321 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1322 format!("({})", tstrs.join(", "))
1325 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1326 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1329 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1330 /// universe index of `TyVar(vid)`.
1331 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1332 use self::type_variable::TypeVariableValue;
1334 match self.inner.borrow_mut().type_variables.probe(vid) {
1335 TypeVariableValue::Known { value } => Ok(value),
1336 TypeVariableValue::Unknown { universe } => Err(universe),
1340 /// Resolve any type variables found in `value` -- but only one
1341 /// level. So, if the variable `?X` is bound to some type
1342 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1343 /// itself be bound to a type).
1345 /// Useful when you only need to inspect the outermost level of
1346 /// the type and don't care about nested types (or perhaps you
1347 /// will be resolving them as well, e.g. in a loop).
1348 pub fn shallow_resolve<T>(&self, value: T) -> T
1350 T: TypeFoldable<'tcx>,
1352 value.fold_with(&mut ShallowResolver { infcx: self })
1355 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1356 self.inner.borrow_mut().type_variables.root_var(var)
1359 /// Where possible, replaces type/const variables in
1360 /// `value` with their final value. Note that region variables
1361 /// are unaffected. If a type/const variable has not been unified, it
1362 /// is left as is. This is an idempotent operation that does
1363 /// not affect inference state in any way and so you can do it
1365 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1367 T: TypeFoldable<'tcx>,
1369 if !value.needs_infer() {
1370 return value.clone(); // Avoid duplicated subst-folding.
1372 let mut r = resolve::OpportunisticVarResolver::new(self);
1373 value.fold_with(&mut r)
1376 /// Returns the first unresolved variable contained in `T`. In the
1377 /// process of visiting `T`, this will resolve (where possible)
1378 /// type variables in `T`, but it never constructs the final,
1379 /// resolved type, so it's more efficient than
1380 /// `resolve_vars_if_possible()`.
1381 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1383 T: TypeFoldable<'tcx>,
1385 let mut r = resolve::UnresolvedTypeFinder::new(self);
1386 value.visit_with(&mut r);
1390 pub fn probe_const_var(
1392 vid: ty::ConstVid<'tcx>,
1393 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1394 match self.inner.borrow_mut().const_unification_table.probe_value(vid).val {
1395 ConstVariableValue::Known { value } => Ok(value),
1396 ConstVariableValue::Unknown { universe } => Err(universe),
1400 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1402 * Attempts to resolve all type/region/const variables in
1403 * `value`. Region inference must have been run already (e.g.,
1404 * by calling `resolve_regions_and_report_errors`). If some
1405 * variable was never unified, an `Err` results.
1407 * This method is idempotent, but it not typically not invoked
1408 * except during the writeback phase.
1411 resolve::fully_resolve(self, value)
1414 // [Note-Type-error-reporting]
1415 // An invariant is that anytime the expected or actual type is Error (the special
1416 // error type, meaning that an error occurred when typechecking this expression),
1417 // this is a derived error. The error cascaded from another error (that was already
1418 // reported), so it's not useful to display it to the user.
1419 // The following methods implement this logic.
1420 // They check if either the actual or expected type is Error, and don't print the error
1421 // in this case. The typechecker should only ever report type errors involving mismatched
1422 // types using one of these methods, and should not call span_err directly for such
1425 pub fn type_error_struct_with_diag<M>(
1429 actual_ty: Ty<'tcx>,
1430 ) -> DiagnosticBuilder<'tcx>
1432 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1434 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1435 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1437 // Don't report an error if actual type is `Error`.
1438 if actual_ty.references_error() {
1439 return self.tcx.sess.diagnostic().struct_dummy();
1442 mk_diag(self.ty_to_string(actual_ty))
1445 pub fn report_mismatched_types(
1447 cause: &ObligationCause<'tcx>,
1450 err: TypeError<'tcx>,
1451 ) -> DiagnosticBuilder<'tcx> {
1452 let trace = TypeTrace::types(cause, true, expected, actual);
1453 self.report_and_explain_type_error(trace, &err)
1456 pub fn replace_bound_vars_with_fresh_vars<T>(
1459 lbrct: LateBoundRegionConversionTime,
1460 value: &ty::Binder<T>,
1461 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1463 T: TypeFoldable<'tcx>,
1465 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1467 self.next_ty_var(TypeVariableOrigin {
1468 kind: TypeVariableOriginKind::MiscVariable,
1472 let fld_c = |_, ty| {
1473 self.next_const_var(
1475 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1478 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1481 /// See the [`region_constraints::verify_generic_bound`] method.
1482 pub fn verify_generic_bound(
1484 origin: SubregionOrigin<'tcx>,
1485 kind: GenericKind<'tcx>,
1486 a: ty::Region<'tcx>,
1487 bound: VerifyBound<'tcx>,
1489 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1493 .unwrap_region_constraints()
1494 .verify_generic_bound(origin, kind, a, bound);
1497 /// Obtains the latest type of the given closure; this may be a
1498 /// closure in the current function, in which case its
1499 /// `ClosureKind` may not yet be known.
1500 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1501 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1502 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1503 closure_kind_ty.to_opt_closure_kind()
1506 /// Clears the selection, evaluation, and projection caches. This is useful when
1507 /// repeatedly attempting to select an `Obligation` while changing only
1508 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1509 pub fn clear_caches(&self) {
1510 self.selection_cache.clear();
1511 self.evaluation_cache.clear();
1512 self.inner.borrow_mut().projection_cache.clear();
1515 fn universe(&self) -> ty::UniverseIndex {
1519 /// Creates and return a fresh universe that extends all previous
1520 /// universes. Updates `self.universe` to that new universe.
1521 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1522 let u = self.universe.get().next_universe();
1523 self.universe.set(u);
1527 /// Resolves and evaluates a constant.
1529 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1530 /// substitutions and environment are used to resolve the constant. Alternatively if the
1531 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1532 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1533 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1534 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1537 /// This handles inferences variables within both `param_env` and `substs` by
1538 /// performing the operation on their respective canonical forms.
1539 pub fn const_eval_resolve(
1541 param_env: ty::ParamEnv<'tcx>,
1543 substs: SubstsRef<'tcx>,
1544 promoted: Option<mir::Promoted>,
1546 ) -> ConstEvalResult<'tcx> {
1547 let mut original_values = OriginalQueryValues::default();
1548 let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1550 let (param_env, substs) = canonical.value;
1551 // The return value is the evaluated value which doesn't contain any reference to inference
1552 // variables, thus we don't need to substitute back the original values.
1553 self.tcx.const_eval_resolve(param_env, def_id, substs, promoted, span)
1556 /// If `typ` is a type variable of some kind, resolve it one level
1557 /// (but do not resolve types found in the result). If `typ` is
1558 /// not a type variable, just return it unmodified.
1559 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1560 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1562 ty::Infer(ty::TyVar(v)) => {
1563 // Not entirely obvious: if `typ` is a type variable,
1564 // it can be resolved to an int/float variable, which
1565 // can then be recursively resolved, hence the
1566 // recursion. Note though that we prevent type
1567 // variables from unifying to other type variables
1568 // directly (though they may be embedded
1569 // structurally), and we prevent cycles in any case,
1570 // so this recursion should always be of very limited
1573 // Note: if these two lines are combined into one we get
1574 // dynamic borrow errors on `self.inner`.
1575 let known = self.inner.borrow_mut().type_variables.probe(v).known();
1576 known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
1579 ty::Infer(ty::IntVar(v)) => self
1582 .int_unification_table
1584 .map(|v| v.to_type(self.tcx))
1587 ty::Infer(ty::FloatVar(v)) => self
1590 .float_unification_table
1592 .map(|v| v.to_type(self.tcx))
1599 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1600 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1601 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1603 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1604 /// inlined, despite being large, because it has only two call sites that
1605 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1606 /// inference variables), and it handles both `Ty` and `ty::Const` without
1607 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1609 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1611 TyOrConstInferVar::Ty(v) => {
1612 use self::type_variable::TypeVariableValue;
1614 // If `inlined_probe` returns a `Known` value, it never equals
1615 // `ty::Infer(ty::TyVar(v))`.
1616 match self.inner.borrow_mut().type_variables.inlined_probe(v) {
1617 TypeVariableValue::Unknown { .. } => false,
1618 TypeVariableValue::Known { .. } => true,
1622 TyOrConstInferVar::TyInt(v) => {
1623 // If `inlined_probe_value` returns a value it's always a
1624 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1626 self.inner.borrow_mut().int_unification_table.inlined_probe_value(v).is_some()
1629 TyOrConstInferVar::TyFloat(v) => {
1630 // If `probe_value` returns a value it's always a
1631 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1633 // Not `inlined_probe_value(v)` because this call site is colder.
1634 self.inner.borrow_mut().float_unification_table.probe_value(v).is_some()
1637 TyOrConstInferVar::Const(v) => {
1638 // If `probe_value` returns a `Known` value, it never equals
1639 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1641 // Not `inlined_probe_value(v)` because this call site is colder.
1642 match self.inner.borrow_mut().const_unification_table.probe_value(v).val {
1643 ConstVariableValue::Unknown { .. } => false,
1644 ConstVariableValue::Known { .. } => true,
1651 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1652 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1653 #[derive(Copy, Clone, Debug)]
1654 pub enum TyOrConstInferVar<'tcx> {
1655 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1657 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1659 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1662 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1663 Const(ConstVid<'tcx>),
1666 impl TyOrConstInferVar<'tcx> {
1667 /// Tries to extract an inference variable from a type or a constant, returns `None`
1668 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1669 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1670 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1671 match arg.unpack() {
1672 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1673 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1674 GenericArgKind::Lifetime(_) => None,
1678 /// Tries to extract an inference variable from a type, returns `None`
1679 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1680 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1682 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1683 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1684 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1689 /// Tries to extract an inference variable from a constant, returns `None`
1690 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1691 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1693 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1699 struct ShallowResolver<'a, 'tcx> {
1700 infcx: &'a InferCtxt<'a, 'tcx>,
1703 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1704 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1708 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1709 self.infcx.shallow_resolve_ty(ty)
1712 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1713 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1717 .const_unification_table
1728 impl<'tcx> TypeTrace<'tcx> {
1729 pub fn span(&self) -> Span {
1734 cause: &ObligationCause<'tcx>,
1735 a_is_expected: bool,
1738 ) -> TypeTrace<'tcx> {
1739 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1742 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1744 cause: ObligationCause::dummy(),
1745 values: Types(ExpectedFound { expected: tcx.types.err, found: tcx.types.err }),
1750 impl<'tcx> SubregionOrigin<'tcx> {
1751 pub fn span(&self) -> Span {
1753 Subtype(ref a) => a.span(),
1754 InfStackClosure(a) => a,
1755 InvokeClosure(a) => a,
1756 DerefPointer(a) => a,
1757 ClosureCapture(a, _) => a,
1759 RelateObjectBound(a) => a,
1760 RelateParamBound(a, _) => a,
1761 RelateRegionParamBound(a) => a,
1762 RelateDefaultParamBound(a, _) => a,
1764 ReborrowUpvar(a, _) => a,
1765 DataBorrowed(_, a) => a,
1766 ReferenceOutlivesReferent(_, a) => a,
1767 ParameterInScope(_, a) => a,
1768 ExprTypeIsNotInScope(_, a) => a,
1769 BindingTypeIsNotValidAtDecl(a) => a,
1776 SafeDestructor(a) => a,
1777 CompareImplMethodObligation { span, .. } => span,
1781 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1783 F: FnOnce() -> Self,
1786 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1787 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1790 traits::ObligationCauseCode::CompareImplMethodObligation {
1794 } => SubregionOrigin::CompareImplMethodObligation {
1806 impl RegionVariableOrigin {
1807 pub fn span(&self) -> Span {
1809 MiscVariable(a) => a,
1810 PatternRegion(a) => a,
1811 AddrOfRegion(a) => a,
1814 EarlyBoundRegion(a, ..) => a,
1815 LateBoundRegion(a, ..) => a,
1816 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1817 UpvarRegion(_, a) => a,
1818 NLL(..) => bug!("NLL variable used with `span`"),
1823 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1824 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1827 "RegionObligation(sub_region={:?}, sup_type={:?})",
1828 self.sub_region, self.sup_type