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