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 use self::opaque_types::OpaqueTypeMap;
8 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
10 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
12 use hir::def_id::CRATE_DEF_ID;
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_data_structures::sync::Lrc;
15 use rustc_data_structures::undo_log::Rollback;
16 use rustc_data_structures::unify as ut;
17 use rustc_errors::DiagnosticBuilder;
19 use rustc_hir::def_id::{DefId, LocalDefId};
20 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
21 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
22 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
23 use rustc_middle::mir::interpret::EvalToConstValueResult;
24 use rustc_middle::traits::select;
25 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
26 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
27 use rustc_middle::ty::relate::RelateResult;
28 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
29 pub use rustc_middle::ty::IntVarValue;
30 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
31 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
32 use rustc_session::config::BorrowckMode;
33 use rustc_span::symbol::Symbol;
36 use std::cell::{Cell, Ref, RefCell};
37 use std::collections::BTreeMap;
40 use self::combine::CombineFields;
41 use self::free_regions::RegionRelations;
42 use self::lexical_region_resolve::LexicalRegionResolutions;
43 use self::outlives::env::OutlivesEnvironment;
44 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
45 use self::region_constraints::{
46 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
48 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
54 pub mod error_reporting;
61 mod lexical_region_resolve;
66 pub mod region_constraints;
69 pub mod type_variable;
72 use crate::infer::canonical::OriginalQueryValues;
73 pub use rustc_middle::infer::unify_key;
77 pub struct InferOk<'tcx, T> {
79 pub obligations: PredicateObligations<'tcx>,
81 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
83 pub type Bound<T> = Option<T>;
84 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
85 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
87 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
88 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
91 /// How we should handle region solving.
93 /// This is used so that the region values inferred by HIR region solving are
94 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
95 /// typeck will also do.
96 #[derive(Copy, Clone, Debug)]
97 pub enum RegionckMode {
98 /// The default mode: report region errors, don't erase regions.
100 /// Erase the results of region after solving.
102 /// A flag that is used to suppress region errors, when we are doing
103 /// region checks that the NLL borrow checker will also do -- it might
105 suppress_errors: bool,
109 impl Default for RegionckMode {
110 fn default() -> Self {
116 /// Indicates that the MIR borrowck will repeat these region
117 /// checks, so we should ignore errors if NLL is (unconditionally)
119 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
120 // FIXME(Centril): Once we actually remove `::Migrate` also make
121 // this always `true` and then proceed to eliminate the dead code.
122 match tcx.borrowck_mode() {
123 // If we're on Migrate mode, report AST region errors
124 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
126 // If we're on MIR, don't report AST region errors as they should be reported by NLL
127 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
132 /// This type contains all the things within `InferCtxt` that sit within a
133 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
134 /// operations are hot enough that we want only one call to `borrow_mut` per
135 /// call to `start_snapshot` and `rollback_to`.
136 pub struct InferCtxtInner<'tcx> {
137 /// Cache for projections. This cache is snapshotted along with the infcx.
139 /// Public so that `traits::project` can use it.
140 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
142 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
143 /// that might instantiate a general type variable have an order,
144 /// represented by its upper and lower bounds.
145 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
147 /// Map from const parameter variable to the kind of const it represents.
148 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
150 /// Map from integral variable to the kind of integer it represents.
151 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
153 /// Map from floating variable to the kind of float it represents.
154 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
156 /// Tracks the set of region variables and the constraints between them.
157 /// This is initially `Some(_)` but when
158 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
159 /// -- further attempts to perform unification, etc., may fail if new
160 /// region constraints would've been added.
161 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
163 /// A set of constraints that regionck must validate. Each
164 /// constraint has the form `T:'a`, meaning "some type `T` must
165 /// outlive the lifetime 'a". These constraints derive from
166 /// instantiated type parameters. So if you had a struct defined
169 /// struct Foo<T:'static> { ... }
171 /// then in some expression `let x = Foo { ... }` it will
172 /// instantiate the type parameter `T` with a fresh type `$0`. At
173 /// the same time, it will record a region obligation of
174 /// `$0:'static`. This will get checked later by regionck. (We
175 /// can't generally check these things right away because we have
176 /// to wait until types are resolved.)
178 /// These are stored in a map keyed to the id of the innermost
179 /// enclosing fn body / static initializer expression. This is
180 /// because the location where the obligation was incurred can be
181 /// relevant with respect to which sublifetime assumptions are in
182 /// place. The reason that we store under the fn-id, and not
183 /// something more fine-grained, is so that it is easier for
184 /// regionck to be sure that it has found *all* the region
185 /// obligations (otherwise, it's easy to fail to walk to a
186 /// particular node-id).
188 /// Before running `resolve_regions_and_report_errors`, the creator
189 /// of the inference context is expected to invoke
190 /// `process_region_obligations` (defined in `self::region_obligations`)
191 /// for each body-id in this map, which will process the
192 /// obligations within. This is expected to be done 'late enough'
193 /// that all type inference variables have been bound and so forth.
194 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
196 undo_log: InferCtxtUndoLogs<'tcx>,
198 // Opaque types found in explicit return types and their
199 // associated fresh inference variable. Writeback resolves these
200 // variables to get the concrete type, which can be used to
201 // 'de-opaque' OpaqueTypeDecl, after typeck is done with all functions.
202 pub opaque_types: OpaqueTypeMap<'tcx>,
204 /// A map from inference variables created from opaque
205 /// type instantiations (`ty::Infer`) to the actual opaque
206 /// type (`ty::Opaque`). Used during fallback to map unconstrained
207 /// opaque type inference variables to their corresponding
209 pub opaque_types_vars: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
212 impl<'tcx> InferCtxtInner<'tcx> {
213 fn new() -> InferCtxtInner<'tcx> {
215 projection_cache: Default::default(),
216 type_variable_storage: type_variable::TypeVariableStorage::new(),
217 undo_log: InferCtxtUndoLogs::default(),
218 const_unification_storage: ut::UnificationTableStorage::new(),
219 int_unification_storage: ut::UnificationTableStorage::new(),
220 float_unification_storage: ut::UnificationTableStorage::new(),
221 region_constraint_storage: Some(RegionConstraintStorage::new()),
222 region_obligations: vec![],
223 opaque_types: Default::default(),
224 opaque_types_vars: Default::default(),
229 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
230 &self.region_obligations
234 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
235 self.projection_cache.with_log(&mut self.undo_log)
239 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
240 self.type_variable_storage.with_log(&mut self.undo_log)
244 fn int_unification_table(
246 ) -> ut::UnificationTable<
249 &mut ut::UnificationStorage<ty::IntVid>,
250 &mut InferCtxtUndoLogs<'tcx>,
253 self.int_unification_storage.with_log(&mut self.undo_log)
257 fn float_unification_table(
259 ) -> ut::UnificationTable<
262 &mut ut::UnificationStorage<ty::FloatVid>,
263 &mut InferCtxtUndoLogs<'tcx>,
266 self.float_unification_storage.with_log(&mut self.undo_log)
270 fn const_unification_table(
272 ) -> ut::UnificationTable<
275 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
276 &mut InferCtxtUndoLogs<'tcx>,
279 self.const_unification_storage.with_log(&mut self.undo_log)
283 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
284 self.region_constraint_storage
286 .expect("region constraints already solved")
287 .with_log(&mut self.undo_log)
291 pub struct InferCtxt<'a, 'tcx> {
292 pub tcx: TyCtxt<'tcx>,
294 /// The `DefId` of the item in whose context we are performing inference or typeck.
295 /// It is used to check whether an opaque type use is a defining use.
296 pub defining_use_anchor: LocalDefId,
298 /// During type-checking/inference of a body, `in_progress_typeck_results`
299 /// contains a reference to the typeck results being built up, which are
300 /// used for reading closure kinds/signatures as they are inferred,
301 /// and for error reporting logic to read arbitrary node types.
302 pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
304 pub inner: RefCell<InferCtxtInner<'tcx>>,
306 /// If set, this flag causes us to skip the 'leak check' during
307 /// higher-ranked subtyping operations. This flag is a temporary one used
308 /// to manage the removal of the leak-check: for the time being, we still run the
309 /// leak-check, but we issue warnings. This flag can only be set to true
310 /// when entering a snapshot.
311 skip_leak_check: Cell<bool>,
313 /// Once region inference is done, the values for each variable.
314 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
316 /// Caches the results of trait selection. This cache is used
317 /// for things that have to do with the parameters in scope.
318 pub selection_cache: select::SelectionCache<'tcx>,
320 /// Caches the results of trait evaluation.
321 pub evaluation_cache: select::EvaluationCache<'tcx>,
323 /// the set of predicates on which errors have been reported, to
324 /// avoid reporting the same error twice.
325 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
327 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
329 /// When an error occurs, we want to avoid reporting "derived"
330 /// errors that are due to this original failure. Normally, we
331 /// handle this with the `err_count_on_creation` count, which
332 /// basically just tracks how many errors were reported when we
333 /// started type-checking a fn and checks to see if any new errors
334 /// have been reported since then. Not great, but it works.
336 /// However, when errors originated in other passes -- notably
337 /// resolve -- this heuristic breaks down. Therefore, we have this
338 /// auxiliary flag that one can set whenever one creates a
339 /// type-error that is due to an error in a prior pass.
341 /// Don't read this flag directly, call `is_tainted_by_errors()`
342 /// and `set_tainted_by_errors()`.
343 tainted_by_errors_flag: Cell<bool>,
345 /// Track how many errors were reported when this infcx is created.
346 /// If the number of errors increases, that's also a sign (line
347 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
348 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
349 err_count_on_creation: usize,
351 /// This flag is true while there is an active snapshot.
352 in_snapshot: Cell<bool>,
354 /// What is the innermost universe we have created? Starts out as
355 /// `UniverseIndex::root()` but grows from there as we enter
356 /// universal quantifiers.
358 /// N.B., at present, we exclude the universal quantifiers on the
359 /// item we are type-checking, and just consider those names as
360 /// part of the root universe. So this would only get incremented
361 /// when we enter into a higher-ranked (`for<..>`) type or trait
363 universe: Cell<ty::UniverseIndex>,
366 /// See the `error_reporting` module for more details.
367 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
368 pub enum ValuePairs<'tcx> {
369 Types(ExpectedFound<Ty<'tcx>>),
370 Regions(ExpectedFound<ty::Region<'tcx>>),
371 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
372 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
373 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
376 /// The trace designates the path through inference that we took to
377 /// encounter an error or subtyping constraint.
379 /// See the `error_reporting` module for more details.
380 #[derive(Clone, Debug)]
381 pub struct TypeTrace<'tcx> {
382 cause: ObligationCause<'tcx>,
383 values: ValuePairs<'tcx>,
386 /// The origin of a `r1 <= r2` constraint.
388 /// See `error_reporting` module for more details
389 #[derive(Clone, Debug)]
390 pub enum SubregionOrigin<'tcx> {
391 /// Arose from a subtyping relation
392 Subtype(Box<TypeTrace<'tcx>>),
394 /// When casting `&'a T` to an `&'b Trait` object,
395 /// relating `'a` to `'b`
396 RelateObjectBound(Span),
398 /// Some type parameter was instantiated with the given type,
399 /// and that type must outlive some region.
400 RelateParamBound(Span, Ty<'tcx>, Option<Span>),
402 /// The given region parameter was instantiated with a region
403 /// that must outlive some other region.
404 RelateRegionParamBound(Span),
406 /// Creating a pointer `b` to contents of another reference
409 /// Creating a pointer `b` to contents of an upvar
410 ReborrowUpvar(Span, ty::UpvarId),
412 /// Data with type `Ty<'tcx>` was borrowed
413 DataBorrowed(Ty<'tcx>, Span),
415 /// (&'a &'b T) where a >= b
416 ReferenceOutlivesReferent(Ty<'tcx>, Span),
418 /// Region in return type of invoked fn must enclose call
421 /// Comparing the signature and requirements of an impl method against
422 /// the containing trait.
423 CompareImplMethodObligation {
426 impl_item_def_id: DefId,
427 trait_item_def_id: DefId,
431 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
432 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
433 static_assert_size!(SubregionOrigin<'_>, 32);
435 /// Times when we replace late-bound regions with variables:
436 #[derive(Clone, Copy, Debug)]
437 pub enum LateBoundRegionConversionTime {
438 /// when a fn is called
441 /// when two higher-ranked types are compared
444 /// when projecting an associated type
445 AssocTypeProjection(DefId),
448 /// Reasons to create a region inference variable
450 /// See `error_reporting` module for more details
451 #[derive(Copy, Clone, Debug)]
452 pub enum RegionVariableOrigin {
453 /// Region variables created for ill-categorized reasons,
454 /// mostly indicates places in need of refactoring
457 /// Regions created by a `&P` or `[...]` pattern
460 /// Regions created by `&` operator
463 /// Regions created as part of an autoref of a method receiver
464 Autoref(Span, ty::AssocItem),
466 /// Regions created as part of an automatic coercion
469 /// Region variables created as the values for early-bound regions
470 EarlyBoundRegion(Span, Symbol),
472 /// Region variables created for bound regions
473 /// in a function or method that is called
474 LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
476 UpvarRegion(ty::UpvarId, Span),
478 /// This origin is used for the inference variables that we create
479 /// during NLL region processing.
480 Nll(NllRegionVariableOrigin),
483 #[derive(Copy, Clone, Debug)]
484 pub enum NllRegionVariableOrigin {
485 /// During NLL region processing, we create variables for free
486 /// regions that we encounter in the function signature and
487 /// elsewhere. This origin indices we've got one of those.
490 /// "Universal" instantiation of a higher-ranked region (e.g.,
491 /// from a `for<'a> T` binder). Meant to represent "any region".
492 Placeholder(ty::PlaceholderRegion),
494 /// The variable we create to represent `'empty(U0)`.
498 /// If this is true, then this variable was created to represent a lifetime
499 /// bound in a `for` binder. For example, it might have been created to
500 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
501 /// Such variables are created when we are trying to figure out if there
502 /// is any valid instantiation of `'a` that could fit into some scenario.
504 /// This is used to inform error reporting: in the case that we are trying to
505 /// determine whether there is any valid instantiation of a `'a` variable that meets
506 /// some constraint C, we want to blame the "source" of that `for` type,
507 /// rather than blaming the source of the constraint C.
512 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
513 #[derive(Copy, Clone, Debug)]
514 pub enum FixupError<'tcx> {
515 UnresolvedIntTy(IntVid),
516 UnresolvedFloatTy(FloatVid),
518 UnresolvedConst(ConstVid<'tcx>),
521 /// See the `region_obligations` field for more information.
523 pub struct RegionObligation<'tcx> {
524 pub sub_region: ty::Region<'tcx>,
525 pub sup_type: Ty<'tcx>,
526 pub origin: SubregionOrigin<'tcx>,
529 impl<'tcx> fmt::Display for FixupError<'tcx> {
530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
531 use self::FixupError::*;
534 UnresolvedIntTy(_) => write!(
536 "cannot determine the type of this integer; \
537 add a suffix to specify the type explicitly"
539 UnresolvedFloatTy(_) => write!(
541 "cannot determine the type of this number; \
542 add a suffix to specify the type explicitly"
544 UnresolvedTy(_) => write!(f, "unconstrained type"),
545 UnresolvedConst(_) => write!(f, "unconstrained const value"),
550 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
551 /// Necessary because we can't write the following bound:
552 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
553 pub struct InferCtxtBuilder<'tcx> {
555 fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
556 defining_use_anchor: LocalDefId,
559 pub trait TyCtxtInferExt<'tcx> {
560 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
563 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
564 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
567 defining_use_anchor: CRATE_DEF_ID,
568 fresh_typeck_results: None,
573 impl<'tcx> InferCtxtBuilder<'tcx> {
574 /// Used only by `rustc_typeck` during body type-checking/inference,
575 /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
576 /// Will also change the scope for opaque type defining use checks to the given owner.
577 pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
578 self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
579 self.with_opaque_type_inference(table_owner)
582 /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types,
583 /// you need to call this function. Otherwise the opaque type will be treated opaquely.
584 pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self {
585 self.defining_use_anchor = defining_use_anchor;
589 /// Given a canonical value `C` as a starting point, create an
590 /// inference context that contains each of the bound values
591 /// within instantiated as a fresh variable. The `f` closure is
592 /// invoked with the new infcx, along with the instantiated value
593 /// `V` and a substitution `S`. This substitution `S` maps from
594 /// the bound values in `C` to their instantiated values in `V`
595 /// (in other words, `S(C) = V`).
596 pub fn enter_with_canonical<T, R>(
599 canonical: &Canonical<'tcx, T>,
600 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
603 T: TypeFoldable<'tcx>,
607 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
608 f(infcx, value, subst)
612 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
613 let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self;
614 let in_progress_typeck_results = fresh_typeck_results.as_ref();
618 in_progress_typeck_results,
619 inner: RefCell::new(InferCtxtInner::new()),
620 lexical_region_resolutions: RefCell::new(None),
621 selection_cache: Default::default(),
622 evaluation_cache: Default::default(),
623 reported_trait_errors: Default::default(),
624 reported_closure_mismatch: Default::default(),
625 tainted_by_errors_flag: Cell::new(false),
626 err_count_on_creation: tcx.sess.err_count(),
627 in_snapshot: Cell::new(false),
628 skip_leak_check: Cell::new(false),
629 universe: Cell::new(ty::UniverseIndex::ROOT),
634 impl<'tcx, T> InferOk<'tcx, T> {
635 pub fn unit(self) -> InferOk<'tcx, ()> {
636 InferOk { value: (), obligations: self.obligations }
639 /// Extracts `value`, registering any obligations into `fulfill_cx`.
640 pub fn into_value_registering_obligations(
642 infcx: &InferCtxt<'_, 'tcx>,
643 fulfill_cx: &mut dyn TraitEngine<'tcx>,
645 let InferOk { value, obligations } = self;
646 for obligation in obligations {
647 fulfill_cx.register_predicate_obligation(infcx, obligation);
653 impl<'tcx> InferOk<'tcx, ()> {
654 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
659 #[must_use = "once you start a snapshot, you should always consume it"]
660 pub struct CombinedSnapshot<'a, 'tcx> {
661 undo_snapshot: Snapshot<'tcx>,
662 region_constraints_snapshot: RegionSnapshot,
663 universe: ty::UniverseIndex,
664 was_in_snapshot: bool,
665 _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
668 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
669 pub fn is_in_snapshot(&self) -> bool {
670 self.in_snapshot.get()
673 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
674 t.fold_with(&mut self.freshener())
677 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
679 ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
684 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
685 freshen::TypeFreshener::new(self, false)
688 /// Like `freshener`, but does not replace `'static` regions.
689 pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
690 freshen::TypeFreshener::new(self, true)
693 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
694 use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
695 use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
697 ty::Infer(ty::IntVar(vid)) => {
698 if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
704 ty::Infer(ty::FloatVar(vid)) => {
705 if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
715 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
716 let mut inner = self.inner.borrow_mut();
717 let mut vars: Vec<Ty<'_>> = inner
719 .unsolved_variables()
721 .map(|t| self.tcx.mk_ty_var(t))
724 (0..inner.int_unification_table().len())
725 .map(|i| ty::IntVid { index: i as u32 })
726 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
727 .map(|v| self.tcx.mk_int_var(v)),
730 (0..inner.float_unification_table().len())
731 .map(|i| ty::FloatVid { index: i as u32 })
732 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
733 .map(|v| self.tcx.mk_float_var(v)),
740 trace: TypeTrace<'tcx>,
741 param_env: ty::ParamEnv<'tcx>,
742 ) -> CombineFields<'a, 'tcx> {
748 obligations: PredicateObligations::new(),
752 /// Clear the "currently in a snapshot" flag, invoke the closure,
753 /// then restore the flag to its original value. This flag is a
754 /// debugging measure designed to detect cases where we start a
755 /// snapshot, create type variables, and register obligations
756 /// which may involve those type variables in the fulfillment cx,
757 /// potentially leaving "dangling type variables" behind.
758 /// In such cases, an assertion will fail when attempting to
759 /// register obligations, within a snapshot. Very useful, much
760 /// better than grovelling through megabytes of `RUSTC_LOG` output.
762 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
763 /// sometimes create a "mini-fulfilment-cx" in which we enroll
764 /// obligations. As long as this fulfillment cx is fully drained
765 /// before we return, this is not a problem, as there won't be any
766 /// escaping obligations in the main cx. In those cases, you can
767 /// use this function.
768 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
770 F: FnOnce(&Self) -> R,
772 let flag = self.in_snapshot.replace(false);
773 let result = func(self);
774 self.in_snapshot.set(flag);
778 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
779 debug!("start_snapshot()");
781 let in_snapshot = self.in_snapshot.replace(true);
783 let mut inner = self.inner.borrow_mut();
786 undo_snapshot: inner.undo_log.start_snapshot(),
787 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
788 universe: self.universe(),
789 was_in_snapshot: in_snapshot,
790 // Borrow typeck results "in progress" (i.e., during typeck)
791 // to ban writes from within a snapshot to them.
792 _in_progress_typeck_results: self
793 .in_progress_typeck_results
794 .map(|typeck_results| typeck_results.borrow()),
798 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
799 debug!("rollback_to(cause={})", cause);
800 let CombinedSnapshot {
802 region_constraints_snapshot,
805 _in_progress_typeck_results,
808 self.in_snapshot.set(was_in_snapshot);
809 self.universe.set(universe);
811 let mut inner = self.inner.borrow_mut();
812 inner.rollback_to(undo_snapshot);
813 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
816 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
817 debug!("commit_from()");
818 let CombinedSnapshot {
820 region_constraints_snapshot: _,
823 _in_progress_typeck_results,
826 self.in_snapshot.set(was_in_snapshot);
828 self.inner.borrow_mut().commit(undo_snapshot);
831 /// Executes `f` and commit the bindings.
832 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
834 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
836 debug!("commit_unconditionally()");
837 let snapshot = self.start_snapshot();
838 let r = f(&snapshot);
839 self.commit_from(snapshot);
843 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
844 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
846 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
848 debug!("commit_if_ok()");
849 let snapshot = self.start_snapshot();
850 let r = f(&snapshot);
851 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
854 self.commit_from(snapshot);
857 self.rollback_to("commit_if_ok -- error", snapshot);
863 /// Execute `f` then unroll any bindings it creates.
864 pub fn probe<R, F>(&self, f: F) -> R
866 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
869 let snapshot = self.start_snapshot();
870 let r = f(&snapshot);
871 self.rollback_to("probe", snapshot);
875 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
876 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
878 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
881 let snapshot = self.start_snapshot();
882 let was_skip_leak_check = self.skip_leak_check.get();
884 self.skip_leak_check.set(true);
886 let r = f(&snapshot);
887 self.rollback_to("probe", snapshot);
888 self.skip_leak_check.set(was_skip_leak_check);
892 /// Scan the constraints produced since `snapshot` began and returns:
894 /// - `None` -- if none of them involve "region outlives" constraints
895 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
896 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
897 pub fn region_constraints_added_in_snapshot(
899 snapshot: &CombinedSnapshot<'a, 'tcx>,
903 .unwrap_region_constraints()
904 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
907 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
908 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
911 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
913 T: at::ToTrace<'tcx>,
915 let origin = &ObligationCause::dummy();
917 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
918 // Ignore obligations, since we are unrolling
919 // everything anyway.
924 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
926 T: at::ToTrace<'tcx>,
928 let origin = &ObligationCause::dummy();
930 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
931 // Ignore obligations, since we are unrolling
932 // everything anyway.
939 origin: SubregionOrigin<'tcx>,
943 debug!("sub_regions({:?} <: {:?})", a, b);
944 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
947 /// Require that the region `r` be equal to one of the regions in
948 /// the set `regions`.
949 pub fn member_constraint(
951 opaque_type_def_id: DefId,
952 definition_span: Span,
954 region: ty::Region<'tcx>,
955 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
957 debug!("member_constraint({:?} <: {:?})", region, in_regions);
958 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
967 pub fn subtype_predicate(
969 cause: &ObligationCause<'tcx>,
970 param_env: ty::ParamEnv<'tcx>,
971 predicate: ty::PolySubtypePredicate<'tcx>,
972 ) -> Option<InferResult<'tcx, ()>> {
973 // Subtle: it's ok to skip the binder here and resolve because
974 // `shallow_resolve` just ignores anything that is not a type
975 // variable, and because type variable's can't (at present, at
976 // least) capture any of the things bound by this binder.
978 // NOTE(nmatsakis): really, there is no *particular* reason to do this
979 // `shallow_resolve` here except as a micro-optimization.
980 // Naturally I could not resist.
981 let two_unbound_type_vars = {
982 let a = self.shallow_resolve(predicate.skip_binder().a);
983 let b = self.shallow_resolve(predicate.skip_binder().b);
984 a.is_ty_var() && b.is_ty_var()
987 if two_unbound_type_vars {
988 // Two unbound type variables? Can't make progress.
992 Some(self.commit_if_ok(|_snapshot| {
993 let ty::SubtypePredicate { a_is_expected, a, b } =
994 self.replace_bound_vars_with_placeholders(predicate);
996 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1002 pub fn region_outlives_predicate(
1004 cause: &traits::ObligationCause<'tcx>,
1005 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1006 ) -> UnitResult<'tcx> {
1007 self.commit_if_ok(|_snapshot| {
1008 let ty::OutlivesPredicate(r_a, r_b) =
1009 self.replace_bound_vars_with_placeholders(predicate);
1010 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1011 RelateRegionParamBound(cause.span)
1013 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1018 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1019 self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
1022 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1023 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1026 pub fn next_ty_var_in_universe(
1028 origin: TypeVariableOrigin,
1029 universe: ty::UniverseIndex,
1031 let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
1032 self.tcx.mk_ty_var(vid)
1035 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1036 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1039 pub fn next_const_var(
1042 origin: ConstVariableOrigin,
1043 ) -> &'tcx ty::Const<'tcx> {
1044 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1047 pub fn next_const_var_in_universe(
1050 origin: ConstVariableOrigin,
1051 universe: ty::UniverseIndex,
1052 ) -> &'tcx ty::Const<'tcx> {
1056 .const_unification_table()
1057 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1058 self.tcx.mk_const_var(vid, ty)
1061 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1062 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1064 val: ConstVariableValue::Unknown { universe: self.universe() },
1068 fn next_int_var_id(&self) -> IntVid {
1069 self.inner.borrow_mut().int_unification_table().new_key(None)
1072 pub fn next_int_var(&self) -> Ty<'tcx> {
1073 self.tcx.mk_int_var(self.next_int_var_id())
1076 fn next_float_var_id(&self) -> FloatVid {
1077 self.inner.borrow_mut().float_unification_table().new_key(None)
1080 pub fn next_float_var(&self) -> Ty<'tcx> {
1081 self.tcx.mk_float_var(self.next_float_var_id())
1084 /// Creates a fresh region variable with the next available index.
1085 /// The variable will be created in the maximum universe created
1086 /// thus far, allowing it to name any region created thus far.
1087 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1088 self.next_region_var_in_universe(origin, self.universe())
1091 /// Creates a fresh region variable with the next available index
1092 /// in the given universe; typically, you can use
1093 /// `next_region_var` and just use the maximal universe.
1094 pub fn next_region_var_in_universe(
1096 origin: RegionVariableOrigin,
1097 universe: ty::UniverseIndex,
1098 ) -> ty::Region<'tcx> {
1100 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1101 self.tcx.mk_region(ty::ReVar(region_var))
1104 /// Return the universe that the region `r` was created in. For
1105 /// most regions (e.g., `'static`, named regions from the user,
1106 /// etc) this is the root universe U0. For inference variables or
1107 /// placeholders, however, it will return the universe which which
1108 /// they are associated.
1109 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1110 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1113 /// Number of region variables created so far.
1114 pub fn num_region_vars(&self) -> usize {
1115 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1118 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1119 pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1120 self.next_region_var(RegionVariableOrigin::Nll(origin))
1123 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1124 pub fn next_nll_region_var_in_universe(
1126 origin: NllRegionVariableOrigin,
1127 universe: ty::UniverseIndex,
1128 ) -> ty::Region<'tcx> {
1129 self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1132 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1134 GenericParamDefKind::Lifetime => {
1135 // Create a region inference variable for the given
1136 // region parameter definition.
1137 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1139 GenericParamDefKind::Type { .. } => {
1140 // Create a type inference variable for the given
1141 // type parameter definition. The substitutions are
1142 // for actual parameters that may be referred to by
1143 // the default of this type parameter, if it exists.
1144 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1145 // used in a path such as `Foo::<T, U>::new()` will
1146 // use an inference variable for `C` with `[T, U]`
1147 // as the substitutions for the default, `(T, U)`.
1148 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1151 TypeVariableOrigin {
1152 kind: TypeVariableOriginKind::TypeParameterDefinition(
1160 self.tcx.mk_ty_var(ty_var_id).into()
1162 GenericParamDefKind::Const { .. } => {
1163 let origin = ConstVariableOrigin {
1164 kind: ConstVariableOriginKind::ConstParameterDefinition(
1171 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1173 val: ConstVariableValue::Unknown { universe: self.universe() },
1175 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1180 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1181 /// type/region parameter to a fresh inference variable.
1182 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1183 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1186 /// Returns `true` if errors have been reported since this infcx was
1187 /// created. This is sometimes used as a heuristic to skip
1188 /// reporting errors that often occur as a result of earlier
1189 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1190 /// inference variables, regionck errors).
1191 pub fn is_tainted_by_errors(&self) -> bool {
1193 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1194 tainted_by_errors_flag={})",
1195 self.tcx.sess.err_count(),
1196 self.err_count_on_creation,
1197 self.tainted_by_errors_flag.get()
1200 if self.tcx.sess.err_count() > self.err_count_on_creation {
1201 return true; // errors reported since this infcx was made
1203 self.tainted_by_errors_flag.get()
1206 /// Set the "tainted by errors" flag to true. We call this when we
1207 /// observe an error from a prior pass.
1208 pub fn set_tainted_by_errors(&self) {
1209 debug!("set_tainted_by_errors()");
1210 self.tainted_by_errors_flag.set(true)
1213 /// Process the region constraints and report any errors that
1214 /// result. After this, no more unification operations should be
1215 /// done -- or the compiler will panic -- but it is legal to use
1216 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1217 pub fn resolve_regions_and_report_errors(
1219 region_context: DefId,
1220 outlives_env: &OutlivesEnvironment<'tcx>,
1223 let (var_infos, data) = {
1224 let mut inner = self.inner.borrow_mut();
1225 let inner = &mut *inner;
1227 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1228 "region_obligations not empty: {:#?}",
1229 inner.region_obligations
1232 .region_constraint_storage
1234 .expect("regions already resolved")
1235 .with_log(&mut inner.undo_log)
1236 .into_infos_and_data()
1240 &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1242 let (lexical_region_resolutions, errors) =
1243 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1245 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1246 assert!(old_value.is_none());
1248 if !self.is_tainted_by_errors() {
1249 // As a heuristic, just skip reporting region errors
1250 // altogether if other errors have been reported while
1251 // this infcx was in use. This is totally hokey but
1252 // otherwise we have a hard time separating legit region
1253 // errors from silly ones.
1254 self.report_region_errors(&errors);
1258 /// Obtains (and clears) the current set of region
1259 /// constraints. The inference context is still usable: further
1260 /// unifications will simply add new constraints.
1262 /// This method is not meant to be used with normal lexical region
1263 /// resolution. Rather, it is used in the NLL mode as a kind of
1264 /// interim hack: basically we run normal type-check and generate
1265 /// region constraints as normal, but then we take them and
1266 /// translate them into the form that the NLL solver
1267 /// understands. See the NLL module for mode details.
1268 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1270 self.inner.borrow().region_obligations.is_empty(),
1271 "region_obligations not empty: {:#?}",
1272 self.inner.borrow().region_obligations
1275 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1278 /// Gives temporary access to the region constraint data.
1279 pub fn with_region_constraints<R>(
1281 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1283 let mut inner = self.inner.borrow_mut();
1284 op(inner.unwrap_region_constraints().data())
1287 /// Takes ownership of the list of variable regions. This implies
1288 /// that all the region constraints have already been taken, and
1289 /// hence that `resolve_regions_and_report_errors` can never be
1290 /// called. This is used only during NLL processing to "hand off" ownership
1291 /// of the set of region variables into the NLL region context.
1292 pub fn take_region_var_origins(&self) -> VarInfos {
1293 let mut inner = self.inner.borrow_mut();
1294 let (var_infos, data) = inner
1295 .region_constraint_storage
1297 .expect("regions already resolved")
1298 .with_log(&mut inner.undo_log)
1299 .into_infos_and_data();
1300 assert!(data.is_empty());
1304 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1305 self.resolve_vars_if_possible(t).to_string()
1308 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1309 /// universe index of `TyVar(vid)`.
1310 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1311 use self::type_variable::TypeVariableValue;
1313 match self.inner.borrow_mut().type_variables().probe(vid) {
1314 TypeVariableValue::Known { value } => Ok(value),
1315 TypeVariableValue::Unknown { universe } => Err(universe),
1319 /// Resolve any type variables found in `value` -- but only one
1320 /// level. So, if the variable `?X` is bound to some type
1321 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1322 /// itself be bound to a type).
1324 /// Useful when you only need to inspect the outermost level of
1325 /// the type and don't care about nested types (or perhaps you
1326 /// will be resolving them as well, e.g. in a loop).
1327 pub fn shallow_resolve<T>(&self, value: T) -> T
1329 T: TypeFoldable<'tcx>,
1331 value.fold_with(&mut ShallowResolver { infcx: self })
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; // 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 value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1367 pub fn probe_const_var(
1369 vid: ty::ConstVid<'tcx>,
1370 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1371 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1372 ConstVariableValue::Known { value } => Ok(value),
1373 ConstVariableValue::Unknown { universe } => Err(universe),
1377 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1379 * Attempts to resolve all type/region/const variables in
1380 * `value`. Region inference must have been run already (e.g.,
1381 * by calling `resolve_regions_and_report_errors`). If some
1382 * variable was never unified, an `Err` results.
1384 * This method is idempotent, but it not typically not invoked
1385 * except during the writeback phase.
1388 resolve::fully_resolve(self, value)
1391 // [Note-Type-error-reporting]
1392 // An invariant is that anytime the expected or actual type is Error (the special
1393 // error type, meaning that an error occurred when typechecking this expression),
1394 // this is a derived error. The error cascaded from another error (that was already
1395 // reported), so it's not useful to display it to the user.
1396 // The following methods implement this logic.
1397 // They check if either the actual or expected type is Error, and don't print the error
1398 // in this case. The typechecker should only ever report type errors involving mismatched
1399 // types using one of these methods, and should not call span_err directly for such
1402 pub fn type_error_struct_with_diag<M>(
1406 actual_ty: Ty<'tcx>,
1407 ) -> DiagnosticBuilder<'tcx>
1409 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1411 let actual_ty = self.resolve_vars_if_possible(actual_ty);
1412 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1414 // Don't report an error if actual type is `Error`.
1415 if actual_ty.references_error() {
1416 return self.tcx.sess.diagnostic().struct_dummy();
1419 mk_diag(self.ty_to_string(actual_ty))
1422 pub fn report_mismatched_types(
1424 cause: &ObligationCause<'tcx>,
1427 err: TypeError<'tcx>,
1428 ) -> DiagnosticBuilder<'tcx> {
1429 let trace = TypeTrace::types(cause, true, expected, actual);
1430 self.report_and_explain_type_error(trace, &err)
1433 pub fn report_mismatched_consts(
1435 cause: &ObligationCause<'tcx>,
1436 expected: &'tcx ty::Const<'tcx>,
1437 actual: &'tcx ty::Const<'tcx>,
1438 err: TypeError<'tcx>,
1439 ) -> DiagnosticBuilder<'tcx> {
1440 let trace = TypeTrace::consts(cause, true, expected, actual);
1441 self.report_and_explain_type_error(trace, &err)
1444 pub fn replace_bound_vars_with_fresh_vars<T>(
1447 lbrct: LateBoundRegionConversionTime,
1448 value: ty::Binder<'tcx, T>,
1449 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1451 T: TypeFoldable<'tcx>,
1454 |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct));
1456 self.next_ty_var(TypeVariableOrigin {
1457 kind: TypeVariableOriginKind::MiscVariable,
1461 let fld_c = |_, ty| {
1462 self.next_const_var(
1464 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1467 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1470 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1471 pub fn verify_generic_bound(
1473 origin: SubregionOrigin<'tcx>,
1474 kind: GenericKind<'tcx>,
1475 a: ty::Region<'tcx>,
1476 bound: VerifyBound<'tcx>,
1478 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1482 .unwrap_region_constraints()
1483 .verify_generic_bound(origin, kind, a, bound);
1486 /// Obtains the latest type of the given closure; this may be a
1487 /// closure in the current function, in which case its
1488 /// `ClosureKind` may not yet be known.
1489 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1490 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1491 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1492 closure_kind_ty.to_opt_closure_kind()
1495 /// Clears the selection, evaluation, and projection caches. This is useful when
1496 /// repeatedly attempting to select an `Obligation` while changing only
1497 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1498 pub fn clear_caches(&self) {
1499 self.selection_cache.clear();
1500 self.evaluation_cache.clear();
1501 self.inner.borrow_mut().projection_cache().clear();
1504 fn universe(&self) -> ty::UniverseIndex {
1508 /// Creates and return a fresh universe that extends all previous
1509 /// universes. Updates `self.universe` to that new universe.
1510 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1511 let u = self.universe.get().next_universe();
1512 self.universe.set(u);
1516 /// Resolves and evaluates a constant.
1518 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1519 /// substitutions and environment are used to resolve the constant. Alternatively if the
1520 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1521 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1522 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1523 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1526 /// This handles inferences variables within both `param_env` and `substs` by
1527 /// performing the operation on their respective canonical forms.
1528 pub fn const_eval_resolve(
1530 param_env: ty::ParamEnv<'tcx>,
1531 ty::Unevaluated { def, substs, promoted }: ty::Unevaluated<'tcx>,
1533 ) -> EvalToConstValueResult<'tcx> {
1534 let mut original_values = OriginalQueryValues::default();
1535 let canonical = self.canonicalize_query((param_env, substs), &mut original_values);
1537 let (param_env, substs) = canonical.value;
1538 // The return value is the evaluated value which doesn't contain any reference to inference
1539 // variables, thus we don't need to substitute back the original values.
1540 self.tcx.const_eval_resolve(param_env, ty::Unevaluated { def, substs, promoted }, span)
1543 /// If `typ` is a type variable of some kind, resolve it one level
1544 /// (but do not resolve types found in the result). If `typ` is
1545 /// not a type variable, just return it unmodified.
1546 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1547 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1549 ty::Infer(ty::TyVar(v)) => {
1550 // Not entirely obvious: if `typ` is a type variable,
1551 // it can be resolved to an int/float variable, which
1552 // can then be recursively resolved, hence the
1553 // recursion. Note though that we prevent type
1554 // variables from unifying to other type variables
1555 // directly (though they may be embedded
1556 // structurally), and we prevent cycles in any case,
1557 // so this recursion should always be of very limited
1560 // Note: if these two lines are combined into one we get
1561 // dynamic borrow errors on `self.inner`.
1562 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1563 known.map_or(typ, |t| self.shallow_resolve_ty(t))
1566 ty::Infer(ty::IntVar(v)) => self
1569 .int_unification_table()
1571 .map(|v| v.to_type(self.tcx))
1574 ty::Infer(ty::FloatVar(v)) => self
1577 .float_unification_table()
1579 .map(|v| v.to_type(self.tcx))
1586 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1587 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1588 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1590 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1591 /// inlined, despite being large, because it has only two call sites that
1592 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1593 /// inference variables), and it handles both `Ty` and `ty::Const` without
1594 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1596 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1598 TyOrConstInferVar::Ty(v) => {
1599 use self::type_variable::TypeVariableValue;
1601 // If `inlined_probe` returns a `Known` value, it never equals
1602 // `ty::Infer(ty::TyVar(v))`.
1603 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1604 TypeVariableValue::Unknown { .. } => false,
1605 TypeVariableValue::Known { .. } => true,
1609 TyOrConstInferVar::TyInt(v) => {
1610 // If `inlined_probe_value` returns a value it's always a
1611 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1613 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1616 TyOrConstInferVar::TyFloat(v) => {
1617 // If `probe_value` returns a value it's always a
1618 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1620 // Not `inlined_probe_value(v)` because this call site is colder.
1621 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1624 TyOrConstInferVar::Const(v) => {
1625 // If `probe_value` returns a `Known` value, it never equals
1626 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1628 // Not `inlined_probe_value(v)` because this call site is colder.
1629 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1630 ConstVariableValue::Unknown { .. } => false,
1631 ConstVariableValue::Known { .. } => true,
1638 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1639 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1640 #[derive(Copy, Clone, Debug)]
1641 pub enum TyOrConstInferVar<'tcx> {
1642 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1644 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1646 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1649 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1650 Const(ConstVid<'tcx>),
1653 impl TyOrConstInferVar<'tcx> {
1654 /// Tries to extract an inference variable from a type or a constant, returns `None`
1655 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1656 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1657 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1658 match arg.unpack() {
1659 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1660 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1661 GenericArgKind::Lifetime(_) => None,
1665 /// Tries to extract an inference variable from a type, returns `None`
1666 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1667 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1669 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1670 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1671 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1676 /// Tries to extract an inference variable from a constant, returns `None`
1677 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1678 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1680 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1686 struct ShallowResolver<'a, 'tcx> {
1687 infcx: &'a InferCtxt<'a, 'tcx>,
1690 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1691 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1695 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1696 self.infcx.shallow_resolve_ty(ty)
1699 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1700 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1704 .const_unification_table()
1715 impl<'tcx> TypeTrace<'tcx> {
1716 pub fn span(&self) -> Span {
1721 cause: &ObligationCause<'tcx>,
1722 a_is_expected: bool,
1725 ) -> TypeTrace<'tcx> {
1726 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1730 cause: &ObligationCause<'tcx>,
1731 a_is_expected: bool,
1732 a: &'tcx ty::Const<'tcx>,
1733 b: &'tcx ty::Const<'tcx>,
1734 ) -> TypeTrace<'tcx> {
1735 TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
1739 impl<'tcx> SubregionOrigin<'tcx> {
1740 pub fn span(&self) -> Span {
1742 Subtype(ref a) => a.span(),
1743 RelateObjectBound(a) => a,
1744 RelateParamBound(a, ..) => a,
1745 RelateRegionParamBound(a) => a,
1747 ReborrowUpvar(a, _) => a,
1748 DataBorrowed(_, a) => a,
1749 ReferenceOutlivesReferent(_, a) => a,
1751 CompareImplMethodObligation { span, .. } => span,
1755 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1757 F: FnOnce() -> Self,
1760 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1761 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1764 traits::ObligationCauseCode::CompareImplMethodObligation {
1768 } => SubregionOrigin::CompareImplMethodObligation {
1780 impl RegionVariableOrigin {
1781 pub fn span(&self) -> Span {
1788 | EarlyBoundRegion(a, ..)
1789 | LateBoundRegion(a, ..)
1790 | UpvarRegion(_, a) => a,
1791 Nll(..) => bug!("NLL variable used with `span`"),
1796 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1797 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1800 "RegionObligation(sub_region={:?}, sup_type={:?})",
1801 self.sub_region, self.sup_type