]> git.lizzy.rs Git - rust.git/blob - src/librustc/infer/mod.rs
Auto merge of #40367 - eddyb:naked-cruft, r=nagisa
[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::LateBoundRegionConversionTime::*;
14 pub use self::RegionVariableOrigin::*;
15 pub use self::SubregionOrigin::*;
16 pub use self::ValuePairs::*;
17 pub use ty::IntVarValue;
18 pub use self::freshen::TypeFreshener;
19 pub use self::region_inference::{GenericKind, VerifyBound};
20
21 use hir::def_id::DefId;
22 use hir;
23 use middle::free_region::FreeRegionMap;
24 use middle::mem_categorization as mc;
25 use middle::mem_categorization::McResult;
26 use middle::lang_items;
27 use mir::tcx::LvalueTy;
28 use ty::subst::{Kind, Subst, Substs};
29 use ty::{TyVid, IntVid, FloatVid};
30 use ty::{self, Ty, TyCtxt};
31 use ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
32 use ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
33 use ty::relate::{Relate, RelateResult, TypeRelation};
34 use traits::{self, ObligationCause, PredicateObligations, Reveal};
35 use rustc_data_structures::unify::{self, UnificationTable};
36 use std::cell::{Cell, RefCell, Ref, RefMut};
37 use std::fmt;
38 use std::ops::Deref;
39 use syntax::ast;
40 use errors::DiagnosticBuilder;
41 use syntax_pos::{self, Span, DUMMY_SP};
42 use util::nodemap::{FxHashMap, FxHashSet};
43 use arena::DroplessArena;
44
45 use self::combine::CombineFields;
46 use self::higher_ranked::HrMatchResult;
47 use self::region_inference::{RegionVarBindings, RegionSnapshot};
48 use self::type_variable::TypeVariableOrigin;
49 use self::unify_key::ToType;
50
51 mod combine;
52 mod equate;
53 pub mod error_reporting;
54 mod fudge;
55 mod glb;
56 mod higher_ranked;
57 pub mod lattice;
58 mod lub;
59 pub mod region_inference;
60 pub mod resolve;
61 mod freshen;
62 mod sub;
63 pub mod type_variable;
64 pub mod unify_key;
65
66 #[must_use]
67 pub struct InferOk<'tcx, T> {
68     pub value: T,
69     pub obligations: PredicateObligations<'tcx>,
70 }
71 pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
72
73 pub type Bound<T> = Option<T>;
74 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
75 pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
76
77 /// A version of &ty::TypeckTables which can be `Missing` (not needed),
78 /// `InProgress` (during typeck) or `Interned` (result of typeck).
79 /// Only the `InProgress` version supports `borrow_mut`.
80 #[derive(Copy, Clone)]
81 pub enum InferTables<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
82     Interned(&'a ty::TypeckTables<'gcx>),
83     InProgress(&'a RefCell<ty::TypeckTables<'tcx>>),
84     Missing
85 }
86
87 pub enum InferTablesRef<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
88     Interned(&'a ty::TypeckTables<'gcx>),
89     InProgress(Ref<'a, ty::TypeckTables<'tcx>>)
90 }
91
92 impl<'a, 'gcx, 'tcx> Deref for InferTablesRef<'a, 'gcx, 'tcx> {
93     type Target = ty::TypeckTables<'tcx>;
94     fn deref(&self) -> &Self::Target {
95         match *self {
96             InferTablesRef::Interned(tables) => tables,
97             InferTablesRef::InProgress(ref tables) => tables
98         }
99     }
100 }
101
102 impl<'a, 'gcx, 'tcx> InferTables<'a, 'gcx, 'tcx> {
103     pub fn borrow(self) -> InferTablesRef<'a, 'gcx, 'tcx> {
104         match self {
105             InferTables::Interned(tables) => InferTablesRef::Interned(tables),
106             InferTables::InProgress(tables) => InferTablesRef::InProgress(tables.borrow()),
107             InferTables::Missing => {
108                 bug!("InferTables: infcx.tables.borrow() with no tables")
109             }
110         }
111     }
112
113     pub fn expect_interned(self) -> &'a ty::TypeckTables<'gcx> {
114         match self {
115             InferTables::Interned(tables) => tables,
116             InferTables::InProgress(_) => {
117                 bug!("InferTables: infcx.tables.expect_interned() during type-checking");
118             }
119             InferTables::Missing => {
120                 bug!("InferTables: infcx.tables.expect_interned() with no tables")
121             }
122         }
123     }
124
125     pub fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> {
126         match self {
127             InferTables::Interned(_) => {
128                 bug!("InferTables: infcx.tables.borrow_mut() outside of type-checking");
129             }
130             InferTables::InProgress(tables) => tables.borrow_mut(),
131             InferTables::Missing => {
132                 bug!("InferTables: infcx.tables.borrow_mut() with no tables")
133             }
134         }
135     }
136 }
137
138 pub struct InferCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
139     pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
140
141     pub tables: InferTables<'a, 'gcx, 'tcx>,
142
143     // Cache for projections. This cache is snapshotted along with the
144     // infcx.
145     //
146     // Public so that `traits::project` can use it.
147     pub projection_cache: RefCell<traits::ProjectionCache<'tcx>>,
148
149     // We instantiate UnificationTable with bounds<Ty> because the
150     // types that might instantiate a general type variable have an
151     // order, represented by its upper and lower bounds.
152     pub type_variables: RefCell<type_variable::TypeVariableTable<'tcx>>,
153
154     // Map from integral variable to the kind of integer it represents
155     int_unification_table: RefCell<UnificationTable<ty::IntVid>>,
156
157     // Map from floating variable to the kind of float it represents
158     float_unification_table: RefCell<UnificationTable<ty::FloatVid>>,
159
160     // For region variables.
161     region_vars: RegionVarBindings<'a, 'gcx, 'tcx>,
162
163     pub parameter_environment: ty::ParameterEnvironment<'gcx>,
164
165     /// Caches the results of trait selection. This cache is used
166     /// for things that have to do with the parameters in scope.
167     pub selection_cache: traits::SelectionCache<'tcx>,
168
169     /// Caches the results of trait evaluation.
170     pub evaluation_cache: traits::EvaluationCache<'tcx>,
171
172     // the set of predicates on which errors have been reported, to
173     // avoid reporting the same error twice.
174     pub reported_trait_errors: RefCell<FxHashSet<traits::TraitErrorKey<'tcx>>>,
175
176     // Sadly, the behavior of projection varies a bit depending on the
177     // stage of compilation. The specifics are given in the
178     // documentation for `Reveal`.
179     projection_mode: Reveal,
180
181     // When an error occurs, we want to avoid reporting "derived"
182     // errors that are due to this original failure. Normally, we
183     // handle this with the `err_count_on_creation` count, which
184     // basically just tracks how many errors were reported when we
185     // started type-checking a fn and checks to see if any new errors
186     // have been reported since then. Not great, but it works.
187     //
188     // However, when errors originated in other passes -- notably
189     // resolve -- this heuristic breaks down. Therefore, we have this
190     // auxiliary flag that one can set whenever one creates a
191     // type-error that is due to an error in a prior pass.
192     //
193     // Don't read this flag directly, call `is_tainted_by_errors()`
194     // and `set_tainted_by_errors()`.
195     tainted_by_errors_flag: Cell<bool>,
196
197     // Track how many errors were reported when this infcx is created.
198     // If the number of errors increases, that's also a sign (line
199     // `tained_by_errors`) to avoid reporting certain kinds of errors.
200     err_count_on_creation: usize,
201
202     // This flag is used for debugging, and is set to true if there are
203     // any obligations set during the current snapshot. In that case, the
204     // snapshot can't be rolled back.
205     pub obligations_in_snapshot: Cell<bool>,
206 }
207
208 /// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
209 /// region that each late-bound region was replaced with.
210 pub type SkolemizationMap<'tcx> = FxHashMap<ty::BoundRegion, &'tcx ty::Region>;
211
212 /// See `error_reporting` module for more details
213 #[derive(Clone, Debug)]
214 pub enum ValuePairs<'tcx> {
215     Types(ExpectedFound<Ty<'tcx>>),
216     TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
217     PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
218 }
219
220 /// The trace designates the path through inference that we took to
221 /// encounter an error or subtyping constraint.
222 ///
223 /// See `error_reporting` module for more details.
224 #[derive(Clone)]
225 pub struct TypeTrace<'tcx> {
226     cause: ObligationCause<'tcx>,
227     values: ValuePairs<'tcx>,
228 }
229
230 /// The origin of a `r1 <= r2` constraint.
231 ///
232 /// See `error_reporting` module for more details
233 #[derive(Clone, Debug)]
234 pub enum SubregionOrigin<'tcx> {
235     // Arose from a subtyping relation
236     Subtype(TypeTrace<'tcx>),
237
238     // Stack-allocated closures cannot outlive innermost loop
239     // or function so as to ensure we only require finite stack
240     InfStackClosure(Span),
241
242     // Invocation of closure must be within its lifetime
243     InvokeClosure(Span),
244
245     // Dereference of reference must be within its lifetime
246     DerefPointer(Span),
247
248     // Closure bound must not outlive captured free variables
249     FreeVariable(Span, ast::NodeId),
250
251     // Index into slice must be within its lifetime
252     IndexSlice(Span),
253
254     // When casting `&'a T` to an `&'b Trait` object,
255     // relating `'a` to `'b`
256     RelateObjectBound(Span),
257
258     // Some type parameter was instantiated with the given type,
259     // and that type must outlive some region.
260     RelateParamBound(Span, Ty<'tcx>),
261
262     // The given region parameter was instantiated with a region
263     // that must outlive some other region.
264     RelateRegionParamBound(Span),
265
266     // A bound placed on type parameters that states that must outlive
267     // the moment of their instantiation.
268     RelateDefaultParamBound(Span, Ty<'tcx>),
269
270     // Creating a pointer `b` to contents of another reference
271     Reborrow(Span),
272
273     // Creating a pointer `b` to contents of an upvar
274     ReborrowUpvar(Span, ty::UpvarId),
275
276     // Data with type `Ty<'tcx>` was borrowed
277     DataBorrowed(Ty<'tcx>, Span),
278
279     // (&'a &'b T) where a >= b
280     ReferenceOutlivesReferent(Ty<'tcx>, Span),
281
282     // Type or region parameters must be in scope.
283     ParameterInScope(ParameterOrigin, Span),
284
285     // The type T of an expression E must outlive the lifetime for E.
286     ExprTypeIsNotInScope(Ty<'tcx>, Span),
287
288     // A `ref b` whose region does not enclose the decl site
289     BindingTypeIsNotValidAtDecl(Span),
290
291     // Regions appearing in a method receiver must outlive method call
292     CallRcvr(Span),
293
294     // Regions appearing in a function argument must outlive func call
295     CallArg(Span),
296
297     // Region in return type of invoked fn must enclose call
298     CallReturn(Span),
299
300     // Operands must be in scope
301     Operand(Span),
302
303     // Region resulting from a `&` expr must enclose the `&` expr
304     AddrOf(Span),
305
306     // An auto-borrow that does not enclose the expr where it occurs
307     AutoBorrow(Span),
308
309     // Region constraint arriving from destructor safety
310     SafeDestructor(Span),
311
312     // Comparing the signature and requirements of an impl method against
313     // the containing trait.
314     CompareImplMethodObligation {
315         span: Span,
316         item_name: ast::Name,
317         impl_item_def_id: DefId,
318         trait_item_def_id: DefId,
319
320         // this is `Some(_)` if this error arises from the bug fix for
321         // #18937. This is a temporary measure.
322         lint_id: Option<ast::NodeId>,
323     },
324 }
325
326 /// Places that type/region parameters can appear.
327 #[derive(Clone, Copy, Debug)]
328 pub enum ParameterOrigin {
329     Path, // foo::bar
330     MethodCall, // foo.bar() <-- parameters on impl providing bar()
331     OverloadedOperator, // a + b when overloaded
332     OverloadedDeref, // *a when overloaded
333 }
334
335 /// Times when we replace late-bound regions with variables:
336 #[derive(Clone, Copy, Debug)]
337 pub enum LateBoundRegionConversionTime {
338     /// when a fn is called
339     FnCall,
340
341     /// when two higher-ranked types are compared
342     HigherRankedType,
343
344     /// when projecting an associated type
345     AssocTypeProjection(ast::Name),
346 }
347
348 /// Reasons to create a region inference variable
349 ///
350 /// See `error_reporting` module for more details
351 #[derive(Clone, Debug)]
352 pub enum RegionVariableOrigin {
353     // Region variables created for ill-categorized reasons,
354     // mostly indicates places in need of refactoring
355     MiscVariable(Span),
356
357     // Regions created by a `&P` or `[...]` pattern
358     PatternRegion(Span),
359
360     // Regions created by `&` operator
361     AddrOfRegion(Span),
362
363     // Regions created as part of an autoref of a method receiver
364     Autoref(Span),
365
366     // Regions created as part of an automatic coercion
367     Coercion(Span),
368
369     // Region variables created as the values for early-bound regions
370     EarlyBoundRegion(Span, ast::Name, Option<ty::Issue32330>),
371
372     // Region variables created for bound regions
373     // in a function or method that is called
374     LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
375
376     UpvarRegion(ty::UpvarId, Span),
377
378     BoundRegionInCoherence(ast::Name),
379 }
380
381 #[derive(Copy, Clone, Debug)]
382 pub enum FixupError {
383     UnresolvedIntTy(IntVid),
384     UnresolvedFloatTy(FloatVid),
385     UnresolvedTy(TyVid)
386 }
387
388 impl fmt::Display for FixupError {
389     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
390         use self::FixupError::*;
391
392         match *self {
393             UnresolvedIntTy(_) => {
394                 write!(f, "cannot determine the type of this integer; \
395                            add a suffix to specify the type explicitly")
396             }
397             UnresolvedFloatTy(_) => {
398                 write!(f, "cannot determine the type of this number; \
399                            add a suffix to specify the type explicitly")
400             }
401             UnresolvedTy(_) => write!(f, "unconstrained type")
402         }
403     }
404 }
405
406 pub trait InferEnv<'a, 'tcx> {
407     fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
408                 -> (Option<&'a ty::TypeckTables<'tcx>>,
409                     Option<ty::TypeckTables<'tcx>>,
410                     Option<ty::ParameterEnvironment<'tcx>>);
411 }
412
413 impl<'a, 'tcx> InferEnv<'a, 'tcx> for () {
414     fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
415                 -> (Option<&'a ty::TypeckTables<'tcx>>,
416                     Option<ty::TypeckTables<'tcx>>,
417                     Option<ty::ParameterEnvironment<'tcx>>) {
418         (None, None, None)
419     }
420 }
421
422 impl<'a, 'tcx> InferEnv<'a, 'tcx> for ty::ParameterEnvironment<'tcx> {
423     fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
424                 -> (Option<&'a ty::TypeckTables<'tcx>>,
425                     Option<ty::TypeckTables<'tcx>>,
426                     Option<ty::ParameterEnvironment<'tcx>>) {
427         (None, None, Some(self))
428     }
429 }
430
431 impl<'a, 'tcx> InferEnv<'a, 'tcx> for (&'a ty::TypeckTables<'tcx>, ty::ParameterEnvironment<'tcx>) {
432     fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
433                 -> (Option<&'a ty::TypeckTables<'tcx>>,
434                     Option<ty::TypeckTables<'tcx>>,
435                     Option<ty::ParameterEnvironment<'tcx>>) {
436         (Some(self.0), None, Some(self.1))
437     }
438 }
439
440 impl<'a, 'tcx> InferEnv<'a, 'tcx> for (ty::TypeckTables<'tcx>, ty::ParameterEnvironment<'tcx>) {
441     fn to_parts(self, _: TyCtxt<'a, 'tcx, 'tcx>)
442                 -> (Option<&'a ty::TypeckTables<'tcx>>,
443                     Option<ty::TypeckTables<'tcx>>,
444                     Option<ty::ParameterEnvironment<'tcx>>) {
445         (None, Some(self.0), Some(self.1))
446     }
447 }
448
449 impl<'a, 'tcx> InferEnv<'a, 'tcx> for hir::BodyId {
450     fn to_parts(self, tcx: TyCtxt<'a, 'tcx, 'tcx>)
451                 -> (Option<&'a ty::TypeckTables<'tcx>>,
452                     Option<ty::TypeckTables<'tcx>>,
453                     Option<ty::ParameterEnvironment<'tcx>>) {
454         let item_id = tcx.hir.body_owner(self);
455         (Some(tcx.item_tables(tcx.hir.local_def_id(item_id))),
456          None,
457          Some(ty::ParameterEnvironment::for_item(tcx, item_id)))
458     }
459 }
460
461 /// Helper type of a temporary returned by tcx.infer_ctxt(...).
462 /// Necessary because we can't write the following bound:
463 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(InferCtxt<'b, 'gcx, 'tcx>).
464 pub struct InferCtxtBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
465     global_tcx: TyCtxt<'a, 'gcx, 'gcx>,
466     arena: DroplessArena,
467     fresh_tables: Option<RefCell<ty::TypeckTables<'tcx>>>,
468     tables: Option<&'a ty::TypeckTables<'gcx>>,
469     param_env: Option<ty::ParameterEnvironment<'gcx>>,
470     projection_mode: Reveal,
471 }
472
473 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
474     pub fn infer_ctxt<E: InferEnv<'a, 'gcx>>(self,
475                                              env: E,
476                                              projection_mode: Reveal)
477                                              -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
478         let (tables, fresh_tables, param_env) = env.to_parts(self);
479         InferCtxtBuilder {
480             global_tcx: self,
481             arena: DroplessArena::new(),
482             fresh_tables: fresh_tables.map(RefCell::new),
483             tables: tables,
484             param_env: param_env,
485             projection_mode: projection_mode,
486         }
487     }
488
489     /// Fake InferCtxt with the global tcx. Used by pre-MIR borrowck
490     /// for MemCategorizationContext/ExprUseVisitor.
491     /// If any inference functionality is used, ICEs will occur.
492     pub fn borrowck_fake_infer_ctxt(self, body: hir::BodyId)
493                                     -> InferCtxt<'a, 'gcx, 'gcx> {
494         let (tables, _, param_env) = body.to_parts(self);
495         InferCtxt {
496             tcx: self,
497             tables: InferTables::Interned(tables.unwrap()),
498             type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
499             int_unification_table: RefCell::new(UnificationTable::new()),
500             float_unification_table: RefCell::new(UnificationTable::new()),
501             region_vars: RegionVarBindings::new(self),
502             parameter_environment: param_env.unwrap(),
503             selection_cache: traits::SelectionCache::new(),
504             evaluation_cache: traits::EvaluationCache::new(),
505             projection_cache: RefCell::new(traits::ProjectionCache::new()),
506             reported_trait_errors: RefCell::new(FxHashSet()),
507             projection_mode: Reveal::UserFacing,
508             tainted_by_errors_flag: Cell::new(false),
509             err_count_on_creation: self.sess.err_count(),
510             obligations_in_snapshot: Cell::new(false),
511         }
512     }
513 }
514
515 impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
516     pub fn enter<F, R>(&'tcx mut self, f: F) -> R
517         where F: for<'b> FnOnce(InferCtxt<'b, 'gcx, 'tcx>) -> R
518     {
519         let InferCtxtBuilder {
520             global_tcx,
521             ref arena,
522             ref fresh_tables,
523             tables,
524             ref mut param_env,
525             projection_mode,
526         } = *self;
527         let tables = tables.map(InferTables::Interned).unwrap_or_else(|| {
528             fresh_tables.as_ref().map_or(InferTables::Missing, InferTables::InProgress)
529         });
530         let param_env = param_env.take().unwrap_or_else(|| {
531             global_tcx.empty_parameter_environment()
532         });
533         global_tcx.enter_local(arena, |tcx| f(InferCtxt {
534             tcx: tcx,
535             tables: tables,
536             projection_cache: RefCell::new(traits::ProjectionCache::new()),
537             type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
538             int_unification_table: RefCell::new(UnificationTable::new()),
539             float_unification_table: RefCell::new(UnificationTable::new()),
540             region_vars: RegionVarBindings::new(tcx),
541             parameter_environment: param_env,
542             selection_cache: traits::SelectionCache::new(),
543             evaluation_cache: traits::EvaluationCache::new(),
544             reported_trait_errors: RefCell::new(FxHashSet()),
545             projection_mode: projection_mode,
546             tainted_by_errors_flag: Cell::new(false),
547             err_count_on_creation: tcx.sess.err_count(),
548             obligations_in_snapshot: Cell::new(false),
549         }))
550     }
551 }
552
553 impl<T> ExpectedFound<T> {
554     pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
555         if a_is_expected {
556             ExpectedFound {expected: a, found: b}
557         } else {
558             ExpectedFound {expected: b, found: a}
559         }
560     }
561 }
562
563 impl<'tcx, T> InferOk<'tcx, T> {
564     pub fn unit(self) -> InferOk<'tcx, ()> {
565         InferOk { value: (), obligations: self.obligations }
566     }
567 }
568
569 #[must_use = "once you start a snapshot, you should always consume it"]
570 pub struct CombinedSnapshot {
571     projection_cache_snapshot: traits::ProjectionCacheSnapshot,
572     type_snapshot: type_variable::Snapshot,
573     int_snapshot: unify::Snapshot<ty::IntVid>,
574     float_snapshot: unify::Snapshot<ty::FloatVid>,
575     region_vars_snapshot: RegionSnapshot,
576     obligations_in_snapshot: bool,
577 }
578
579 /// Helper trait for shortening the lifetimes inside a
580 /// value for post-type-checking normalization.
581 pub trait TransNormalize<'gcx>: TypeFoldable<'gcx> {
582     fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self;
583 }
584
585 macro_rules! items { ($($item:item)+) => ($($item)+) }
586 macro_rules! impl_trans_normalize {
587     ($lt_gcx:tt, $($ty:ty),+) => {
588         items!($(impl<$lt_gcx> TransNormalize<$lt_gcx> for $ty {
589             fn trans_normalize<'a, 'tcx>(&self,
590                                          infcx: &InferCtxt<'a, $lt_gcx, 'tcx>)
591                                          -> Self {
592                 infcx.normalize_projections_in(self)
593             }
594         })+);
595     }
596 }
597
598 impl_trans_normalize!('gcx,
599     Ty<'gcx>,
600     &'gcx Substs<'gcx>,
601     ty::FnSig<'gcx>,
602     ty::PolyFnSig<'gcx>,
603     ty::ClosureSubsts<'gcx>,
604     ty::PolyTraitRef<'gcx>,
605     ty::ExistentialTraitRef<'gcx>
606 );
607
608 impl<'gcx> TransNormalize<'gcx> for LvalueTy<'gcx> {
609     fn trans_normalize<'a, 'tcx>(&self, infcx: &InferCtxt<'a, 'gcx, 'tcx>) -> Self {
610         match *self {
611             LvalueTy::Ty { ty } => LvalueTy::Ty { ty: ty.trans_normalize(infcx) },
612             LvalueTy::Downcast { adt_def, substs, variant_index } => {
613                 LvalueTy::Downcast {
614                     adt_def: adt_def,
615                     substs: substs.trans_normalize(infcx),
616                     variant_index: variant_index
617                 }
618             }
619         }
620     }
621 }
622
623 // NOTE: Callable from trans only!
624 impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
625     /// Currently, higher-ranked type bounds inhibit normalization. Therefore,
626     /// each time we erase them in translation, we need to normalize
627     /// the contents.
628     pub fn erase_late_bound_regions_and_normalize<T>(self, value: &ty::Binder<T>)
629         -> T
630         where T: TransNormalize<'tcx>
631     {
632         assert!(!value.needs_subst());
633         let value = self.erase_late_bound_regions(value);
634         self.normalize_associated_type(&value)
635     }
636
637     pub fn normalize_associated_type<T>(self, value: &T) -> T
638         where T: TransNormalize<'tcx>
639     {
640         debug!("normalize_associated_type(t={:?})", value);
641
642         let value = self.erase_regions(value);
643
644         if !value.has_projection_types() {
645             return value;
646         }
647
648         self.infer_ctxt((), Reveal::All).enter(|infcx| {
649             value.trans_normalize(&infcx)
650         })
651     }
652
653     pub fn normalize_associated_type_in_env<T>(
654         self, value: &T, env: &'a ty::ParameterEnvironment<'tcx>
655     ) -> T
656         where T: TransNormalize<'tcx>
657     {
658         debug!("normalize_associated_type_in_env(t={:?})", value);
659
660         let value = self.erase_regions(value);
661
662         if !value.has_projection_types() {
663             return value;
664         }
665
666         self.infer_ctxt(env.clone(), Reveal::All).enter(|infcx| {
667             value.trans_normalize(&infcx)
668        })
669     }
670 }
671
672 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
673     fn normalize_projections_in<T>(&self, value: &T) -> T::Lifted
674         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
675     {
676         let mut selcx = traits::SelectionContext::new(self);
677         let cause = traits::ObligationCause::dummy();
678         let traits::Normalized { value: result, obligations } =
679             traits::normalize(&mut selcx, cause, value);
680
681         debug!("normalize_projections_in: result={:?} obligations={:?}",
682                 result, obligations);
683
684         let mut fulfill_cx = traits::FulfillmentContext::new();
685
686         for obligation in obligations {
687             fulfill_cx.register_predicate_obligation(self, obligation);
688         }
689
690         self.drain_fulfillment_cx_or_panic(DUMMY_SP, &mut fulfill_cx, &result)
691     }
692
693     /// Finishes processes any obligations that remain in the
694     /// fulfillment context, and then returns the result with all type
695     /// variables removed and regions erased. Because this is intended
696     /// for use after type-check has completed, if any errors occur,
697     /// it will panic. It is used during normalization and other cases
698     /// where processing the obligations in `fulfill_cx` may cause
699     /// type inference variables that appear in `result` to be
700     /// unified, and hence we need to process those obligations to get
701     /// the complete picture of the type.
702     pub fn drain_fulfillment_cx_or_panic<T>(&self,
703                                             span: Span,
704                                             fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
705                                             result: &T)
706                                             -> T::Lifted
707         where T: TypeFoldable<'tcx> + ty::Lift<'gcx>
708     {
709         debug!("drain_fulfillment_cx_or_panic()");
710
711         // In principle, we only need to do this so long as `result`
712         // contains unbound type parameters. It could be a slight
713         // optimization to stop iterating early.
714         match fulfill_cx.select_all_or_error(self) {
715             Ok(()) => { }
716             Err(errors) => {
717                 span_bug!(span, "Encountered errors `{:?}` resolving bounds after type-checking",
718                           errors);
719             }
720         }
721
722         let result = self.resolve_type_vars_if_possible(result);
723         let result = self.tcx.erase_regions(&result);
724
725         match self.tcx.lift_to_global(&result) {
726             Some(result) => result,
727             None => {
728                 span_bug!(span, "Uninferred types/regions in `{:?}`", result);
729             }
730         }
731     }
732
733     pub fn projection_mode(&self) -> Reveal {
734         self.projection_mode
735     }
736
737     pub fn freshen<T:TypeFoldable<'tcx>>(&self, t: T) -> T {
738         t.fold_with(&mut self.freshener())
739     }
740
741     pub fn type_var_diverges(&'a self, ty: Ty) -> bool {
742         match ty.sty {
743             ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().var_diverges(vid),
744             _ => false
745         }
746     }
747
748     pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'gcx, 'tcx> {
749         freshen::TypeFreshener::new(self)
750     }
751
752     pub fn type_is_unconstrained_numeric(&'a self, ty: Ty) -> UnconstrainedNumeric {
753         use ty::error::UnconstrainedNumeric::Neither;
754         use ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
755         match ty.sty {
756             ty::TyInfer(ty::IntVar(vid)) => {
757                 if self.int_unification_table.borrow_mut().has_value(vid) {
758                     Neither
759                 } else {
760                     UnconstrainedInt
761                 }
762             },
763             ty::TyInfer(ty::FloatVar(vid)) => {
764                 if self.float_unification_table.borrow_mut().has_value(vid) {
765                     Neither
766                 } else {
767                     UnconstrainedFloat
768                 }
769             },
770             _ => Neither,
771         }
772     }
773
774     /// Returns a type variable's default fallback if any exists. A default
775     /// must be attached to the variable when created, if it is created
776     /// without a default, this will return None.
777     ///
778     /// This code does not apply to integral or floating point variables,
779     /// only to use declared defaults.
780     ///
781     /// See `new_ty_var_with_default` to create a type variable with a default.
782     /// See `type_variable::Default` for details about what a default entails.
783     pub fn default(&self, ty: Ty<'tcx>) -> Option<type_variable::Default<'tcx>> {
784         match ty.sty {
785             ty::TyInfer(ty::TyVar(vid)) => self.type_variables.borrow().default(vid),
786             _ => None
787         }
788     }
789
790     pub fn unsolved_variables(&self) -> Vec<ty::Ty<'tcx>> {
791         let mut variables = Vec::new();
792
793         let unbound_ty_vars = self.type_variables
794                                   .borrow_mut()
795                                   .unsolved_variables()
796                                   .into_iter()
797                                   .map(|t| self.tcx.mk_var(t));
798
799         let unbound_int_vars = self.int_unification_table
800                                    .borrow_mut()
801                                    .unsolved_variables()
802                                    .into_iter()
803                                    .map(|v| self.tcx.mk_int_var(v));
804
805         let unbound_float_vars = self.float_unification_table
806                                      .borrow_mut()
807                                      .unsolved_variables()
808                                      .into_iter()
809                                      .map(|v| self.tcx.mk_float_var(v));
810
811         variables.extend(unbound_ty_vars);
812         variables.extend(unbound_int_vars);
813         variables.extend(unbound_float_vars);
814
815         return variables;
816     }
817
818     fn combine_fields(&'a self, trace: TypeTrace<'tcx>)
819                       -> CombineFields<'a, 'gcx, 'tcx> {
820         CombineFields {
821             infcx: self,
822             trace: trace,
823             cause: None,
824             obligations: PredicateObligations::new(),
825         }
826     }
827
828     pub fn equate<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
829         -> InferResult<'tcx, T>
830         where T: Relate<'tcx>
831     {
832         let mut fields = self.combine_fields(trace);
833         let result = fields.equate(a_is_expected).relate(a, b);
834         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
835     }
836
837     pub fn sub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
838         -> InferResult<'tcx, T>
839         where T: Relate<'tcx>
840     {
841         let mut fields = self.combine_fields(trace);
842         let result = fields.sub(a_is_expected).relate(a, b);
843         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
844     }
845
846     pub fn lub<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
847         -> InferResult<'tcx, T>
848         where T: Relate<'tcx>
849     {
850         let mut fields = self.combine_fields(trace);
851         let result = fields.lub(a_is_expected).relate(a, b);
852         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
853     }
854
855     pub fn glb<T>(&'a self, a_is_expected: bool, trace: TypeTrace<'tcx>, a: &T, b: &T)
856         -> InferResult<'tcx, T>
857         where T: Relate<'tcx>
858     {
859         let mut fields = self.combine_fields(trace);
860         let result = fields.glb(a_is_expected).relate(a, b);
861         result.map(move |t| InferOk { value: t, obligations: fields.obligations })
862     }
863
864     // Clear the "obligations in snapshot" flag, invoke the closure,
865     // then restore the flag to its original value. This flag is a
866     // debugging measure designed to detect cases where we start a
867     // snapshot, create type variables, register obligations involving
868     // those type variables in the fulfillment cx, and then have to
869     // unroll the snapshot, leaving "dangling type variables" behind.
870     // In such cases, the flag will be set by the fulfillment cx, and
871     // an assertion will fail when rolling the snapshot back.  Very
872     // useful, much better than grovelling through megabytes of
873     // RUST_LOG output.
874     //
875     // HOWEVER, in some cases the flag is wrong. In particular, we
876     // sometimes create a "mini-fulfilment-cx" in which we enroll
877     // obligations. As long as this fulfillment cx is fully drained
878     // before we return, this is not a problem, as there won't be any
879     // escaping obligations in the main cx. In those cases, you can
880     // use this function.
881     pub fn save_and_restore_obligations_in_snapshot_flag<F, R>(&self, func: F) -> R
882         where F: FnOnce(&Self) -> R
883     {
884         let flag = self.obligations_in_snapshot.get();
885         self.obligations_in_snapshot.set(false);
886         let result = func(self);
887         self.obligations_in_snapshot.set(flag);
888         result
889     }
890
891     fn start_snapshot(&self) -> CombinedSnapshot {
892         debug!("start_snapshot()");
893
894         let obligations_in_snapshot = self.obligations_in_snapshot.get();
895         self.obligations_in_snapshot.set(false);
896
897         CombinedSnapshot {
898             projection_cache_snapshot: self.projection_cache.borrow_mut().snapshot(),
899             type_snapshot: self.type_variables.borrow_mut().snapshot(),
900             int_snapshot: self.int_unification_table.borrow_mut().snapshot(),
901             float_snapshot: self.float_unification_table.borrow_mut().snapshot(),
902             region_vars_snapshot: self.region_vars.start_snapshot(),
903             obligations_in_snapshot: obligations_in_snapshot,
904         }
905     }
906
907     fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot) {
908         debug!("rollback_to(cause={})", cause);
909         let CombinedSnapshot { projection_cache_snapshot,
910                                type_snapshot,
911                                int_snapshot,
912                                float_snapshot,
913                                region_vars_snapshot,
914                                obligations_in_snapshot } = snapshot;
915
916         assert!(!self.obligations_in_snapshot.get());
917         self.obligations_in_snapshot.set(obligations_in_snapshot);
918
919         self.projection_cache
920             .borrow_mut()
921             .rollback_to(projection_cache_snapshot);
922         self.type_variables
923             .borrow_mut()
924             .rollback_to(type_snapshot);
925         self.int_unification_table
926             .borrow_mut()
927             .rollback_to(int_snapshot);
928         self.float_unification_table
929             .borrow_mut()
930             .rollback_to(float_snapshot);
931         self.region_vars
932             .rollback_to(region_vars_snapshot);
933     }
934
935     fn commit_from(&self, snapshot: CombinedSnapshot) {
936         debug!("commit_from()");
937         let CombinedSnapshot { projection_cache_snapshot,
938                                type_snapshot,
939                                int_snapshot,
940                                float_snapshot,
941                                region_vars_snapshot,
942                                obligations_in_snapshot } = snapshot;
943
944         self.obligations_in_snapshot.set(obligations_in_snapshot);
945
946         self.projection_cache
947             .borrow_mut()
948             .commit(projection_cache_snapshot);
949         self.type_variables
950             .borrow_mut()
951             .commit(type_snapshot);
952         self.int_unification_table
953             .borrow_mut()
954             .commit(int_snapshot);
955         self.float_unification_table
956             .borrow_mut()
957             .commit(float_snapshot);
958         self.region_vars
959             .commit(region_vars_snapshot);
960     }
961
962     /// Execute `f` and commit the bindings
963     pub fn commit_unconditionally<R, F>(&self, f: F) -> R where
964         F: FnOnce() -> R,
965     {
966         debug!("commit()");
967         let snapshot = self.start_snapshot();
968         let r = f();
969         self.commit_from(snapshot);
970         r
971     }
972
973     /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`
974     pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E> where
975         F: FnOnce(&CombinedSnapshot) -> Result<T, E>
976     {
977         debug!("commit_if_ok()");
978         let snapshot = self.start_snapshot();
979         let r = f(&snapshot);
980         debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
981         match r {
982             Ok(_) => { self.commit_from(snapshot); }
983             Err(_) => { self.rollback_to("commit_if_ok -- error", snapshot); }
984         }
985         r
986     }
987
988     // Execute `f` in a snapshot, and commit the bindings it creates
989     pub fn in_snapshot<T, F>(&self, f: F) -> T where
990         F: FnOnce(&CombinedSnapshot) -> T
991     {
992         debug!("in_snapshot()");
993         let snapshot = self.start_snapshot();
994         let r = f(&snapshot);
995         self.commit_from(snapshot);
996         r
997     }
998
999     /// Execute `f` then unroll any bindings it creates
1000     pub fn probe<R, F>(&self, f: F) -> R where
1001         F: FnOnce(&CombinedSnapshot) -> R,
1002     {
1003         debug!("probe()");
1004         let snapshot = self.start_snapshot();
1005         let r = f(&snapshot);
1006         self.rollback_to("probe", snapshot);
1007         r
1008     }
1009
1010     pub fn add_given(&self,
1011                      sub: ty::FreeRegion,
1012                      sup: ty::RegionVid)
1013     {
1014         self.region_vars.add_given(sub, sup);
1015     }
1016
1017     pub fn sub_types(&self,
1018                      a_is_expected: bool,
1019                      cause: &ObligationCause<'tcx>,
1020                      a: Ty<'tcx>,
1021                      b: Ty<'tcx>)
1022         -> InferResult<'tcx, ()>
1023     {
1024         debug!("sub_types({:?} <: {:?})", a, b);
1025         self.commit_if_ok(|_| {
1026             let trace = TypeTrace::types(cause, a_is_expected, a, b);
1027             self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1028         })
1029     }
1030
1031     pub fn can_sub_types(&self,
1032                          a: Ty<'tcx>,
1033                          b: Ty<'tcx>)
1034                          -> UnitResult<'tcx>
1035     {
1036         self.probe(|_| {
1037             let origin = &ObligationCause::dummy();
1038             let trace = TypeTrace::types(origin, true, a, b);
1039             self.sub(true, trace, &a, &b).map(|InferOk { obligations: _, .. }| {
1040                 // Ignore obligations, since we are unrolling
1041                 // everything anyway.
1042             })
1043         })
1044     }
1045
1046     pub fn eq_types(&self,
1047                     a_is_expected: bool,
1048                     cause: &ObligationCause<'tcx>,
1049                     a: Ty<'tcx>,
1050                     b: Ty<'tcx>)
1051         -> InferResult<'tcx, ()>
1052     {
1053         self.commit_if_ok(|_| {
1054             let trace = TypeTrace::types(cause, a_is_expected, a, b);
1055             self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1056         })
1057     }
1058
1059     pub fn eq_trait_refs(&self,
1060                           a_is_expected: bool,
1061                           cause: &ObligationCause<'tcx>,
1062                           a: ty::TraitRef<'tcx>,
1063                           b: ty::TraitRef<'tcx>)
1064         -> InferResult<'tcx, ()>
1065     {
1066         debug!("eq_trait_refs({:?} = {:?})", a, b);
1067         self.commit_if_ok(|_| {
1068             let trace = TypeTrace {
1069                 cause: cause.clone(),
1070                 values: TraitRefs(ExpectedFound::new(a_is_expected, a, b))
1071             };
1072             self.equate(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1073         })
1074     }
1075
1076     pub fn eq_impl_headers(&self,
1077                            a_is_expected: bool,
1078                            cause: &ObligationCause<'tcx>,
1079                            a: &ty::ImplHeader<'tcx>,
1080                            b: &ty::ImplHeader<'tcx>)
1081                            -> InferResult<'tcx, ()>
1082     {
1083         debug!("eq_impl_header({:?} = {:?})", a, b);
1084         match (a.trait_ref, b.trait_ref) {
1085             (Some(a_ref), Some(b_ref)) => self.eq_trait_refs(a_is_expected, cause, a_ref, b_ref),
1086             (None, None) => self.eq_types(a_is_expected, cause, a.self_ty, b.self_ty),
1087             _ => bug!("mk_eq_impl_headers given mismatched impl kinds"),
1088         }
1089     }
1090
1091     pub fn sub_poly_trait_refs(&self,
1092                                a_is_expected: bool,
1093                                cause: ObligationCause<'tcx>,
1094                                a: ty::PolyTraitRef<'tcx>,
1095                                b: ty::PolyTraitRef<'tcx>)
1096         -> InferResult<'tcx, ()>
1097     {
1098         debug!("sub_poly_trait_refs({:?} <: {:?})", a, b);
1099         self.commit_if_ok(|_| {
1100             let trace = TypeTrace {
1101                 cause: cause,
1102                 values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b))
1103             };
1104             self.sub(a_is_expected, trace, &a, &b).map(|ok| ok.unit())
1105         })
1106     }
1107
1108     pub fn sub_regions(&self,
1109                        origin: SubregionOrigin<'tcx>,
1110                        a: &'tcx ty::Region,
1111                        b: &'tcx ty::Region) {
1112         debug!("sub_regions({:?} <: {:?})", a, b);
1113         self.region_vars.make_subregion(origin, a, b);
1114     }
1115
1116     pub fn equality_predicate(&self,
1117                               cause: &ObligationCause<'tcx>,
1118                               predicate: &ty::PolyEquatePredicate<'tcx>)
1119         -> InferResult<'tcx, ()>
1120     {
1121         self.commit_if_ok(|snapshot| {
1122             let (ty::EquatePredicate(a, b), skol_map) =
1123                 self.skolemize_late_bound_regions(predicate, snapshot);
1124             let cause_span = cause.span;
1125             let eqty_ok = self.eq_types(false, cause, a, b)?;
1126             self.leak_check(false, cause_span, &skol_map, snapshot)?;
1127             self.pop_skolemized(skol_map, snapshot);
1128             Ok(eqty_ok.unit())
1129         })
1130     }
1131
1132     pub fn subtype_predicate(&self,
1133                              cause: &ObligationCause<'tcx>,
1134                              predicate: &ty::PolySubtypePredicate<'tcx>)
1135         -> Option<InferResult<'tcx, ()>>
1136     {
1137         // Subtle: it's ok to skip the binder here and resolve because
1138         // `shallow_resolve` just ignores anything that is not a type
1139         // variable, and because type variable's can't (at present, at
1140         // least) capture any of the things bound by this binder.
1141         //
1142         // Really, there is no *particular* reason to do this
1143         // `shallow_resolve` here except as a
1144         // micro-optimization. Naturally I could not
1145         // resist. -nmatsakis
1146         let two_unbound_type_vars = {
1147             let a = self.shallow_resolve(predicate.skip_binder().a);
1148             let b = self.shallow_resolve(predicate.skip_binder().b);
1149             a.is_ty_var() && b.is_ty_var()
1150         };
1151
1152         if two_unbound_type_vars {
1153             // Two unbound type variables? Can't make progress.
1154             return None;
1155         }
1156
1157         Some(self.commit_if_ok(|snapshot| {
1158             let (ty::SubtypePredicate { a_is_expected, a, b}, skol_map) =
1159                 self.skolemize_late_bound_regions(predicate, snapshot);
1160
1161             let cause_span = cause.span;
1162             let ok = self.sub_types(a_is_expected, cause, a, b)?;
1163             self.leak_check(false, cause_span, &skol_map, snapshot)?;
1164             self.pop_skolemized(skol_map, snapshot);
1165             Ok(ok.unit())
1166         }))
1167     }
1168
1169     pub fn region_outlives_predicate(&self,
1170                                      cause: &traits::ObligationCause<'tcx>,
1171                                      predicate: &ty::PolyRegionOutlivesPredicate<'tcx>)
1172         -> UnitResult<'tcx>
1173     {
1174         self.commit_if_ok(|snapshot| {
1175             let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
1176                 self.skolemize_late_bound_regions(predicate, snapshot);
1177             let origin =
1178                 SubregionOrigin::from_obligation_cause(cause,
1179                                                        || RelateRegionParamBound(cause.span));
1180             self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
1181             self.leak_check(false, cause.span, &skol_map, snapshot)?;
1182             Ok(self.pop_skolemized(skol_map, snapshot))
1183         })
1184     }
1185
1186     pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
1187         self.type_variables
1188             .borrow_mut()
1189             .new_var(diverging, origin, None)
1190     }
1191
1192     pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1193         self.tcx.mk_var(self.next_ty_var_id(false, origin))
1194     }
1195
1196     pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
1197         self.tcx.mk_var(self.next_ty_var_id(true, origin))
1198     }
1199
1200     pub fn next_int_var_id(&self) -> IntVid {
1201         self.int_unification_table
1202             .borrow_mut()
1203             .new_key(None)
1204     }
1205
1206     pub fn next_float_var_id(&self) -> FloatVid {
1207         self.float_unification_table
1208             .borrow_mut()
1209             .new_key(None)
1210     }
1211
1212     pub fn next_region_var(&self, origin: RegionVariableOrigin)
1213                            -> &'tcx ty::Region {
1214         self.tcx.mk_region(ty::ReVar(self.region_vars.new_region_var(origin)))
1215     }
1216
1217     /// Create a region inference variable for the given
1218     /// region parameter definition.
1219     pub fn region_var_for_def(&self,
1220                               span: Span,
1221                               def: &ty::RegionParameterDef)
1222                               -> &'tcx ty::Region {
1223         self.next_region_var(EarlyBoundRegion(span, def.name, def.issue_32330))
1224     }
1225
1226     /// Create a type inference variable for the given
1227     /// type parameter definition. The substitutions are
1228     /// for actual parameters that may be referred to by
1229     /// the default of this type parameter, if it exists.
1230     /// E.g. `struct Foo<A, B, C = (A, B)>(...);` when
1231     /// used in a path such as `Foo::<T, U>::new()` will
1232     /// use an inference variable for `C` with `[T, U]`
1233     /// as the substitutions for the default, `(T, U)`.
1234     pub fn type_var_for_def(&self,
1235                             span: Span,
1236                             def: &ty::TypeParameterDef,
1237                             substs: &[Kind<'tcx>])
1238                             -> Ty<'tcx> {
1239         let default = if def.has_default {
1240             let default = self.tcx.item_type(def.def_id);
1241             Some(type_variable::Default {
1242                 ty: default.subst_spanned(self.tcx, substs, Some(span)),
1243                 origin_span: span,
1244                 def_id: def.def_id
1245             })
1246         } else {
1247             None
1248         };
1249
1250
1251         let ty_var_id = self.type_variables
1252                             .borrow_mut()
1253                             .new_var(false,
1254                                      TypeVariableOrigin::TypeParameterDefinition(span, def.name),
1255                                      default);
1256
1257         self.tcx.mk_var(ty_var_id)
1258     }
1259
1260     /// Given a set of generics defined on a type or impl, returns a substitution mapping each
1261     /// type/region parameter to a fresh inference variable.
1262     pub fn fresh_substs_for_item(&self,
1263                                  span: Span,
1264                                  def_id: DefId)
1265                                  -> &'tcx Substs<'tcx> {
1266         Substs::for_item(self.tcx, def_id, |def, _| {
1267             self.region_var_for_def(span, def)
1268         }, |def, substs| {
1269             self.type_var_for_def(span, def, substs)
1270         })
1271     }
1272
1273     pub fn fresh_bound_region(&self, debruijn: ty::DebruijnIndex) -> &'tcx ty::Region {
1274         self.region_vars.new_bound(debruijn)
1275     }
1276
1277     /// True if errors have been reported since this infcx was
1278     /// created.  This is sometimes used as a heuristic to skip
1279     /// reporting errors that often occur as a result of earlier
1280     /// errors, but where it's hard to be 100% sure (e.g., unresolved
1281     /// inference variables, regionck errors).
1282     pub fn is_tainted_by_errors(&self) -> bool {
1283         debug!("is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
1284                 tainted_by_errors_flag={})",
1285                self.tcx.sess.err_count(),
1286                self.err_count_on_creation,
1287                self.tainted_by_errors_flag.get());
1288
1289         if self.tcx.sess.err_count() > self.err_count_on_creation {
1290             return true; // errors reported since this infcx was made
1291         }
1292         self.tainted_by_errors_flag.get()
1293     }
1294
1295     /// Set the "tainted by errors" flag to true. We call this when we
1296     /// observe an error from a prior pass.
1297     pub fn set_tainted_by_errors(&self) {
1298         debug!("set_tainted_by_errors()");
1299         self.tainted_by_errors_flag.set(true)
1300     }
1301
1302     pub fn node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
1303         match self.tables.borrow().node_types.get(&id) {
1304             Some(&t) => t,
1305             // FIXME
1306             None if self.is_tainted_by_errors() =>
1307                 self.tcx.types.err,
1308             None => {
1309                 bug!("no type for node {}: {} in fcx",
1310                      id, self.tcx.hir.node_to_string(id));
1311             }
1312         }
1313     }
1314
1315     pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
1316         match self.tables.borrow().node_types.get(&ex.id) {
1317             Some(&t) => t,
1318             None => {
1319                 bug!("no type for expr in fcx");
1320             }
1321         }
1322     }
1323
1324     pub fn resolve_regions_and_report_errors(&self,
1325                                              free_regions: &FreeRegionMap,
1326                                              subject_node_id: ast::NodeId) {
1327         let errors = self.region_vars.resolve_regions(free_regions, subject_node_id);
1328         if !self.is_tainted_by_errors() {
1329             // As a heuristic, just skip reporting region errors
1330             // altogether if other errors have been reported while
1331             // this infcx was in use.  This is totally hokey but
1332             // otherwise we have a hard time separating legit region
1333             // errors from silly ones.
1334             self.report_region_errors(&errors); // see error_reporting module
1335         }
1336     }
1337
1338     pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
1339         self.resolve_type_vars_if_possible(&t).to_string()
1340     }
1341
1342     pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
1343         let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
1344         format!("({})", tstrs.join(", "))
1345     }
1346
1347     pub fn trait_ref_to_string(&self, t: &ty::TraitRef<'tcx>) -> String {
1348         self.resolve_type_vars_if_possible(t).to_string()
1349     }
1350
1351     pub fn shallow_resolve(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
1352         match typ.sty {
1353             ty::TyInfer(ty::TyVar(v)) => {
1354                 // Not entirely obvious: if `typ` is a type variable,
1355                 // it can be resolved to an int/float variable, which
1356                 // can then be recursively resolved, hence the
1357                 // recursion. Note though that we prevent type
1358                 // variables from unifying to other type variables
1359                 // directly (though they may be embedded
1360                 // structurally), and we prevent cycles in any case,
1361                 // so this recursion should always be of very limited
1362                 // depth.
1363                 self.type_variables.borrow_mut()
1364                     .probe(v)
1365                     .map(|t| self.shallow_resolve(t))
1366                     .unwrap_or(typ)
1367             }
1368
1369             ty::TyInfer(ty::IntVar(v)) => {
1370                 self.int_unification_table
1371                     .borrow_mut()
1372                     .probe(v)
1373                     .map(|v| v.to_type(self.tcx))
1374                     .unwrap_or(typ)
1375             }
1376
1377             ty::TyInfer(ty::FloatVar(v)) => {
1378                 self.float_unification_table
1379                     .borrow_mut()
1380                     .probe(v)
1381                     .map(|v| v.to_type(self.tcx))
1382                     .unwrap_or(typ)
1383             }
1384
1385             _ => {
1386                 typ
1387             }
1388         }
1389     }
1390
1391     pub fn resolve_type_vars_if_possible<T>(&self, value: &T) -> T
1392         where T: TypeFoldable<'tcx>
1393     {
1394         /*!
1395          * Where possible, replaces type/int/float variables in
1396          * `value` with their final value. Note that region variables
1397          * are unaffected. If a type variable has not been unified, it
1398          * is left as is.  This is an idempotent operation that does
1399          * not affect inference state in any way and so you can do it
1400          * at will.
1401          */
1402
1403         if !value.needs_infer() {
1404             return value.clone(); // avoid duplicated subst-folding
1405         }
1406         let mut r = resolve::OpportunisticTypeResolver::new(self);
1407         value.fold_with(&mut r)
1408     }
1409
1410     pub fn resolve_type_and_region_vars_if_possible<T>(&self, value: &T) -> T
1411         where T: TypeFoldable<'tcx>
1412     {
1413         let mut r = resolve::OpportunisticTypeAndRegionResolver::new(self);
1414         value.fold_with(&mut r)
1415     }
1416
1417     /// Resolves all type variables in `t` and then, if any were left
1418     /// unresolved, substitutes an error type. This is used after the
1419     /// main checking when doing a second pass before writeback. The
1420     /// justification is that writeback will produce an error for
1421     /// these unconstrained type variables.
1422     fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
1423         let ty = self.resolve_type_vars_if_possible(t);
1424         if ty.references_error() || ty.is_ty_var() {
1425             debug!("resolve_type_vars_or_error: error from {:?}", ty);
1426             Err(())
1427         } else {
1428             Ok(ty)
1429         }
1430     }
1431
1432     pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
1433         /*!
1434          * Attempts to resolve all type/region variables in
1435          * `value`. Region inference must have been run already (e.g.,
1436          * by calling `resolve_regions_and_report_errors`).  If some
1437          * variable was never unified, an `Err` results.
1438          *
1439          * This method is idempotent, but it not typically not invoked
1440          * except during the writeback phase.
1441          */
1442
1443         resolve::fully_resolve(self, value)
1444     }
1445
1446     // [Note-Type-error-reporting]
1447     // An invariant is that anytime the expected or actual type is TyError (the special
1448     // error type, meaning that an error occurred when typechecking this expression),
1449     // this is a derived error. The error cascaded from another error (that was already
1450     // reported), so it's not useful to display it to the user.
1451     // The following methods implement this logic.
1452     // They check if either the actual or expected type is TyError, and don't print the error
1453     // in this case. The typechecker should only ever report type errors involving mismatched
1454     // types using one of these methods, and should not call span_err directly for such
1455     // errors.
1456
1457     pub fn type_error_message<M>(&self,
1458                                  sp: Span,
1459                                  mk_msg: M,
1460                                  actual_ty: Ty<'tcx>)
1461         where M: FnOnce(String) -> String,
1462     {
1463         self.type_error_struct(sp, mk_msg, actual_ty).emit();
1464     }
1465
1466     // FIXME: this results in errors without an error code. Deprecate?
1467     pub fn type_error_struct<M>(&self,
1468                                 sp: Span,
1469                                 mk_msg: M,
1470                                 actual_ty: Ty<'tcx>)
1471                                 -> DiagnosticBuilder<'tcx>
1472         where M: FnOnce(String) -> String,
1473     {
1474         self.type_error_struct_with_diag(sp, |actual_ty| {
1475             self.tcx.sess.struct_span_err(sp, &mk_msg(actual_ty))
1476         }, actual_ty)
1477     }
1478
1479     pub fn type_error_struct_with_diag<M>(&self,
1480                                           sp: Span,
1481                                           mk_diag: M,
1482                                           actual_ty: Ty<'tcx>)
1483                                           -> DiagnosticBuilder<'tcx>
1484         where M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
1485     {
1486         let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
1487         debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
1488
1489         // Don't report an error if actual type is TyError.
1490         if actual_ty.references_error() {
1491             return self.tcx.sess.diagnostic().struct_dummy();
1492         }
1493
1494         mk_diag(self.ty_to_string(actual_ty))
1495     }
1496
1497     pub fn report_mismatched_types(&self,
1498                                    cause: &ObligationCause<'tcx>,
1499                                    expected: Ty<'tcx>,
1500                                    actual: Ty<'tcx>,
1501                                    err: TypeError<'tcx>)
1502                                    -> DiagnosticBuilder<'tcx> {
1503         let trace = TypeTrace::types(cause, true, expected, actual);
1504         self.report_and_explain_type_error(trace, &err)
1505     }
1506
1507     pub fn report_conflicting_default_types(&self,
1508                                             span: Span,
1509                                             body_id: ast::NodeId,
1510                                             expected: type_variable::Default<'tcx>,
1511                                             actual: type_variable::Default<'tcx>) {
1512         let trace = TypeTrace {
1513             cause: ObligationCause::misc(span, body_id),
1514             values: Types(ExpectedFound {
1515                 expected: expected.ty,
1516                 found: actual.ty
1517             })
1518         };
1519
1520         self.report_and_explain_type_error(
1521             trace,
1522             &TypeError::TyParamDefaultMismatch(ExpectedFound {
1523                 expected: expected,
1524                 found: actual
1525             }))
1526             .emit();
1527     }
1528
1529     pub fn replace_late_bound_regions_with_fresh_var<T>(
1530         &self,
1531         span: Span,
1532         lbrct: LateBoundRegionConversionTime,
1533         value: &ty::Binder<T>)
1534         -> (T, FxHashMap<ty::BoundRegion, &'tcx ty::Region>)
1535         where T : TypeFoldable<'tcx>
1536     {
1537         self.tcx.replace_late_bound_regions(
1538             value,
1539             |br| self.next_region_var(LateBoundRegion(span, br, lbrct)))
1540     }
1541
1542     /// Given a higher-ranked projection predicate like:
1543     ///
1544     ///     for<'a> <T as Fn<&'a u32>>::Output = &'a u32
1545     ///
1546     /// and a target trait-ref like:
1547     ///
1548     ///     <T as Fn<&'x u32>>
1549     ///
1550     /// find a substitution `S` for the higher-ranked regions (here,
1551     /// `['a => 'x]`) such that the predicate matches the trait-ref,
1552     /// and then return the value (here, `&'a u32`) but with the
1553     /// substitution applied (hence, `&'x u32`).
1554     ///
1555     /// See `higher_ranked_match` in `higher_ranked/mod.rs` for more
1556     /// details.
1557     pub fn match_poly_projection_predicate(&self,
1558                                            cause: ObligationCause<'tcx>,
1559                                            match_a: ty::PolyProjectionPredicate<'tcx>,
1560                                            match_b: ty::TraitRef<'tcx>)
1561                                            -> InferResult<'tcx, HrMatchResult<Ty<'tcx>>>
1562     {
1563         let span = cause.span;
1564         let match_trait_ref = match_a.skip_binder().projection_ty.trait_ref;
1565         let trace = TypeTrace {
1566             cause: cause,
1567             values: TraitRefs(ExpectedFound::new(true, match_trait_ref, match_b))
1568         };
1569
1570         let match_pair = match_a.map_bound(|p| (p.projection_ty.trait_ref, p.ty));
1571         let mut combine = self.combine_fields(trace);
1572         let result = combine.higher_ranked_match(span, &match_pair, &match_b, true)?;
1573         Ok(InferOk { value: result, obligations: combine.obligations })
1574     }
1575
1576     /// See `verify_generic_bound` method in `region_inference`
1577     pub fn verify_generic_bound(&self,
1578                                 origin: SubregionOrigin<'tcx>,
1579                                 kind: GenericKind<'tcx>,
1580                                 a: &'tcx ty::Region,
1581                                 bound: VerifyBound<'tcx>) {
1582         debug!("verify_generic_bound({:?}, {:?} <: {:?})",
1583                kind,
1584                a,
1585                bound);
1586
1587         self.region_vars.verify_generic_bound(origin, kind, a, bound);
1588     }
1589
1590     pub fn can_equate<T>(&self, a: &T, b: &T) -> UnitResult<'tcx>
1591         where T: Relate<'tcx> + fmt::Debug
1592     {
1593         debug!("can_equate({:?}, {:?})", a, b);
1594         self.probe(|_| {
1595             // Gin up a dummy trace, since this won't be committed
1596             // anyhow. We should make this typetrace stuff more
1597             // generic so we don't have to do anything quite this
1598             // terrible.
1599             let trace = TypeTrace::dummy(self.tcx);
1600             self.equate(true, trace, a, b).map(|InferOk { obligations, .. }| {
1601                 // FIXME(#32730) propagate obligations
1602                 assert!(obligations.is_empty());
1603             })
1604         })
1605     }
1606
1607     pub fn node_ty(&self, id: ast::NodeId) -> McResult<Ty<'tcx>> {
1608         let ty = self.node_type(id);
1609         self.resolve_type_vars_or_error(&ty)
1610     }
1611
1612     pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> McResult<Ty<'tcx>> {
1613         let ty = self.tables.borrow().expr_ty_adjusted(expr);
1614         self.resolve_type_vars_or_error(&ty)
1615     }
1616
1617     pub fn type_moves_by_default(&self, ty: Ty<'tcx>, span: Span) -> bool {
1618         let ty = self.resolve_type_vars_if_possible(&ty);
1619         if let Some(ty) = self.tcx.lift_to_global(&ty) {
1620             // Even if the type may have no inference variables, during
1621             // type-checking closure types are in local tables only.
1622             let local_closures = match self.tables {
1623                 InferTables::InProgress(_) => ty.has_closure_types(),
1624                 _ => false
1625             };
1626             if !local_closures {
1627                 return ty.moves_by_default(self.tcx.global_tcx(), self.param_env(), span);
1628             }
1629         }
1630
1631         let copy_def_id = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
1632
1633         // this can get called from typeck (by euv), and moves_by_default
1634         // rightly refuses to work with inference variables, but
1635         // moves_by_default has a cache, which we want to use in other
1636         // cases.
1637         !traits::type_known_to_meet_bound(self, ty, copy_def_id, span)
1638     }
1639
1640     pub fn node_method_ty(&self, method_call: ty::MethodCall)
1641                           -> Option<Ty<'tcx>> {
1642         self.tables
1643             .borrow()
1644             .method_map
1645             .get(&method_call)
1646             .map(|method| method.ty)
1647             .map(|ty| self.resolve_type_vars_if_possible(&ty))
1648     }
1649
1650     pub fn node_method_id(&self, method_call: ty::MethodCall)
1651                           -> Option<DefId> {
1652         self.tables
1653             .borrow()
1654             .method_map
1655             .get(&method_call)
1656             .map(|method| method.def_id)
1657     }
1658
1659     pub fn is_method_call(&self, id: ast::NodeId) -> bool {
1660         self.tables.borrow().method_map.contains_key(&ty::MethodCall::expr(id))
1661     }
1662
1663     pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarCapture<'tcx>> {
1664         self.tables.borrow().upvar_capture_map.get(&upvar_id).cloned()
1665     }
1666
1667     pub fn param_env(&self) -> &ty::ParameterEnvironment<'gcx> {
1668         &self.parameter_environment
1669     }
1670
1671     pub fn closure_kind(&self,
1672                         def_id: DefId)
1673                         -> Option<ty::ClosureKind>
1674     {
1675         if let InferTables::InProgress(tables) = self.tables {
1676             if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1677                 return tables.borrow().closure_kinds.get(&id).cloned();
1678             }
1679         }
1680
1681         // During typeck, ALL closures are local. But afterwards,
1682         // during trans, we see closure ids from other traits.
1683         // That may require loading the closure data out of the
1684         // cstore.
1685         Some(self.tcx.closure_kind(def_id))
1686     }
1687
1688     pub fn closure_type(&self, def_id: DefId) -> ty::PolyFnSig<'tcx> {
1689         if let InferTables::InProgress(tables) = self.tables {
1690             if let Some(id) = self.tcx.hir.as_local_node_id(def_id) {
1691                 if let Some(&ty) = tables.borrow().closure_tys.get(&id) {
1692                     return ty;
1693                 }
1694             }
1695         }
1696
1697         self.tcx.closure_type(def_id)
1698     }
1699 }
1700
1701 impl<'a, 'gcx, 'tcx> TypeTrace<'tcx> {
1702     pub fn span(&self) -> Span {
1703         self.cause.span
1704     }
1705
1706     pub fn types(cause: &ObligationCause<'tcx>,
1707                  a_is_expected: bool,
1708                  a: Ty<'tcx>,
1709                  b: Ty<'tcx>)
1710                  -> TypeTrace<'tcx> {
1711         TypeTrace {
1712             cause: cause.clone(),
1713             values: Types(ExpectedFound::new(a_is_expected, a, b))
1714         }
1715     }
1716
1717     pub fn dummy(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> TypeTrace<'tcx> {
1718         TypeTrace {
1719             cause: ObligationCause::dummy(),
1720             values: Types(ExpectedFound {
1721                 expected: tcx.types.err,
1722                 found: tcx.types.err,
1723             })
1724         }
1725     }
1726 }
1727
1728 impl<'tcx> fmt::Debug for TypeTrace<'tcx> {
1729     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1730         write!(f, "TypeTrace({:?})", self.cause)
1731     }
1732 }
1733
1734 impl<'tcx> SubregionOrigin<'tcx> {
1735     pub fn span(&self) -> Span {
1736         match *self {
1737             Subtype(ref a) => a.span(),
1738             InfStackClosure(a) => a,
1739             InvokeClosure(a) => a,
1740             DerefPointer(a) => a,
1741             FreeVariable(a, _) => a,
1742             IndexSlice(a) => a,
1743             RelateObjectBound(a) => a,
1744             RelateParamBound(a, _) => a,
1745             RelateRegionParamBound(a) => a,
1746             RelateDefaultParamBound(a, _) => a,
1747             Reborrow(a) => a,
1748             ReborrowUpvar(a, _) => a,
1749             DataBorrowed(_, a) => a,
1750             ReferenceOutlivesReferent(_, a) => a,
1751             ParameterInScope(_, a) => a,
1752             ExprTypeIsNotInScope(_, a) => a,
1753             BindingTypeIsNotValidAtDecl(a) => a,
1754             CallRcvr(a) => a,
1755             CallArg(a) => a,
1756             CallReturn(a) => a,
1757             Operand(a) => a,
1758             AddrOf(a) => a,
1759             AutoBorrow(a) => a,
1760             SafeDestructor(a) => a,
1761             CompareImplMethodObligation { span, .. } => span,
1762         }
1763     }
1764
1765     pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>,
1766                                     default: F)
1767                                     -> Self
1768         where F: FnOnce() -> Self
1769     {
1770         match cause.code {
1771             traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) =>
1772                 SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span),
1773
1774             traits::ObligationCauseCode::CompareImplMethodObligation { item_name,
1775                                                                        impl_item_def_id,
1776                                                                        trait_item_def_id,
1777                                                                        lint_id } =>
1778                 SubregionOrigin::CompareImplMethodObligation {
1779                     span: cause.span,
1780                     item_name: item_name,
1781                     impl_item_def_id: impl_item_def_id,
1782                     trait_item_def_id: trait_item_def_id,
1783                     lint_id: lint_id,
1784                 },
1785
1786             _ => default(),
1787         }
1788     }
1789 }
1790
1791 impl RegionVariableOrigin {
1792     pub fn span(&self) -> Span {
1793         match *self {
1794             MiscVariable(a) => a,
1795             PatternRegion(a) => a,
1796             AddrOfRegion(a) => a,
1797             Autoref(a) => a,
1798             Coercion(a) => a,
1799             EarlyBoundRegion(a, ..) => a,
1800             LateBoundRegion(a, ..) => a,
1801             BoundRegionInCoherence(_) => syntax_pos::DUMMY_SP,
1802             UpvarRegion(_, a) => a
1803         }
1804     }
1805 }
1806
1807 impl<'tcx> TypeFoldable<'tcx> for ValuePairs<'tcx> {
1808     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1809         match *self {
1810             ValuePairs::Types(ref ef) => {
1811                 ValuePairs::Types(ef.fold_with(folder))
1812             }
1813             ValuePairs::TraitRefs(ref ef) => {
1814                 ValuePairs::TraitRefs(ef.fold_with(folder))
1815             }
1816             ValuePairs::PolyTraitRefs(ref ef) => {
1817                 ValuePairs::PolyTraitRefs(ef.fold_with(folder))
1818             }
1819         }
1820     }
1821
1822     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1823         match *self {
1824             ValuePairs::Types(ref ef) => ef.visit_with(visitor),
1825             ValuePairs::TraitRefs(ref ef) => ef.visit_with(visitor),
1826             ValuePairs::PolyTraitRefs(ref ef) => ef.visit_with(visitor),
1827         }
1828     }
1829 }
1830
1831 impl<'tcx> TypeFoldable<'tcx> for TypeTrace<'tcx> {
1832     fn super_fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
1833         TypeTrace {
1834             cause: self.cause.fold_with(folder),
1835             values: self.values.fold_with(folder)
1836         }
1837     }
1838
1839     fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
1840         self.cause.visit_with(visitor) || self.values.visit_with(visitor)
1841     }
1842 }