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