1 //! See the Book for more information.
3 pub use self::freshen::TypeFreshener;
4 pub use self::LateBoundRegionConversionTime::*;
5 pub use self::RegionVariableOrigin::*;
6 pub use self::SubregionOrigin::*;
7 pub use self::ValuePairs::*;
9 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
11 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
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;
24 use rustc_middle::mir::interpret::ConstEvalResult;
25 use rustc_middle::traits::select;
26 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
27 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
28 use rustc_middle::ty::relate::RelateResult;
29 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
30 pub use rustc_middle::ty::IntVarValue;
31 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
32 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
33 use rustc_session::config::BorrowckMode;
34 use rustc_span::symbol::Symbol;
37 use std::cell::{Cell, Ref, RefCell};
38 use std::collections::BTreeMap;
41 use self::combine::CombineFields;
42 use self::free_regions::RegionRelations;
43 use self::lexical_region_resolve::LexicalRegionResolutions;
44 use self::outlives::env::OutlivesEnvironment;
45 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
46 use self::region_constraints::{
47 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
49 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
55 pub mod error_reporting;
62 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 pub fn suppressed(self) -> bool {
118 Self::Solve => false,
119 Self::Erase { suppress_errors } => suppress_errors,
123 /// Indicates that the MIR borrowck will repeat these region
124 /// checks, so we should ignore errors if NLL is (unconditionally)
126 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
127 // FIXME(Centril): Once we actually remove `::Migrate` also make
128 // this always `true` and then proceed to eliminate the dead code.
129 match tcx.borrowck_mode() {
130 // If we're on Migrate mode, report AST region errors
131 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
133 // If we're on MIR, don't report AST region errors as they should be reported by NLL
134 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
139 /// This type contains all the things within `InferCtxt` that sit within a
140 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
141 /// operations are hot enough that we want only one call to `borrow_mut` per
142 /// call to `start_snapshot` and `rollback_to`.
143 pub struct InferCtxtInner<'tcx> {
144 /// Cache for projections. This cache is snapshotted along with the infcx.
146 /// Public so that `traits::project` can use it.
147 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
149 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
150 /// that might instantiate a general type variable have an order,
151 /// represented by its upper and lower bounds.
152 type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
154 /// Map from const parameter variable to the kind of const it represents.
155 const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
157 /// Map from integral variable to the kind of integer it represents.
158 int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
160 /// Map from floating variable to the kind of float it represents.
161 float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
163 /// Tracks the set of region variables and the constraints between them.
164 /// This is initially `Some(_)` but when
165 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
166 /// -- further attempts to perform unification, etc., may fail if new
167 /// region constraints would've been added.
168 region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
170 /// A set of constraints that regionck must validate. Each
171 /// constraint has the form `T:'a`, meaning "some type `T` must
172 /// outlive the lifetime 'a". These constraints derive from
173 /// instantiated type parameters. So if you had a struct defined
176 /// struct Foo<T:'static> { ... }
178 /// then in some expression `let x = Foo { ... }` it will
179 /// instantiate the type parameter `T` with a fresh type `$0`. At
180 /// the same time, it will record a region obligation of
181 /// `$0:'static`. This will get checked later by regionck. (We
182 /// can't generally check these things right away because we have
183 /// to wait until types are resolved.)
185 /// These are stored in a map keyed to the id of the innermost
186 /// enclosing fn body / static initializer expression. This is
187 /// because the location where the obligation was incurred can be
188 /// relevant with respect to which sublifetime assumptions are in
189 /// place. The reason that we store under the fn-id, and not
190 /// something more fine-grained, is so that it is easier for
191 /// regionck to be sure that it has found *all* the region
192 /// obligations (otherwise, it's easy to fail to walk to a
193 /// particular node-id).
195 /// Before running `resolve_regions_and_report_errors`, the creator
196 /// of the inference context is expected to invoke
197 /// `process_region_obligations` (defined in `self::region_obligations`)
198 /// for each body-id in this map, which will process the
199 /// obligations within. This is expected to be done 'late enough'
200 /// that all type inference variables have been bound and so forth.
201 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
203 undo_log: InferCtxtUndoLogs<'tcx>,
206 impl<'tcx> InferCtxtInner<'tcx> {
207 fn new() -> InferCtxtInner<'tcx> {
209 projection_cache: Default::default(),
210 type_variable_storage: type_variable::TypeVariableStorage::new(),
211 undo_log: InferCtxtUndoLogs::default(),
212 const_unification_storage: ut::UnificationTableStorage::new(),
213 int_unification_storage: ut::UnificationTableStorage::new(),
214 float_unification_storage: ut::UnificationTableStorage::new(),
215 region_constraint_storage: Some(RegionConstraintStorage::new()),
216 region_obligations: vec![],
221 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
222 &self.region_obligations
226 pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
227 self.projection_cache.with_log(&mut self.undo_log)
231 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
232 self.type_variable_storage.with_log(&mut self.undo_log)
236 fn int_unification_table(
238 ) -> ut::UnificationTable<
241 &mut ut::UnificationStorage<ty::IntVid>,
242 &mut InferCtxtUndoLogs<'tcx>,
245 self.int_unification_storage.with_log(&mut self.undo_log)
249 fn float_unification_table(
251 ) -> ut::UnificationTable<
254 &mut ut::UnificationStorage<ty::FloatVid>,
255 &mut InferCtxtUndoLogs<'tcx>,
258 self.float_unification_storage.with_log(&mut self.undo_log)
262 fn const_unification_table(
264 ) -> ut::UnificationTable<
267 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
268 &mut InferCtxtUndoLogs<'tcx>,
271 self.const_unification_storage.with_log(&mut self.undo_log)
275 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
276 self.region_constraint_storage
278 .expect("region constraints already solved")
279 .with_log(&mut self.undo_log)
283 pub struct InferCtxt<'a, 'tcx> {
284 pub tcx: TyCtxt<'tcx>,
286 /// During type-checking/inference of a body, `in_progress_tables`
287 /// contains a reference to the tables being built up, which are
288 /// used for reading closure kinds/signatures as they are inferred,
289 /// and for error reporting logic to read arbitrary node types.
290 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
292 pub inner: RefCell<InferCtxtInner<'tcx>>,
294 /// If set, this flag causes us to skip the 'leak check' during
295 /// higher-ranked subtyping operations. This flag is a temporary one used
296 /// to manage the removal of the leak-check: for the time being, we still run the
297 /// leak-check, but we issue warnings. This flag can only be set to true
298 /// when entering a snapshot.
299 skip_leak_check: Cell<bool>,
301 /// Once region inference is done, the values for each variable.
302 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
304 /// Caches the results of trait selection. This cache is used
305 /// for things that have to do with the parameters in scope.
306 pub selection_cache: select::SelectionCache<'tcx>,
308 /// Caches the results of trait evaluation.
309 pub evaluation_cache: select::EvaluationCache<'tcx>,
311 /// the set of predicates on which errors have been reported, to
312 /// avoid reporting the same error twice.
313 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
315 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
317 /// When an error occurs, we want to avoid reporting "derived"
318 /// errors that are due to this original failure. Normally, we
319 /// handle this with the `err_count_on_creation` count, which
320 /// basically just tracks how many errors were reported when we
321 /// started type-checking a fn and checks to see if any new errors
322 /// have been reported since then. Not great, but it works.
324 /// However, when errors originated in other passes -- notably
325 /// resolve -- this heuristic breaks down. Therefore, we have this
326 /// auxiliary flag that one can set whenever one creates a
327 /// type-error that is due to an error in a prior pass.
329 /// Don't read this flag directly, call `is_tainted_by_errors()`
330 /// and `set_tainted_by_errors()`.
331 tainted_by_errors_flag: Cell<bool>,
333 /// Track how many errors were reported when this infcx is created.
334 /// If the number of errors increases, that's also a sign (line
335 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
336 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
337 err_count_on_creation: usize,
339 /// This flag is true while there is an active snapshot.
340 in_snapshot: Cell<bool>,
342 /// What is the innermost universe we have created? Starts out as
343 /// `UniverseIndex::root()` but grows from there as we enter
344 /// universal quantifiers.
346 /// N.B., at present, we exclude the universal quantifiers on the
347 /// item we are type-checking, and just consider those names as
348 /// part of the root universe. So this would only get incremented
349 /// when we enter into a higher-ranked (`for<..>`) type or trait
351 universe: Cell<ty::UniverseIndex>,
354 /// A map returned by `replace_bound_vars_with_placeholders()`
355 /// indicating the placeholder region that each late-bound region was
357 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
359 /// See the `error_reporting` module for more details.
360 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
361 pub enum ValuePairs<'tcx> {
362 Types(ExpectedFound<Ty<'tcx>>),
363 Regions(ExpectedFound<ty::Region<'tcx>>),
364 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
365 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
366 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
369 /// The trace designates the path through inference that we took to
370 /// encounter an error or subtyping constraint.
372 /// See the `error_reporting` module for more details.
373 #[derive(Clone, Debug)]
374 pub struct TypeTrace<'tcx> {
375 cause: ObligationCause<'tcx>,
376 values: ValuePairs<'tcx>,
379 /// The origin of a `r1 <= r2` constraint.
381 /// See `error_reporting` module for more details
382 #[derive(Clone, Debug)]
383 pub enum SubregionOrigin<'tcx> {
384 /// Arose from a subtyping relation
385 Subtype(Box<TypeTrace<'tcx>>),
387 /// When casting `&'a T` to an `&'b Trait` object,
388 /// relating `'a` to `'b`
389 RelateObjectBound(Span),
391 /// Some type parameter was instantiated with the given type,
392 /// and that type must outlive some region.
393 RelateParamBound(Span, Ty<'tcx>),
395 /// The given region parameter was instantiated with a region
396 /// that must outlive some other region.
397 RelateRegionParamBound(Span),
399 /// Creating a pointer `b` to contents of another reference
402 /// Creating a pointer `b` to contents of an upvar
403 ReborrowUpvar(Span, ty::UpvarId),
405 /// Data with type `Ty<'tcx>` was borrowed
406 DataBorrowed(Ty<'tcx>, Span),
408 /// (&'a &'b T) where a >= b
409 ReferenceOutlivesReferent(Ty<'tcx>, Span),
411 /// Region in return type of invoked fn must enclose call
414 /// Comparing the signature and requirements of an impl method against
415 /// the containing trait.
416 CompareImplMethodObligation {
419 impl_item_def_id: DefId,
420 trait_item_def_id: DefId,
424 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
425 #[cfg(target_arch = "x86_64")]
426 static_assert_size!(SubregionOrigin<'_>, 32);
428 /// Places that type/region parameters can appear.
429 #[derive(Clone, Copy, Debug)]
430 pub enum ParameterOrigin {
432 MethodCall, // foo.bar() <-- parameters on impl providing bar()
433 OverloadedOperator, // a + b when overloaded
434 OverloadedDeref, // *a when overloaded
437 /// Times when we replace late-bound regions with variables:
438 #[derive(Clone, Copy, Debug)]
439 pub enum LateBoundRegionConversionTime {
440 /// when a fn is called
443 /// when two higher-ranked types are compared
446 /// when projecting an associated type
447 AssocTypeProjection(DefId),
450 /// Reasons to create a region inference variable
452 /// See `error_reporting` module for more details
453 #[derive(Copy, Clone, Debug)]
454 pub enum RegionVariableOrigin {
455 /// Region variables created for ill-categorized reasons,
456 /// mostly indicates places in need of refactoring
459 /// Regions created by a `&P` or `[...]` pattern
462 /// Regions created by `&` operator
465 /// Regions created as part of an autoref of a method receiver
468 /// Regions created as part of an automatic coercion
471 /// Region variables created as the values for early-bound regions
472 EarlyBoundRegion(Span, Symbol),
474 /// Region variables created for bound regions
475 /// in a function or method that is called
476 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
478 UpvarRegion(ty::UpvarId, Span),
480 BoundRegionInCoherence(Symbol),
482 /// This origin is used for the inference variables that we create
483 /// during NLL region processing.
484 NLL(NLLRegionVariableOrigin),
487 #[derive(Copy, Clone, Debug)]
488 pub enum NLLRegionVariableOrigin {
489 /// During NLL region processing, we create variables for free
490 /// regions that we encounter in the function signature and
491 /// elsewhere. This origin indices we've got one of those.
494 /// "Universal" instantiation of a higher-ranked region (e.g.,
495 /// from a `for<'a> T` binder). Meant to represent "any region".
496 Placeholder(ty::PlaceholderRegion),
498 /// The variable we create to represent `'empty(U0)`.
502 /// If this is true, then this variable was created to represent a lifetime
503 /// bound in a `for` binder. For example, it might have been created to
504 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
505 /// Such variables are created when we are trying to figure out if there
506 /// is any valid instantiation of `'a` that could fit into some scenario.
508 /// This is used to inform error reporting: in the case that we are trying to
509 /// determine whether there is any valid instantiation of a `'a` variable that meets
510 /// some constraint C, we want to blame the "source" of that `for` type,
511 /// rather than blaming the source of the constraint C.
516 impl NLLRegionVariableOrigin {
517 pub fn is_universal(self) -> bool {
519 NLLRegionVariableOrigin::FreeRegion => true,
520 NLLRegionVariableOrigin::Placeholder(..) => true,
521 NLLRegionVariableOrigin::Existential { .. } => false,
522 NLLRegionVariableOrigin::RootEmptyRegion => false,
526 pub fn is_existential(self) -> bool {
531 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
532 #[derive(Copy, Clone, Debug)]
533 pub enum FixupError<'tcx> {
534 UnresolvedIntTy(IntVid),
535 UnresolvedFloatTy(FloatVid),
537 UnresolvedConst(ConstVid<'tcx>),
540 /// See the `region_obligations` field for more information.
542 pub struct RegionObligation<'tcx> {
543 pub sub_region: ty::Region<'tcx>,
544 pub sup_type: Ty<'tcx>,
545 pub origin: SubregionOrigin<'tcx>,
548 impl<'tcx> fmt::Display for FixupError<'tcx> {
549 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550 use self::FixupError::*;
553 UnresolvedIntTy(_) => write!(
555 "cannot determine the type of this integer; \
556 add a suffix to specify the type explicitly"
558 UnresolvedFloatTy(_) => write!(
560 "cannot determine the type of this number; \
561 add a suffix to specify the type explicitly"
563 UnresolvedTy(_) => write!(f, "unconstrained type"),
564 UnresolvedConst(_) => write!(f, "unconstrained const value"),
569 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
570 /// Necessary because we can't write the following bound:
571 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
572 pub struct InferCtxtBuilder<'tcx> {
573 global_tcx: TyCtxt<'tcx>,
574 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
577 pub trait TyCtxtInferExt<'tcx> {
578 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
581 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
582 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
583 InferCtxtBuilder { global_tcx: self, fresh_tables: None }
587 impl<'tcx> InferCtxtBuilder<'tcx> {
588 /// Used only by `rustc_typeck` during body type-checking/inference,
589 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
590 pub fn with_fresh_in_progress_tables(mut self, table_owner: LocalDefId) -> Self {
591 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
595 /// Given a canonical value `C` as a starting point, create an
596 /// inference context that contains each of the bound values
597 /// within instantiated as a fresh variable. The `f` closure is
598 /// invoked with the new infcx, along with the instantiated value
599 /// `V` and a substitution `S`. This substitution `S` maps from
600 /// the bound values in `C` to their instantiated values in `V`
601 /// (in other words, `S(C) = V`).
602 pub fn enter_with_canonical<T, R>(
605 canonical: &Canonical<'tcx, T>,
606 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
609 T: TypeFoldable<'tcx>,
613 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
614 f(infcx, value, subst)
618 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
619 let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
620 let in_progress_tables = fresh_tables.as_ref();
621 global_tcx.enter_local(|tcx| {
625 inner: RefCell::new(InferCtxtInner::new()),
626 lexical_region_resolutions: RefCell::new(None),
627 selection_cache: Default::default(),
628 evaluation_cache: Default::default(),
629 reported_trait_errors: Default::default(),
630 reported_closure_mismatch: Default::default(),
631 tainted_by_errors_flag: Cell::new(false),
632 err_count_on_creation: tcx.sess.err_count(),
633 in_snapshot: Cell::new(false),
634 skip_leak_check: Cell::new(false),
635 universe: Cell::new(ty::UniverseIndex::ROOT),
641 impl<'tcx, T> InferOk<'tcx, T> {
642 pub fn unit(self) -> InferOk<'tcx, ()> {
643 InferOk { value: (), obligations: self.obligations }
646 /// Extracts `value`, registering any obligations into `fulfill_cx`.
647 pub fn into_value_registering_obligations(
649 infcx: &InferCtxt<'_, 'tcx>,
650 fulfill_cx: &mut dyn TraitEngine<'tcx>,
652 let InferOk { value, obligations } = self;
653 for obligation in obligations {
654 fulfill_cx.register_predicate_obligation(infcx, obligation);
660 impl<'tcx> InferOk<'tcx, ()> {
661 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
666 #[must_use = "once you start a snapshot, you should always consume it"]
667 pub struct CombinedSnapshot<'a, 'tcx> {
668 undo_snapshot: Snapshot<'tcx>,
669 region_constraints_snapshot: RegionSnapshot,
670 universe: ty::UniverseIndex,
671 was_in_snapshot: bool,
672 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
675 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
676 pub fn is_in_snapshot(&self) -> bool {
677 self.in_snapshot.get()
680 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
681 t.fold_with(&mut self.freshener())
684 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
686 ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
691 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
692 freshen::TypeFreshener::new(self)
695 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
696 use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
697 use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
699 ty::Infer(ty::IntVar(vid)) => {
700 if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
706 ty::Infer(ty::FloatVar(vid)) => {
707 if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
717 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
718 let mut inner = self.inner.borrow_mut();
719 // FIXME(const_generics): should there be an equivalent function for const variables?
721 let mut vars: Vec<Ty<'_>> = inner
723 .unsolved_variables()
725 .map(|t| self.tcx.mk_ty_var(t))
728 (0..inner.int_unification_table().len())
729 .map(|i| ty::IntVid { index: i as u32 })
730 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
731 .map(|v| self.tcx.mk_int_var(v)),
734 (0..inner.float_unification_table().len())
735 .map(|i| ty::FloatVid { index: i as u32 })
736 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
737 .map(|v| self.tcx.mk_float_var(v)),
744 trace: TypeTrace<'tcx>,
745 param_env: ty::ParamEnv<'tcx>,
746 ) -> CombineFields<'a, 'tcx> {
752 obligations: PredicateObligations::new(),
756 /// Clear the "currently in a snapshot" flag, invoke the closure,
757 /// then restore the flag to its original value. This flag is a
758 /// debugging measure designed to detect cases where we start a
759 /// snapshot, create type variables, and register obligations
760 /// which may involve those type variables in the fulfillment cx,
761 /// potentially leaving "dangling type variables" behind.
762 /// In such cases, an assertion will fail when attempting to
763 /// register obligations, within a snapshot. Very useful, much
764 /// better than grovelling through megabytes of `RUSTC_LOG` output.
766 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
767 /// sometimes create a "mini-fulfilment-cx" in which we enroll
768 /// obligations. As long as this fulfillment cx is fully drained
769 /// before we return, this is not a problem, as there won't be any
770 /// escaping obligations in the main cx. In those cases, you can
771 /// use this function.
772 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
774 F: FnOnce(&Self) -> R,
776 let flag = self.in_snapshot.replace(false);
777 let result = func(self);
778 self.in_snapshot.set(flag);
782 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
783 debug!("start_snapshot()");
785 let in_snapshot = self.in_snapshot.replace(true);
787 let mut inner = self.inner.borrow_mut();
790 undo_snapshot: inner.undo_log.start_snapshot(),
791 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
792 universe: self.universe(),
793 was_in_snapshot: in_snapshot,
794 // Borrow tables "in progress" (i.e., during typeck)
795 // to ban writes from within a snapshot to them.
796 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
800 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
801 debug!("rollback_to(cause={})", cause);
802 let CombinedSnapshot {
804 region_constraints_snapshot,
810 self.in_snapshot.set(was_in_snapshot);
811 self.universe.set(universe);
813 let mut inner = self.inner.borrow_mut();
814 inner.rollback_to(undo_snapshot);
815 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
818 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
819 debug!("commit_from()");
820 let CombinedSnapshot {
822 region_constraints_snapshot: _,
828 self.in_snapshot.set(was_in_snapshot);
830 self.inner.borrow_mut().commit(undo_snapshot);
833 /// Executes `f` and commit the bindings.
834 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
836 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
838 debug!("commit_unconditionally()");
839 let snapshot = self.start_snapshot();
840 let r = f(&snapshot);
841 self.commit_from(snapshot);
845 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
846 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
848 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
850 debug!("commit_if_ok()");
851 let snapshot = self.start_snapshot();
852 let r = f(&snapshot);
853 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
856 self.commit_from(snapshot);
859 self.rollback_to("commit_if_ok -- error", snapshot);
865 /// Execute `f` then unroll any bindings it creates.
866 pub fn probe<R, F>(&self, f: F) -> R
868 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
871 let snapshot = self.start_snapshot();
872 let r = f(&snapshot);
873 self.rollback_to("probe", snapshot);
877 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
878 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
880 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
883 let snapshot = self.start_snapshot();
884 let was_skip_leak_check = self.skip_leak_check.get();
886 self.skip_leak_check.set(true);
888 let r = f(&snapshot);
889 self.rollback_to("probe", snapshot);
890 self.skip_leak_check.set(was_skip_leak_check);
894 /// Scan the constraints produced since `snapshot` began and returns:
896 /// - `None` -- if none of them involve "region outlives" constraints
897 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
898 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
899 pub fn region_constraints_added_in_snapshot(
901 snapshot: &CombinedSnapshot<'a, 'tcx>,
905 .unwrap_region_constraints()
906 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
909 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
910 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
913 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
915 T: at::ToTrace<'tcx>,
917 let origin = &ObligationCause::dummy();
919 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
920 // Ignore obligations, since we are unrolling
921 // everything anyway.
926 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
928 T: at::ToTrace<'tcx>,
930 let origin = &ObligationCause::dummy();
932 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
933 // Ignore obligations, since we are unrolling
934 // everything anyway.
941 origin: SubregionOrigin<'tcx>,
945 debug!("sub_regions({:?} <: {:?})", a, b);
946 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
949 /// Require that the region `r` be equal to one of the regions in
950 /// the set `regions`.
951 pub fn member_constraint(
953 opaque_type_def_id: DefId,
954 definition_span: Span,
956 region: ty::Region<'tcx>,
957 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
959 debug!("member_constraint({:?} <: {:?})", region, in_regions);
960 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
969 pub fn subtype_predicate(
971 cause: &ObligationCause<'tcx>,
972 param_env: ty::ParamEnv<'tcx>,
973 predicate: ty::PolySubtypePredicate<'tcx>,
974 ) -> Option<InferResult<'tcx, ()>> {
975 // Subtle: it's ok to skip the binder here and resolve because
976 // `shallow_resolve` just ignores anything that is not a type
977 // variable, and because type variable's can't (at present, at
978 // least) capture any of the things bound by this binder.
980 // NOTE(nmatsakis): really, there is no *particular* reason to do this
981 // `shallow_resolve` here except as a micro-optimization.
982 // Naturally I could not resist.
983 let two_unbound_type_vars = {
984 let a = self.shallow_resolve(predicate.skip_binder().a);
985 let b = self.shallow_resolve(predicate.skip_binder().b);
986 a.is_ty_var() && b.is_ty_var()
989 if two_unbound_type_vars {
990 // Two unbound type variables? Can't make progress.
994 Some(self.commit_if_ok(|snapshot| {
995 let (ty::SubtypePredicate { a_is_expected, a, b }, _) =
996 self.replace_bound_vars_with_placeholders(&predicate);
998 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1000 self.leak_check(false, snapshot)?;
1006 pub fn region_outlives_predicate(
1008 cause: &traits::ObligationCause<'tcx>,
1009 predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
1010 ) -> UnitResult<'tcx> {
1011 self.commit_if_ok(|snapshot| {
1012 let (ty::OutlivesPredicate(r_a, r_b), _) =
1013 self.replace_bound_vars_with_placeholders(&predicate);
1014 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1015 RelateRegionParamBound(cause.span)
1017 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1018 self.leak_check(false, snapshot)?;
1023 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1024 self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
1027 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1028 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1031 pub fn next_ty_var_in_universe(
1033 origin: TypeVariableOrigin,
1034 universe: ty::UniverseIndex,
1036 let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
1037 self.tcx.mk_ty_var(vid)
1040 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1041 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1044 pub fn next_const_var(
1047 origin: ConstVariableOrigin,
1048 ) -> &'tcx ty::Const<'tcx> {
1049 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1052 pub fn next_const_var_in_universe(
1055 origin: ConstVariableOrigin,
1056 universe: ty::UniverseIndex,
1057 ) -> &'tcx ty::Const<'tcx> {
1061 .const_unification_table()
1062 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1063 self.tcx.mk_const_var(vid, ty)
1066 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1067 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1069 val: ConstVariableValue::Unknown { universe: self.universe() },
1073 fn next_int_var_id(&self) -> IntVid {
1074 self.inner.borrow_mut().int_unification_table().new_key(None)
1077 pub fn next_int_var(&self) -> Ty<'tcx> {
1078 self.tcx.mk_int_var(self.next_int_var_id())
1081 fn next_float_var_id(&self) -> FloatVid {
1082 self.inner.borrow_mut().float_unification_table().new_key(None)
1085 pub fn next_float_var(&self) -> Ty<'tcx> {
1086 self.tcx.mk_float_var(self.next_float_var_id())
1089 /// Creates a fresh region variable with the next available index.
1090 /// The variable will be created in the maximum universe created
1091 /// thus far, allowing it to name any region created thus far.
1092 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1093 self.next_region_var_in_universe(origin, self.universe())
1096 /// Creates a fresh region variable with the next available index
1097 /// in the given universe; typically, you can use
1098 /// `next_region_var` and just use the maximal universe.
1099 pub fn next_region_var_in_universe(
1101 origin: RegionVariableOrigin,
1102 universe: ty::UniverseIndex,
1103 ) -> ty::Region<'tcx> {
1105 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1106 self.tcx.mk_region(ty::ReVar(region_var))
1109 /// Return the universe that the region `r` was created in. For
1110 /// most regions (e.g., `'static`, named regions from the user,
1111 /// etc) this is the root universe U0. For inference variables or
1112 /// placeholders, however, it will return the universe which which
1113 /// they are associated.
1114 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1115 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1118 /// Number of region variables created so far.
1119 pub fn num_region_vars(&self) -> usize {
1120 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1123 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1124 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1125 self.next_region_var(RegionVariableOrigin::NLL(origin))
1128 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1129 pub fn next_nll_region_var_in_universe(
1131 origin: NLLRegionVariableOrigin,
1132 universe: ty::UniverseIndex,
1133 ) -> ty::Region<'tcx> {
1134 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1137 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1139 GenericParamDefKind::Lifetime => {
1140 // Create a region inference variable for the given
1141 // region parameter definition.
1142 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1144 GenericParamDefKind::Type { .. } => {
1145 // Create a type inference variable for the given
1146 // type parameter definition. The substitutions are
1147 // for actual parameters that may be referred to by
1148 // the default of this type parameter, if it exists.
1149 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1150 // used in a path such as `Foo::<T, U>::new()` will
1151 // use an inference variable for `C` with `[T, U]`
1152 // as the substitutions for the default, `(T, U)`.
1153 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1156 TypeVariableOrigin {
1157 kind: TypeVariableOriginKind::TypeParameterDefinition(
1165 self.tcx.mk_ty_var(ty_var_id).into()
1167 GenericParamDefKind::Const { .. } => {
1168 let origin = ConstVariableOrigin {
1169 kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1173 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1175 val: ConstVariableValue::Unknown { universe: self.universe() },
1177 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1182 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1183 /// type/region parameter to a fresh inference variable.
1184 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1185 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1188 /// Returns `true` if errors have been reported since this infcx was
1189 /// created. This is sometimes used as a heuristic to skip
1190 /// reporting errors that often occur as a result of earlier
1191 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1192 /// inference variables, regionck errors).
1193 pub fn is_tainted_by_errors(&self) -> bool {
1195 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1196 tainted_by_errors_flag={})",
1197 self.tcx.sess.err_count(),
1198 self.err_count_on_creation,
1199 self.tainted_by_errors_flag.get()
1202 if self.tcx.sess.err_count() > self.err_count_on_creation {
1203 return true; // errors reported since this infcx was made
1205 self.tainted_by_errors_flag.get()
1208 /// Set the "tainted by errors" flag to true. We call this when we
1209 /// observe an error from a prior pass.
1210 pub fn set_tainted_by_errors(&self) {
1211 debug!("set_tainted_by_errors()");
1212 self.tainted_by_errors_flag.set(true)
1215 /// Process the region constraints and report any errors that
1216 /// result. After this, no more unification operations should be
1217 /// done -- or the compiler will panic -- but it is legal to use
1218 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1219 pub fn resolve_regions_and_report_errors(
1221 region_context: DefId,
1222 outlives_env: &OutlivesEnvironment<'tcx>,
1225 let (var_infos, data) = {
1226 let mut inner = self.inner.borrow_mut();
1227 let inner = &mut *inner;
1229 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1230 "region_obligations not empty: {:#?}",
1231 inner.region_obligations
1234 .region_constraint_storage
1236 .expect("regions already resolved")
1237 .with_log(&mut inner.undo_log)
1238 .into_infos_and_data()
1242 &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1244 let (lexical_region_resolutions, errors) =
1245 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1247 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1248 assert!(old_value.is_none());
1250 if !self.is_tainted_by_errors() {
1251 // As a heuristic, just skip reporting region errors
1252 // altogether if other errors have been reported while
1253 // this infcx was in use. This is totally hokey but
1254 // otherwise we have a hard time separating legit region
1255 // errors from silly ones.
1256 self.report_region_errors(&errors);
1260 /// Obtains (and clears) the current set of region
1261 /// constraints. The inference context is still usable: further
1262 /// unifications will simply add new constraints.
1264 /// This method is not meant to be used with normal lexical region
1265 /// resolution. Rather, it is used in the NLL mode as a kind of
1266 /// interim hack: basically we run normal type-check and generate
1267 /// region constraints as normal, but then we take them and
1268 /// translate them into the form that the NLL solver
1269 /// understands. See the NLL module for mode details.
1270 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1272 self.inner.borrow().region_obligations.is_empty(),
1273 "region_obligations not empty: {:#?}",
1274 self.inner.borrow().region_obligations
1277 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1280 /// Gives temporary access to the region constraint data.
1281 #[allow(non_camel_case_types)] // bug with impl trait
1282 pub fn with_region_constraints<R>(
1284 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1286 let mut inner = self.inner.borrow_mut();
1287 op(inner.unwrap_region_constraints().data())
1290 /// Takes ownership of the list of variable regions. This implies
1291 /// that all the region constraints have already been taken, and
1292 /// hence that `resolve_regions_and_report_errors` can never be
1293 /// called. This is used only during NLL processing to "hand off" ownership
1294 /// of the set of region variables into the NLL region context.
1295 pub fn take_region_var_origins(&self) -> VarInfos {
1296 let mut inner = self.inner.borrow_mut();
1297 let (var_infos, data) = inner
1298 .region_constraint_storage
1300 .expect("regions already resolved")
1301 .with_log(&mut inner.undo_log)
1302 .into_infos_and_data();
1303 assert!(data.is_empty());
1307 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1308 self.resolve_vars_if_possible(&t).to_string()
1311 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1312 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1313 format!("({})", tstrs.join(", "))
1316 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1317 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1320 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1321 /// universe index of `TyVar(vid)`.
1322 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1323 use self::type_variable::TypeVariableValue;
1325 match self.inner.borrow_mut().type_variables().probe(vid) {
1326 TypeVariableValue::Known { value } => Ok(value),
1327 TypeVariableValue::Unknown { universe } => Err(universe),
1331 /// Resolve any type variables found in `value` -- but only one
1332 /// level. So, if the variable `?X` is bound to some type
1333 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1334 /// itself be bound to a type).
1336 /// Useful when you only need to inspect the outermost level of
1337 /// the type and don't care about nested types (or perhaps you
1338 /// will be resolving them as well, e.g. in a loop).
1339 pub fn shallow_resolve<T>(&self, value: T) -> T
1341 T: TypeFoldable<'tcx>,
1343 value.fold_with(&mut ShallowResolver { infcx: self })
1346 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1347 self.inner.borrow_mut().type_variables().root_var(var)
1350 /// Where possible, replaces type/const variables in
1351 /// `value` with their final value. Note that region variables
1352 /// are unaffected. If a type/const variable has not been unified, it
1353 /// is left as is. This is an idempotent operation that does
1354 /// not affect inference state in any way and so you can do it
1356 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1358 T: TypeFoldable<'tcx>,
1360 if !value.needs_infer() {
1361 return value.clone(); // Avoid duplicated subst-folding.
1363 let mut r = resolve::OpportunisticVarResolver::new(self);
1364 value.fold_with(&mut r)
1367 /// Returns the first unresolved variable contained in `T`. In the
1368 /// process of visiting `T`, this will resolve (where possible)
1369 /// type variables in `T`, but it never constructs the final,
1370 /// resolved type, so it's more efficient than
1371 /// `resolve_vars_if_possible()`.
1372 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1374 T: TypeFoldable<'tcx>,
1376 let mut r = resolve::UnresolvedTypeFinder::new(self);
1377 value.visit_with(&mut r);
1381 pub fn probe_const_var(
1383 vid: ty::ConstVid<'tcx>,
1384 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1385 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1386 ConstVariableValue::Known { value } => Ok(value),
1387 ConstVariableValue::Unknown { universe } => Err(universe),
1391 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1393 * Attempts to resolve all type/region/const variables in
1394 * `value`. Region inference must have been run already (e.g.,
1395 * by calling `resolve_regions_and_report_errors`). If some
1396 * variable was never unified, an `Err` results.
1398 * This method is idempotent, but it not typically not invoked
1399 * except during the writeback phase.
1402 resolve::fully_resolve(self, value)
1405 // [Note-Type-error-reporting]
1406 // An invariant is that anytime the expected or actual type is Error (the special
1407 // error type, meaning that an error occurred when typechecking this expression),
1408 // this is a derived error. The error cascaded from another error (that was already
1409 // reported), so it's not useful to display it to the user.
1410 // The following methods implement this logic.
1411 // They check if either the actual or expected type is Error, and don't print the error
1412 // in this case. The typechecker should only ever report type errors involving mismatched
1413 // types using one of these methods, and should not call span_err directly for such
1416 pub fn type_error_struct_with_diag<M>(
1420 actual_ty: Ty<'tcx>,
1421 ) -> DiagnosticBuilder<'tcx>
1423 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1425 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1426 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1428 // Don't report an error if actual type is `Error`.
1429 if actual_ty.references_error() {
1430 return self.tcx.sess.diagnostic().struct_dummy();
1433 mk_diag(self.ty_to_string(actual_ty))
1436 pub fn report_mismatched_types(
1438 cause: &ObligationCause<'tcx>,
1441 err: TypeError<'tcx>,
1442 ) -> DiagnosticBuilder<'tcx> {
1443 let trace = TypeTrace::types(cause, true, expected, actual);
1444 self.report_and_explain_type_error(trace, &err)
1447 pub fn report_mismatched_consts(
1449 cause: &ObligationCause<'tcx>,
1450 expected: &'tcx ty::Const<'tcx>,
1451 actual: &'tcx ty::Const<'tcx>,
1452 err: TypeError<'tcx>,
1453 ) -> DiagnosticBuilder<'tcx> {
1454 let trace = TypeTrace::consts(cause, true, expected, actual);
1455 self.report_and_explain_type_error(trace, &err)
1458 pub fn replace_bound_vars_with_fresh_vars<T>(
1461 lbrct: LateBoundRegionConversionTime,
1462 value: &ty::Binder<T>,
1463 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1465 T: TypeFoldable<'tcx>,
1467 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1469 self.next_ty_var(TypeVariableOrigin {
1470 kind: TypeVariableOriginKind::MiscVariable,
1474 let fld_c = |_, ty| {
1475 self.next_const_var(
1477 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1480 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1483 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1484 pub fn verify_generic_bound(
1486 origin: SubregionOrigin<'tcx>,
1487 kind: GenericKind<'tcx>,
1488 a: ty::Region<'tcx>,
1489 bound: VerifyBound<'tcx>,
1491 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1495 .unwrap_region_constraints()
1496 .verify_generic_bound(origin, kind, a, bound);
1499 /// Obtains the latest type of the given closure; this may be a
1500 /// closure in the current function, in which case its
1501 /// `ClosureKind` may not yet be known.
1502 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1503 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1504 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1505 closure_kind_ty.to_opt_closure_kind()
1508 /// Clears the selection, evaluation, and projection caches. This is useful when
1509 /// repeatedly attempting to select an `Obligation` while changing only
1510 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1511 pub fn clear_caches(&self) {
1512 self.selection_cache.clear();
1513 self.evaluation_cache.clear();
1514 self.inner.borrow_mut().projection_cache().clear();
1517 fn universe(&self) -> ty::UniverseIndex {
1521 /// Creates and return a fresh universe that extends all previous
1522 /// universes. Updates `self.universe` to that new universe.
1523 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1524 let u = self.universe.get().next_universe();
1525 self.universe.set(u);
1529 /// Resolves and evaluates a constant.
1531 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1532 /// substitutions and environment are used to resolve the constant. Alternatively if the
1533 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1534 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1535 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1536 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1539 /// This handles inferences variables within both `param_env` and `substs` by
1540 /// performing the operation on their respective canonical forms.
1541 pub fn const_eval_resolve(
1543 param_env: ty::ParamEnv<'tcx>,
1545 substs: SubstsRef<'tcx>,
1546 promoted: Option<mir::Promoted>,
1548 ) -> ConstEvalResult<'tcx> {
1549 let mut original_values = OriginalQueryValues::default();
1550 let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1552 let (param_env, substs) = canonical.value;
1553 // The return value is the evaluated value which doesn't contain any reference to inference
1554 // variables, thus we don't need to substitute back the original values.
1555 self.tcx.const_eval_resolve(param_env, def_id, substs, promoted, span)
1558 /// If `typ` is a type variable of some kind, resolve it one level
1559 /// (but do not resolve types found in the result). If `typ` is
1560 /// not a type variable, just return it unmodified.
1561 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1562 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1564 ty::Infer(ty::TyVar(v)) => {
1565 // Not entirely obvious: if `typ` is a type variable,
1566 // it can be resolved to an int/float variable, which
1567 // can then be recursively resolved, hence the
1568 // recursion. Note though that we prevent type
1569 // variables from unifying to other type variables
1570 // directly (though they may be embedded
1571 // structurally), and we prevent cycles in any case,
1572 // so this recursion should always be of very limited
1575 // Note: if these two lines are combined into one we get
1576 // dynamic borrow errors on `self.inner`.
1577 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1578 known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
1581 ty::Infer(ty::IntVar(v)) => self
1584 .int_unification_table()
1586 .map(|v| v.to_type(self.tcx))
1589 ty::Infer(ty::FloatVar(v)) => self
1592 .float_unification_table()
1594 .map(|v| v.to_type(self.tcx))
1601 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1602 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1603 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1605 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1606 /// inlined, despite being large, because it has only two call sites that
1607 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1608 /// inference variables), and it handles both `Ty` and `ty::Const` without
1609 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1611 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1613 TyOrConstInferVar::Ty(v) => {
1614 use self::type_variable::TypeVariableValue;
1616 // If `inlined_probe` returns a `Known` value, it never equals
1617 // `ty::Infer(ty::TyVar(v))`.
1618 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1619 TypeVariableValue::Unknown { .. } => false,
1620 TypeVariableValue::Known { .. } => true,
1624 TyOrConstInferVar::TyInt(v) => {
1625 // If `inlined_probe_value` returns a value it's always a
1626 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1628 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1631 TyOrConstInferVar::TyFloat(v) => {
1632 // If `probe_value` returns a value it's always a
1633 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1635 // Not `inlined_probe_value(v)` because this call site is colder.
1636 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1639 TyOrConstInferVar::Const(v) => {
1640 // If `probe_value` returns a `Known` value, it never equals
1641 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1643 // Not `inlined_probe_value(v)` because this call site is colder.
1644 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1645 ConstVariableValue::Unknown { .. } => false,
1646 ConstVariableValue::Known { .. } => true,
1653 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1654 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1655 #[derive(Copy, Clone, Debug)]
1656 pub enum TyOrConstInferVar<'tcx> {
1657 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1659 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1661 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1664 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1665 Const(ConstVid<'tcx>),
1668 impl TyOrConstInferVar<'tcx> {
1669 /// Tries to extract an inference variable from a type or a constant, returns `None`
1670 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1671 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1672 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1673 match arg.unpack() {
1674 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1675 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1676 GenericArgKind::Lifetime(_) => None,
1680 /// Tries to extract an inference variable from a type, returns `None`
1681 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1682 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1684 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1685 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1686 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1691 /// Tries to extract an inference variable from a constant, returns `None`
1692 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1693 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1695 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1701 struct ShallowResolver<'a, 'tcx> {
1702 infcx: &'a InferCtxt<'a, 'tcx>,
1705 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1706 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1710 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1711 self.infcx.shallow_resolve_ty(ty)
1714 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1715 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1719 .const_unification_table()
1730 impl<'tcx> TypeTrace<'tcx> {
1731 pub fn span(&self) -> Span {
1736 cause: &ObligationCause<'tcx>,
1737 a_is_expected: bool,
1740 ) -> TypeTrace<'tcx> {
1741 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1745 cause: &ObligationCause<'tcx>,
1746 a_is_expected: bool,
1747 a: &'tcx ty::Const<'tcx>,
1748 b: &'tcx ty::Const<'tcx>,
1749 ) -> TypeTrace<'tcx> {
1750 TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
1753 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1754 let err = tcx.ty_error();
1756 cause: ObligationCause::dummy(),
1757 values: Types(ExpectedFound { expected: err, found: err }),
1762 impl<'tcx> SubregionOrigin<'tcx> {
1763 pub fn span(&self) -> Span {
1765 Subtype(ref a) => a.span(),
1766 RelateObjectBound(a) => a,
1767 RelateParamBound(a, _) => a,
1768 RelateRegionParamBound(a) => a,
1770 ReborrowUpvar(a, _) => a,
1771 DataBorrowed(_, a) => a,
1772 ReferenceOutlivesReferent(_, a) => a,
1774 CompareImplMethodObligation { span, .. } => span,
1778 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1780 F: FnOnce() -> Self,
1783 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1784 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1787 traits::ObligationCauseCode::CompareImplMethodObligation {
1791 } => SubregionOrigin::CompareImplMethodObligation {
1803 impl RegionVariableOrigin {
1804 pub fn span(&self) -> Span {
1806 MiscVariable(a) => a,
1807 PatternRegion(a) => a,
1808 AddrOfRegion(a) => a,
1811 EarlyBoundRegion(a, ..) => a,
1812 LateBoundRegion(a, ..) => a,
1813 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1814 UpvarRegion(_, a) => a,
1815 NLL(..) => bug!("NLL variable used with `span`"),
1820 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1821 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1824 "RegionObligation(sub_region={:?}, sup_type={:?})",
1825 self.sub_region, self.sup_type