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::region;
18 use rustc::mir::interpret::ConstEvalResult;
19 use rustc::session::config::BorrowckMode;
20 use rustc::traits::select;
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;
62 pub mod region_constraints;
65 pub mod type_variable;
67 use crate::infer::canonical::OriginalQueryValues;
68 pub use rustc::infer::unify_key;
72 pub struct InferOk<'tcx, T> {
74 pub obligations: PredicateObligations<'tcx>,
76 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
78 pub type Bound<T> = Option<T>;
79 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
80 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
82 /// A flag that is used to suppress region errors. This is normally
83 /// false, but sometimes -- when we are doing region checks that the
84 /// NLL borrow checker will also do -- it might be set to true.
85 #[derive(Copy, Clone, Default, Debug)]
86 pub struct SuppressRegionErrors {
90 impl SuppressRegionErrors {
91 pub fn suppressed(self) -> bool {
95 /// Indicates that the MIR borrowck will repeat these region
96 /// checks, so we should ignore errors if NLL is (unconditionally)
98 pub fn when_nll_is_enabled(tcx: TyCtxt<'_>) -> Self {
99 // FIXME(Centril): Once we actually remove `::Migrate` also make
100 // this always `true` and then proceed to eliminate the dead code.
101 match tcx.borrowck_mode() {
102 // If we're on Migrate mode, report AST region errors
103 BorrowckMode::Migrate => SuppressRegionErrors { suppressed: false },
105 // If we're on MIR, don't report AST region errors as they should be reported by NLL
106 BorrowckMode::Mir => SuppressRegionErrors { suppressed: true },
111 /// This type contains all the things within `InferCtxt` that sit within a
112 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
113 /// operations are hot enough that we want only one call to `borrow_mut` per
114 /// call to `start_snapshot` and `rollback_to`.
115 pub struct InferCtxtInner<'tcx> {
116 /// Cache for projections. This cache is snapshotted along with the infcx.
118 /// Public so that `traits::project` can use it.
119 pub projection_cache: traits::ProjectionCache<'tcx>,
121 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
122 /// that might instantiate a general type variable have an order,
123 /// represented by its upper and lower bounds.
124 type_variables: type_variable::TypeVariableTable<'tcx>,
126 /// Map from const parameter variable to the kind of const it represents.
127 const_unification_table: ut::UnificationTable<ut::InPlace<ty::ConstVid<'tcx>>>,
129 /// Map from integral variable to the kind of integer it represents.
130 int_unification_table: ut::UnificationTable<ut::InPlace<ty::IntVid>>,
132 /// Map from floating variable to the kind of float it represents.
133 float_unification_table: ut::UnificationTable<ut::InPlace<ty::FloatVid>>,
135 /// Tracks the set of region variables and the constraints between them.
136 /// This is initially `Some(_)` but when
137 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
138 /// -- further attempts to perform unification, etc., may fail if new
139 /// region constraints would've been added.
140 region_constraints: Option<RegionConstraintCollector<'tcx>>,
142 /// A set of constraints that regionck must validate. Each
143 /// constraint has the form `T:'a`, meaning "some type `T` must
144 /// outlive the lifetime 'a". These constraints derive from
145 /// instantiated type parameters. So if you had a struct defined
148 /// struct Foo<T:'static> { ... }
150 /// then in some expression `let x = Foo { ... }` it will
151 /// instantiate the type parameter `T` with a fresh type `$0`. At
152 /// the same time, it will record a region obligation of
153 /// `$0:'static`. This will get checked later by regionck. (We
154 /// can't generally check these things right away because we have
155 /// to wait until types are resolved.)
157 /// These are stored in a map keyed to the id of the innermost
158 /// enclosing fn body / static initializer expression. This is
159 /// because the location where the obligation was incurred can be
160 /// relevant with respect to which sublifetime assumptions are in
161 /// place. The reason that we store under the fn-id, and not
162 /// something more fine-grained, is so that it is easier for
163 /// regionck to be sure that it has found *all* the region
164 /// obligations (otherwise, it's easy to fail to walk to a
165 /// particular node-id).
167 /// Before running `resolve_regions_and_report_errors`, the creator
168 /// of the inference context is expected to invoke
169 /// `process_region_obligations` (defined in `self::region_obligations`)
170 /// for each body-id in this map, which will process the
171 /// obligations within. This is expected to be done 'late enough'
172 /// that all type inference variables have been bound and so forth.
173 pub region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
176 impl<'tcx> InferCtxtInner<'tcx> {
177 fn new() -> InferCtxtInner<'tcx> {
179 projection_cache: Default::default(),
180 type_variables: type_variable::TypeVariableTable::new(),
181 const_unification_table: ut::UnificationTable::new(),
182 int_unification_table: ut::UnificationTable::new(),
183 float_unification_table: ut::UnificationTable::new(),
184 region_constraints: Some(RegionConstraintCollector::new()),
185 region_obligations: vec![],
189 pub fn unwrap_region_constraints(&mut self) -> &mut RegionConstraintCollector<'tcx> {
190 self.region_constraints.as_mut().expect("region constraints already solved")
194 pub struct InferCtxt<'a, 'tcx> {
195 pub tcx: TyCtxt<'tcx>,
197 /// During type-checking/inference of a body, `in_progress_tables`
198 /// contains a reference to the tables being built up, which are
199 /// used for reading closure kinds/signatures as they are inferred,
200 /// and for error reporting logic to read arbitrary node types.
201 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
203 pub inner: RefCell<InferCtxtInner<'tcx>>,
205 /// If set, this flag causes us to skip the 'leak check' during
206 /// higher-ranked subtyping operations. This flag is a temporary one used
207 /// to manage the removal of the leak-check: for the time being, we still run the
208 /// leak-check, but we issue warnings. This flag can only be set to true
209 /// when entering a snapshot.
210 skip_leak_check: Cell<bool>,
212 /// Once region inference is done, the values for each variable.
213 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
215 /// Caches the results of trait selection. This cache is used
216 /// for things that have to do with the parameters in scope.
217 pub selection_cache: select::SelectionCache<'tcx>,
219 /// Caches the results of trait evaluation.
220 pub evaluation_cache: select::EvaluationCache<'tcx>,
222 /// the set of predicates on which errors have been reported, to
223 /// avoid reporting the same error twice.
224 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
226 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
228 /// When an error occurs, we want to avoid reporting "derived"
229 /// errors that are due to this original failure. Normally, we
230 /// handle this with the `err_count_on_creation` count, which
231 /// basically just tracks how many errors were reported when we
232 /// started type-checking a fn and checks to see if any new errors
233 /// have been reported since then. Not great, but it works.
235 /// However, when errors originated in other passes -- notably
236 /// resolve -- this heuristic breaks down. Therefore, we have this
237 /// auxiliary flag that one can set whenever one creates a
238 /// type-error that is due to an error in a prior pass.
240 /// Don't read this flag directly, call `is_tainted_by_errors()`
241 /// and `set_tainted_by_errors()`.
242 tainted_by_errors_flag: Cell<bool>,
244 /// Track how many errors were reported when this infcx is created.
245 /// If the number of errors increases, that's also a sign (line
246 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
247 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
248 err_count_on_creation: usize,
250 /// This flag is true while there is an active snapshot.
251 in_snapshot: Cell<bool>,
253 /// What is the innermost universe we have created? Starts out as
254 /// `UniverseIndex::root()` but grows from there as we enter
255 /// universal quantifiers.
257 /// N.B., at present, we exclude the universal quantifiers on the
258 /// item we are type-checking, and just consider those names as
259 /// part of the root universe. So this would only get incremented
260 /// when we enter into a higher-ranked (`for<..>`) type or trait
262 universe: Cell<ty::UniverseIndex>,
265 /// A map returned by `replace_bound_vars_with_placeholders()`
266 /// indicating the placeholder region that each late-bound region was
268 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
270 /// See the `error_reporting` module for more details.
271 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
272 pub enum ValuePairs<'tcx> {
273 Types(ExpectedFound<Ty<'tcx>>),
274 Regions(ExpectedFound<ty::Region<'tcx>>),
275 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
276 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
277 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
280 /// The trace designates the path through inference that we took to
281 /// encounter an error or subtyping constraint.
283 /// See the `error_reporting` module for more details.
284 #[derive(Clone, Debug)]
285 pub struct TypeTrace<'tcx> {
286 cause: ObligationCause<'tcx>,
287 values: ValuePairs<'tcx>,
290 /// The origin of a `r1 <= r2` constraint.
292 /// See `error_reporting` module for more details
293 #[derive(Clone, Debug)]
294 pub enum SubregionOrigin<'tcx> {
295 /// Arose from a subtyping relation
296 Subtype(Box<TypeTrace<'tcx>>),
298 /// Stack-allocated closures cannot outlive innermost loop
299 /// or function so as to ensure we only require finite stack
300 InfStackClosure(Span),
302 /// Invocation of closure must be within its lifetime
305 /// Dereference of reference must be within its lifetime
308 /// Closure bound must not outlive captured variables
309 ClosureCapture(Span, hir::HirId),
311 /// Index into slice must be within its lifetime
314 /// When casting `&'a T` to an `&'b Trait` object,
315 /// relating `'a` to `'b`
316 RelateObjectBound(Span),
318 /// Some type parameter was instantiated with the given type,
319 /// and that type must outlive some region.
320 RelateParamBound(Span, Ty<'tcx>),
322 /// The given region parameter was instantiated with a region
323 /// that must outlive some other region.
324 RelateRegionParamBound(Span),
326 /// A bound placed on type parameters that states that must outlive
327 /// the moment of their instantiation.
328 RelateDefaultParamBound(Span, Ty<'tcx>),
330 /// Creating a pointer `b` to contents of another reference
333 /// Creating a pointer `b` to contents of an upvar
334 ReborrowUpvar(Span, ty::UpvarId),
336 /// Data with type `Ty<'tcx>` was borrowed
337 DataBorrowed(Ty<'tcx>, Span),
339 /// (&'a &'b T) where a >= b
340 ReferenceOutlivesReferent(Ty<'tcx>, Span),
342 /// Type or region parameters must be in scope.
343 ParameterInScope(ParameterOrigin, Span),
345 /// The type T of an expression E must outlive the lifetime for E.
346 ExprTypeIsNotInScope(Ty<'tcx>, Span),
348 /// A `ref b` whose region does not enclose the decl site
349 BindingTypeIsNotValidAtDecl(Span),
351 /// Regions appearing in a method receiver must outlive method call
354 /// Regions appearing in a function argument must outlive func call
357 /// Region in return type of invoked fn must enclose call
360 /// Operands must be in scope
363 /// Region resulting from a `&` expr must enclose the `&` expr
366 /// An auto-borrow that does not enclose the expr where it occurs
369 /// Region constraint arriving from destructor safety
370 SafeDestructor(Span),
372 /// Comparing the signature and requirements of an impl method against
373 /// the containing trait.
374 CompareImplMethodObligation {
376 item_name: ast::Name,
377 impl_item_def_id: DefId,
378 trait_item_def_id: DefId,
382 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
383 #[cfg(target_arch = "x86_64")]
384 static_assert_size!(SubregionOrigin<'_>, 32);
386 /// Places that type/region parameters can appear.
387 #[derive(Clone, Copy, Debug)]
388 pub enum ParameterOrigin {
390 MethodCall, // foo.bar() <-- parameters on impl providing bar()
391 OverloadedOperator, // a + b when overloaded
392 OverloadedDeref, // *a when overloaded
395 /// Times when we replace late-bound regions with variables:
396 #[derive(Clone, Copy, Debug)]
397 pub enum LateBoundRegionConversionTime {
398 /// when a fn is called
401 /// when two higher-ranked types are compared
404 /// when projecting an associated type
405 AssocTypeProjection(DefId),
408 /// Reasons to create a region inference variable
410 /// See `error_reporting` module for more details
411 #[derive(Copy, Clone, Debug)]
412 pub enum RegionVariableOrigin {
413 /// Region variables created for ill-categorized reasons,
414 /// mostly indicates places in need of refactoring
417 /// Regions created by a `&P` or `[...]` pattern
420 /// Regions created by `&` operator
423 /// Regions created as part of an autoref of a method receiver
426 /// Regions created as part of an automatic coercion
429 /// Region variables created as the values for early-bound regions
430 EarlyBoundRegion(Span, Symbol),
432 /// Region variables created for bound regions
433 /// in a function or method that is called
434 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
436 UpvarRegion(ty::UpvarId, Span),
438 BoundRegionInCoherence(ast::Name),
440 /// This origin is used for the inference variables that we create
441 /// during NLL region processing.
442 NLL(NLLRegionVariableOrigin),
445 #[derive(Copy, Clone, Debug)]
446 pub enum NLLRegionVariableOrigin {
447 /// During NLL region processing, we create variables for free
448 /// regions that we encounter in the function signature and
449 /// elsewhere. This origin indices we've got one of those.
452 /// "Universal" instantiation of a higher-ranked region (e.g.,
453 /// from a `for<'a> T` binder). Meant to represent "any region".
454 Placeholder(ty::PlaceholderRegion),
457 /// If this is true, then this variable was created to represent a lifetime
458 /// bound in a `for` binder. For example, it might have been created to
459 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
460 /// Such variables are created when we are trying to figure out if there
461 /// is any valid instantiation of `'a` that could fit into some scenario.
463 /// This is used to inform error reporting: in the case that we are trying to
464 /// determine whether there is any valid instantiation of a `'a` variable that meets
465 /// some constraint C, we want to blame the "source" of that `for` type,
466 /// rather than blaming the source of the constraint C.
471 impl NLLRegionVariableOrigin {
472 pub fn is_universal(self) -> bool {
474 NLLRegionVariableOrigin::FreeRegion => true,
475 NLLRegionVariableOrigin::Placeholder(..) => true,
476 NLLRegionVariableOrigin::Existential { .. } => false,
480 pub fn is_existential(self) -> bool {
485 #[derive(Copy, Clone, Debug)]
486 pub enum FixupError<'tcx> {
487 UnresolvedIntTy(IntVid),
488 UnresolvedFloatTy(FloatVid),
490 UnresolvedConst(ConstVid<'tcx>),
493 /// See the `region_obligations` field for more information.
495 pub struct RegionObligation<'tcx> {
496 pub sub_region: ty::Region<'tcx>,
497 pub sup_type: Ty<'tcx>,
498 pub origin: SubregionOrigin<'tcx>,
501 impl<'tcx> fmt::Display for FixupError<'tcx> {
502 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503 use self::FixupError::*;
506 UnresolvedIntTy(_) => write!(
508 "cannot determine the type of this integer; \
509 add a suffix to specify the type explicitly"
511 UnresolvedFloatTy(_) => write!(
513 "cannot determine the type of this number; \
514 add a suffix to specify the type explicitly"
516 UnresolvedTy(_) => write!(f, "unconstrained type"),
517 UnresolvedConst(_) => write!(f, "unconstrained const value"),
522 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
523 /// Necessary because we can't write the following bound:
524 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
525 pub struct InferCtxtBuilder<'tcx> {
526 global_tcx: TyCtxt<'tcx>,
527 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
530 pub trait TyCtxtInferExt<'tcx> {
531 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
534 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
535 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
536 InferCtxtBuilder { global_tcx: self, fresh_tables: None }
540 impl<'tcx> InferCtxtBuilder<'tcx> {
541 /// Used only by `rustc_typeck` during body type-checking/inference,
542 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
543 pub fn with_fresh_in_progress_tables(mut self, table_owner: DefId) -> Self {
544 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
548 /// Given a canonical value `C` as a starting point, create an
549 /// inference context that contains each of the bound values
550 /// within instantiated as a fresh variable. The `f` closure is
551 /// invoked with the new infcx, along with the instantiated value
552 /// `V` and a substitution `S`. This substitution `S` maps from
553 /// the bound values in `C` to their instantiated values in `V`
554 /// (in other words, `S(C) = V`).
555 pub fn enter_with_canonical<T, R>(
558 canonical: &Canonical<'tcx, T>,
559 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
562 T: TypeFoldable<'tcx>,
566 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
567 f(infcx, value, subst)
571 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
572 let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
573 let in_progress_tables = fresh_tables.as_ref();
574 global_tcx.enter_local(|tcx| {
578 inner: RefCell::new(InferCtxtInner::new()),
579 lexical_region_resolutions: RefCell::new(None),
580 selection_cache: Default::default(),
581 evaluation_cache: Default::default(),
582 reported_trait_errors: Default::default(),
583 reported_closure_mismatch: Default::default(),
584 tainted_by_errors_flag: Cell::new(false),
585 err_count_on_creation: tcx.sess.err_count(),
586 in_snapshot: Cell::new(false),
587 skip_leak_check: Cell::new(false),
588 universe: Cell::new(ty::UniverseIndex::ROOT),
594 impl<'tcx, T> InferOk<'tcx, T> {
595 pub fn unit(self) -> InferOk<'tcx, ()> {
596 InferOk { value: (), obligations: self.obligations }
599 /// Extracts `value`, registering any obligations into `fulfill_cx`.
600 pub fn into_value_registering_obligations(
602 infcx: &InferCtxt<'_, 'tcx>,
603 fulfill_cx: &mut dyn TraitEngine<'tcx>,
605 let InferOk { value, obligations } = self;
606 for obligation in obligations {
607 fulfill_cx.register_predicate_obligation(infcx, obligation);
613 impl<'tcx> InferOk<'tcx, ()> {
614 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
619 #[must_use = "once you start a snapshot, you should always consume it"]
620 pub struct CombinedSnapshot<'a, 'tcx> {
621 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
622 type_snapshot: type_variable::Snapshot<'tcx>,
623 const_snapshot: ut::Snapshot<ut::InPlace<ty::ConstVid<'tcx>>>,
624 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
625 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
626 region_constraints_snapshot: RegionSnapshot,
627 region_obligations_snapshot: usize,
628 universe: ty::UniverseIndex,
629 was_in_snapshot: bool,
630 was_skip_leak_check: bool,
631 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
634 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
635 pub fn is_in_snapshot(&self) -> bool {
636 self.in_snapshot.get()
639 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
640 t.fold_with(&mut self.freshener())
643 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
645 ty::Infer(ty::TyVar(vid)) => self.inner.borrow().type_variables.var_diverges(vid),
650 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
651 freshen::TypeFreshener::new(self)
654 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
655 use rustc::ty::error::UnconstrainedNumeric::Neither;
656 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
658 ty::Infer(ty::IntVar(vid)) => {
659 if self.inner.borrow_mut().int_unification_table.probe_value(vid).is_some() {
665 ty::Infer(ty::FloatVar(vid)) => {
666 if self.inner.borrow_mut().float_unification_table.probe_value(vid).is_some() {
676 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
677 let mut inner = self.inner.borrow_mut();
678 // FIXME(const_generics): should there be an equivalent function for const variables?
680 let mut vars: Vec<Ty<'_>> = inner
682 .unsolved_variables()
684 .map(|t| self.tcx.mk_ty_var(t))
687 (0..inner.int_unification_table.len())
688 .map(|i| ty::IntVid { index: i as u32 })
689 .filter(|&vid| inner.int_unification_table.probe_value(vid).is_none())
690 .map(|v| self.tcx.mk_int_var(v)),
693 (0..inner.float_unification_table.len())
694 .map(|i| ty::FloatVid { index: i as u32 })
695 .filter(|&vid| inner.float_unification_table.probe_value(vid).is_none())
696 .map(|v| self.tcx.mk_float_var(v)),
703 trace: TypeTrace<'tcx>,
704 param_env: ty::ParamEnv<'tcx>,
705 ) -> CombineFields<'a, 'tcx> {
711 obligations: PredicateObligations::new(),
715 /// Clear the "currently in a snapshot" flag, invoke the closure,
716 /// then restore the flag to its original value. This flag is a
717 /// debugging measure designed to detect cases where we start a
718 /// snapshot, create type variables, and register obligations
719 /// which may involve those type variables in the fulfillment cx,
720 /// potentially leaving "dangling type variables" behind.
721 /// In such cases, an assertion will fail when attempting to
722 /// register obligations, within a snapshot. Very useful, much
723 /// better than grovelling through megabytes of `RUSTC_LOG` output.
725 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
726 /// sometimes create a "mini-fulfilment-cx" in which we enroll
727 /// obligations. As long as this fulfillment cx is fully drained
728 /// before we return, this is not a problem, as there won't be any
729 /// escaping obligations in the main cx. In those cases, you can
730 /// use this function.
731 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
733 F: FnOnce(&Self) -> R,
735 let flag = self.in_snapshot.replace(false);
736 let result = func(self);
737 self.in_snapshot.set(flag);
741 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
742 debug!("start_snapshot()");
744 let in_snapshot = self.in_snapshot.replace(true);
746 let mut inner = self.inner.borrow_mut();
748 projection_cache_snapshot: inner.projection_cache.snapshot(),
749 type_snapshot: inner.type_variables.snapshot(),
750 const_snapshot: inner.const_unification_table.snapshot(),
751 int_snapshot: inner.int_unification_table.snapshot(),
752 float_snapshot: inner.float_unification_table.snapshot(),
753 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
754 region_obligations_snapshot: inner.region_obligations.len(),
755 universe: self.universe(),
756 was_in_snapshot: in_snapshot,
757 was_skip_leak_check: self.skip_leak_check.get(),
758 // Borrow tables "in progress" (i.e., during typeck)
759 // to ban writes from within a snapshot to them.
760 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
764 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
765 debug!("rollback_to(cause={})", cause);
766 let CombinedSnapshot {
767 projection_cache_snapshot,
772 region_constraints_snapshot,
773 region_obligations_snapshot,
780 self.in_snapshot.set(was_in_snapshot);
781 self.universe.set(universe);
782 self.skip_leak_check.set(was_skip_leak_check);
784 let mut inner = self.inner.borrow_mut();
785 inner.projection_cache.rollback_to(projection_cache_snapshot);
786 inner.type_variables.rollback_to(type_snapshot);
787 inner.const_unification_table.rollback_to(const_snapshot);
788 inner.int_unification_table.rollback_to(int_snapshot);
789 inner.float_unification_table.rollback_to(float_snapshot);
790 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
791 inner.region_obligations.truncate(region_obligations_snapshot);
794 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
795 debug!("commit_from()");
796 let CombinedSnapshot {
797 projection_cache_snapshot,
802 region_constraints_snapshot,
803 region_obligations_snapshot: _,
810 self.in_snapshot.set(was_in_snapshot);
811 self.skip_leak_check.set(was_skip_leak_check);
813 let mut inner = self.inner.borrow_mut();
814 inner.projection_cache.commit(projection_cache_snapshot);
815 inner.type_variables.commit(type_snapshot);
816 inner.const_unification_table.commit(const_snapshot);
817 inner.int_unification_table.commit(int_snapshot);
818 inner.float_unification_table.commit(float_snapshot);
819 inner.unwrap_region_constraints().commit(region_constraints_snapshot);
822 /// Executes `f` and commit the bindings.
823 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
825 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
827 debug!("commit_unconditionally()");
828 let snapshot = self.start_snapshot();
829 let r = f(&snapshot);
830 self.commit_from(snapshot);
834 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
835 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
837 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
839 debug!("commit_if_ok()");
840 let snapshot = self.start_snapshot();
841 let r = f(&snapshot);
842 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
845 self.commit_from(snapshot);
848 self.rollback_to("commit_if_ok -- error", snapshot);
854 /// Execute `f` then unroll any bindings it creates.
855 pub fn probe<R, F>(&self, f: F) -> R
857 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
860 let snapshot = self.start_snapshot();
861 let r = f(&snapshot);
862 self.rollback_to("probe", snapshot);
866 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
867 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
869 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
872 let snapshot = self.start_snapshot();
873 let skip_leak_check = should_skip || self.skip_leak_check.get();
874 self.skip_leak_check.set(skip_leak_check);
875 let r = f(&snapshot);
876 self.rollback_to("probe", snapshot);
880 /// Scan the constraints produced since `snapshot` began and returns:
882 /// - `None` -- if none of them involve "region outlives" constraints
883 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
884 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
885 pub fn region_constraints_added_in_snapshot(
887 snapshot: &CombinedSnapshot<'a, 'tcx>,
891 .unwrap_region_constraints()
892 .region_constraints_added_in_snapshot(&snapshot.region_constraints_snapshot)
895 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
896 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
899 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
901 T: at::ToTrace<'tcx>,
903 let origin = &ObligationCause::dummy();
905 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
906 // Ignore obligations, since we are unrolling
907 // everything anyway.
912 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
914 T: at::ToTrace<'tcx>,
916 let origin = &ObligationCause::dummy();
918 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
919 // Ignore obligations, since we are unrolling
920 // everything anyway.
927 origin: SubregionOrigin<'tcx>,
931 debug!("sub_regions({:?} <: {:?})", a, b);
932 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
935 /// Require that the region `r` be equal to one of the regions in
936 /// the set `regions`.
937 pub fn member_constraint(
939 opaque_type_def_id: DefId,
940 definition_span: Span,
942 region: ty::Region<'tcx>,
943 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
945 debug!("member_constraint({:?} <: {:?})", region, in_regions);
946 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
955 pub fn subtype_predicate(
957 cause: &ObligationCause<'tcx>,
958 param_env: ty::ParamEnv<'tcx>,
959 predicate: &ty::PolySubtypePredicate<'tcx>,
960 ) -> Option<InferResult<'tcx, ()>> {
961 // Subtle: it's ok to skip the binder here and resolve because
962 // `shallow_resolve` just ignores anything that is not a type
963 // variable, and because type variable's can't (at present, at
964 // least) capture any of the things bound by this binder.
966 // NOTE(nmatsakis): really, there is no *particular* reason to do this
967 // `shallow_resolve` here except as a micro-optimization.
968 // Naturally I could not resist.
969 let two_unbound_type_vars = {
970 let a = self.shallow_resolve(predicate.skip_binder().a);
971 let b = self.shallow_resolve(predicate.skip_binder().b);
972 a.is_ty_var() && b.is_ty_var()
975 if two_unbound_type_vars {
976 // Two unbound type variables? Can't make progress.
980 Some(self.commit_if_ok(|snapshot| {
981 let (ty::SubtypePredicate { a_is_expected, a, b }, placeholder_map) =
982 self.replace_bound_vars_with_placeholders(predicate);
984 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
986 self.leak_check(false, &placeholder_map, snapshot)?;
992 pub fn region_outlives_predicate(
994 cause: &traits::ObligationCause<'tcx>,
995 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
996 ) -> UnitResult<'tcx> {
997 self.commit_if_ok(|snapshot| {
998 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
999 self.replace_bound_vars_with_placeholders(predicate);
1000 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1001 RelateRegionParamBound(cause.span)
1003 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1004 self.leak_check(false, &placeholder_map, snapshot)?;
1009 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1010 self.inner.borrow_mut().type_variables.new_var(self.universe(), diverging, origin)
1013 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1014 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1017 pub fn next_ty_var_in_universe(
1019 origin: TypeVariableOrigin,
1020 universe: ty::UniverseIndex,
1022 let vid = self.inner.borrow_mut().type_variables.new_var(universe, false, origin);
1023 self.tcx.mk_ty_var(vid)
1026 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1027 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1030 pub fn next_const_var(
1033 origin: ConstVariableOrigin,
1034 ) -> &'tcx ty::Const<'tcx> {
1035 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1038 pub fn next_const_var_in_universe(
1041 origin: ConstVariableOrigin,
1042 universe: ty::UniverseIndex,
1043 ) -> &'tcx ty::Const<'tcx> {
1047 .const_unification_table
1048 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1049 self.tcx.mk_const_var(vid, ty)
1052 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1053 self.inner.borrow_mut().const_unification_table.new_key(ConstVarValue {
1055 val: ConstVariableValue::Unknown { universe: self.universe() },
1059 fn next_int_var_id(&self) -> IntVid {
1060 self.inner.borrow_mut().int_unification_table.new_key(None)
1063 pub fn next_int_var(&self) -> Ty<'tcx> {
1064 self.tcx.mk_int_var(self.next_int_var_id())
1067 fn next_float_var_id(&self) -> FloatVid {
1068 self.inner.borrow_mut().float_unification_table.new_key(None)
1071 pub fn next_float_var(&self) -> Ty<'tcx> {
1072 self.tcx.mk_float_var(self.next_float_var_id())
1075 /// Creates a fresh region variable with the next available index.
1076 /// The variable will be created in the maximum universe created
1077 /// thus far, allowing it to name any region created thus far.
1078 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1079 self.next_region_var_in_universe(origin, self.universe())
1082 /// Creates a fresh region variable with the next available index
1083 /// in the given universe; typically, you can use
1084 /// `next_region_var` and just use the maximal universe.
1085 pub fn next_region_var_in_universe(
1087 origin: RegionVariableOrigin,
1088 universe: ty::UniverseIndex,
1089 ) -> ty::Region<'tcx> {
1091 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1092 self.tcx.mk_region(ty::ReVar(region_var))
1095 /// Return the universe that the region `r` was created in. For
1096 /// most regions (e.g., `'static`, named regions from the user,
1097 /// etc) this is the root universe U0. For inference variables or
1098 /// placeholders, however, it will return the universe which which
1099 /// they are associated.
1100 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1101 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1104 /// Number of region variables created so far.
1105 pub fn num_region_vars(&self) -> usize {
1106 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1109 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1110 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1111 self.next_region_var(RegionVariableOrigin::NLL(origin))
1114 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1115 pub fn next_nll_region_var_in_universe(
1117 origin: NLLRegionVariableOrigin,
1118 universe: ty::UniverseIndex,
1119 ) -> ty::Region<'tcx> {
1120 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1123 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1125 GenericParamDefKind::Lifetime => {
1126 // Create a region inference variable for the given
1127 // region parameter definition.
1128 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1130 GenericParamDefKind::Type { .. } => {
1131 // Create a type inference variable for the given
1132 // type parameter definition. The substitutions are
1133 // for actual parameters that may be referred to by
1134 // the default of this type parameter, if it exists.
1135 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1136 // used in a path such as `Foo::<T, U>::new()` will
1137 // use an inference variable for `C` with `[T, U]`
1138 // as the substitutions for the default, `(T, U)`.
1139 let ty_var_id = self.inner.borrow_mut().type_variables.new_var(
1142 TypeVariableOrigin {
1143 kind: TypeVariableOriginKind::TypeParameterDefinition(
1151 self.tcx.mk_ty_var(ty_var_id).into()
1153 GenericParamDefKind::Const { .. } => {
1154 let origin = ConstVariableOrigin {
1155 kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1159 self.inner.borrow_mut().const_unification_table.new_key(ConstVarValue {
1161 val: ConstVariableValue::Unknown { universe: self.universe() },
1163 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1168 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1169 /// type/region parameter to a fresh inference variable.
1170 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1171 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1174 /// Returns `true` if errors have been reported since this infcx was
1175 /// created. This is sometimes used as a heuristic to skip
1176 /// reporting errors that often occur as a result of earlier
1177 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1178 /// inference variables, regionck errors).
1179 pub fn is_tainted_by_errors(&self) -> bool {
1181 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1182 tainted_by_errors_flag={})",
1183 self.tcx.sess.err_count(),
1184 self.err_count_on_creation,
1185 self.tainted_by_errors_flag.get()
1188 if self.tcx.sess.err_count() > self.err_count_on_creation {
1189 return true; // errors reported since this infcx was made
1191 self.tainted_by_errors_flag.get()
1194 /// Set the "tainted by errors" flag to true. We call this when we
1195 /// observe an error from a prior pass.
1196 pub fn set_tainted_by_errors(&self) {
1197 debug!("set_tainted_by_errors()");
1198 self.tainted_by_errors_flag.set(true)
1201 /// Process the region constraints and report any errors that
1202 /// result. After this, no more unification operations should be
1203 /// done -- or the compiler will panic -- but it is legal to use
1204 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1205 pub fn resolve_regions_and_report_errors(
1207 region_context: DefId,
1208 region_map: ®ion::ScopeTree,
1209 outlives_env: &OutlivesEnvironment<'tcx>,
1210 suppress: SuppressRegionErrors,
1213 self.is_tainted_by_errors() || self.inner.borrow().region_obligations.is_empty(),
1214 "region_obligations not empty: {:#?}",
1215 self.inner.borrow().region_obligations
1218 let region_rels = &RegionRelations::new(
1222 outlives_env.free_region_map(),
1224 let (var_infos, data) = self
1229 .expect("regions already resolved")
1230 .into_infos_and_data();
1231 let (lexical_region_resolutions, errors) =
1232 lexical_region_resolve::resolve(region_rels, var_infos, data);
1234 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1235 assert!(old_value.is_none());
1237 if !self.is_tainted_by_errors() {
1238 // As a heuristic, just skip reporting region errors
1239 // altogether if other errors have been reported while
1240 // this infcx was in use. This is totally hokey but
1241 // otherwise we have a hard time separating legit region
1242 // errors from silly ones.
1243 self.report_region_errors(region_map, &errors, suppress);
1247 /// Obtains (and clears) the current set of region
1248 /// constraints. The inference context is still usable: further
1249 /// unifications will simply add new constraints.
1251 /// This method is not meant to be used with normal lexical region
1252 /// resolution. Rather, it is used in the NLL mode as a kind of
1253 /// interim hack: basically we run normal type-check and generate
1254 /// region constraints as normal, but then we take them and
1255 /// translate them into the form that the NLL solver
1256 /// understands. See the NLL module for mode details.
1257 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1259 self.inner.borrow().region_obligations.is_empty(),
1260 "region_obligations not empty: {:#?}",
1261 self.inner.borrow().region_obligations
1264 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1267 /// Gives temporary access to the region constraint data.
1268 #[allow(non_camel_case_types)] // bug with impl trait
1269 pub fn with_region_constraints<R>(
1271 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1273 let mut inner = self.inner.borrow_mut();
1274 op(inner.unwrap_region_constraints().data())
1277 /// Takes ownership of the list of variable regions. This implies
1278 /// that all the region constraints have already been taken, and
1279 /// hence that `resolve_regions_and_report_errors` can never be
1280 /// called. This is used only during NLL processing to "hand off" ownership
1281 /// of the set of region variables into the NLL region context.
1282 pub fn take_region_var_origins(&self) -> VarInfos {
1283 let (var_infos, data) = self
1288 .expect("regions already resolved")
1289 .into_infos_and_data();
1290 assert!(data.is_empty());
1294 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1295 self.resolve_vars_if_possible(&t).to_string()
1298 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1299 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1300 format!("({})", tstrs.join(", "))
1303 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1304 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1307 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1308 /// universe index of `TyVar(vid)`.
1309 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1310 use self::type_variable::TypeVariableValue;
1312 match self.inner.borrow_mut().type_variables.probe(vid) {
1313 TypeVariableValue::Known { value } => Ok(value),
1314 TypeVariableValue::Unknown { universe } => Err(universe),
1318 /// Resolve any type variables found in `value` -- but only one
1319 /// level. So, if the variable `?X` is bound to some type
1320 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1321 /// itself be bound to a type).
1323 /// Useful when you only need to inspect the outermost level of
1324 /// the type and don't care about nested types (or perhaps you
1325 /// will be resolving them as well, e.g. in a loop).
1326 pub fn shallow_resolve<T>(&self, value: T) -> T
1328 T: TypeFoldable<'tcx>,
1330 let mut r = ShallowResolver::new(self);
1331 value.fold_with(&mut r)
1334 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1335 self.inner.borrow_mut().type_variables.root_var(var)
1338 /// Where possible, replaces type/const variables in
1339 /// `value` with their final value. Note that region variables
1340 /// are unaffected. If a type/const variable has not been unified, it
1341 /// is left as is. This is an idempotent operation that does
1342 /// not affect inference state in any way and so you can do it
1344 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1346 T: TypeFoldable<'tcx>,
1348 if !value.needs_infer() {
1349 return value.clone(); // Avoid duplicated subst-folding.
1351 let mut r = resolve::OpportunisticVarResolver::new(self);
1352 value.fold_with(&mut r)
1355 /// Returns the first unresolved variable contained in `T`. In the
1356 /// process of visiting `T`, this will resolve (where possible)
1357 /// type variables in `T`, but it never constructs the final,
1358 /// resolved type, so it's more efficient than
1359 /// `resolve_vars_if_possible()`.
1360 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1362 T: TypeFoldable<'tcx>,
1364 let mut r = resolve::UnresolvedTypeFinder::new(self);
1365 value.visit_with(&mut r);
1369 pub fn probe_const_var(
1371 vid: ty::ConstVid<'tcx>,
1372 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1373 match self.inner.borrow_mut().const_unification_table.probe_value(vid).val {
1374 ConstVariableValue::Known { value } => Ok(value),
1375 ConstVariableValue::Unknown { universe } => Err(universe),
1379 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1381 * Attempts to resolve all type/region/const variables in
1382 * `value`. Region inference must have been run already (e.g.,
1383 * by calling `resolve_regions_and_report_errors`). If some
1384 * variable was never unified, an `Err` results.
1386 * This method is idempotent, but it not typically not invoked
1387 * except during the writeback phase.
1390 resolve::fully_resolve(self, value)
1393 // [Note-Type-error-reporting]
1394 // An invariant is that anytime the expected or actual type is Error (the special
1395 // error type, meaning that an error occurred when typechecking this expression),
1396 // this is a derived error. The error cascaded from another error (that was already
1397 // reported), so it's not useful to display it to the user.
1398 // The following methods implement this logic.
1399 // They check if either the actual or expected type is Error, and don't print the error
1400 // in this case. The typechecker should only ever report type errors involving mismatched
1401 // types using one of these methods, and should not call span_err directly for such
1404 pub fn type_error_struct_with_diag<M>(
1408 actual_ty: Ty<'tcx>,
1409 ) -> DiagnosticBuilder<'tcx>
1411 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1413 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1414 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1416 // Don't report an error if actual type is `Error`.
1417 if actual_ty.references_error() {
1418 return self.tcx.sess.diagnostic().struct_dummy();
1421 mk_diag(self.ty_to_string(actual_ty))
1424 pub fn report_mismatched_types(
1426 cause: &ObligationCause<'tcx>,
1429 err: TypeError<'tcx>,
1430 ) -> DiagnosticBuilder<'tcx> {
1431 let trace = TypeTrace::types(cause, true, expected, actual);
1432 self.report_and_explain_type_error(trace, &err)
1435 pub fn replace_bound_vars_with_fresh_vars<T>(
1438 lbrct: LateBoundRegionConversionTime,
1439 value: &ty::Binder<T>,
1440 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1442 T: TypeFoldable<'tcx>,
1444 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1446 self.next_ty_var(TypeVariableOrigin {
1447 kind: TypeVariableOriginKind::MiscVariable,
1451 let fld_c = |_, ty| {
1452 self.next_const_var(
1454 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1457 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1460 /// See the [`region_constraints::verify_generic_bound`] method.
1461 pub fn verify_generic_bound(
1463 origin: SubregionOrigin<'tcx>,
1464 kind: GenericKind<'tcx>,
1465 a: ty::Region<'tcx>,
1466 bound: VerifyBound<'tcx>,
1468 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1472 .unwrap_region_constraints()
1473 .verify_generic_bound(origin, kind, a, bound);
1476 /// Obtains the latest type of the given closure; this may be a
1477 /// closure in the current function, in which case its
1478 /// `ClosureKind` may not yet be known.
1479 pub fn closure_kind(
1481 closure_def_id: DefId,
1482 closure_substs: SubstsRef<'tcx>,
1483 ) -> Option<ty::ClosureKind> {
1484 let closure_kind_ty = closure_substs.as_closure().kind_ty(closure_def_id, self.tcx);
1485 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1486 closure_kind_ty.to_opt_closure_kind()
1489 /// Obtains the signature of a closure. For closures, unlike
1490 /// `tcx.fn_sig(def_id)`, this method will work during the
1491 /// type-checking of the enclosing function and return the closure
1492 /// signature in its partially inferred state.
1493 pub fn closure_sig(&self, def_id: DefId, substs: SubstsRef<'tcx>) -> ty::PolyFnSig<'tcx> {
1494 let closure_sig_ty = substs.as_closure().sig_ty(def_id, self.tcx);
1495 let closure_sig_ty = self.shallow_resolve(closure_sig_ty);
1496 closure_sig_ty.fn_sig(self.tcx)
1499 /// Clears the selection, evaluation, and projection caches. This is useful when
1500 /// repeatedly attempting to select an `Obligation` while changing only
1501 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1502 pub fn clear_caches(&self) {
1503 self.selection_cache.clear();
1504 self.evaluation_cache.clear();
1505 self.inner.borrow_mut().projection_cache.clear();
1508 fn universe(&self) -> ty::UniverseIndex {
1512 /// Creates and return a fresh universe that extends all previous
1513 /// universes. Updates `self.universe` to that new universe.
1514 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1515 let u = self.universe.get().next_universe();
1516 self.universe.set(u);
1520 /// Resolves and evaluates a constant.
1522 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1523 /// substitutions and environment are used to resolve the constant. Alternatively if the
1524 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1525 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1526 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1527 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1530 /// This handles inferences variables within both `param_env` and `substs` by
1531 /// performing the operation on their respective canonical forms.
1532 pub fn const_eval_resolve(
1534 param_env: ty::ParamEnv<'tcx>,
1536 substs: SubstsRef<'tcx>,
1537 promoted: Option<mir::Promoted>,
1539 ) -> ConstEvalResult<'tcx> {
1540 let mut original_values = OriginalQueryValues::default();
1541 let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1543 let (param_env, substs) = canonical.value;
1544 // The return value is the evaluated value which doesn't contain any reference to inference
1545 // variables, thus we don't need to substitute back the original values.
1546 self.tcx.const_eval_resolve(param_env, def_id, substs, promoted, span)
1550 pub struct ShallowResolver<'a, 'tcx> {
1551 infcx: &'a InferCtxt<'a, 'tcx>,
1554 impl<'a, 'tcx> ShallowResolver<'a, 'tcx> {
1556 pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self {
1557 ShallowResolver { infcx }
1560 /// If `typ` is a type variable of some kind, resolve it one level
1561 /// (but do not resolve types found in the result). If `typ` is
1562 /// not a type variable, just return it unmodified.
1563 pub fn shallow_resolve(&mut self, typ: Ty<'tcx>) -> Ty<'tcx> {
1565 ty::Infer(ty::TyVar(v)) => {
1566 // Not entirely obvious: if `typ` is a type variable,
1567 // it can be resolved to an int/float variable, which
1568 // can then be recursively resolved, hence the
1569 // recursion. Note though that we prevent type
1570 // variables from unifying to other type variables
1571 // directly (though they may be embedded
1572 // structurally), and we prevent cycles in any case,
1573 // so this recursion should always be of very limited
1576 // Note: if these two lines are combined into one we get
1577 // dynamic borrow errors on `self.infcx.inner`.
1578 let known = self.infcx.inner.borrow_mut().type_variables.probe(v).known();
1579 known.map(|t| self.fold_ty(t)).unwrap_or(typ)
1582 ty::Infer(ty::IntVar(v)) => self
1586 .int_unification_table
1588 .map(|v| v.to_type(self.infcx.tcx))
1591 ty::Infer(ty::FloatVar(v)) => self
1595 .float_unification_table
1597 .map(|v| v.to_type(self.infcx.tcx))
1604 // `resolver.shallow_resolve_changed(ty)` is equivalent to
1605 // `resolver.shallow_resolve(ty) != ty`, but more efficient. It's always
1606 // inlined, despite being large, because it has only two call sites that
1607 // are extremely hot.
1609 pub fn shallow_resolve_changed(&self, infer: ty::InferTy) -> bool {
1612 use self::type_variable::TypeVariableValue;
1614 // If `inlined_probe` returns a `Known` value its `kind` never
1616 match self.infcx.inner.borrow_mut().type_variables.inlined_probe(v) {
1617 TypeVariableValue::Unknown { .. } => false,
1618 TypeVariableValue::Known { .. } => true,
1623 // If inlined_probe_value returns a value it's always a
1624 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1626 self.infcx.inner.borrow_mut().int_unification_table.inlined_probe_value(v).is_some()
1629 ty::FloatVar(v) => {
1630 // If inlined_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.infcx.inner.borrow_mut().float_unification_table.probe_value(v).is_some()
1637 _ => unreachable!(),
1642 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1643 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1647 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1648 self.shallow_resolve(ty)
1651 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1652 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1656 .const_unification_table
1667 impl<'tcx> TypeTrace<'tcx> {
1668 pub fn span(&self) -> Span {
1673 cause: &ObligationCause<'tcx>,
1674 a_is_expected: bool,
1677 ) -> TypeTrace<'tcx> {
1678 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1681 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1683 cause: ObligationCause::dummy(),
1684 values: Types(ExpectedFound { expected: tcx.types.err, found: tcx.types.err }),
1689 impl<'tcx> SubregionOrigin<'tcx> {
1690 pub fn span(&self) -> Span {
1692 Subtype(ref a) => a.span(),
1693 InfStackClosure(a) => a,
1694 InvokeClosure(a) => a,
1695 DerefPointer(a) => a,
1696 ClosureCapture(a, _) => a,
1698 RelateObjectBound(a) => a,
1699 RelateParamBound(a, _) => a,
1700 RelateRegionParamBound(a) => a,
1701 RelateDefaultParamBound(a, _) => a,
1703 ReborrowUpvar(a, _) => a,
1704 DataBorrowed(_, a) => a,
1705 ReferenceOutlivesReferent(_, a) => a,
1706 ParameterInScope(_, a) => a,
1707 ExprTypeIsNotInScope(_, a) => a,
1708 BindingTypeIsNotValidAtDecl(a) => a,
1715 SafeDestructor(a) => a,
1716 CompareImplMethodObligation { span, .. } => span,
1720 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1722 F: FnOnce() -> Self,
1725 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1726 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1729 traits::ObligationCauseCode::CompareImplMethodObligation {
1733 } => SubregionOrigin::CompareImplMethodObligation {
1745 impl RegionVariableOrigin {
1746 pub fn span(&self) -> Span {
1748 MiscVariable(a) => a,
1749 PatternRegion(a) => a,
1750 AddrOfRegion(a) => a,
1753 EarlyBoundRegion(a, ..) => a,
1754 LateBoundRegion(a, ..) => a,
1755 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1756 UpvarRegion(_, a) => a,
1757 NLL(..) => bug!("NLL variable used with `span`"),
1762 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1763 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1766 "RegionObligation(sub_region={:?}, sup_type={:?})",
1767 self.sub_region, self.sup_type