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 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_data_structures::sync::Lrc;
14 use rustc_data_structures::unify as ut;
15 use rustc_errors::DiagnosticBuilder;
17 use rustc_hir::def_id::{DefId, LocalDefId};
18 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
19 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
20 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
21 use rustc_middle::middle::region;
22 use rustc_middle::mir;
23 use rustc_middle::mir::interpret::ConstEvalResult;
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::{RegionConstraintCollector, RegionSnapshot};
46 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
52 pub mod error_reporting;
59 mod lexical_region_resolve;
63 pub mod region_constraints;
66 pub mod type_variable;
68 use crate::infer::canonical::OriginalQueryValues;
69 pub use rustc_middle::infer::unify_key;
73 pub struct InferOk<'tcx, T> {
75 pub obligations: PredicateObligations<'tcx>,
77 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
79 pub type Bound<T> = Option<T>;
80 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
81 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
83 /// How we should handle region solving.
85 /// This is used so that the region values inferred by HIR region solving are
86 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
87 /// typeck will also do.
88 #[derive(Copy, Clone, Debug)]
89 pub enum RegionckMode {
90 /// The default mode: report region errors, don't erase regions.
92 /// Erase the results of region after solving.
94 /// A flag that is used to suppress region errors, when we are doing
95 /// region checks that the NLL borrow checker will also do -- it might
97 suppress_errors: bool,
101 impl Default for RegionckMode {
102 fn default() -> Self {
108 pub fn suppressed(self) -> bool {
110 Self::Solve => false,
111 Self::Erase { suppress_errors } => suppress_errors,
115 /// Indicates that the MIR borrowck will repeat these region
116 /// checks, so we should ignore errors if NLL is (unconditionally)
118 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
119 // FIXME(Centril): Once we actually remove `::Migrate` also make
120 // this always `true` and then proceed to eliminate the dead code.
121 match tcx.borrowck_mode() {
122 // If we're on Migrate mode, report AST region errors
123 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
125 // If we're on MIR, don't report AST region errors as they should be reported by NLL
126 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
131 /// This type contains all the things within `InferCtxt` that sit within a
132 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
133 /// operations are hot enough that we want only one call to `borrow_mut` per
134 /// call to `start_snapshot` and `rollback_to`.
135 pub struct InferCtxtInner<'tcx> {
136 /// Cache for projections. This cache is snapshotted along with the infcx.
138 /// Public so that `traits::project` can use it.
139 pub projection_cache: traits::ProjectionCache<'tcx>,
141 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
142 /// that might instantiate a general type variable have an order,
143 /// represented by its upper and lower bounds.
144 type_variables: type_variable::TypeVariableTable<'tcx>,
146 /// Map from const parameter variable to the kind of const it represents.
147 const_unification_table: ut::UnificationTable<ut::InPlace<ty::ConstVid<'tcx>>>,
149 /// Map from integral variable to the kind of integer it represents.
150 int_unification_table: ut::UnificationTable<ut::InPlace<ty::IntVid>>,
152 /// Map from floating variable to the kind of float it represents.
153 float_unification_table: ut::UnificationTable<ut::InPlace<ty::FloatVid>>,
155 /// Tracks the set of region variables and the constraints between them.
156 /// This is initially `Some(_)` but when
157 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
158 /// -- further attempts to perform unification, etc., may fail if new
159 /// region constraints would've been added.
160 region_constraints: Option<RegionConstraintCollector<'tcx>>,
162 /// A set of constraints that regionck must validate. Each
163 /// constraint has the form `T:'a`, meaning "some type `T` must
164 /// outlive the lifetime 'a". These constraints derive from
165 /// instantiated type parameters. So if you had a struct defined
168 /// struct Foo<T:'static> { ... }
170 /// then in some expression `let x = Foo { ... }` it will
171 /// instantiate the type parameter `T` with a fresh type `$0`. At
172 /// the same time, it will record a region obligation of
173 /// `$0:'static`. This will get checked later by regionck. (We
174 /// can't generally check these things right away because we have
175 /// to wait until types are resolved.)
177 /// These are stored in a map keyed to the id of the innermost
178 /// enclosing fn body / static initializer expression. This is
179 /// because the location where the obligation was incurred can be
180 /// relevant with respect to which sublifetime assumptions are in
181 /// place. The reason that we store under the fn-id, and not
182 /// something more fine-grained, is so that it is easier for
183 /// regionck to be sure that it has found *all* the region
184 /// obligations (otherwise, it's easy to fail to walk to a
185 /// particular node-id).
187 /// Before running `resolve_regions_and_report_errors`, the creator
188 /// of the inference context is expected to invoke
189 /// `process_region_obligations` (defined in `self::region_obligations`)
190 /// for each body-id in this map, which will process the
191 /// obligations within. This is expected to be done 'late enough'
192 /// that all type inference variables have been bound and so forth.
193 pub region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
196 impl<'tcx> InferCtxtInner<'tcx> {
197 fn new() -> InferCtxtInner<'tcx> {
199 projection_cache: Default::default(),
200 type_variables: type_variable::TypeVariableTable::new(),
201 const_unification_table: ut::UnificationTable::new(),
202 int_unification_table: ut::UnificationTable::new(),
203 float_unification_table: ut::UnificationTable::new(),
204 region_constraints: Some(RegionConstraintCollector::new()),
205 region_obligations: vec![],
209 pub fn unwrap_region_constraints(&mut self) -> &mut RegionConstraintCollector<'tcx> {
210 self.region_constraints.as_mut().expect("region constraints already solved")
214 pub struct InferCtxt<'a, 'tcx> {
215 pub tcx: TyCtxt<'tcx>,
217 /// During type-checking/inference of a body, `in_progress_tables`
218 /// contains a reference to the tables being built up, which are
219 /// used for reading closure kinds/signatures as they are inferred,
220 /// and for error reporting logic to read arbitrary node types.
221 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
223 pub inner: RefCell<InferCtxtInner<'tcx>>,
225 /// If set, this flag causes us to skip the 'leak check' during
226 /// higher-ranked subtyping operations. This flag is a temporary one used
227 /// to manage the removal of the leak-check: for the time being, we still run the
228 /// leak-check, but we issue warnings. This flag can only be set to true
229 /// when entering a snapshot.
230 skip_leak_check: Cell<bool>,
232 /// Once region inference is done, the values for each variable.
233 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
235 /// Caches the results of trait selection. This cache is used
236 /// for things that have to do with the parameters in scope.
237 pub selection_cache: select::SelectionCache<'tcx>,
239 /// Caches the results of trait evaluation.
240 pub evaluation_cache: select::EvaluationCache<'tcx>,
242 /// the set of predicates on which errors have been reported, to
243 /// avoid reporting the same error twice.
244 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
246 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
248 /// When an error occurs, we want to avoid reporting "derived"
249 /// errors that are due to this original failure. Normally, we
250 /// handle this with the `err_count_on_creation` count, which
251 /// basically just tracks how many errors were reported when we
252 /// started type-checking a fn and checks to see if any new errors
253 /// have been reported since then. Not great, but it works.
255 /// However, when errors originated in other passes -- notably
256 /// resolve -- this heuristic breaks down. Therefore, we have this
257 /// auxiliary flag that one can set whenever one creates a
258 /// type-error that is due to an error in a prior pass.
260 /// Don't read this flag directly, call `is_tainted_by_errors()`
261 /// and `set_tainted_by_errors()`.
262 tainted_by_errors_flag: Cell<bool>,
264 /// Track how many errors were reported when this infcx is created.
265 /// If the number of errors increases, that's also a sign (line
266 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
267 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
268 err_count_on_creation: usize,
270 /// This flag is true while there is an active snapshot.
271 in_snapshot: Cell<bool>,
273 /// What is the innermost universe we have created? Starts out as
274 /// `UniverseIndex::root()` but grows from there as we enter
275 /// universal quantifiers.
277 /// N.B., at present, we exclude the universal quantifiers on the
278 /// item we are type-checking, and just consider those names as
279 /// part of the root universe. So this would only get incremented
280 /// when we enter into a higher-ranked (`for<..>`) type or trait
282 universe: Cell<ty::UniverseIndex>,
285 /// A map returned by `replace_bound_vars_with_placeholders()`
286 /// indicating the placeholder region that each late-bound region was
288 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
290 /// See the `error_reporting` module for more details.
291 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
292 pub enum ValuePairs<'tcx> {
293 Types(ExpectedFound<Ty<'tcx>>),
294 Regions(ExpectedFound<ty::Region<'tcx>>),
295 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
296 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
297 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
300 /// The trace designates the path through inference that we took to
301 /// encounter an error or subtyping constraint.
303 /// See the `error_reporting` module for more details.
304 #[derive(Clone, Debug)]
305 pub struct TypeTrace<'tcx> {
306 cause: ObligationCause<'tcx>,
307 values: ValuePairs<'tcx>,
310 /// The origin of a `r1 <= r2` constraint.
312 /// See `error_reporting` module for more details
313 #[derive(Clone, Debug)]
314 pub enum SubregionOrigin<'tcx> {
315 /// Arose from a subtyping relation
316 Subtype(Box<TypeTrace<'tcx>>),
318 /// Stack-allocated closures cannot outlive innermost loop
319 /// or function so as to ensure we only require finite stack
320 InfStackClosure(Span),
322 /// Invocation of closure must be within its lifetime
325 /// Dereference of reference must be within its lifetime
328 /// Closure bound must not outlive captured variables
329 ClosureCapture(Span, hir::HirId),
331 /// Index into slice must be within its lifetime
334 /// When casting `&'a T` to an `&'b Trait` object,
335 /// relating `'a` to `'b`
336 RelateObjectBound(Span),
338 /// Some type parameter was instantiated with the given type,
339 /// and that type must outlive some region.
340 RelateParamBound(Span, Ty<'tcx>),
342 /// The given region parameter was instantiated with a region
343 /// that must outlive some other region.
344 RelateRegionParamBound(Span),
346 /// A bound placed on type parameters that states that must outlive
347 /// the moment of their instantiation.
348 RelateDefaultParamBound(Span, Ty<'tcx>),
350 /// Creating a pointer `b` to contents of another reference
353 /// Creating a pointer `b` to contents of an upvar
354 ReborrowUpvar(Span, ty::UpvarId),
356 /// Data with type `Ty<'tcx>` was borrowed
357 DataBorrowed(Ty<'tcx>, Span),
359 /// (&'a &'b T) where a >= b
360 ReferenceOutlivesReferent(Ty<'tcx>, Span),
362 /// Type or region parameters must be in scope.
363 ParameterInScope(ParameterOrigin, Span),
365 /// The type T of an expression E must outlive the lifetime for E.
366 ExprTypeIsNotInScope(Ty<'tcx>, Span),
368 /// A `ref b` whose region does not enclose the decl site
369 BindingTypeIsNotValidAtDecl(Span),
371 /// Regions appearing in a method receiver must outlive method call
374 /// Regions appearing in a function argument must outlive func call
377 /// Region in return type of invoked fn must enclose call
380 /// Operands must be in scope
383 /// Region resulting from a `&` expr must enclose the `&` expr
386 /// An auto-borrow that does not enclose the expr where it occurs
389 /// Region constraint arriving from destructor safety
390 SafeDestructor(Span),
392 /// Comparing the signature and requirements of an impl method against
393 /// the containing trait.
394 CompareImplMethodObligation {
396 item_name: ast::Name,
397 impl_item_def_id: DefId,
398 trait_item_def_id: DefId,
402 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
403 #[cfg(target_arch = "x86_64")]
404 static_assert_size!(SubregionOrigin<'_>, 32);
406 /// Places that type/region parameters can appear.
407 #[derive(Clone, Copy, Debug)]
408 pub enum ParameterOrigin {
410 MethodCall, // foo.bar() <-- parameters on impl providing bar()
411 OverloadedOperator, // a + b when overloaded
412 OverloadedDeref, // *a when overloaded
415 /// Times when we replace late-bound regions with variables:
416 #[derive(Clone, Copy, Debug)]
417 pub enum LateBoundRegionConversionTime {
418 /// when a fn is called
421 /// when two higher-ranked types are compared
424 /// when projecting an associated type
425 AssocTypeProjection(DefId),
428 /// Reasons to create a region inference variable
430 /// See `error_reporting` module for more details
431 #[derive(Copy, Clone, Debug)]
432 pub enum RegionVariableOrigin {
433 /// Region variables created for ill-categorized reasons,
434 /// mostly indicates places in need of refactoring
437 /// Regions created by a `&P` or `[...]` pattern
440 /// Regions created by `&` operator
443 /// Regions created as part of an autoref of a method receiver
446 /// Regions created as part of an automatic coercion
449 /// Region variables created as the values for early-bound regions
450 EarlyBoundRegion(Span, Symbol),
452 /// Region variables created for bound regions
453 /// in a function or method that is called
454 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
456 UpvarRegion(ty::UpvarId, Span),
458 BoundRegionInCoherence(ast::Name),
460 /// This origin is used for the inference variables that we create
461 /// during NLL region processing.
462 NLL(NLLRegionVariableOrigin),
465 #[derive(Copy, Clone, Debug)]
466 pub enum NLLRegionVariableOrigin {
467 /// During NLL region processing, we create variables for free
468 /// regions that we encounter in the function signature and
469 /// elsewhere. This origin indices we've got one of those.
472 /// "Universal" instantiation of a higher-ranked region (e.g.,
473 /// from a `for<'a> T` binder). Meant to represent "any region".
474 Placeholder(ty::PlaceholderRegion),
476 /// The variable we create to represent `'empty(U0)`.
480 /// If this is true, then this variable was created to represent a lifetime
481 /// bound in a `for` binder. For example, it might have been created to
482 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
483 /// Such variables are created when we are trying to figure out if there
484 /// is any valid instantiation of `'a` that could fit into some scenario.
486 /// This is used to inform error reporting: in the case that we are trying to
487 /// determine whether there is any valid instantiation of a `'a` variable that meets
488 /// some constraint C, we want to blame the "source" of that `for` type,
489 /// rather than blaming the source of the constraint C.
494 impl NLLRegionVariableOrigin {
495 pub fn is_universal(self) -> bool {
497 NLLRegionVariableOrigin::FreeRegion => true,
498 NLLRegionVariableOrigin::Placeholder(..) => true,
499 NLLRegionVariableOrigin::Existential { .. } => false,
500 NLLRegionVariableOrigin::RootEmptyRegion => false,
504 pub fn is_existential(self) -> bool {
509 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
510 #[derive(Copy, Clone, Debug)]
511 pub enum FixupError<'tcx> {
512 UnresolvedIntTy(IntVid),
513 UnresolvedFloatTy(FloatVid),
515 UnresolvedConst(ConstVid<'tcx>),
518 /// See the `region_obligations` field for more information.
520 pub struct RegionObligation<'tcx> {
521 pub sub_region: ty::Region<'tcx>,
522 pub sup_type: Ty<'tcx>,
523 pub origin: SubregionOrigin<'tcx>,
526 impl<'tcx> fmt::Display for FixupError<'tcx> {
527 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528 use self::FixupError::*;
531 UnresolvedIntTy(_) => write!(
533 "cannot determine the type of this integer; \
534 add a suffix to specify the type explicitly"
536 UnresolvedFloatTy(_) => write!(
538 "cannot determine the type of this number; \
539 add a suffix to specify the type explicitly"
541 UnresolvedTy(_) => write!(f, "unconstrained type"),
542 UnresolvedConst(_) => write!(f, "unconstrained const value"),
547 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
548 /// Necessary because we can't write the following bound:
549 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
550 pub struct InferCtxtBuilder<'tcx> {
551 global_tcx: TyCtxt<'tcx>,
552 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
555 pub trait TyCtxtInferExt<'tcx> {
556 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
559 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
560 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
561 InferCtxtBuilder { global_tcx: self, fresh_tables: None }
565 impl<'tcx> InferCtxtBuilder<'tcx> {
566 /// Used only by `rustc_typeck` during body type-checking/inference,
567 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
568 pub fn with_fresh_in_progress_tables(mut self, table_owner: LocalDefId) -> Self {
569 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
573 /// Given a canonical value `C` as a starting point, create an
574 /// inference context that contains each of the bound values
575 /// within instantiated as a fresh variable. The `f` closure is
576 /// invoked with the new infcx, along with the instantiated value
577 /// `V` and a substitution `S`. This substitution `S` maps from
578 /// the bound values in `C` to their instantiated values in `V`
579 /// (in other words, `S(C) = V`).
580 pub fn enter_with_canonical<T, R>(
583 canonical: &Canonical<'tcx, T>,
584 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
587 T: TypeFoldable<'tcx>,
591 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
592 f(infcx, value, subst)
596 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
597 let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
598 let in_progress_tables = fresh_tables.as_ref();
599 global_tcx.enter_local(|tcx| {
603 inner: RefCell::new(InferCtxtInner::new()),
604 lexical_region_resolutions: RefCell::new(None),
605 selection_cache: Default::default(),
606 evaluation_cache: Default::default(),
607 reported_trait_errors: Default::default(),
608 reported_closure_mismatch: Default::default(),
609 tainted_by_errors_flag: Cell::new(false),
610 err_count_on_creation: tcx.sess.err_count(),
611 in_snapshot: Cell::new(false),
612 skip_leak_check: Cell::new(false),
613 universe: Cell::new(ty::UniverseIndex::ROOT),
619 impl<'tcx, T> InferOk<'tcx, T> {
620 pub fn unit(self) -> InferOk<'tcx, ()> {
621 InferOk { value: (), obligations: self.obligations }
624 /// Extracts `value`, registering any obligations into `fulfill_cx`.
625 pub fn into_value_registering_obligations(
627 infcx: &InferCtxt<'_, 'tcx>,
628 fulfill_cx: &mut dyn TraitEngine<'tcx>,
630 let InferOk { value, obligations } = self;
631 for obligation in obligations {
632 fulfill_cx.register_predicate_obligation(infcx, obligation);
638 impl<'tcx> InferOk<'tcx, ()> {
639 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
644 #[must_use = "once you start a snapshot, you should always consume it"]
645 pub struct CombinedSnapshot<'a, 'tcx> {
646 projection_cache_snapshot: traits::ProjectionCacheSnapshot,
647 type_snapshot: type_variable::Snapshot<'tcx>,
648 const_snapshot: ut::Snapshot<ut::InPlace<ty::ConstVid<'tcx>>>,
649 int_snapshot: ut::Snapshot<ut::InPlace<ty::IntVid>>,
650 float_snapshot: ut::Snapshot<ut::InPlace<ty::FloatVid>>,
651 region_constraints_snapshot: RegionSnapshot,
652 region_obligations_snapshot: usize,
653 universe: ty::UniverseIndex,
654 was_in_snapshot: bool,
655 was_skip_leak_check: bool,
656 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
659 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
660 pub fn is_in_snapshot(&self) -> bool {
661 self.in_snapshot.get()
664 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
665 t.fold_with(&mut self.freshener())
668 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
670 ty::Infer(ty::TyVar(vid)) => self.inner.borrow().type_variables.var_diverges(vid),
675 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
676 freshen::TypeFreshener::new(self)
679 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
680 use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
681 use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
683 ty::Infer(ty::IntVar(vid)) => {
684 if self.inner.borrow_mut().int_unification_table.probe_value(vid).is_some() {
690 ty::Infer(ty::FloatVar(vid)) => {
691 if self.inner.borrow_mut().float_unification_table.probe_value(vid).is_some() {
701 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
702 let mut inner = self.inner.borrow_mut();
703 // FIXME(const_generics): should there be an equivalent function for const variables?
705 let mut vars: Vec<Ty<'_>> = inner
707 .unsolved_variables()
709 .map(|t| self.tcx.mk_ty_var(t))
712 (0..inner.int_unification_table.len())
713 .map(|i| ty::IntVid { index: i as u32 })
714 .filter(|&vid| inner.int_unification_table.probe_value(vid).is_none())
715 .map(|v| self.tcx.mk_int_var(v)),
718 (0..inner.float_unification_table.len())
719 .map(|i| ty::FloatVid { index: i as u32 })
720 .filter(|&vid| inner.float_unification_table.probe_value(vid).is_none())
721 .map(|v| self.tcx.mk_float_var(v)),
728 trace: TypeTrace<'tcx>,
729 param_env: ty::ParamEnv<'tcx>,
730 ) -> CombineFields<'a, 'tcx> {
736 obligations: PredicateObligations::new(),
740 /// Clear the "currently in a snapshot" flag, invoke the closure,
741 /// then restore the flag to its original value. This flag is a
742 /// debugging measure designed to detect cases where we start a
743 /// snapshot, create type variables, and register obligations
744 /// which may involve those type variables in the fulfillment cx,
745 /// potentially leaving "dangling type variables" behind.
746 /// In such cases, an assertion will fail when attempting to
747 /// register obligations, within a snapshot. Very useful, much
748 /// better than grovelling through megabytes of `RUSTC_LOG` output.
750 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
751 /// sometimes create a "mini-fulfilment-cx" in which we enroll
752 /// obligations. As long as this fulfillment cx is fully drained
753 /// before we return, this is not a problem, as there won't be any
754 /// escaping obligations in the main cx. In those cases, you can
755 /// use this function.
756 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
758 F: FnOnce(&Self) -> R,
760 let flag = self.in_snapshot.replace(false);
761 let result = func(self);
762 self.in_snapshot.set(flag);
766 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
767 debug!("start_snapshot()");
769 let in_snapshot = self.in_snapshot.replace(true);
771 let mut inner = self.inner.borrow_mut();
773 projection_cache_snapshot: inner.projection_cache.snapshot(),
774 type_snapshot: inner.type_variables.snapshot(),
775 const_snapshot: inner.const_unification_table.snapshot(),
776 int_snapshot: inner.int_unification_table.snapshot(),
777 float_snapshot: inner.float_unification_table.snapshot(),
778 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
779 region_obligations_snapshot: inner.region_obligations.len(),
780 universe: self.universe(),
781 was_in_snapshot: in_snapshot,
782 was_skip_leak_check: self.skip_leak_check.get(),
783 // Borrow tables "in progress" (i.e., during typeck)
784 // to ban writes from within a snapshot to them.
785 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
789 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
790 debug!("rollback_to(cause={})", cause);
791 let CombinedSnapshot {
792 projection_cache_snapshot,
797 region_constraints_snapshot,
798 region_obligations_snapshot,
805 self.in_snapshot.set(was_in_snapshot);
806 self.universe.set(universe);
807 self.skip_leak_check.set(was_skip_leak_check);
809 let mut inner = self.inner.borrow_mut();
810 inner.projection_cache.rollback_to(projection_cache_snapshot);
811 inner.type_variables.rollback_to(type_snapshot);
812 inner.const_unification_table.rollback_to(const_snapshot);
813 inner.int_unification_table.rollback_to(int_snapshot);
814 inner.float_unification_table.rollback_to(float_snapshot);
815 inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
816 inner.region_obligations.truncate(region_obligations_snapshot);
819 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
820 debug!("commit_from()");
821 let CombinedSnapshot {
822 projection_cache_snapshot,
827 region_constraints_snapshot,
828 region_obligations_snapshot: _,
835 self.in_snapshot.set(was_in_snapshot);
836 self.skip_leak_check.set(was_skip_leak_check);
838 let mut inner = self.inner.borrow_mut();
839 inner.projection_cache.commit(projection_cache_snapshot);
840 inner.type_variables.commit(type_snapshot);
841 inner.const_unification_table.commit(const_snapshot);
842 inner.int_unification_table.commit(int_snapshot);
843 inner.float_unification_table.commit(float_snapshot);
844 inner.unwrap_region_constraints().commit(region_constraints_snapshot);
847 /// Executes `f` and commit the bindings.
848 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
850 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
852 debug!("commit_unconditionally()");
853 let snapshot = self.start_snapshot();
854 let r = f(&snapshot);
855 self.commit_from(snapshot);
859 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
860 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
862 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
864 debug!("commit_if_ok()");
865 let snapshot = self.start_snapshot();
866 let r = f(&snapshot);
867 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
870 self.commit_from(snapshot);
873 self.rollback_to("commit_if_ok -- error", snapshot);
879 /// Execute `f` then unroll any bindings it creates.
880 pub fn probe<R, F>(&self, f: F) -> R
882 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
885 let snapshot = self.start_snapshot();
886 let r = f(&snapshot);
887 self.rollback_to("probe", snapshot);
891 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
892 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
894 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
897 let snapshot = self.start_snapshot();
898 let skip_leak_check = should_skip || self.skip_leak_check.get();
899 self.skip_leak_check.set(skip_leak_check);
900 let r = f(&snapshot);
901 self.rollback_to("probe", snapshot);
905 /// Scan the constraints produced since `snapshot` began and returns:
907 /// - `None` -- if none of them involve "region outlives" constraints
908 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
909 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
910 pub fn region_constraints_added_in_snapshot(
912 snapshot: &CombinedSnapshot<'a, 'tcx>,
916 .unwrap_region_constraints()
917 .region_constraints_added_in_snapshot(&snapshot.region_constraints_snapshot)
920 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
921 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
924 pub fn can_sub<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).sub(a, b).map(|InferOk { obligations: _, .. }| {
931 // Ignore obligations, since we are unrolling
932 // everything anyway.
937 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
939 T: at::ToTrace<'tcx>,
941 let origin = &ObligationCause::dummy();
943 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
944 // Ignore obligations, since we are unrolling
945 // everything anyway.
952 origin: SubregionOrigin<'tcx>,
956 debug!("sub_regions({:?} <: {:?})", a, b);
957 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
960 /// Require that the region `r` be equal to one of the regions in
961 /// the set `regions`.
962 pub fn member_constraint(
964 opaque_type_def_id: DefId,
965 definition_span: Span,
967 region: ty::Region<'tcx>,
968 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
970 debug!("member_constraint({:?} <: {:?})", region, in_regions);
971 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
980 pub fn subtype_predicate(
982 cause: &ObligationCause<'tcx>,
983 param_env: ty::ParamEnv<'tcx>,
984 predicate: &ty::PolySubtypePredicate<'tcx>,
985 ) -> Option<InferResult<'tcx, ()>> {
986 // Subtle: it's ok to skip the binder here and resolve because
987 // `shallow_resolve` just ignores anything that is not a type
988 // variable, and because type variable's can't (at present, at
989 // least) capture any of the things bound by this binder.
991 // NOTE(nmatsakis): really, there is no *particular* reason to do this
992 // `shallow_resolve` here except as a micro-optimization.
993 // Naturally I could not resist.
994 let two_unbound_type_vars = {
995 let a = self.shallow_resolve(predicate.skip_binder().a);
996 let b = self.shallow_resolve(predicate.skip_binder().b);
997 a.is_ty_var() && b.is_ty_var()
1000 if two_unbound_type_vars {
1001 // Two unbound type variables? Can't make progress.
1005 Some(self.commit_if_ok(|snapshot| {
1006 let (ty::SubtypePredicate { a_is_expected, a, b }, placeholder_map) =
1007 self.replace_bound_vars_with_placeholders(predicate);
1009 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1011 self.leak_check(false, &placeholder_map, snapshot)?;
1017 pub fn region_outlives_predicate(
1019 cause: &traits::ObligationCause<'tcx>,
1020 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
1021 ) -> UnitResult<'tcx> {
1022 self.commit_if_ok(|snapshot| {
1023 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
1024 self.replace_bound_vars_with_placeholders(predicate);
1025 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1026 RelateRegionParamBound(cause.span)
1028 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1029 self.leak_check(false, &placeholder_map, snapshot)?;
1034 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1035 self.inner.borrow_mut().type_variables.new_var(self.universe(), diverging, origin)
1038 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1039 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1042 pub fn next_ty_var_in_universe(
1044 origin: TypeVariableOrigin,
1045 universe: ty::UniverseIndex,
1047 let vid = self.inner.borrow_mut().type_variables.new_var(universe, false, origin);
1048 self.tcx.mk_ty_var(vid)
1051 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1052 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1055 pub fn next_const_var(
1058 origin: ConstVariableOrigin,
1059 ) -> &'tcx ty::Const<'tcx> {
1060 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1063 pub fn next_const_var_in_universe(
1066 origin: ConstVariableOrigin,
1067 universe: ty::UniverseIndex,
1068 ) -> &'tcx ty::Const<'tcx> {
1072 .const_unification_table
1073 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1074 self.tcx.mk_const_var(vid, ty)
1077 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1078 self.inner.borrow_mut().const_unification_table.new_key(ConstVarValue {
1080 val: ConstVariableValue::Unknown { universe: self.universe() },
1084 fn next_int_var_id(&self) -> IntVid {
1085 self.inner.borrow_mut().int_unification_table.new_key(None)
1088 pub fn next_int_var(&self) -> Ty<'tcx> {
1089 self.tcx.mk_int_var(self.next_int_var_id())
1092 fn next_float_var_id(&self) -> FloatVid {
1093 self.inner.borrow_mut().float_unification_table.new_key(None)
1096 pub fn next_float_var(&self) -> Ty<'tcx> {
1097 self.tcx.mk_float_var(self.next_float_var_id())
1100 /// Creates a fresh region variable with the next available index.
1101 /// The variable will be created in the maximum universe created
1102 /// thus far, allowing it to name any region created thus far.
1103 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1104 self.next_region_var_in_universe(origin, self.universe())
1107 /// Creates a fresh region variable with the next available index
1108 /// in the given universe; typically, you can use
1109 /// `next_region_var` and just use the maximal universe.
1110 pub fn next_region_var_in_universe(
1112 origin: RegionVariableOrigin,
1113 universe: ty::UniverseIndex,
1114 ) -> ty::Region<'tcx> {
1116 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1117 self.tcx.mk_region(ty::ReVar(region_var))
1120 /// Return the universe that the region `r` was created in. For
1121 /// most regions (e.g., `'static`, named regions from the user,
1122 /// etc) this is the root universe U0. For inference variables or
1123 /// placeholders, however, it will return the universe which which
1124 /// they are associated.
1125 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1126 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1129 /// Number of region variables created so far.
1130 pub fn num_region_vars(&self) -> usize {
1131 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1134 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1135 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1136 self.next_region_var(RegionVariableOrigin::NLL(origin))
1139 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1140 pub fn next_nll_region_var_in_universe(
1142 origin: NLLRegionVariableOrigin,
1143 universe: ty::UniverseIndex,
1144 ) -> ty::Region<'tcx> {
1145 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1148 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1150 GenericParamDefKind::Lifetime => {
1151 // Create a region inference variable for the given
1152 // region parameter definition.
1153 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1155 GenericParamDefKind::Type { .. } => {
1156 // Create a type inference variable for the given
1157 // type parameter definition. The substitutions are
1158 // for actual parameters that may be referred to by
1159 // the default of this type parameter, if it exists.
1160 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1161 // used in a path such as `Foo::<T, U>::new()` will
1162 // use an inference variable for `C` with `[T, U]`
1163 // as the substitutions for the default, `(T, U)`.
1164 let ty_var_id = self.inner.borrow_mut().type_variables.new_var(
1167 TypeVariableOrigin {
1168 kind: TypeVariableOriginKind::TypeParameterDefinition(
1176 self.tcx.mk_ty_var(ty_var_id).into()
1178 GenericParamDefKind::Const { .. } => {
1179 let origin = ConstVariableOrigin {
1180 kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1184 self.inner.borrow_mut().const_unification_table.new_key(ConstVarValue {
1186 val: ConstVariableValue::Unknown { universe: self.universe() },
1188 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1193 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1194 /// type/region parameter to a fresh inference variable.
1195 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1196 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1199 /// Returns `true` if errors have been reported since this infcx was
1200 /// created. This is sometimes used as a heuristic to skip
1201 /// reporting errors that often occur as a result of earlier
1202 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1203 /// inference variables, regionck errors).
1204 pub fn is_tainted_by_errors(&self) -> bool {
1206 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1207 tainted_by_errors_flag={})",
1208 self.tcx.sess.err_count(),
1209 self.err_count_on_creation,
1210 self.tainted_by_errors_flag.get()
1213 if self.tcx.sess.err_count() > self.err_count_on_creation {
1214 return true; // errors reported since this infcx was made
1216 self.tainted_by_errors_flag.get()
1219 /// Set the "tainted by errors" flag to true. We call this when we
1220 /// observe an error from a prior pass.
1221 pub fn set_tainted_by_errors(&self) {
1222 debug!("set_tainted_by_errors()");
1223 self.tainted_by_errors_flag.set(true)
1226 /// Process the region constraints and report any errors that
1227 /// result. After this, no more unification operations should be
1228 /// done -- or the compiler will panic -- but it is legal to use
1229 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1230 pub fn resolve_regions_and_report_errors(
1232 region_context: DefId,
1233 region_map: ®ion::ScopeTree,
1234 outlives_env: &OutlivesEnvironment<'tcx>,
1238 self.is_tainted_by_errors() || self.inner.borrow().region_obligations.is_empty(),
1239 "region_obligations not empty: {:#?}",
1240 self.inner.borrow().region_obligations
1242 let (var_infos, data) = self
1247 .expect("regions already resolved")
1248 .into_infos_and_data();
1250 let region_rels = &RegionRelations::new(
1254 outlives_env.free_region_map(),
1257 let (lexical_region_resolutions, errors) =
1258 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1260 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1261 assert!(old_value.is_none());
1263 if !self.is_tainted_by_errors() {
1264 // As a heuristic, just skip reporting region errors
1265 // altogether if other errors have been reported while
1266 // this infcx was in use. This is totally hokey but
1267 // otherwise we have a hard time separating legit region
1268 // errors from silly ones.
1269 self.report_region_errors(region_map, &errors);
1273 /// Obtains (and clears) the current set of region
1274 /// constraints. The inference context is still usable: further
1275 /// unifications will simply add new constraints.
1277 /// This method is not meant to be used with normal lexical region
1278 /// resolution. Rather, it is used in the NLL mode as a kind of
1279 /// interim hack: basically we run normal type-check and generate
1280 /// region constraints as normal, but then we take them and
1281 /// translate them into the form that the NLL solver
1282 /// understands. See the NLL module for mode details.
1283 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1285 self.inner.borrow().region_obligations.is_empty(),
1286 "region_obligations not empty: {:#?}",
1287 self.inner.borrow().region_obligations
1290 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1293 /// Gives temporary access to the region constraint data.
1294 #[allow(non_camel_case_types)] // bug with impl trait
1295 pub fn with_region_constraints<R>(
1297 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1299 let mut inner = self.inner.borrow_mut();
1300 op(inner.unwrap_region_constraints().data())
1303 /// Takes ownership of the list of variable regions. This implies
1304 /// that all the region constraints have already been taken, and
1305 /// hence that `resolve_regions_and_report_errors` can never be
1306 /// called. This is used only during NLL processing to "hand off" ownership
1307 /// of the set of region variables into the NLL region context.
1308 pub fn take_region_var_origins(&self) -> VarInfos {
1309 let (var_infos, data) = self
1314 .expect("regions already resolved")
1315 .into_infos_and_data();
1316 assert!(data.is_empty());
1320 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1321 self.resolve_vars_if_possible(&t).to_string()
1324 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1325 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1326 format!("({})", tstrs.join(", "))
1329 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1330 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1333 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1334 /// universe index of `TyVar(vid)`.
1335 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1336 use self::type_variable::TypeVariableValue;
1338 match self.inner.borrow_mut().type_variables.probe(vid) {
1339 TypeVariableValue::Known { value } => Ok(value),
1340 TypeVariableValue::Unknown { universe } => Err(universe),
1344 /// Resolve any type variables found in `value` -- but only one
1345 /// level. So, if the variable `?X` is bound to some type
1346 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1347 /// itself be bound to a type).
1349 /// Useful when you only need to inspect the outermost level of
1350 /// the type and don't care about nested types (or perhaps you
1351 /// will be resolving them as well, e.g. in a loop).
1352 pub fn shallow_resolve<T>(&self, value: T) -> T
1354 T: TypeFoldable<'tcx>,
1356 value.fold_with(&mut ShallowResolver { infcx: self })
1359 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1360 self.inner.borrow_mut().type_variables.root_var(var)
1363 /// Where possible, replaces type/const variables in
1364 /// `value` with their final value. Note that region variables
1365 /// are unaffected. If a type/const variable has not been unified, it
1366 /// is left as is. This is an idempotent operation that does
1367 /// not affect inference state in any way and so you can do it
1369 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1371 T: TypeFoldable<'tcx>,
1373 if !value.needs_infer() {
1374 return value.clone(); // Avoid duplicated subst-folding.
1376 let mut r = resolve::OpportunisticVarResolver::new(self);
1377 value.fold_with(&mut r)
1380 /// Returns the first unresolved variable contained in `T`. In the
1381 /// process of visiting `T`, this will resolve (where possible)
1382 /// type variables in `T`, but it never constructs the final,
1383 /// resolved type, so it's more efficient than
1384 /// `resolve_vars_if_possible()`.
1385 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1387 T: TypeFoldable<'tcx>,
1389 let mut r = resolve::UnresolvedTypeFinder::new(self);
1390 value.visit_with(&mut r);
1394 pub fn probe_const_var(
1396 vid: ty::ConstVid<'tcx>,
1397 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1398 match self.inner.borrow_mut().const_unification_table.probe_value(vid).val {
1399 ConstVariableValue::Known { value } => Ok(value),
1400 ConstVariableValue::Unknown { universe } => Err(universe),
1404 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1406 * Attempts to resolve all type/region/const variables in
1407 * `value`. Region inference must have been run already (e.g.,
1408 * by calling `resolve_regions_and_report_errors`). If some
1409 * variable was never unified, an `Err` results.
1411 * This method is idempotent, but it not typically not invoked
1412 * except during the writeback phase.
1415 resolve::fully_resolve(self, value)
1418 // [Note-Type-error-reporting]
1419 // An invariant is that anytime the expected or actual type is Error (the special
1420 // error type, meaning that an error occurred when typechecking this expression),
1421 // this is a derived error. The error cascaded from another error (that was already
1422 // reported), so it's not useful to display it to the user.
1423 // The following methods implement this logic.
1424 // They check if either the actual or expected type is Error, and don't print the error
1425 // in this case. The typechecker should only ever report type errors involving mismatched
1426 // types using one of these methods, and should not call span_err directly for such
1429 pub fn type_error_struct_with_diag<M>(
1433 actual_ty: Ty<'tcx>,
1434 ) -> DiagnosticBuilder<'tcx>
1436 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1438 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1439 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1441 // Don't report an error if actual type is `Error`.
1442 if actual_ty.references_error() {
1443 return self.tcx.sess.diagnostic().struct_dummy();
1446 mk_diag(self.ty_to_string(actual_ty))
1449 pub fn report_mismatched_types(
1451 cause: &ObligationCause<'tcx>,
1454 err: TypeError<'tcx>,
1455 ) -> DiagnosticBuilder<'tcx> {
1456 let trace = TypeTrace::types(cause, true, expected, actual);
1457 self.report_and_explain_type_error(trace, &err)
1460 pub fn replace_bound_vars_with_fresh_vars<T>(
1463 lbrct: LateBoundRegionConversionTime,
1464 value: &ty::Binder<T>,
1465 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1467 T: TypeFoldable<'tcx>,
1469 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1471 self.next_ty_var(TypeVariableOrigin {
1472 kind: TypeVariableOriginKind::MiscVariable,
1476 let fld_c = |_, ty| {
1477 self.next_const_var(
1479 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1482 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1485 /// See the [`region_constraints::verify_generic_bound`] method.
1486 pub fn verify_generic_bound(
1488 origin: SubregionOrigin<'tcx>,
1489 kind: GenericKind<'tcx>,
1490 a: ty::Region<'tcx>,
1491 bound: VerifyBound<'tcx>,
1493 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1497 .unwrap_region_constraints()
1498 .verify_generic_bound(origin, kind, a, bound);
1501 /// Obtains the latest type of the given closure; this may be a
1502 /// closure in the current function, in which case its
1503 /// `ClosureKind` may not yet be known.
1504 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1505 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1506 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1507 closure_kind_ty.to_opt_closure_kind()
1510 /// Clears the selection, evaluation, and projection caches. This is useful when
1511 /// repeatedly attempting to select an `Obligation` while changing only
1512 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1513 pub fn clear_caches(&self) {
1514 self.selection_cache.clear();
1515 self.evaluation_cache.clear();
1516 self.inner.borrow_mut().projection_cache.clear();
1519 fn universe(&self) -> ty::UniverseIndex {
1523 /// Creates and return a fresh universe that extends all previous
1524 /// universes. Updates `self.universe` to that new universe.
1525 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1526 let u = self.universe.get().next_universe();
1527 self.universe.set(u);
1531 /// Resolves and evaluates a constant.
1533 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1534 /// substitutions and environment are used to resolve the constant. Alternatively if the
1535 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1536 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1537 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1538 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1541 /// This handles inferences variables within both `param_env` and `substs` by
1542 /// performing the operation on their respective canonical forms.
1543 pub fn const_eval_resolve(
1545 param_env: ty::ParamEnv<'tcx>,
1547 substs: SubstsRef<'tcx>,
1548 promoted: Option<mir::Promoted>,
1550 ) -> ConstEvalResult<'tcx> {
1551 let mut original_values = OriginalQueryValues::default();
1552 let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1554 let (param_env, substs) = canonical.value;
1555 // The return value is the evaluated value which doesn't contain any reference to inference
1556 // variables, thus we don't need to substitute back the original values.
1557 self.tcx.const_eval_resolve(param_env, def_id, substs, promoted, span)
1560 /// If `typ` is a type variable of some kind, resolve it one level
1561 /// (but do not resolve types found in the result). If `typ` is
1562 /// not a type variable, just return it unmodified.
1563 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1564 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1566 ty::Infer(ty::TyVar(v)) => {
1567 // Not entirely obvious: if `typ` is a type variable,
1568 // it can be resolved to an int/float variable, which
1569 // can then be recursively resolved, hence the
1570 // recursion. Note though that we prevent type
1571 // variables from unifying to other type variables
1572 // directly (though they may be embedded
1573 // structurally), and we prevent cycles in any case,
1574 // so this recursion should always be of very limited
1577 // Note: if these two lines are combined into one we get
1578 // dynamic borrow errors on `self.inner`.
1579 let known = self.inner.borrow_mut().type_variables.probe(v).known();
1580 known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
1583 ty::Infer(ty::IntVar(v)) => self
1586 .int_unification_table
1588 .map(|v| v.to_type(self.tcx))
1591 ty::Infer(ty::FloatVar(v)) => self
1594 .float_unification_table
1596 .map(|v| v.to_type(self.tcx))
1603 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1604 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1605 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1607 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1608 /// inlined, despite being large, because it has only two call sites that
1609 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1610 /// inference variables), and it handles both `Ty` and `ty::Const` without
1611 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1613 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1615 TyOrConstInferVar::Ty(v) => {
1616 use self::type_variable::TypeVariableValue;
1618 // If `inlined_probe` returns a `Known` value, it never equals
1619 // `ty::Infer(ty::TyVar(v))`.
1620 match self.inner.borrow_mut().type_variables.inlined_probe(v) {
1621 TypeVariableValue::Unknown { .. } => false,
1622 TypeVariableValue::Known { .. } => true,
1626 TyOrConstInferVar::TyInt(v) => {
1627 // If `inlined_probe_value` returns a value it's always a
1628 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1630 self.inner.borrow_mut().int_unification_table.inlined_probe_value(v).is_some()
1633 TyOrConstInferVar::TyFloat(v) => {
1634 // If `probe_value` returns a value it's always a
1635 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1637 // Not `inlined_probe_value(v)` because this call site is colder.
1638 self.inner.borrow_mut().float_unification_table.probe_value(v).is_some()
1641 TyOrConstInferVar::Const(v) => {
1642 // If `probe_value` returns a `Known` value, it never equals
1643 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1645 // Not `inlined_probe_value(v)` because this call site is colder.
1646 match self.inner.borrow_mut().const_unification_table.probe_value(v).val {
1647 ConstVariableValue::Unknown { .. } => false,
1648 ConstVariableValue::Known { .. } => true,
1655 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1656 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1657 #[derive(Copy, Clone, Debug)]
1658 pub enum TyOrConstInferVar<'tcx> {
1659 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1661 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1663 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1666 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1667 Const(ConstVid<'tcx>),
1670 impl TyOrConstInferVar<'tcx> {
1671 /// Tries to extract an inference variable from a type or a constant, returns `None`
1672 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1673 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1674 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1675 match arg.unpack() {
1676 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1677 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1678 GenericArgKind::Lifetime(_) => None,
1682 /// Tries to extract an inference variable from a type, returns `None`
1683 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1684 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1686 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1687 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1688 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1693 /// Tries to extract an inference variable from a constant, returns `None`
1694 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1695 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1697 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1703 struct ShallowResolver<'a, 'tcx> {
1704 infcx: &'a InferCtxt<'a, 'tcx>,
1707 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1708 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1712 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1713 self.infcx.shallow_resolve_ty(ty)
1716 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1717 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1721 .const_unification_table
1732 impl<'tcx> TypeTrace<'tcx> {
1733 pub fn span(&self) -> Span {
1738 cause: &ObligationCause<'tcx>,
1739 a_is_expected: bool,
1742 ) -> TypeTrace<'tcx> {
1743 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1746 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1748 cause: ObligationCause::dummy(),
1749 values: Types(ExpectedFound { expected: tcx.types.err, found: tcx.types.err }),
1754 impl<'tcx> SubregionOrigin<'tcx> {
1755 pub fn span(&self) -> Span {
1757 Subtype(ref a) => a.span(),
1758 InfStackClosure(a) => a,
1759 InvokeClosure(a) => a,
1760 DerefPointer(a) => a,
1761 ClosureCapture(a, _) => a,
1763 RelateObjectBound(a) => a,
1764 RelateParamBound(a, _) => a,
1765 RelateRegionParamBound(a) => a,
1766 RelateDefaultParamBound(a, _) => a,
1768 ReborrowUpvar(a, _) => a,
1769 DataBorrowed(_, a) => a,
1770 ReferenceOutlivesReferent(_, a) => a,
1771 ParameterInScope(_, a) => a,
1772 ExprTypeIsNotInScope(_, a) => a,
1773 BindingTypeIsNotValidAtDecl(a) => a,
1780 SafeDestructor(a) => a,
1781 CompareImplMethodObligation { span, .. } => span,
1785 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1787 F: FnOnce() -> Self,
1790 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1791 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1794 traits::ObligationCauseCode::CompareImplMethodObligation {
1798 } => SubregionOrigin::CompareImplMethodObligation {
1810 impl RegionVariableOrigin {
1811 pub fn span(&self) -> Span {
1813 MiscVariable(a) => a,
1814 PatternRegion(a) => a,
1815 AddrOfRegion(a) => a,
1818 EarlyBoundRegion(a, ..) => a,
1819 LateBoundRegion(a, ..) => a,
1820 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1821 UpvarRegion(_, a) => a,
1822 NLL(..) => bug!("NLL variable used with `span`"),
1827 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1828 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1831 "RegionObligation(sub_region={:?}, sup_type={:?})",
1832 self.sub_region, self.sup_type