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