]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/mod.rs
Remove need for &format!(...) or &&"" dances in `span_label` calls
[rust.git] / src / librustc_typeck / check / mod.rs
1 // Copyright 2012-2015 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 /*
12
13 # check.rs
14
15 Within the check phase of type check, we check each item one at a time
16 (bodies of function expressions are checked as part of the containing
17 function).  Inference is used to supply types wherever they are
18 unknown.
19
20 By far the most complex case is checking the body of a function. This
21 can be broken down into several distinct phases:
22
23 - gather: creates type variables to represent the type of each local
24   variable and pattern binding.
25
26 - main: the main pass does the lion's share of the work: it
27   determines the types of all expressions, resolves
28   methods, checks for most invalid conditions, and so forth.  In
29   some cases, where a type is unknown, it may create a type or region
30   variable and use that as the type of an expression.
31
32   In the process of checking, various constraints will be placed on
33   these type variables through the subtyping relationships requested
34   through the `demand` module.  The `infer` module is in charge
35   of resolving those constraints.
36
37 - regionck: after main is complete, the regionck pass goes over all
38   types looking for regions and making sure that they did not escape
39   into places they are not in scope.  This may also influence the
40   final assignments of the various region variables if there is some
41   flexibility.
42
43 - vtable: find and records the impls to use for each trait bound that
44   appears on a type parameter.
45
46 - writeback: writes the final types within a function body, replacing
47   type variables with their final inferred types.  These final types
48   are written into the `tcx.node_types` table, which should *never* contain
49   any reference to a type variable.
50
51 ## Intermediate types
52
53 While type checking a function, the intermediate types for the
54 expressions, blocks, and so forth contained within the function are
55 stored in `fcx.node_types` and `fcx.item_substs`.  These types
56 may contain unresolved type variables.  After type checking is
57 complete, the functions in the writeback module are used to take the
58 types from this table, resolve them, and then write them into their
59 permanent home in the type context `tcx`.
60
61 This means that during inferencing you should use `fcx.write_ty()`
62 and `fcx.expr_ty()` / `fcx.node_ty()` to write/obtain the types of
63 nodes within the function.
64
65 The types of top-level items, which never contain unbound type
66 variables, are stored directly into the `tcx` tables.
67
68 n.b.: A type variable is not the same thing as a type parameter.  A
69 type variable is rather an "instance" of a type parameter: that is,
70 given a generic function `fn foo<T>(t: T)`: while checking the
71 function `foo`, the type `ty_param(0)` refers to the type `T`, which
72 is treated in abstract.  When `foo()` is called, however, `T` will be
73 substituted for a fresh type variable `N`.  This variable will
74 eventually be resolved to some concrete type (which might itself be
75 type parameter).
76
77 */
78
79 pub use self::Expectation::*;
80 use self::coercion::{CoerceMany, DynamicCoerceMany};
81 pub use self::compare_method::{compare_impl_method, compare_const_impl};
82 use self::TupleArgumentsFlag::*;
83
84 use astconv::AstConv;
85 use fmt_macros::{Parser, Piece, Position};
86 use hir::def::{Def, CtorKind};
87 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
88 use rustc_back::slice::ref_slice;
89 use rustc::infer::{self, InferCtxt, InferOk, RegionVariableOrigin};
90 use rustc::infer::type_variable::{TypeVariableOrigin};
91 use rustc::ty::subst::{Kind, Subst, Substs};
92 use rustc::traits::{self, FulfillmentContext, ObligationCause, ObligationCauseCode, Reveal};
93 use rustc::ty::{ParamTy, ParameterEnvironment};
94 use rustc::ty::{LvaluePreference, NoPreference, PreferMutLvalue};
95 use rustc::ty::{self, Ty, TyCtxt, Visibility};
96 use rustc::ty::{MethodCall, MethodCallee};
97 use rustc::ty::adjustment::{Adjust, Adjustment, AutoBorrow};
98 use rustc::ty::fold::{BottomUpFolder, TypeFoldable};
99 use rustc::ty::maps::Providers;
100 use rustc::ty::util::{Representability, IntTypeExt};
101 use errors::DiagnosticBuilder;
102 use require_c_abi_if_variadic;
103 use session::{Session, CompileResult};
104 use TypeAndSubsts;
105 use lint;
106 use util::common::{ErrorReported, indenter};
107 use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
108
109 use std::cell::{Cell, RefCell};
110 use std::collections::hash_map::Entry;
111 use std::cmp;
112 use std::mem::replace;
113 use std::ops::{self, Deref};
114 use syntax::abi::Abi;
115 use syntax::ast;
116 use syntax::codemap::{self, original_sp, Spanned};
117 use syntax::feature_gate::{GateIssue, emit_feature_err};
118 use syntax::ptr::P;
119 use syntax::symbol::{Symbol, InternedString, keywords};
120 use syntax::util::lev_distance::find_best_match_for_name;
121 use syntax_pos::{self, BytePos, Span, DUMMY_SP};
122
123 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
124 use rustc::hir::itemlikevisit::ItemLikeVisitor;
125 use rustc::hir::{self, PatKind};
126 use rustc::middle::lang_items;
127 use rustc_back::slice;
128 use rustc::middle::const_val::eval_length;
129 use rustc_const_math::ConstInt;
130
131 mod autoderef;
132 pub mod dropck;
133 pub mod _match;
134 pub mod writeback;
135 pub mod regionck;
136 pub mod coercion;
137 pub mod demand;
138 pub mod method;
139 mod upvar;
140 mod wfcheck;
141 mod cast;
142 mod closure;
143 mod callee;
144 mod compare_method;
145 mod intrinsic;
146 mod op;
147
148 /// closures defined within the function.  For example:
149 ///
150 ///     fn foo() {
151 ///         bar(move|| { ... })
152 ///     }
153 ///
154 /// Here, the function `foo()` and the closure passed to
155 /// `bar()` will each have their own `FnCtxt`, but they will
156 /// share the inherited fields.
157 pub struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
158     infcx: InferCtxt<'a, 'gcx, 'tcx>,
159
160     locals: RefCell<NodeMap<Ty<'tcx>>>,
161
162     fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
163
164     // When we process a call like `c()` where `c` is a closure type,
165     // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
166     // `FnOnce` closure. In that case, we defer full resolution of the
167     // call until upvar inference can kick in and make the
168     // decision. We keep these deferred resolutions grouped by the
169     // def-id of the closure, so that once we decide, we can easily go
170     // back and process them.
171     deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>>>,
172
173     deferred_cast_checks: RefCell<Vec<cast::CastCheck<'tcx>>>,
174
175     // Anonymized types found in explicit return types and their
176     // associated fresh inference variable. Writeback resolves these
177     // variables to get the concrete type, which can be used to
178     // deanonymize TyAnon, after typeck is done with all functions.
179     anon_types: RefCell<NodeMap<Ty<'tcx>>>,
180 }
181
182 impl<'a, 'gcx, 'tcx> Deref for Inherited<'a, 'gcx, 'tcx> {
183     type Target = InferCtxt<'a, 'gcx, 'tcx>;
184     fn deref(&self) -> &Self::Target {
185         &self.infcx
186     }
187 }
188
189 trait DeferredCallResolution<'gcx, 'tcx> {
190     fn resolve<'a>(&mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>);
191 }
192
193 type DeferredCallResolutionHandler<'gcx, 'tcx> = Box<DeferredCallResolution<'gcx, 'tcx>+'tcx>;
194
195 /// When type-checking an expression, we propagate downward
196 /// whatever type hint we are able in the form of an `Expectation`.
197 #[derive(Copy, Clone, Debug)]
198 pub enum Expectation<'tcx> {
199     /// We know nothing about what type this expression should have.
200     NoExpectation,
201
202     /// This expression should have the type given (or some subtype)
203     ExpectHasType(Ty<'tcx>),
204
205     /// This expression will be cast to the `Ty`
206     ExpectCastableToType(Ty<'tcx>),
207
208     /// This rvalue expression will be wrapped in `&` or `Box` and coerced
209     /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`.
210     ExpectRvalueLikeUnsized(Ty<'tcx>),
211 }
212
213 impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
214     // Disregard "castable to" expectations because they
215     // can lead us astray. Consider for example `if cond
216     // {22} else {c} as u8` -- if we propagate the
217     // "castable to u8" constraint to 22, it will pick the
218     // type 22u8, which is overly constrained (c might not
219     // be a u8). In effect, the problem is that the
220     // "castable to" expectation is not the tightest thing
221     // we can say, so we want to drop it in this case.
222     // The tightest thing we can say is "must unify with
223     // else branch". Note that in the case of a "has type"
224     // constraint, this limitation does not hold.
225
226     // If the expected type is just a type variable, then don't use
227     // an expected type. Otherwise, we might write parts of the type
228     // when checking the 'then' block which are incompatible with the
229     // 'else' branch.
230     fn adjust_for_branches(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
231         match *self {
232             ExpectHasType(ety) => {
233                 let ety = fcx.shallow_resolve(ety);
234                 if !ety.is_ty_var() {
235                     ExpectHasType(ety)
236                 } else {
237                     NoExpectation
238                 }
239             }
240             ExpectRvalueLikeUnsized(ety) => {
241                 ExpectRvalueLikeUnsized(ety)
242             }
243             _ => NoExpectation
244         }
245     }
246
247     /// Provide an expectation for an rvalue expression given an *optional*
248     /// hint, which is not required for type safety (the resulting type might
249     /// be checked higher up, as is the case with `&expr` and `box expr`), but
250     /// is useful in determining the concrete type.
251     ///
252     /// The primary use case is where the expected type is a fat pointer,
253     /// like `&[isize]`. For example, consider the following statement:
254     ///
255     ///    let x: &[isize] = &[1, 2, 3];
256     ///
257     /// In this case, the expected type for the `&[1, 2, 3]` expression is
258     /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
259     /// expectation `ExpectHasType([isize])`, that would be too strong --
260     /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
261     /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
262     /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
263     /// which still is useful, because it informs integer literals and the like.
264     /// See the test case `test/run-pass/coerce-expect-unsized.rs` and #20169
265     /// for examples of where this comes up,.
266     fn rvalue_hint(fcx: &FnCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> {
267         match fcx.tcx.struct_tail(ty).sty {
268             ty::TySlice(_) | ty::TyStr | ty::TyDynamic(..) => {
269                 ExpectRvalueLikeUnsized(ty)
270             }
271             _ => ExpectHasType(ty)
272         }
273     }
274
275     // Resolves `expected` by a single level if it is a variable. If
276     // there is no expected type or resolution is not possible (e.g.,
277     // no constraints yet present), just returns `None`.
278     fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
279         match self {
280             NoExpectation => {
281                 NoExpectation
282             }
283             ExpectCastableToType(t) => {
284                 ExpectCastableToType(fcx.resolve_type_vars_if_possible(&t))
285             }
286             ExpectHasType(t) => {
287                 ExpectHasType(fcx.resolve_type_vars_if_possible(&t))
288             }
289             ExpectRvalueLikeUnsized(t) => {
290                 ExpectRvalueLikeUnsized(fcx.resolve_type_vars_if_possible(&t))
291             }
292         }
293     }
294
295     fn to_option(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
296         match self.resolve(fcx) {
297             NoExpectation => None,
298             ExpectCastableToType(ty) |
299             ExpectHasType(ty) |
300             ExpectRvalueLikeUnsized(ty) => Some(ty),
301         }
302     }
303
304     /// It sometimes happens that we want to turn an expectation into
305     /// a **hard constraint** (i.e., something that must be satisfied
306     /// for the program to type-check). `only_has_type` will return
307     /// such a constraint, if it exists.
308     fn only_has_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
309         match self.resolve(fcx) {
310             ExpectHasType(ty) => Some(ty),
311             _ => None
312         }
313     }
314
315     /// Like `only_has_type`, but instead of returning `None` if no
316     /// hard constraint exists, creates a fresh type variable.
317     fn coercion_target_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, span: Span) -> Ty<'tcx> {
318         self.only_has_type(fcx)
319             .unwrap_or_else(|| fcx.next_ty_var(TypeVariableOrigin::MiscVariable(span)))
320     }
321 }
322
323 #[derive(Copy, Clone)]
324 pub struct UnsafetyState {
325     pub def: ast::NodeId,
326     pub unsafety: hir::Unsafety,
327     pub unsafe_push_count: u32,
328     from_fn: bool
329 }
330
331 impl UnsafetyState {
332     pub fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState {
333         UnsafetyState { def: def, unsafety: unsafety, unsafe_push_count: 0, from_fn: true }
334     }
335
336     pub fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState {
337         match self.unsafety {
338             // If this unsafe, then if the outer function was already marked as
339             // unsafe we shouldn't attribute the unsafe'ness to the block. This
340             // way the block can be warned about instead of ignoring this
341             // extraneous block (functions are never warned about).
342             hir::Unsafety::Unsafe if self.from_fn => *self,
343
344             unsafety => {
345                 let (unsafety, def, count) = match blk.rules {
346                     hir::PushUnsafeBlock(..) =>
347                         (unsafety, blk.id, self.unsafe_push_count.checked_add(1).unwrap()),
348                     hir::PopUnsafeBlock(..) =>
349                         (unsafety, blk.id, self.unsafe_push_count.checked_sub(1).unwrap()),
350                     hir::UnsafeBlock(..) =>
351                         (hir::Unsafety::Unsafe, blk.id, self.unsafe_push_count),
352                     hir::DefaultBlock =>
353                         (unsafety, self.def, self.unsafe_push_count),
354                 };
355                 UnsafetyState{ def: def,
356                                unsafety: unsafety,
357                                unsafe_push_count: count,
358                                from_fn: false }
359             }
360         }
361     }
362 }
363
364 #[derive(Debug, Copy, Clone)]
365 pub enum LvalueOp {
366     Deref,
367     Index
368 }
369
370 #[derive(Copy, Clone, Debug)]
371 pub struct AdjustedRcvr<'a> {
372     pub rcvr_expr: &'a hir::Expr,
373     pub autoderefs: usize,
374     pub unsize: bool
375 }
376
377 /// Tracks whether executing a node may exit normally (versus
378 /// return/break/panic, which "diverge", leaving dead code in their
379 /// wake). Tracked semi-automatically (through type variables marked
380 /// as diverging), with some manual adjustments for control-flow
381 /// primitives (approximating a CFG).
382 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
383 pub enum Diverges {
384     /// Potentially unknown, some cases converge,
385     /// others require a CFG to determine them.
386     Maybe,
387
388     /// Definitely known to diverge and therefore
389     /// not reach the next sibling or its parent.
390     Always,
391
392     /// Same as `Always` but with a reachability
393     /// warning already emitted
394     WarnedAlways
395 }
396
397 // Convenience impls for combinig `Diverges`.
398
399 impl ops::BitAnd for Diverges {
400     type Output = Self;
401     fn bitand(self, other: Self) -> Self {
402         cmp::min(self, other)
403     }
404 }
405
406 impl ops::BitOr for Diverges {
407     type Output = Self;
408     fn bitor(self, other: Self) -> Self {
409         cmp::max(self, other)
410     }
411 }
412
413 impl ops::BitAndAssign for Diverges {
414     fn bitand_assign(&mut self, other: Self) {
415         *self = *self & other;
416     }
417 }
418
419 impl ops::BitOrAssign for Diverges {
420     fn bitor_assign(&mut self, other: Self) {
421         *self = *self | other;
422     }
423 }
424
425 impl Diverges {
426     fn always(self) -> bool {
427         self >= Diverges::Always
428     }
429 }
430
431 pub struct BreakableCtxt<'gcx: 'tcx, 'tcx> {
432     may_break: bool,
433
434     // this is `null` for loops where break with a value is illegal,
435     // such as `while`, `for`, and `while let`
436     coerce: Option<DynamicCoerceMany<'gcx, 'tcx>>,
437 }
438
439 pub struct EnclosingBreakables<'gcx: 'tcx, 'tcx> {
440     stack: Vec<BreakableCtxt<'gcx, 'tcx>>,
441     by_id: NodeMap<usize>,
442 }
443
444 impl<'gcx, 'tcx> EnclosingBreakables<'gcx, 'tcx> {
445     fn find_breakable(&mut self, target_id: ast::NodeId) -> &mut BreakableCtxt<'gcx, 'tcx> {
446         let ix = *self.by_id.get(&target_id).unwrap_or_else(|| {
447             bug!("could not find enclosing breakable with id {}", target_id);
448         });
449         &mut self.stack[ix]
450     }
451 }
452
453 pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
454     body_id: ast::NodeId,
455
456     // Number of errors that had been reported when we started
457     // checking this function. On exit, if we find that *more* errors
458     // have been reported, we will skip regionck and other work that
459     // expects the types within the function to be consistent.
460     err_count_on_creation: usize,
461
462     ret_coercion: Option<RefCell<DynamicCoerceMany<'gcx, 'tcx>>>,
463
464     ps: RefCell<UnsafetyState>,
465
466     /// Whether the last checked node generates a divergence (e.g.,
467     /// `return` will set this to Always). In general, when entering
468     /// an expression or other node in the tree, the initial value
469     /// indicates whether prior parts of the containing expression may
470     /// have diverged. It is then typically set to `Maybe` (and the
471     /// old value remembered) for processing the subparts of the
472     /// current expression. As each subpart is processed, they may set
473     /// the flag to `Always` etc.  Finally, at the end, we take the
474     /// result and "union" it with the original value, so that when we
475     /// return the flag indicates if any subpart of the the parent
476     /// expression (up to and including this part) has diverged.  So,
477     /// if you read it after evaluating a subexpression `X`, the value
478     /// you get indicates whether any subexpression that was
479     /// evaluating up to and including `X` diverged.
480     ///
481     /// We use this flag for two purposes:
482     ///
483     /// - To warn about unreachable code: if, after processing a
484     ///   sub-expression but before we have applied the effects of the
485     ///   current node, we see that the flag is set to `Always`, we
486     ///   can issue a warning. This corresponds to something like
487     ///   `foo(return)`; we warn on the `foo()` expression. (We then
488     ///   update the flag to `WarnedAlways` to suppress duplicate
489     ///   reports.) Similarly, if we traverse to a fresh statement (or
490     ///   tail expression) from a `Always` setting, we will isssue a
491     ///   warning. This corresponds to something like `{return;
492     ///   foo();}` or `{return; 22}`, where we would warn on the
493     ///   `foo()` or `22`.
494     ///
495     /// - To permit assignment into a local variable or other lvalue
496     ///   (including the "return slot") of type `!`.  This is allowed
497     ///   if **either** the type of value being assigned is `!`, which
498     ///   means the current code is dead, **or** the expression's
499     ///   divering flag is true, which means that a divering value was
500     ///   wrapped (e.g., `let x: ! = foo(return)`).
501     ///
502     /// To repeat the last point: an expression represents dead-code
503     /// if, after checking it, **either** its type is `!` OR the
504     /// diverges flag is set to something other than `Maybe`.
505     diverges: Cell<Diverges>,
506
507     /// Whether any child nodes have any type errors.
508     has_errors: Cell<bool>,
509
510     enclosing_breakables: RefCell<EnclosingBreakables<'gcx, 'tcx>>,
511
512     inh: &'a Inherited<'a, 'gcx, 'tcx>,
513 }
514
515 impl<'a, 'gcx, 'tcx> Deref for FnCtxt<'a, 'gcx, 'tcx> {
516     type Target = Inherited<'a, 'gcx, 'tcx>;
517     fn deref(&self) -> &Self::Target {
518         &self.inh
519     }
520 }
521
522 /// Helper type of a temporary returned by Inherited::build(...).
523 /// Necessary because we can't write the following bound:
524 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(Inherited<'b, 'gcx, 'tcx>).
525 pub struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
526     infcx: infer::InferCtxtBuilder<'a, 'gcx, 'tcx>
527 }
528
529 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
530     pub fn build(tcx: TyCtxt<'a, 'gcx, 'gcx>, id: ast::NodeId)
531                  -> InheritedBuilder<'a, 'gcx, 'tcx> {
532         let tables = ty::TypeckTables::empty();
533         let param_env = ParameterEnvironment::for_item(tcx, id);
534         InheritedBuilder {
535             infcx: tcx.infer_ctxt((tables, param_env), Reveal::UserFacing)
536         }
537     }
538 }
539
540 impl<'a, 'gcx, 'tcx> InheritedBuilder<'a, 'gcx, 'tcx> {
541     fn enter<F, R>(&'tcx mut self, f: F) -> R
542         where F: for<'b> FnOnce(Inherited<'b, 'gcx, 'tcx>) -> R
543     {
544         self.infcx.enter(|infcx| f(Inherited::new(infcx)))
545     }
546 }
547
548 impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
549     fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>) -> Self {
550         Inherited {
551             infcx: infcx,
552             fulfillment_cx: RefCell::new(traits::FulfillmentContext::new()),
553             locals: RefCell::new(NodeMap()),
554             deferred_call_resolutions: RefCell::new(DefIdMap()),
555             deferred_cast_checks: RefCell::new(Vec::new()),
556             anon_types: RefCell::new(NodeMap()),
557         }
558     }
559
560     fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
561         debug!("register_predicate({:?})", obligation);
562         if obligation.has_escaping_regions() {
563             span_bug!(obligation.cause.span, "escaping regions in predicate {:?}",
564                       obligation);
565         }
566         self.fulfillment_cx
567             .borrow_mut()
568             .register_predicate_obligation(self, obligation);
569     }
570
571     fn register_predicates(&self, obligations: Vec<traits::PredicateObligation<'tcx>>) {
572         for obligation in obligations {
573             self.register_predicate(obligation);
574         }
575     }
576
577     fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
578         self.register_predicates(infer_ok.obligations);
579         infer_ok.value
580     }
581
582     fn normalize_associated_types_in<T>(&self,
583                                         span: Span,
584                                         body_id: ast::NodeId,
585                                         value: &T) -> T
586         where T : TypeFoldable<'tcx>
587     {
588         let ok = self.normalize_associated_types_in_as_infer_ok(span, body_id, value);
589         self.register_infer_ok_obligations(ok)
590     }
591
592     fn normalize_associated_types_in_as_infer_ok<T>(&self,
593                                                     span: Span,
594                                                     body_id: ast::NodeId,
595                                                     value: &T)
596                                                     -> InferOk<'tcx, T>
597         where T : TypeFoldable<'tcx>
598     {
599         debug!("normalize_associated_types_in(value={:?})", value);
600         let mut selcx = traits::SelectionContext::new(self);
601         let cause = ObligationCause::misc(span, body_id);
602         let traits::Normalized { value, obligations } =
603             traits::normalize(&mut selcx, cause, value);
604         debug!("normalize_associated_types_in: result={:?} predicates={:?}",
605             value,
606             obligations);
607         InferOk { value, obligations }
608     }
609 }
610
611 struct CheckItemTypesVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
612
613 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckItemTypesVisitor<'a, 'tcx> {
614     fn visit_item(&mut self, i: &'tcx hir::Item) {
615         check_item_type(self.tcx, i);
616     }
617     fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) { }
618     fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) { }
619 }
620
621 pub fn check_wf_new<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
622     tcx.sess.track_errors(|| {
623         let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
624         tcx.hir.krate().visit_all_item_likes(&mut visit.as_deep_visitor());
625     })
626 }
627
628 pub fn check_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
629     tcx.sess.track_errors(|| {
630         tcx.hir.krate().visit_all_item_likes(&mut CheckItemTypesVisitor { tcx });
631     })
632 }
633
634 pub fn check_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
635     tcx.typeck_item_bodies(LOCAL_CRATE)
636 }
637
638 fn typeck_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> CompileResult {
639     debug_assert!(crate_num == LOCAL_CRATE);
640     tcx.sess.track_errors(|| {
641         for body_owner_def_id in tcx.body_owners() {
642             tcx.typeck_tables_of(body_owner_def_id);
643         }
644     })
645 }
646
647 pub fn provide(providers: &mut Providers) {
648     *providers = Providers {
649         typeck_item_bodies,
650         typeck_tables_of,
651         has_typeck_tables,
652         closure_type,
653         closure_kind,
654         adt_destructor,
655         ..*providers
656     };
657 }
658
659 fn closure_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
660                           def_id: DefId)
661                           -> ty::PolyFnSig<'tcx> {
662     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
663     tcx.typeck_tables_of(def_id).closure_tys[&node_id]
664 }
665
666 fn closure_kind<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
667                           def_id: DefId)
668                           -> ty::ClosureKind {
669     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
670     tcx.typeck_tables_of(def_id).closure_kinds[&node_id]
671 }
672
673 fn adt_destructor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
674                             def_id: DefId)
675                             -> Option<ty::Destructor> {
676     tcx.calculate_dtor(def_id, &mut dropck::check_drop_impl)
677 }
678
679 /// If this def-id is a "primary tables entry", returns `Some((body_id, decl))`
680 /// with information about it's body-id and fn-decl (if any). Otherwise,
681 /// returns `None`.
682 ///
683 /// If this function returns "some", then `typeck_tables(def_id)` will
684 /// succeed; if it returns `None`, then `typeck_tables(def_id)` may or
685 /// may not succeed.  In some cases where this function returns `None`
686 /// (notably closures), `typeck_tables(def_id)` would wind up
687 /// redirecting to the owning function.
688 fn primary_body_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
689                              id: ast::NodeId)
690                              -> Option<(hir::BodyId, Option<&'tcx hir::FnDecl>)>
691 {
692     match tcx.hir.get(id) {
693         hir::map::NodeItem(item) => {
694             match item.node {
695                 hir::ItemConst(_, body) |
696                 hir::ItemStatic(_, _, body) =>
697                     Some((body, None)),
698                 hir::ItemFn(ref decl, .., body) =>
699                     Some((body, Some(decl))),
700                 _ =>
701                     None,
702             }
703         }
704         hir::map::NodeTraitItem(item) => {
705             match item.node {
706                 hir::TraitItemKind::Const(_, Some(body)) =>
707                     Some((body, None)),
708                 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) =>
709                     Some((body, Some(&sig.decl))),
710                 _ =>
711                     None,
712             }
713         }
714         hir::map::NodeImplItem(item) => {
715             match item.node {
716                 hir::ImplItemKind::Const(_, body) =>
717                     Some((body, None)),
718                 hir::ImplItemKind::Method(ref sig, body) =>
719                     Some((body, Some(&sig.decl))),
720                 _ =>
721                     None,
722             }
723         }
724         hir::map::NodeExpr(expr) => {
725             // FIXME(eddyb) Closures should have separate
726             // function definition IDs and expression IDs.
727             // Type-checking should not let closures get
728             // this far in a constant position.
729             // Assume that everything other than closures
730             // is a constant "initializer" expression.
731             match expr.node {
732                 hir::ExprClosure(..) =>
733                     None,
734                 _ =>
735                     Some((hir::BodyId { node_id: expr.id }, None)),
736             }
737         }
738         _ => None,
739     }
740 }
741
742 fn has_typeck_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
743                                def_id: DefId)
744                                -> bool {
745     // Closures' tables come from their outermost function,
746     // as they are part of the same "inference environment".
747     let outer_def_id = tcx.closure_base_def_id(def_id);
748     if outer_def_id != def_id {
749         return tcx.has_typeck_tables(outer_def_id);
750     }
751
752     let id = tcx.hir.as_local_node_id(def_id).unwrap();
753     primary_body_of(tcx, id).is_some()
754 }
755
756 fn typeck_tables_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
757                               def_id: DefId)
758                               -> &'tcx ty::TypeckTables<'tcx> {
759     // Closures' tables come from their outermost function,
760     // as they are part of the same "inference environment".
761     let outer_def_id = tcx.closure_base_def_id(def_id);
762     if outer_def_id != def_id {
763         return tcx.typeck_tables_of(outer_def_id);
764     }
765
766     let id = tcx.hir.as_local_node_id(def_id).unwrap();
767     let span = tcx.hir.span(id);
768
769     // Figure out what primary body this item has.
770     let (body_id, fn_decl) = primary_body_of(tcx, id).unwrap_or_else(|| {
771         span_bug!(span, "can't type-check body of {:?}", def_id);
772     });
773     let body = tcx.hir.body(body_id);
774
775     Inherited::build(tcx, id).enter(|inh| {
776         let fcx = if let Some(decl) = fn_decl {
777             let fn_sig = tcx.type_of(def_id).fn_sig();
778
779             check_abi(tcx, span, fn_sig.abi());
780
781             // Compute the fty from point of view of inside fn.
782             let fn_scope = inh.tcx.call_site_extent(id, body_id.node_id);
783             let fn_sig =
784                 fn_sig.subst(inh.tcx, &inh.parameter_environment.free_substs);
785             let fn_sig =
786                 inh.tcx.liberate_late_bound_regions(Some(fn_scope), &fn_sig);
787             let fn_sig =
788                 inh.normalize_associated_types_in(body.value.span, body_id.node_id, &fn_sig);
789
790             check_fn(&inh, fn_sig, decl, id, body)
791         } else {
792             let fcx = FnCtxt::new(&inh, body.value.id);
793             let expected_type = tcx.type_of(def_id);
794             let expected_type = fcx.normalize_associated_types_in(body.value.span, &expected_type);
795             fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized);
796
797             // Gather locals in statics (because of block expressions).
798             // This is technically unnecessary because locals in static items are forbidden,
799             // but prevents type checking from blowing up before const checking can properly
800             // emit an error.
801             GatherLocalsVisitor { fcx: &fcx }.visit_body(body);
802
803             fcx.check_expr_coercable_to_type(&body.value, expected_type);
804
805             fcx
806         };
807
808         fcx.select_all_obligations_and_apply_defaults();
809         fcx.closure_analyze(body);
810         fcx.select_obligations_where_possible();
811         fcx.check_casts();
812         fcx.select_all_obligations_or_error();
813
814         if fn_decl.is_some() {
815             fcx.regionck_fn(id, body);
816         } else {
817             fcx.regionck_expr(body);
818         }
819
820         fcx.resolve_type_vars_in_body(body)
821     })
822 }
823
824 fn check_abi<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, abi: Abi) {
825     if !tcx.sess.target.target.is_abi_supported(abi) {
826         struct_span_err!(tcx.sess, span, E0570,
827             "The ABI `{}` is not supported for the current target", abi).emit()
828     }
829 }
830
831 struct GatherLocalsVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
832     fcx: &'a FnCtxt<'a, 'gcx, 'tcx>
833 }
834
835 impl<'a, 'gcx, 'tcx> GatherLocalsVisitor<'a, 'gcx, 'tcx> {
836     fn assign(&mut self, span: Span, nid: ast::NodeId, ty_opt: Option<Ty<'tcx>>) -> Ty<'tcx> {
837         match ty_opt {
838             None => {
839                 // infer the variable's type
840                 let var_ty = self.fcx.next_ty_var(TypeVariableOrigin::TypeInference(span));
841                 self.fcx.locals.borrow_mut().insert(nid, var_ty);
842                 var_ty
843             }
844             Some(typ) => {
845                 // take type that the user specified
846                 self.fcx.locals.borrow_mut().insert(nid, typ);
847                 typ
848             }
849         }
850     }
851 }
852
853 impl<'a, 'gcx, 'tcx> Visitor<'gcx> for GatherLocalsVisitor<'a, 'gcx, 'tcx> {
854     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
855         NestedVisitorMap::None
856     }
857
858     // Add explicitly-declared locals.
859     fn visit_local(&mut self, local: &'gcx hir::Local) {
860         let o_ty = match local.ty {
861             Some(ref ty) => Some(self.fcx.to_ty(&ty)),
862             None => None
863         };
864         self.assign(local.span, local.id, o_ty);
865         debug!("Local variable {:?} is assigned type {}",
866                local.pat,
867                self.fcx.ty_to_string(
868                    self.fcx.locals.borrow().get(&local.id).unwrap().clone()));
869         intravisit::walk_local(self, local);
870     }
871
872     // Add pattern bindings.
873     fn visit_pat(&mut self, p: &'gcx hir::Pat) {
874         if let PatKind::Binding(_, _, ref path1, _) = p.node {
875             let var_ty = self.assign(p.span, p.id, None);
876
877             self.fcx.require_type_is_sized(var_ty, p.span,
878                                            traits::VariableType(p.id));
879
880             debug!("Pattern binding {} is assigned to {} with type {:?}",
881                    path1.node,
882                    self.fcx.ty_to_string(
883                        self.fcx.locals.borrow().get(&p.id).unwrap().clone()),
884                    var_ty);
885         }
886         intravisit::walk_pat(self, p);
887     }
888
889     // Don't descend into the bodies of nested closures
890     fn visit_fn(&mut self, _: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
891                 _: hir::BodyId, _: Span, _: ast::NodeId) { }
892 }
893
894 /// Helper used for fns and closures. Does the grungy work of checking a function
895 /// body and returns the function context used for that purpose, since in the case of a fn item
896 /// there is still a bit more to do.
897 ///
898 /// * ...
899 /// * inherited: other fields inherited from the enclosing fn (if any)
900 fn check_fn<'a, 'gcx, 'tcx>(inherited: &'a Inherited<'a, 'gcx, 'tcx>,
901                             fn_sig: ty::FnSig<'tcx>,
902                             decl: &'gcx hir::FnDecl,
903                             fn_id: ast::NodeId,
904                             body: &'gcx hir::Body)
905                             -> FnCtxt<'a, 'gcx, 'tcx>
906 {
907     let mut fn_sig = fn_sig.clone();
908
909     debug!("check_fn(sig={:?}, fn_id={})", fn_sig, fn_id);
910
911     // Create the function context.  This is either derived from scratch or,
912     // in the case of function expressions, based on the outer context.
913     let mut fcx = FnCtxt::new(inherited, body.value.id);
914     *fcx.ps.borrow_mut() = UnsafetyState::function(fn_sig.unsafety, fn_id);
915
916     let ret_ty = fn_sig.output();
917     fcx.require_type_is_sized(ret_ty, decl.output.span(), traits::ReturnType);
918     let ret_ty = fcx.instantiate_anon_types(&ret_ty);
919     fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
920     fn_sig = fcx.tcx.mk_fn_sig(
921         fn_sig.inputs().iter().cloned(),
922         ret_ty,
923         fn_sig.variadic,
924         fn_sig.unsafety,
925         fn_sig.abi
926     );
927
928     GatherLocalsVisitor { fcx: &fcx, }.visit_body(body);
929
930     // Add formal parameters.
931     for (arg_ty, arg) in fn_sig.inputs().iter().zip(&body.arguments) {
932         // The type of the argument must be well-formed.
933         //
934         // NB -- this is now checked in wfcheck, but that
935         // currently only results in warnings, so we issue an
936         // old-style WF obligation here so that we still get the
937         // errors that we used to get.
938         fcx.register_old_wf_obligation(arg_ty, arg.pat.span, traits::MiscObligation);
939
940         // Check the pattern.
941         fcx.check_pat_arg(&arg.pat, arg_ty, true);
942         fcx.write_ty(arg.id, arg_ty);
943     }
944
945     inherited.tables.borrow_mut().liberated_fn_sigs.insert(fn_id, fn_sig);
946
947     fcx.check_return_expr(&body.value);
948
949     // Finalize the return check by taking the LUB of the return types
950     // we saw and assigning it to the expected return type. This isn't
951     // really expected to fail, since the coercions would have failed
952     // earlier when trying to find a LUB.
953     //
954     // However, the behavior around `!` is sort of complex. In the
955     // event that the `actual_return_ty` comes back as `!`, that
956     // indicates that the fn either does not return or "returns" only
957     // values of type `!`. In this case, if there is an expected
958     // return type that is *not* `!`, that should be ok. But if the
959     // return type is being inferred, we want to "fallback" to `!`:
960     //
961     //     let x = move || panic!();
962     //
963     // To allow for that, I am creating a type variable with diverging
964     // fallback. This was deemed ever so slightly better than unifying
965     // the return value with `!` because it allows for the caller to
966     // make more assumptions about the return type (e.g., they could do
967     //
968     //     let y: Option<u32> = Some(x());
969     //
970     // which would then cause this return type to become `u32`, not
971     // `!`).
972     let coercion = fcx.ret_coercion.take().unwrap().into_inner();
973     let mut actual_return_ty = coercion.complete(&fcx);
974     if actual_return_ty.is_never() {
975         actual_return_ty = fcx.next_diverging_ty_var(
976             TypeVariableOrigin::DivergingFn(body.value.span));
977     }
978     fcx.demand_suptype(body.value.span, ret_ty, actual_return_ty);
979
980     fcx
981 }
982
983 fn check_struct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
984                           id: ast::NodeId,
985                           span: Span) {
986     let def_id = tcx.hir.local_def_id(id);
987     let def = tcx.adt_def(def_id);
988     def.destructor(tcx); // force the destructor to be evaluated
989     check_representable(tcx, span, def_id);
990
991     if def.repr.simd() {
992         check_simd(tcx, span, def_id);
993     }
994
995     // if struct is packed and not aligned, check fields for alignment.
996     // Checks for combining packed and align attrs on single struct are done elsewhere.
997     if tcx.adt_def(def_id).repr.packed() && tcx.adt_def(def_id).repr.align == 0 {
998         check_packed(tcx, span, def_id);
999     }
1000 }
1001
1002 fn check_union<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1003                          id: ast::NodeId,
1004                          span: Span) {
1005     let def_id = tcx.hir.local_def_id(id);
1006     let def = tcx.adt_def(def_id);
1007     def.destructor(tcx); // force the destructor to be evaluated
1008     check_representable(tcx, span, def_id);
1009 }
1010
1011 pub fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item) {
1012     debug!("check_item_type(it.id={}, it.name={})",
1013            it.id,
1014            tcx.item_path_str(tcx.hir.local_def_id(it.id)));
1015     let _indenter = indenter();
1016     match it.node {
1017       // Consts can play a role in type-checking, so they are included here.
1018       hir::ItemStatic(..) |
1019       hir::ItemConst(..) => {
1020         tcx.typeck_tables_of(tcx.hir.local_def_id(it.id));
1021       }
1022       hir::ItemEnum(ref enum_definition, _) => {
1023         check_enum(tcx,
1024                    it.span,
1025                    &enum_definition.variants,
1026                    it.id);
1027       }
1028       hir::ItemFn(..) => {} // entirely within check_item_body
1029       hir::ItemImpl(.., ref impl_item_refs) => {
1030           debug!("ItemImpl {} with id {}", it.name, it.id);
1031           let impl_def_id = tcx.hir.local_def_id(it.id);
1032           if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) {
1033               check_impl_items_against_trait(tcx,
1034                                              it.span,
1035                                              impl_def_id,
1036                                              impl_trait_ref,
1037                                              impl_item_refs);
1038               let trait_def_id = impl_trait_ref.def_id;
1039               check_on_unimplemented(tcx, trait_def_id, it);
1040           }
1041       }
1042       hir::ItemTrait(..) => {
1043         let def_id = tcx.hir.local_def_id(it.id);
1044         check_on_unimplemented(tcx, def_id, it);
1045       }
1046       hir::ItemStruct(..) => {
1047         check_struct(tcx, it.id, it.span);
1048       }
1049       hir::ItemUnion(..) => {
1050         check_union(tcx, it.id, it.span);
1051       }
1052       hir::ItemTy(_, ref generics) => {
1053         let def_id = tcx.hir.local_def_id(it.id);
1054         let pty_ty = tcx.type_of(def_id);
1055         check_bounds_are_used(tcx, generics, pty_ty);
1056       }
1057       hir::ItemForeignMod(ref m) => {
1058         check_abi(tcx, it.span, m.abi);
1059
1060         if m.abi == Abi::RustIntrinsic {
1061             for item in &m.items {
1062                 intrinsic::check_intrinsic_type(tcx, item);
1063             }
1064         } else if m.abi == Abi::PlatformIntrinsic {
1065             for item in &m.items {
1066                 intrinsic::check_platform_intrinsic_type(tcx, item);
1067             }
1068         } else {
1069             for item in &m.items {
1070                 let generics = tcx.generics_of(tcx.hir.local_def_id(item.id));
1071                 if !generics.types.is_empty() {
1072                     let mut err = struct_span_err!(tcx.sess, item.span, E0044,
1073                         "foreign items may not have type parameters");
1074                     span_help!(&mut err, item.span,
1075                         "consider using specialization instead of \
1076                         type parameters");
1077                     err.emit();
1078                 }
1079
1080                 if let hir::ForeignItemFn(ref fn_decl, _, _) = item.node {
1081                     require_c_abi_if_variadic(tcx, fn_decl, m.abi, item.span);
1082                 }
1083             }
1084         }
1085       }
1086       _ => {/* nothing to do */ }
1087     }
1088 }
1089
1090 fn check_on_unimplemented<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1091                                     def_id: DefId,
1092                                     item: &hir::Item) {
1093     let generics = tcx.generics_of(def_id);
1094     if let Some(ref attr) = item.attrs.iter().find(|a| {
1095         a.check_name("rustc_on_unimplemented")
1096     }) {
1097         if let Some(istring) = attr.value_str() {
1098             let istring = istring.as_str();
1099             let parser = Parser::new(&istring);
1100             let types = &generics.types;
1101             for token in parser {
1102                 match token {
1103                     Piece::String(_) => (), // Normal string, no need to check it
1104                     Piece::NextArgument(a) => match a.position {
1105                         // `{Self}` is allowed
1106                         Position::ArgumentNamed(s) if s == "Self" => (),
1107                         // So is `{A}` if A is a type parameter
1108                         Position::ArgumentNamed(s) => match types.iter().find(|t| {
1109                             t.name == s
1110                         }) {
1111                             Some(_) => (),
1112                             None => {
1113                                 let name = tcx.item_name(def_id);
1114                                 span_err!(tcx.sess, attr.span, E0230,
1115                                                  "there is no type parameter \
1116                                                           {} on trait {}",
1117                                                            s, name);
1118                             }
1119                         },
1120                         // `{:1}` and `{}` are not to be used
1121                         Position::ArgumentIs(_) => {
1122                             span_err!(tcx.sess, attr.span, E0231,
1123                                                   "only named substitution \
1124                                                    parameters are allowed");
1125                         }
1126                     }
1127                 }
1128             }
1129         } else {
1130             struct_span_err!(
1131                 tcx.sess, attr.span, E0232,
1132                 "this attribute must have a value")
1133                 .span_label(attr.span, "attribute requires a value")
1134                 .note(&format!("eg `#[rustc_on_unimplemented = \"foo\"]`"))
1135                 .emit();
1136         }
1137     }
1138 }
1139
1140 fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1141                                              impl_item: &hir::ImplItem,
1142                                              parent_impl: DefId)
1143 {
1144     let mut err = struct_span_err!(
1145         tcx.sess, impl_item.span, E0520,
1146         "`{}` specializes an item from a parent `impl`, but \
1147          that item is not marked `default`",
1148         impl_item.name);
1149     err.span_label(impl_item.span, format!("cannot specialize default item `{}`",
1150                                             impl_item.name));
1151
1152     match tcx.span_of_impl(parent_impl) {
1153         Ok(span) => {
1154             err.span_label(span, "parent `impl` is here");
1155             err.note(&format!("to specialize, `{}` in the parent `impl` must be marked `default`",
1156                               impl_item.name));
1157         }
1158         Err(cname) => {
1159             err.note(&format!("parent implementation is in crate `{}`", cname));
1160         }
1161     }
1162
1163     err.emit();
1164 }
1165
1166 fn check_specialization_validity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1167                                            trait_def: &ty::TraitDef,
1168                                            impl_id: DefId,
1169                                            impl_item: &hir::ImplItem)
1170 {
1171     let ancestors = trait_def.ancestors(impl_id);
1172
1173     let kind = match impl_item.node {
1174         hir::ImplItemKind::Const(..) => ty::AssociatedKind::Const,
1175         hir::ImplItemKind::Method(..) => ty::AssociatedKind::Method,
1176         hir::ImplItemKind::Type(_) => ty::AssociatedKind::Type
1177     };
1178     let parent = ancestors.defs(tcx, impl_item.name, kind).skip(1).next()
1179         .map(|node_item| node_item.map(|parent| parent.defaultness));
1180
1181     if let Some(parent) = parent {
1182         if tcx.impl_item_is_final(&parent) {
1183             report_forbidden_specialization(tcx, impl_item, parent.node.def_id());
1184         }
1185     }
1186
1187 }
1188
1189 fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1190                                             impl_span: Span,
1191                                             impl_id: DefId,
1192                                             impl_trait_ref: ty::TraitRef<'tcx>,
1193                                             impl_item_refs: &[hir::ImplItemRef]) {
1194     // If the trait reference itself is erroneous (so the compilation is going
1195     // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1196     // isn't populated for such impls.
1197     if impl_trait_ref.references_error() { return; }
1198
1199     // Locate trait definition and items
1200     let trait_def = tcx.trait_def(impl_trait_ref.def_id);
1201     let mut overridden_associated_type = None;
1202
1203     let impl_items = || impl_item_refs.iter().map(|iiref| tcx.hir.impl_item(iiref.id));
1204
1205     // Check existing impl methods to see if they are both present in trait
1206     // and compatible with trait signature
1207     for impl_item in impl_items() {
1208         let ty_impl_item = tcx.associated_item(tcx.hir.local_def_id(impl_item.id));
1209         let ty_trait_item = tcx.associated_items(impl_trait_ref.def_id)
1210             .find(|ac| ac.name == ty_impl_item.name);
1211
1212         // Check that impl definition matches trait definition
1213         if let Some(ty_trait_item) = ty_trait_item {
1214             match impl_item.node {
1215                 hir::ImplItemKind::Const(..) => {
1216                     // Find associated const definition.
1217                     if ty_trait_item.kind == ty::AssociatedKind::Const {
1218                         compare_const_impl(tcx,
1219                                            &ty_impl_item,
1220                                            impl_item.span,
1221                                            &ty_trait_item,
1222                                            impl_trait_ref);
1223                     } else {
1224                          let mut err = struct_span_err!(tcx.sess, impl_item.span, E0323,
1225                                   "item `{}` is an associated const, \
1226                                   which doesn't match its trait `{}`",
1227                                   ty_impl_item.name,
1228                                   impl_trait_ref);
1229                          err.span_label(impl_item.span, "does not match trait");
1230                          // We can only get the spans from local trait definition
1231                          // Same for E0324 and E0325
1232                          if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1233                             err.span_label(trait_span, "item in trait");
1234                          }
1235                          err.emit()
1236                     }
1237                 }
1238                 hir::ImplItemKind::Method(..) => {
1239                     let trait_span = tcx.hir.span_if_local(ty_trait_item.def_id);
1240                     if ty_trait_item.kind == ty::AssociatedKind::Method {
1241                         let err_count = tcx.sess.err_count();
1242                         compare_impl_method(tcx,
1243                                             &ty_impl_item,
1244                                             impl_item.span,
1245                                             &ty_trait_item,
1246                                             impl_trait_ref,
1247                                             trait_span,
1248                                             true); // start with old-broken-mode
1249                         if err_count == tcx.sess.err_count() {
1250                             // old broken mode did not report an error. Try with the new mode.
1251                             compare_impl_method(tcx,
1252                                                 &ty_impl_item,
1253                                                 impl_item.span,
1254                                                 &ty_trait_item,
1255                                                 impl_trait_ref,
1256                                                 trait_span,
1257                                                 false); // use the new mode
1258                         }
1259                     } else {
1260                         let mut err = struct_span_err!(tcx.sess, impl_item.span, E0324,
1261                                   "item `{}` is an associated method, \
1262                                   which doesn't match its trait `{}`",
1263                                   ty_impl_item.name,
1264                                   impl_trait_ref);
1265                          err.span_label(impl_item.span, "does not match trait");
1266                          if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1267                             err.span_label(trait_span, "item in trait");
1268                          }
1269                          err.emit()
1270                     }
1271                 }
1272                 hir::ImplItemKind::Type(_) => {
1273                     if ty_trait_item.kind == ty::AssociatedKind::Type {
1274                         if ty_trait_item.defaultness.has_value() {
1275                             overridden_associated_type = Some(impl_item);
1276                         }
1277                     } else {
1278                         let mut err = struct_span_err!(tcx.sess, impl_item.span, E0325,
1279                                   "item `{}` is an associated type, \
1280                                   which doesn't match its trait `{}`",
1281                                   ty_impl_item.name,
1282                                   impl_trait_ref);
1283                          err.span_label(impl_item.span, "does not match trait");
1284                          if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
1285                             err.span_label(trait_span, "item in trait");
1286                          }
1287                          err.emit()
1288                     }
1289                 }
1290             }
1291         }
1292
1293         check_specialization_validity(tcx, trait_def, impl_id, impl_item);
1294     }
1295
1296     // Check for missing items from trait
1297     let mut missing_items = Vec::new();
1298     let mut invalidated_items = Vec::new();
1299     let associated_type_overridden = overridden_associated_type.is_some();
1300     for trait_item in tcx.associated_items(impl_trait_ref.def_id) {
1301         let is_implemented = trait_def.ancestors(impl_id)
1302             .defs(tcx, trait_item.name, trait_item.kind)
1303             .next()
1304             .map(|node_item| !node_item.node.is_from_trait())
1305             .unwrap_or(false);
1306
1307         if !is_implemented {
1308             if !trait_item.defaultness.has_value() {
1309                 missing_items.push(trait_item);
1310             } else if associated_type_overridden {
1311                 invalidated_items.push(trait_item.name);
1312             }
1313         }
1314     }
1315
1316     let signature = |item: &ty::AssociatedItem| {
1317         match item.kind {
1318             ty::AssociatedKind::Method => {
1319                 format!("{}", tcx.type_of(item.def_id).fn_sig().0)
1320             }
1321             ty::AssociatedKind::Type => format!("type {};", item.name.to_string()),
1322             ty::AssociatedKind::Const => {
1323                 format!("const {}: {:?};", item.name.to_string(), tcx.type_of(item.def_id))
1324             }
1325         }
1326     };
1327
1328     if !missing_items.is_empty() {
1329         let mut err = struct_span_err!(tcx.sess, impl_span, E0046,
1330             "not all trait items implemented, missing: `{}`",
1331             missing_items.iter()
1332                   .map(|trait_item| trait_item.name.to_string())
1333                   .collect::<Vec<_>>().join("`, `"));
1334         err.span_label(impl_span, format!("missing `{}` in implementation",
1335                 missing_items.iter()
1336                     .map(|trait_item| trait_item.name.to_string())
1337                     .collect::<Vec<_>>().join("`, `")));
1338         for trait_item in missing_items {
1339             if let Some(span) = tcx.hir.span_if_local(trait_item.def_id) {
1340                 err.span_label(span, format!("`{}` from trait", trait_item.name));
1341             } else {
1342                 err.note(&format!("`{}` from trait: `{}`",
1343                                   trait_item.name,
1344                                   signature(&trait_item)));
1345             }
1346         }
1347         err.emit();
1348     }
1349
1350     if !invalidated_items.is_empty() {
1351         let invalidator = overridden_associated_type.unwrap();
1352         span_err!(tcx.sess, invalidator.span, E0399,
1353                   "the following trait items need to be reimplemented \
1354                    as `{}` was overridden: `{}`",
1355                   invalidator.name,
1356                   invalidated_items.iter()
1357                                    .map(|name| name.to_string())
1358                                    .collect::<Vec<_>>().join("`, `"))
1359     }
1360 }
1361
1362 /// Checks whether a type can be represented in memory. In particular, it
1363 /// identifies types that contain themselves without indirection through a
1364 /// pointer, which would mean their size is unbounded.
1365 fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1366                                  sp: Span,
1367                                  item_def_id: DefId)
1368                                  -> bool {
1369     let rty = tcx.type_of(item_def_id);
1370
1371     // Check that it is possible to represent this type. This call identifies
1372     // (1) types that contain themselves and (2) types that contain a different
1373     // recursive type. It is only necessary to throw an error on those that
1374     // contain themselves. For case 2, there must be an inner type that will be
1375     // caught by case 1.
1376     match rty.is_representable(tcx, sp) {
1377         Representability::SelfRecursive(spans) => {
1378             let mut err = tcx.recursive_type_with_infinite_size_error(item_def_id);
1379             for span in spans {
1380                 err.span_label(span, "recursive without indirection");
1381             }
1382             err.emit();
1383             return false
1384         }
1385         Representability::Representable | Representability::ContainsRecursive => (),
1386     }
1387     return true
1388 }
1389
1390 pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
1391     let t = tcx.type_of(def_id);
1392     match t.sty {
1393         ty::TyAdt(def, substs) if def.is_struct() => {
1394             let fields = &def.struct_variant().fields;
1395             if fields.is_empty() {
1396                 span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty");
1397                 return;
1398             }
1399             let e = fields[0].ty(tcx, substs);
1400             if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1401                 struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
1402                                 .span_label(sp, "SIMD elements must have the same type")
1403                                 .emit();
1404                 return;
1405             }
1406             match e.sty {
1407                 ty::TyParam(_) => { /* struct<T>(T, T, T, T) is ok */ }
1408                 _ if e.is_machine()  => { /* struct(u8, u8, u8, u8) is ok */ }
1409                 _ => {
1410                     span_err!(tcx.sess, sp, E0077,
1411                               "SIMD vector element type should be machine type");
1412                     return;
1413                 }
1414             }
1415         }
1416         _ => ()
1417     }
1418 }
1419
1420 fn check_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
1421     if check_packed_inner(tcx, def_id, &mut Vec::new()) {
1422         struct_span_err!(tcx.sess, sp, E0588,
1423             "packed struct cannot transitively contain a `[repr(align)]` struct").emit();
1424     }
1425 }
1426
1427 fn check_packed_inner<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1428                                 def_id: DefId,
1429                                 stack: &mut Vec<DefId>) -> bool {
1430     let t = tcx.type_of(def_id);
1431     if stack.contains(&def_id) {
1432         debug!("check_packed_inner: {:?} is recursive", t);
1433         return false;
1434     }
1435     match t.sty {
1436         ty::TyAdt(def, substs) if def.is_struct() => {
1437             if tcx.adt_def(def.did).repr.align > 0 {
1438                 return true;
1439             }
1440             // push struct def_id before checking fields
1441             stack.push(def_id);
1442             for field in &def.struct_variant().fields {
1443                 let f = field.ty(tcx, substs);
1444                 match f.sty {
1445                     ty::TyAdt(def, _) => {
1446                         if check_packed_inner(tcx, def.did, stack) {
1447                             return true;
1448                         }
1449                     }
1450                     _ => ()
1451                 }
1452             }
1453             // only need to pop if not early out
1454             stack.pop();
1455         }
1456         _ => ()
1457     }
1458     false
1459 }
1460
1461 #[allow(trivial_numeric_casts)]
1462 pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1463                             sp: Span,
1464                             vs: &'tcx [hir::Variant],
1465                             id: ast::NodeId) {
1466     let def_id = tcx.hir.local_def_id(id);
1467     let def = tcx.adt_def(def_id);
1468     def.destructor(tcx); // force the destructor to be evaluated
1469
1470     if vs.is_empty() && tcx.has_attr(def_id, "repr") {
1471         struct_span_err!(
1472             tcx.sess, sp, E0084,
1473             "unsupported representation for zero-variant enum")
1474             .span_label(sp, "unsupported enum representation")
1475             .emit();
1476     }
1477
1478     let repr_type_ty = def.repr.discr_type().to_ty(tcx);
1479     if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1480         if !tcx.sess.features.borrow().i128_type {
1481             emit_feature_err(&tcx.sess.parse_sess,
1482                              "i128_type", sp, GateIssue::Language, "128-bit type is unstable");
1483         }
1484     }
1485
1486     for v in vs {
1487         if let Some(e) = v.node.disr_expr {
1488             tcx.typeck_tables_of(tcx.hir.local_def_id(e.node_id));
1489         }
1490     }
1491
1492     let mut disr_vals: Vec<ConstInt> = Vec::new();
1493     for (discr, v) in def.discriminants(tcx).zip(vs) {
1494         // Check for duplicate discriminant values
1495         if let Some(i) = disr_vals.iter().position(|&x| x == discr) {
1496             let variant_i_node_id = tcx.hir.as_local_node_id(def.variants[i].did).unwrap();
1497             let variant_i = tcx.hir.expect_variant(variant_i_node_id);
1498             let i_span = match variant_i.node.disr_expr {
1499                 Some(expr) => tcx.hir.span(expr.node_id),
1500                 None => tcx.hir.span(variant_i_node_id)
1501             };
1502             let span = match v.node.disr_expr {
1503                 Some(expr) => tcx.hir.span(expr.node_id),
1504                 None => v.span
1505             };
1506             struct_span_err!(tcx.sess, span, E0081,
1507                              "discriminant value `{}` already exists", disr_vals[i])
1508                 .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
1509                 .span_label(span , format!("enum already has `{}`", disr_vals[i]))
1510                 .emit();
1511         }
1512         disr_vals.push(discr);
1513     }
1514
1515     check_representable(tcx, sp, def_id);
1516 }
1517
1518 impl<'a, 'gcx, 'tcx> AstConv<'gcx, 'tcx> for FnCtxt<'a, 'gcx, 'tcx> {
1519     fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
1520
1521     fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
1522         Some(&self.parameter_environment.free_substs)
1523     }
1524
1525     fn get_type_parameter_bounds(&self, _: Span, def_id: DefId)
1526                                  -> ty::GenericPredicates<'tcx>
1527     {
1528         let tcx = self.tcx;
1529         let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
1530         let item_id = tcx.hir.ty_param_owner(node_id);
1531         let item_def_id = tcx.hir.local_def_id(item_id);
1532         let generics = tcx.generics_of(item_def_id);
1533         let index = generics.type_param_to_index[&def_id.index];
1534         ty::GenericPredicates {
1535             parent: None,
1536             predicates: self.parameter_environment.caller_bounds.iter().filter(|predicate| {
1537                 match **predicate {
1538                     ty::Predicate::Trait(ref data) => {
1539                         data.0.self_ty().is_param(index)
1540                     }
1541                     _ => false
1542                 }
1543             }).cloned().collect()
1544         }
1545     }
1546
1547     fn re_infer(&self, span: Span, def: Option<&ty::RegionParameterDef>)
1548                 -> Option<ty::Region<'tcx>> {
1549         let v = match def {
1550             Some(def) => infer::EarlyBoundRegion(span, def.name, def.issue_32330),
1551             None => infer::MiscVariable(span)
1552         };
1553         Some(self.next_region_var(v))
1554     }
1555
1556     fn ty_infer(&self, span: Span) -> Ty<'tcx> {
1557         self.next_ty_var(TypeVariableOrigin::TypeInference(span))
1558     }
1559
1560     fn ty_infer_for_def(&self,
1561                         ty_param_def: &ty::TypeParameterDef,
1562                         substs: &[Kind<'tcx>],
1563                         span: Span) -> Ty<'tcx> {
1564         self.type_var_for_def(span, ty_param_def, substs)
1565     }
1566
1567     fn projected_ty_from_poly_trait_ref(&self,
1568                                         span: Span,
1569                                         poly_trait_ref: ty::PolyTraitRef<'tcx>,
1570                                         item_name: ast::Name)
1571                                         -> Ty<'tcx>
1572     {
1573         let (trait_ref, _) =
1574             self.replace_late_bound_regions_with_fresh_var(
1575                 span,
1576                 infer::LateBoundRegionConversionTime::AssocTypeProjection(item_name),
1577                 &poly_trait_ref);
1578
1579         self.tcx().mk_projection(trait_ref, item_name)
1580     }
1581
1582     fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1583         if ty.has_escaping_regions() {
1584             ty // FIXME: normalization and escaping regions
1585         } else {
1586             self.normalize_associated_types_in(span, &ty)
1587         }
1588     }
1589
1590     fn set_tainted_by_errors(&self) {
1591         self.infcx.set_tainted_by_errors()
1592     }
1593 }
1594
1595 /// Controls whether the arguments are tupled. This is used for the call
1596 /// operator.
1597 ///
1598 /// Tupling means that all call-side arguments are packed into a tuple and
1599 /// passed as a single parameter. For example, if tupling is enabled, this
1600 /// function:
1601 ///
1602 ///     fn f(x: (isize, isize))
1603 ///
1604 /// Can be called as:
1605 ///
1606 ///     f(1, 2);
1607 ///
1608 /// Instead of:
1609 ///
1610 ///     f((1, 2));
1611 #[derive(Clone, Eq, PartialEq)]
1612 enum TupleArgumentsFlag {
1613     DontTupleArguments,
1614     TupleArguments,
1615 }
1616
1617 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1618     pub fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>,
1619                body_id: ast::NodeId)
1620                -> FnCtxt<'a, 'gcx, 'tcx> {
1621         FnCtxt {
1622             body_id: body_id,
1623             err_count_on_creation: inh.tcx.sess.err_count(),
1624             ret_coercion: None,
1625             ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal,
1626                                                      ast::CRATE_NODE_ID)),
1627             diverges: Cell::new(Diverges::Maybe),
1628             has_errors: Cell::new(false),
1629             enclosing_breakables: RefCell::new(EnclosingBreakables {
1630                 stack: Vec::new(),
1631                 by_id: NodeMap(),
1632             }),
1633             inh: inh,
1634         }
1635     }
1636
1637     pub fn sess(&self) -> &Session {
1638         &self.tcx.sess
1639     }
1640
1641     pub fn err_count_since_creation(&self) -> usize {
1642         self.tcx.sess.err_count() - self.err_count_on_creation
1643     }
1644
1645     /// Produce warning on the given node, if the current point in the
1646     /// function is unreachable, and there hasn't been another warning.
1647     fn warn_if_unreachable(&self, id: ast::NodeId, span: Span, kind: &str) {
1648         if self.diverges.get() == Diverges::Always {
1649             self.diverges.set(Diverges::WarnedAlways);
1650
1651             debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
1652
1653             self.tables.borrow_mut().lints.add_lint(
1654                 lint::builtin::UNREACHABLE_CODE,
1655                 id, span,
1656                 format!("unreachable {}", kind));
1657         }
1658     }
1659
1660     pub fn cause(&self,
1661                  span: Span,
1662                  code: ObligationCauseCode<'tcx>)
1663                  -> ObligationCause<'tcx> {
1664         ObligationCause::new(span, self.body_id, code)
1665     }
1666
1667     pub fn misc(&self, span: Span) -> ObligationCause<'tcx> {
1668         self.cause(span, ObligationCauseCode::MiscObligation)
1669     }
1670
1671     /// Resolves type variables in `ty` if possible. Unlike the infcx
1672     /// version (resolve_type_vars_if_possible), this version will
1673     /// also select obligations if it seems useful, in an effort
1674     /// to get more type information.
1675     fn resolve_type_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
1676         debug!("resolve_type_vars_with_obligations(ty={:?})", ty);
1677
1678         // No TyInfer()? Nothing needs doing.
1679         if !ty.has_infer_types() {
1680             debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1681             return ty;
1682         }
1683
1684         // If `ty` is a type variable, see whether we already know what it is.
1685         ty = self.resolve_type_vars_if_possible(&ty);
1686         if !ty.has_infer_types() {
1687             debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1688             return ty;
1689         }
1690
1691         // If not, try resolving pending obligations as much as
1692         // possible. This can help substantially when there are
1693         // indirect dependencies that don't seem worth tracking
1694         // precisely.
1695         self.select_obligations_where_possible();
1696         ty = self.resolve_type_vars_if_possible(&ty);
1697
1698         debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
1699         ty
1700     }
1701
1702     fn record_deferred_call_resolution(&self,
1703                                        closure_def_id: DefId,
1704                                        r: DeferredCallResolutionHandler<'gcx, 'tcx>) {
1705         let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1706         deferred_call_resolutions.entry(closure_def_id).or_insert(vec![]).push(r);
1707     }
1708
1709     fn remove_deferred_call_resolutions(&self,
1710                                         closure_def_id: DefId)
1711                                         -> Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>
1712     {
1713         let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
1714         deferred_call_resolutions.remove(&closure_def_id).unwrap_or(Vec::new())
1715     }
1716
1717     pub fn tag(&self) -> String {
1718         let self_ptr: *const FnCtxt = self;
1719         format!("{:?}", self_ptr)
1720     }
1721
1722     pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> {
1723         match self.locals.borrow().get(&nid) {
1724             Some(&t) => t,
1725             None => {
1726                 span_bug!(span, "no type for local variable {}",
1727                           self.tcx.hir.node_to_string(nid));
1728             }
1729         }
1730     }
1731
1732     #[inline]
1733     pub fn write_ty(&self, node_id: ast::NodeId, ty: Ty<'tcx>) {
1734         debug!("write_ty({}, {:?}) in fcx {}",
1735                node_id, self.resolve_type_vars_if_possible(&ty), self.tag());
1736         self.tables.borrow_mut().node_types.insert(node_id, ty);
1737
1738         if ty.references_error() {
1739             self.has_errors.set(true);
1740             self.set_tainted_by_errors();
1741         }
1742     }
1743
1744     pub fn write_substs(&self, node_id: ast::NodeId, substs: ty::ItemSubsts<'tcx>) {
1745         if !substs.substs.is_noop() {
1746             debug!("write_substs({}, {:?}) in fcx {}",
1747                    node_id,
1748                    substs,
1749                    self.tag());
1750
1751             self.tables.borrow_mut().item_substs.insert(node_id, substs);
1752         }
1753     }
1754
1755     pub fn apply_autoderef_adjustment(&self,
1756                                       node_id: ast::NodeId,
1757                                       derefs: usize,
1758                                       adjusted_ty: Ty<'tcx>) {
1759         self.apply_adjustment(node_id, Adjustment {
1760             kind: Adjust::DerefRef {
1761                 autoderefs: derefs,
1762                 autoref: None,
1763                 unsize: false
1764             },
1765             target: adjusted_ty
1766         });
1767     }
1768
1769     pub fn apply_adjustment(&self, node_id: ast::NodeId, adj: Adjustment<'tcx>) {
1770         debug!("apply_adjustment(node_id={}, adj={:?})", node_id, adj);
1771
1772         if adj.is_identity() {
1773             return;
1774         }
1775
1776         match self.tables.borrow_mut().adjustments.entry(node_id) {
1777             Entry::Vacant(entry) => { entry.insert(adj); },
1778             Entry::Occupied(mut entry) => {
1779                 debug!(" - composing on top of {:?}", entry.get());
1780                 let composed_kind = match (entry.get().kind, adj.kind) {
1781                     // Applying any adjustment on top of a NeverToAny
1782                     // is a valid NeverToAny adjustment, because it can't
1783                     // be reached.
1784                     (Adjust::NeverToAny, _) => Adjust::NeverToAny,
1785                     (Adjust::DerefRef {
1786                         autoderefs: 1,
1787                         autoref: Some(AutoBorrow::Ref(..)),
1788                         unsize: false
1789                     }, Adjust::DerefRef { autoderefs, .. }) if autoderefs > 0 => {
1790                         // A reborrow has no effect before a dereference.
1791                         adj.kind
1792                     }
1793                     // FIXME: currently we never try to compose autoderefs
1794                     // and ReifyFnPointer/UnsafeFnPointer, but we could.
1795                     _ =>
1796                         bug!("while adjusting {}, can't compose {:?} and {:?}",
1797                              node_id, entry.get(), adj)
1798                 };
1799                 *entry.get_mut() = Adjustment {
1800                     kind: composed_kind,
1801                     target: adj.target
1802                 };
1803             }
1804         }
1805     }
1806
1807     /// Basically whenever we are converting from a type scheme into
1808     /// the fn body space, we always want to normalize associated
1809     /// types as well. This function combines the two.
1810     fn instantiate_type_scheme<T>(&self,
1811                                   span: Span,
1812                                   substs: &Substs<'tcx>,
1813                                   value: &T)
1814                                   -> T
1815         where T : TypeFoldable<'tcx>
1816     {
1817         let value = value.subst(self.tcx, substs);
1818         let result = self.normalize_associated_types_in(span, &value);
1819         debug!("instantiate_type_scheme(value={:?}, substs={:?}) = {:?}",
1820                value,
1821                substs,
1822                result);
1823         result
1824     }
1825
1826     /// As `instantiate_type_scheme`, but for the bounds found in a
1827     /// generic type scheme.
1828     fn instantiate_bounds(&self, span: Span, def_id: DefId, substs: &Substs<'tcx>)
1829                           -> ty::InstantiatedPredicates<'tcx> {
1830         let bounds = self.tcx.predicates_of(def_id);
1831         let result = bounds.instantiate(self.tcx, substs);
1832         let result = self.normalize_associated_types_in(span, &result);
1833         debug!("instantiate_bounds(bounds={:?}, substs={:?}) = {:?}",
1834                bounds,
1835                substs,
1836                result);
1837         result
1838     }
1839
1840     /// Replace all anonymized types with fresh inference variables
1841     /// and record them for writeback.
1842     fn instantiate_anon_types<T: TypeFoldable<'tcx>>(&self, value: &T) -> T {
1843         value.fold_with(&mut BottomUpFolder { tcx: self.tcx, fldop: |ty| {
1844             if let ty::TyAnon(def_id, substs) = ty.sty {
1845                 // Use the same type variable if the exact same TyAnon appears more
1846                 // than once in the return type (e.g. if it's pased to a type alias).
1847                 let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
1848                 if let Some(ty_var) = self.anon_types.borrow().get(&id) {
1849                     return ty_var;
1850                 }
1851                 let span = self.tcx.def_span(def_id);
1852                 let ty_var = self.next_ty_var(TypeVariableOrigin::TypeInference(span));
1853                 self.anon_types.borrow_mut().insert(id, ty_var);
1854
1855                 let predicates_of = self.tcx.predicates_of(def_id);
1856                 let bounds = predicates_of.instantiate(self.tcx, substs);
1857
1858                 for predicate in bounds.predicates {
1859                     // Change the predicate to refer to the type variable,
1860                     // which will be the concrete type, instead of the TyAnon.
1861                     // This also instantiates nested `impl Trait`.
1862                     let predicate = self.instantiate_anon_types(&predicate);
1863
1864                     // Require that the predicate holds for the concrete type.
1865                     let cause = traits::ObligationCause::new(span, self.body_id,
1866                                                              traits::ReturnType);
1867                     self.register_predicate(traits::Obligation::new(cause, predicate));
1868                 }
1869
1870                 ty_var
1871             } else {
1872                 ty
1873             }
1874         }})
1875     }
1876
1877     fn normalize_associated_types_in<T>(&self, span: Span, value: &T) -> T
1878         where T : TypeFoldable<'tcx>
1879     {
1880         let ok = self.normalize_associated_types_in_as_infer_ok(span, value);
1881         self.register_infer_ok_obligations(ok)
1882     }
1883
1884     fn normalize_associated_types_in_as_infer_ok<T>(&self, span: Span, value: &T)
1885                                                     -> InferOk<'tcx, T>
1886         where T : TypeFoldable<'tcx>
1887     {
1888         self.inh.normalize_associated_types_in_as_infer_ok(span, self.body_id, value)
1889     }
1890
1891     pub fn write_nil(&self, node_id: ast::NodeId) {
1892         self.write_ty(node_id, self.tcx.mk_nil());
1893     }
1894
1895     pub fn write_error(&self, node_id: ast::NodeId) {
1896         self.write_ty(node_id, self.tcx.types.err);
1897     }
1898
1899     pub fn require_type_meets(&self,
1900                               ty: Ty<'tcx>,
1901                               span: Span,
1902                               code: traits::ObligationCauseCode<'tcx>,
1903                               def_id: DefId)
1904     {
1905         self.register_bound(
1906             ty,
1907             def_id,
1908             traits::ObligationCause::new(span, self.body_id, code));
1909     }
1910
1911     pub fn require_type_is_sized(&self,
1912                                  ty: Ty<'tcx>,
1913                                  span: Span,
1914                                  code: traits::ObligationCauseCode<'tcx>)
1915     {
1916         let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem);
1917         self.require_type_meets(ty, span, code, lang_item);
1918     }
1919
1920     pub fn register_bound(&self,
1921                           ty: Ty<'tcx>,
1922                           def_id: DefId,
1923                           cause: traits::ObligationCause<'tcx>)
1924     {
1925         self.fulfillment_cx.borrow_mut()
1926             .register_bound(self, ty, def_id, cause);
1927     }
1928
1929     pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> {
1930         let t = AstConv::ast_ty_to_ty(self, ast_t);
1931         self.register_wf_obligation(t, ast_t.span, traits::MiscObligation);
1932         t
1933     }
1934
1935     pub fn node_ty(&self, id: ast::NodeId) -> Ty<'tcx> {
1936         match self.tables.borrow().node_types.get(&id) {
1937             Some(&t) => t,
1938             None if self.err_count_since_creation() != 0 => self.tcx.types.err,
1939             None => {
1940                 bug!("no type for node {}: {} in fcx {}",
1941                      id, self.tcx.hir.node_to_string(id),
1942                      self.tag());
1943             }
1944         }
1945     }
1946
1947     pub fn opt_node_ty_substs<F>(&self,
1948                                  id: ast::NodeId,
1949                                  f: F) where
1950         F: FnOnce(&ty::ItemSubsts<'tcx>),
1951     {
1952         if let Some(s) = self.tables.borrow().item_substs.get(&id) {
1953             f(s);
1954         }
1955     }
1956
1957     /// Registers an obligation for checking later, during regionck, that the type `ty` must
1958     /// outlive the region `r`.
1959     pub fn register_region_obligation(&self,
1960                                       ty: Ty<'tcx>,
1961                                       region: ty::Region<'tcx>,
1962                                       cause: traits::ObligationCause<'tcx>)
1963     {
1964         let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
1965         fulfillment_cx.register_region_obligation(ty, region, cause);
1966     }
1967
1968     /// Registers an obligation for checking later, during regionck, that the type `ty` must
1969     /// outlive the region `r`.
1970     pub fn register_wf_obligation(&self,
1971                                   ty: Ty<'tcx>,
1972                                   span: Span,
1973                                   code: traits::ObligationCauseCode<'tcx>)
1974     {
1975         // WF obligations never themselves fail, so no real need to give a detailed cause:
1976         let cause = traits::ObligationCause::new(span, self.body_id, code);
1977         self.register_predicate(traits::Obligation::new(cause, ty::Predicate::WellFormed(ty)));
1978     }
1979
1980     pub fn register_old_wf_obligation(&self,
1981                                       ty: Ty<'tcx>,
1982                                       span: Span,
1983                                       code: traits::ObligationCauseCode<'tcx>)
1984     {
1985         // Registers an "old-style" WF obligation that uses the
1986         // implicator code.  This is basically a buggy version of
1987         // `register_wf_obligation` that is being kept around
1988         // temporarily just to help with phasing in the newer rules.
1989         //
1990         // FIXME(#27579) all uses of this should be migrated to register_wf_obligation eventually
1991         let cause = traits::ObligationCause::new(span, self.body_id, code);
1992         self.register_region_obligation(ty, self.tcx.types.re_empty, cause);
1993     }
1994
1995     /// Registers obligations that all types appearing in `substs` are well-formed.
1996     pub fn add_wf_bounds(&self, substs: &Substs<'tcx>, expr: &hir::Expr)
1997     {
1998         for ty in substs.types() {
1999             self.register_wf_obligation(ty, expr.span, traits::MiscObligation);
2000         }
2001     }
2002
2003     /// Given a fully substituted set of bounds (`generic_bounds`), and the values with which each
2004     /// type/region parameter was instantiated (`substs`), creates and registers suitable
2005     /// trait/region obligations.
2006     ///
2007     /// For example, if there is a function:
2008     ///
2009     /// ```
2010     /// fn foo<'a,T:'a>(...)
2011     /// ```
2012     ///
2013     /// and a reference:
2014     ///
2015     /// ```
2016     /// let f = foo;
2017     /// ```
2018     ///
2019     /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a`
2020     /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally.
2021     pub fn add_obligations_for_parameters(&self,
2022                                           cause: traits::ObligationCause<'tcx>,
2023                                           predicates: &ty::InstantiatedPredicates<'tcx>)
2024     {
2025         assert!(!predicates.has_escaping_regions());
2026
2027         debug!("add_obligations_for_parameters(predicates={:?})",
2028                predicates);
2029
2030         for obligation in traits::predicates_for_generics(cause, predicates) {
2031             self.register_predicate(obligation);
2032         }
2033     }
2034
2035     // FIXME(arielb1): use this instead of field.ty everywhere
2036     // Only for fields! Returns <none> for methods>
2037     // Indifferent to privacy flags
2038     pub fn field_ty(&self,
2039                     span: Span,
2040                     field: &'tcx ty::FieldDef,
2041                     substs: &Substs<'tcx>)
2042                     -> Ty<'tcx>
2043     {
2044         self.normalize_associated_types_in(span,
2045                                            &field.ty(self.tcx, substs))
2046     }
2047
2048     fn check_casts(&self) {
2049         let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
2050         for cast in deferred_cast_checks.drain(..) {
2051             cast.check(self);
2052         }
2053     }
2054
2055     /// Apply "fallbacks" to some types
2056     /// unconstrained types get replaced with ! or  () (depending on whether
2057     /// feature(never_type) is enabled), unconstrained ints with i32, and
2058     /// unconstrained floats with f64.
2059     fn default_type_parameters(&self) {
2060         use rustc::ty::error::UnconstrainedNumeric::Neither;
2061         use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
2062
2063         // Defaulting inference variables becomes very dubious if we have
2064         // encountered type-checking errors. Therefore, if we think we saw
2065         // some errors in this function, just resolve all uninstanted type
2066         // varibles to TyError.
2067         if self.is_tainted_by_errors() {
2068             for ty in &self.unsolved_variables() {
2069                 if let ty::TyInfer(_) = self.shallow_resolve(ty).sty {
2070                     debug!("default_type_parameters: defaulting `{:?}` to error", ty);
2071                     self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx().types.err);
2072                 }
2073             }
2074             return;
2075         }
2076
2077         for ty in &self.unsolved_variables() {
2078             let resolved = self.resolve_type_vars_if_possible(ty);
2079             if self.type_var_diverges(resolved) {
2080                 debug!("default_type_parameters: defaulting `{:?}` to `!` because it diverges",
2081                        resolved);
2082                 self.demand_eqtype(syntax_pos::DUMMY_SP, *ty,
2083                                    self.tcx.mk_diverging_default());
2084             } else {
2085                 match self.type_is_unconstrained_numeric(resolved) {
2086                     UnconstrainedInt => {
2087                         debug!("default_type_parameters: defaulting `{:?}` to `i32`",
2088                                resolved);
2089                         self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.i32)
2090                     },
2091                     UnconstrainedFloat => {
2092                         debug!("default_type_parameters: defaulting `{:?}` to `f32`",
2093                                resolved);
2094                         self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.f64)
2095                     }
2096                     Neither => { }
2097                 }
2098             }
2099         }
2100     }
2101
2102     // Implements type inference fallback algorithm
2103     fn select_all_obligations_and_apply_defaults(&self) {
2104         self.select_obligations_where_possible();
2105         self.default_type_parameters();
2106         self.select_obligations_where_possible();
2107     }
2108
2109     fn select_all_obligations_or_error(&self) {
2110         debug!("select_all_obligations_or_error");
2111
2112         // upvar inference should have ensured that all deferred call
2113         // resolutions are handled by now.
2114         assert!(self.deferred_call_resolutions.borrow().is_empty());
2115
2116         self.select_all_obligations_and_apply_defaults();
2117
2118         let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
2119
2120         match fulfillment_cx.select_all_or_error(self) {
2121             Ok(()) => { }
2122             Err(errors) => { self.report_fulfillment_errors(&errors); }
2123         }
2124     }
2125
2126     /// Select as many obligations as we can at present.
2127     fn select_obligations_where_possible(&self) {
2128         match self.fulfillment_cx.borrow_mut().select_where_possible(self) {
2129             Ok(()) => { }
2130             Err(errors) => { self.report_fulfillment_errors(&errors); }
2131         }
2132     }
2133
2134     /// For the overloaded lvalue expressions (`*x`, `x[3]`), the trait
2135     /// returns a type of `&T`, but the actual type we assign to the
2136     /// *expression* is `T`. So this function just peels off the return
2137     /// type by one layer to yield `T`.
2138     fn make_overloaded_lvalue_return_type(&self,
2139                                           method: MethodCallee<'tcx>)
2140                                           -> ty::TypeAndMut<'tcx>
2141     {
2142         // extract method return type, which will be &T;
2143         // all LB regions should have been instantiated during method lookup
2144         let ret_ty = method.ty.fn_ret();
2145         let ret_ty = self.tcx.no_late_bound_regions(&ret_ty).unwrap();
2146
2147         // method returns &T, but the type as visible to user is T, so deref
2148         ret_ty.builtin_deref(true, NoPreference).unwrap()
2149     }
2150
2151     fn lookup_indexing(&self,
2152                        expr: &hir::Expr,
2153                        base_expr: &'gcx hir::Expr,
2154                        base_ty: Ty<'tcx>,
2155                        idx_ty: Ty<'tcx>,
2156                        lvalue_pref: LvaluePreference)
2157                        -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2158     {
2159         // FIXME(#18741) -- this is almost but not quite the same as the
2160         // autoderef that normal method probing does. They could likely be
2161         // consolidated.
2162
2163         let mut autoderef = self.autoderef(base_expr.span, base_ty);
2164
2165         while let Some((adj_ty, autoderefs)) = autoderef.next() {
2166             if let Some(final_mt) = self.try_index_step(
2167                 MethodCall::expr(expr.id), expr, Some(AdjustedRcvr {
2168                     rcvr_expr: base_expr,
2169                     autoderefs,
2170                     unsize: false
2171                 }), base_expr.span, adj_ty, lvalue_pref, idx_ty)
2172             {
2173                 autoderef.finalize(lvalue_pref, base_expr);
2174                 return Some(final_mt);
2175             }
2176
2177             if let ty::TyArray(element_ty, _) = adj_ty.sty {
2178                 autoderef.finalize(lvalue_pref, base_expr);
2179                 let adj_ty = self.tcx.mk_slice(element_ty);
2180                 return self.try_index_step(
2181                     MethodCall::expr(expr.id), expr, Some(AdjustedRcvr {
2182                         rcvr_expr: base_expr,
2183                         autoderefs,
2184                         unsize: true
2185                     }), base_expr.span, adj_ty, lvalue_pref, idx_ty)
2186             }
2187         }
2188         autoderef.unambiguous_final_ty();
2189         None
2190     }
2191
2192     /// To type-check `base_expr[index_expr]`, we progressively autoderef
2193     /// (and otherwise adjust) `base_expr`, looking for a type which either
2194     /// supports builtin indexing or overloaded indexing.
2195     /// This loop implements one step in that search; the autoderef loop
2196     /// is implemented by `lookup_indexing`.
2197     fn try_index_step(&self,
2198                       method_call: MethodCall,
2199                       expr: &hir::Expr,
2200                       base_expr: Option<AdjustedRcvr>,
2201                       base_span: Span,
2202                       adjusted_ty: Ty<'tcx>,
2203                       lvalue_pref: LvaluePreference,
2204                       index_ty: Ty<'tcx>)
2205                       -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2206     {
2207         let tcx = self.tcx;
2208         debug!("try_index_step(expr={:?}, base_expr={:?}, adjusted_ty={:?}, \
2209                                index_ty={:?})",
2210                expr,
2211                base_expr,
2212                adjusted_ty,
2213                index_ty);
2214
2215         let input_ty = self.next_ty_var(TypeVariableOrigin::AutoDeref(base_span));
2216
2217         // First, try built-in indexing.
2218         match (adjusted_ty.builtin_index(), &index_ty.sty) {
2219             (Some(ty), &ty::TyUint(ast::UintTy::Us)) | (Some(ty), &ty::TyInfer(ty::IntVar(_))) => {
2220                 debug!("try_index_step: success, using built-in indexing");
2221                 // If we had `[T; N]`, we should've caught it before unsizing to `[T]`.
2222                 if let Some(base_expr) = base_expr {
2223                     assert!(!base_expr.unsize);
2224                     self.apply_autoderef_adjustment(
2225                         base_expr.rcvr_expr.id, base_expr.autoderefs, adjusted_ty);
2226                 }
2227                 return Some((tcx.types.usize, ty));
2228             }
2229             _ => {}
2230         }
2231
2232         // If some lookup succeeds, write callee into table and extract index/element
2233         // type from the method signature.
2234         // If some lookup succeeded, install method in table
2235         let method = self.try_overloaded_lvalue_op(
2236             expr.span, base_expr, adjusted_ty, &[input_ty], lvalue_pref, LvalueOp::Index);
2237
2238         method.map(|ok| {
2239             debug!("try_index_step: success, using overloaded indexing");
2240             let method = self.register_infer_ok_obligations(ok);
2241             self.tables.borrow_mut().method_map.insert(method_call, method);
2242             (input_ty, self.make_overloaded_lvalue_return_type(method).ty)
2243         })
2244     }
2245
2246     fn resolve_lvalue_op(&self, op: LvalueOp, is_mut: bool) -> (Option<DefId>, Symbol) {
2247         let (tr, name) = match (op, is_mut) {
2248             (LvalueOp::Deref, false) =>
2249                 (self.tcx.lang_items.deref_trait(), "deref"),
2250             (LvalueOp::Deref, true) =>
2251                 (self.tcx.lang_items.deref_mut_trait(), "deref_mut"),
2252             (LvalueOp::Index, false) =>
2253                 (self.tcx.lang_items.index_trait(), "index"),
2254             (LvalueOp::Index, true) =>
2255                 (self.tcx.lang_items.index_mut_trait(), "index_mut"),
2256         };
2257         (tr, Symbol::intern(name))
2258     }
2259
2260     fn try_overloaded_lvalue_op(&self,
2261                                 span: Span,
2262                                 base_expr: Option<AdjustedRcvr>,
2263                                 base_ty: Ty<'tcx>,
2264                                 arg_tys: &[Ty<'tcx>],
2265                                 lvalue_pref: LvaluePreference,
2266                                 op: LvalueOp)
2267                                 -> Option<InferOk<'tcx, MethodCallee<'tcx>>>
2268     {
2269         debug!("try_overloaded_lvalue_op({:?},{:?},{:?},{:?},{:?})",
2270                span,
2271                base_expr,
2272                base_ty,
2273                lvalue_pref,
2274                op);
2275
2276         // Try Mut first, if preferred.
2277         let (mut_tr, mut_op) = self.resolve_lvalue_op(op, true);
2278         let method = match (lvalue_pref, mut_tr) {
2279             (PreferMutLvalue, Some(trait_did)) => {
2280                 self.lookup_method_in_trait_adjusted(span,
2281                                                      base_expr,
2282                                                      mut_op,
2283                                                      trait_did,
2284                                                      base_ty,
2285                                                      Some(arg_tys.to_owned()))
2286             }
2287             _ => None,
2288         };
2289
2290         // Otherwise, fall back to the immutable version.
2291         let (imm_tr, imm_op) = self.resolve_lvalue_op(op, false);
2292         let method = match (method, imm_tr) {
2293             (None, Some(trait_did)) => {
2294                 self.lookup_method_in_trait_adjusted(span,
2295                                                      base_expr,
2296                                                      imm_op,
2297                                                      trait_did,
2298                                                      base_ty,
2299                                                      Some(arg_tys.to_owned()))
2300             }
2301             (method, _) => method,
2302         };
2303
2304         method
2305     }
2306
2307     fn check_method_argument_types(&self,
2308                                    sp: Span,
2309                                    method_fn_ty: Ty<'tcx>,
2310                                    callee_expr: &'gcx hir::Expr,
2311                                    args_no_rcvr: &'gcx [hir::Expr],
2312                                    tuple_arguments: TupleArgumentsFlag,
2313                                    expected: Expectation<'tcx>)
2314                                    -> Ty<'tcx> {
2315         if method_fn_ty.references_error() {
2316             let err_inputs = self.err_args(args_no_rcvr.len());
2317
2318             let err_inputs = match tuple_arguments {
2319                 DontTupleArguments => err_inputs,
2320                 TupleArguments => vec![self.tcx.intern_tup(&err_inputs[..], false)],
2321             };
2322
2323             self.check_argument_types(sp, &err_inputs[..], &[], args_no_rcvr,
2324                                       false, tuple_arguments, None);
2325             self.tcx.types.err
2326         } else {
2327             match method_fn_ty.sty {
2328                 ty::TyFnDef(def_id, .., ref fty) => {
2329                     // HACK(eddyb) ignore self in the definition (see above).
2330                     let expected_arg_tys = self.expected_inputs_for_expected_output(
2331                         sp,
2332                         expected,
2333                         fty.0.output(),
2334                         &fty.0.inputs()[1..]
2335                     );
2336                     self.check_argument_types(sp, &fty.0.inputs()[1..], &expected_arg_tys[..],
2337                                               args_no_rcvr, fty.0.variadic, tuple_arguments,
2338                                               self.tcx.hir.span_if_local(def_id));
2339                     fty.0.output()
2340                 }
2341                 _ => {
2342                     span_bug!(callee_expr.span, "method without bare fn type");
2343                 }
2344             }
2345         }
2346     }
2347
2348     /// Generic function that factors out common logic from function calls,
2349     /// method calls and overloaded operators.
2350     fn check_argument_types(&self,
2351                             sp: Span,
2352                             fn_inputs: &[Ty<'tcx>],
2353                             expected_arg_tys: &[Ty<'tcx>],
2354                             args: &'gcx [hir::Expr],
2355                             variadic: bool,
2356                             tuple_arguments: TupleArgumentsFlag,
2357                             def_span: Option<Span>) {
2358         let tcx = self.tcx;
2359
2360         // Grab the argument types, supplying fresh type variables
2361         // if the wrong number of arguments were supplied
2362         let supplied_arg_count = if tuple_arguments == DontTupleArguments {
2363             args.len()
2364         } else {
2365             1
2366         };
2367
2368         // All the input types from the fn signature must outlive the call
2369         // so as to validate implied bounds.
2370         for &fn_input_ty in fn_inputs {
2371             self.register_wf_obligation(fn_input_ty, sp, traits::MiscObligation);
2372         }
2373
2374         let mut expected_arg_tys = expected_arg_tys;
2375         let expected_arg_count = fn_inputs.len();
2376
2377         let sp_args = if args.len() > 0 {
2378             let (first, args) = args.split_at(1);
2379             let mut sp_tmp = first[0].span;
2380             for arg in args {
2381                 let sp_opt = self.sess().codemap().merge_spans(sp_tmp, arg.span);
2382                 if ! sp_opt.is_some() {
2383                     break;
2384                 }
2385                 sp_tmp = sp_opt.unwrap();
2386             };
2387             sp_tmp
2388         } else {
2389             sp
2390         };
2391
2392         fn parameter_count_error<'tcx>(sess: &Session, sp: Span, expected_count: usize,
2393                                        arg_count: usize, error_code: &str, variadic: bool,
2394                                        def_span: Option<Span>) {
2395             let mut err = sess.struct_span_err_with_code(sp,
2396                 &format!("this function takes {}{} parameter{} but {} parameter{} supplied",
2397                     if variadic {"at least "} else {""},
2398                     expected_count,
2399                     if expected_count == 1 {""} else {"s"},
2400                     arg_count,
2401                     if arg_count == 1 {" was"} else {"s were"}),
2402                 error_code);
2403
2404             err.span_label(sp, format!("expected {}{} parameter{}",
2405                                         if variadic {"at least "} else {""},
2406                                         expected_count,
2407                                         if expected_count == 1 {""} else {"s"}));
2408             if let Some(def_s) = def_span {
2409                 err.span_label(def_s, "defined here");
2410             }
2411             err.emit();
2412         }
2413
2414         let formal_tys = if tuple_arguments == TupleArguments {
2415             let tuple_type = self.structurally_resolved_type(sp, fn_inputs[0]);
2416             match tuple_type.sty {
2417                 ty::TyTuple(arg_types, _) if arg_types.len() != args.len() => {
2418                     parameter_count_error(tcx.sess, sp_args, arg_types.len(), args.len(),
2419                                           "E0057", false, def_span);
2420                     expected_arg_tys = &[];
2421                     self.err_args(args.len())
2422                 }
2423                 ty::TyTuple(arg_types, _) => {
2424                     expected_arg_tys = match expected_arg_tys.get(0) {
2425                         Some(&ty) => match ty.sty {
2426                             ty::TyTuple(ref tys, _) => &tys,
2427                             _ => &[]
2428                         },
2429                         None => &[]
2430                     };
2431                     arg_types.to_vec()
2432                 }
2433                 _ => {
2434                     span_err!(tcx.sess, sp, E0059,
2435                         "cannot use call notation; the first type parameter \
2436                          for the function trait is neither a tuple nor unit");
2437                     expected_arg_tys = &[];
2438                     self.err_args(args.len())
2439                 }
2440             }
2441         } else if expected_arg_count == supplied_arg_count {
2442             fn_inputs.to_vec()
2443         } else if variadic {
2444             if supplied_arg_count >= expected_arg_count {
2445                 fn_inputs.to_vec()
2446             } else {
2447                 parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2448                                       supplied_arg_count, "E0060", true, def_span);
2449                 expected_arg_tys = &[];
2450                 self.err_args(supplied_arg_count)
2451             }
2452         } else {
2453             parameter_count_error(tcx.sess, sp_args, expected_arg_count,
2454                                   supplied_arg_count, "E0061", false, def_span);
2455             expected_arg_tys = &[];
2456             self.err_args(supplied_arg_count)
2457         };
2458
2459         debug!("check_argument_types: formal_tys={:?}",
2460                formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>());
2461
2462         // Check the arguments.
2463         // We do this in a pretty awful way: first we typecheck any arguments
2464         // that are not closures, then we typecheck the closures. This is so
2465         // that we have more information about the types of arguments when we
2466         // typecheck the functions. This isn't really the right way to do this.
2467         for &check_closures in &[false, true] {
2468             debug!("check_closures={}", check_closures);
2469
2470             // More awful hacks: before we check argument types, try to do
2471             // an "opportunistic" vtable resolution of any trait bounds on
2472             // the call. This helps coercions.
2473             if check_closures {
2474                 self.select_obligations_where_possible();
2475             }
2476
2477             // For variadic functions, we don't have a declared type for all of
2478             // the arguments hence we only do our usual type checking with
2479             // the arguments who's types we do know.
2480             let t = if variadic {
2481                 expected_arg_count
2482             } else if tuple_arguments == TupleArguments {
2483                 args.len()
2484             } else {
2485                 supplied_arg_count
2486             };
2487             for (i, arg) in args.iter().take(t).enumerate() {
2488                 // Warn only for the first loop (the "no closures" one).
2489                 // Closure arguments themselves can't be diverging, but
2490                 // a previous argument can, e.g. `foo(panic!(), || {})`.
2491                 if !check_closures {
2492                     self.warn_if_unreachable(arg.id, arg.span, "expression");
2493                 }
2494
2495                 let is_closure = match arg.node {
2496                     hir::ExprClosure(..) => true,
2497                     _ => false
2498                 };
2499
2500                 if is_closure != check_closures {
2501                     continue;
2502                 }
2503
2504                 debug!("checking the argument");
2505                 let formal_ty = formal_tys[i];
2506
2507                 // The special-cased logic below has three functions:
2508                 // 1. Provide as good of an expected type as possible.
2509                 let expected = expected_arg_tys.get(i).map(|&ty| {
2510                     Expectation::rvalue_hint(self, ty)
2511                 });
2512
2513                 let checked_ty = self.check_expr_with_expectation(
2514                     &arg,
2515                     expected.unwrap_or(ExpectHasType(formal_ty)));
2516
2517                 // 2. Coerce to the most detailed type that could be coerced
2518                 //    to, which is `expected_ty` if `rvalue_hint` returns an
2519                 //    `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
2520                 let coerce_ty = expected.and_then(|e| e.only_has_type(self));
2521                 self.demand_coerce(&arg, checked_ty, coerce_ty.unwrap_or(formal_ty));
2522
2523                 // 3. Relate the expected type and the formal one,
2524                 //    if the expected type was used for the coercion.
2525                 coerce_ty.map(|ty| self.demand_suptype(arg.span, formal_ty, ty));
2526             }
2527         }
2528
2529         // We also need to make sure we at least write the ty of the other
2530         // arguments which we skipped above.
2531         if variadic {
2532             for arg in args.iter().skip(expected_arg_count) {
2533                 let arg_ty = self.check_expr(&arg);
2534
2535                 // There are a few types which get autopromoted when passed via varargs
2536                 // in C but we just error out instead and require explicit casts.
2537                 let arg_ty = self.structurally_resolved_type(arg.span,
2538                                                              arg_ty);
2539                 match arg_ty.sty {
2540                     ty::TyFloat(ast::FloatTy::F32) => {
2541                         self.type_error_message(arg.span, |t| {
2542                             format!("can't pass an `{}` to variadic \
2543                                      function, cast to `c_double`", t)
2544                         }, arg_ty);
2545                     }
2546                     ty::TyInt(ast::IntTy::I8) | ty::TyInt(ast::IntTy::I16) | ty::TyBool => {
2547                         self.type_error_message(arg.span, |t| {
2548                             format!("can't pass `{}` to variadic \
2549                                      function, cast to `c_int`",
2550                                            t)
2551                         }, arg_ty);
2552                     }
2553                     ty::TyUint(ast::UintTy::U8) | ty::TyUint(ast::UintTy::U16) => {
2554                         self.type_error_message(arg.span, |t| {
2555                             format!("can't pass `{}` to variadic \
2556                                      function, cast to `c_uint`",
2557                                            t)
2558                         }, arg_ty);
2559                     }
2560                     ty::TyFnDef(.., f) => {
2561                         let ptr_ty = self.tcx.mk_fn_ptr(f);
2562                         let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty);
2563                         self.type_error_message(arg.span,
2564                                                 |t| {
2565                             format!("can't pass `{}` to variadic \
2566                                      function, cast to `{}`", t, ptr_ty)
2567                         }, arg_ty);
2568                     }
2569                     _ => {}
2570                 }
2571             }
2572         }
2573     }
2574
2575     fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
2576         (0..len).map(|_| self.tcx.types.err).collect()
2577     }
2578
2579     // AST fragment checking
2580     fn check_lit(&self,
2581                  lit: &ast::Lit,
2582                  expected: Expectation<'tcx>)
2583                  -> Ty<'tcx>
2584     {
2585         let tcx = self.tcx;
2586
2587         match lit.node {
2588             ast::LitKind::Str(..) => tcx.mk_static_str(),
2589             ast::LitKind::ByteStr(ref v) => {
2590                 tcx.mk_imm_ref(tcx.types.re_static,
2591                                 tcx.mk_array(tcx.types.u8, v.len()))
2592             }
2593             ast::LitKind::Byte(_) => tcx.types.u8,
2594             ast::LitKind::Char(_) => tcx.types.char,
2595             ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(t),
2596             ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(t),
2597             ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
2598                 let opt_ty = expected.to_option(self).and_then(|ty| {
2599                     match ty.sty {
2600                         ty::TyInt(_) | ty::TyUint(_) => Some(ty),
2601                         ty::TyChar => Some(tcx.types.u8),
2602                         ty::TyRawPtr(..) => Some(tcx.types.usize),
2603                         ty::TyFnDef(..) | ty::TyFnPtr(_) => Some(tcx.types.usize),
2604                         _ => None
2605                     }
2606                 });
2607                 opt_ty.unwrap_or_else(
2608                     || tcx.mk_int_var(self.next_int_var_id()))
2609             }
2610             ast::LitKind::Float(_, t) => tcx.mk_mach_float(t),
2611             ast::LitKind::FloatUnsuffixed(_) => {
2612                 let opt_ty = expected.to_option(self).and_then(|ty| {
2613                     match ty.sty {
2614                         ty::TyFloat(_) => Some(ty),
2615                         _ => None
2616                     }
2617                 });
2618                 opt_ty.unwrap_or_else(
2619                     || tcx.mk_float_var(self.next_float_var_id()))
2620             }
2621             ast::LitKind::Bool(_) => tcx.types.bool
2622         }
2623     }
2624
2625     fn check_expr_eq_type(&self,
2626                           expr: &'gcx hir::Expr,
2627                           expected: Ty<'tcx>) {
2628         let ty = self.check_expr_with_hint(expr, expected);
2629         self.demand_eqtype(expr.span, expected, ty);
2630     }
2631
2632     pub fn check_expr_has_type(&self,
2633                                expr: &'gcx hir::Expr,
2634                                expected: Ty<'tcx>) -> Ty<'tcx> {
2635         let mut ty = self.check_expr_with_hint(expr, expected);
2636
2637         // While we don't allow *arbitrary* coercions here, we *do* allow
2638         // coercions from ! to `expected`.
2639         if ty.is_never() {
2640             assert!(!self.tables.borrow().adjustments.contains_key(&expr.id),
2641                     "expression with never type wound up being adjusted");
2642             let adj_ty = self.next_diverging_ty_var(
2643                 TypeVariableOrigin::AdjustmentType(expr.span));
2644             self.apply_adjustment(expr.id, Adjustment {
2645                 kind: Adjust::NeverToAny,
2646                 target: adj_ty
2647             });
2648             ty = adj_ty;
2649         }
2650
2651         self.demand_suptype(expr.span, expected, ty);
2652         ty
2653     }
2654
2655     fn check_expr_coercable_to_type(&self,
2656                                     expr: &'gcx hir::Expr,
2657                                     expected: Ty<'tcx>) -> Ty<'tcx> {
2658         let ty = self.check_expr_with_hint(expr, expected);
2659         self.demand_coerce(expr, ty, expected);
2660         ty
2661     }
2662
2663     fn check_expr_with_hint(&self, expr: &'gcx hir::Expr,
2664                             expected: Ty<'tcx>) -> Ty<'tcx> {
2665         self.check_expr_with_expectation(expr, ExpectHasType(expected))
2666     }
2667
2668     fn check_expr_with_expectation(&self,
2669                                    expr: &'gcx hir::Expr,
2670                                    expected: Expectation<'tcx>) -> Ty<'tcx> {
2671         self.check_expr_with_expectation_and_lvalue_pref(expr, expected, NoPreference)
2672     }
2673
2674     fn check_expr(&self, expr: &'gcx hir::Expr) -> Ty<'tcx> {
2675         self.check_expr_with_expectation(expr, NoExpectation)
2676     }
2677
2678     fn check_expr_with_lvalue_pref(&self, expr: &'gcx hir::Expr,
2679                                    lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2680         self.check_expr_with_expectation_and_lvalue_pref(expr, NoExpectation, lvalue_pref)
2681     }
2682
2683     // determine the `self` type, using fresh variables for all variables
2684     // declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>`
2685     // would return ($0, $1) where $0 and $1 are freshly instantiated type
2686     // variables.
2687     pub fn impl_self_ty(&self,
2688                         span: Span, // (potential) receiver for this impl
2689                         did: DefId)
2690                         -> TypeAndSubsts<'tcx> {
2691         let ity = self.tcx.type_of(did);
2692         debug!("impl_self_ty: ity={:?}", ity);
2693
2694         let substs = self.fresh_substs_for_item(span, did);
2695         let substd_ty = self.instantiate_type_scheme(span, &substs, &ity);
2696
2697         TypeAndSubsts { substs: substs, ty: substd_ty }
2698     }
2699
2700     /// Unifies the output type with the expected type early, for more coercions
2701     /// and forward type information on the input expressions.
2702     fn expected_inputs_for_expected_output(&self,
2703                                            call_span: Span,
2704                                            expected_ret: Expectation<'tcx>,
2705                                            formal_ret: Ty<'tcx>,
2706                                            formal_args: &[Ty<'tcx>])
2707                                            -> Vec<Ty<'tcx>> {
2708         let expected_args = expected_ret.only_has_type(self).and_then(|ret_ty| {
2709             self.fudge_regions_if_ok(&RegionVariableOrigin::Coercion(call_span), || {
2710                 // Attempt to apply a subtyping relationship between the formal
2711                 // return type (likely containing type variables if the function
2712                 // is polymorphic) and the expected return type.
2713                 // No argument expectations are produced if unification fails.
2714                 let origin = self.misc(call_span);
2715                 let ures = self.sub_types(false, &origin, formal_ret, ret_ty);
2716
2717                 // FIXME(#15760) can't use try! here, FromError doesn't default
2718                 // to identity so the resulting type is not constrained.
2719                 match ures {
2720                     Ok(ok) => {
2721                         // Process any obligations locally as much as
2722                         // we can.  We don't care if some things turn
2723                         // out unconstrained or ambiguous, as we're
2724                         // just trying to get hints here.
2725                         let result = self.save_and_restore_in_snapshot_flag(|_| {
2726                             let mut fulfill = FulfillmentContext::new();
2727                             let ok = ok; // FIXME(#30046)
2728                             for obligation in ok.obligations {
2729                                 fulfill.register_predicate_obligation(self, obligation);
2730                             }
2731                             fulfill.select_where_possible(self)
2732                         });
2733
2734                         match result {
2735                             Ok(()) => { }
2736                             Err(_) => return Err(()),
2737                         }
2738                     }
2739                     Err(_) => return Err(()),
2740                 }
2741
2742                 // Record all the argument types, with the substitutions
2743                 // produced from the above subtyping unification.
2744                 Ok(formal_args.iter().map(|ty| {
2745                     self.resolve_type_vars_if_possible(ty)
2746                 }).collect())
2747             }).ok()
2748         }).unwrap_or(vec![]);
2749         debug!("expected_inputs_for_expected_output(formal={:?} -> {:?}, expected={:?} -> {:?})",
2750                formal_args, formal_ret,
2751                expected_args, expected_ret);
2752         expected_args
2753     }
2754
2755     // Checks a method call.
2756     fn check_method_call(&self,
2757                          expr: &'gcx hir::Expr,
2758                          method_name: Spanned<ast::Name>,
2759                          args: &'gcx [hir::Expr],
2760                          tps: &[P<hir::Ty>],
2761                          expected: Expectation<'tcx>,
2762                          lvalue_pref: LvaluePreference) -> Ty<'tcx> {
2763         let rcvr = &args[0];
2764         let rcvr_t = self.check_expr_with_lvalue_pref(&rcvr, lvalue_pref);
2765
2766         // no need to check for bot/err -- callee does that
2767         let expr_t = self.structurally_resolved_type(expr.span, rcvr_t);
2768
2769         let tps = tps.iter().map(|ast_ty| self.to_ty(&ast_ty)).collect::<Vec<_>>();
2770         let fn_ty = match self.lookup_method(method_name.span,
2771                                              method_name.node,
2772                                              expr_t,
2773                                              tps,
2774                                              expr,
2775                                              rcvr) {
2776             Ok(method) => {
2777                 let method_ty = method.ty;
2778                 let method_call = MethodCall::expr(expr.id);
2779                 self.tables.borrow_mut().method_map.insert(method_call, method);
2780                 method_ty
2781             }
2782             Err(error) => {
2783                 if method_name.node != keywords::Invalid.name() {
2784                     self.report_method_error(method_name.span,
2785                                              expr_t,
2786                                              method_name.node,
2787                                              Some(rcvr),
2788                                              error,
2789                                              Some(args));
2790                 }
2791                 self.write_error(expr.id);
2792                 self.tcx.types.err
2793             }
2794         };
2795
2796         // Call the generic checker.
2797         let ret_ty = self.check_method_argument_types(method_name.span, fn_ty,
2798                                                       expr, &args[1..],
2799                                                       DontTupleArguments,
2800                                                       expected);
2801
2802         ret_ty
2803     }
2804
2805     fn check_return_expr(&self, return_expr: &'gcx hir::Expr) {
2806         let ret_coercion =
2807             self.ret_coercion
2808                 .as_ref()
2809                 .unwrap_or_else(|| span_bug!(return_expr.span,
2810                                              "check_return_expr called outside fn body"));
2811
2812         let ret_ty = ret_coercion.borrow().expected_ty();
2813         let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
2814         ret_coercion.borrow_mut()
2815                     .coerce(self,
2816                             &self.misc(return_expr.span),
2817                             return_expr,
2818                             return_expr_ty,
2819                             self.diverges.get());
2820     }
2821
2822
2823     // A generic function for checking the then and else in an if
2824     // or if-else.
2825     fn check_then_else(&self,
2826                        cond_expr: &'gcx hir::Expr,
2827                        then_expr: &'gcx hir::Expr,
2828                        opt_else_expr: Option<&'gcx hir::Expr>,
2829                        sp: Span,
2830                        expected: Expectation<'tcx>) -> Ty<'tcx> {
2831         let cond_ty = self.check_expr_has_type(cond_expr, self.tcx.types.bool);
2832         let cond_diverges = self.diverges.get();
2833         self.diverges.set(Diverges::Maybe);
2834
2835         let expected = expected.adjust_for_branches(self);
2836         let then_ty = self.check_expr_with_expectation(then_expr, expected);
2837         let then_diverges = self.diverges.get();
2838         self.diverges.set(Diverges::Maybe);
2839
2840         // We've already taken the expected type's preferences
2841         // into account when typing the `then` branch. To figure
2842         // out the initial shot at a LUB, we thus only consider
2843         // `expected` if it represents a *hard* constraint
2844         // (`only_has_type`); otherwise, we just go with a
2845         // fresh type variable.
2846         let coerce_to_ty = expected.coercion_target_type(self, sp);
2847         let mut coerce: DynamicCoerceMany = CoerceMany::new(coerce_to_ty);
2848
2849         let if_cause = self.cause(sp, ObligationCauseCode::IfExpression);
2850         coerce.coerce(self, &if_cause, then_expr, then_ty, then_diverges);
2851
2852         if let Some(else_expr) = opt_else_expr {
2853             let else_ty = self.check_expr_with_expectation(else_expr, expected);
2854             let else_diverges = self.diverges.get();
2855
2856             coerce.coerce(self, &if_cause, else_expr, else_ty, else_diverges);
2857
2858             // We won't diverge unless both branches do (or the condition does).
2859             self.diverges.set(cond_diverges | then_diverges & else_diverges);
2860         } else {
2861             let else_cause = self.cause(sp, ObligationCauseCode::IfExpressionWithNoElse);
2862             coerce.coerce_forced_unit(self, &else_cause, &mut |_| (), true);
2863
2864             // If the condition is false we can't diverge.
2865             self.diverges.set(cond_diverges);
2866         }
2867
2868         let result_ty = coerce.complete(self);
2869         if cond_ty.references_error() {
2870             self.tcx.types.err
2871         } else {
2872             result_ty
2873         }
2874     }
2875
2876     // Check field access expressions
2877     fn check_field(&self,
2878                    expr: &'gcx hir::Expr,
2879                    lvalue_pref: LvaluePreference,
2880                    base: &'gcx hir::Expr,
2881                    field: &Spanned<ast::Name>) -> Ty<'tcx> {
2882         let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
2883         let expr_t = self.structurally_resolved_type(expr.span,
2884                                                      expr_t);
2885         let mut private_candidate = None;
2886         let mut autoderef = self.autoderef(expr.span, expr_t);
2887         while let Some((base_t, autoderefs)) = autoderef.next() {
2888             match base_t.sty {
2889                 ty::TyAdt(base_def, substs) if !base_def.is_enum() => {
2890                     debug!("struct named {:?}",  base_t);
2891                     if let Some(field) = base_def.struct_variant().find_field_named(field.node) {
2892                         let field_ty = self.field_ty(expr.span, field, substs);
2893                         if self.tcx.vis_is_accessible_from(field.vis, self.body_id) {
2894                             autoderef.finalize(lvalue_pref, base);
2895                             self.apply_autoderef_adjustment(base.id, autoderefs, base_t);
2896
2897                             self.tcx.check_stability(field.did, expr.id, expr.span);
2898
2899                             return field_ty;
2900                         }
2901                         private_candidate = Some((base_def.did, field_ty));
2902                     }
2903                 }
2904                 _ => {}
2905             }
2906         }
2907         autoderef.unambiguous_final_ty();
2908
2909         if let Some((did, field_ty)) = private_candidate {
2910             let struct_path = self.tcx().item_path_str(did);
2911             let msg = format!("field `{}` of struct `{}` is private", field.node, struct_path);
2912             let mut err = self.tcx().sess.struct_span_err(expr.span, &msg);
2913             // Also check if an accessible method exists, which is often what is meant.
2914             if self.method_exists(field.span, field.node, expr_t, expr.id, false) {
2915                 err.note(&format!("a method `{}` also exists, perhaps you wish to call it",
2916                                   field.node));
2917             }
2918             err.emit();
2919             field_ty
2920         } else if field.node == keywords::Invalid.name() {
2921             self.tcx().types.err
2922         } else if self.method_exists(field.span, field.node, expr_t, expr.id, true) {
2923             self.type_error_struct(field.span, |actual| {
2924                 format!("attempted to take value of method `{}` on type \
2925                          `{}`", field.node, actual)
2926             }, expr_t)
2927                 .help("maybe a `()` to call it is missing? \
2928                        If not, try an anonymous function")
2929                 .emit();
2930             self.tcx().types.err
2931         } else {
2932             let mut err = self.type_error_struct(field.span, |actual| {
2933                 format!("no field `{}` on type `{}`",
2934                         field.node, actual)
2935             }, expr_t);
2936             match expr_t.sty {
2937                 ty::TyAdt(def, _) if !def.is_enum() => {
2938                     if let Some(suggested_field_name) =
2939                         Self::suggest_field_name(def.struct_variant(), field, vec![]) {
2940                             err.span_label(field.span,
2941                                            format!("did you mean `{}`?", suggested_field_name));
2942                         } else {
2943                             err.span_label(field.span,
2944                                            "unknown field");
2945                         };
2946                 }
2947                 ty::TyRawPtr(..) => {
2948                     err.note(&format!("`{0}` is a native pointer; perhaps you need to deref with \
2949                                       `(*{0}).{1}`",
2950                                       self.tcx.hir.node_to_pretty_string(base.id),
2951                                       field.node));
2952                 }
2953                 _ => {}
2954             }
2955             err.emit();
2956             self.tcx().types.err
2957         }
2958     }
2959
2960     // Return an hint about the closest match in field names
2961     fn suggest_field_name(variant: &'tcx ty::VariantDef,
2962                           field: &Spanned<ast::Name>,
2963                           skip : Vec<InternedString>)
2964                           -> Option<Symbol> {
2965         let name = field.node.as_str();
2966         let names = variant.fields.iter().filter_map(|field| {
2967             // ignore already set fields and private fields from non-local crates
2968             if skip.iter().any(|x| *x == field.name.as_str()) ||
2969                (variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
2970                 None
2971             } else {
2972                 Some(&field.name)
2973             }
2974         });
2975
2976         // only find fits with at least one matching letter
2977         find_best_match_for_name(names, &name, Some(name.len()))
2978     }
2979
2980     // Check tuple index expressions
2981     fn check_tup_field(&self,
2982                        expr: &'gcx hir::Expr,
2983                        lvalue_pref: LvaluePreference,
2984                        base: &'gcx hir::Expr,
2985                        idx: codemap::Spanned<usize>) -> Ty<'tcx> {
2986         let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
2987         let expr_t = self.structurally_resolved_type(expr.span,
2988                                                      expr_t);
2989         let mut private_candidate = None;
2990         let mut tuple_like = false;
2991         let mut autoderef = self.autoderef(expr.span, expr_t);
2992         while let Some((base_t, autoderefs)) = autoderef.next() {
2993             let field = match base_t.sty {
2994                 ty::TyAdt(base_def, substs) if base_def.is_struct() => {
2995                     tuple_like = base_def.struct_variant().ctor_kind == CtorKind::Fn;
2996                     if !tuple_like { continue }
2997
2998                     debug!("tuple struct named {:?}",  base_t);
2999                     base_def.struct_variant().fields.get(idx.node).and_then(|field| {
3000                         let field_ty = self.field_ty(expr.span, field, substs);
3001                         private_candidate = Some((base_def.did, field_ty));
3002                         if self.tcx.vis_is_accessible_from(field.vis, self.body_id) {
3003                             self.tcx.check_stability(field.did, expr.id, expr.span);
3004                             Some(field_ty)
3005                         } else {
3006                             None
3007                         }
3008                     })
3009                 }
3010                 ty::TyTuple(ref v, _) => {
3011                     tuple_like = true;
3012                     v.get(idx.node).cloned()
3013                 }
3014                 _ => continue
3015             };
3016
3017             if let Some(field_ty) = field {
3018                 autoderef.finalize(lvalue_pref, base);
3019                 self.apply_autoderef_adjustment(base.id, autoderefs, base_t);
3020                 return field_ty;
3021             }
3022         }
3023         autoderef.unambiguous_final_ty();
3024
3025         if let Some((did, field_ty)) = private_candidate {
3026             let struct_path = self.tcx().item_path_str(did);
3027             let msg = format!("field `{}` of struct `{}` is private", idx.node, struct_path);
3028             self.tcx().sess.span_err(expr.span, &msg);
3029             return field_ty;
3030         }
3031
3032         self.type_error_message(
3033             expr.span,
3034             |actual| {
3035                 if tuple_like {
3036                     format!("attempted out-of-bounds tuple index `{}` on \
3037                                     type `{}`",
3038                                    idx.node,
3039                                    actual)
3040                 } else {
3041                     format!("attempted tuple index `{}` on type `{}`, but the \
3042                                      type was not a tuple or tuple struct",
3043                                     idx.node,
3044                                     actual)
3045                 }
3046             },
3047             expr_t);
3048
3049         self.tcx().types.err
3050     }
3051
3052     fn report_unknown_field(&self,
3053                             ty: Ty<'tcx>,
3054                             variant: &'tcx ty::VariantDef,
3055                             field: &hir::Field,
3056                             skip_fields: &[hir::Field],
3057                             kind_name: &str) {
3058         let mut err = self.type_error_struct_with_diag(
3059             field.name.span,
3060             |actual| match ty.sty {
3061                 ty::TyAdt(adt, ..) if adt.is_enum() => {
3062                     struct_span_err!(self.tcx.sess, field.name.span, E0559,
3063                                     "{} `{}::{}` has no field named `{}`",
3064                                     kind_name, actual, variant.name, field.name.node)
3065                 }
3066                 _ => {
3067                     struct_span_err!(self.tcx.sess, field.name.span, E0560,
3068                                     "{} `{}` has no field named `{}`",
3069                                     kind_name, actual, field.name.node)
3070                 }
3071             },
3072             ty);
3073         // prevent all specified fields from being suggested
3074         let skip_fields = skip_fields.iter().map(|ref x| x.name.node.as_str());
3075         if let Some(field_name) = Self::suggest_field_name(variant,
3076                                                            &field.name,
3077                                                            skip_fields.collect()) {
3078             err.span_label(field.name.span,
3079                            format!("field does not exist - did you mean `{}`?", field_name));
3080         } else {
3081             match ty.sty {
3082                 ty::TyAdt(adt, ..) if adt.is_enum() => {
3083                     err.span_label(field.name.span, format!("`{}::{}` does not have this field",
3084                                                              ty, variant.name));
3085                 }
3086                 _ => {
3087                     err.span_label(field.name.span, format!("`{}` does not have this field", ty));
3088                 }
3089             }
3090         };
3091         err.emit();
3092     }
3093
3094     fn check_expr_struct_fields(&self,
3095                                 adt_ty: Ty<'tcx>,
3096                                 expected: Expectation<'tcx>,
3097                                 expr_id: ast::NodeId,
3098                                 span: Span,
3099                                 variant: &'tcx ty::VariantDef,
3100                                 ast_fields: &'gcx [hir::Field],
3101                                 check_completeness: bool) {
3102         let tcx = self.tcx;
3103
3104         let adt_ty_hint =
3105             self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
3106                 .get(0).cloned().unwrap_or(adt_ty);
3107
3108         let (substs, hint_substs, adt_kind, kind_name) = match (&adt_ty.sty, &adt_ty_hint.sty) {
3109             (&ty::TyAdt(adt, substs), &ty::TyAdt(_, hint_substs)) => {
3110                 (substs, hint_substs, adt.adt_kind(), adt.variant_descr())
3111             }
3112             _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
3113         };
3114
3115         let mut remaining_fields = FxHashMap();
3116         for field in &variant.fields {
3117             remaining_fields.insert(field.name, field);
3118         }
3119
3120         let mut seen_fields = FxHashMap();
3121
3122         let mut error_happened = false;
3123
3124         // Typecheck each field.
3125         for field in ast_fields {
3126             let final_field_type;
3127             let field_type_hint;
3128
3129             if let Some(v_field) = remaining_fields.remove(&field.name.node) {
3130                 final_field_type = self.field_ty(field.span, v_field, substs);
3131                 field_type_hint = self.field_ty(field.span, v_field, hint_substs);
3132
3133                 seen_fields.insert(field.name.node, field.span);
3134
3135                 // we don't look at stability attributes on
3136                 // struct-like enums (yet...), but it's definitely not
3137                 // a bug to have construct one.
3138                 if adt_kind != ty::AdtKind::Enum {
3139                     tcx.check_stability(v_field.did, expr_id, field.span);
3140                 }
3141             } else {
3142                 error_happened = true;
3143                 final_field_type = tcx.types.err;
3144                 field_type_hint = tcx.types.err;
3145                 if let Some(_) = variant.find_field_named(field.name.node) {
3146                     let mut err = struct_span_err!(self.tcx.sess,
3147                                                 field.name.span,
3148                                                 E0062,
3149                                                 "field `{}` specified more than once",
3150                                                 field.name.node);
3151
3152                     err.span_label(field.name.span, "used more than once");
3153
3154                     if let Some(prev_span) = seen_fields.get(&field.name.node) {
3155                         err.span_label(*prev_span, format!("first use of `{}`", field.name.node));
3156                     }
3157
3158                     err.emit();
3159                 } else {
3160                     self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name);
3161                 }
3162             }
3163
3164             // Make sure to give a type to the field even if there's
3165             // an error, so we can continue typechecking
3166             let ty = self.check_expr_with_hint(&field.expr, field_type_hint);
3167             self.demand_coerce(&field.expr, ty, final_field_type);
3168         }
3169
3170         // Make sure the programmer specified correct number of fields.
3171         if kind_name == "union" {
3172             if ast_fields.len() != 1 {
3173                 tcx.sess.span_err(span, "union expressions should have exactly one field");
3174             }
3175         } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
3176             let len = remaining_fields.len();
3177
3178             let mut displayable_field_names = remaining_fields
3179                                               .keys()
3180                                               .map(|x| x.as_str())
3181                                               .collect::<Vec<_>>();
3182
3183             displayable_field_names.sort();
3184
3185             let truncated_fields_error = if len <= 3 {
3186                 "".to_string()
3187             } else {
3188                 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
3189             };
3190
3191             let remaining_fields_names = displayable_field_names.iter().take(3)
3192                                         .map(|n| format!("`{}`", n))
3193                                         .collect::<Vec<_>>()
3194                                         .join(", ");
3195
3196             struct_span_err!(tcx.sess, span, E0063,
3197                         "missing field{} {}{} in initializer of `{}`",
3198                         if remaining_fields.len() == 1 {""} else {"s"},
3199                         remaining_fields_names,
3200                         truncated_fields_error,
3201                         adt_ty)
3202                         .span_label(span, format!("missing {}{}",
3203                             remaining_fields_names,
3204                             truncated_fields_error))
3205                         .emit();
3206         }
3207     }
3208
3209     fn check_struct_fields_on_error(&self,
3210                                     fields: &'gcx [hir::Field],
3211                                     base_expr: &'gcx Option<P<hir::Expr>>) {
3212         for field in fields {
3213             self.check_expr(&field.expr);
3214         }
3215         match *base_expr {
3216             Some(ref base) => {
3217                 self.check_expr(&base);
3218             },
3219             None => {}
3220         }
3221     }
3222
3223     pub fn check_struct_path(&self,
3224                              qpath: &hir::QPath,
3225                              node_id: ast::NodeId)
3226                              -> Option<(&'tcx ty::VariantDef,  Ty<'tcx>)> {
3227         let path_span = match *qpath {
3228             hir::QPath::Resolved(_, ref path) => path.span,
3229             hir::QPath::TypeRelative(ref qself, _) => qself.span
3230         };
3231         let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, node_id);
3232         let variant = match def {
3233             Def::Err => {
3234                 self.set_tainted_by_errors();
3235                 return None;
3236             }
3237             Def::Variant(..) => {
3238                 match ty.sty {
3239                     ty::TyAdt(adt, substs) => {
3240                         Some((adt.variant_of_def(def), adt.did, substs))
3241                     }
3242                     _ => bug!("unexpected type: {:?}", ty.sty)
3243                 }
3244             }
3245             Def::Struct(..) | Def::Union(..) | Def::TyAlias(..) |
3246             Def::AssociatedTy(..) | Def::SelfTy(..) => {
3247                 match ty.sty {
3248                     ty::TyAdt(adt, substs) if !adt.is_enum() => {
3249                         Some((adt.struct_variant(), adt.did, substs))
3250                     }
3251                     _ => None,
3252                 }
3253             }
3254             _ => bug!("unexpected definition: {:?}", def)
3255         };
3256
3257         if let Some((variant, did, substs)) = variant {
3258             // Check bounds on type arguments used in the path.
3259             let bounds = self.instantiate_bounds(path_span, did, substs);
3260             let cause = traits::ObligationCause::new(path_span, self.body_id,
3261                                                      traits::ItemObligation(did));
3262             self.add_obligations_for_parameters(cause, &bounds);
3263
3264             Some((variant, ty))
3265         } else {
3266             struct_span_err!(self.tcx.sess, path_span, E0071,
3267                              "expected struct, variant or union type, found {}",
3268                              ty.sort_string(self.tcx))
3269                 .span_label(path_span, "not a struct")
3270                 .emit();
3271             None
3272         }
3273     }
3274
3275     fn check_expr_struct(&self,
3276                          expr: &hir::Expr,
3277                          expected: Expectation<'tcx>,
3278                          qpath: &hir::QPath,
3279                          fields: &'gcx [hir::Field],
3280                          base_expr: &'gcx Option<P<hir::Expr>>) -> Ty<'tcx>
3281     {
3282         // Find the relevant variant
3283         let (variant, struct_ty) =
3284         if let Some(variant_ty) = self.check_struct_path(qpath, expr.id) {
3285             variant_ty
3286         } else {
3287             self.check_struct_fields_on_error(fields, base_expr);
3288             return self.tcx.types.err;
3289         };
3290
3291         let path_span = match *qpath {
3292             hir::QPath::Resolved(_, ref path) => path.span,
3293             hir::QPath::TypeRelative(ref qself, _) => qself.span
3294         };
3295
3296         self.check_expr_struct_fields(struct_ty, expected, expr.id, path_span, variant, fields,
3297                                       base_expr.is_none());
3298         if let &Some(ref base_expr) = base_expr {
3299             self.check_expr_has_type(base_expr, struct_ty);
3300             match struct_ty.sty {
3301                 ty::TyAdt(adt, substs) if adt.is_struct() => {
3302                     self.tables.borrow_mut().fru_field_types.insert(
3303                         expr.id,
3304                         adt.struct_variant().fields.iter().map(|f| {
3305                             self.normalize_associated_types_in(
3306                                 expr.span, &f.ty(self.tcx, substs)
3307                             )
3308                         }).collect()
3309                     );
3310                 }
3311                 _ => {
3312                     span_err!(self.tcx.sess, base_expr.span, E0436,
3313                               "functional record update syntax requires a struct");
3314                 }
3315             }
3316         }
3317         self.require_type_is_sized(struct_ty, expr.span, traits::StructInitializerSized);
3318         struct_ty
3319     }
3320
3321
3322     /// Invariant:
3323     /// If an expression has any sub-expressions that result in a type error,
3324     /// inspecting that expression's type with `ty.references_error()` will return
3325     /// true. Likewise, if an expression is known to diverge, inspecting its
3326     /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
3327     /// strict, _|_ can appear in the type of an expression that does not,
3328     /// itself, diverge: for example, fn() -> _|_.)
3329     /// Note that inspecting a type's structure *directly* may expose the fact
3330     /// that there are actually multiple representations for `TyError`, so avoid
3331     /// that when err needs to be handled differently.
3332     fn check_expr_with_expectation_and_lvalue_pref(&self,
3333                                                    expr: &'gcx hir::Expr,
3334                                                    expected: Expectation<'tcx>,
3335                                                    lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3336         debug!(">> typechecking: expr={:?} expected={:?}",
3337                expr, expected);
3338
3339         // Warn for expressions after diverging siblings.
3340         self.warn_if_unreachable(expr.id, expr.span, "expression");
3341
3342         // Hide the outer diverging and has_errors flags.
3343         let old_diverges = self.diverges.get();
3344         let old_has_errors = self.has_errors.get();
3345         self.diverges.set(Diverges::Maybe);
3346         self.has_errors.set(false);
3347
3348         let ty = self.check_expr_kind(expr, expected, lvalue_pref);
3349
3350         // Warn for non-block expressions with diverging children.
3351         match expr.node {
3352             hir::ExprBlock(_) |
3353             hir::ExprLoop(..) | hir::ExprWhile(..) |
3354             hir::ExprIf(..) | hir::ExprMatch(..) => {}
3355
3356             _ => self.warn_if_unreachable(expr.id, expr.span, "expression")
3357         }
3358
3359         // Any expression that produces a value of type `!` must have diverged
3360         if ty.is_never() {
3361             self.diverges.set(self.diverges.get() | Diverges::Always);
3362         }
3363
3364         // Record the type, which applies it effects.
3365         // We need to do this after the warning above, so that
3366         // we don't warn for the diverging expression itself.
3367         self.write_ty(expr.id, ty);
3368
3369         // Combine the diverging and has_error flags.
3370         self.diverges.set(self.diverges.get() | old_diverges);
3371         self.has_errors.set(self.has_errors.get() | old_has_errors);
3372
3373         debug!("type of {} is...", self.tcx.hir.node_to_string(expr.id));
3374         debug!("... {:?}, expected is {:?}", ty, expected);
3375
3376         ty
3377     }
3378
3379     fn check_expr_kind(&self,
3380                        expr: &'gcx hir::Expr,
3381                        expected: Expectation<'tcx>,
3382                        lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3383         let tcx = self.tcx;
3384         let id = expr.id;
3385         match expr.node {
3386           hir::ExprBox(ref subexpr) => {
3387             let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
3388                 match ty.sty {
3389                     ty::TyAdt(def, _) if def.is_box()
3390                         => Expectation::rvalue_hint(self, ty.boxed_ty()),
3391                     _ => NoExpectation
3392                 }
3393             });
3394             let referent_ty = self.check_expr_with_expectation(subexpr, expected_inner);
3395             tcx.mk_box(referent_ty)
3396           }
3397
3398           hir::ExprLit(ref lit) => {
3399             self.check_lit(&lit, expected)
3400           }
3401           hir::ExprBinary(op, ref lhs, ref rhs) => {
3402             self.check_binop(expr, op, lhs, rhs)
3403           }
3404           hir::ExprAssignOp(op, ref lhs, ref rhs) => {
3405             self.check_binop_assign(expr, op, lhs, rhs)
3406           }
3407           hir::ExprUnary(unop, ref oprnd) => {
3408             let expected_inner = match unop {
3409                 hir::UnNot | hir::UnNeg => {
3410                     expected
3411                 }
3412                 hir::UnDeref => {
3413                     NoExpectation
3414                 }
3415             };
3416             let lvalue_pref = match unop {
3417                 hir::UnDeref => lvalue_pref,
3418                 _ => NoPreference
3419             };
3420             let mut oprnd_t = self.check_expr_with_expectation_and_lvalue_pref(&oprnd,
3421                                                                                expected_inner,
3422                                                                                lvalue_pref);
3423
3424             if !oprnd_t.references_error() {
3425                 match unop {
3426                     hir::UnDeref => {
3427                         oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
3428
3429                         if let Some(mt) = oprnd_t.builtin_deref(true, NoPreference) {
3430                             oprnd_t = mt.ty;
3431                         } else if let Some(ok) = self.try_overloaded_deref(
3432                                 expr.span, Some(&oprnd), oprnd_t, lvalue_pref) {
3433                             let method = self.register_infer_ok_obligations(ok);
3434                             oprnd_t = self.make_overloaded_lvalue_return_type(method).ty;
3435                             self.tables.borrow_mut().method_map.insert(MethodCall::expr(expr.id),
3436                                                                            method);
3437                         } else {
3438                             self.type_error_message(expr.span, |actual| {
3439                                 format!("type `{}` cannot be \
3440                                         dereferenced", actual)
3441                             }, oprnd_t);
3442                             oprnd_t = tcx.types.err;
3443                         }
3444                     }
3445                     hir::UnNot => {
3446                         oprnd_t = self.structurally_resolved_type(oprnd.span,
3447                                                                   oprnd_t);
3448                         let result = self.check_user_unop("!", "not",
3449                                                           tcx.lang_items.not_trait(),
3450                                                           expr, &oprnd, oprnd_t, unop);
3451                         // If it's builtin, we can reuse the type, this helps inference.
3452                         if !(oprnd_t.is_integral() || oprnd_t.sty == ty::TyBool) {
3453                             oprnd_t = result;
3454                         }
3455                     }
3456                     hir::UnNeg => {
3457                         oprnd_t = self.structurally_resolved_type(oprnd.span,
3458                                                                   oprnd_t);
3459                         let result = self.check_user_unop("-", "neg",
3460                                                           tcx.lang_items.neg_trait(),
3461                                                           expr, &oprnd, oprnd_t, unop);
3462                         // If it's builtin, we can reuse the type, this helps inference.
3463                         if !(oprnd_t.is_integral() || oprnd_t.is_fp()) {
3464                             oprnd_t = result;
3465                         }
3466                     }
3467                 }
3468             }
3469             oprnd_t
3470           }
3471           hir::ExprAddrOf(mutbl, ref oprnd) => {
3472             let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
3473                 match ty.sty {
3474                     ty::TyRef(_, ref mt) | ty::TyRawPtr(ref mt) => {
3475                         if self.tcx.expr_is_lval(&oprnd) {
3476                             // Lvalues may legitimately have unsized types.
3477                             // For example, dereferences of a fat pointer and
3478                             // the last field of a struct can be unsized.
3479                             ExpectHasType(mt.ty)
3480                         } else {
3481                             Expectation::rvalue_hint(self, mt.ty)
3482                         }
3483                     }
3484                     _ => NoExpectation
3485                 }
3486             });
3487             let lvalue_pref = LvaluePreference::from_mutbl(mutbl);
3488             let ty = self.check_expr_with_expectation_and_lvalue_pref(&oprnd, hint, lvalue_pref);
3489
3490             let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
3491             if tm.ty.references_error() {
3492                 tcx.types.err
3493             } else {
3494                 // Note: at this point, we cannot say what the best lifetime
3495                 // is to use for resulting pointer.  We want to use the
3496                 // shortest lifetime possible so as to avoid spurious borrowck
3497                 // errors.  Moreover, the longest lifetime will depend on the
3498                 // precise details of the value whose address is being taken
3499                 // (and how long it is valid), which we don't know yet until type
3500                 // inference is complete.
3501                 //
3502                 // Therefore, here we simply generate a region variable.  The
3503                 // region inferencer will then select the ultimate value.
3504                 // Finally, borrowck is charged with guaranteeing that the
3505                 // value whose address was taken can actually be made to live
3506                 // as long as it needs to live.
3507                 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
3508                 tcx.mk_ref(region, tm)
3509             }
3510           }
3511           hir::ExprPath(ref qpath) => {
3512               let (def, opt_ty, segments) = self.resolve_ty_and_def_ufcs(qpath,
3513                                                                          expr.id, expr.span);
3514               let ty = if def != Def::Err {
3515                   self.instantiate_value_path(segments, opt_ty, def, expr.span, id)
3516               } else {
3517                   self.set_tainted_by_errors();
3518                   tcx.types.err
3519               };
3520
3521               // We always require that the type provided as the value for
3522               // a type parameter outlives the moment of instantiation.
3523               self.opt_node_ty_substs(expr.id, |item_substs| {
3524                   self.add_wf_bounds(&item_substs.substs, expr);
3525               });
3526
3527               ty
3528           }
3529           hir::ExprInlineAsm(_, ref outputs, ref inputs) => {
3530               for output in outputs {
3531                   self.check_expr(output);
3532               }
3533               for input in inputs {
3534                   self.check_expr(input);
3535               }
3536               tcx.mk_nil()
3537           }
3538           hir::ExprBreak(destination, ref expr_opt) => {
3539               if let Some(target_id) = destination.target_id.opt_id() {
3540                   let (e_ty, e_diverges, cause);
3541                   if let Some(ref e) = *expr_opt {
3542                       // If this is a break with a value, we need to type-check
3543                       // the expression. Get an expected type from the loop context.
3544                       let opt_coerce_to = {
3545                           let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3546                           enclosing_breakables.find_breakable(target_id)
3547                                               .coerce
3548                                               .as_ref()
3549                                               .map(|coerce| coerce.expected_ty())
3550                       };
3551
3552                       // If the loop context is not a `loop { }`, then break with
3553                       // a value is illegal, and `opt_coerce_to` will be `None`.
3554                       // Just set expectation to error in that case.
3555                       let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
3556
3557                       // Recurse without `enclosing_breakables` borrowed.
3558                       e_ty = self.check_expr_with_hint(e, coerce_to);
3559                       e_diverges = self.diverges.get();
3560                       cause = self.misc(e.span);
3561                   } else {
3562                       // Otherwise, this is a break *without* a value. That's
3563                       // always legal, and is equivalent to `break ()`.
3564                       e_ty = tcx.mk_nil();
3565                       e_diverges = Diverges::Maybe;
3566                       cause = self.misc(expr.span);
3567                   }
3568
3569                   // Now that we have type-checked `expr_opt`, borrow
3570                   // the `enclosing_loops` field and let's coerce the
3571                   // type of `expr_opt` into what is expected.
3572                   let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3573                   let ctxt = enclosing_breakables.find_breakable(target_id);
3574                   if let Some(ref mut coerce) = ctxt.coerce {
3575                       if let Some(ref e) = *expr_opt {
3576                           coerce.coerce(self, &cause, e, e_ty, e_diverges);
3577                       } else {
3578                           assert!(e_ty.is_nil());
3579                           coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
3580                       }
3581                   } else {
3582                       // If `ctxt.coerce` is `None`, we can just ignore
3583                       // the type of the expresison.  This is because
3584                       // either this was a break *without* a value, in
3585                       // which case it is always a legal type (`()`), or
3586                       // else an error would have been flagged by the
3587                       // `loops` pass for using break with an expression
3588                       // where you are not supposed to.
3589                       assert!(expr_opt.is_none() || self.tcx.sess.err_count() > 0);
3590                   }
3591
3592                   ctxt.may_break = true;
3593               } else {
3594                   // Otherwise, we failed to find the enclosing loop;
3595                   // this can only happen if the `break` was not
3596                   // inside a loop at all, which is caught by the
3597                   // loop-checking pass.
3598                   assert!(self.tcx.sess.err_count() > 0);
3599               }
3600
3601               // the type of a `break` is always `!`, since it diverges
3602               tcx.types.never
3603           }
3604           hir::ExprAgain(_) => { tcx.types.never }
3605           hir::ExprRet(ref expr_opt) => {
3606             if self.ret_coercion.is_none() {
3607                 struct_span_err!(self.tcx.sess, expr.span, E0572,
3608                                  "return statement outside of function body").emit();
3609             } else if let Some(ref e) = *expr_opt {
3610                 self.check_return_expr(e);
3611             } else {
3612                 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
3613                 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
3614                 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
3615             }
3616             tcx.types.never
3617           }
3618           hir::ExprAssign(ref lhs, ref rhs) => {
3619             let lhs_ty = self.check_expr_with_lvalue_pref(&lhs, PreferMutLvalue);
3620
3621             let tcx = self.tcx;
3622             if !tcx.expr_is_lval(&lhs) {
3623                 struct_span_err!(
3624                     tcx.sess, expr.span, E0070,
3625                     "invalid left-hand side expression")
3626                 .span_label(
3627                     expr.span,
3628                     "left-hand of expression not valid")
3629                 .emit();
3630             }
3631
3632             let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
3633
3634             self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
3635
3636             if lhs_ty.references_error() || rhs_ty.references_error() {
3637                 tcx.types.err
3638             } else {
3639                 tcx.mk_nil()
3640             }
3641           }
3642           hir::ExprIf(ref cond, ref then_expr, ref opt_else_expr) => {
3643               self.check_then_else(&cond, then_expr, opt_else_expr.as_ref().map(|e| &**e),
3644                                    expr.span, expected)
3645           }
3646           hir::ExprWhile(ref cond, ref body, _) => {
3647               let ctxt = BreakableCtxt {
3648                   // cannot use break with a value from a while loop
3649                   coerce: None,
3650                   may_break: true,
3651               };
3652
3653               self.with_breakable_ctxt(expr.id, ctxt, || {
3654                   self.check_expr_has_type(&cond, tcx.types.bool);
3655                   let cond_diverging = self.diverges.get();
3656                   self.check_block_no_value(&body);
3657
3658                   // We may never reach the body so it diverging means nothing.
3659                   self.diverges.set(cond_diverging);
3660               });
3661
3662               self.tcx.mk_nil()
3663           }
3664           hir::ExprLoop(ref body, _, source) => {
3665               let coerce = match source {
3666                   // you can only use break with a value from a normal `loop { }`
3667                   hir::LoopSource::Loop => {
3668                       let coerce_to = expected.coercion_target_type(self, body.span);
3669                       Some(CoerceMany::new(coerce_to))
3670                   }
3671
3672                   hir::LoopSource::WhileLet |
3673                   hir::LoopSource::ForLoop => {
3674                       None
3675                   }
3676               };
3677
3678               let ctxt = BreakableCtxt {
3679                   coerce: coerce,
3680                   may_break: false, // will get updated if/when we find a `break`
3681               };
3682
3683               let (ctxt, ()) = self.with_breakable_ctxt(expr.id, ctxt, || {
3684                   self.check_block_no_value(&body);
3685               });
3686
3687               if ctxt.may_break {
3688                   // No way to know whether it's diverging because
3689                   // of a `break` or an outer `break` or `return.
3690                   self.diverges.set(Diverges::Maybe);
3691               }
3692
3693               // If we permit break with a value, then result type is
3694               // the LUB of the breaks (possibly ! if none); else, it
3695               // is nil. This makes sense because infinite loops
3696               // (which would have type !) are only possible iff we
3697               // permit break with a value [1].
3698               assert!(ctxt.coerce.is_some() || ctxt.may_break); // [1]
3699               ctxt.coerce.map(|c| c.complete(self)).unwrap_or(self.tcx.mk_nil())
3700           }
3701           hir::ExprMatch(ref discrim, ref arms, match_src) => {
3702             self.check_match(expr, &discrim, arms, expected, match_src)
3703           }
3704           hir::ExprClosure(capture, ref decl, body_id, _) => {
3705               self.check_expr_closure(expr, capture, &decl, body_id, expected)
3706           }
3707           hir::ExprBlock(ref body) => {
3708             self.check_block_with_expected(&body, expected)
3709           }
3710           hir::ExprCall(ref callee, ref args) => {
3711               self.check_call(expr, &callee, args, expected)
3712           }
3713           hir::ExprMethodCall(name, ref tps, ref args) => {
3714               self.check_method_call(expr, name, args, &tps[..], expected, lvalue_pref)
3715           }
3716           hir::ExprCast(ref e, ref t) => {
3717             // Find the type of `e`. Supply hints based on the type we are casting to,
3718             // if appropriate.
3719             let t_cast = self.to_ty(t);
3720             let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3721             let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
3722             let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3723             let diverges = self.diverges.get();
3724
3725             // Eagerly check for some obvious errors.
3726             if t_expr.references_error() || t_cast.references_error() {
3727                 tcx.types.err
3728             } else {
3729                 // Defer other checks until we're done type checking.
3730                 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
3731                 match cast::CastCheck::new(self, e, t_expr, diverges, t_cast, t.span, expr.span) {
3732                     Ok(cast_check) => {
3733                         deferred_cast_checks.push(cast_check);
3734                         t_cast
3735                     }
3736                     Err(ErrorReported) => {
3737                         tcx.types.err
3738                     }
3739                 }
3740             }
3741           }
3742           hir::ExprType(ref e, ref t) => {
3743             let typ = self.to_ty(&t);
3744             self.check_expr_eq_type(&e, typ);
3745             typ
3746           }
3747           hir::ExprArray(ref args) => {
3748               let uty = expected.to_option(self).and_then(|uty| {
3749                   match uty.sty {
3750                       ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3751                       _ => None
3752                   }
3753               });
3754
3755               let element_ty = if !args.is_empty() {
3756                   let coerce_to = uty.unwrap_or_else(
3757                       || self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span)));
3758                   let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
3759                   assert_eq!(self.diverges.get(), Diverges::Maybe);
3760                   for e in args {
3761                       let e_ty = self.check_expr_with_hint(e, coerce_to);
3762                       let cause = self.misc(e.span);
3763                       coerce.coerce(self, &cause, e, e_ty, self.diverges.get());
3764                   }
3765                   coerce.complete(self)
3766               } else {
3767                   self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span))
3768               };
3769               tcx.mk_array(element_ty, args.len())
3770           }
3771           hir::ExprRepeat(ref element, count) => {
3772             let count = eval_length(self.tcx, count, "repeat count")
3773                   .unwrap_or(0);
3774
3775             let uty = match expected {
3776                 ExpectHasType(uty) => {
3777                     match uty.sty {
3778                         ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3779                         _ => None
3780                     }
3781                 }
3782                 _ => None
3783             };
3784
3785             let (element_ty, t) = match uty {
3786                 Some(uty) => {
3787                     self.check_expr_coercable_to_type(&element, uty);
3788                     (uty, uty)
3789                 }
3790                 None => {
3791                     let t: Ty = self.next_ty_var(TypeVariableOrigin::MiscVariable(element.span));
3792                     let element_ty = self.check_expr_has_type(&element, t);
3793                     (element_ty, t)
3794                 }
3795             };
3796
3797             if count > 1 {
3798                 // For [foo, ..n] where n > 1, `foo` must have
3799                 // Copy type:
3800                 let lang_item = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
3801                 self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
3802             }
3803
3804             if element_ty.references_error() {
3805                 tcx.types.err
3806             } else {
3807                 tcx.mk_array(t, count)
3808             }
3809           }
3810           hir::ExprTup(ref elts) => {
3811             let flds = expected.only_has_type(self).and_then(|ty| {
3812                 match ty.sty {
3813                     ty::TyTuple(ref flds, _) => Some(&flds[..]),
3814                     _ => None
3815                 }
3816             });
3817
3818             let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
3819                 let t = match flds {
3820                     Some(ref fs) if i < fs.len() => {
3821                         let ety = fs[i];
3822                         self.check_expr_coercable_to_type(&e, ety);
3823                         ety
3824                     }
3825                     _ => {
3826                         self.check_expr_with_expectation(&e, NoExpectation)
3827                     }
3828                 };
3829                 t
3830             });
3831             let tuple = tcx.mk_tup(elt_ts_iter, false);
3832             if tuple.references_error() {
3833                 tcx.types.err
3834             } else {
3835                 tuple
3836             }
3837           }
3838           hir::ExprStruct(ref qpath, ref fields, ref base_expr) => {
3839             self.check_expr_struct(expr, expected, qpath, fields, base_expr)
3840           }
3841           hir::ExprField(ref base, ref field) => {
3842             self.check_field(expr, lvalue_pref, &base, field)
3843           }
3844           hir::ExprTupField(ref base, idx) => {
3845             self.check_tup_field(expr, lvalue_pref, &base, idx)
3846           }
3847           hir::ExprIndex(ref base, ref idx) => {
3848               let base_t = self.check_expr_with_lvalue_pref(&base, lvalue_pref);
3849               let idx_t = self.check_expr(&idx);
3850
3851               if base_t.references_error() {
3852                   base_t
3853               } else if idx_t.references_error() {
3854                   idx_t
3855               } else {
3856                   let base_t = self.structurally_resolved_type(expr.span, base_t);
3857                   match self.lookup_indexing(expr, base, base_t, idx_t, lvalue_pref) {
3858                       Some((index_ty, element_ty)) => {
3859                           self.demand_coerce(idx, idx_t, index_ty);
3860                           element_ty
3861                       }
3862                       None => {
3863                           let mut err = self.type_error_struct(
3864                               expr.span,
3865                               |actual| {
3866                                   format!("cannot index a value of type `{}`",
3867                                           actual)
3868                               },
3869                               base_t);
3870                           // Try to give some advice about indexing tuples.
3871                           if let ty::TyTuple(..) = base_t.sty {
3872                               let mut needs_note = true;
3873                               // If the index is an integer, we can show the actual
3874                               // fixed expression:
3875                               if let hir::ExprLit(ref lit) = idx.node {
3876                                   if let ast::LitKind::Int(i,
3877                                             ast::LitIntType::Unsuffixed) = lit.node {
3878                                       let snip = tcx.sess.codemap().span_to_snippet(base.span);
3879                                       if let Ok(snip) = snip {
3880                                           err.span_suggestion(expr.span,
3881                                                               "to access tuple elements, use",
3882                                                               format!("{}.{}", snip, i));
3883                                           needs_note = false;
3884                                       }
3885                                   }
3886                               }
3887                               if needs_note {
3888                                   err.help("to access tuple elements, use tuple indexing \
3889                                             syntax (e.g. `tuple.0`)");
3890                               }
3891                           }
3892                           err.emit();
3893                           self.tcx.types.err
3894                       }
3895                   }
3896               }
3897            }
3898         }
3899     }
3900
3901     // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
3902     // The newly resolved definition is written into `type_relative_path_defs`.
3903     fn finish_resolving_struct_path(&self,
3904                                     qpath: &hir::QPath,
3905                                     path_span: Span,
3906                                     node_id: ast::NodeId)
3907                                     -> (Def, Ty<'tcx>)
3908     {
3909         match *qpath {
3910             hir::QPath::Resolved(ref maybe_qself, ref path) => {
3911                 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself));
3912                 let ty = AstConv::def_to_ty(self, opt_self_ty, path, true);
3913                 (path.def, ty)
3914             }
3915             hir::QPath::TypeRelative(ref qself, ref segment) => {
3916                 let ty = self.to_ty(qself);
3917
3918                 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
3919                     path.def
3920                 } else {
3921                     Def::Err
3922                 };
3923                 let (ty, def) = AstConv::associated_path_def_to_ty(self, node_id, path_span,
3924                                                                    ty, def, segment);
3925
3926                 // Write back the new resolution.
3927                 self.tables.borrow_mut().type_relative_path_defs.insert(node_id, def);
3928
3929                 (def, ty)
3930             }
3931         }
3932     }
3933
3934     // Resolve associated value path into a base type and associated constant or method definition.
3935     // The newly resolved definition is written into `type_relative_path_defs`.
3936     pub fn resolve_ty_and_def_ufcs<'b>(&self,
3937                                        qpath: &'b hir::QPath,
3938                                        node_id: ast::NodeId,
3939                                        span: Span)
3940                                        -> (Def, Option<Ty<'tcx>>, &'b [hir::PathSegment])
3941     {
3942         let (ty, item_segment) = match *qpath {
3943             hir::QPath::Resolved(ref opt_qself, ref path) => {
3944                 return (path.def,
3945                         opt_qself.as_ref().map(|qself| self.to_ty(qself)),
3946                         &path.segments[..]);
3947             }
3948             hir::QPath::TypeRelative(ref qself, ref segment) => {
3949                 (self.to_ty(qself), segment)
3950             }
3951         };
3952         let item_name = item_segment.name;
3953         let def = match self.resolve_ufcs(span, item_name, ty, node_id) {
3954             Ok(def) => def,
3955             Err(error) => {
3956                 let def = match error {
3957                     method::MethodError::PrivateMatch(def) => def,
3958                     _ => Def::Err,
3959                 };
3960                 if item_name != keywords::Invalid.name() {
3961                     self.report_method_error(span, ty, item_name, None, error, None);
3962                 }
3963                 def
3964             }
3965         };
3966
3967         // Write back the new resolution.
3968         self.tables.borrow_mut().type_relative_path_defs.insert(node_id, def);
3969         (def, Some(ty), slice::ref_slice(&**item_segment))
3970     }
3971
3972     pub fn check_decl_initializer(&self,
3973                                   local: &'gcx hir::Local,
3974                                   init: &'gcx hir::Expr) -> Ty<'tcx>
3975     {
3976         let ref_bindings = local.pat.contains_ref_binding();
3977
3978         let local_ty = self.local_ty(init.span, local.id);
3979         if let Some(m) = ref_bindings {
3980             // Somewhat subtle: if we have a `ref` binding in the pattern,
3981             // we want to avoid introducing coercions for the RHS. This is
3982             // both because it helps preserve sanity and, in the case of
3983             // ref mut, for soundness (issue #23116). In particular, in
3984             // the latter case, we need to be clear that the type of the
3985             // referent for the reference that results is *equal to* the
3986             // type of the lvalue it is referencing, and not some
3987             // supertype thereof.
3988             let init_ty = self.check_expr_with_lvalue_pref(init, LvaluePreference::from_mutbl(m));
3989             self.demand_eqtype(init.span, init_ty, local_ty);
3990             init_ty
3991         } else {
3992             self.check_expr_coercable_to_type(init, local_ty)
3993         }
3994     }
3995
3996     pub fn check_decl_local(&self, local: &'gcx hir::Local)  {
3997         let t = self.local_ty(local.span, local.id);
3998         self.write_ty(local.id, t);
3999
4000         if let Some(ref init) = local.init {
4001             let init_ty = self.check_decl_initializer(local, &init);
4002             if init_ty.references_error() {
4003                 self.write_ty(local.id, init_ty);
4004             }
4005         }
4006
4007         self.check_pat(&local.pat, t);
4008         let pat_ty = self.node_ty(local.pat.id);
4009         if pat_ty.references_error() {
4010             self.write_ty(local.id, pat_ty);
4011         }
4012     }
4013
4014     pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) {
4015         // Don't do all the complex logic below for DeclItem.
4016         match stmt.node {
4017             hir::StmtDecl(ref decl, id) => {
4018                 match decl.node {
4019                     hir::DeclLocal(_) => {}
4020                     hir::DeclItem(_) => {
4021                         self.write_nil(id);
4022                         return;
4023                     }
4024                 }
4025             }
4026             hir::StmtExpr(..) | hir::StmtSemi(..) => {}
4027         }
4028
4029         self.warn_if_unreachable(stmt.node.id(), stmt.span, "statement");
4030
4031         // Hide the outer diverging and has_errors flags.
4032         let old_diverges = self.diverges.get();
4033         let old_has_errors = self.has_errors.get();
4034         self.diverges.set(Diverges::Maybe);
4035         self.has_errors.set(false);
4036
4037         let (node_id, _span) = match stmt.node {
4038             hir::StmtDecl(ref decl, id) => {
4039                 let span = match decl.node {
4040                     hir::DeclLocal(ref l) => {
4041                         self.check_decl_local(&l);
4042                         l.span
4043                     }
4044                     hir::DeclItem(_) => {/* ignore for now */
4045                         DUMMY_SP
4046                     }
4047                 };
4048                 (id, span)
4049             }
4050             hir::StmtExpr(ref expr, id) => {
4051                 // Check with expected type of ()
4052                 self.check_expr_has_type(&expr, self.tcx.mk_nil());
4053                 (id, expr.span)
4054             }
4055             hir::StmtSemi(ref expr, id) => {
4056                 self.check_expr(&expr);
4057                 (id, expr.span)
4058             }
4059         };
4060
4061         if self.has_errors.get() {
4062             self.write_error(node_id);
4063         } else {
4064             self.write_nil(node_id);
4065         }
4066
4067         // Combine the diverging and has_error flags.
4068         self.diverges.set(self.diverges.get() | old_diverges);
4069         self.has_errors.set(self.has_errors.get() | old_has_errors);
4070     }
4071
4072     pub fn check_block_no_value(&self, blk: &'gcx hir::Block)  {
4073         let unit = self.tcx.mk_nil();
4074         let ty = self.check_block_with_expected(blk, ExpectHasType(unit));
4075
4076         // if the block produces a `!` value, that can always be
4077         // (effectively) coerced to unit.
4078         if !ty.is_never() {
4079             self.demand_suptype(blk.span, unit, ty);
4080         }
4081     }
4082
4083     fn check_block_with_expected(&self,
4084                                  blk: &'gcx hir::Block,
4085                                  expected: Expectation<'tcx>) -> Ty<'tcx> {
4086         let prev = {
4087             let mut fcx_ps = self.ps.borrow_mut();
4088             let unsafety_state = fcx_ps.recurse(blk);
4089             replace(&mut *fcx_ps, unsafety_state)
4090         };
4091
4092         // In some cases, blocks have just one exit, but other blocks
4093         // can be targeted by multiple breaks. This cannot happen in
4094         // normal Rust syntax today, but it can happen when we desugar
4095         // a `do catch { ... }` expression.
4096         //
4097         // Example 1:
4098         //
4099         //    'a: { if true { break 'a Err(()); } Ok(()) }
4100         //
4101         // Here we would wind up with two coercions, one from
4102         // `Err(())` and the other from the tail expression
4103         // `Ok(())`. If the tail expression is omitted, that's a
4104         // "forced unit" -- unless the block diverges, in which
4105         // case we can ignore the tail expression (e.g., `'a: {
4106         // break 'a 22; }` would not force the type of the block
4107         // to be `()`).
4108         let tail_expr = blk.expr.as_ref();
4109         let coerce_to_ty = expected.coercion_target_type(self, blk.span);
4110         let coerce = if blk.targeted_by_break {
4111             CoerceMany::new(coerce_to_ty)
4112         } else {
4113             let tail_expr: &[P<hir::Expr>] = match tail_expr {
4114                 Some(e) => ref_slice(e),
4115                 None => &[],
4116             };
4117             CoerceMany::with_coercion_sites(coerce_to_ty, tail_expr)
4118         };
4119
4120         let ctxt = BreakableCtxt {
4121             coerce: Some(coerce),
4122             may_break: false,
4123         };
4124
4125         let (ctxt, ()) = self.with_breakable_ctxt(blk.id, ctxt, || {
4126             for s in &blk.stmts {
4127                 self.check_stmt(s);
4128             }
4129
4130             // check the tail expression **without** holding the
4131             // `enclosing_breakables` lock below.
4132             let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected));
4133
4134             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4135             let mut ctxt = enclosing_breakables.find_breakable(blk.id);
4136             let mut coerce = ctxt.coerce.as_mut().unwrap();
4137             if let Some(tail_expr_ty) = tail_expr_ty {
4138                 let tail_expr = tail_expr.unwrap();
4139                 coerce.coerce(self,
4140                               &self.misc(tail_expr.span),
4141                               tail_expr,
4142                               tail_expr_ty,
4143                               self.diverges.get());
4144             } else {
4145                 // Subtle: if there is no explicit tail expression,
4146                 // that is typically equivalent to a tail expression
4147                 // of `()` -- except if the block diverges. In that
4148                 // case, there is no value supplied from the tail
4149                 // expression (assuming there are no other breaks,
4150                 // this implies that the type of the block will be
4151                 // `!`).
4152                 //
4153                 // #41425 -- label the implicit `()` as being the
4154                 // "found type" here, rather than the "expected type".
4155                 if !self.diverges.get().always() {
4156                     coerce.coerce_forced_unit(self, &self.misc(blk.span), &mut |err| {
4157                         if let Some(expected_ty) = expected.only_has_type(self) {
4158                             self.consider_hint_about_removing_semicolon(blk,
4159                                                                         expected_ty,
4160                                                                         err);
4161                         }
4162                     }, false);
4163                 }
4164             }
4165         });
4166
4167         let mut ty = ctxt.coerce.unwrap().complete(self);
4168
4169         if self.has_errors.get() || ty.references_error() {
4170             ty = self.tcx.types.err
4171         }
4172
4173         self.write_ty(blk.id, ty);
4174
4175         *self.ps.borrow_mut() = prev;
4176         ty
4177     }
4178
4179     /// A common error is to add an extra semicolon:
4180     ///
4181     /// ```
4182     /// fn foo() -> usize {
4183     ///     22;
4184     /// }
4185     /// ```
4186     ///
4187     /// This routine checks if the final statement in a block is an
4188     /// expression with an explicit semicolon whose type is compatible
4189     /// with `expected_ty`. If so, it suggests removing the semicolon.
4190     fn consider_hint_about_removing_semicolon(&self,
4191                                               blk: &'gcx hir::Block,
4192                                               expected_ty: Ty<'tcx>,
4193                                               err: &mut DiagnosticBuilder) {
4194         // Be helpful when the user wrote `{... expr;}` and
4195         // taking the `;` off is enough to fix the error.
4196         let last_stmt = match blk.stmts.last() {
4197             Some(s) => s,
4198             None => return,
4199         };
4200         let last_expr = match last_stmt.node {
4201             hir::StmtSemi(ref e, _) => e,
4202             _ => return,
4203         };
4204         let last_expr_ty = self.expr_ty(last_expr);
4205         if self.can_sub_types(last_expr_ty, expected_ty).is_err() {
4206             return;
4207         }
4208         let original_span = original_sp(last_stmt.span, blk.span);
4209         let span_semi = Span {
4210             lo: original_span.hi - BytePos(1),
4211             hi: original_span.hi,
4212             ctxt: original_span.ctxt,
4213         };
4214         err.span_help(span_semi, "consider removing this semicolon:");
4215     }
4216
4217     // Instantiates the given path, which must refer to an item with the given
4218     // number of type parameters and type.
4219     pub fn instantiate_value_path(&self,
4220                                   segments: &[hir::PathSegment],
4221                                   opt_self_ty: Option<Ty<'tcx>>,
4222                                   def: Def,
4223                                   span: Span,
4224                                   node_id: ast::NodeId)
4225                                   -> Ty<'tcx> {
4226         debug!("instantiate_value_path(path={:?}, def={:?}, node_id={})",
4227                segments,
4228                def,
4229                node_id);
4230
4231         // We need to extract the type parameters supplied by the user in
4232         // the path `path`. Due to the current setup, this is a bit of a
4233         // tricky-process; the problem is that resolve only tells us the
4234         // end-point of the path resolution, and not the intermediate steps.
4235         // Luckily, we can (at least for now) deduce the intermediate steps
4236         // just from the end-point.
4237         //
4238         // There are basically four cases to consider:
4239         //
4240         // 1. Reference to a constructor of enum variant or struct:
4241         //
4242         //        struct Foo<T>(...)
4243         //        enum E<T> { Foo(...) }
4244         //
4245         //    In these cases, the parameters are declared in the type
4246         //    space.
4247         //
4248         // 2. Reference to a fn item or a free constant:
4249         //
4250         //        fn foo<T>() { }
4251         //
4252         //    In this case, the path will again always have the form
4253         //    `a::b::foo::<T>` where only the final segment should have
4254         //    type parameters. However, in this case, those parameters are
4255         //    declared on a value, and hence are in the `FnSpace`.
4256         //
4257         // 3. Reference to a method or an associated constant:
4258         //
4259         //        impl<A> SomeStruct<A> {
4260         //            fn foo<B>(...)
4261         //        }
4262         //
4263         //    Here we can have a path like
4264         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
4265         //    may appear in two places. The penultimate segment,
4266         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
4267         //    final segment, `foo::<B>` contains parameters in fn space.
4268         //
4269         // 4. Reference to a local variable
4270         //
4271         //    Local variables can't have any type parameters.
4272         //
4273         // The first step then is to categorize the segments appropriately.
4274
4275         assert!(!segments.is_empty());
4276
4277         let mut ufcs_associated = None;
4278         let mut type_segment = None;
4279         let mut fn_segment = None;
4280         match def {
4281             // Case 1. Reference to a struct/variant constructor.
4282             Def::StructCtor(def_id, ..) |
4283             Def::VariantCtor(def_id, ..) => {
4284                 // Everything but the final segment should have no
4285                 // parameters at all.
4286                 let mut generics = self.tcx.generics_of(def_id);
4287                 if let Some(def_id) = generics.parent {
4288                     // Variant and struct constructors use the
4289                     // generics of their parent type definition.
4290                     generics = self.tcx.generics_of(def_id);
4291                 }
4292                 type_segment = Some((segments.last().unwrap(), generics));
4293             }
4294
4295             // Case 2. Reference to a top-level value.
4296             Def::Fn(def_id) |
4297             Def::Const(def_id) |
4298             Def::Static(def_id, _) => {
4299                 fn_segment = Some((segments.last().unwrap(),
4300                                    self.tcx.generics_of(def_id)));
4301             }
4302
4303             // Case 3. Reference to a method or associated const.
4304             Def::Method(def_id) |
4305             Def::AssociatedConst(def_id) => {
4306                 let container = self.tcx.associated_item(def_id).container;
4307                 match container {
4308                     ty::TraitContainer(trait_did) => {
4309                         callee::check_legal_trait_for_method_call(self.tcx, span, trait_did)
4310                     }
4311                     ty::ImplContainer(_) => {}
4312                 }
4313
4314                 let generics = self.tcx.generics_of(def_id);
4315                 if segments.len() >= 2 {
4316                     let parent_generics = self.tcx.generics_of(generics.parent.unwrap());
4317                     type_segment = Some((&segments[segments.len() - 2], parent_generics));
4318                 } else {
4319                     // `<T>::assoc` will end up here, and so can `T::assoc`.
4320                     let self_ty = opt_self_ty.expect("UFCS sugared assoc missing Self");
4321                     ufcs_associated = Some((container, self_ty));
4322                 }
4323                 fn_segment = Some((segments.last().unwrap(), generics));
4324             }
4325
4326             // Case 4. Local variable, no generics.
4327             Def::Local(..) | Def::Upvar(..) => {}
4328
4329             _ => bug!("unexpected definition: {:?}", def),
4330         }
4331
4332         debug!("type_segment={:?} fn_segment={:?}", type_segment, fn_segment);
4333
4334         // Now that we have categorized what space the parameters for each
4335         // segment belong to, let's sort out the parameters that the user
4336         // provided (if any) into their appropriate spaces. We'll also report
4337         // errors if type parameters are provided in an inappropriate place.
4338         let poly_segments = type_segment.is_some() as usize +
4339                             fn_segment.is_some() as usize;
4340         AstConv::prohibit_type_params(self, &segments[..segments.len() - poly_segments]);
4341
4342         match def {
4343             Def::Local(def_id) | Def::Upvar(def_id, ..) => {
4344                 let nid = self.tcx.hir.as_local_node_id(def_id).unwrap();
4345                 let ty = self.local_ty(span, nid);
4346                 let ty = self.normalize_associated_types_in(span, &ty);
4347                 self.write_ty(node_id, ty);
4348                 self.write_substs(node_id, ty::ItemSubsts {
4349                     substs: self.tcx.intern_substs(&[])
4350                 });
4351                 return ty;
4352             }
4353             _ => {}
4354         }
4355
4356         // Now we have to compare the types that the user *actually*
4357         // provided against the types that were *expected*. If the user
4358         // did not provide any types, then we want to substitute inference
4359         // variables. If the user provided some types, we may still need
4360         // to add defaults. If the user provided *too many* types, that's
4361         // a problem.
4362         self.check_path_parameter_count(span, &mut type_segment);
4363         self.check_path_parameter_count(span, &mut fn_segment);
4364
4365         let (fn_start, has_self) = match (type_segment, fn_segment) {
4366             (_, Some((_, generics))) => {
4367                 (generics.parent_count(), generics.has_self)
4368             }
4369             (Some((_, generics)), None) => {
4370                 (generics.own_count(), generics.has_self)
4371             }
4372             (None, None) => (0, false)
4373         };
4374         let substs = Substs::for_item(self.tcx, def.def_id(), |def, _| {
4375             let mut i = def.index as usize;
4376
4377             let segment = if i < fn_start {
4378                 i -= has_self as usize;
4379                 type_segment
4380             } else {
4381                 i -= fn_start;
4382                 fn_segment
4383             };
4384             let lifetimes = match segment.map(|(s, _)| &s.parameters) {
4385                 Some(&hir::AngleBracketedParameters(ref data)) => &data.lifetimes[..],
4386                 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4387                 None => &[]
4388             };
4389
4390             if let Some(lifetime) = lifetimes.get(i) {
4391                 AstConv::ast_region_to_region(self, lifetime, Some(def))
4392             } else {
4393                 self.re_infer(span, Some(def)).unwrap()
4394             }
4395         }, |def, substs| {
4396             let mut i = def.index as usize;
4397
4398             let segment = if i < fn_start {
4399                 // Handle Self first, so we can adjust the index to match the AST.
4400                 if has_self && i == 0 {
4401                     return opt_self_ty.unwrap_or_else(|| {
4402                         self.type_var_for_def(span, def, substs)
4403                     });
4404                 }
4405                 i -= has_self as usize;
4406                 type_segment
4407             } else {
4408                 i -= fn_start;
4409                 fn_segment
4410             };
4411             let (types, infer_types) = match segment.map(|(s, _)| &s.parameters) {
4412                 Some(&hir::AngleBracketedParameters(ref data)) => {
4413                     (&data.types[..], data.infer_types)
4414                 }
4415                 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4416                 None => (&[][..], true)
4417             };
4418
4419             // Skip over the lifetimes in the same segment.
4420             if let Some((_, generics)) = segment {
4421                 i -= generics.regions.len();
4422             }
4423
4424             if let Some(ast_ty) = types.get(i) {
4425                 // A provided type parameter.
4426                 self.to_ty(ast_ty)
4427             } else if !infer_types && def.has_default {
4428                 // No type parameter provided, but a default exists.
4429                 let default = self.tcx.type_of(def.def_id);
4430                 self.normalize_ty(
4431                     span,
4432                     default.subst_spanned(self.tcx, substs, Some(span))
4433                 )
4434             } else {
4435                 // No type parameters were provided, we can infer all.
4436                 // This can also be reached in some error cases:
4437                 // We prefer to use inference variables instead of
4438                 // TyError to let type inference recover somewhat.
4439                 self.type_var_for_def(span, def, substs)
4440             }
4441         });
4442
4443         // The things we are substituting into the type should not contain
4444         // escaping late-bound regions, and nor should the base type scheme.
4445         let ty = self.tcx.type_of(def.def_id());
4446         assert!(!substs.has_escaping_regions());
4447         assert!(!ty.has_escaping_regions());
4448
4449         // Add all the obligations that are required, substituting and
4450         // normalized appropriately.
4451         let bounds = self.instantiate_bounds(span, def.def_id(), &substs);
4452         self.add_obligations_for_parameters(
4453             traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def.def_id())),
4454             &bounds);
4455
4456         // Substitute the values for the type parameters into the type of
4457         // the referenced item.
4458         let ty_substituted = self.instantiate_type_scheme(span, &substs, &ty);
4459
4460         if let Some((ty::ImplContainer(impl_def_id), self_ty)) = ufcs_associated {
4461             // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
4462             // is inherent, there is no `Self` parameter, instead, the impl needs
4463             // type parameters, which we can infer by unifying the provided `Self`
4464             // with the substituted impl type.
4465             let ty = self.tcx.type_of(impl_def_id);
4466
4467             let impl_ty = self.instantiate_type_scheme(span, &substs, &ty);
4468             match self.sub_types(false, &self.misc(span), self_ty, impl_ty) {
4469                 Ok(ok) => self.register_infer_ok_obligations(ok),
4470                 Err(_) => {
4471                     span_bug!(span,
4472                         "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
4473                         self_ty,
4474                         impl_ty);
4475                 }
4476             }
4477         }
4478
4479         debug!("instantiate_value_path: type of {:?} is {:?}",
4480                node_id,
4481                ty_substituted);
4482         self.write_substs(node_id, ty::ItemSubsts {
4483             substs: substs
4484         });
4485         ty_substituted
4486     }
4487
4488     /// Report errors if the provided parameters are too few or too many.
4489     fn check_path_parameter_count(&self,
4490                                   span: Span,
4491                                   segment: &mut Option<(&hir::PathSegment, &ty::Generics)>) {
4492         let (lifetimes, types, infer_types, bindings) = {
4493             match segment.map(|(s, _)| &s.parameters) {
4494                 Some(&hir::AngleBracketedParameters(ref data)) => {
4495                     (&data.lifetimes[..], &data.types[..], data.infer_types, &data.bindings[..])
4496                 }
4497                 Some(&hir::ParenthesizedParameters(_)) => {
4498                     span_bug!(span, "parenthesized parameters cannot appear in ExprPath");
4499                 }
4500                 None => (&[][..], &[][..], true, &[][..])
4501             }
4502         };
4503
4504         let count_lifetime_params = |n| {
4505             format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" })
4506         };
4507         let count_type_params = |n| {
4508             format!("{} type parameter{}", n, if n == 1 { "" } else { "s" })
4509         };
4510
4511         // Check provided lifetime parameters.
4512         let lifetime_defs = segment.map_or(&[][..], |(_, generics)| &generics.regions);
4513         if lifetimes.len() > lifetime_defs.len() {
4514             let expected_text = count_lifetime_params(lifetime_defs.len());
4515             let actual_text = count_lifetime_params(lifetimes.len());
4516             struct_span_err!(self.tcx.sess, span, E0088,
4517                              "too many lifetime parameters provided: \
4518                               expected at most {}, found {}",
4519                              expected_text, actual_text)
4520                 .span_label(span, format!("expected {}", expected_text))
4521                 .emit();
4522         } else if lifetimes.len() > 0 && lifetimes.len() < lifetime_defs.len() {
4523             let expected_text = count_lifetime_params(lifetime_defs.len());
4524             let actual_text = count_lifetime_params(lifetimes.len());
4525             struct_span_err!(self.tcx.sess, span, E0090,
4526                              "too few lifetime parameters provided: \
4527                               expected {}, found {}",
4528                              expected_text, actual_text)
4529                 .span_label(span, format!("expected {}", expected_text))
4530                 .emit();
4531         }
4532
4533         // The case where there is not enough lifetime parameters is not checked,
4534         // because this is not possible - a function never takes lifetime parameters.
4535         // See discussion for Pull Request 36208.
4536
4537         // Check provided type parameters.
4538         let type_defs = segment.map_or(&[][..], |(_, generics)| {
4539             if generics.parent.is_none() {
4540                 &generics.types[generics.has_self as usize..]
4541             } else {
4542                 &generics.types
4543             }
4544         });
4545         let required_len = type_defs.iter().take_while(|d| !d.has_default).count();
4546         if types.len() > type_defs.len() {
4547             let span = types[type_defs.len()].span;
4548             let expected_text = count_type_params(type_defs.len());
4549             let actual_text = count_type_params(types.len());
4550             struct_span_err!(self.tcx.sess, span, E0087,
4551                              "too many type parameters provided: \
4552                               expected at most {}, found {}",
4553                              expected_text, actual_text)
4554                 .span_label(span, format!("expected {}", expected_text))
4555                 .emit();
4556
4557             // To prevent derived errors to accumulate due to extra
4558             // type parameters, we force instantiate_value_path to
4559             // use inference variables instead of the provided types.
4560             *segment = None;
4561         } else if !infer_types && types.len() < required_len {
4562             let expected_text = count_type_params(required_len);
4563             let actual_text = count_type_params(types.len());
4564             struct_span_err!(self.tcx.sess, span, E0089,
4565                              "too few type parameters provided: \
4566                               expected {}, found {}",
4567                              expected_text, actual_text)
4568                 .span_label(span, format!("expected {}", expected_text))
4569                 .emit();
4570         }
4571
4572         if !bindings.is_empty() {
4573             span_err!(self.tcx.sess, bindings[0].span, E0182,
4574                       "unexpected binding of associated item in expression path \
4575                        (only allowed in type paths)");
4576         }
4577     }
4578
4579     fn structurally_resolve_type_or_else<F>(&self, sp: Span, ty: Ty<'tcx>, f: F)
4580                                             -> Ty<'tcx>
4581         where F: Fn() -> Ty<'tcx>
4582     {
4583         let mut ty = self.resolve_type_vars_with_obligations(ty);
4584
4585         if ty.is_ty_var() {
4586             let alternative = f();
4587
4588             // If not, error.
4589             if alternative.is_ty_var() || alternative.references_error() {
4590                 if !self.is_tainted_by_errors() {
4591                     self.type_error_message(sp, |_actual| {
4592                         "the type of this value must be known in this context".to_string()
4593                     }, ty);
4594                 }
4595                 self.demand_suptype(sp, self.tcx.types.err, ty);
4596                 ty = self.tcx.types.err;
4597             } else {
4598                 self.demand_suptype(sp, alternative, ty);
4599                 ty = alternative;
4600             }
4601         }
4602
4603         ty
4604     }
4605
4606     // Resolves `typ` by a single level if `typ` is a type variable.  If no
4607     // resolution is possible, then an error is reported.
4608     pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
4609         self.structurally_resolve_type_or_else(sp, ty, || {
4610             self.tcx.types.err
4611         })
4612     }
4613
4614     fn with_breakable_ctxt<F: FnOnce() -> R, R>(&self, id: ast::NodeId,
4615                                         ctxt: BreakableCtxt<'gcx, 'tcx>, f: F)
4616                                    -> (BreakableCtxt<'gcx, 'tcx>, R) {
4617         let index;
4618         {
4619             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4620             index = enclosing_breakables.stack.len();
4621             enclosing_breakables.by_id.insert(id, index);
4622             enclosing_breakables.stack.push(ctxt);
4623         }
4624         let result = f();
4625         let ctxt = {
4626             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4627             debug_assert!(enclosing_breakables.stack.len() == index + 1);
4628             enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
4629             enclosing_breakables.stack.pop().expect("missing breakable context")
4630         };
4631         (ctxt, result)
4632     }
4633 }
4634
4635 pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
4636                                        generics: &hir::Generics,
4637                                        ty: Ty<'tcx>) {
4638     debug!("check_bounds_are_used(n_tps={}, ty={:?})",
4639            generics.ty_params.len(),  ty);
4640
4641     // make a vector of booleans initially false, set to true when used
4642     if generics.ty_params.is_empty() { return; }
4643     let mut tps_used = vec![false; generics.ty_params.len()];
4644
4645     for leaf_ty in ty.walk() {
4646         if let ty::TyParam(ParamTy {idx, ..}) = leaf_ty.sty {
4647             debug!("Found use of ty param num {}", idx);
4648             tps_used[idx as usize - generics.lifetimes.len()] = true;
4649         }
4650     }
4651
4652     for (&used, param) in tps_used.iter().zip(&generics.ty_params) {
4653         if !used {
4654             struct_span_err!(tcx.sess, param.span, E0091,
4655                 "type parameter `{}` is unused",
4656                 param.name)
4657                 .span_label(param.span, "unused type parameter")
4658                 .emit();
4659         }
4660     }
4661 }