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::*;
8 pub use rustc::ty::IntVarValue;
10 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
12 use rustc::infer::canonical::{Canonical, CanonicalVarValues};
13 use rustc::infer::unify_key::{ConstVarValue, ConstVariableValue};
14 use rustc::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
15 use rustc::middle::free_region::RegionRelations;
16 use rustc::middle::lang_items;
17 use rustc::middle::region;
19 use rustc::mir::interpret::ConstEvalResult;
20 use rustc::session::config::BorrowckMode;
21 use rustc::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
22 use rustc::ty::fold::{TypeFoldable, TypeFolder};
23 use rustc::ty::relate::RelateResult;
24 use rustc::ty::subst::{GenericArg, InternalSubsts, SubstsRef};
25 use rustc::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
26 use rustc::ty::{ConstVid, FloatVid, IntVid, TyVid};
29 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
30 use rustc_data_structures::sync::Lrc;
31 use rustc_data_structures::unify as ut;
32 use rustc_errors::DiagnosticBuilder;
34 use rustc_hir::def_id::DefId;
35 use rustc_span::symbol::Symbol;
37 use std::cell::{Cell, Ref, RefCell};
38 use std::collections::BTreeMap;
41 use self::combine::CombineFields;
42 use self::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;
58 mod lexical_region_resolve;
63 pub mod region_constraints;
66 pub mod type_variable;
68 use crate::infer::canonical::OriginalQueryValues;
69 pub use rustc::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 /// A flag that is used to suppress region errors. This is normally
84 /// false, but sometimes -- when we are doing region checks that the
85 /// NLL borrow checker will also do -- it might be set to true.
86 #[derive(Copy, Clone, Default, Debug)]
87 pub struct SuppressRegionErrors {
91 impl SuppressRegionErrors {
92 pub fn suppressed(self) -> bool {
96 /// Indicates that the MIR borrowck will repeat these region
97 /// checks, so we should ignore errors if NLL is (unconditionally)
99 pub fn when_nll_is_enabled(tcx: TyCtxt<'_>) -> Self {
100 // FIXME(Centril): Once we actually remove `::Migrate` also make
101 // this always `true` and then proceed to eliminate the dead code.
102 match tcx.borrowck_mode() {
103 // If we're on Migrate mode, report AST region errors
104 BorrowckMode::Migrate => SuppressRegionErrors { suppressed: false },
106 // If we're on MIR, don't report AST region errors as they should be reported by NLL
107 BorrowckMode::Mir => SuppressRegionErrors { suppressed: true },
112 /// This type contains all the things within `InferCtxt` that sit within a
113 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
114 /// operations are hot enough that we want only one call to `borrow_mut` per
115 /// call to `start_snapshot` and `rollback_to`.
116 pub struct InferCtxtInner<'tcx> {
117 /// Cache for projections. This cache is snapshotted along with the infcx.
119 /// Public so that `traits::project` can use it.
120 pub projection_cache: traits::ProjectionCache<'tcx>,
122 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
123 /// that might instantiate a general type variable have an order,
124 /// represented by its upper and lower bounds.
125 type_variables: type_variable::TypeVariableTable<'tcx>,
127 /// Map from const parameter variable to the kind of const it represents.
128 const_unification_table: ut::UnificationTable<ut::InPlace<ty::ConstVid<'tcx>>>,
130 /// Map from integral variable to the kind of integer it represents.
131 int_unification_table: ut::UnificationTable<ut::InPlace<ty::IntVid>>,
133 /// Map from floating variable to the kind of float it represents.
134 float_unification_table: ut::UnificationTable<ut::InPlace<ty::FloatVid>>,
136 /// Tracks the set of region variables and the constraints between them.
137 /// This is initially `Some(_)` but when
138 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
139 /// -- further attempts to perform unification, etc., may fail if new
140 /// region constraints would've been added.
141 region_constraints: Option<RegionConstraintCollector<'tcx>>,
143 /// A set of constraints that regionck must validate. Each
144 /// constraint has the form `T:'a`, meaning "some type `T` must
145 /// outlive the lifetime 'a". These constraints derive from
146 /// instantiated type parameters. So if you had a struct defined
149 /// struct Foo<T:'static> { ... }
151 /// then in some expression `let x = Foo { ... }` it will
152 /// instantiate the type parameter `T` with a fresh type `$0`. At
153 /// the same time, it will record a region obligation of
154 /// `$0:'static`. This will get checked later by regionck. (We
155 /// can't generally check these things right away because we have
156 /// to wait until types are resolved.)
158 /// These are stored in a map keyed to the id of the innermost
159 /// enclosing fn body / static initializer expression. This is
160 /// because the location where the obligation was incurred can be
161 /// relevant with respect to which sublifetime assumptions are in
162 /// place. The reason that we store under the fn-id, and not
163 /// something more fine-grained, is so that it is easier for
164 /// regionck to be sure that it has found *all* the region
165 /// obligations (otherwise, it's easy to fail to walk to a
166 /// particular node-id).
168 /// Before running `resolve_regions_and_report_errors`, the creator
169 /// of the inference context is expected to invoke
170 /// `process_region_obligations` (defined in `self::region_obligations`)
171 /// for each body-id in this map, which will process the
172 /// obligations within. This is expected to be done 'late enough'
173 /// that all type inference variables have been bound and so forth.
174 pub region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
177 impl<'tcx> InferCtxtInner<'tcx> {
178 fn new() -> InferCtxtInner<'tcx> {
180 projection_cache: Default::default(),
181 type_variables: type_variable::TypeVariableTable::new(),
182 const_unification_table: ut::UnificationTable::new(),
183 int_unification_table: ut::UnificationTable::new(),
184 float_unification_table: ut::UnificationTable::new(),
185 region_constraints: Some(RegionConstraintCollector::new()),
186 region_obligations: vec![],
190 pub fn unwrap_region_constraints(&mut self) -> &mut RegionConstraintCollector<'tcx> {
191 self.region_constraints.as_mut().expect("region constraints already solved")
195 pub struct InferCtxt<'a, 'tcx> {
196 pub tcx: TyCtxt<'tcx>,
198 /// During type-checking/inference of a body, `in_progress_tables`
199 /// contains a reference to the tables being built up, which are
200 /// used for reading closure kinds/signatures as they are inferred,
201 /// and for error reporting logic to read arbitrary node types.
202 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
204 pub inner: RefCell<InferCtxtInner<'tcx>>,
206 /// If set, this flag causes us to skip the 'leak check' during
207 /// higher-ranked subtyping operations. This flag is a temporary one used
208 /// to manage the removal of the leak-check: for the time being, we still run the
209 /// leak-check, but we issue warnings. This flag can only be set to true
210 /// when entering a snapshot.
211 skip_leak_check: Cell<bool>,
213 /// Once region inference is done, the values for each variable.
214 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
216 /// Caches the results of trait selection. This cache is used
217 /// for things that have to do with the parameters in scope.
218 pub selection_cache: traits::SelectionCache<'tcx>,
220 /// Caches the results of trait evaluation.
221 pub evaluation_cache: traits::EvaluationCache<'tcx>,
223 /// the set of predicates on which errors have been reported, to
224 /// avoid reporting the same error twice.
225 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
227 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
229 /// When an error occurs, we want to avoid reporting "derived"
230 /// errors that are due to this original failure. Normally, we
231 /// handle this with the `err_count_on_creation` count, which
232 /// basically just tracks how many errors were reported when we
233 /// started type-checking a fn and checks to see if any new errors
234 /// have been reported since then. Not great, but it works.
236 /// However, when errors originated in other passes -- notably
237 /// resolve -- this heuristic breaks down. Therefore, we have this
238 /// auxiliary flag that one can set whenever one creates a
239 /// type-error that is due to an error in a prior pass.
241 /// Don't read this flag directly, call `is_tainted_by_errors()`
242 /// and `set_tainted_by_errors()`.
243 tainted_by_errors_flag: Cell<bool>,
245 /// Track how many errors were reported when this infcx is created.
246 /// If the number of errors increases, that's also a sign (line
247 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
248 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
249 err_count_on_creation: usize,
251 /// This flag is true while there is an active snapshot.
252 in_snapshot: Cell<bool>,
254 /// What is the innermost universe we have created? Starts out as
255 /// `UniverseIndex::root()` but grows from there as we enter
256 /// universal quantifiers.
258 /// N.B., at present, we exclude the universal quantifiers on the
259 /// item we are type-checking, and just consider those names as
260 /// part of the root universe. So this would only get incremented
261 /// when we enter into a higher-ranked (`for<..>`) type or trait
263 universe: Cell<ty::UniverseIndex>,
266 /// A map returned by `replace_bound_vars_with_placeholders()`
267 /// indicating the placeholder region that each late-bound region was
269 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
271 /// See the `error_reporting` module for more details.
272 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
273 pub enum ValuePairs<'tcx> {
274 Types(ExpectedFound<Ty<'tcx>>),
275 Regions(ExpectedFound<ty::Region<'tcx>>),
276 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
277 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
278 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
281 /// The trace designates the path through inference that we took to
282 /// encounter an error or subtyping constraint.
284 /// See the `error_reporting` module for more details.
285 #[derive(Clone, Debug)]
286 pub struct TypeTrace<'tcx> {
287 cause: ObligationCause<'tcx>,
288 values: ValuePairs<'tcx>,
291 /// The origin of a `r1 <= r2` constraint.
293 /// See `error_reporting` module for more details
294 #[derive(Clone, Debug)]
295 pub enum SubregionOrigin<'tcx> {
296 /// Arose from a subtyping relation
297 Subtype(Box<TypeTrace<'tcx>>),
299 /// Stack-allocated closures cannot outlive innermost loop
300 /// or function so as to ensure we only require finite stack
301 InfStackClosure(Span),
303 /// Invocation of closure must be within its lifetime
306 /// Dereference of reference must be within its lifetime
309 /// Closure bound must not outlive captured variables
310 ClosureCapture(Span, hir::HirId),
312 /// Index into slice must be within its lifetime
315 /// When casting `&'a T` to an `&'b Trait` object,
316 /// relating `'a` to `'b`
317 RelateObjectBound(Span),
319 /// Some type parameter was instantiated with the given type,
320 /// and that type must outlive some region.
321 RelateParamBound(Span, Ty<'tcx>),
323 /// The given region parameter was instantiated with a region
324 /// that must outlive some other region.
325 RelateRegionParamBound(Span),
327 /// A bound placed on type parameters that states that must outlive
328 /// the moment of their instantiation.
329 RelateDefaultParamBound(Span, Ty<'tcx>),
331 /// Creating a pointer `b` to contents of another reference
334 /// Creating a pointer `b` to contents of an upvar
335 ReborrowUpvar(Span, ty::UpvarId),
337 /// Data with type `Ty<'tcx>` was borrowed
338 DataBorrowed(Ty<'tcx>, Span),
340 /// (&'a &'b T) where a >= b
341 ReferenceOutlivesReferent(Ty<'tcx>, Span),
343 /// Type or region parameters must be in scope.
344 ParameterInScope(ParameterOrigin, Span),
346 /// The type T of an expression E must outlive the lifetime for E.
347 ExprTypeIsNotInScope(Ty<'tcx>, Span),
349 /// A `ref b` whose region does not enclose the decl site
350 BindingTypeIsNotValidAtDecl(Span),
352 /// Regions appearing in a method receiver must outlive method call
355 /// Regions appearing in a function argument must outlive func call
358 /// Region in return type of invoked fn must enclose call
361 /// Operands must be in scope
364 /// Region resulting from a `&` expr must enclose the `&` expr
367 /// An auto-borrow that does not enclose the expr where it occurs
370 /// Region constraint arriving from destructor safety
371 SafeDestructor(Span),
373 /// Comparing the signature and requirements of an impl method against
374 /// the containing trait.
375 CompareImplMethodObligation {
377 item_name: ast::Name,
378 impl_item_def_id: DefId,
379 trait_item_def_id: DefId,
383 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
384 #[cfg(target_arch = "x86_64")]
385 static_assert_size!(SubregionOrigin<'_>, 32);
387 /// Places that type/region parameters can appear.
388 #[derive(Clone, Copy, Debug)]
389 pub enum ParameterOrigin {
391 MethodCall, // foo.bar() <-- parameters on impl providing bar()
392 OverloadedOperator, // a + b when overloaded
393 OverloadedDeref, // *a when overloaded
396 /// Times when we replace late-bound regions with variables:
397 #[derive(Clone, Copy, Debug)]
398 pub enum LateBoundRegionConversionTime {
399 /// when a fn is called
402 /// when two higher-ranked types are compared
405 /// when projecting an associated type
406 AssocTypeProjection(DefId),
409 /// Reasons to create a region inference variable
411 /// See `error_reporting` module for more details
412 #[derive(Copy, Clone, Debug)]
413 pub enum RegionVariableOrigin {
414 /// Region variables created for ill-categorized reasons,
415 /// mostly indicates places in need of refactoring
418 /// Regions created by a `&P` or `[...]` pattern
421 /// Regions created by `&` operator
424 /// Regions created as part of an autoref of a method receiver
427 /// Regions created as part of an automatic coercion
430 /// Region variables created as the values for early-bound regions
431 EarlyBoundRegion(Span, Symbol),
433 /// Region variables created for bound regions
434 /// in a function or method that is called
435 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
437 UpvarRegion(ty::UpvarId, Span),
439 BoundRegionInCoherence(ast::Name),
441 /// This origin is used for the inference variables that we create
442 /// during NLL region processing.
443 NLL(NLLRegionVariableOrigin),
446 #[derive(Copy, Clone, Debug)]
447 pub enum NLLRegionVariableOrigin {
448 /// During NLL region processing, we create variables for free
449 /// regions that we encounter in the function signature and
450 /// elsewhere. This origin indices we've got one of those.
453 /// "Universal" instantiation of a higher-ranked region (e.g.,
454 /// from a `for<'a> T` binder). Meant to represent "any region".
455 Placeholder(ty::PlaceholderRegion),
458 /// If this is true, then this variable was created to represent a lifetime
459 /// bound in a `for` binder. For example, it might have been created to
460 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
461 /// Such variables are created when we are trying to figure out if there
462 /// is any valid instantiation of `'a` that could fit into some scenario.
464 /// This is used to inform error reporting: in the case that we are trying to
465 /// determine whether there is any valid instantiation of a `'a` variable that meets
466 /// some constraint C, we want to blame the "source" of that `for` type,
467 /// rather than blaming the source of the constraint C.
472 impl NLLRegionVariableOrigin {
473 pub fn is_universal(self) -> bool {
475 NLLRegionVariableOrigin::FreeRegion => true,
476 NLLRegionVariableOrigin::Placeholder(..) => true,
477 NLLRegionVariableOrigin::Existential { .. } => false,
481 pub fn is_existential(self) -> bool {
486 #[derive(Copy, Clone, Debug)]
487 pub enum FixupError<'tcx> {
488 UnresolvedIntTy(IntVid),
489 UnresolvedFloatTy(FloatVid),
491 UnresolvedConst(ConstVid<'tcx>),
494 /// See the `region_obligations` field for more information.
496 pub struct RegionObligation<'tcx> {
497 pub sub_region: ty::Region<'tcx>,
498 pub sup_type: Ty<'tcx>,
499 pub origin: SubregionOrigin<'tcx>,
502 impl<'tcx> fmt::Display for FixupError<'tcx> {
503 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504 use self::FixupError::*;
507 UnresolvedIntTy(_) => write!(
509 "cannot determine the type of this integer; \
510 add a suffix to specify the type explicitly"
512 UnresolvedFloatTy(_) => write!(
514 "cannot determine the type of this number; \
515 add a suffix to specify the type explicitly"
517 UnresolvedTy(_) => write!(f, "unconstrained type"),
518 UnresolvedConst(_) => write!(f, "unconstrained const value"),
523 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
524 /// Necessary because we can't write the following bound:
525 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
526 pub struct InferCtxtBuilder<'tcx> {
527 global_tcx: TyCtxt<'tcx>,
528 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
531 pub trait TyCtxtInferExt<'tcx> {
532 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
535 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
536 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
537 InferCtxtBuilder { global_tcx: self, fresh_tables: None }
541 impl<'tcx> InferCtxtBuilder<'tcx> {
542 /// Used only by `rustc_typeck` during body type-checking/inference,
543 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
544 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
545 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
549 /// Given a canonical value `C` as a starting point, create an
550 /// inference context that contains each of the bound values
551 /// within instantiated as a fresh variable. The `f` closure is
552 /// invoked with the new infcx, along with the instantiated value
553 /// `V` and a substitution `S`. This substitution `S` maps from
554 /// the bound values in `C` to their instantiated values in `V`
555 /// (in other words, `S(C) = V`).
556 pub fn enter_with_canonical<T, R>(
559 canonical: &Canonical<'tcx, T>,
560 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
563 T: TypeFoldable<'tcx>,
567 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
568 f(infcx, value, subst)
572 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
573 let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
574 let in_progress_tables = fresh_tables.as_ref();
575 global_tcx.enter_local(|tcx| {
579 inner: RefCell::new(InferCtxtInner::new()),
580 lexical_region_resolutions: RefCell::new(None),
581 selection_cache: Default::default(),
582 evaluation_cache: Default::default(),
583 reported_trait_errors: Default::default(),
584 reported_closure_mismatch: Default::default(),
585 tainted_by_errors_flag: Cell::new(false),
586 err_count_on_creation: tcx.sess.err_count(),
587 in_snapshot: Cell::new(false),
588 skip_leak_check: Cell::new(false),
589 universe: Cell::new(ty::UniverseIndex::ROOT),
595 impl<'tcx, T> InferOk<'tcx, T> {
596 pub fn unit(self) -> InferOk<'tcx, ()> {
597 InferOk { value: (), obligations: self.obligations }
600 /// Extracts `value`, registering any obligations into `fulfill_cx`.
601 pub fn into_value_registering_obligations(
603 infcx: &InferCtxt<'_, 'tcx>,
604 fulfill_cx: &mut dyn TraitEngine<'tcx>,
606 let InferOk { value, obligations } = self;
607 for obligation in obligations {
608 fulfill_cx.register_predicate_obligation(infcx, obligation);
614 impl<'tcx> InferOk<'tcx, ()> {
615 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
620 #[must_use = "once you start a snapshot, you should always consume it"]
621 pub struct CombinedSnapshot<'a, 'tcx> {
622 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
623 type_snapshot: type_variable::Snapshot<'tcx>,
624 const_snapshot: ut::Snapshot<ut::InPlace<ty::ConstVid<'tcx>>>,
625 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
626 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
627 region_constraints_snapshot: RegionSnapshot,
628 region_obligations_snapshot: usize,
629 universe: ty::UniverseIndex,
630 was_in_snapshot: bool,
631 was_skip_leak_check: bool,
632 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
635 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
636 pub fn is_in_snapshot(&self) -> bool {
637 self.in_snapshot.get()
640 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
641 t.fold_with(&mut self.freshener())
644 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
646 ty::Infer(ty::TyVar(vid)) => self.inner.borrow().type_variables.var_diverges(vid),
651 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
652 freshen::TypeFreshener::new(self)
655 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
656 use rustc::ty::error::UnconstrainedNumeric::Neither;
657 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
659 ty::Infer(ty::IntVar(vid)) => {
660 if self.inner.borrow_mut().int_unification_table.probe_value(vid).is_some() {
666 ty::Infer(ty::FloatVar(vid)) => {
667 if self.inner.borrow_mut().float_unification_table.probe_value(vid).is_some() {
677 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
678 let mut inner = self.inner.borrow_mut();
679 // FIXME(const_generics): should there be an equivalent function for const variables?
681 let mut vars: Vec<Ty<'_>> = inner
683 .unsolved_variables()
685 .map(|t| self.tcx.mk_ty_var(t))
688 (0..inner.int_unification_table.len())
689 .map(|i| ty::IntVid { index: i as u32 })
690 .filter(|&vid| inner.int_unification_table.probe_value(vid).is_none())
691 .map(|v| self.tcx.mk_int_var(v)),
694 (0..inner.float_unification_table.len())
695 .map(|i| ty::FloatVid { index: i as u32 })
696 .filter(|&vid| inner.float_unification_table.probe_value(vid).is_none())
697 .map(|v| self.tcx.mk_float_var(v)),
704 trace: TypeTrace<'tcx>,
705 param_env: ty::ParamEnv<'tcx>,
706 ) -> CombineFields<'a, 'tcx> {
712 obligations: PredicateObligations::new(),
716 /// Clear the "currently in a snapshot" flag, invoke the closure,
717 /// then restore the flag to its original value. This flag is a
718 /// debugging measure designed to detect cases where we start a
719 /// snapshot, create type variables, and register obligations
720 /// which may involve those type variables in the fulfillment cx,
721 /// potentially leaving "dangling type variables" behind.
722 /// In such cases, an assertion will fail when attempting to
723 /// register obligations, within a snapshot. Very useful, much
724 /// better than grovelling through megabytes of `RUSTC_LOG` output.
726 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
727 /// sometimes create a "mini-fulfilment-cx" in which we enroll
728 /// obligations. As long as this fulfillment cx is fully drained
729 /// before we return, this is not a problem, as there won't be any
730 /// escaping obligations in the main cx. In those cases, you can
731 /// use this function.
732 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
734 F: FnOnce(&Self) -> R,
736 let flag = self.in_snapshot.replace(false);
737 let result = func(self);
738 self.in_snapshot.set(flag);
742 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
743 debug!("start_snapshot()");
745 let in_snapshot = self.in_snapshot.replace(true);
747 let mut inner = self.inner.borrow_mut();
749 projection_cache_snapshot: inner.projection_cache.snapshot(),
750 type_snapshot: inner.type_variables.snapshot(),
751 const_snapshot: inner.const_unification_table.snapshot(),
752 int_snapshot: inner.int_unification_table.snapshot(),
753 float_snapshot: inner.float_unification_table.snapshot(),
754 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
755 region_obligations_snapshot: inner.region_obligations.len(),
756 universe: self.universe(),
757 was_in_snapshot: in_snapshot,
758 was_skip_leak_check: self.skip_leak_check.get(),
759 // Borrow tables "in progress" (i.e., during typeck)
760 // to ban writes from within a snapshot to them.
761 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
765 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
766 debug!("rollback_to(cause={})", cause);
767 let CombinedSnapshot {
768 projection_cache_snapshot,
773 region_constraints_snapshot,
774 region_obligations_snapshot,
781 self.in_snapshot.set(was_in_snapshot);
782 self.universe.set(universe);
783 self.skip_leak_check.set(was_skip_leak_check);
785 let mut inner = self.inner.borrow_mut();
786 inner.projection_cache.rollback_to(projection_cache_snapshot);
787 inner.type_variables.rollback_to(type_snapshot);
788 inner.const_unification_table.rollback_to(const_snapshot);
789 inner.int_unification_table.rollback_to(int_snapshot);
790 inner.float_unification_table.rollback_to(float_snapshot);
791 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
792 inner.region_obligations.truncate(region_obligations_snapshot);
795 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
796 debug!("commit_from()");
797 let CombinedSnapshot {
798 projection_cache_snapshot,
803 region_constraints_snapshot,
804 region_obligations_snapshot: _,
811 self.in_snapshot.set(was_in_snapshot);
812 self.skip_leak_check.set(was_skip_leak_check);
814 let mut inner = self.inner.borrow_mut();
815 inner.projection_cache.commit(projection_cache_snapshot);
816 inner.type_variables.commit(type_snapshot);
817 inner.const_unification_table.commit(const_snapshot);
818 inner.int_unification_table.commit(int_snapshot);
819 inner.float_unification_table.commit(float_snapshot);
820 inner.unwrap_region_constraints().commit(region_constraints_snapshot);
823 /// Executes `f` and commit the bindings.
824 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
826 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
828 debug!("commit_unconditionally()");
829 let snapshot = self.start_snapshot();
830 let r = f(&snapshot);
831 self.commit_from(snapshot);
835 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
836 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
838 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
840 debug!("commit_if_ok()");
841 let snapshot = self.start_snapshot();
842 let r = f(&snapshot);
843 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
846 self.commit_from(snapshot);
849 self.rollback_to("commit_if_ok -- error", snapshot);
855 /// Execute `f` then unroll any bindings it creates.
856 pub fn probe<R, F>(&self, f: F) -> R
858 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
861 let snapshot = self.start_snapshot();
862 let r = f(&snapshot);
863 self.rollback_to("probe", snapshot);
867 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
868 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
870 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
873 let snapshot = self.start_snapshot();
874 let skip_leak_check = should_skip || self.skip_leak_check.get();
875 self.skip_leak_check.set(skip_leak_check);
876 let r = f(&snapshot);
877 self.rollback_to("probe", snapshot);
881 /// Scan the constraints produced since `snapshot` began and returns:
883 /// - `None` -- if none of them involve "region outlives" constraints
884 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
885 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
886 pub fn region_constraints_added_in_snapshot(
888 snapshot: &CombinedSnapshot<'a, 'tcx>,
892 .unwrap_region_constraints()
893 .region_constraints_added_in_snapshot(&snapshot.region_constraints_snapshot)
896 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
897 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
900 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
902 T: at::ToTrace<'tcx>,
904 let origin = &ObligationCause::dummy();
906 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
907 // Ignore obligations, since we are unrolling
908 // everything anyway.
913 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
915 T: at::ToTrace<'tcx>,
917 let origin = &ObligationCause::dummy();
919 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
920 // Ignore obligations, since we are unrolling
921 // everything anyway.
928 origin: SubregionOrigin<'tcx>,
932 debug!("sub_regions({:?} <: {:?})", a, b);
933 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
936 /// Require that the region `r` be equal to one of the regions in
937 /// the set `regions`.
938 pub fn member_constraint(
940 opaque_type_def_id: DefId,
941 definition_span: Span,
943 region: ty::Region<'tcx>,
944 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
946 debug!("member_constraint({:?} <: {:?})", region, in_regions);
947 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
956 pub fn subtype_predicate(
958 cause: &ObligationCause<'tcx>,
959 param_env: ty::ParamEnv<'tcx>,
960 predicate: &ty::PolySubtypePredicate<'tcx>,
961 ) -> Option<InferResult<'tcx, ()>> {
962 // Subtle: it's ok to skip the binder here and resolve because
963 // `shallow_resolve` just ignores anything that is not a type
964 // variable, and because type variable's can't (at present, at
965 // least) capture any of the things bound by this binder.
967 // NOTE(nmatsakis): really, there is no *particular* reason to do this
968 // `shallow_resolve` here except as a micro-optimization.
969 // Naturally I could not resist.
970 let two_unbound_type_vars = {
971 let a = self.shallow_resolve(predicate.skip_binder().a);
972 let b = self.shallow_resolve(predicate.skip_binder().b);
973 a.is_ty_var() && b.is_ty_var()
976 if two_unbound_type_vars {
977 // Two unbound type variables? Can't make progress.
981 Some(self.commit_if_ok(|snapshot| {
982 let (ty::SubtypePredicate { a_is_expected, a, b }, placeholder_map) =
983 self.replace_bound_vars_with_placeholders(predicate);
985 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
987 self.leak_check(false, &placeholder_map, snapshot)?;
993 pub fn region_outlives_predicate(
995 cause: &traits::ObligationCause<'tcx>,
996 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
997 ) -> UnitResult<'tcx> {
998 self.commit_if_ok(|snapshot| {
999 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
1000 self.replace_bound_vars_with_placeholders(predicate);
1001 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1002 RelateRegionParamBound(cause.span)
1004 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1005 self.leak_check(false, &placeholder_map, snapshot)?;
1010 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1011 self.inner.borrow_mut().type_variables.new_var(self.universe(), diverging, origin)
1014 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1015 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1018 pub fn next_ty_var_in_universe(
1020 origin: TypeVariableOrigin,
1021 universe: ty::UniverseIndex,
1023 let vid = self.inner.borrow_mut().type_variables.new_var(universe, false, origin);
1024 self.tcx.mk_ty_var(vid)
1027 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1028 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1031 pub fn next_const_var(
1034 origin: ConstVariableOrigin,
1035 ) -> &'tcx ty::Const<'tcx> {
1036 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1039 pub fn next_const_var_in_universe(
1042 origin: ConstVariableOrigin,
1043 universe: ty::UniverseIndex,
1044 ) -> &'tcx ty::Const<'tcx> {
1048 .const_unification_table
1049 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1050 self.tcx.mk_const_var(vid, ty)
1053 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1054 self.inner.borrow_mut().const_unification_table.new_key(ConstVarValue {
1056 val: ConstVariableValue::Unknown { universe: self.universe() },
1060 fn next_int_var_id(&self) -> IntVid {
1061 self.inner.borrow_mut().int_unification_table.new_key(None)
1064 pub fn next_int_var(&self) -> Ty<'tcx> {
1065 self.tcx.mk_int_var(self.next_int_var_id())
1068 fn next_float_var_id(&self) -> FloatVid {
1069 self.inner.borrow_mut().float_unification_table.new_key(None)
1072 pub fn next_float_var(&self) -> Ty<'tcx> {
1073 self.tcx.mk_float_var(self.next_float_var_id())
1076 /// Creates a fresh region variable with the next available index.
1077 /// The variable will be created in the maximum universe created
1078 /// thus far, allowing it to name any region created thus far.
1079 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1080 self.next_region_var_in_universe(origin, self.universe())
1083 /// Creates a fresh region variable with the next available index
1084 /// in the given universe; typically, you can use
1085 /// `next_region_var` and just use the maximal universe.
1086 pub fn next_region_var_in_universe(
1088 origin: RegionVariableOrigin,
1089 universe: ty::UniverseIndex,
1090 ) -> ty::Region<'tcx> {
1092 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1093 self.tcx.mk_region(ty::ReVar(region_var))
1096 /// Return the universe that the region `r` was created in. For
1097 /// most regions (e.g., `'static`, named regions from the user,
1098 /// etc) this is the root universe U0. For inference variables or
1099 /// placeholders, however, it will return the universe which which
1100 /// they are associated.
1101 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1102 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1105 /// Number of region variables created so far.
1106 pub fn num_region_vars(&self) -> usize {
1107 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1110 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1111 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1112 self.next_region_var(RegionVariableOrigin::NLL(origin))
1115 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1116 pub fn next_nll_region_var_in_universe(
1118 origin: NLLRegionVariableOrigin,
1119 universe: ty::UniverseIndex,
1120 ) -> ty::Region<'tcx> {
1121 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1124 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1126 GenericParamDefKind::Lifetime => {
1127 // Create a region inference variable for the given
1128 // region parameter definition.
1129 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1131 GenericParamDefKind::Type { .. } => {
1132 // Create a type inference variable for the given
1133 // type parameter definition. The substitutions are
1134 // for actual parameters that may be referred to by
1135 // the default of this type parameter, if it exists.
1136 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1137 // used in a path such as `Foo::<T, U>::new()` will
1138 // use an inference variable for `C` with `[T, U]`
1139 // as the substitutions for the default, `(T, U)`.
1140 let ty_var_id = self.inner.borrow_mut().type_variables.new_var(
1143 TypeVariableOrigin {
1144 kind: TypeVariableOriginKind::TypeParameterDefinition(
1152 self.tcx.mk_ty_var(ty_var_id).into()
1154 GenericParamDefKind::Const { .. } => {
1155 let origin = ConstVariableOrigin {
1156 kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1160 self.inner.borrow_mut().const_unification_table.new_key(ConstVarValue {
1162 val: ConstVariableValue::Unknown { universe: self.universe() },
1164 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1169 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1170 /// type/region parameter to a fresh inference variable.
1171 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1172 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1175 /// Returns `true` if errors have been reported since this infcx was
1176 /// created. This is sometimes used as a heuristic to skip
1177 /// reporting errors that often occur as a result of earlier
1178 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1179 /// inference variables, regionck errors).
1180 pub fn is_tainted_by_errors(&self) -> bool {
1182 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1183 tainted_by_errors_flag={})",
1184 self.tcx.sess.err_count(),
1185 self.err_count_on_creation,
1186 self.tainted_by_errors_flag.get()
1189 if self.tcx.sess.err_count() > self.err_count_on_creation {
1190 return true; // errors reported since this infcx was made
1192 self.tainted_by_errors_flag.get()
1195 /// Set the "tainted by errors" flag to true. We call this when we
1196 /// observe an error from a prior pass.
1197 pub fn set_tainted_by_errors(&self) {
1198 debug!("set_tainted_by_errors()");
1199 self.tainted_by_errors_flag.set(true)
1202 /// Process the region constraints and report any errors that
1203 /// result. After this, no more unification operations should be
1204 /// done -- or the compiler will panic -- but it is legal to use
1205 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1206 pub fn resolve_regions_and_report_errors(
1208 region_context: DefId,
1209 region_map: ®ion::ScopeTree,
1210 outlives_env: &OutlivesEnvironment<'tcx>,
1211 suppress: SuppressRegionErrors,
1214 self.is_tainted_by_errors() || self.inner.borrow().region_obligations.is_empty(),
1215 "region_obligations not empty: {:#?}",
1216 self.inner.borrow().region_obligations
1219 let region_rels = &RegionRelations::new(
1223 outlives_env.free_region_map(),
1225 let (var_infos, data) = self
1230 .expect("regions already resolved")
1231 .into_infos_and_data();
1232 let (lexical_region_resolutions, errors) =
1233 lexical_region_resolve::resolve(region_rels, var_infos, data);
1235 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1236 assert!(old_value.is_none());
1238 if !self.is_tainted_by_errors() {
1239 // As a heuristic, just skip reporting region errors
1240 // altogether if other errors have been reported while
1241 // this infcx was in use. This is totally hokey but
1242 // otherwise we have a hard time separating legit region
1243 // errors from silly ones.
1244 self.report_region_errors(region_map, &errors, suppress);
1248 /// Obtains (and clears) the current set of region
1249 /// constraints. The inference context is still usable: further
1250 /// unifications will simply add new constraints.
1252 /// This method is not meant to be used with normal lexical region
1253 /// resolution. Rather, it is used in the NLL mode as a kind of
1254 /// interim hack: basically we run normal type-check and generate
1255 /// region constraints as normal, but then we take them and
1256 /// translate them into the form that the NLL solver
1257 /// understands. See the NLL module for mode details.
1258 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1260 self.inner.borrow().region_obligations.is_empty(),
1261 "region_obligations not empty: {:#?}",
1262 self.inner.borrow().region_obligations
1265 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1268 /// Gives temporary access to the region constraint data.
1269 #[allow(non_camel_case_types)] // bug with impl trait
1270 pub fn with_region_constraints<R>(
1272 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1274 let mut inner = self.inner.borrow_mut();
1275 op(inner.unwrap_region_constraints().data())
1278 /// Takes ownership of the list of variable regions. This implies
1279 /// that all the region constraints have already been taken, and
1280 /// hence that `resolve_regions_and_report_errors` can never be
1281 /// called. This is used only during NLL processing to "hand off" ownership
1282 /// of the set of region variables into the NLL region context.
1283 pub fn take_region_var_origins(&self) -> VarInfos {
1284 let (var_infos, data) = self
1289 .expect("regions already resolved")
1290 .into_infos_and_data();
1291 assert!(data.is_empty());
1295 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1296 self.resolve_vars_if_possible(&t).to_string()
1299 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1300 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1301 format!("({})", tstrs.join(", "))
1304 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1305 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1308 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1309 /// universe index of `TyVar(vid)`.
1310 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1311 use self::type_variable::TypeVariableValue;
1313 match self.inner.borrow_mut().type_variables.probe(vid) {
1314 TypeVariableValue::Known { value } => Ok(value),
1315 TypeVariableValue::Unknown { universe } => Err(universe),
1319 /// Resolve any type variables found in `value` -- but only one
1320 /// level. So, if the variable `?X` is bound to some type
1321 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1322 /// itself be bound to a type).
1324 /// Useful when you only need to inspect the outermost level of
1325 /// the type and don't care about nested types (or perhaps you
1326 /// will be resolving them as well, e.g. in a loop).
1327 pub fn shallow_resolve<T>(&self, value: T) -> T
1329 T: TypeFoldable<'tcx>,
1331 let mut r = ShallowResolver::new(self);
1332 value.fold_with(&mut r)
1335 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1336 self.inner.borrow_mut().type_variables.root_var(var)
1339 /// Where possible, replaces type/const variables in
1340 /// `value` with their final value. Note that region variables
1341 /// are unaffected. If a type/const variable has not been unified, it
1342 /// is left as is. This is an idempotent operation that does
1343 /// not affect inference state in any way and so you can do it
1345 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1347 T: TypeFoldable<'tcx>,
1349 if !value.needs_infer() {
1350 return value.clone(); // Avoid duplicated subst-folding.
1352 let mut r = resolve::OpportunisticVarResolver::new(self);
1353 value.fold_with(&mut r)
1356 /// Returns the first unresolved variable contained in `T`. In the
1357 /// process of visiting `T`, this will resolve (where possible)
1358 /// type variables in `T`, but it never constructs the final,
1359 /// resolved type, so it's more efficient than
1360 /// `resolve_vars_if_possible()`.
1361 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1363 T: TypeFoldable<'tcx>,
1365 let mut r = resolve::UnresolvedTypeFinder::new(self);
1366 value.visit_with(&mut r);
1370 pub fn probe_const_var(
1372 vid: ty::ConstVid<'tcx>,
1373 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1374 match self.inner.borrow_mut().const_unification_table.probe_value(vid).val {
1375 ConstVariableValue::Known { value } => Ok(value),
1376 ConstVariableValue::Unknown { universe } => Err(universe),
1380 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1382 * Attempts to resolve all type/region/const variables in
1383 * `value`. Region inference must have been run already (e.g.,
1384 * by calling `resolve_regions_and_report_errors`). If some
1385 * variable was never unified, an `Err` results.
1387 * This method is idempotent, but it not typically not invoked
1388 * except during the writeback phase.
1391 resolve::fully_resolve(self, value)
1394 // [Note-Type-error-reporting]
1395 // An invariant is that anytime the expected or actual type is Error (the special
1396 // error type, meaning that an error occurred when typechecking this expression),
1397 // this is a derived error. The error cascaded from another error (that was already
1398 // reported), so it's not useful to display it to the user.
1399 // The following methods implement this logic.
1400 // They check if either the actual or expected type is Error, and don't print the error
1401 // in this case. The typechecker should only ever report type errors involving mismatched
1402 // types using one of these methods, and should not call span_err directly for such
1405 pub fn type_error_struct_with_diag<M>(
1409 actual_ty: Ty<'tcx>,
1410 ) -> DiagnosticBuilder<'tcx>
1412 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1414 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1415 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1417 // Don't report an error if actual type is `Error`.
1418 if actual_ty.references_error() {
1419 return self.tcx.sess.diagnostic().struct_dummy();
1422 mk_diag(self.ty_to_string(actual_ty))
1425 pub fn report_mismatched_types(
1427 cause: &ObligationCause<'tcx>,
1430 err: TypeError<'tcx>,
1431 ) -> DiagnosticBuilder<'tcx> {
1432 let trace = TypeTrace::types(cause, true, expected, actual);
1433 self.report_and_explain_type_error(trace, &err)
1436 pub fn replace_bound_vars_with_fresh_vars<T>(
1439 lbrct: LateBoundRegionConversionTime,
1440 value: &ty::Binder<T>,
1441 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1443 T: TypeFoldable<'tcx>,
1445 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1447 self.next_ty_var(TypeVariableOrigin {
1448 kind: TypeVariableOriginKind::MiscVariable,
1452 let fld_c = |_, ty| {
1453 self.next_const_var(
1455 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1458 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1461 /// See the [`region_constraints::verify_generic_bound`] method.
1462 pub fn verify_generic_bound(
1464 origin: SubregionOrigin<'tcx>,
1465 kind: GenericKind<'tcx>,
1466 a: ty::Region<'tcx>,
1467 bound: VerifyBound<'tcx>,
1469 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1473 .unwrap_region_constraints()
1474 .verify_generic_bound(origin, kind, a, bound);
1477 pub fn type_is_copy_modulo_regions(
1479 param_env: ty::ParamEnv<'tcx>,
1483 let ty = self.resolve_vars_if_possible(&ty);
1485 if !(param_env, ty).has_local_value() {
1486 return ty.is_copy_modulo_regions(self.tcx, param_env, span);
1489 let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem, None);
1491 // This can get called from typeck (by euv), and `moves_by_default`
1492 // rightly refuses to work with inference variables, but
1493 // moves_by_default has a cache, which we want to use in other
1495 traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id, span)
1498 /// Obtains the latest type of the given closure; this may be a
1499 /// closure in the current function, in which case its
1500 /// `ClosureKind` may not yet be known.
1501 pub fn closure_kind(
1503 closure_def_id: DefId,
1504 closure_substs: SubstsRef<'tcx>,
1505 ) -> Option<ty::ClosureKind> {
1506 let closure_kind_ty = closure_substs.as_closure().kind_ty(closure_def_id, self.tcx);
1507 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1508 closure_kind_ty.to_opt_closure_kind()
1511 /// Obtains the signature of a closure. For closures, unlike
1512 /// `tcx.fn_sig(def_id)`, this method will work during the
1513 /// type-checking of the enclosing function and return the closure
1514 /// signature in its partially inferred state.
1515 pub fn closure_sig(&self, def_id: DefId, substs: SubstsRef<'tcx>) -> ty::PolyFnSig<'tcx> {
1516 let closure_sig_ty = substs.as_closure().sig_ty(def_id, self.tcx);
1517 let closure_sig_ty = self.shallow_resolve(closure_sig_ty);
1518 closure_sig_ty.fn_sig(self.tcx)
1521 /// Normalizes associated types in `value`, potentially returning
1522 /// new obligations that must further be processed.
1523 pub fn partially_normalize_associated_types_in<T>(
1526 body_id: hir::HirId,
1527 param_env: ty::ParamEnv<'tcx>,
1529 ) -> InferOk<'tcx, T>
1531 T: TypeFoldable<'tcx>,
1533 debug!("partially_normalize_associated_types_in(value={:?})", value);
1534 let mut selcx = traits::SelectionContext::new(self);
1535 let cause = ObligationCause::misc(span, body_id);
1536 let traits::Normalized { value, obligations } =
1537 traits::normalize(&mut selcx, param_env, cause, value);
1539 "partially_normalize_associated_types_in: result={:?} predicates={:?}",
1542 InferOk { value, obligations }
1545 /// Clears the selection, evaluation, and projection caches. This is useful when
1546 /// repeatedly attempting to select an `Obligation` while changing only
1547 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1548 pub fn clear_caches(&self) {
1549 self.selection_cache.clear();
1550 self.evaluation_cache.clear();
1551 self.inner.borrow_mut().projection_cache.clear();
1554 fn universe(&self) -> ty::UniverseIndex {
1558 /// Creates and return a fresh universe that extends all previous
1559 /// universes. Updates `self.universe` to that new universe.
1560 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1561 let u = self.universe.get().next_universe();
1562 self.universe.set(u);
1566 /// Resolves and evaluates a constant.
1568 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1569 /// substitutions and environment are used to resolve the constant. Alternatively if the
1570 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1571 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1572 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1573 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1576 /// This handles inferences variables within both `param_env` and `substs` by
1577 /// performing the operation on their respective canonical forms.
1578 pub fn const_eval_resolve(
1580 param_env: ty::ParamEnv<'tcx>,
1582 substs: SubstsRef<'tcx>,
1583 promoted: Option<mir::Promoted>,
1585 ) -> ConstEvalResult<'tcx> {
1586 let mut original_values = OriginalQueryValues::default();
1587 let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1589 let (param_env, substs) = canonical.value;
1590 // The return value is the evaluated value which doesn't contain any reference to inference
1591 // variables, thus we don't need to substitute back the original values.
1592 self.tcx.const_eval_resolve(param_env, def_id, substs, promoted, span)
1596 pub struct ShallowResolver<'a, 'tcx> {
1597 infcx: &'a InferCtxt<'a, 'tcx>,
1600 impl<'a, 'tcx> ShallowResolver<'a, 'tcx> {
1602 pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self {
1603 ShallowResolver { infcx }
1606 /// If `typ` is a type variable of some kind, resolve it one level
1607 /// (but do not resolve types found in the result). If `typ` is
1608 /// not a type variable, just return it unmodified.
1609 pub fn shallow_resolve(&mut self, typ: Ty<'tcx>) -> Ty<'tcx> {
1611 ty::Infer(ty::TyVar(v)) => {
1612 // Not entirely obvious: if `typ` is a type variable,
1613 // it can be resolved to an int/float variable, which
1614 // can then be recursively resolved, hence the
1615 // recursion. Note though that we prevent type
1616 // variables from unifying to other type variables
1617 // directly (though they may be embedded
1618 // structurally), and we prevent cycles in any case,
1619 // so this recursion should always be of very limited
1622 // Note: if these two lines are combined into one we get
1623 // dynamic borrow errors on `self.infcx.inner`.
1624 let known = self.infcx.inner.borrow_mut().type_variables.probe(v).known();
1625 known.map(|t| self.fold_ty(t)).unwrap_or(typ)
1628 ty::Infer(ty::IntVar(v)) => self
1632 .int_unification_table
1634 .map(|v| v.to_type(self.infcx.tcx))
1637 ty::Infer(ty::FloatVar(v)) => self
1641 .float_unification_table
1643 .map(|v| v.to_type(self.infcx.tcx))
1650 // `resolver.shallow_resolve_changed(ty)` is equivalent to
1651 // `resolver.shallow_resolve(ty) != ty`, but more efficient. It's always
1652 // inlined, despite being large, because it has only two call sites that
1653 // are extremely hot.
1655 pub fn shallow_resolve_changed(&self, infer: ty::InferTy) -> bool {
1658 use self::type_variable::TypeVariableValue;
1660 // If `inlined_probe` returns a `Known` value its `kind` never
1662 match self.infcx.inner.borrow_mut().type_variables.inlined_probe(v) {
1663 TypeVariableValue::Unknown { .. } => false,
1664 TypeVariableValue::Known { .. } => true,
1669 // If inlined_probe_value returns a value it's always a
1670 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1672 self.infcx.inner.borrow_mut().int_unification_table.inlined_probe_value(v).is_some()
1675 ty::FloatVar(v) => {
1676 // If inlined_probe_value returns a value it's always a
1677 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1679 // Not `inlined_probe_value(v)` because this call site is colder.
1680 self.infcx.inner.borrow_mut().float_unification_table.probe_value(v).is_some()
1683 _ => unreachable!(),
1688 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1689 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1693 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1694 self.shallow_resolve(ty)
1697 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1698 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1702 .const_unification_table
1713 impl<'tcx> TypeTrace<'tcx> {
1714 pub fn span(&self) -> Span {
1719 cause: &ObligationCause<'tcx>,
1720 a_is_expected: bool,
1723 ) -> TypeTrace<'tcx> {
1724 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1727 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1729 cause: ObligationCause::dummy(),
1730 values: Types(ExpectedFound { expected: tcx.types.err, found: tcx.types.err }),
1735 impl<'tcx> SubregionOrigin<'tcx> {
1736 pub fn span(&self) -> Span {
1738 Subtype(ref a) => a.span(),
1739 InfStackClosure(a) => a,
1740 InvokeClosure(a) => a,
1741 DerefPointer(a) => a,
1742 ClosureCapture(a, _) => a,
1744 RelateObjectBound(a) => a,
1745 RelateParamBound(a, _) => a,
1746 RelateRegionParamBound(a) => a,
1747 RelateDefaultParamBound(a, _) => a,
1749 ReborrowUpvar(a, _) => a,
1750 DataBorrowed(_, a) => a,
1751 ReferenceOutlivesReferent(_, a) => a,
1752 ParameterInScope(_, a) => a,
1753 ExprTypeIsNotInScope(_, a) => a,
1754 BindingTypeIsNotValidAtDecl(a) => a,
1761 SafeDestructor(a) => a,
1762 CompareImplMethodObligation { span, .. } => span,
1766 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1768 F: FnOnce() -> Self,
1771 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1772 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1775 traits::ObligationCauseCode::CompareImplMethodObligation {
1779 } => SubregionOrigin::CompareImplMethodObligation {
1791 impl RegionVariableOrigin {
1792 pub fn span(&self) -> Span {
1794 MiscVariable(a) => a,
1795 PatternRegion(a) => a,
1796 AddrOfRegion(a) => a,
1799 EarlyBoundRegion(a, ..) => a,
1800 LateBoundRegion(a, ..) => a,
1801 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1802 UpvarRegion(_, a) => a,
1803 NLL(..) => bug!("NLL variable used with `span`"),
1808 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1809 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1812 "RegionObligation(sub_region={:?}, sup_type={:?})",
1813 self.sub_region, self.sup_type