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