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