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