]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/mod.rs
Rollup merge of #83280 - starthal:fix-typo-keyword-docs, r=dtolnay
[rust.git] / compiler / rustc_infer / src / infer / mod.rs
1 pub use self::freshen::TypeFreshener;
2 pub use self::LateBoundRegionConversionTime::*;
3 pub use self::RegionVariableOrigin::*;
4 pub use self::SubregionOrigin::*;
5 pub use self::ValuePairs::*;
6
7 pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
8
9 use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
10
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_data_structures::sync::Lrc;
13 use rustc_data_structures::undo_log::Rollback;
14 use rustc_data_structures::unify as ut;
15 use rustc_errors::DiagnosticBuilder;
16 use rustc_hir as hir;
17 use rustc_hir::def_id::{DefId, LocalDefId};
18 use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
19 use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
20 use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
21 use rustc_middle::mir::interpret::EvalToConstValueResult;
22 use rustc_middle::traits::select;
23 use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
24 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
25 use rustc_middle::ty::relate::RelateResult;
26 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
27 pub use rustc_middle::ty::IntVarValue;
28 use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
29 use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
30 use rustc_session::config::BorrowckMode;
31 use rustc_span::symbol::Symbol;
32 use rustc_span::Span;
33
34 use std::cell::{Cell, Ref, RefCell};
35 use std::collections::BTreeMap;
36 use std::fmt;
37
38 use self::combine::CombineFields;
39 use self::free_regions::RegionRelations;
40 use self::lexical_region_resolve::LexicalRegionResolutions;
41 use self::outlives::env::OutlivesEnvironment;
42 use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
43 use self::region_constraints::{
44     RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
45 };
46 use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
47
48 pub mod at;
49 pub mod canonical;
50 mod combine;
51 mod equate;
52 pub mod error_reporting;
53 pub mod free_regions;
54 mod freshen;
55 mod fudge;
56 mod glb;
57 mod higher_ranked;
58 pub mod lattice;
59 mod lexical_region_resolve;
60 mod lub;
61 pub mod nll_relate;
62 pub mod outlives;
63 pub mod region_constraints;
64 pub mod resolve;
65 mod sub;
66 pub mod type_variable;
67 mod undo_log;
68
69 use crate::infer::canonical::OriginalQueryValues;
70 pub use rustc_middle::infer::unify_key;
71
72 #[must_use]
73 #[derive(Debug)]
74 pub struct InferOk<'tcx, T> {
75     pub value: T,
76     pub obligations: PredicateObligations<'tcx>,
77 }
78 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
79
80 pub type Bound<T> = Option<T>;
81 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
82 pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>; // "fixup result"
83
84 pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
85     ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
86 >;
87
88 /// How we should handle region solving.
89 ///
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.
96     Solve,
97     /// Erase the results of region after solving.
98     Erase {
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
101         /// be set to true.
102         suppress_errors: bool,
103     },
104 }
105
106 impl Default for RegionckMode {
107     fn default() -> Self {
108         RegionckMode::Solve
109     }
110 }
111
112 impl RegionckMode {
113     /// Indicates that the MIR borrowck will repeat these region
114     /// checks, so we should ignore errors if NLL is (unconditionally)
115     /// enabled.
116     pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
117         // FIXME(Centril): Once we actually remove `::Migrate` also make
118         // this always `true` and then proceed to eliminate the dead code.
119         match tcx.borrowck_mode() {
120             // If we're on Migrate mode, report AST region errors
121             BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
122
123             // If we're on MIR, don't report AST region errors as they should be reported by NLL
124             BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
125         }
126     }
127 }
128
129 /// This type contains all the things within `InferCtxt` that sit within a
130 /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
131 /// operations are hot enough that we want only one call to `borrow_mut` per
132 /// call to `start_snapshot` and `rollback_to`.
133 pub struct InferCtxtInner<'tcx> {
134     /// Cache for projections. This cache is snapshotted along with the infcx.
135     ///
136     /// Public so that `traits::project` can use it.
137     pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
138
139     /// We instantiate `UnificationTable` with `bounds<Ty>` because the types
140     /// that might instantiate a general type variable have an order,
141     /// represented by its upper and lower bounds.
142     type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
143
144     /// Map from const parameter variable to the kind of const it represents.
145     const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
146
147     /// Map from integral variable to the kind of integer it represents.
148     int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
149
150     /// Map from floating variable to the kind of float it represents.
151     float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
152
153     /// Tracks the set of region variables and the constraints between them.
154     /// This is initially `Some(_)` but when
155     /// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
156     /// -- further attempts to perform unification, etc., may fail if new
157     /// region constraints would've been added.
158     region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
159
160     /// A set of constraints that regionck must validate. Each
161     /// constraint has the form `T:'a`, meaning "some type `T` must
162     /// outlive the lifetime 'a". These constraints derive from
163     /// instantiated type parameters. So if you had a struct defined
164     /// like
165     ///
166     ///     struct Foo<T:'static> { ... }
167     ///
168     /// then in some expression `let x = Foo { ... }` it will
169     /// instantiate the type parameter `T` with a fresh type `$0`. At
170     /// the same time, it will record a region obligation of
171     /// `$0:'static`. This will get checked later by regionck. (We
172     /// can't generally check these things right away because we have
173     /// to wait until types are resolved.)
174     ///
175     /// These are stored in a map keyed to the id of the innermost
176     /// enclosing fn body / static initializer expression. This is
177     /// because the location where the obligation was incurred can be
178     /// relevant with respect to which sublifetime assumptions are in
179     /// place. The reason that we store under the fn-id, and not
180     /// something more fine-grained, is so that it is easier for
181     /// regionck to be sure that it has found *all* the region
182     /// obligations (otherwise, it's easy to fail to walk to a
183     /// particular node-id).
184     ///
185     /// Before running `resolve_regions_and_report_errors`, the creator
186     /// of the inference context is expected to invoke
187     /// `process_region_obligations` (defined in `self::region_obligations`)
188     /// for each body-id in this map, which will process the
189     /// obligations within. This is expected to be done 'late enough'
190     /// that all type inference variables have been bound and so forth.
191     region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
192
193     undo_log: InferCtxtUndoLogs<'tcx>,
194 }
195
196 impl<'tcx> InferCtxtInner<'tcx> {
197     fn new() -> InferCtxtInner<'tcx> {
198         InferCtxtInner {
199             projection_cache: Default::default(),
200             type_variable_storage: type_variable::TypeVariableStorage::new(),
201             undo_log: InferCtxtUndoLogs::default(),
202             const_unification_storage: ut::UnificationTableStorage::new(),
203             int_unification_storage: ut::UnificationTableStorage::new(),
204             float_unification_storage: ut::UnificationTableStorage::new(),
205             region_constraint_storage: Some(RegionConstraintStorage::new()),
206             region_obligations: vec![],
207         }
208     }
209
210     #[inline]
211     pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
212         &self.region_obligations
213     }
214
215     #[inline]
216     pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
217         self.projection_cache.with_log(&mut self.undo_log)
218     }
219
220     #[inline]
221     fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
222         self.type_variable_storage.with_log(&mut self.undo_log)
223     }
224
225     #[inline]
226     fn int_unification_table(
227         &mut self,
228     ) -> ut::UnificationTable<
229         ut::InPlace<
230             ty::IntVid,
231             &mut ut::UnificationStorage<ty::IntVid>,
232             &mut InferCtxtUndoLogs<'tcx>,
233         >,
234     > {
235         self.int_unification_storage.with_log(&mut self.undo_log)
236     }
237
238     #[inline]
239     fn float_unification_table(
240         &mut self,
241     ) -> ut::UnificationTable<
242         ut::InPlace<
243             ty::FloatVid,
244             &mut ut::UnificationStorage<ty::FloatVid>,
245             &mut InferCtxtUndoLogs<'tcx>,
246         >,
247     > {
248         self.float_unification_storage.with_log(&mut self.undo_log)
249     }
250
251     #[inline]
252     fn const_unification_table(
253         &mut self,
254     ) -> ut::UnificationTable<
255         ut::InPlace<
256             ty::ConstVid<'tcx>,
257             &mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
258             &mut InferCtxtUndoLogs<'tcx>,
259         >,
260     > {
261         self.const_unification_storage.with_log(&mut self.undo_log)
262     }
263
264     #[inline]
265     pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
266         self.region_constraint_storage
267             .as_mut()
268             .expect("region constraints already solved")
269             .with_log(&mut self.undo_log)
270     }
271 }
272
273 pub struct InferCtxt<'a, 'tcx> {
274     pub tcx: TyCtxt<'tcx>,
275
276     /// During type-checking/inference of a body, `in_progress_typeck_results`
277     /// contains a reference to the typeck results being built up, which are
278     /// used for reading closure kinds/signatures as they are inferred,
279     /// and for error reporting logic to read arbitrary node types.
280     pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
281
282     pub inner: RefCell<InferCtxtInner<'tcx>>,
283
284     /// If set, this flag causes us to skip the 'leak check' during
285     /// higher-ranked subtyping operations. This flag is a temporary one used
286     /// to manage the removal of the leak-check: for the time being, we still run the
287     /// leak-check, but we issue warnings. This flag can only be set to true
288     /// when entering a snapshot.
289     skip_leak_check: Cell<bool>,
290
291     /// Once region inference is done, the values for each variable.
292     lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
293
294     /// Caches the results of trait selection. This cache is used
295     /// for things that have to do with the parameters in scope.
296     pub selection_cache: select::SelectionCache<'tcx>,
297
298     /// Caches the results of trait evaluation.
299     pub evaluation_cache: select::EvaluationCache<'tcx>,
300
301     /// the set of predicates on which errors have been reported, to
302     /// avoid reporting the same error twice.
303     pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
304
305     pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
306
307     /// When an error occurs, we want to avoid reporting "derived"
308     /// errors that are due to this original failure. Normally, we
309     /// handle this with the `err_count_on_creation` count, which
310     /// basically just tracks how many errors were reported when we
311     /// started type-checking a fn and checks to see if any new errors
312     /// have been reported since then. Not great, but it works.
313     ///
314     /// However, when errors originated in other passes -- notably
315     /// resolve -- this heuristic breaks down. Therefore, we have this
316     /// auxiliary flag that one can set whenever one creates a
317     /// type-error that is due to an error in a prior pass.
318     ///
319     /// Don't read this flag directly, call `is_tainted_by_errors()`
320     /// and `set_tainted_by_errors()`.
321     tainted_by_errors_flag: Cell<bool>,
322
323     /// Track how many errors were reported when this infcx is created.
324     /// If the number of errors increases, that's also a sign (line
325     /// `tained_by_errors`) to avoid reporting certain kinds of errors.
326     // FIXME(matthewjasper) Merge into `tainted_by_errors_flag`
327     err_count_on_creation: usize,
328
329     /// This flag is true while there is an active snapshot.
330     in_snapshot: Cell<bool>,
331
332     /// What is the innermost universe we have created? Starts out as
333     /// `UniverseIndex::root()` but grows from there as we enter
334     /// universal quantifiers.
335     ///
336     /// N.B., at present, we exclude the universal quantifiers on the
337     /// item we are type-checking, and just consider those names as
338     /// part of the root universe. So this would only get incremented
339     /// when we enter into a higher-ranked (`for<..>`) type or trait
340     /// bound.
341     universe: Cell<ty::UniverseIndex>,
342 }
343
344 /// See the `error_reporting` module for more details.
345 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
346 pub enum ValuePairs<'tcx> {
347     Types(ExpectedFound<Ty<'tcx>>),
348     Regions(ExpectedFound<ty::Region<'tcx>>),
349     Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
350     TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
351     PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
352 }
353
354 /// The trace designates the path through inference that we took to
355 /// encounter an error or subtyping constraint.
356 ///
357 /// See the `error_reporting` module for more details.
358 #[derive(Clone, Debug)]
359 pub struct TypeTrace<'tcx> {
360     cause: ObligationCause<'tcx>,
361     values: ValuePairs<'tcx>,
362 }
363
364 /// The origin of a `r1 <= r2` constraint.
365 ///
366 /// See `error_reporting` module for more details
367 #[derive(Clone, Debug)]
368 pub enum SubregionOrigin<'tcx> {
369     /// Arose from a subtyping relation
370     Subtype(Box<TypeTrace<'tcx>>),
371
372     /// When casting `&'a T` to an `&'b Trait` object,
373     /// relating `'a` to `'b`
374     RelateObjectBound(Span),
375
376     /// Some type parameter was instantiated with the given type,
377     /// and that type must outlive some region.
378     RelateParamBound(Span, Ty<'tcx>),
379
380     /// The given region parameter was instantiated with a region
381     /// that must outlive some other region.
382     RelateRegionParamBound(Span),
383
384     /// Creating a pointer `b` to contents of another reference
385     Reborrow(Span),
386
387     /// Creating a pointer `b` to contents of an upvar
388     ReborrowUpvar(Span, ty::UpvarId),
389
390     /// Data with type `Ty<'tcx>` was borrowed
391     DataBorrowed(Ty<'tcx>, Span),
392
393     /// (&'a &'b T) where a >= b
394     ReferenceOutlivesReferent(Ty<'tcx>, Span),
395
396     /// Region in return type of invoked fn must enclose call
397     CallReturn(Span),
398
399     /// Comparing the signature and requirements of an impl method against
400     /// the containing trait.
401     CompareImplMethodObligation {
402         span: Span,
403         item_name: Symbol,
404         impl_item_def_id: DefId,
405         trait_item_def_id: DefId,
406     },
407 }
408
409 // `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
410 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
411 static_assert_size!(SubregionOrigin<'_>, 32);
412
413 /// Times when we replace late-bound regions with variables:
414 #[derive(Clone, Copy, Debug)]
415 pub enum LateBoundRegionConversionTime {
416     /// when a fn is called
417     FnCall,
418
419     /// when two higher-ranked types are compared
420     HigherRankedType,
421
422     /// when projecting an associated type
423     AssocTypeProjection(DefId),
424 }
425
426 /// Reasons to create a region inference variable
427 ///
428 /// See `error_reporting` module for more details
429 #[derive(Copy, Clone, Debug)]
430 pub enum RegionVariableOrigin {
431     /// Region variables created for ill-categorized reasons,
432     /// mostly indicates places in need of refactoring
433     MiscVariable(Span),
434
435     /// Regions created by a `&P` or `[...]` pattern
436     PatternRegion(Span),
437
438     /// Regions created by `&` operator
439     AddrOfRegion(Span),
440
441     /// Regions created as part of an autoref of a method receiver
442     Autoref(Span, ty::AssocItem),
443
444     /// Regions created as part of an automatic coercion
445     Coercion(Span),
446
447     /// Region variables created as the values for early-bound regions
448     EarlyBoundRegion(Span, Symbol),
449
450     /// Region variables created for bound regions
451     /// in a function or method that is called
452     LateBoundRegion(Span, ty::BoundRegionKind, LateBoundRegionConversionTime),
453
454     UpvarRegion(ty::UpvarId, Span),
455
456     BoundRegionInCoherence(Symbol),
457
458     /// This origin is used for the inference variables that we create
459     /// during NLL region processing.
460     Nll(NllRegionVariableOrigin),
461 }
462
463 #[derive(Copy, Clone, Debug)]
464 pub enum NllRegionVariableOrigin {
465     /// During NLL region processing, we create variables for free
466     /// regions that we encounter in the function signature and
467     /// elsewhere. This origin indices we've got one of those.
468     FreeRegion,
469
470     /// "Universal" instantiation of a higher-ranked region (e.g.,
471     /// from a `for<'a> T` binder). Meant to represent "any region".
472     Placeholder(ty::PlaceholderRegion),
473
474     /// The variable we create to represent `'empty(U0)`.
475     RootEmptyRegion,
476
477     Existential {
478         /// If this is true, then this variable was created to represent a lifetime
479         /// bound in a `for` binder. For example, it might have been created to
480         /// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
481         /// Such variables are created when we are trying to figure out if there
482         /// is any valid instantiation of `'a` that could fit into some scenario.
483         ///
484         /// This is used to inform error reporting: in the case that we are trying to
485         /// determine whether there is any valid instantiation of a `'a` variable that meets
486         /// some constraint C, we want to blame the "source" of that `for` type,
487         /// rather than blaming the source of the constraint C.
488         from_forall: bool,
489     },
490 }
491
492 // FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
493 #[derive(Copy, Clone, Debug)]
494 pub enum FixupError<'tcx> {
495     UnresolvedIntTy(IntVid),
496     UnresolvedFloatTy(FloatVid),
497     UnresolvedTy(TyVid),
498     UnresolvedConst(ConstVid<'tcx>),
499 }
500
501 /// See the `region_obligations` field for more information.
502 #[derive(Clone)]
503 pub struct RegionObligation<'tcx> {
504     pub sub_region: ty::Region<'tcx>,
505     pub sup_type: Ty<'tcx>,
506     pub origin: SubregionOrigin<'tcx>,
507 }
508
509 impl<'tcx> fmt::Display for FixupError<'tcx> {
510     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511         use self::FixupError::*;
512
513         match *self {
514             UnresolvedIntTy(_) => write!(
515                 f,
516                 "cannot determine the type of this integer; \
517                  add a suffix to specify the type explicitly"
518             ),
519             UnresolvedFloatTy(_) => write!(
520                 f,
521                 "cannot determine the type of this number; \
522                  add a suffix to specify the type explicitly"
523             ),
524             UnresolvedTy(_) => write!(f, "unconstrained type"),
525             UnresolvedConst(_) => write!(f, "unconstrained const value"),
526         }
527     }
528 }
529
530 /// Helper type of a temporary returned by `tcx.infer_ctxt()`.
531 /// Necessary because we can't write the following bound:
532 /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`.
533 pub struct InferCtxtBuilder<'tcx> {
534     tcx: TyCtxt<'tcx>,
535     fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
536 }
537
538 pub trait TyCtxtInferExt<'tcx> {
539     fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
540 }
541
542 impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
543     fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
544         InferCtxtBuilder { tcx: self, fresh_typeck_results: None }
545     }
546 }
547
548 impl<'tcx> InferCtxtBuilder<'tcx> {
549     /// Used only by `rustc_typeck` during body type-checking/inference,
550     /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`.
551     pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
552         self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
553         self
554     }
555
556     /// Given a canonical value `C` as a starting point, create an
557     /// inference context that contains each of the bound values
558     /// within instantiated as a fresh variable. The `f` closure is
559     /// invoked with the new infcx, along with the instantiated value
560     /// `V` and a substitution `S`. This substitution `S` maps from
561     /// the bound values in `C` to their instantiated values in `V`
562     /// (in other words, `S(C) = V`).
563     pub fn enter_with_canonical<T, R>(
564         &mut self,
565         span: Span,
566         canonical: &Canonical<'tcx, T>,
567         f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
568     ) -> R
569     where
570         T: TypeFoldable<'tcx>,
571     {
572         self.enter(|infcx| {
573             let (value, subst) =
574                 infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
575             f(infcx, value, subst)
576         })
577     }
578
579     pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
580         let InferCtxtBuilder { tcx, ref fresh_typeck_results } = *self;
581         let in_progress_typeck_results = fresh_typeck_results.as_ref();
582         f(InferCtxt {
583             tcx,
584             in_progress_typeck_results,
585             inner: RefCell::new(InferCtxtInner::new()),
586             lexical_region_resolutions: RefCell::new(None),
587             selection_cache: Default::default(),
588             evaluation_cache: Default::default(),
589             reported_trait_errors: Default::default(),
590             reported_closure_mismatch: Default::default(),
591             tainted_by_errors_flag: Cell::new(false),
592             err_count_on_creation: tcx.sess.err_count(),
593             in_snapshot: Cell::new(false),
594             skip_leak_check: Cell::new(false),
595             universe: Cell::new(ty::UniverseIndex::ROOT),
596         })
597     }
598 }
599
600 impl<'tcx, T> InferOk<'tcx, T> {
601     pub fn unit(self) -> InferOk<'tcx, ()> {
602         InferOk { value: (), obligations: self.obligations }
603     }
604
605     /// Extracts `value`, registering any obligations into `fulfill_cx`.
606     pub fn into_value_registering_obligations(
607         self,
608         infcx: &InferCtxt<'_, 'tcx>,
609         fulfill_cx: &mut dyn TraitEngine<'tcx>,
610     ) -> T {
611         let InferOk { value, obligations } = self;
612         for obligation in obligations {
613             fulfill_cx.register_predicate_obligation(infcx, obligation);
614         }
615         value
616     }
617 }
618
619 impl<'tcx> InferOk<'tcx, ()> {
620     pub fn into_obligations(self) -> PredicateObligations<'tcx> {
621         self.obligations
622     }
623 }
624
625 #[must_use = "once you start a snapshot, you should always consume it"]
626 pub struct CombinedSnapshot<'a, 'tcx> {
627     undo_snapshot: Snapshot<'tcx>,
628     region_constraints_snapshot: RegionSnapshot,
629     universe: ty::UniverseIndex,
630     was_in_snapshot: bool,
631     _in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
632 }
633
634 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
635     pub fn is_in_snapshot(&self) -> bool {
636         self.in_snapshot.get()
637     }
638
639     pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
640         t.fold_with(&mut self.freshener())
641     }
642
643     pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
644         match *ty.kind() {
645             ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
646             _ => false,
647         }
648     }
649
650     pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
651         freshen::TypeFreshener::new(self)
652     }
653
654     pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
655         use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
656         use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
657         match *ty.kind() {
658             ty::Infer(ty::IntVar(vid)) => {
659                 if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
660                     Neither
661                 } else {
662                     UnconstrainedInt
663                 }
664             }
665             ty::Infer(ty::FloatVar(vid)) => {
666                 if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
667                     Neither
668                 } else {
669                     UnconstrainedFloat
670                 }
671             }
672             _ => Neither,
673         }
674     }
675
676     pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
677         let mut inner = self.inner.borrow_mut();
678         let mut vars: Vec<Ty<'_>> = inner
679             .type_variables()
680             .unsolved_variables()
681             .into_iter()
682             .map(|t| self.tcx.mk_ty_var(t))
683             .collect();
684         vars.extend(
685             (0..inner.int_unification_table().len())
686                 .map(|i| ty::IntVid { index: i as u32 })
687                 .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
688                 .map(|v| self.tcx.mk_int_var(v)),
689         );
690         vars.extend(
691             (0..inner.float_unification_table().len())
692                 .map(|i| ty::FloatVid { index: i as u32 })
693                 .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
694                 .map(|v| self.tcx.mk_float_var(v)),
695         );
696         vars
697     }
698
699     fn combine_fields(
700         &'a self,
701         trace: TypeTrace<'tcx>,
702         param_env: ty::ParamEnv<'tcx>,
703     ) -> CombineFields<'a, 'tcx> {
704         CombineFields {
705             infcx: self,
706             trace,
707             cause: None,
708             param_env,
709             obligations: PredicateObligations::new(),
710         }
711     }
712
713     /// Clear the "currently in a snapshot" flag, invoke the closure,
714     /// then restore the flag to its original value. This flag is a
715     /// debugging measure designed to detect cases where we start a
716     /// snapshot, create type variables, and register obligations
717     /// which may involve those type variables in the fulfillment cx,
718     /// potentially leaving "dangling type variables" behind.
719     /// In such cases, an assertion will fail when attempting to
720     /// register obligations, within a snapshot. Very useful, much
721     /// better than grovelling through megabytes of `RUSTC_LOG` output.
722     ///
723     /// HOWEVER, in some cases the flag is unhelpful. In particular, we
724     /// sometimes create a "mini-fulfilment-cx" in which we enroll
725     /// obligations. As long as this fulfillment cx is fully drained
726     /// before we return, this is not a problem, as there won't be any
727     /// escaping obligations in the main cx. In those cases, you can
728     /// use this function.
729     pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
730     where
731         F: FnOnce(&Self) -> R,
732     {
733         let flag = self.in_snapshot.replace(false);
734         let result = func(self);
735         self.in_snapshot.set(flag);
736         result
737     }
738
739     fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
740         debug!("start_snapshot()");
741
742         let in_snapshot = self.in_snapshot.replace(true);
743
744         let mut inner = self.inner.borrow_mut();
745
746         CombinedSnapshot {
747             undo_snapshot: inner.undo_log.start_snapshot(),
748             region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
749             universe: self.universe(),
750             was_in_snapshot: in_snapshot,
751             // Borrow typeck results "in progress" (i.e., during typeck)
752             // to ban writes from within a snapshot to them.
753             _in_progress_typeck_results: self
754                 .in_progress_typeck_results
755                 .map(|typeck_results| typeck_results.borrow()),
756         }
757     }
758
759     fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
760         debug!("rollback_to(cause={})", cause);
761         let CombinedSnapshot {
762             undo_snapshot,
763             region_constraints_snapshot,
764             universe,
765             was_in_snapshot,
766             _in_progress_typeck_results,
767         } = snapshot;
768
769         self.in_snapshot.set(was_in_snapshot);
770         self.universe.set(universe);
771
772         let mut inner = self.inner.borrow_mut();
773         inner.rollback_to(undo_snapshot);
774         inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
775     }
776
777     fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
778         debug!("commit_from()");
779         let CombinedSnapshot {
780             undo_snapshot,
781             region_constraints_snapshot: _,
782             universe: _,
783             was_in_snapshot,
784             _in_progress_typeck_results,
785         } = snapshot;
786
787         self.in_snapshot.set(was_in_snapshot);
788
789         self.inner.borrow_mut().commit(undo_snapshot);
790     }
791
792     /// Executes `f` and commit the bindings.
793     pub fn commit_unconditionally<R, F>(&self, f: F) -> R
794     where
795         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
796     {
797         debug!("commit_unconditionally()");
798         let snapshot = self.start_snapshot();
799         let r = f(&snapshot);
800         self.commit_from(snapshot);
801         r
802     }
803
804     /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.
805     pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
806     where
807         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
808     {
809         debug!("commit_if_ok()");
810         let snapshot = self.start_snapshot();
811         let r = f(&snapshot);
812         debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
813         match r {
814             Ok(_) => {
815                 self.commit_from(snapshot);
816             }
817             Err(_) => {
818                 self.rollback_to("commit_if_ok -- error", snapshot);
819             }
820         }
821         r
822     }
823
824     /// Execute `f` then unroll any bindings it creates.
825     pub fn probe<R, F>(&self, f: F) -> R
826     where
827         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
828     {
829         debug!("probe()");
830         let snapshot = self.start_snapshot();
831         let r = f(&snapshot);
832         self.rollback_to("probe", snapshot);
833         r
834     }
835
836     /// If `should_skip` is true, then execute `f` then unroll any bindings it creates.
837     pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
838     where
839         F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
840     {
841         debug!("probe()");
842         let snapshot = self.start_snapshot();
843         let was_skip_leak_check = self.skip_leak_check.get();
844         if should_skip {
845             self.skip_leak_check.set(true);
846         }
847         let r = f(&snapshot);
848         self.rollback_to("probe", snapshot);
849         self.skip_leak_check.set(was_skip_leak_check);
850         r
851     }
852
853     /// Scan the constraints produced since `snapshot` began and returns:
854     ///
855     /// - `None` -- if none of them involve "region outlives" constraints
856     /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder
857     /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders
858     pub fn region_constraints_added_in_snapshot(
859         &self,
860         snapshot: &CombinedSnapshot<'a, 'tcx>,
861     ) -> Option<bool> {
862         self.inner
863             .borrow_mut()
864             .unwrap_region_constraints()
865             .region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
866     }
867
868     pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
869         self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
870     }
871
872     pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
873     where
874         T: at::ToTrace<'tcx>,
875     {
876         let origin = &ObligationCause::dummy();
877         self.probe(|_| {
878             self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
879                 // Ignore obligations, since we are unrolling
880                 // everything anyway.
881             })
882         })
883     }
884
885     pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
886     where
887         T: at::ToTrace<'tcx>,
888     {
889         let origin = &ObligationCause::dummy();
890         self.probe(|_| {
891             self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
892                 // Ignore obligations, since we are unrolling
893                 // everything anyway.
894             })
895         })
896     }
897
898     pub fn sub_regions(
899         &self,
900         origin: SubregionOrigin<'tcx>,
901         a: ty::Region<'tcx>,
902         b: ty::Region<'tcx>,
903     ) {
904         debug!("sub_regions({:?} <: {:?})", a, b);
905         self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
906     }
907
908     /// Require that the region `r` be equal to one of the regions in
909     /// the set `regions`.
910     pub fn member_constraint(
911         &self,
912         opaque_type_def_id: DefId,
913         definition_span: Span,
914         hidden_ty: Ty<'tcx>,
915         region: ty::Region<'tcx>,
916         in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
917     ) {
918         debug!("member_constraint({:?} <: {:?})", region, in_regions);
919         self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
920             opaque_type_def_id,
921             definition_span,
922             hidden_ty,
923             region,
924             in_regions,
925         );
926     }
927
928     pub fn subtype_predicate(
929         &self,
930         cause: &ObligationCause<'tcx>,
931         param_env: ty::ParamEnv<'tcx>,
932         predicate: ty::PolySubtypePredicate<'tcx>,
933     ) -> Option<InferResult<'tcx, ()>> {
934         // Subtle: it's ok to skip the binder here and resolve because
935         // `shallow_resolve` just ignores anything that is not a type
936         // variable, and because type variable's can't (at present, at
937         // least) capture any of the things bound by this binder.
938         //
939         // NOTE(nmatsakis): really, there is no *particular* reason to do this
940         // `shallow_resolve` here except as a micro-optimization.
941         // Naturally I could not resist.
942         let two_unbound_type_vars = {
943             let a = self.shallow_resolve(predicate.skip_binder().a);
944             let b = self.shallow_resolve(predicate.skip_binder().b);
945             a.is_ty_var() && b.is_ty_var()
946         };
947
948         if two_unbound_type_vars {
949             // Two unbound type variables? Can't make progress.
950             return None;
951         }
952
953         Some(self.commit_if_ok(|_snapshot| {
954             let ty::SubtypePredicate { a_is_expected, a, b } =
955                 self.replace_bound_vars_with_placeholders(predicate);
956
957             let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
958
959             Ok(ok.unit())
960         }))
961     }
962
963     pub fn region_outlives_predicate(
964         &self,
965         cause: &traits::ObligationCause<'tcx>,
966         predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
967     ) -> UnitResult<'tcx> {
968         self.commit_if_ok(|_snapshot| {
969             let ty::OutlivesPredicate(r_a, r_b) =
970                 self.replace_bound_vars_with_placeholders(predicate);
971             let origin = SubregionOrigin::from_obligation_cause(cause, || {
972                 RelateRegionParamBound(cause.span)
973             });
974             self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
975             Ok(())
976         })
977     }
978
979     pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
980         self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
981     }
982
983     pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
984         self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
985     }
986
987     pub fn next_ty_var_in_universe(
988         &self,
989         origin: TypeVariableOrigin,
990         universe: ty::UniverseIndex,
991     ) -> Ty<'tcx> {
992         let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
993         self.tcx.mk_ty_var(vid)
994     }
995
996     pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
997         self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
998     }
999
1000     pub fn next_const_var(
1001         &self,
1002         ty: Ty<'tcx>,
1003         origin: ConstVariableOrigin,
1004     ) -> &'tcx ty::Const<'tcx> {
1005         self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
1006     }
1007
1008     pub fn next_const_var_in_universe(
1009         &self,
1010         ty: Ty<'tcx>,
1011         origin: ConstVariableOrigin,
1012         universe: ty::UniverseIndex,
1013     ) -> &'tcx ty::Const<'tcx> {
1014         let vid = self
1015             .inner
1016             .borrow_mut()
1017             .const_unification_table()
1018             .new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
1019         self.tcx.mk_const_var(vid, ty)
1020     }
1021
1022     pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
1023         self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1024             origin,
1025             val: ConstVariableValue::Unknown { universe: self.universe() },
1026         })
1027     }
1028
1029     fn next_int_var_id(&self) -> IntVid {
1030         self.inner.borrow_mut().int_unification_table().new_key(None)
1031     }
1032
1033     pub fn next_int_var(&self) -> Ty<'tcx> {
1034         self.tcx.mk_int_var(self.next_int_var_id())
1035     }
1036
1037     fn next_float_var_id(&self) -> FloatVid {
1038         self.inner.borrow_mut().float_unification_table().new_key(None)
1039     }
1040
1041     pub fn next_float_var(&self) -> Ty<'tcx> {
1042         self.tcx.mk_float_var(self.next_float_var_id())
1043     }
1044
1045     /// Creates a fresh region variable with the next available index.
1046     /// The variable will be created in the maximum universe created
1047     /// thus far, allowing it to name any region created thus far.
1048     pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
1049         self.next_region_var_in_universe(origin, self.universe())
1050     }
1051
1052     /// Creates a fresh region variable with the next available index
1053     /// in the given universe; typically, you can use
1054     /// `next_region_var` and just use the maximal universe.
1055     pub fn next_region_var_in_universe(
1056         &self,
1057         origin: RegionVariableOrigin,
1058         universe: ty::UniverseIndex,
1059     ) -> ty::Region<'tcx> {
1060         let region_var =
1061             self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
1062         self.tcx.mk_region(ty::ReVar(region_var))
1063     }
1064
1065     /// Return the universe that the region `r` was created in.  For
1066     /// most regions (e.g., `'static`, named regions from the user,
1067     /// etc) this is the root universe U0. For inference variables or
1068     /// placeholders, however, it will return the universe which which
1069     /// they are associated.
1070     fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
1071         self.inner.borrow_mut().unwrap_region_constraints().universe(r)
1072     }
1073
1074     /// Number of region variables created so far.
1075     pub fn num_region_vars(&self) -> usize {
1076         self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
1077     }
1078
1079     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1080     pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
1081         self.next_region_var(RegionVariableOrigin::Nll(origin))
1082     }
1083
1084     /// Just a convenient wrapper of `next_region_var` for using during NLL.
1085     pub fn next_nll_region_var_in_universe(
1086         &self,
1087         origin: NllRegionVariableOrigin,
1088         universe: ty::UniverseIndex,
1089     ) -> ty::Region<'tcx> {
1090         self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
1091     }
1092
1093     pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
1094         match param.kind {
1095             GenericParamDefKind::Lifetime => {
1096                 // Create a region inference variable for the given
1097                 // region parameter definition.
1098                 self.next_region_var(EarlyBoundRegion(span, param.name)).into()
1099             }
1100             GenericParamDefKind::Type { .. } => {
1101                 // Create a type inference variable for the given
1102                 // type parameter definition. The substitutions are
1103                 // for actual parameters that may be referred to by
1104                 // the default of this type parameter, if it exists.
1105                 // e.g., `struct Foo<A, B, C = (A, B)>(...);` when
1106                 // used in a path such as `Foo::<T, U>::new()` will
1107                 // use an inference variable for `C` with `[T, U]`
1108                 // as the substitutions for the default, `(T, U)`.
1109                 let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
1110                     self.universe(),
1111                     false,
1112                     TypeVariableOrigin {
1113                         kind: TypeVariableOriginKind::TypeParameterDefinition(
1114                             param.name,
1115                             Some(param.def_id),
1116                         ),
1117                         span,
1118                     },
1119                 );
1120
1121                 self.tcx.mk_ty_var(ty_var_id).into()
1122             }
1123             GenericParamDefKind::Const { .. } => {
1124                 let origin = ConstVariableOrigin {
1125                     kind: ConstVariableOriginKind::ConstParameterDefinition(
1126                         param.name,
1127                         param.def_id,
1128                     ),
1129                     span,
1130                 };
1131                 let const_var_id =
1132                     self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
1133                         origin,
1134                         val: ConstVariableValue::Unknown { universe: self.universe() },
1135                     });
1136                 self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
1137             }
1138         }
1139     }
1140
1141     /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1142     /// type/region parameter to a fresh inference variable.
1143     pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
1144         InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
1145     }
1146
1147     /// Returns `true` if errors have been reported since this infcx was
1148     /// created. This is sometimes used as a heuristic to skip
1149     /// reporting errors that often occur as a result of earlier
1150     /// errors, but where it's hard to be 100% sure (e.g., unresolved
1151     /// inference variables, regionck errors).
1152     pub fn is_tainted_by_errors(&self) -> bool {
1153         debug!(
1154             "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1155              tainted_by_errors_flag={})",
1156             self.tcx.sess.err_count(),
1157             self.err_count_on_creation,
1158             self.tainted_by_errors_flag.get()
1159         );
1160
1161         if self.tcx.sess.err_count() > self.err_count_on_creation {
1162             return true; // errors reported since this infcx was made
1163         }
1164         self.tainted_by_errors_flag.get()
1165     }
1166
1167     /// Set the "tainted by errors" flag to true. We call this when we
1168     /// observe an error from a prior pass.
1169     pub fn set_tainted_by_errors(&self) {
1170         debug!("set_tainted_by_errors()");
1171         self.tainted_by_errors_flag.set(true)
1172     }
1173
1174     /// Process the region constraints and report any errors that
1175     /// result. After this, no more unification operations should be
1176     /// done -- or the compiler will panic -- but it is legal to use
1177     /// `resolve_vars_if_possible` as well as `fully_resolve`.
1178     pub fn resolve_regions_and_report_errors(
1179         &self,
1180         region_context: DefId,
1181         outlives_env: &OutlivesEnvironment<'tcx>,
1182         mode: RegionckMode,
1183     ) {
1184         let (var_infos, data) = {
1185             let mut inner = self.inner.borrow_mut();
1186             let inner = &mut *inner;
1187             assert!(
1188                 self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
1189                 "region_obligations not empty: {:#?}",
1190                 inner.region_obligations
1191             );
1192             inner
1193                 .region_constraint_storage
1194                 .take()
1195                 .expect("regions already resolved")
1196                 .with_log(&mut inner.undo_log)
1197                 .into_infos_and_data()
1198         };
1199
1200         let region_rels =
1201             &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
1202
1203         let (lexical_region_resolutions, errors) =
1204             lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
1205
1206         let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
1207         assert!(old_value.is_none());
1208
1209         if !self.is_tainted_by_errors() {
1210             // As a heuristic, just skip reporting region errors
1211             // altogether if other errors have been reported while
1212             // this infcx was in use.  This is totally hokey but
1213             // otherwise we have a hard time separating legit region
1214             // errors from silly ones.
1215             self.report_region_errors(&errors);
1216         }
1217     }
1218
1219     /// Obtains (and clears) the current set of region
1220     /// constraints. The inference context is still usable: further
1221     /// unifications will simply add new constraints.
1222     ///
1223     /// This method is not meant to be used with normal lexical region
1224     /// resolution. Rather, it is used in the NLL mode as a kind of
1225     /// interim hack: basically we run normal type-check and generate
1226     /// region constraints as normal, but then we take them and
1227     /// translate them into the form that the NLL solver
1228     /// understands. See the NLL module for mode details.
1229     pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
1230         assert!(
1231             self.inner.borrow().region_obligations.is_empty(),
1232             "region_obligations not empty: {:#?}",
1233             self.inner.borrow().region_obligations
1234         );
1235
1236         self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
1237     }
1238
1239     /// Gives temporary access to the region constraint data.
1240     pub fn with_region_constraints<R>(
1241         &self,
1242         op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
1243     ) -> R {
1244         let mut inner = self.inner.borrow_mut();
1245         op(inner.unwrap_region_constraints().data())
1246     }
1247
1248     /// Takes ownership of the list of variable regions. This implies
1249     /// that all the region constraints have already been taken, and
1250     /// hence that `resolve_regions_and_report_errors` can never be
1251     /// called. This is used only during NLL processing to "hand off" ownership
1252     /// of the set of region variables into the NLL region context.
1253     pub fn take_region_var_origins(&self) -> VarInfos {
1254         let mut inner = self.inner.borrow_mut();
1255         let (var_infos, data) = inner
1256             .region_constraint_storage
1257             .take()
1258             .expect("regions already resolved")
1259             .with_log(&mut inner.undo_log)
1260             .into_infos_and_data();
1261         assert!(data.is_empty());
1262         var_infos
1263     }
1264
1265     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1266         self.resolve_vars_if_possible(t).to_string()
1267     }
1268
1269     pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1270         let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1271         format!("({})", tstrs.join(", "))
1272     }
1273
1274     pub fn trait_ref_to_string(&self, t: ty::TraitRef<'tcx>) -> String {
1275         self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
1276     }
1277
1278     /// If `TyVar(vid)` resolves to a type, return that type. Else, return the
1279     /// universe index of `TyVar(vid)`.
1280     pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
1281         use self::type_variable::TypeVariableValue;
1282
1283         match self.inner.borrow_mut().type_variables().probe(vid) {
1284             TypeVariableValue::Known { value } => Ok(value),
1285             TypeVariableValue::Unknown { universe } => Err(universe),
1286         }
1287     }
1288
1289     /// Resolve any type variables found in `value` -- but only one
1290     /// level.  So, if the variable `?X` is bound to some type
1291     /// `Foo<?Y>`, then this would return `Foo<?Y>` (but `?Y` may
1292     /// itself be bound to a type).
1293     ///
1294     /// Useful when you only need to inspect the outermost level of
1295     /// the type and don't care about nested types (or perhaps you
1296     /// will be resolving them as well, e.g. in a loop).
1297     pub fn shallow_resolve<T>(&self, value: T) -> T
1298     where
1299         T: TypeFoldable<'tcx>,
1300     {
1301         value.fold_with(&mut ShallowResolver { infcx: self })
1302     }
1303
1304     pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
1305         self.inner.borrow_mut().type_variables().root_var(var)
1306     }
1307
1308     /// Where possible, replaces type/const variables in
1309     /// `value` with their final value. Note that region variables
1310     /// are unaffected. If a type/const variable has not been unified, it
1311     /// is left as is. This is an idempotent operation that does
1312     /// not affect inference state in any way and so you can do it
1313     /// at will.
1314     pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
1315     where
1316         T: TypeFoldable<'tcx>,
1317     {
1318         if !value.needs_infer() {
1319             return value; // Avoid duplicated subst-folding.
1320         }
1321         let mut r = resolve::OpportunisticVarResolver::new(self);
1322         value.fold_with(&mut r)
1323     }
1324
1325     /// Returns the first unresolved variable contained in `T`. In the
1326     /// process of visiting `T`, this will resolve (where possible)
1327     /// type variables in `T`, but it never constructs the final,
1328     /// resolved type, so it's more efficient than
1329     /// `resolve_vars_if_possible()`.
1330     pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
1331     where
1332         T: TypeFoldable<'tcx>,
1333     {
1334         value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
1335     }
1336
1337     pub fn probe_const_var(
1338         &self,
1339         vid: ty::ConstVid<'tcx>,
1340     ) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
1341         match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
1342             ConstVariableValue::Known { value } => Ok(value),
1343             ConstVariableValue::Unknown { universe } => Err(universe),
1344         }
1345     }
1346
1347     pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
1348         /*!
1349          * Attempts to resolve all type/region/const variables in
1350          * `value`. Region inference must have been run already (e.g.,
1351          * by calling `resolve_regions_and_report_errors`). If some
1352          * variable was never unified, an `Err` results.
1353          *
1354          * This method is idempotent, but it not typically not invoked
1355          * except during the writeback phase.
1356          */
1357
1358         resolve::fully_resolve(self, value)
1359     }
1360
1361     // [Note-Type-error-reporting]
1362     // An invariant is that anytime the expected or actual type is Error (the special
1363     // error type, meaning that an error occurred when typechecking this expression),
1364     // this is a derived error. The error cascaded from another error (that was already
1365     // reported), so it's not useful to display it to the user.
1366     // The following methods implement this logic.
1367     // They check if either the actual or expected type is Error, and don't print the error
1368     // in this case. The typechecker should only ever report type errors involving mismatched
1369     // types using one of these methods, and should not call span_err directly for such
1370     // errors.
1371
1372     pub fn type_error_struct_with_diag<M>(
1373         &self,
1374         sp: Span,
1375         mk_diag: M,
1376         actual_ty: Ty<'tcx>,
1377     ) -> DiagnosticBuilder<'tcx>
1378     where
1379         M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1380     {
1381         let actual_ty = self.resolve_vars_if_possible(actual_ty);
1382         debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1383
1384         // Don't report an error if actual type is `Error`.
1385         if actual_ty.references_error() {
1386             return self.tcx.sess.diagnostic().struct_dummy();
1387         }
1388
1389         mk_diag(self.ty_to_string(actual_ty))
1390     }
1391
1392     pub fn report_mismatched_types(
1393         &self,
1394         cause: &ObligationCause<'tcx>,
1395         expected: Ty<'tcx>,
1396         actual: Ty<'tcx>,
1397         err: TypeError<'tcx>,
1398     ) -> DiagnosticBuilder<'tcx> {
1399         let trace = TypeTrace::types(cause, true, expected, actual);
1400         self.report_and_explain_type_error(trace, &err)
1401     }
1402
1403     pub fn report_mismatched_consts(
1404         &self,
1405         cause: &ObligationCause<'tcx>,
1406         expected: &'tcx ty::Const<'tcx>,
1407         actual: &'tcx ty::Const<'tcx>,
1408         err: TypeError<'tcx>,
1409     ) -> DiagnosticBuilder<'tcx> {
1410         let trace = TypeTrace::consts(cause, true, expected, actual);
1411         self.report_and_explain_type_error(trace, &err)
1412     }
1413
1414     pub fn replace_bound_vars_with_fresh_vars<T>(
1415         &self,
1416         span: Span,
1417         lbrct: LateBoundRegionConversionTime,
1418         value: ty::Binder<T>,
1419     ) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
1420     where
1421         T: TypeFoldable<'tcx>,
1422     {
1423         let fld_r =
1424             |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct));
1425         let fld_t = |_| {
1426             self.next_ty_var(TypeVariableOrigin {
1427                 kind: TypeVariableOriginKind::MiscVariable,
1428                 span,
1429             })
1430         };
1431         let fld_c = |_, ty| {
1432             self.next_const_var(
1433                 ty,
1434                 ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
1435             )
1436         };
1437         self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
1438     }
1439
1440     /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
1441     pub fn verify_generic_bound(
1442         &self,
1443         origin: SubregionOrigin<'tcx>,
1444         kind: GenericKind<'tcx>,
1445         a: ty::Region<'tcx>,
1446         bound: VerifyBound<'tcx>,
1447     ) {
1448         debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
1449
1450         self.inner
1451             .borrow_mut()
1452             .unwrap_region_constraints()
1453             .verify_generic_bound(origin, kind, a, bound);
1454     }
1455
1456     /// Obtains the latest type of the given closure; this may be a
1457     /// closure in the current function, in which case its
1458     /// `ClosureKind` may not yet be known.
1459     pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
1460         let closure_kind_ty = closure_substs.as_closure().kind_ty();
1461         let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
1462         closure_kind_ty.to_opt_closure_kind()
1463     }
1464
1465     /// Clears the selection, evaluation, and projection caches. This is useful when
1466     /// repeatedly attempting to select an `Obligation` while changing only
1467     /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing.
1468     pub fn clear_caches(&self) {
1469         self.selection_cache.clear();
1470         self.evaluation_cache.clear();
1471         self.inner.borrow_mut().projection_cache().clear();
1472     }
1473
1474     fn universe(&self) -> ty::UniverseIndex {
1475         self.universe.get()
1476     }
1477
1478     /// Creates and return a fresh universe that extends all previous
1479     /// universes. Updates `self.universe` to that new universe.
1480     pub fn create_next_universe(&self) -> ty::UniverseIndex {
1481         let u = self.universe.get().next_universe();
1482         self.universe.set(u);
1483         u
1484     }
1485
1486     /// Resolves and evaluates a constant.
1487     ///
1488     /// The constant can be located on a trait like `<A as B>::C`, in which case the given
1489     /// substitutions and environment are used to resolve the constant. Alternatively if the
1490     /// constant has generic parameters in scope the substitutions are used to evaluate the value of
1491     /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
1492     /// constant `bar::<T>()` requires a substitution for `T`, if the substitution for `T` is still
1493     /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
1494     /// returned.
1495     ///
1496     /// This handles inferences variables within both `param_env` and `substs` by
1497     /// performing the operation on their respective canonical forms.
1498     pub fn const_eval_resolve(
1499         &self,
1500         param_env: ty::ParamEnv<'tcx>,
1501         ty::Unevaluated { def, substs, promoted }: ty::Unevaluated<'tcx>,
1502         span: Option<Span>,
1503     ) -> EvalToConstValueResult<'tcx> {
1504         let mut original_values = OriginalQueryValues::default();
1505         let canonical = self.canonicalize_query((param_env, substs), &mut original_values);
1506
1507         let (param_env, substs) = canonical.value;
1508         // The return value is the evaluated value which doesn't contain any reference to inference
1509         // variables, thus we don't need to substitute back the original values.
1510         self.tcx.const_eval_resolve(param_env, ty::Unevaluated { def, substs, promoted }, span)
1511     }
1512
1513     /// If `typ` is a type variable of some kind, resolve it one level
1514     /// (but do not resolve types found in the result). If `typ` is
1515     /// not a type variable, just return it unmodified.
1516     // FIXME(eddyb) inline into `ShallowResolver::visit_ty`.
1517     fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1518         match *typ.kind() {
1519             ty::Infer(ty::TyVar(v)) => {
1520                 // Not entirely obvious: if `typ` is a type variable,
1521                 // it can be resolved to an int/float variable, which
1522                 // can then be recursively resolved, hence the
1523                 // recursion. Note though that we prevent type
1524                 // variables from unifying to other type variables
1525                 // directly (though they may be embedded
1526                 // structurally), and we prevent cycles in any case,
1527                 // so this recursion should always be of very limited
1528                 // depth.
1529                 //
1530                 // Note: if these two lines are combined into one we get
1531                 // dynamic borrow errors on `self.inner`.
1532                 let known = self.inner.borrow_mut().type_variables().probe(v).known();
1533                 known.map_or(typ, |t| self.shallow_resolve_ty(t))
1534             }
1535
1536             ty::Infer(ty::IntVar(v)) => self
1537                 .inner
1538                 .borrow_mut()
1539                 .int_unification_table()
1540                 .probe_value(v)
1541                 .map(|v| v.to_type(self.tcx))
1542                 .unwrap_or(typ),
1543
1544             ty::Infer(ty::FloatVar(v)) => self
1545                 .inner
1546                 .borrow_mut()
1547                 .float_unification_table()
1548                 .probe_value(v)
1549                 .map(|v| v.to_type(self.tcx))
1550                 .unwrap_or(typ),
1551
1552             _ => typ,
1553         }
1554     }
1555
1556     /// `ty_or_const_infer_var_changed` is equivalent to one of these two:
1557     ///   * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
1558     ///   * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)
1559     ///
1560     /// However, `ty_or_const_infer_var_changed` is more efficient. It's always
1561     /// inlined, despite being large, because it has only two call sites that
1562     /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on`
1563     /// inference variables), and it handles both `Ty` and `ty::Const` without
1564     /// having to resort to storing full `GenericArg`s in `stalled_on`.
1565     #[inline(always)]
1566     pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
1567         match infer_var {
1568             TyOrConstInferVar::Ty(v) => {
1569                 use self::type_variable::TypeVariableValue;
1570
1571                 // If `inlined_probe` returns a `Known` value, it never equals
1572                 // `ty::Infer(ty::TyVar(v))`.
1573                 match self.inner.borrow_mut().type_variables().inlined_probe(v) {
1574                     TypeVariableValue::Unknown { .. } => false,
1575                     TypeVariableValue::Known { .. } => true,
1576                 }
1577             }
1578
1579             TyOrConstInferVar::TyInt(v) => {
1580                 // If `inlined_probe_value` returns a value it's always a
1581                 // `ty::Int(_)` or `ty::UInt(_)`, which never matches a
1582                 // `ty::Infer(_)`.
1583                 self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
1584             }
1585
1586             TyOrConstInferVar::TyFloat(v) => {
1587                 // If `probe_value` returns a value it's always a
1588                 // `ty::Float(_)`, which never matches a `ty::Infer(_)`.
1589                 //
1590                 // Not `inlined_probe_value(v)` because this call site is colder.
1591                 self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
1592             }
1593
1594             TyOrConstInferVar::Const(v) => {
1595                 // If `probe_value` returns a `Known` value, it never equals
1596                 // `ty::ConstKind::Infer(ty::InferConst::Var(v))`.
1597                 //
1598                 // Not `inlined_probe_value(v)` because this call site is colder.
1599                 match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
1600                     ConstVariableValue::Unknown { .. } => false,
1601                     ConstVariableValue::Known { .. } => true,
1602                 }
1603             }
1604         }
1605     }
1606 }
1607
1608 /// Helper for `ty_or_const_infer_var_changed` (see comment on that), currently
1609 /// used only for `traits::fulfill`'s list of `stalled_on` inference variables.
1610 #[derive(Copy, Clone, Debug)]
1611 pub enum TyOrConstInferVar<'tcx> {
1612     /// Equivalent to `ty::Infer(ty::TyVar(_))`.
1613     Ty(TyVid),
1614     /// Equivalent to `ty::Infer(ty::IntVar(_))`.
1615     TyInt(IntVid),
1616     /// Equivalent to `ty::Infer(ty::FloatVar(_))`.
1617     TyFloat(FloatVid),
1618
1619     /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`.
1620     Const(ConstVid<'tcx>),
1621 }
1622
1623 impl TyOrConstInferVar<'tcx> {
1624     /// Tries to extract an inference variable from a type or a constant, returns `None`
1625     /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and
1626     /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1627     pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
1628         match arg.unpack() {
1629             GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
1630             GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
1631             GenericArgKind::Lifetime(_) => None,
1632         }
1633     }
1634
1635     /// Tries to extract an inference variable from a type, returns `None`
1636     /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`).
1637     pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
1638         match *ty.kind() {
1639             ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
1640             ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
1641             ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
1642             _ => None,
1643         }
1644     }
1645
1646     /// Tries to extract an inference variable from a constant, returns `None`
1647     /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`).
1648     pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
1649         match ct.val {
1650             ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
1651             _ => None,
1652         }
1653     }
1654 }
1655
1656 struct ShallowResolver<'a, 'tcx> {
1657     infcx: &'a InferCtxt<'a, 'tcx>,
1658 }
1659
1660 impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
1661     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
1662         self.infcx.tcx
1663     }
1664
1665     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1666         self.infcx.shallow_resolve_ty(ty)
1667     }
1668
1669     fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
1670         if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
1671             self.infcx
1672                 .inner
1673                 .borrow_mut()
1674                 .const_unification_table()
1675                 .probe_value(*vid)
1676                 .val
1677                 .known()
1678                 .unwrap_or(ct)
1679         } else {
1680             ct
1681         }
1682     }
1683 }
1684
1685 impl<'tcx> TypeTrace<'tcx> {
1686     pub fn span(&self) -> Span {
1687         self.cause.span
1688     }
1689
1690     pub fn types(
1691         cause: &ObligationCause<'tcx>,
1692         a_is_expected: bool,
1693         a: Ty<'tcx>,
1694         b: Ty<'tcx>,
1695     ) -> TypeTrace<'tcx> {
1696         TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
1697     }
1698
1699     pub fn consts(
1700         cause: &ObligationCause<'tcx>,
1701         a_is_expected: bool,
1702         a: &'tcx ty::Const<'tcx>,
1703         b: &'tcx ty::Const<'tcx>,
1704     ) -> TypeTrace<'tcx> {
1705         TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
1706     }
1707
1708     pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
1709         let err = tcx.ty_error();
1710         TypeTrace {
1711             cause: ObligationCause::dummy(),
1712             values: Types(ExpectedFound { expected: err, found: err }),
1713         }
1714     }
1715 }
1716
1717 impl<'tcx> SubregionOrigin<'tcx> {
1718     pub fn span(&self) -> Span {
1719         match *self {
1720             Subtype(ref a) => a.span(),
1721             RelateObjectBound(a) => a,
1722             RelateParamBound(a, _) => a,
1723             RelateRegionParamBound(a) => a,
1724             Reborrow(a) => a,
1725             ReborrowUpvar(a, _) => a,
1726             DataBorrowed(_, a) => a,
1727             ReferenceOutlivesReferent(_, a) => a,
1728             CallReturn(a) => a,
1729             CompareImplMethodObligation { span, .. } => span,
1730         }
1731     }
1732
1733     pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
1734     where
1735         F: FnOnce() -> Self,
1736     {
1737         match cause.code {
1738             traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
1739                 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
1740             }
1741
1742             traits::ObligationCauseCode::CompareImplMethodObligation {
1743                 item_name,
1744                 impl_item_def_id,
1745                 trait_item_def_id,
1746             } => SubregionOrigin::CompareImplMethodObligation {
1747                 span: cause.span,
1748                 item_name,
1749                 impl_item_def_id,
1750                 trait_item_def_id,
1751             },
1752
1753             _ => default(),
1754         }
1755     }
1756 }
1757
1758 impl RegionVariableOrigin {
1759     pub fn span(&self) -> Span {
1760         match *self {
1761             MiscVariable(a)
1762             | PatternRegion(a)
1763             | AddrOfRegion(a)
1764             | Autoref(a, _)
1765             | Coercion(a)
1766             | EarlyBoundRegion(a, ..)
1767             | LateBoundRegion(a, ..)
1768             | UpvarRegion(_, a) => a,
1769             BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
1770             Nll(..) => bug!("NLL variable used with `span`"),
1771         }
1772     }
1773 }
1774
1775 impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
1776     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1777         write!(
1778             f,
1779             "RegionObligation(sub_region={:?}, sup_type={:?})",
1780             self.sub_region, self.sup_type
1781         )
1782     }
1783 }