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