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