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