1 pub use self::freshen::TypeFreshener;
2 pub use self::LateBoundRegionConversionTime::*;
3 pub use self::RegionVariableOrigin::*;
4 pub use self::SubregionOrigin::*;
5 pub use self::ValuePairs::*;
7 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
9 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_data_structures::sync::Lrc;
13 use rustc_data_structures::undo_log::Rollback;
14 use rustc_data_structures::unify as ut;
15 use rustc_errors::DiagnosticBuilder;
17 use rustc_hir::def_id::{DefId, LocalDefId};
18 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
19 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
20 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
21 use rustc_middle::mir;
22 use rustc_middle::mir::interpret::EvalToConstValueResult;
23 use rustc_middle::traits::select;
24 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
25 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
26 use rustc_middle::ty::relate::RelateResult;
27 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
28 pub use rustc_middle::ty::IntVarValue;
29 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
30 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
31 use rustc_session::config::BorrowckMode;
32 use rustc_span::symbol::Symbol;
35 use std::cell::{Cell, Ref, RefCell};
36 use std::collections::BTreeMap;
39 use self::combine::CombineFields;
40 use self::free_regions::RegionRelations;
41 use self::lexical_region_resolve::LexicalRegionResolutions;
42 use self::outlives::env::OutlivesEnvironment;
43 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
44 use self::region_constraints::{
45 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
47 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
53 pub mod error_reporting;
60 mod lexical_region_resolve;
64 pub mod region_constraints;
67 pub mod type_variable;
70 use crate::infer::canonical::OriginalQueryValues;
71 pub use rustc_middle::infer::unify_key;
75 pub struct InferOk<'tcx, T> {
77 pub obligations: PredicateObligations<'tcx>,
79 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
81 pub type Bound<T> = Option<T>;
82 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
83 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
85 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
86 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
89 /// How we should handle region solving.
91 /// This is used so that the region values inferred by HIR region solving are
92 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
93 /// typeck will also do.
94 #[derive(Copy, Clone, Debug)]
95 pub enum RegionckMode {
96 /// The default mode: report region errors, don't erase regions.
98 /// Erase the results of region after solving.
100 /// A flag that is used to suppress region errors, when we are doing
101 /// region checks that the NLL borrow checker will also do -- it might
103 suppress_errors: bool,
107 impl Default for RegionckMode {
108 fn default() -> Self {
114 /// Indicates that the MIR borrowck will repeat these region
115 /// checks, so we should ignore errors if NLL is (unconditionally)
117 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
118 // FIXME(Centril): Once we actually remove `::Migrate` also make
119 // this always `true` and then proceed to eliminate the dead code.
120 match tcx.borrowck_mode() {
121 // If we're on Migrate mode, report AST region errors
122 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
124 // If we're on MIR, don't report AST region errors as they should be reported by NLL
125 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
130 /// This type contains all the things within `InferCtxt` that sit within a
131 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
132 /// operations are hot enough that we want only one call to `borrow_mut` per
133 /// call to `start_snapshot` and `rollback_to`.
134 pub struct InferCtxtInner<'tcx> {
135 /// Cache for projections. This cache is snapshotted along with the infcx.
137 /// Public so that `traits::project` can use it.
138 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
140 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
141 /// that might instantiate a general type variable have an order,
142 /// represented by its upper and lower bounds.
143 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
145 /// Map from const parameter variable to the kind of const it represents.
146 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
148 /// Map from integral variable to the kind of integer it represents.
149 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
151 /// Map from floating variable to the kind of float it represents.
152 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
154 /// Tracks the set of region variables and the constraints between them.
155 /// This is initially `Some(_)` but when
156 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
157 /// -- further attempts to perform unification, etc., may fail if new
158 /// region constraints would've been added.
159 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
161 /// A set of constraints that regionck must validate. Each
162 /// constraint has the form `T:'a`, meaning "some type `T` must
163 /// outlive the lifetime 'a". These constraints derive from
164 /// instantiated type parameters. So if you had a struct defined
167 /// struct Foo<T:'static> { ... }
169 /// then in some expression `let x = Foo { ... }` it will
170 /// instantiate the type parameter `T` with a fresh type `$0`. At
171 /// the same time, it will record a region obligation of
172 /// `$0:'static`. This will get checked later by regionck. (We
173 /// can't generally check these things right away because we have
174 /// to wait until types are resolved.)
176 /// These are stored in a map keyed to the id of the innermost
177 /// enclosing fn body / static initializer expression. This is
178 /// because the location where the obligation was incurred can be
179 /// relevant with respect to which sublifetime assumptions are in
180 /// place. The reason that we store under the fn-id, and not
181 /// something more fine-grained, is so that it is easier for
182 /// regionck to be sure that it has found *all* the region
183 /// obligations (otherwise, it's easy to fail to walk to a
184 /// particular node-id).
186 /// Before running `resolve_regions_and_report_errors`, the creator
187 /// of the inference context is expected to invoke
188 /// `process_region_obligations` (defined in `self::region_obligations`)
189 /// for each body-id in this map, which will process the
190 /// obligations within. This is expected to be done 'late enough'
191 /// that all type inference variables have been bound and so forth.
192 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
194 undo_log: InferCtxtUndoLogs<'tcx>,
197 impl<'tcx> InferCtxtInner<'tcx> {
198 fn new() -> InferCtxtInner<'tcx> {
200 projection_cache: Default::default(),
201 type_variable_storage: type_variable::TypeVariableStorage::new(),
202 undo_log: InferCtxtUndoLogs::default(),
203 const_unification_storage: ut::UnificationTableStorage::new(),
204 int_unification_storage: ut::UnificationTableStorage::new(),
205 float_unification_storage: ut::UnificationTableStorage::new(),
206 region_constraint_storage: Some(RegionConstraintStorage::new()),
207 region_obligations: vec![],
212 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
213 &self.region_obligations
217 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
218 self.projection_cache.with_log(&mut self.undo_log)
222 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
223 self.type_variable_storage.with_log(&mut self.undo_log)
227 fn int_unification_table(
229 ) -> ut::UnificationTable<
232 &mut ut::UnificationStorage<ty::IntVid>,
233 &mut InferCtxtUndoLogs<'tcx>,
236 self.int_unification_storage.with_log(&mut self.undo_log)
240 fn float_unification_table(
242 ) -> ut::UnificationTable<
245 &mut ut::UnificationStorage<ty::FloatVid>,
246 &mut InferCtxtUndoLogs<'tcx>,
249 self.float_unification_storage.with_log(&mut self.undo_log)
253 fn const_unification_table(
255 ) -> ut::UnificationTable<
258 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
259 &mut InferCtxtUndoLogs<'tcx>,
262 self.const_unification_storage.with_log(&mut self.undo_log)
266 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
267 self.region_constraint_storage
269 .expect("region constraints already solved")
270 .with_log(&mut self.undo_log)
274 pub struct InferCtxt<'a, 'tcx> {
275 pub tcx: TyCtxt<'tcx>,
277 /// During type-checking/inference of a body, `in_progress_typeck_results`
278 /// contains a reference to the typeck results being built up, which are
279 /// used for reading closure kinds/signatures as they are inferred,
280 /// and for error reporting logic to read arbitrary node types.
281 pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
283 pub inner: RefCell<InferCtxtInner<'tcx>>,
285 /// If set, this flag causes us to skip the 'leak check' during
286 /// higher-ranked subtyping operations. This flag is a temporary one used
287 /// to manage the removal of the leak-check: for the time being, we still run the
288 /// leak-check, but we issue warnings. This flag can only be set to true
289 /// when entering a snapshot.
290 skip_leak_check: Cell<bool>,
292 /// Once region inference is done, the values for each variable.
293 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
295 /// Caches the results of trait selection. This cache is used
296 /// for things that have to do with the parameters in scope.
297 pub selection_cache: select::SelectionCache<'tcx>,
299 /// Caches the results of trait evaluation.
300 pub evaluation_cache: select::EvaluationCache<'tcx>,
302 /// the set of predicates on which errors have been reported, to
303 /// avoid reporting the same error twice.
304 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
306 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
308 /// When an error occurs, we want to avoid reporting "derived"
309 /// errors that are due to this original failure. Normally, we
310 /// handle this with the `err_count_on_creation` count, which
311 /// basically just tracks how many errors were reported when we
312 /// started type-checking a fn and checks to see if any new errors
313 /// have been reported since then. Not great, but it works.
315 /// However, when errors originated in other passes -- notably
316 /// resolve -- this heuristic breaks down. Therefore, we have this
317 /// auxiliary flag that one can set whenever one creates a
318 /// type-error that is due to an error in a prior pass.
320 /// Don't read this flag directly, call `is_tainted_by_errors()`
321 /// and `set_tainted_by_errors()`.
322 tainted_by_errors_flag: Cell<bool>,
324 /// Track how many errors were reported when this infcx is created.
325 /// If the number of errors increases, that's also a sign (line
326 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
327 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
328 err_count_on_creation: usize,
330 /// This flag is true while there is an active snapshot.
331 in_snapshot: Cell<bool>,
333 /// What is the innermost universe we have created? Starts out as
334 /// `UniverseIndex::root()` but grows from there as we enter
335 /// universal quantifiers.
337 /// N.B., at present, we exclude the universal quantifiers on the
338 /// item we are type-checking, and just consider those names as
339 /// part of the root universe. So this would only get incremented
340 /// when we enter into a higher-ranked (`for<..>`) type or trait
342 universe: Cell<ty::UniverseIndex>,
345 /// See the `error_reporting` module for more details.
346 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
347 pub enum ValuePairs<'tcx> {
348 Types(ExpectedFound<Ty<'tcx>>),
349 Regions(ExpectedFound<ty::Region<'tcx>>),
350 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
351 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
352 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
355 /// The trace designates the path through inference that we took to
356 /// encounter an error or subtyping constraint.
358 /// See the `error_reporting` module for more details.
359 #[derive(Clone, Debug)]
360 pub struct TypeTrace<'tcx> {
361 cause: ObligationCause<'tcx>,
362 values: ValuePairs<'tcx>,
365 /// The origin of a `r1 <= r2` constraint.
367 /// See `error_reporting` module for more details
368 #[derive(Clone, Debug)]
369 pub enum SubregionOrigin<'tcx> {
370 /// Arose from a subtyping relation
371 Subtype(Box<TypeTrace<'tcx>>),
373 /// When casting `&'a T` to an `&'b Trait` object,
374 /// relating `'a` to `'b`
375 RelateObjectBound(Span),
377 /// Some type parameter was instantiated with the given type,
378 /// and that type must outlive some region.
379 RelateParamBound(Span, Ty<'tcx>),
381 /// The given region parameter was instantiated with a region
382 /// that must outlive some other region.
383 RelateRegionParamBound(Span),
385 /// Creating a pointer `b` to contents of another reference
388 /// Creating a pointer `b` to contents of an upvar
389 ReborrowUpvar(Span, ty::UpvarId),
391 /// Data with type `Ty<'tcx>` was borrowed
392 DataBorrowed(Ty<'tcx>, Span),
394 /// (&'a &'b T) where a >= b
395 ReferenceOutlivesReferent(Ty<'tcx>, Span),
397 /// Region in return type of invoked fn must enclose call
400 /// Comparing the signature and requirements of an impl method against
401 /// the containing trait.
402 CompareImplMethodObligation {
405 impl_item_def_id: DefId,
406 trait_item_def_id: DefId,
410 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
411 #[cfg(target_arch = "x86_64")]
412 static_assert_size!(SubregionOrigin<'_>, 32);
414 /// Times when we replace late-bound regions with variables:
415 #[derive(Clone, Copy, Debug)]
416 pub enum LateBoundRegionConversionTime {
417 /// when a fn is called
420 /// when two higher-ranked types are compared
423 /// when projecting an associated type
424 AssocTypeProjection(DefId),
427 /// Reasons to create a region inference variable
429 /// See `error_reporting` module for more details
430 #[derive(Copy, Clone, Debug)]
431 pub enum RegionVariableOrigin {
432 /// Region variables created for ill-categorized reasons,
433 /// mostly indicates places in need of refactoring
436 /// Regions created by a `&P` or `[...]` pattern
439 /// Regions created by `&` operator
442 /// Regions created as part of an autoref of a method receiver
443 Autoref(Span, ty::AssocItem),
445 /// Regions created as part of an automatic coercion
448 /// Region variables created as the values for early-bound regions
449 EarlyBoundRegion(Span, Symbol),
451 /// Region variables created for bound regions
452 /// in a function or method that is called
453 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
455 UpvarRegion(ty::UpvarId, Span),
457 BoundRegionInCoherence(Symbol),
459 /// This origin is used for the inference variables that we create
460 /// during NLL region processing.
461 Nll(NllRegionVariableOrigin),
464 #[derive(Copy, Clone, Debug)]
465 pub enum NllRegionVariableOrigin {
466 /// During NLL region processing, we create variables for free
467 /// regions that we encounter in the function signature and
468 /// elsewhere. This origin indices we've got one of those.
471 /// "Universal" instantiation of a higher-ranked region (e.g.,
472 /// from a `for<'a> T` binder). Meant to represent "any region".
473 Placeholder(ty::PlaceholderRegion),
475 /// The variable we create to represent `'empty(U0)`.
479 /// If this is true, then this variable was created to represent a lifetime
480 /// bound in a `for` binder. For example, it might have been created to
481 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
482 /// Such variables are created when we are trying to figure out if there
483 /// is any valid instantiation of `'a` that could fit into some scenario.
485 /// This is used to inform error reporting: in the case that we are trying to
486 /// determine whether there is any valid instantiation of a `'a` variable that meets
487 /// some constraint C, we want to blame the "source" of that `for` type,
488 /// rather than blaming the source of the constraint C.
493 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
494 #[derive(Copy, Clone, Debug)]
495 pub enum FixupError<'tcx> {
496 UnresolvedIntTy(IntVid),
497 UnresolvedFloatTy(FloatVid),
499 UnresolvedConst(ConstVid<'tcx>),
502 /// See the `region_obligations` field for more information.
504 pub struct RegionObligation<'tcx> {
505 pub sub_region: ty::Region<'tcx>,
506 pub sup_type: Ty<'tcx>,
507 pub origin: SubregionOrigin<'tcx>,
510 impl<'tcx> fmt::Display for FixupError<'tcx> {
511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512 use self::FixupError::*;
515 UnresolvedIntTy(_) => write!(
517 "cannot determine the type of this integer; \
518 add a suffix to specify the type explicitly"
520 UnresolvedFloatTy(_) => write!(
522 "cannot determine the type of this number; \
523 add a suffix to specify the type explicitly"
525 UnresolvedTy(_) => write!(f, "unconstrained type"),
526 UnresolvedConst(_) => write!(f, "unconstrained const value"),
531 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
532 /// Necessary because we can't write the following bound:
533 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
534 pub struct InferCtxtBuilder<'tcx> {
536 fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
539 pub trait TyCtxtInferExt<'tcx> {
540 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
543 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
544 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
545 InferCtxtBuilder { tcx: self, fresh_typeck_results: None }
549 impl<'tcx> InferCtxtBuilder<'tcx> {
550 /// Used only by `rustc_typeck` during body type-checking/inference,
551 /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
552 pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
553 self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
557 /// Given a canonical value `C` as a starting point, create an
558 /// inference context that contains each of the bound values
559 /// within instantiated as a fresh variable. The `f` closure is
560 /// invoked with the new infcx, along with the instantiated value
561 /// `V` and a substitution `S`. This substitution `S` maps from
562 /// the bound values in `C` to their instantiated values in `V`
563 /// (in other words, `S(C) = V`).
564 pub fn enter_with_canonical<T, R>(
567 canonical: &Canonical<'tcx, T>,
568 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
571 T: TypeFoldable<'tcx>,
575 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
576 f(infcx, value, subst)
580 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
581 let InferCtxtBuilder { tcx, ref fresh_typeck_results } = *self;
582 let in_progress_typeck_results = fresh_typeck_results.as_ref();
585 in_progress_typeck_results,
586 inner: RefCell::new(InferCtxtInner::new()),
587 lexical_region_resolutions: RefCell::new(None),
588 selection_cache: Default::default(),
589 evaluation_cache: Default::default(),
590 reported_trait_errors: Default::default(),
591 reported_closure_mismatch: Default::default(),
592 tainted_by_errors_flag: Cell::new(false),
593 err_count_on_creation: tcx.sess.err_count(),
594 in_snapshot: Cell::new(false),
595 skip_leak_check: Cell::new(false),
596 universe: Cell::new(ty::UniverseIndex::ROOT),
601 impl<'tcx, T> InferOk<'tcx, T> {
602 pub fn unit(self) -> InferOk<'tcx, ()> {
603 InferOk { value: (), obligations: self.obligations }
606 /// Extracts `value`, registering any obligations into `fulfill_cx`.
607 pub fn into_value_registering_obligations(
609 infcx: &InferCtxt<'_, 'tcx>,
610 fulfill_cx: &mut dyn TraitEngine<'tcx>,
612 let InferOk { value, obligations } = self;
613 for obligation in obligations {
614 fulfill_cx.register_predicate_obligation(infcx, obligation);
620 impl<'tcx> InferOk<'tcx, ()> {
621 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
626 #[must_use = "once you start a snapshot, you should always consume it"]
627 pub struct CombinedSnapshot<'a, 'tcx> {
628 undo_snapshot: Snapshot<'tcx>,
629 region_constraints_snapshot: RegionSnapshot,
630 universe: ty::UniverseIndex,
631 was_in_snapshot: bool,
632 _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'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_mut().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_middle::ty::error::UnconstrainedNumeric::Neither;
657 use rustc_middle::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 let mut vars: Vec<Ty<'_>> = inner
681 .unsolved_variables()
683 .map(|t| self.tcx.mk_ty_var(t))
686 (0..inner.int_unification_table().len())
687 .map(|i| ty::IntVid { index: i as u32 })
688 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
689 .map(|v| self.tcx.mk_int_var(v)),
692 (0..inner.float_unification_table().len())
693 .map(|i| ty::FloatVid { index: i as u32 })
694 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
695 .map(|v| self.tcx.mk_float_var(v)),
702 trace: TypeTrace<'tcx>,
703 param_env: ty::ParamEnv<'tcx>,
704 ) -> CombineFields<'a, 'tcx> {
710 obligations: PredicateObligations::new(),
714 /// Clear the "currently in a snapshot" flag, invoke the closure,
715 /// then restore the flag to its original value. This flag is a
716 /// debugging measure designed to detect cases where we start a
717 /// snapshot, create type variables, and register obligations
718 /// which may involve those type variables in the fulfillment cx,
719 /// potentially leaving "dangling type variables" behind.
720 /// In such cases, an assertion will fail when attempting to
721 /// register obligations, within a snapshot. Very useful, much
722 /// better than grovelling through megabytes of `RUSTC_LOG` output.
724 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
725 /// sometimes create a "mini-fulfilment-cx" in which we enroll
726 /// obligations. As long as this fulfillment cx is fully drained
727 /// before we return, this is not a problem, as there won't be any
728 /// escaping obligations in the main cx. In those cases, you can
729 /// use this function.
730 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
732 F: FnOnce(&Self) -> R,
734 let flag = self.in_snapshot.replace(false);
735 let result = func(self);
736 self.in_snapshot.set(flag);
740 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
741 debug!("start_snapshot()");
743 let in_snapshot = self.in_snapshot.replace(true);
745 let mut inner = self.inner.borrow_mut();
748 undo_snapshot: inner.undo_log.start_snapshot(),
749 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
750 universe: self.universe(),
751 was_in_snapshot: in_snapshot,
752 // Borrow typeck results "in progress" (i.e., during typeck)
753 // to ban writes from within a snapshot to them.
754 _in_progress_typeck_results: self
755 .in_progress_typeck_results
756 .map(|typeck_results| typeck_results.borrow()),
760 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
761 debug!("rollback_to(cause={})", cause);
762 let CombinedSnapshot {
764 region_constraints_snapshot,
767 _in_progress_typeck_results,
770 self.in_snapshot.set(was_in_snapshot);
771 self.universe.set(universe);
773 let mut inner = self.inner.borrow_mut();
774 inner.rollback_to(undo_snapshot);
775 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
778 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
779 debug!("commit_from()");
780 let CombinedSnapshot {
782 region_constraints_snapshot: _,
785 _in_progress_typeck_results,
788 self.in_snapshot.set(was_in_snapshot);
790 self.inner.borrow_mut().commit(undo_snapshot);
793 /// Executes `f` and commit the bindings.
794 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
796 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
798 debug!("commit_unconditionally()");
799 let snapshot = self.start_snapshot();
800 let r = f(&snapshot);
801 self.commit_from(snapshot);
805 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
806 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
808 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
810 debug!("commit_if_ok()");
811 let snapshot = self.start_snapshot();
812 let r = f(&snapshot);
813 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
816 self.commit_from(snapshot);
819 self.rollback_to("commit_if_ok -- error", snapshot);
825 /// Execute `f` then unroll any bindings it creates.
826 pub fn probe<R, F>(&self, f: F) -> R
828 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
831 let snapshot = self.start_snapshot();
832 let r = f(&snapshot);
833 self.rollback_to("probe", snapshot);
837 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
838 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
840 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
843 let snapshot = self.start_snapshot();
844 let was_skip_leak_check = self.skip_leak_check.get();
846 self.skip_leak_check.set(true);
848 let r = f(&snapshot);
849 self.rollback_to("probe", snapshot);
850 self.skip_leak_check.set(was_skip_leak_check);
854 /// Scan the constraints produced since `snapshot` began and returns:
856 /// - `None` -- if none of them involve "region outlives" constraints
857 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
858 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
859 pub fn region_constraints_added_in_snapshot(
861 snapshot: &CombinedSnapshot<'a, 'tcx>,
865 .unwrap_region_constraints()
866 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
869 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
870 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
873 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
875 T: at::ToTrace<'tcx>,
877 let origin = &ObligationCause::dummy();
879 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
880 // Ignore obligations, since we are unrolling
881 // everything anyway.
886 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
888 T: at::ToTrace<'tcx>,
890 let origin = &ObligationCause::dummy();
892 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
893 // Ignore obligations, since we are unrolling
894 // everything anyway.
901 origin: SubregionOrigin<'tcx>,
905 debug!("sub_regions({:?} <: {:?})", a, b);
906 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
909 /// Require that the region `r` be equal to one of the regions in
910 /// the set `regions`.
911 pub fn member_constraint(
913 opaque_type_def_id: DefId,
914 definition_span: Span,
916 region: ty::Region<'tcx>,
917 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
919 debug!("member_constraint({:?} <: {:?})", region, in_regions);
920 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
929 pub fn subtype_predicate(
931 cause: &ObligationCause<'tcx>,
932 param_env: ty::ParamEnv<'tcx>,
933 predicate: ty::PolySubtypePredicate<'tcx>,
934 ) -> Option<InferResult<'tcx, ()>> {
935 // Subtle: it's ok to skip the binder here and resolve because
936 // `shallow_resolve` just ignores anything that is not a type
937 // variable, and because type variable's can't (at present, at
938 // least) capture any of the things bound by this binder.
940 // NOTE(nmatsakis): really, there is no *particular* reason to do this
941 // `shallow_resolve` here except as a micro-optimization.
942 // Naturally I could not resist.
943 let two_unbound_type_vars = {
944 let a = self.shallow_resolve(predicate.skip_binder().a);
945 let b = self.shallow_resolve(predicate.skip_binder().b);
946 a.is_ty_var() && b.is_ty_var()
949 if two_unbound_type_vars {
950 // Two unbound type variables? Can't make progress.
954 Some(self.commit_if_ok(|_snapshot| {
955 let ty::SubtypePredicate { a_is_expected, a, b } =
956 self.replace_bound_vars_with_placeholders(predicate);
958 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
964 pub fn region_outlives_predicate(
966 cause: &traits::ObligationCause<'tcx>,
967 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
968 ) -> UnitResult<'tcx> {
969 self.commit_if_ok(|_snapshot| {
970 let ty::OutlivesPredicate(r_a, r_b) =
971 self.replace_bound_vars_with_placeholders(predicate);
972 let origin = SubregionOrigin::from_obligation_cause(cause, || {
973 RelateRegionParamBound(cause.span)
975 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
980 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
981 self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
984 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
985 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
988 pub fn next_ty_var_in_universe(
990 origin: TypeVariableOrigin,
991 universe: ty::UniverseIndex,
993 let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
994 self.tcx.mk_ty_var(vid)
997 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
998 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1001 pub fn next_const_var(
1004 origin: ConstVariableOrigin,
1005 ) -> &'tcx ty::Const<'tcx> {
1006 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1009 pub fn next_const_var_in_universe(
1012 origin: ConstVariableOrigin,
1013 universe: ty::UniverseIndex,
1014 ) -> &'tcx ty::Const<'tcx> {
1018 .const_unification_table()
1019 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1020 self.tcx.mk_const_var(vid, ty)
1023 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1024 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1026 val: ConstVariableValue::Unknown { universe: self.universe() },
1030 fn next_int_var_id(&self) -> IntVid {
1031 self.inner.borrow_mut().int_unification_table().new_key(None)
1034 pub fn next_int_var(&self) -> Ty<'tcx> {
1035 self.tcx.mk_int_var(self.next_int_var_id())
1038 fn next_float_var_id(&self) -> FloatVid {
1039 self.inner.borrow_mut().float_unification_table().new_key(None)
1042 pub fn next_float_var(&self) -> Ty<'tcx> {
1043 self.tcx.mk_float_var(self.next_float_var_id())
1046 /// Creates a fresh region variable with the next available index.
1047 /// The variable will be created in the maximum universe created
1048 /// thus far, allowing it to name any region created thus far.
1049 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1050 self.next_region_var_in_universe(origin, self.universe())
1053 /// Creates a fresh region variable with the next available index
1054 /// in the given universe; typically, you can use
1055 /// `next_region_var` and just use the maximal universe.
1056 pub fn next_region_var_in_universe(
1058 origin: RegionVariableOrigin,
1059 universe: ty::UniverseIndex,
1060 ) -> ty::Region<'tcx> {
1062 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1063 self.tcx.mk_region(ty::ReVar(region_var))
1066 /// Return the universe that the region `r` was created in. For
1067 /// most regions (e.g., `'static`, named regions from the user,
1068 /// etc) this is the root universe U0. For inference variables or
1069 /// placeholders, however, it will return the universe which which
1070 /// they are associated.
1071 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1072 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1075 /// Number of region variables created so far.
1076 pub fn num_region_vars(&self) -> usize {
1077 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1080 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1081 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1082 self.next_region_var(RegionVariableOrigin::Nll(origin))
1085 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1086 pub fn next_nll_region_var_in_universe(
1088 origin: NllRegionVariableOrigin,
1089 universe: ty::UniverseIndex,
1090 ) -> ty::Region<'tcx> {
1091 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1094 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1096 GenericParamDefKind::Lifetime => {
1097 // Create a region inference variable for the given
1098 // region parameter definition.
1099 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1101 GenericParamDefKind::Type { .. } => {
1102 // Create a type inference variable for the given
1103 // type parameter definition. The substitutions are
1104 // for actual parameters that may be referred to by
1105 // the default of this type parameter, if it exists.
1106 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1107 // used in a path such as `Foo::<T, U>::new()` will
1108 // use an inference variable for `C` with `[T, U]`
1109 // as the substitutions for the default, `(T, U)`.
1110 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1113 TypeVariableOrigin {
1114 kind: TypeVariableOriginKind::TypeParameterDefinition(
1122 self.tcx.mk_ty_var(ty_var_id).into()
1124 GenericParamDefKind::Const { .. } => {
1125 let origin = ConstVariableOrigin {
1126 kind: ConstVariableOriginKind::ConstParameterDefinition(
1133 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1135 val: ConstVariableValue::Unknown { universe: self.universe() },
1137 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1142 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1143 /// type/region parameter to a fresh inference variable.
1144 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1145 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1148 /// Returns `true` if errors have been reported since this infcx was
1149 /// created. This is sometimes used as a heuristic to skip
1150 /// reporting errors that often occur as a result of earlier
1151 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1152 /// inference variables, regionck errors).
1153 pub fn is_tainted_by_errors(&self) -> bool {
1155 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1156 tainted_by_errors_flag={})",
1157 self.tcx.sess.err_count(),
1158 self.err_count_on_creation,
1159 self.tainted_by_errors_flag.get()
1162 if self.tcx.sess.err_count() > self.err_count_on_creation {
1163 return true; // errors reported since this infcx was made
1165 self.tainted_by_errors_flag.get()
1168 /// Set the "tainted by errors" flag to true. We call this when we
1169 /// observe an error from a prior pass.
1170 pub fn set_tainted_by_errors(&self) {
1171 debug!("set_tainted_by_errors()");
1172 self.tainted_by_errors_flag.set(true)
1175 /// Process the region constraints and report any errors that
1176 /// result. After this, no more unification operations should be
1177 /// done -- or the compiler will panic -- but it is legal to use
1178 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1179 pub fn resolve_regions_and_report_errors(
1181 region_context: DefId,
1182 outlives_env: &OutlivesEnvironment<'tcx>,
1185 let (var_infos, data) = {
1186 let mut inner = self.inner.borrow_mut();
1187 let inner = &mut *inner;
1189 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1190 "region_obligations not empty: {:#?}",
1191 inner.region_obligations
1194 .region_constraint_storage
1196 .expect("regions already resolved")
1197 .with_log(&mut inner.undo_log)
1198 .into_infos_and_data()
1202 &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1204 let (lexical_region_resolutions, errors) =
1205 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1207 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1208 assert!(old_value.is_none());
1210 if !self.is_tainted_by_errors() {
1211 // As a heuristic, just skip reporting region errors
1212 // altogether if other errors have been reported while
1213 // this infcx was in use. This is totally hokey but
1214 // otherwise we have a hard time separating legit region
1215 // errors from silly ones.
1216 self.report_region_errors(&errors);
1220 /// Obtains (and clears) the current set of region
1221 /// constraints. The inference context is still usable: further
1222 /// unifications will simply add new constraints.
1224 /// This method is not meant to be used with normal lexical region
1225 /// resolution. Rather, it is used in the NLL mode as a kind of
1226 /// interim hack: basically we run normal type-check and generate
1227 /// region constraints as normal, but then we take them and
1228 /// translate them into the form that the NLL solver
1229 /// understands. See the NLL module for mode details.
1230 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1232 self.inner.borrow().region_obligations.is_empty(),
1233 "region_obligations not empty: {:#?}",
1234 self.inner.borrow().region_obligations
1237 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1240 /// Gives temporary access to the region constraint data.
1241 pub fn with_region_constraints<R>(
1243 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1245 let mut inner = self.inner.borrow_mut();
1246 op(inner.unwrap_region_constraints().data())
1249 /// Takes ownership of the list of variable regions. This implies
1250 /// that all the region constraints have already been taken, and
1251 /// hence that `resolve_regions_and_report_errors` can never be
1252 /// called. This is used only during NLL processing to "hand off" ownership
1253 /// of the set of region variables into the NLL region context.
1254 pub fn take_region_var_origins(&self) -> VarInfos {
1255 let mut inner = self.inner.borrow_mut();
1256 let (var_infos, data) = inner
1257 .region_constraint_storage
1259 .expect("regions already resolved")
1260 .with_log(&mut inner.undo_log)
1261 .into_infos_and_data();
1262 assert!(data.is_empty());
1266 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1267 self.resolve_vars_if_possible(t).to_string()
1270 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1271 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1272 format!("({})", tstrs.join(", "))
1275 pub fn trait_ref_to_string(&self, t: ty::TraitRef<'tcx>) -> String {
1276 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1279 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1280 /// universe index of `TyVar(vid)`.
1281 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1282 use self::type_variable::TypeVariableValue;
1284 match self.inner.borrow_mut().type_variables().probe(vid) {
1285 TypeVariableValue::Known { value } => Ok(value),
1286 TypeVariableValue::Unknown { universe } => Err(universe),
1290 /// Resolve any type variables found in `value` -- but only one
1291 /// level. So, if the variable `?X` is bound to some type
1292 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1293 /// itself be bound to a type).
1295 /// Useful when you only need to inspect the outermost level of
1296 /// the type and don't care about nested types (or perhaps you
1297 /// will be resolving them as well, e.g. in a loop).
1298 pub fn shallow_resolve<T>(&self, value: T) -> T
1300 T: TypeFoldable<'tcx>,
1302 value.fold_with(&mut ShallowResolver { infcx: self })
1305 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1306 self.inner.borrow_mut().type_variables().root_var(var)
1309 /// Where possible, replaces type/const variables in
1310 /// `value` with their final value. Note that region variables
1311 /// are unaffected. If a type/const variable has not been unified, it
1312 /// is left as is. This is an idempotent operation that does
1313 /// not affect inference state in any way and so you can do it
1315 pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1317 T: TypeFoldable<'tcx>,
1319 if !value.needs_infer() {
1320 return value; // Avoid duplicated subst-folding.
1322 let mut r = resolve::OpportunisticVarResolver::new(self);
1323 value.fold_with(&mut r)
1326 /// Returns the first unresolved variable contained in `T`. In the
1327 /// process of visiting `T`, this will resolve (where possible)
1328 /// type variables in `T`, but it never constructs the final,
1329 /// resolved type, so it's more efficient than
1330 /// `resolve_vars_if_possible()`.
1331 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1333 T: TypeFoldable<'tcx>,
1335 value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1338 pub fn probe_const_var(
1340 vid: ty::ConstVid<'tcx>,
1341 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1342 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1343 ConstVariableValue::Known { value } => Ok(value),
1344 ConstVariableValue::Unknown { universe } => Err(universe),
1348 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1350 * Attempts to resolve all type/region/const variables in
1351 * `value`. Region inference must have been run already (e.g.,
1352 * by calling `resolve_regions_and_report_errors`). If some
1353 * variable was never unified, an `Err` results.
1355 * This method is idempotent, but it not typically not invoked
1356 * except during the writeback phase.
1359 resolve::fully_resolve(self, value)
1362 // [Note-Type-error-reporting]
1363 // An invariant is that anytime the expected or actual type is Error (the special
1364 // error type, meaning that an error occurred when typechecking this expression),
1365 // this is a derived error. The error cascaded from another error (that was already
1366 // reported), so it's not useful to display it to the user.
1367 // The following methods implement this logic.
1368 // They check if either the actual or expected type is Error, and don't print the error
1369 // in this case. The typechecker should only ever report type errors involving mismatched
1370 // types using one of these methods, and should not call span_err directly for such
1373 pub fn type_error_struct_with_diag<M>(
1377 actual_ty: Ty<'tcx>,
1378 ) -> DiagnosticBuilder<'tcx>
1380 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1382 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1383 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1385 // Don't report an error if actual type is `Error`.
1386 if actual_ty.references_error() {
1387 return self.tcx.sess.diagnostic().struct_dummy();
1390 mk_diag(self.ty_to_string(actual_ty))
1393 pub fn report_mismatched_types(
1395 cause: &ObligationCause<'tcx>,
1398 err: TypeError<'tcx>,
1399 ) -> DiagnosticBuilder<'tcx> {
1400 let trace = TypeTrace::types(cause, true, expected, actual);
1401 self.report_and_explain_type_error(trace, &err)
1404 pub fn report_mismatched_consts(
1406 cause: &ObligationCause<'tcx>,
1407 expected: &'tcx ty::Const<'tcx>,
1408 actual: &'tcx ty::Const<'tcx>,
1409 err: TypeError<'tcx>,
1410 ) -> DiagnosticBuilder<'tcx> {
1411 let trace = TypeTrace::consts(cause, true, expected, actual);
1412 self.report_and_explain_type_error(trace, &err)
1415 pub fn replace_bound_vars_with_fresh_vars<T>(
1418 lbrct: LateBoundRegionConversionTime,
1419 value: ty::Binder<T>,
1420 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1422 T: TypeFoldable<'tcx>,
1425 |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct));
1427 self.next_ty_var(TypeVariableOrigin {
1428 kind: TypeVariableOriginKind::MiscVariable,
1432 let fld_c = |_, ty| {
1433 self.next_const_var(
1435 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1438 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1441 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1442 pub fn verify_generic_bound(
1444 origin: SubregionOrigin<'tcx>,
1445 kind: GenericKind<'tcx>,
1446 a: ty::Region<'tcx>,
1447 bound: VerifyBound<'tcx>,
1449 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1453 .unwrap_region_constraints()
1454 .verify_generic_bound(origin, kind, a, bound);
1457 /// Obtains the latest type of the given closure; this may be a
1458 /// closure in the current function, in which case its
1459 /// `ClosureKind` may not yet be known.
1460 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1461 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1462 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1463 closure_kind_ty.to_opt_closure_kind()
1466 /// Clears the selection, evaluation, and projection caches. This is useful when
1467 /// repeatedly attempting to select an `Obligation` while changing only
1468 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1469 pub fn clear_caches(&self) {
1470 self.selection_cache.clear();
1471 self.evaluation_cache.clear();
1472 self.inner.borrow_mut().projection_cache().clear();
1475 fn universe(&self) -> ty::UniverseIndex {
1479 /// Creates and return a fresh universe that extends all previous
1480 /// universes. Updates `self.universe` to that new universe.
1481 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1482 let u = self.universe.get().next_universe();
1483 self.universe.set(u);
1487 /// Resolves and evaluates a constant.
1489 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1490 /// substitutions and environment are used to resolve the constant. Alternatively if the
1491 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1492 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1493 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1494 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1497 /// This handles inferences variables within both `param_env` and `substs` by
1498 /// performing the operation on their respective canonical forms.
1499 pub fn const_eval_resolve(
1501 param_env: ty::ParamEnv<'tcx>,
1502 def: ty::WithOptConstParam<DefId>,
1503 substs: SubstsRef<'tcx>,
1504 promoted: Option<mir::Promoted>,
1506 ) -> EvalToConstValueResult<'tcx> {
1507 let mut original_values = OriginalQueryValues::default();
1508 let canonical = self.canonicalize_query((param_env, substs), &mut original_values);
1510 let (param_env, substs) = canonical.value;
1511 // The return value is the evaluated value which doesn't contain any reference to inference
1512 // variables, thus we don't need to substitute back the original values.
1513 self.tcx.const_eval_resolve(param_env, def, substs, promoted, span)
1516 /// If `typ` is a type variable of some kind, resolve it one level
1517 /// (but do not resolve types found in the result). If `typ` is
1518 /// not a type variable, just return it unmodified.
1519 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1520 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1522 ty::Infer(ty::TyVar(v)) => {
1523 // Not entirely obvious: if `typ` is a type variable,
1524 // it can be resolved to an int/float variable, which
1525 // can then be recursively resolved, hence the
1526 // recursion. Note though that we prevent type
1527 // variables from unifying to other type variables
1528 // directly (though they may be embedded
1529 // structurally), and we prevent cycles in any case,
1530 // so this recursion should always be of very limited
1533 // Note: if these two lines are combined into one we get
1534 // dynamic borrow errors on `self.inner`.
1535 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1536 known.map_or(typ, |t| self.shallow_resolve_ty(t))
1539 ty::Infer(ty::IntVar(v)) => self
1542 .int_unification_table()
1544 .map(|v| v.to_type(self.tcx))
1547 ty::Infer(ty::FloatVar(v)) => self
1550 .float_unification_table()
1552 .map(|v| v.to_type(self.tcx))
1559 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1560 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1561 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1563 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1564 /// inlined, despite being large, because it has only two call sites that
1565 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1566 /// inference variables), and it handles both `Ty` and `ty::Const` without
1567 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1569 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1571 TyOrConstInferVar::Ty(v) => {
1572 use self::type_variable::TypeVariableValue;
1574 // If `inlined_probe` returns a `Known` value, it never equals
1575 // `ty::Infer(ty::TyVar(v))`.
1576 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1577 TypeVariableValue::Unknown { .. } => false,
1578 TypeVariableValue::Known { .. } => true,
1582 TyOrConstInferVar::TyInt(v) => {
1583 // If `inlined_probe_value` returns a value it's always a
1584 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1586 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1589 TyOrConstInferVar::TyFloat(v) => {
1590 // If `probe_value` returns a value it's always a
1591 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1593 // Not `inlined_probe_value(v)` because this call site is colder.
1594 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1597 TyOrConstInferVar::Const(v) => {
1598 // If `probe_value` returns a `Known` value, it never equals
1599 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1601 // Not `inlined_probe_value(v)` because this call site is colder.
1602 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1603 ConstVariableValue::Unknown { .. } => false,
1604 ConstVariableValue::Known { .. } => true,
1611 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1612 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1613 #[derive(Copy, Clone, Debug)]
1614 pub enum TyOrConstInferVar<'tcx> {
1615 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1617 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1619 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1622 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1623 Const(ConstVid<'tcx>),
1626 impl TyOrConstInferVar<'tcx> {
1627 /// Tries to extract an inference variable from a type or a constant, returns `None`
1628 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1629 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1630 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1631 match arg.unpack() {
1632 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1633 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1634 GenericArgKind::Lifetime(_) => None,
1638 /// Tries to extract an inference variable from a type, returns `None`
1639 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1640 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1642 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1643 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1644 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1649 /// Tries to extract an inference variable from a constant, returns `None`
1650 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1651 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1653 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1659 struct ShallowResolver<'a, 'tcx> {
1660 infcx: &'a InferCtxt<'a, 'tcx>,
1663 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1664 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1668 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1669 self.infcx.shallow_resolve_ty(ty)
1672 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1673 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1677 .const_unification_table()
1688 impl<'tcx> TypeTrace<'tcx> {
1689 pub fn span(&self) -> Span {
1694 cause: &ObligationCause<'tcx>,
1695 a_is_expected: bool,
1698 ) -> TypeTrace<'tcx> {
1699 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1703 cause: &ObligationCause<'tcx>,
1704 a_is_expected: bool,
1705 a: &'tcx ty::Const<'tcx>,
1706 b: &'tcx ty::Const<'tcx>,
1707 ) -> TypeTrace<'tcx> {
1708 TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
1711 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1712 let err = tcx.ty_error();
1714 cause: ObligationCause::dummy(),
1715 values: Types(ExpectedFound { expected: err, found: err }),
1720 impl<'tcx> SubregionOrigin<'tcx> {
1721 pub fn span(&self) -> Span {
1723 Subtype(ref a) => a.span(),
1724 RelateObjectBound(a) => a,
1725 RelateParamBound(a, _) => a,
1726 RelateRegionParamBound(a) => a,
1728 ReborrowUpvar(a, _) => a,
1729 DataBorrowed(_, a) => a,
1730 ReferenceOutlivesReferent(_, a) => a,
1732 CompareImplMethodObligation { span, .. } => span,
1736 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1738 F: FnOnce() -> Self,
1741 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1742 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1745 traits::ObligationCauseCode::CompareImplMethodObligation {
1749 } => SubregionOrigin::CompareImplMethodObligation {
1761 impl RegionVariableOrigin {
1762 pub fn span(&self) -> Span {
1769 | EarlyBoundRegion(a, ..)
1770 | LateBoundRegion(a, ..)
1771 | UpvarRegion(_, a) => a,
1772 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1773 Nll(..) => bug!("NLL variable used with `span`"),
1778 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1779 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1782 "RegionObligation(sub_region={:?}, sup_type={:?})",
1783 self.sub_region, self.sup_type