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::snapshot_vec as sv;
14 use rustc_data_structures::sync::Lrc;
15 use rustc_data_structures::undo_log::{Rollback, Snapshots, UndoLogs};
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::middle::region;
24 use rustc_middle::mir;
25 use rustc_middle::mir::interpret::ConstEvalResult;
26 use rustc_middle::traits::select;
27 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
28 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
29 use rustc_middle::ty::relate::RelateResult;
30 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
31 pub use rustc_middle::ty::IntVarValue;
32 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
33 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
34 use rustc_session::config::BorrowckMode;
35 use rustc_span::symbol::Symbol;
38 use std::cell::{Cell, Ref, RefCell};
39 use std::collections::BTreeMap;
41 use std::marker::PhantomData;
43 use self::combine::CombineFields;
44 use self::free_regions::RegionRelations;
45 use self::lexical_region_resolve::LexicalRegionResolutions;
46 use self::outlives::env::OutlivesEnvironment;
47 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
48 use self::region_constraints::{
49 RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
51 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
57 pub mod error_reporting;
64 mod lexical_region_resolve;
68 pub mod region_constraints;
71 pub mod type_variable;
73 use crate::infer::canonical::OriginalQueryValues;
74 pub use rustc_middle::infer::unify_key;
78 pub struct InferOk<'tcx, T> {
80 pub obligations: PredicateObligations<'tcx>,
82 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
84 pub type Bound<T> = Option<T>;
85 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
86 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
88 /// How we should handle region solving.
90 /// This is used so that the region values inferred by HIR region solving are
91 /// not exposed, and so that we can avoid doing work in HIR typeck that MIR
92 /// typeck will also do.
93 #[derive(Copy, Clone, Debug)]
94 pub enum RegionckMode {
95 /// The default mode: report region errors, don't erase regions.
97 /// Erase the results of region after solving.
99 /// A flag that is used to suppress region errors, when we are doing
100 /// region checks that the NLL borrow checker will also do -- it might
102 suppress_errors: bool,
106 impl Default for RegionckMode {
107 fn default() -> Self {
113 pub fn suppressed(self) -> bool {
115 Self::Solve => false,
116 Self::Erase { suppress_errors } => suppress_errors,
120 /// Indicates that the MIR borrowck will repeat these region
121 /// checks, so we should ignore errors if NLL is (unconditionally)
123 pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
124 // FIXME(Centril): Once we actually remove `::Migrate` also make
125 // this always `true` and then proceed to eliminate the dead code.
126 match tcx.borrowck_mode() {
127 // If we're on Migrate mode, report AST region errors
128 BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
130 // If we're on MIR, don't report AST region errors as they should be reported by NLL
131 BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
136 /// This type contains all the things within `InferCtxt` that sit within a
137 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
138 /// operations are hot enough that we want only one call to `borrow_mut` per
139 /// call to `start_snapshot` and `rollback_to`.
140 pub struct InferCtxtInner<'tcx> {
141 /// Cache for projections. This cache is snapshotted along with the infcx.
143 /// Public so that `traits::project` can use it.
144 pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
146 /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
147 /// that might instantiate a general type variable have an order,
148 /// represented by its upper and lower bounds.
149 type_variables: type_variable::TypeVariableStorage<'tcx>,
151 /// Map from const parameter variable to the kind of const it represents.
152 const_unification_table: ut::UnificationStorage<ty::ConstVid<'tcx>>,
154 /// Map from integral variable to the kind of integer it represents.
155 int_unification_table: ut::UnificationStorage<ty::IntVid>,
157 /// Map from floating variable to the kind of float it represents.
158 float_unification_table: ut::UnificationStorage<ty::FloatVid>,
160 /// Tracks the set of region variables and the constraints between them.
161 /// This is initially `Some(_)` but when
162 /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
163 /// -- further attempts to perform unification, etc., may fail if new
164 /// region constraints would've been added.
165 region_constraints: Option<RegionConstraintStorage<'tcx>>,
167 /// A set of constraints that regionck must validate. Each
168 /// constraint has the form `T:'a`, meaning "some type `T` must
169 /// outlive the lifetime 'a". These constraints derive from
170 /// instantiated type parameters. So if you had a struct defined
173 /// struct Foo<T:'static> { ... }
175 /// then in some expression `let x = Foo { ... }` it will
176 /// instantiate the type parameter `T` with a fresh type `$0`. At
177 /// the same time, it will record a region obligation of
178 /// `$0:'static`. This will get checked later by regionck. (We
179 /// can't generally check these things right away because we have
180 /// to wait until types are resolved.)
182 /// These are stored in a map keyed to the id of the innermost
183 /// enclosing fn body / static initializer expression. This is
184 /// because the location where the obligation was incurred can be
185 /// relevant with respect to which sublifetime assumptions are in
186 /// place. The reason that we store under the fn-id, and not
187 /// something more fine-grained, is so that it is easier for
188 /// regionck to be sure that it has found *all* the region
189 /// obligations (otherwise, it's easy to fail to walk to a
190 /// particular node-id).
192 /// Before running `resolve_regions_and_report_errors`, the creator
193 /// of the inference context is expected to invoke
194 /// `process_region_obligations` (defined in `self::region_obligations`)
195 /// for each body-id in this map, which will process the
196 /// obligations within. This is expected to be done 'late enough'
197 /// that all type inference variables have been bound and so forth.
198 region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
200 undo_log: InferCtxtUndoLogs<'tcx>,
203 impl<'tcx> InferCtxtInner<'tcx> {
204 fn new() -> InferCtxtInner<'tcx> {
206 projection_cache: Default::default(),
207 type_variables: type_variable::TypeVariableStorage::new(),
208 undo_log: InferCtxtUndoLogs::default(),
209 const_unification_table: ut::UnificationStorage::new(),
210 int_unification_table: ut::UnificationStorage::new(),
211 float_unification_table: ut::UnificationStorage::new(),
212 region_constraints: Some(RegionConstraintStorage::new()),
213 region_obligations: vec![],
217 pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
218 &self.region_obligations
221 pub(crate) fn projection_cache(&mut self) -> traits::ProjectionCache<'tcx, '_> {
222 self.projection_cache.with_log(&mut self.undo_log)
225 fn type_variables(&mut self) -> type_variable::TypeVariableTable<'tcx, '_> {
226 self.type_variables.with_log(&mut self.undo_log)
229 fn int_unification_table(
231 ) -> ut::UnificationTable<
234 &mut ut::UnificationStorage<ty::IntVid>,
235 &mut InferCtxtUndoLogs<'tcx>,
238 ut::UnificationTable::with_log(&mut self.int_unification_table, &mut self.undo_log)
241 fn float_unification_table(
243 ) -> ut::UnificationTable<
246 &mut ut::UnificationStorage<ty::FloatVid>,
247 &mut InferCtxtUndoLogs<'tcx>,
250 ut::UnificationTable::with_log(&mut self.float_unification_table, &mut self.undo_log)
253 fn const_unification_table(
255 ) -> ut::UnificationTable<
258 &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
259 &mut InferCtxtUndoLogs<'tcx>,
262 ut::UnificationTable::with_log(&mut self.const_unification_table, &mut self.undo_log)
265 pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'tcx, '_> {
266 self.region_constraints
268 .expect("region constraints already solved")
269 .with_log(&mut self.undo_log)
273 pub struct Snapshot<'tcx> {
275 _marker: PhantomData<&'tcx ()>,
278 pub(crate) enum UndoLog<'tcx> {
279 TypeVariables(type_variable::UndoLog<'tcx>),
280 ConstUnificationTable(sv::UndoLog<ut::Delegate<ty::ConstVid<'tcx>>>),
281 IntUnificationTable(sv::UndoLog<ut::Delegate<ty::IntVid>>),
282 FloatUnificationTable(sv::UndoLog<ut::Delegate<ty::FloatVid>>),
283 RegionConstraintCollector(region_constraints::UndoLog<'tcx>),
284 RegionUnificationTable(sv::UndoLog<ut::Delegate<ty::RegionVid>>),
285 ProjectionCache(traits::UndoLog<'tcx>),
286 PushRegionObligation,
289 impl<'tcx> From<region_constraints::UndoLog<'tcx>> for UndoLog<'tcx> {
290 fn from(l: region_constraints::UndoLog<'tcx>) -> Self {
291 UndoLog::RegionConstraintCollector(l)
295 impl<'tcx> From<sv::UndoLog<ut::Delegate<type_variable::TyVidEqKey<'tcx>>>> for UndoLog<'tcx> {
296 fn from(l: sv::UndoLog<ut::Delegate<type_variable::TyVidEqKey<'tcx>>>) -> Self {
297 UndoLog::TypeVariables(type_variable::UndoLog::EqRelation(l))
301 impl<'tcx> From<sv::UndoLog<ut::Delegate<ty::TyVid>>> for UndoLog<'tcx> {
302 fn from(l: sv::UndoLog<ut::Delegate<ty::TyVid>>) -> Self {
303 UndoLog::TypeVariables(type_variable::UndoLog::SubRelation(l))
307 impl<'tcx> From<sv::UndoLog<type_variable::Delegate>> for UndoLog<'tcx> {
308 fn from(l: sv::UndoLog<type_variable::Delegate>) -> Self {
309 UndoLog::TypeVariables(type_variable::UndoLog::Values(l))
313 impl<'tcx> From<type_variable::Instantiate> for UndoLog<'tcx> {
314 fn from(l: type_variable::Instantiate) -> Self {
315 UndoLog::TypeVariables(type_variable::UndoLog::from(l))
319 impl From<type_variable::UndoLog<'tcx>> for UndoLog<'tcx> {
320 fn from(t: type_variable::UndoLog<'tcx>) -> Self {
321 Self::TypeVariables(t)
325 impl<'tcx> From<sv::UndoLog<ut::Delegate<ty::ConstVid<'tcx>>>> for UndoLog<'tcx> {
326 fn from(l: sv::UndoLog<ut::Delegate<ty::ConstVid<'tcx>>>) -> Self {
327 Self::ConstUnificationTable(l)
331 impl<'tcx> From<sv::UndoLog<ut::Delegate<ty::IntVid>>> for UndoLog<'tcx> {
332 fn from(l: sv::UndoLog<ut::Delegate<ty::IntVid>>) -> Self {
333 Self::IntUnificationTable(l)
337 impl<'tcx> From<sv::UndoLog<ut::Delegate<ty::FloatVid>>> for UndoLog<'tcx> {
338 fn from(l: sv::UndoLog<ut::Delegate<ty::FloatVid>>) -> Self {
339 Self::FloatUnificationTable(l)
343 impl<'tcx> From<sv::UndoLog<ut::Delegate<ty::RegionVid>>> for UndoLog<'tcx> {
344 fn from(l: sv::UndoLog<ut::Delegate<ty::RegionVid>>) -> Self {
345 Self::RegionUnificationTable(l)
349 impl<'tcx> From<traits::UndoLog<'tcx>> for UndoLog<'tcx> {
350 fn from(l: traits::UndoLog<'tcx>) -> Self {
351 Self::ProjectionCache(l)
355 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
356 ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
359 struct RollbackView<'tcx, 'a> {
360 type_variables: &'a mut type_variable::TypeVariableStorage<'tcx>,
361 const_unification_table: &'a mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
362 int_unification_table: &'a mut ut::UnificationStorage<ty::IntVid>,
363 float_unification_table: &'a mut ut::UnificationStorage<ty::FloatVid>,
364 region_constraints: &'a mut RegionConstraintStorage<'tcx>,
365 projection_cache: &'a mut traits::ProjectionCacheStorage<'tcx>,
366 region_obligations: &'a mut Vec<(hir::HirId, RegionObligation<'tcx>)>,
369 impl<'tcx> Rollback<UndoLog<'tcx>> for RollbackView<'tcx, '_> {
370 fn reverse(&mut self, undo: UndoLog<'tcx>) {
372 UndoLog::TypeVariables(undo) => self.type_variables.reverse(undo),
373 UndoLog::ConstUnificationTable(undo) => self.const_unification_table.reverse(undo),
374 UndoLog::IntUnificationTable(undo) => self.int_unification_table.reverse(undo),
375 UndoLog::FloatUnificationTable(undo) => self.float_unification_table.reverse(undo),
376 UndoLog::RegionConstraintCollector(undo) => self.region_constraints.reverse(undo),
377 UndoLog::RegionUnificationTable(undo) => {
378 self.region_constraints.unification_table.reverse(undo)
380 UndoLog::ProjectionCache(undo) => self.projection_cache.reverse(undo),
381 UndoLog::PushRegionObligation => {
382 self.region_obligations.pop();
388 pub(crate) struct InferCtxtUndoLogs<'tcx> {
389 logs: Vec<UndoLog<'tcx>>,
390 num_open_snapshots: usize,
393 impl Default for InferCtxtUndoLogs<'_> {
394 fn default() -> Self {
395 Self { logs: Default::default(), num_open_snapshots: Default::default() }
399 impl<'tcx, T> UndoLogs<T> for InferCtxtUndoLogs<'tcx>
401 UndoLog<'tcx>: From<T>,
403 fn num_open_snapshots(&self) -> usize {
404 self.num_open_snapshots
406 fn push(&mut self, undo: T) {
407 if self.in_snapshot() {
408 self.logs.push(undo.into())
411 fn clear(&mut self) {
413 self.num_open_snapshots = 0;
415 fn extend<J>(&mut self, undos: J)
418 J: IntoIterator<Item = T>,
420 if self.in_snapshot() {
421 self.logs.extend(undos.into_iter().map(UndoLog::from))
426 impl<'tcx> Snapshots<UndoLog<'tcx>> for InferCtxtUndoLogs<'tcx> {
427 type Snapshot = Snapshot<'tcx>;
428 fn actions_since_snapshot(&self, snapshot: &Self::Snapshot) -> &[UndoLog<'tcx>] {
429 &self.logs[snapshot.undo_len..]
432 fn start_snapshot(&mut self) -> Self::Snapshot {
433 self.num_open_snapshots += 1;
434 Snapshot { undo_len: self.logs.len(), _marker: PhantomData }
437 fn rollback_to<R>(&mut self, values: impl FnOnce() -> R, snapshot: Self::Snapshot)
439 R: Rollback<UndoLog<'tcx>>,
441 debug!("rollback_to({})", snapshot.undo_len);
442 self.assert_open_snapshot(&snapshot);
444 if self.logs.len() > snapshot.undo_len {
445 let mut values = values();
446 while self.logs.len() > snapshot.undo_len {
447 values.reverse(self.logs.pop().unwrap());
451 if self.num_open_snapshots == 1 {
452 // The root snapshot. It's safe to clear the undo log because
453 // there's no snapshot further out that we might need to roll back
455 assert!(snapshot.undo_len == 0);
459 self.num_open_snapshots -= 1;
462 fn commit(&mut self, snapshot: Self::Snapshot) {
463 debug!("commit({})", snapshot.undo_len);
465 if self.num_open_snapshots == 1 {
466 // The root snapshot. It's safe to clear the undo log because
467 // there's no snapshot further out that we might need to roll back
469 assert!(snapshot.undo_len == 0);
473 self.num_open_snapshots -= 1;
477 impl<'tcx> InferCtxtUndoLogs<'tcx> {
478 pub(crate) fn region_constraints(
481 ) -> impl Iterator<Item = &'_ region_constraints::UndoLog<'tcx>> + Clone {
482 self.logs[after..].iter().filter_map(|log| match log {
483 UndoLog::RegionConstraintCollector(log) => Some(log),
488 fn assert_open_snapshot(&self, snapshot: &Snapshot<'tcx>) {
489 // Failures here may indicate a failure to follow a stack discipline.
490 assert!(self.logs.len() >= snapshot.undo_len);
491 assert!(self.num_open_snapshots > 0);
495 pub struct InferCtxt<'a, 'tcx> {
496 pub tcx: TyCtxt<'tcx>,
498 /// During type-checking/inference of a body, `in_progress_tables`
499 /// contains a reference to the tables being built up, which are
500 /// used for reading closure kinds/signatures as they are inferred,
501 /// and for error reporting logic to read arbitrary node types.
502 pub in_progress_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>,
504 pub inner: RefCell<InferCtxtInner<'tcx>>,
506 /// If set, this flag causes us to skip the 'leak check' during
507 /// higher-ranked subtyping operations. This flag is a temporary one used
508 /// to manage the removal of the leak-check: for the time being, we still run the
509 /// leak-check, but we issue warnings. This flag can only be set to true
510 /// when entering a snapshot.
511 skip_leak_check: Cell<bool>,
513 /// Once region inference is done, the values for each variable.
514 lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
516 /// Caches the results of trait selection. This cache is used
517 /// for things that have to do with the parameters in scope.
518 pub selection_cache: select::SelectionCache<'tcx>,
520 /// Caches the results of trait evaluation.
521 pub evaluation_cache: select::EvaluationCache<'tcx>,
523 /// the set of predicates on which errors have been reported, to
524 /// avoid reporting the same error twice.
525 pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
527 pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
529 /// When an error occurs, we want to avoid reporting "derived"
530 /// errors that are due to this original failure. Normally, we
531 /// handle this with the `err_count_on_creation` count, which
532 /// basically just tracks how many errors were reported when we
533 /// started type-checking a fn and checks to see if any new errors
534 /// have been reported since then. Not great, but it works.
536 /// However, when errors originated in other passes -- notably
537 /// resolve -- this heuristic breaks down. Therefore, we have this
538 /// auxiliary flag that one can set whenever one creates a
539 /// type-error that is due to an error in a prior pass.
541 /// Don't read this flag directly, call `is_tainted_by_errors()`
542 /// and `set_tainted_by_errors()`.
543 tainted_by_errors_flag: Cell<bool>,
545 /// Track how many errors were reported when this infcx is created.
546 /// If the number of errors increases, that's also a sign (line
547 /// `tained_by_errors`) to avoid reporting certain kinds of errors.
548 // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
549 err_count_on_creation: usize,
551 /// This flag is true while there is an active snapshot.
552 in_snapshot: Cell<bool>,
554 /// What is the innermost universe we have created? Starts out as
555 /// `UniverseIndex::root()` but grows from there as we enter
556 /// universal quantifiers.
558 /// N.B., at present, we exclude the universal quantifiers on the
559 /// item we are type-checking, and just consider those names as
560 /// part of the root universe. So this would only get incremented
561 /// when we enter into a higher-ranked (`for<..>`) type or trait
563 universe: Cell<ty::UniverseIndex>,
566 /// A map returned by `replace_bound_vars_with_placeholders()`
567 /// indicating the placeholder region that each late-bound region was
569 pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
571 /// See the `error_reporting` module for more details.
572 #[derive(Clone, Debug, PartialEq, Eq, TypeFoldable)]
573 pub enum ValuePairs<'tcx> {
574 Types(ExpectedFound<Ty<'tcx>>),
575 Regions(ExpectedFound<ty::Region<'tcx>>),
576 Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
577 TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
578 PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
581 /// The trace designates the path through inference that we took to
582 /// encounter an error or subtyping constraint.
584 /// See the `error_reporting` module for more details.
585 #[derive(Clone, Debug)]
586 pub struct TypeTrace<'tcx> {
587 cause: ObligationCause<'tcx>,
588 values: ValuePairs<'tcx>,
591 /// The origin of a `r1 <= r2` constraint.
593 /// See `error_reporting` module for more details
594 #[derive(Clone, Debug)]
595 pub enum SubregionOrigin<'tcx> {
596 /// Arose from a subtyping relation
597 Subtype(Box<TypeTrace<'tcx>>),
599 /// Stack-allocated closures cannot outlive innermost loop
600 /// or function so as to ensure we only require finite stack
601 InfStackClosure(Span),
603 /// Invocation of closure must be within its lifetime
606 /// Dereference of reference must be within its lifetime
609 /// Closure bound must not outlive captured variables
610 ClosureCapture(Span, hir::HirId),
612 /// Index into slice must be within its lifetime
615 /// When casting `&'a T` to an `&'b Trait` object,
616 /// relating `'a` to `'b`
617 RelateObjectBound(Span),
619 /// Some type parameter was instantiated with the given type,
620 /// and that type must outlive some region.
621 RelateParamBound(Span, Ty<'tcx>),
623 /// The given region parameter was instantiated with a region
624 /// that must outlive some other region.
625 RelateRegionParamBound(Span),
627 /// A bound placed on type parameters that states that must outlive
628 /// the moment of their instantiation.
629 RelateDefaultParamBound(Span, Ty<'tcx>),
631 /// Creating a pointer `b` to contents of another reference
634 /// Creating a pointer `b` to contents of an upvar
635 ReborrowUpvar(Span, ty::UpvarId),
637 /// Data with type `Ty<'tcx>` was borrowed
638 DataBorrowed(Ty<'tcx>, Span),
640 /// (&'a &'b T) where a >= b
641 ReferenceOutlivesReferent(Ty<'tcx>, Span),
643 /// Type or region parameters must be in scope.
644 ParameterInScope(ParameterOrigin, Span),
646 /// The type T of an expression E must outlive the lifetime for E.
647 ExprTypeIsNotInScope(Ty<'tcx>, Span),
649 /// A `ref b` whose region does not enclose the decl site
650 BindingTypeIsNotValidAtDecl(Span),
652 /// Regions appearing in a method receiver must outlive method call
655 /// Regions appearing in a function argument must outlive func call
658 /// Region in return type of invoked fn must enclose call
661 /// Operands must be in scope
664 /// Region resulting from a `&` expr must enclose the `&` expr
667 /// An auto-borrow that does not enclose the expr where it occurs
670 /// Region constraint arriving from destructor safety
671 SafeDestructor(Span),
673 /// Comparing the signature and requirements of an impl method against
674 /// the containing trait.
675 CompareImplMethodObligation {
677 item_name: ast::Name,
678 impl_item_def_id: DefId,
679 trait_item_def_id: DefId,
683 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
684 #[cfg(target_arch = "x86_64")]
685 static_assert_size!(SubregionOrigin<'_>, 32);
687 /// Places that type/region parameters can appear.
688 #[derive(Clone, Copy, Debug)]
689 pub enum ParameterOrigin {
691 MethodCall, // foo.bar() <-- parameters on impl providing bar()
692 OverloadedOperator, // a + b when overloaded
693 OverloadedDeref, // *a when overloaded
696 /// Times when we replace late-bound regions with variables:
697 #[derive(Clone, Copy, Debug)]
698 pub enum LateBoundRegionConversionTime {
699 /// when a fn is called
702 /// when two higher-ranked types are compared
705 /// when projecting an associated type
706 AssocTypeProjection(DefId),
709 /// Reasons to create a region inference variable
711 /// See `error_reporting` module for more details
712 #[derive(Copy, Clone, Debug)]
713 pub enum RegionVariableOrigin {
714 /// Region variables created for ill-categorized reasons,
715 /// mostly indicates places in need of refactoring
718 /// Regions created by a `&P` or `[...]` pattern
721 /// Regions created by `&` operator
724 /// Regions created as part of an autoref of a method receiver
727 /// Regions created as part of an automatic coercion
730 /// Region variables created as the values for early-bound regions
731 EarlyBoundRegion(Span, Symbol),
733 /// Region variables created for bound regions
734 /// in a function or method that is called
735 LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
737 UpvarRegion(ty::UpvarId, Span),
739 BoundRegionInCoherence(ast::Name),
741 /// This origin is used for the inference variables that we create
742 /// during NLL region processing.
743 NLL(NLLRegionVariableOrigin),
746 #[derive(Copy, Clone, Debug)]
747 pub enum NLLRegionVariableOrigin {
748 /// During NLL region processing, we create variables for free
749 /// regions that we encounter in the function signature and
750 /// elsewhere. This origin indices we've got one of those.
753 /// "Universal" instantiation of a higher-ranked region (e.g.,
754 /// from a `for<'a> T` binder). Meant to represent "any region".
755 Placeholder(ty::PlaceholderRegion),
757 /// The variable we create to represent `'empty(U0)`.
761 /// If this is true, then this variable was created to represent a lifetime
762 /// bound in a `for` binder. For example, it might have been created to
763 /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
764 /// Such variables are created when we are trying to figure out if there
765 /// is any valid instantiation of `'a` that could fit into some scenario.
767 /// This is used to inform error reporting: in the case that we are trying to
768 /// determine whether there is any valid instantiation of a `'a` variable that meets
769 /// some constraint C, we want to blame the "source" of that `for` type,
770 /// rather than blaming the source of the constraint C.
775 impl NLLRegionVariableOrigin {
776 pub fn is_universal(self) -> bool {
778 NLLRegionVariableOrigin::FreeRegion => true,
779 NLLRegionVariableOrigin::Placeholder(..) => true,
780 NLLRegionVariableOrigin::Existential { .. } => false,
781 NLLRegionVariableOrigin::RootEmptyRegion => false,
785 pub fn is_existential(self) -> bool {
790 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
791 #[derive(Copy, Clone, Debug)]
792 pub enum FixupError<'tcx> {
793 UnresolvedIntTy(IntVid),
794 UnresolvedFloatTy(FloatVid),
796 UnresolvedConst(ConstVid<'tcx>),
799 /// See the `region_obligations` field for more information.
801 pub struct RegionObligation<'tcx> {
802 pub sub_region: ty::Region<'tcx>,
803 pub sup_type: Ty<'tcx>,
804 pub origin: SubregionOrigin<'tcx>,
807 impl<'tcx> fmt::Display for FixupError<'tcx> {
808 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
809 use self::FixupError::*;
812 UnresolvedIntTy(_) => write!(
814 "cannot determine the type of this integer; \
815 add a suffix to specify the type explicitly"
817 UnresolvedFloatTy(_) => write!(
819 "cannot determine the type of this number; \
820 add a suffix to specify the type explicitly"
822 UnresolvedTy(_) => write!(f, "unconstrained type"),
823 UnresolvedConst(_) => write!(f, "unconstrained const value"),
828 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
829 /// Necessary because we can't write the following bound:
830 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
831 pub struct InferCtxtBuilder<'tcx> {
832 global_tcx: TyCtxt<'tcx>,
833 fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
836 pub trait TyCtxtInferExt<'tcx> {
837 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
840 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
841 fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
842 InferCtxtBuilder { global_tcx: self, fresh_tables: None }
846 impl<'tcx> InferCtxtBuilder<'tcx> {
847 /// Used only by `rustc_typeck` during body type-checking/inference,
848 /// will initialize `in_progress_tables` with fresh `TypeckTables`.
849 pub fn with_fresh_in_progress_tables(mut self, table_owner: LocalDefId) -> Self {
850 self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner))));
854 /// Given a canonical value `C` as a starting point, create an
855 /// inference context that contains each of the bound values
856 /// within instantiated as a fresh variable. The `f` closure is
857 /// invoked with the new infcx, along with the instantiated value
858 /// `V` and a substitution `S`. This substitution `S` maps from
859 /// the bound values in `C` to their instantiated values in `V`
860 /// (in other words, `S(C) = V`).
861 pub fn enter_with_canonical<T, R>(
864 canonical: &Canonical<'tcx, T>,
865 f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
868 T: TypeFoldable<'tcx>,
872 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
873 f(infcx, value, subst)
877 pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
878 let InferCtxtBuilder { global_tcx, ref fresh_tables } = *self;
879 let in_progress_tables = fresh_tables.as_ref();
880 global_tcx.enter_local(|tcx| {
884 inner: RefCell::new(InferCtxtInner::new()),
885 lexical_region_resolutions: RefCell::new(None),
886 selection_cache: Default::default(),
887 evaluation_cache: Default::default(),
888 reported_trait_errors: Default::default(),
889 reported_closure_mismatch: Default::default(),
890 tainted_by_errors_flag: Cell::new(false),
891 err_count_on_creation: tcx.sess.err_count(),
892 in_snapshot: Cell::new(false),
893 skip_leak_check: Cell::new(false),
894 universe: Cell::new(ty::UniverseIndex::ROOT),
900 impl<'tcx, T> InferOk<'tcx, T> {
901 pub fn unit(self) -> InferOk<'tcx, ()> {
902 InferOk { value: (), obligations: self.obligations }
905 /// Extracts `value`, registering any obligations into `fulfill_cx`.
906 pub fn into_value_registering_obligations(
908 infcx: &InferCtxt<'_, 'tcx>,
909 fulfill_cx: &mut dyn TraitEngine<'tcx>,
911 let InferOk { value, obligations } = self;
912 for obligation in obligations {
913 fulfill_cx.register_predicate_obligation(infcx, obligation);
919 impl<'tcx> InferOk<'tcx, ()> {
920 pub fn into_obligations(self) -> PredicateObligations<'tcx> {
925 #[must_use = "once you start a snapshot, you should always consume it"]
926 pub struct FullSnapshot<'a, 'tcx> {
927 snapshot: CombinedSnapshot<'a, 'tcx>,
928 region_constraints_snapshot: RegionSnapshot,
929 type_snapshot: type_variable::Snapshot<'tcx>,
930 const_snapshot: usize,
932 float_snapshot: usize,
935 #[must_use = "once you start a snapshot, you should always consume it"]
936 pub struct CombinedSnapshot<'a, 'tcx> {
937 undo_snapshot: Snapshot<'tcx>,
938 universe: ty::UniverseIndex,
939 was_in_snapshot: bool,
940 _in_progress_tables: Option<Ref<'a, ty::TypeckTables<'tcx>>>,
943 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
944 pub fn is_in_snapshot(&self) -> bool {
945 self.in_snapshot.get()
948 pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
949 t.fold_with(&mut self.freshener())
952 pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
954 ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
959 pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
960 freshen::TypeFreshener::new(self)
963 pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
964 use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
965 use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
967 ty::Infer(ty::IntVar(vid)) => {
968 if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
974 ty::Infer(ty::FloatVar(vid)) => {
975 if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
985 pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
986 let mut inner = self.inner.borrow_mut();
987 // FIXME(const_generics): should there be an equivalent function for const variables?
989 let mut vars: Vec<Ty<'_>> = inner
991 .unsolved_variables()
993 .map(|t| self.tcx.mk_ty_var(t))
996 (0..inner.int_unification_table().len())
997 .map(|i| ty::IntVid { index: i as u32 })
998 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
999 .map(|v| self.tcx.mk_int_var(v)),
1002 (0..inner.float_unification_table().len())
1003 .map(|i| ty::FloatVid { index: i as u32 })
1004 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
1005 .map(|v| self.tcx.mk_float_var(v)),
1012 trace: TypeTrace<'tcx>,
1013 param_env: ty::ParamEnv<'tcx>,
1014 ) -> CombineFields<'a, 'tcx> {
1020 obligations: PredicateObligations::new(),
1024 /// Clear the "currently in a snapshot" flag, invoke the closure,
1025 /// then restore the flag to its original value. This flag is a
1026 /// debugging measure designed to detect cases where we start a
1027 /// snapshot, create type variables, and register obligations
1028 /// which may involve those type variables in the fulfillment cx,
1029 /// potentially leaving "dangling type variables" behind.
1030 /// In such cases, an assertion will fail when attempting to
1031 /// register obligations, within a snapshot. Very useful, much
1032 /// better than grovelling through megabytes of `RUSTC_LOG` output.
1034 /// HOWEVER, in some cases the flag is unhelpful. In particular, we
1035 /// sometimes create a "mini-fulfilment-cx" in which we enroll
1036 /// obligations. As long as this fulfillment cx is fully drained
1037 /// before we return, this is not a problem, as there won't be any
1038 /// escaping obligations in the main cx. In those cases, you can
1039 /// use this function.
1040 pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
1042 F: FnOnce(&Self) -> R,
1044 let flag = self.in_snapshot.replace(false);
1045 let result = func(self);
1046 self.in_snapshot.set(flag);
1050 fn start_full_snapshot(&self) -> FullSnapshot<'a, 'tcx> {
1051 let snapshot = self.start_snapshot();
1052 let mut inner = self.inner.borrow_mut();
1055 type_snapshot: inner.type_variables().snapshot(),
1056 const_snapshot: inner.const_unification_table().len(),
1057 int_snapshot: inner.int_unification_table().len(),
1058 float_snapshot: inner.float_unification_table().len(),
1059 region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
1063 fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
1064 debug!("start_snapshot()");
1066 let in_snapshot = self.in_snapshot.replace(true);
1068 let mut inner = self.inner.borrow_mut();
1071 undo_snapshot: inner.undo_log.start_snapshot(),
1072 universe: self.universe(),
1073 was_in_snapshot: in_snapshot,
1074 // Borrow tables "in progress" (i.e., during typeck)
1075 // to ban writes from within a snapshot to them.
1076 _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()),
1080 fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
1081 debug!("rollback_to(cause={})", cause);
1082 let CombinedSnapshot { undo_snapshot, universe, was_in_snapshot, _in_progress_tables } =
1085 self.in_snapshot.set(was_in_snapshot);
1086 self.universe.set(universe);
1088 let InferCtxtInner {
1090 const_unification_table,
1091 int_unification_table,
1092 float_unification_table,
1098 } = &mut *self.inner.borrow_mut();
1099 undo_log.rollback_to(
1102 const_unification_table,
1103 int_unification_table,
1104 float_unification_table,
1105 region_constraints: region_constraints.as_mut().unwrap(),
1113 fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
1114 debug!("commit_from()");
1115 let CombinedSnapshot { undo_snapshot, universe: _, was_in_snapshot, _in_progress_tables } =
1118 self.in_snapshot.set(was_in_snapshot);
1120 let mut inner = self.inner.borrow_mut();
1121 inner.undo_log.commit(undo_snapshot);
1124 /// Executes `f` and commit the bindings.
1125 pub fn commit_unconditionally<R, F>(&self, f: F) -> R
1127 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
1129 debug!("commit_unconditionally()");
1130 let snapshot = self.start_snapshot();
1131 let r = f(&snapshot);
1132 self.commit_from(snapshot);
1136 /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
1137 pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
1139 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
1141 debug!("commit_if_ok()");
1142 let snapshot = self.start_snapshot();
1143 let r = f(&snapshot);
1144 debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
1147 self.commit_from(snapshot);
1150 self.rollback_to("commit_if_ok -- error", snapshot);
1156 /// Execute `f` then unroll any bindings it creates.
1157 pub fn probe<R, F>(&self, f: F) -> R
1159 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
1162 let snapshot = self.start_snapshot();
1163 let r = f(&snapshot);
1164 self.rollback_to("probe", snapshot);
1168 pub fn probe_full<R, F>(&self, f: F) -> R
1170 F: FnOnce(&FullSnapshot<'a, 'tcx>) -> R,
1173 let snapshot = self.start_full_snapshot();
1174 let r = f(&snapshot);
1175 self.rollback_to("probe", snapshot.snapshot);
1179 /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
1180 pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
1182 F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
1185 let snapshot = self.start_snapshot();
1186 let was_skip_leak_check = self.skip_leak_check.get();
1188 self.skip_leak_check.set(true);
1190 let r = f(&snapshot);
1191 self.rollback_to("probe", snapshot);
1192 self.skip_leak_check.set(was_skip_leak_check);
1196 /// Scan the constraints produced since `snapshot` began and returns:
1198 /// - `None` -- if none of them involve "region outlives" constraints
1199 /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
1200 /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
1201 pub fn region_constraints_added_in_snapshot(
1203 snapshot: &CombinedSnapshot<'a, 'tcx>,
1207 .unwrap_region_constraints()
1208 .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
1211 pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
1212 self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
1215 pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
1217 T: at::ToTrace<'tcx>,
1219 let origin = &ObligationCause::dummy();
1221 self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
1222 // Ignore obligations, since we are unrolling
1223 // everything anyway.
1228 pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
1230 T: at::ToTrace<'tcx>,
1232 let origin = &ObligationCause::dummy();
1234 self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
1235 // Ignore obligations, since we are unrolling
1236 // everything anyway.
1243 origin: SubregionOrigin<'tcx>,
1244 a: ty::Region<'tcx>,
1245 b: ty::Region<'tcx>,
1247 debug!("sub_regions({:?} <: {:?})", a, b);
1248 self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
1251 /// Require that the region `r` be equal to one of the regions in
1252 /// the set `regions`.
1253 pub fn member_constraint(
1255 opaque_type_def_id: DefId,
1256 definition_span: Span,
1257 hidden_ty: Ty<'tcx>,
1258 region: ty::Region<'tcx>,
1259 in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
1261 debug!("member_constraint({:?} <: {:?})", region, in_regions);
1262 self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
1271 pub fn subtype_predicate(
1273 cause: &ObligationCause<'tcx>,
1274 param_env: ty::ParamEnv<'tcx>,
1275 predicate: &ty::PolySubtypePredicate<'tcx>,
1276 ) -> Option<InferResult<'tcx, ()>> {
1277 // Subtle: it's ok to skip the binder here and resolve because
1278 // `shallow_resolve` just ignores anything that is not a type
1279 // variable, and because type variable's can't (at present, at
1280 // least) capture any of the things bound by this binder.
1282 // NOTE(nmatsakis): really, there is no *particular* reason to do this
1283 // `shallow_resolve` here except as a micro-optimization.
1284 // Naturally I could not resist.
1285 let two_unbound_type_vars = {
1286 let a = self.shallow_resolve(predicate.skip_binder().a);
1287 let b = self.shallow_resolve(predicate.skip_binder().b);
1288 a.is_ty_var() && b.is_ty_var()
1291 if two_unbound_type_vars {
1292 // Two unbound type variables? Can't make progress.
1296 Some(self.commit_if_ok(|snapshot| {
1297 let (ty::SubtypePredicate { a_is_expected, a, b }, placeholder_map) =
1298 self.replace_bound_vars_with_placeholders(predicate);
1300 let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
1302 self.leak_check(false, &placeholder_map, snapshot)?;
1308 pub fn region_outlives_predicate(
1310 cause: &traits::ObligationCause<'tcx>,
1311 predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
1312 ) -> UnitResult<'tcx> {
1313 self.commit_if_ok(|snapshot| {
1314 let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
1315 self.replace_bound_vars_with_placeholders(predicate);
1316 let origin = SubregionOrigin::from_obligation_cause(cause, || {
1317 RelateRegionParamBound(cause.span)
1319 self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1320 self.leak_check(false, &placeholder_map, snapshot)?;
1325 pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1326 self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
1329 pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1330 self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
1333 pub fn next_ty_var_in_universe(
1335 origin: TypeVariableOrigin,
1336 universe: ty::UniverseIndex,
1338 let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
1339 self.tcx.mk_ty_var(vid)
1342 pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1343 self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
1346 pub fn next_const_var(
1349 origin: ConstVariableOrigin,
1350 ) -> &'tcx ty::Const<'tcx> {
1351 self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1354 pub fn next_const_var_in_universe(
1357 origin: ConstVariableOrigin,
1358 universe: ty::UniverseIndex,
1359 ) -> &'tcx ty::Const<'tcx> {
1363 .const_unification_table()
1364 .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1365 self.tcx.mk_const_var(vid, ty)
1368 pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1369 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1371 val: ConstVariableValue::Unknown { universe: self.universe() },
1375 fn next_int_var_id(&self) -> IntVid {
1376 self.inner.borrow_mut().int_unification_table().new_key(None)
1379 pub fn next_int_var(&self) -> Ty<'tcx> {
1380 self.tcx.mk_int_var(self.next_int_var_id())
1383 fn next_float_var_id(&self) -> FloatVid {
1384 self.inner.borrow_mut().float_unification_table().new_key(None)
1387 pub fn next_float_var(&self) -> Ty<'tcx> {
1388 self.tcx.mk_float_var(self.next_float_var_id())
1391 /// Creates a fresh region variable with the next available index.
1392 /// The variable will be created in the maximum universe created
1393 /// thus far, allowing it to name any region created thus far.
1394 pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1395 self.next_region_var_in_universe(origin, self.universe())
1398 /// Creates a fresh region variable with the next available index
1399 /// in the given universe; typically, you can use
1400 /// `next_region_var` and just use the maximal universe.
1401 pub fn next_region_var_in_universe(
1403 origin: RegionVariableOrigin,
1404 universe: ty::UniverseIndex,
1405 ) -> ty::Region<'tcx> {
1407 self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1408 self.tcx.mk_region(ty::ReVar(region_var))
1411 /// Return the universe that the region `r` was created in. For
1412 /// most regions (e.g., `'static`, named regions from the user,
1413 /// etc) this is the root universe U0. For inference variables or
1414 /// placeholders, however, it will return the universe which which
1415 /// they are associated.
1416 fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1417 self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1420 /// Number of region variables created so far.
1421 pub fn num_region_vars(&self) -> usize {
1422 self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1425 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1426 pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
1427 self.next_region_var(RegionVariableOrigin::NLL(origin))
1430 /// Just a convenient wrapper of `next_region_var` for using during NLL.
1431 pub fn next_nll_region_var_in_universe(
1433 origin: NLLRegionVariableOrigin,
1434 universe: ty::UniverseIndex,
1435 ) -> ty::Region<'tcx> {
1436 self.next_region_var_in_universe(RegionVariableOrigin::NLL(origin), universe)
1439 pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1441 GenericParamDefKind::Lifetime => {
1442 // Create a region inference variable for the given
1443 // region parameter definition.
1444 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1446 GenericParamDefKind::Type { .. } => {
1447 // Create a type inference variable for the given
1448 // type parameter definition. The substitutions are
1449 // for actual parameters that may be referred to by
1450 // the default of this type parameter, if it exists.
1451 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1452 // used in a path such as `Foo::<T, U>::new()` will
1453 // use an inference variable for `C` with `[T, U]`
1454 // as the substitutions for the default, `(T, U)`.
1455 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1458 TypeVariableOrigin {
1459 kind: TypeVariableOriginKind::TypeParameterDefinition(
1467 self.tcx.mk_ty_var(ty_var_id).into()
1469 GenericParamDefKind::Const { .. } => {
1470 let origin = ConstVariableOrigin {
1471 kind: ConstVariableOriginKind::ConstParameterDefinition(param.name),
1475 self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1477 val: ConstVariableValue::Unknown { universe: self.universe() },
1479 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1484 /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1485 /// type/region parameter to a fresh inference variable.
1486 pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1487 InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1490 /// Returns `true` if errors have been reported since this infcx was
1491 /// created. This is sometimes used as a heuristic to skip
1492 /// reporting errors that often occur as a result of earlier
1493 /// errors, but where it's hard to be 100% sure (e.g., unresolved
1494 /// inference variables, regionck errors).
1495 pub fn is_tainted_by_errors(&self) -> bool {
1497 "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1498 tainted_by_errors_flag={})",
1499 self.tcx.sess.err_count(),
1500 self.err_count_on_creation,
1501 self.tainted_by_errors_flag.get()
1504 if self.tcx.sess.err_count() > self.err_count_on_creation {
1505 return true; // errors reported since this infcx was made
1507 self.tainted_by_errors_flag.get()
1510 /// Set the "tainted by errors" flag to true. We call this when we
1511 /// observe an error from a prior pass.
1512 pub fn set_tainted_by_errors(&self) {
1513 debug!("set_tainted_by_errors()");
1514 self.tainted_by_errors_flag.set(true)
1517 /// Process the region constraints and report any errors that
1518 /// result. After this, no more unification operations should be
1519 /// done -- or the compiler will panic -- but it is legal to use
1520 /// `resolve_vars_if_possible` as well as `fully_resolve`.
1521 pub fn resolve_regions_and_report_errors(
1523 region_context: DefId,
1524 region_map: ®ion::ScopeTree,
1525 outlives_env: &OutlivesEnvironment<'tcx>,
1529 self.is_tainted_by_errors() || self.inner.borrow().region_obligations.is_empty(),
1530 "region_obligations not empty: {:#?}",
1531 self.inner.borrow().region_obligations
1533 let (var_infos, data) = self
1538 .expect("regions already resolved")
1539 .with_log(&mut inner.undo_log)
1540 .into_infos_and_data();
1542 let region_rels = &RegionRelations::new(
1546 outlives_env.free_region_map(),
1549 let (lexical_region_resolutions, errors) =
1550 lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1552 let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1553 assert!(old_value.is_none());
1555 if !self.is_tainted_by_errors() {
1556 // As a heuristic, just skip reporting region errors
1557 // altogether if other errors have been reported while
1558 // this infcx was in use. This is totally hokey but
1559 // otherwise we have a hard time separating legit region
1560 // errors from silly ones.
1561 self.report_region_errors(region_map, &errors);
1565 /// Obtains (and clears) the current set of region
1566 /// constraints. The inference context is still usable: further
1567 /// unifications will simply add new constraints.
1569 /// This method is not meant to be used with normal lexical region
1570 /// resolution. Rather, it is used in the NLL mode as a kind of
1571 /// interim hack: basically we run normal type-check and generate
1572 /// region constraints as normal, but then we take them and
1573 /// translate them into the form that the NLL solver
1574 /// understands. See the NLL module for mode details.
1575 pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1577 self.inner.borrow().region_obligations.is_empty(),
1578 "region_obligations not empty: {:#?}",
1579 self.inner.borrow().region_obligations
1582 self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1585 /// Gives temporary access to the region constraint data.
1586 #[allow(non_camel_case_types)] // bug with impl trait
1587 pub fn with_region_constraints<R>(
1589 op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1591 let mut inner = self.inner.borrow_mut();
1592 op(inner.unwrap_region_constraints().data())
1595 /// Takes ownership of the list of variable regions. This implies
1596 /// that all the region constraints have already been taken, and
1597 /// hence that `resolve_regions_and_report_errors` can never be
1598 /// called. This is used only during NLL processing to "hand off" ownership
1599 /// of the set of region variables into the NLL region context.
1600 pub fn take_region_var_origins(&self) -> VarInfos {
1601 let mut inner = self.inner.borrow_mut();
1602 let (var_infos, data) = inner
1605 .expect("regions already resolved")
1606 .with_log(&mut inner.undo_log)
1607 .into_infos_and_data();
1608 assert!(data.is_empty());
1612 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1613 self.resolve_vars_if_possible(&t).to_string()
1616 pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1617 let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1618 format!("({})", tstrs.join(", "))
1621 pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1622 self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1625 /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1626 /// universe index of `TyVar(vid)`.
1627 pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1628 use self::type_variable::TypeVariableValue;
1630 match self.inner.borrow_mut().type_variables().probe(vid) {
1631 TypeVariableValue::Known { value } => Ok(value),
1632 TypeVariableValue::Unknown { universe } => Err(universe),
1636 /// Resolve any type variables found in `value` -- but only one
1637 /// level. So, if the variable `?X` is bound to some type
1638 /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1639 /// itself be bound to a type).
1641 /// Useful when you only need to inspect the outermost level of
1642 /// the type and don't care about nested types (or perhaps you
1643 /// will be resolving them as well, e.g. in a loop).
1644 pub fn shallow_resolve<T>(&self, value: T) -> T
1646 T: TypeFoldable<'tcx>,
1648 value.fold_with(&mut ShallowResolver { infcx: self })
1651 pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1652 self.inner.borrow_mut().type_variables().root_var(var)
1655 /// Where possible, replaces type/const variables in
1656 /// `value` with their final value. Note that region variables
1657 /// are unaffected. If a type/const variable has not been unified, it
1658 /// is left as is. This is an idempotent operation that does
1659 /// not affect inference state in any way and so you can do it
1661 pub fn resolve_vars_if_possible<T>(&self, value: &T) -> T
1663 T: TypeFoldable<'tcx>,
1665 if !value.needs_infer() {
1666 return value.clone(); // Avoid duplicated subst-folding.
1668 let mut r = resolve::OpportunisticVarResolver::new(self);
1669 value.fold_with(&mut r)
1672 /// Returns the first unresolved variable contained in `T`. In the
1673 /// process of visiting `T`, this will resolve (where possible)
1674 /// type variables in `T`, but it never constructs the final,
1675 /// resolved type, so it's more efficient than
1676 /// `resolve_vars_if_possible()`.
1677 pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1679 T: TypeFoldable<'tcx>,
1681 let mut r = resolve::UnresolvedTypeFinder::new(self);
1682 value.visit_with(&mut r);
1686 pub fn probe_const_var(
1688 vid: ty::ConstVid<'tcx>,
1689 ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1690 match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1691 ConstVariableValue::Known { value } => Ok(value),
1692 ConstVariableValue::Unknown { universe } => Err(universe),
1696 pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<'tcx, T> {
1698 * Attempts to resolve all type/region/const variables in
1699 * `value`. Region inference must have been run already (e.g.,
1700 * by calling `resolve_regions_and_report_errors`). If some
1701 * variable was never unified, an `Err` results.
1703 * This method is idempotent, but it not typically not invoked
1704 * except during the writeback phase.
1707 resolve::fully_resolve(self, value)
1710 // [Note-Type-error-reporting]
1711 // An invariant is that anytime the expected or actual type is Error (the special
1712 // error type, meaning that an error occurred when typechecking this expression),
1713 // this is a derived error. The error cascaded from another error (that was already
1714 // reported), so it's not useful to display it to the user.
1715 // The following methods implement this logic.
1716 // They check if either the actual or expected type is Error, and don't print the error
1717 // in this case. The typechecker should only ever report type errors involving mismatched
1718 // types using one of these methods, and should not call span_err directly for such
1721 pub fn type_error_struct_with_diag<M>(
1725 actual_ty: Ty<'tcx>,
1726 ) -> DiagnosticBuilder<'tcx>
1728 M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1730 let actual_ty = self.resolve_vars_if_possible(&actual_ty);
1731 debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1733 // Don't report an error if actual type is `Error`.
1734 if actual_ty.references_error() {
1735 return self.tcx.sess.diagnostic().struct_dummy();
1738 mk_diag(self.ty_to_string(actual_ty))
1741 pub fn report_mismatched_types(
1743 cause: &ObligationCause<'tcx>,
1746 err: TypeError<'tcx>,
1747 ) -> DiagnosticBuilder<'tcx> {
1748 let trace = TypeTrace::types(cause, true, expected, actual);
1749 self.report_and_explain_type_error(trace, &err)
1752 pub fn replace_bound_vars_with_fresh_vars<T>(
1755 lbrct: LateBoundRegionConversionTime,
1756 value: &ty::Binder<T>,
1757 ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1759 T: TypeFoldable<'tcx>,
1761 let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
1763 self.next_ty_var(TypeVariableOrigin {
1764 kind: TypeVariableOriginKind::MiscVariable,
1768 let fld_c = |_, ty| {
1769 self.next_const_var(
1771 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1774 self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1777 /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1778 pub fn verify_generic_bound(
1780 origin: SubregionOrigin<'tcx>,
1781 kind: GenericKind<'tcx>,
1782 a: ty::Region<'tcx>,
1783 bound: VerifyBound<'tcx>,
1785 debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1789 .unwrap_region_constraints()
1790 .verify_generic_bound(origin, kind, a, bound);
1793 /// Obtains the latest type of the given closure; this may be a
1794 /// closure in the current function, in which case its
1795 /// `ClosureKind` may not yet be known.
1796 pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1797 let closure_kind_ty = closure_substs.as_closure().kind_ty();
1798 let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1799 closure_kind_ty.to_opt_closure_kind()
1802 /// Clears the selection, evaluation, and projection caches. This is useful when
1803 /// repeatedly attempting to select an `Obligation` while changing only
1804 /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1805 pub fn clear_caches(&self) {
1806 self.selection_cache.clear();
1807 self.evaluation_cache.clear();
1808 self.inner.borrow_mut().projection_cache().clear();
1811 fn universe(&self) -> ty::UniverseIndex {
1815 /// Creates and return a fresh universe that extends all previous
1816 /// universes. Updates `self.universe` to that new universe.
1817 pub fn create_next_universe(&self) -> ty::UniverseIndex {
1818 let u = self.universe.get().next_universe();
1819 self.universe.set(u);
1823 /// Resolves and evaluates a constant.
1825 /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1826 /// substitutions and environment are used to resolve the constant. Alternatively if the
1827 /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1828 /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1829 /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1830 /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1833 /// This handles inferences variables within both `param_env` and `substs` by
1834 /// performing the operation on their respective canonical forms.
1835 pub fn const_eval_resolve(
1837 param_env: ty::ParamEnv<'tcx>,
1839 substs: SubstsRef<'tcx>,
1840 promoted: Option<mir::Promoted>,
1842 ) -> ConstEvalResult<'tcx> {
1843 let mut original_values = OriginalQueryValues::default();
1844 let canonical = self.canonicalize_query(&(param_env, substs), &mut original_values);
1846 let (param_env, substs) = canonical.value;
1847 // The return value is the evaluated value which doesn't contain any reference to inference
1848 // variables, thus we don't need to substitute back the original values.
1849 self.tcx.const_eval_resolve(param_env, def_id, substs, promoted, span)
1852 /// If `typ` is a type variable of some kind, resolve it one level
1853 /// (but do not resolve types found in the result). If `typ` is
1854 /// not a type variable, just return it unmodified.
1855 // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1856 fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1858 ty::Infer(ty::TyVar(v)) => {
1859 // Not entirely obvious: if `typ` is a type variable,
1860 // it can be resolved to an int/float variable, which
1861 // can then be recursively resolved, hence the
1862 // recursion. Note though that we prevent type
1863 // variables from unifying to other type variables
1864 // directly (though they may be embedded
1865 // structurally), and we prevent cycles in any case,
1866 // so this recursion should always be of very limited
1869 // Note: if these two lines are combined into one we get
1870 // dynamic borrow errors on `self.inner`.
1871 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1872 known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
1875 ty::Infer(ty::IntVar(v)) => self
1878 .int_unification_table()
1880 .map(|v| v.to_type(self.tcx))
1883 ty::Infer(ty::FloatVar(v)) => self
1886 .float_unification_table()
1888 .map(|v| v.to_type(self.tcx))
1895 /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1896 /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1897 /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1899 /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1900 /// inlined, despite being large, because it has only two call sites that
1901 /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1902 /// inference variables), and it handles both `Ty` and `ty::Const` without
1903 /// having to resort to storing full `GenericArg`s in `stalled_on`.
1905 pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1907 TyOrConstInferVar::Ty(v) => {
1908 use self::type_variable::TypeVariableValue;
1910 // If `inlined_probe` returns a `Known` value, it never equals
1911 // `ty::Infer(ty::TyVar(v))`.
1912 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1913 TypeVariableValue::Unknown { .. } => false,
1914 TypeVariableValue::Known { .. } => true,
1918 TyOrConstInferVar::TyInt(v) => {
1919 // If `inlined_probe_value` returns a value it's always a
1920 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1922 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1925 TyOrConstInferVar::TyFloat(v) => {
1926 // If `probe_value` returns a value it's always a
1927 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1929 // Not `inlined_probe_value(v)` because this call site is colder.
1930 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1933 TyOrConstInferVar::Const(v) => {
1934 // If `probe_value` returns a `Known` value, it never equals
1935 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1937 // Not `inlined_probe_value(v)` because this call site is colder.
1938 match self.inner.borrow_mut().const_unification_table.probe_value(v).val {
1939 ConstVariableValue::Unknown { .. } => false,
1940 ConstVariableValue::Known { .. } => true,
1947 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1948 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1949 #[derive(Copy, Clone, Debug)]
1950 pub enum TyOrConstInferVar<'tcx> {
1951 /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1953 /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1955 /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1958 /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1959 Const(ConstVid<'tcx>),
1962 impl TyOrConstInferVar<'tcx> {
1963 /// Tries to extract an inference variable from a type or a constant, returns `None`
1964 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1965 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1966 pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1967 match arg.unpack() {
1968 GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1969 GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1970 GenericArgKind::Lifetime(_) => None,
1974 /// Tries to extract an inference variable from a type, returns `None`
1975 /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1976 pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1978 ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1979 ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1980 ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1985 /// Tries to extract an inference variable from a constant, returns `None`
1986 /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1987 pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1989 ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1995 struct ShallowResolver<'a, 'tcx> {
1996 infcx: &'a InferCtxt<'a, 'tcx>,
1999 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
2000 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2004 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2005 self.infcx.shallow_resolve_ty(ty)
2008 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
2009 if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
2013 .const_unification_table()
2024 impl<'tcx> TypeTrace<'tcx> {
2025 pub fn span(&self) -> Span {
2030 cause: &ObligationCause<'tcx>,
2031 a_is_expected: bool,
2034 ) -> TypeTrace<'tcx> {
2035 TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
2038 pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
2040 cause: ObligationCause::dummy(),
2041 values: Types(ExpectedFound { expected: tcx.types.err, found: tcx.types.err }),
2046 impl<'tcx> SubregionOrigin<'tcx> {
2047 pub fn span(&self) -> Span {
2049 Subtype(ref a) => a.span(),
2050 InfStackClosure(a) => a,
2051 InvokeClosure(a) => a,
2052 DerefPointer(a) => a,
2053 ClosureCapture(a, _) => a,
2055 RelateObjectBound(a) => a,
2056 RelateParamBound(a, _) => a,
2057 RelateRegionParamBound(a) => a,
2058 RelateDefaultParamBound(a, _) => a,
2060 ReborrowUpvar(a, _) => a,
2061 DataBorrowed(_, a) => a,
2062 ReferenceOutlivesReferent(_, a) => a,
2063 ParameterInScope(_, a) => a,
2064 ExprTypeIsNotInScope(_, a) => a,
2065 BindingTypeIsNotValidAtDecl(a) => a,
2072 SafeDestructor(a) => a,
2073 CompareImplMethodObligation { span, .. } => span,
2077 pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
2079 F: FnOnce() -> Self,
2082 traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
2083 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
2086 traits::ObligationCauseCode::CompareImplMethodObligation {
2090 } => SubregionOrigin::CompareImplMethodObligation {
2102 impl RegionVariableOrigin {
2103 pub fn span(&self) -> Span {
2105 MiscVariable(a) => a,
2106 PatternRegion(a) => a,
2107 AddrOfRegion(a) => a,
2110 EarlyBoundRegion(a, ..) => a,
2111 LateBoundRegion(a, ..) => a,
2112 BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
2113 UpvarRegion(_, a) => a,
2114 NLL(..) => bug!("NLL variable used with `span`"),
2119 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
2120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2123 "RegionObligation(sub_region={:?}, sup_type={:?})",
2124 self.sub_region, self.sup_type