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