]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/mod.rs
rustc: make the comon case of tcx.infer_ctxt(()) nicer.
[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             let mut err = self.type_error_struct(field.span, |actual| {
2956                 format!("no field `{}` on type `{}`",
2957                         field.node, actual)
2958             }, 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,
2967                                            "unknown field");
2968                         };
2969                 }
2970                 ty::TyRawPtr(..) => {
2971                     err.note(&format!("`{0}` is a native pointer; perhaps you need to deref with \
2972                                       `(*{0}).{1}`",
2973                                       self.tcx.hir.node_to_pretty_string(base.id),
2974                                       field.node));
2975                 }
2976                 _ => {}
2977             }
2978             err.emit();
2979             self.tcx().types.err
2980         }
2981     }
2982
2983     // Return an hint about the closest match in field names
2984     fn suggest_field_name(variant: &'tcx ty::VariantDef,
2985                           field: &Spanned<ast::Name>,
2986                           skip : Vec<InternedString>)
2987                           -> Option<Symbol> {
2988         let name = field.node.as_str();
2989         let names = variant.fields.iter().filter_map(|field| {
2990             // ignore already set fields and private fields from non-local crates
2991             if skip.iter().any(|x| *x == field.name.as_str()) ||
2992                (variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
2993                 None
2994             } else {
2995                 Some(&field.name)
2996             }
2997         });
2998
2999         // only find fits with at least one matching letter
3000         find_best_match_for_name(names, &name, Some(name.len()))
3001     }
3002
3003     // Check tuple index expressions
3004     fn check_tup_field(&self,
3005                        expr: &'gcx hir::Expr,
3006                        lvalue_pref: LvaluePreference,
3007                        base: &'gcx hir::Expr,
3008                        idx: codemap::Spanned<usize>) -> Ty<'tcx> {
3009         let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
3010         let expr_t = self.structurally_resolved_type(expr.span,
3011                                                      expr_t);
3012         let mut private_candidate = None;
3013         let mut tuple_like = false;
3014         let mut autoderef = self.autoderef(expr.span, expr_t);
3015         while let Some((base_t, _)) = autoderef.next() {
3016             let field = match base_t.sty {
3017                 ty::TyAdt(base_def, substs) if base_def.is_struct() => {
3018                     tuple_like = base_def.struct_variant().ctor_kind == CtorKind::Fn;
3019                     if !tuple_like { continue }
3020
3021                     debug!("tuple struct named {:?}",  base_t);
3022                     let ident = ast::Ident {
3023                         name: Symbol::intern(&idx.node.to_string()),
3024                         ctxt: idx.span.ctxt.modern(),
3025                     };
3026                     let (ident, def_scope) =
3027                         self.tcx.adjust_ident(ident, base_def.did, self.body_id);
3028                     let fields = &base_def.struct_variant().fields;
3029                     if let Some(field) = fields.iter().find(|f| f.name.to_ident() == ident) {
3030                         let field_ty = self.field_ty(expr.span, field, substs);
3031                         if field.vis.is_accessible_from(def_scope, self.tcx) {
3032                             self.tcx.check_stability(field.did, expr.id, expr.span);
3033                             Some(field_ty)
3034                         } else {
3035                             private_candidate = Some((base_def.did, field_ty));
3036                             None
3037                         }
3038                     } else {
3039                         None
3040                     }
3041                 }
3042                 ty::TyTuple(ref v, _) => {
3043                     tuple_like = true;
3044                     v.get(idx.node).cloned()
3045                 }
3046                 _ => continue
3047             };
3048
3049             if let Some(field_ty) = field {
3050                 let adjustments = autoderef.adjust_steps(lvalue_pref);
3051                 self.apply_adjustments(base, adjustments);
3052                 autoderef.finalize();
3053                 return field_ty;
3054             }
3055         }
3056         autoderef.unambiguous_final_ty();
3057
3058         if let Some((did, field_ty)) = private_candidate {
3059             let struct_path = self.tcx().item_path_str(did);
3060             let msg = format!("field `{}` of struct `{}` is private", idx.node, struct_path);
3061             self.tcx().sess.span_err(expr.span, &msg);
3062             return field_ty;
3063         }
3064
3065         self.type_error_message(
3066             expr.span,
3067             |actual| {
3068                 if tuple_like {
3069                     format!("attempted out-of-bounds tuple index `{}` on \
3070                                     type `{}`",
3071                                    idx.node,
3072                                    actual)
3073                 } else {
3074                     format!("attempted tuple index `{}` on type `{}`, but the \
3075                                      type was not a tuple or tuple struct",
3076                                     idx.node,
3077                                     actual)
3078                 }
3079             },
3080             expr_t);
3081
3082         self.tcx().types.err
3083     }
3084
3085     fn report_unknown_field(&self,
3086                             ty: Ty<'tcx>,
3087                             variant: &'tcx ty::VariantDef,
3088                             field: &hir::Field,
3089                             skip_fields: &[hir::Field],
3090                             kind_name: &str) {
3091         let mut err = self.type_error_struct_with_diag(
3092             field.name.span,
3093             |actual| match ty.sty {
3094                 ty::TyAdt(adt, ..) if adt.is_enum() => {
3095                     struct_span_err!(self.tcx.sess, field.name.span, E0559,
3096                                     "{} `{}::{}` has no field named `{}`",
3097                                     kind_name, actual, variant.name, field.name.node)
3098                 }
3099                 _ => {
3100                     struct_span_err!(self.tcx.sess, field.name.span, E0560,
3101                                     "{} `{}` has no field named `{}`",
3102                                     kind_name, actual, field.name.node)
3103                 }
3104             },
3105             ty);
3106         // prevent all specified fields from being suggested
3107         let skip_fields = skip_fields.iter().map(|ref x| x.name.node.as_str());
3108         if let Some(field_name) = Self::suggest_field_name(variant,
3109                                                            &field.name,
3110                                                            skip_fields.collect()) {
3111             err.span_label(field.name.span,
3112                            format!("field does not exist - did you mean `{}`?", field_name));
3113         } else {
3114             match ty.sty {
3115                 ty::TyAdt(adt, ..) if adt.is_enum() => {
3116                     err.span_label(field.name.span, format!("`{}::{}` does not have this field",
3117                                                              ty, variant.name));
3118                 }
3119                 _ => {
3120                     err.span_label(field.name.span, format!("`{}` does not have this field", ty));
3121                 }
3122             }
3123         };
3124         err.emit();
3125     }
3126
3127     fn check_expr_struct_fields(&self,
3128                                 adt_ty: Ty<'tcx>,
3129                                 expected: Expectation<'tcx>,
3130                                 expr_id: ast::NodeId,
3131                                 span: Span,
3132                                 variant: &'tcx ty::VariantDef,
3133                                 ast_fields: &'gcx [hir::Field],
3134                                 check_completeness: bool) {
3135         let tcx = self.tcx;
3136
3137         let adt_ty_hint =
3138             self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
3139                 .get(0).cloned().unwrap_or(adt_ty);
3140
3141         let (substs, hint_substs, adt_kind, kind_name) = match (&adt_ty.sty, &adt_ty_hint.sty) {
3142             (&ty::TyAdt(adt, substs), &ty::TyAdt(_, hint_substs)) => {
3143                 (substs, hint_substs, adt.adt_kind(), adt.variant_descr())
3144             }
3145             _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
3146         };
3147
3148         let mut remaining_fields = FxHashMap();
3149         for field in &variant.fields {
3150             remaining_fields.insert(field.name.to_ident(), field);
3151         }
3152
3153         let mut seen_fields = FxHashMap();
3154
3155         let mut error_happened = false;
3156
3157         // Typecheck each field.
3158         for field in ast_fields {
3159             let final_field_type;
3160             let field_type_hint;
3161
3162             let ident = tcx.adjust(field.name.node, variant.did, self.body_id).0;
3163             if let Some(v_field) = remaining_fields.remove(&ident) {
3164                 final_field_type = self.field_ty(field.span, v_field, substs);
3165                 field_type_hint = self.field_ty(field.span, v_field, hint_substs);
3166
3167                 seen_fields.insert(field.name.node, field.span);
3168
3169                 // we don't look at stability attributes on
3170                 // struct-like enums (yet...), but it's definitely not
3171                 // a bug to have construct one.
3172                 if adt_kind != ty::AdtKind::Enum {
3173                     tcx.check_stability(v_field.did, expr_id, field.span);
3174                 }
3175             } else {
3176                 error_happened = true;
3177                 final_field_type = tcx.types.err;
3178                 field_type_hint = tcx.types.err;
3179                 if let Some(_) = variant.find_field_named(field.name.node) {
3180                     let mut err = struct_span_err!(self.tcx.sess,
3181                                                 field.name.span,
3182                                                 E0062,
3183                                                 "field `{}` specified more than once",
3184                                                 field.name.node);
3185
3186                     err.span_label(field.name.span, "used more than once");
3187
3188                     if let Some(prev_span) = seen_fields.get(&field.name.node) {
3189                         err.span_label(*prev_span, format!("first use of `{}`", field.name.node));
3190                     }
3191
3192                     err.emit();
3193                 } else {
3194                     self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name);
3195                 }
3196             }
3197
3198             // Make sure to give a type to the field even if there's
3199             // an error, so we can continue typechecking
3200             let ty = self.check_expr_with_hint(&field.expr, field_type_hint);
3201             self.demand_coerce(&field.expr, ty, final_field_type);
3202         }
3203
3204         // Make sure the programmer specified correct number of fields.
3205         if kind_name == "union" {
3206             if ast_fields.len() != 1 {
3207                 tcx.sess.span_err(span, "union expressions should have exactly one field");
3208             }
3209         } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
3210             let len = remaining_fields.len();
3211
3212             let mut displayable_field_names = remaining_fields
3213                                               .keys()
3214                                               .map(|ident| ident.name.as_str())
3215                                               .collect::<Vec<_>>();
3216
3217             displayable_field_names.sort();
3218
3219             let truncated_fields_error = if len <= 3 {
3220                 "".to_string()
3221             } else {
3222                 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
3223             };
3224
3225             let remaining_fields_names = displayable_field_names.iter().take(3)
3226                                         .map(|n| format!("`{}`", n))
3227                                         .collect::<Vec<_>>()
3228                                         .join(", ");
3229
3230             struct_span_err!(tcx.sess, span, E0063,
3231                         "missing field{} {}{} in initializer of `{}`",
3232                         if remaining_fields.len() == 1 {""} else {"s"},
3233                         remaining_fields_names,
3234                         truncated_fields_error,
3235                         adt_ty)
3236                         .span_label(span, format!("missing {}{}",
3237                             remaining_fields_names,
3238                             truncated_fields_error))
3239                         .emit();
3240         }
3241     }
3242
3243     fn check_struct_fields_on_error(&self,
3244                                     fields: &'gcx [hir::Field],
3245                                     base_expr: &'gcx Option<P<hir::Expr>>) {
3246         for field in fields {
3247             self.check_expr(&field.expr);
3248         }
3249         match *base_expr {
3250             Some(ref base) => {
3251                 self.check_expr(&base);
3252             },
3253             None => {}
3254         }
3255     }
3256
3257     pub fn check_struct_path(&self,
3258                              qpath: &hir::QPath,
3259                              node_id: ast::NodeId)
3260                              -> Option<(&'tcx ty::VariantDef,  Ty<'tcx>)> {
3261         let path_span = match *qpath {
3262             hir::QPath::Resolved(_, ref path) => path.span,
3263             hir::QPath::TypeRelative(ref qself, _) => qself.span
3264         };
3265         let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, node_id);
3266         let variant = match def {
3267             Def::Err => {
3268                 self.set_tainted_by_errors();
3269                 return None;
3270             }
3271             Def::Variant(..) => {
3272                 match ty.sty {
3273                     ty::TyAdt(adt, substs) => {
3274                         Some((adt.variant_of_def(def), adt.did, substs))
3275                     }
3276                     _ => bug!("unexpected type: {:?}", ty.sty)
3277                 }
3278             }
3279             Def::Struct(..) | Def::Union(..) | Def::TyAlias(..) |
3280             Def::AssociatedTy(..) | Def::SelfTy(..) => {
3281                 match ty.sty {
3282                     ty::TyAdt(adt, substs) if !adt.is_enum() => {
3283                         Some((adt.struct_variant(), adt.did, substs))
3284                     }
3285                     _ => None,
3286                 }
3287             }
3288             _ => bug!("unexpected definition: {:?}", def)
3289         };
3290
3291         if let Some((variant, did, substs)) = variant {
3292             // Check bounds on type arguments used in the path.
3293             let bounds = self.instantiate_bounds(path_span, did, substs);
3294             let cause = traits::ObligationCause::new(path_span, self.body_id,
3295                                                      traits::ItemObligation(did));
3296             self.add_obligations_for_parameters(cause, &bounds);
3297
3298             Some((variant, ty))
3299         } else {
3300             struct_span_err!(self.tcx.sess, path_span, E0071,
3301                              "expected struct, variant or union type, found {}",
3302                              ty.sort_string(self.tcx))
3303                 .span_label(path_span, "not a struct")
3304                 .emit();
3305             None
3306         }
3307     }
3308
3309     fn check_expr_struct(&self,
3310                          expr: &hir::Expr,
3311                          expected: Expectation<'tcx>,
3312                          qpath: &hir::QPath,
3313                          fields: &'gcx [hir::Field],
3314                          base_expr: &'gcx Option<P<hir::Expr>>) -> Ty<'tcx>
3315     {
3316         // Find the relevant variant
3317         let (variant, struct_ty) =
3318         if let Some(variant_ty) = self.check_struct_path(qpath, expr.id) {
3319             variant_ty
3320         } else {
3321             self.check_struct_fields_on_error(fields, base_expr);
3322             return self.tcx.types.err;
3323         };
3324
3325         let path_span = match *qpath {
3326             hir::QPath::Resolved(_, ref path) => path.span,
3327             hir::QPath::TypeRelative(ref qself, _) => qself.span
3328         };
3329
3330         self.check_expr_struct_fields(struct_ty, expected, expr.id, path_span, variant, fields,
3331                                       base_expr.is_none());
3332         if let &Some(ref base_expr) = base_expr {
3333             self.check_expr_has_type(base_expr, struct_ty);
3334             match struct_ty.sty {
3335                 ty::TyAdt(adt, substs) if adt.is_struct() => {
3336                     let fru_field_types = adt.struct_variant().fields.iter().map(|f| {
3337                         self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
3338                     }).collect();
3339                     self.tables.borrow_mut().fru_field_types.insert(expr.id, fru_field_types);
3340                 }
3341                 _ => {
3342                     span_err!(self.tcx.sess, base_expr.span, E0436,
3343                               "functional record update syntax requires a struct");
3344                 }
3345             }
3346         }
3347         self.require_type_is_sized(struct_ty, expr.span, traits::StructInitializerSized);
3348         struct_ty
3349     }
3350
3351
3352     /// Invariant:
3353     /// If an expression has any sub-expressions that result in a type error,
3354     /// inspecting that expression's type with `ty.references_error()` will return
3355     /// true. Likewise, if an expression is known to diverge, inspecting its
3356     /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
3357     /// strict, _|_ can appear in the type of an expression that does not,
3358     /// itself, diverge: for example, fn() -> _|_.)
3359     /// Note that inspecting a type's structure *directly* may expose the fact
3360     /// that there are actually multiple representations for `TyError`, so avoid
3361     /// that when err needs to be handled differently.
3362     fn check_expr_with_expectation_and_lvalue_pref(&self,
3363                                                    expr: &'gcx hir::Expr,
3364                                                    expected: Expectation<'tcx>,
3365                                                    lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3366         debug!(">> typechecking: expr={:?} expected={:?}",
3367                expr, expected);
3368
3369         // Warn for expressions after diverging siblings.
3370         self.warn_if_unreachable(expr.id, expr.span, "expression");
3371
3372         // Hide the outer diverging and has_errors flags.
3373         let old_diverges = self.diverges.get();
3374         let old_has_errors = self.has_errors.get();
3375         self.diverges.set(Diverges::Maybe);
3376         self.has_errors.set(false);
3377
3378         let ty = self.check_expr_kind(expr, expected, lvalue_pref);
3379
3380         // Warn for non-block expressions with diverging children.
3381         match expr.node {
3382             hir::ExprBlock(_) |
3383             hir::ExprLoop(..) | hir::ExprWhile(..) |
3384             hir::ExprIf(..) | hir::ExprMatch(..) => {}
3385
3386             _ => self.warn_if_unreachable(expr.id, expr.span, "expression")
3387         }
3388
3389         // Any expression that produces a value of type `!` must have diverged
3390         if ty.is_never() {
3391             self.diverges.set(self.diverges.get() | Diverges::Always);
3392         }
3393
3394         // Record the type, which applies it effects.
3395         // We need to do this after the warning above, so that
3396         // we don't warn for the diverging expression itself.
3397         self.write_ty(expr.id, ty);
3398
3399         // Combine the diverging and has_error flags.
3400         self.diverges.set(self.diverges.get() | old_diverges);
3401         self.has_errors.set(self.has_errors.get() | old_has_errors);
3402
3403         debug!("type of {} is...", self.tcx.hir.node_to_string(expr.id));
3404         debug!("... {:?}, expected is {:?}", ty, expected);
3405
3406         ty
3407     }
3408
3409     fn check_expr_kind(&self,
3410                        expr: &'gcx hir::Expr,
3411                        expected: Expectation<'tcx>,
3412                        lvalue_pref: LvaluePreference) -> Ty<'tcx> {
3413         let tcx = self.tcx;
3414         let id = expr.id;
3415         match expr.node {
3416           hir::ExprBox(ref subexpr) => {
3417             let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
3418                 match ty.sty {
3419                     ty::TyAdt(def, _) if def.is_box()
3420                         => Expectation::rvalue_hint(self, ty.boxed_ty()),
3421                     _ => NoExpectation
3422                 }
3423             });
3424             let referent_ty = self.check_expr_with_expectation(subexpr, expected_inner);
3425             tcx.mk_box(referent_ty)
3426           }
3427
3428           hir::ExprLit(ref lit) => {
3429             self.check_lit(&lit, expected)
3430           }
3431           hir::ExprBinary(op, ref lhs, ref rhs) => {
3432             self.check_binop(expr, op, lhs, rhs)
3433           }
3434           hir::ExprAssignOp(op, ref lhs, ref rhs) => {
3435             self.check_binop_assign(expr, op, lhs, rhs)
3436           }
3437           hir::ExprUnary(unop, ref oprnd) => {
3438             let expected_inner = match unop {
3439                 hir::UnNot | hir::UnNeg => {
3440                     expected
3441                 }
3442                 hir::UnDeref => {
3443                     NoExpectation
3444                 }
3445             };
3446             let lvalue_pref = match unop {
3447                 hir::UnDeref => lvalue_pref,
3448                 _ => NoPreference
3449             };
3450             let mut oprnd_t = self.check_expr_with_expectation_and_lvalue_pref(&oprnd,
3451                                                                                expected_inner,
3452                                                                                lvalue_pref);
3453
3454             if !oprnd_t.references_error() {
3455                 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
3456                 match unop {
3457                     hir::UnDeref => {
3458                         if let Some(mt) = oprnd_t.builtin_deref(true, NoPreference) {
3459                             oprnd_t = mt.ty;
3460                         } else if let Some(ok) = self.try_overloaded_deref(
3461                                 expr.span, oprnd_t, lvalue_pref) {
3462                             let method = self.register_infer_ok_obligations(ok);
3463                             if let ty::TyRef(region, mt) = method.sig.inputs()[0].sty {
3464                                 self.apply_adjustments(oprnd, vec![Adjustment {
3465                                     kind: Adjust::Borrow(AutoBorrow::Ref(region, mt.mutbl)),
3466                                     target: method.sig.inputs()[0]
3467                                 }]);
3468                             }
3469                             oprnd_t = self.make_overloaded_lvalue_return_type(method).ty;
3470                             self.write_method_call(expr.id, method);
3471                         } else {
3472                             self.type_error_message(expr.span, |actual| {
3473                                 format!("type `{}` cannot be \
3474                                         dereferenced", actual)
3475                             }, oprnd_t);
3476                             oprnd_t = tcx.types.err;
3477                         }
3478                     }
3479                     hir::UnNot => {
3480                         let result = self.check_user_unop(expr, oprnd_t, unop);
3481                         // If it's builtin, we can reuse the type, this helps inference.
3482                         if !(oprnd_t.is_integral() || oprnd_t.sty == ty::TyBool) {
3483                             oprnd_t = result;
3484                         }
3485                     }
3486                     hir::UnNeg => {
3487                         let result = self.check_user_unop(expr, oprnd_t, unop);
3488                         // If it's builtin, we can reuse the type, this helps inference.
3489                         if !(oprnd_t.is_integral() || oprnd_t.is_fp()) {
3490                             oprnd_t = result;
3491                         }
3492                     }
3493                 }
3494             }
3495             oprnd_t
3496           }
3497           hir::ExprAddrOf(mutbl, ref oprnd) => {
3498             let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
3499                 match ty.sty {
3500                     ty::TyRef(_, ref mt) | ty::TyRawPtr(ref mt) => {
3501                         if self.tcx.expr_is_lval(&oprnd) {
3502                             // Lvalues may legitimately have unsized types.
3503                             // For example, dereferences of a fat pointer and
3504                             // the last field of a struct can be unsized.
3505                             ExpectHasType(mt.ty)
3506                         } else {
3507                             Expectation::rvalue_hint(self, mt.ty)
3508                         }
3509                     }
3510                     _ => NoExpectation
3511                 }
3512             });
3513             let lvalue_pref = LvaluePreference::from_mutbl(mutbl);
3514             let ty = self.check_expr_with_expectation_and_lvalue_pref(&oprnd, hint, lvalue_pref);
3515
3516             let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
3517             if tm.ty.references_error() {
3518                 tcx.types.err
3519             } else {
3520                 // Note: at this point, we cannot say what the best lifetime
3521                 // is to use for resulting pointer.  We want to use the
3522                 // shortest lifetime possible so as to avoid spurious borrowck
3523                 // errors.  Moreover, the longest lifetime will depend on the
3524                 // precise details of the value whose address is being taken
3525                 // (and how long it is valid), which we don't know yet until type
3526                 // inference is complete.
3527                 //
3528                 // Therefore, here we simply generate a region variable.  The
3529                 // region inferencer will then select the ultimate value.
3530                 // Finally, borrowck is charged with guaranteeing that the
3531                 // value whose address was taken can actually be made to live
3532                 // as long as it needs to live.
3533                 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
3534                 tcx.mk_ref(region, tm)
3535             }
3536           }
3537           hir::ExprPath(ref qpath) => {
3538               let (def, opt_ty, segments) = self.resolve_ty_and_def_ufcs(qpath,
3539                                                                          expr.id, expr.span);
3540               let ty = if def != Def::Err {
3541                   self.instantiate_value_path(segments, opt_ty, def, expr.span, id)
3542               } else {
3543                   self.set_tainted_by_errors();
3544                   tcx.types.err
3545               };
3546
3547               // We always require that the type provided as the value for
3548               // a type parameter outlives the moment of instantiation.
3549               let substs = self.tables.borrow().node_substs(expr.id);
3550               self.add_wf_bounds(substs, expr);
3551
3552               ty
3553           }
3554           hir::ExprInlineAsm(_, ref outputs, ref inputs) => {
3555               for output in outputs {
3556                   self.check_expr(output);
3557               }
3558               for input in inputs {
3559                   self.check_expr(input);
3560               }
3561               tcx.mk_nil()
3562           }
3563           hir::ExprBreak(destination, ref expr_opt) => {
3564               if let Some(target_id) = destination.target_id.opt_id() {
3565                   let (e_ty, e_diverges, cause);
3566                   if let Some(ref e) = *expr_opt {
3567                       // If this is a break with a value, we need to type-check
3568                       // the expression. Get an expected type from the loop context.
3569                       let opt_coerce_to = {
3570                           let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3571                           enclosing_breakables.find_breakable(target_id)
3572                                               .coerce
3573                                               .as_ref()
3574                                               .map(|coerce| coerce.expected_ty())
3575                       };
3576
3577                       // If the loop context is not a `loop { }`, then break with
3578                       // a value is illegal, and `opt_coerce_to` will be `None`.
3579                       // Just set expectation to error in that case.
3580                       let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
3581
3582                       // Recurse without `enclosing_breakables` borrowed.
3583                       e_ty = self.check_expr_with_hint(e, coerce_to);
3584                       e_diverges = self.diverges.get();
3585                       cause = self.misc(e.span);
3586                   } else {
3587                       // Otherwise, this is a break *without* a value. That's
3588                       // always legal, and is equivalent to `break ()`.
3589                       e_ty = tcx.mk_nil();
3590                       e_diverges = Diverges::Maybe;
3591                       cause = self.misc(expr.span);
3592                   }
3593
3594                   // Now that we have type-checked `expr_opt`, borrow
3595                   // the `enclosing_loops` field and let's coerce the
3596                   // type of `expr_opt` into what is expected.
3597                   let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
3598                   let ctxt = enclosing_breakables.find_breakable(target_id);
3599                   if let Some(ref mut coerce) = ctxt.coerce {
3600                       if let Some(ref e) = *expr_opt {
3601                           coerce.coerce(self, &cause, e, e_ty, e_diverges);
3602                       } else {
3603                           assert!(e_ty.is_nil());
3604                           coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
3605                       }
3606                   } else {
3607                       // If `ctxt.coerce` is `None`, we can just ignore
3608                       // the type of the expresison.  This is because
3609                       // either this was a break *without* a value, in
3610                       // which case it is always a legal type (`()`), or
3611                       // else an error would have been flagged by the
3612                       // `loops` pass for using break with an expression
3613                       // where you are not supposed to.
3614                       assert!(expr_opt.is_none() || self.tcx.sess.err_count() > 0);
3615                   }
3616
3617                   ctxt.may_break = true;
3618               } else {
3619                   // Otherwise, we failed to find the enclosing loop;
3620                   // this can only happen if the `break` was not
3621                   // inside a loop at all, which is caught by the
3622                   // loop-checking pass.
3623                   assert!(self.tcx.sess.err_count() > 0);
3624               }
3625
3626               // the type of a `break` is always `!`, since it diverges
3627               tcx.types.never
3628           }
3629           hir::ExprAgain(_) => { tcx.types.never }
3630           hir::ExprRet(ref expr_opt) => {
3631             if self.ret_coercion.is_none() {
3632                 struct_span_err!(self.tcx.sess, expr.span, E0572,
3633                                  "return statement outside of function body").emit();
3634             } else if let Some(ref e) = *expr_opt {
3635                 self.check_return_expr(e);
3636             } else {
3637                 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
3638                 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
3639                 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
3640             }
3641             tcx.types.never
3642           }
3643           hir::ExprAssign(ref lhs, ref rhs) => {
3644             let lhs_ty = self.check_expr_with_lvalue_pref(&lhs, PreferMutLvalue);
3645
3646             let tcx = self.tcx;
3647             if !tcx.expr_is_lval(&lhs) {
3648                 struct_span_err!(
3649                     tcx.sess, expr.span, E0070,
3650                     "invalid left-hand side expression")
3651                 .span_label(
3652                     expr.span,
3653                     "left-hand of expression not valid")
3654                 .emit();
3655             }
3656
3657             let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
3658
3659             self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
3660
3661             if lhs_ty.references_error() || rhs_ty.references_error() {
3662                 tcx.types.err
3663             } else {
3664                 tcx.mk_nil()
3665             }
3666           }
3667           hir::ExprIf(ref cond, ref then_expr, ref opt_else_expr) => {
3668               self.check_then_else(&cond, then_expr, opt_else_expr.as_ref().map(|e| &**e),
3669                                    expr.span, expected)
3670           }
3671           hir::ExprWhile(ref cond, ref body, _) => {
3672               let ctxt = BreakableCtxt {
3673                   // cannot use break with a value from a while loop
3674                   coerce: None,
3675                   may_break: true,
3676               };
3677
3678               self.with_breakable_ctxt(expr.id, ctxt, || {
3679                   self.check_expr_has_type(&cond, tcx.types.bool);
3680                   let cond_diverging = self.diverges.get();
3681                   self.check_block_no_value(&body);
3682
3683                   // We may never reach the body so it diverging means nothing.
3684                   self.diverges.set(cond_diverging);
3685               });
3686
3687               self.tcx.mk_nil()
3688           }
3689           hir::ExprLoop(ref body, _, source) => {
3690               let coerce = match source {
3691                   // you can only use break with a value from a normal `loop { }`
3692                   hir::LoopSource::Loop => {
3693                       let coerce_to = expected.coercion_target_type(self, body.span);
3694                       Some(CoerceMany::new(coerce_to))
3695                   }
3696
3697                   hir::LoopSource::WhileLet |
3698                   hir::LoopSource::ForLoop => {
3699                       None
3700                   }
3701               };
3702
3703               let ctxt = BreakableCtxt {
3704                   coerce: coerce,
3705                   may_break: false, // will get updated if/when we find a `break`
3706               };
3707
3708               let (ctxt, ()) = self.with_breakable_ctxt(expr.id, ctxt, || {
3709                   self.check_block_no_value(&body);
3710               });
3711
3712               if ctxt.may_break {
3713                   // No way to know whether it's diverging because
3714                   // of a `break` or an outer `break` or `return.
3715                   self.diverges.set(Diverges::Maybe);
3716               }
3717
3718               // If we permit break with a value, then result type is
3719               // the LUB of the breaks (possibly ! if none); else, it
3720               // is nil. This makes sense because infinite loops
3721               // (which would have type !) are only possible iff we
3722               // permit break with a value [1].
3723               assert!(ctxt.coerce.is_some() || ctxt.may_break); // [1]
3724               ctxt.coerce.map(|c| c.complete(self)).unwrap_or(self.tcx.mk_nil())
3725           }
3726           hir::ExprMatch(ref discrim, ref arms, match_src) => {
3727             self.check_match(expr, &discrim, arms, expected, match_src)
3728           }
3729           hir::ExprClosure(capture, ref decl, body_id, _) => {
3730               self.check_expr_closure(expr, capture, &decl, body_id, expected)
3731           }
3732           hir::ExprBlock(ref body) => {
3733             self.check_block_with_expected(&body, expected)
3734           }
3735           hir::ExprCall(ref callee, ref args) => {
3736               self.check_call(expr, &callee, args, expected)
3737           }
3738           hir::ExprMethodCall(name, ref tps, ref args) => {
3739               self.check_method_call(expr, name, args, &tps[..], expected, lvalue_pref)
3740           }
3741           hir::ExprCast(ref e, ref t) => {
3742             // Find the type of `e`. Supply hints based on the type we are casting to,
3743             // if appropriate.
3744             let t_cast = self.to_ty(t);
3745             let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3746             let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
3747             let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3748             let diverges = self.diverges.get();
3749
3750             // Eagerly check for some obvious errors.
3751             if t_expr.references_error() || t_cast.references_error() {
3752                 tcx.types.err
3753             } else {
3754                 // Defer other checks until we're done type checking.
3755                 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
3756                 match cast::CastCheck::new(self, e, t_expr, diverges, t_cast, t.span, expr.span) {
3757                     Ok(cast_check) => {
3758                         deferred_cast_checks.push(cast_check);
3759                         t_cast
3760                     }
3761                     Err(ErrorReported) => {
3762                         tcx.types.err
3763                     }
3764                 }
3765             }
3766           }
3767           hir::ExprType(ref e, ref t) => {
3768             let typ = self.to_ty(&t);
3769             self.check_expr_eq_type(&e, typ);
3770             typ
3771           }
3772           hir::ExprArray(ref args) => {
3773               let uty = expected.to_option(self).and_then(|uty| {
3774                   match uty.sty {
3775                       ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3776                       _ => None
3777                   }
3778               });
3779
3780               let element_ty = if !args.is_empty() {
3781                   let coerce_to = uty.unwrap_or_else(
3782                       || self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span)));
3783                   let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
3784                   assert_eq!(self.diverges.get(), Diverges::Maybe);
3785                   for e in args {
3786                       let e_ty = self.check_expr_with_hint(e, coerce_to);
3787                       let cause = self.misc(e.span);
3788                       coerce.coerce(self, &cause, e, e_ty, self.diverges.get());
3789                   }
3790                   coerce.complete(self)
3791               } else {
3792                   self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span))
3793               };
3794               tcx.mk_array(element_ty, args.len())
3795           }
3796           hir::ExprRepeat(ref element, count) => {
3797             let count = eval_length(self.tcx, count, "repeat count")
3798                   .unwrap_or(0);
3799
3800             let uty = match expected {
3801                 ExpectHasType(uty) => {
3802                     match uty.sty {
3803                         ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3804                         _ => None
3805                     }
3806                 }
3807                 _ => None
3808             };
3809
3810             let (element_ty, t) = match uty {
3811                 Some(uty) => {
3812                     self.check_expr_coercable_to_type(&element, uty);
3813                     (uty, uty)
3814                 }
3815                 None => {
3816                     let t: Ty = self.next_ty_var(TypeVariableOrigin::MiscVariable(element.span));
3817                     let element_ty = self.check_expr_has_type(&element, t);
3818                     (element_ty, t)
3819                 }
3820             };
3821
3822             if count > 1 {
3823                 // For [foo, ..n] where n > 1, `foo` must have
3824                 // Copy type:
3825                 let lang_item = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
3826                 self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
3827             }
3828
3829             if element_ty.references_error() {
3830                 tcx.types.err
3831             } else {
3832                 tcx.mk_array(t, count)
3833             }
3834           }
3835           hir::ExprTup(ref elts) => {
3836             let flds = expected.only_has_type(self).and_then(|ty| {
3837                 match ty.sty {
3838                     ty::TyTuple(ref flds, _) => Some(&flds[..]),
3839                     _ => None
3840                 }
3841             });
3842
3843             let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
3844                 let t = match flds {
3845                     Some(ref fs) if i < fs.len() => {
3846                         let ety = fs[i];
3847                         self.check_expr_coercable_to_type(&e, ety);
3848                         ety
3849                     }
3850                     _ => {
3851                         self.check_expr_with_expectation(&e, NoExpectation)
3852                     }
3853                 };
3854                 t
3855             });
3856             let tuple = tcx.mk_tup(elt_ts_iter, false);
3857             if tuple.references_error() {
3858                 tcx.types.err
3859             } else {
3860                 tuple
3861             }
3862           }
3863           hir::ExprStruct(ref qpath, ref fields, ref base_expr) => {
3864             self.check_expr_struct(expr, expected, qpath, fields, base_expr)
3865           }
3866           hir::ExprField(ref base, ref field) => {
3867             self.check_field(expr, lvalue_pref, &base, field)
3868           }
3869           hir::ExprTupField(ref base, idx) => {
3870             self.check_tup_field(expr, lvalue_pref, &base, idx)
3871           }
3872           hir::ExprIndex(ref base, ref idx) => {
3873               let base_t = self.check_expr_with_lvalue_pref(&base, lvalue_pref);
3874               let idx_t = self.check_expr(&idx);
3875
3876               if base_t.references_error() {
3877                   base_t
3878               } else if idx_t.references_error() {
3879                   idx_t
3880               } else {
3881                   let base_t = self.structurally_resolved_type(expr.span, base_t);
3882                   match self.lookup_indexing(expr, base, base_t, idx_t, lvalue_pref) {
3883                       Some((index_ty, element_ty)) => {
3884                           self.demand_coerce(idx, idx_t, index_ty);
3885                           element_ty
3886                       }
3887                       None => {
3888                           let mut err = self.type_error_struct(
3889                               expr.span,
3890                               |actual| {
3891                                   format!("cannot index a value of type `{}`",
3892                                           actual)
3893                               },
3894                               base_t);
3895                           // Try to give some advice about indexing tuples.
3896                           if let ty::TyTuple(..) = base_t.sty {
3897                               let mut needs_note = true;
3898                               // If the index is an integer, we can show the actual
3899                               // fixed expression:
3900                               if let hir::ExprLit(ref lit) = idx.node {
3901                                   if let ast::LitKind::Int(i,
3902                                             ast::LitIntType::Unsuffixed) = lit.node {
3903                                       let snip = tcx.sess.codemap().span_to_snippet(base.span);
3904                                       if let Ok(snip) = snip {
3905                                           err.span_suggestion(expr.span,
3906                                                               "to access tuple elements, use",
3907                                                               format!("{}.{}", snip, i));
3908                                           needs_note = false;
3909                                       }
3910                                   }
3911                               }
3912                               if needs_note {
3913                                   err.help("to access tuple elements, use tuple indexing \
3914                                             syntax (e.g. `tuple.0`)");
3915                               }
3916                           }
3917                           err.emit();
3918                           self.tcx.types.err
3919                       }
3920                   }
3921               }
3922            }
3923         }
3924     }
3925
3926     // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
3927     // The newly resolved definition is written into `type_dependent_defs`.
3928     fn finish_resolving_struct_path(&self,
3929                                     qpath: &hir::QPath,
3930                                     path_span: Span,
3931                                     node_id: ast::NodeId)
3932                                     -> (Def, Ty<'tcx>)
3933     {
3934         match *qpath {
3935             hir::QPath::Resolved(ref maybe_qself, ref path) => {
3936                 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself));
3937                 let ty = AstConv::def_to_ty(self, opt_self_ty, path, true);
3938                 (path.def, ty)
3939             }
3940             hir::QPath::TypeRelative(ref qself, ref segment) => {
3941                 let ty = self.to_ty(qself);
3942
3943                 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
3944                     path.def
3945                 } else {
3946                     Def::Err
3947                 };
3948                 let (ty, def) = AstConv::associated_path_def_to_ty(self, node_id, path_span,
3949                                                                    ty, def, segment);
3950
3951                 // Write back the new resolution.
3952                 self.tables.borrow_mut().type_dependent_defs.insert(node_id, def);
3953
3954                 (def, ty)
3955             }
3956         }
3957     }
3958
3959     // Resolve associated value path into a base type and associated constant or method definition.
3960     // The newly resolved definition is written into `type_dependent_defs`.
3961     pub fn resolve_ty_and_def_ufcs<'b>(&self,
3962                                        qpath: &'b hir::QPath,
3963                                        node_id: ast::NodeId,
3964                                        span: Span)
3965                                        -> (Def, Option<Ty<'tcx>>, &'b [hir::PathSegment])
3966     {
3967         let (ty, item_segment) = match *qpath {
3968             hir::QPath::Resolved(ref opt_qself, ref path) => {
3969                 return (path.def,
3970                         opt_qself.as_ref().map(|qself| self.to_ty(qself)),
3971                         &path.segments[..]);
3972             }
3973             hir::QPath::TypeRelative(ref qself, ref segment) => {
3974                 (self.to_ty(qself), segment)
3975             }
3976         };
3977         let item_name = item_segment.name;
3978         let def = match self.resolve_ufcs(span, item_name, ty, node_id) {
3979             Ok(def) => def,
3980             Err(error) => {
3981                 let def = match error {
3982                     method::MethodError::PrivateMatch(def) => def,
3983                     _ => Def::Err,
3984                 };
3985                 if item_name != keywords::Invalid.name() {
3986                     self.report_method_error(span, ty, item_name, None, error, None);
3987                 }
3988                 def
3989             }
3990         };
3991
3992         // Write back the new resolution.
3993         self.tables.borrow_mut().type_dependent_defs.insert(node_id, def);
3994         (def, Some(ty), slice::ref_slice(&**item_segment))
3995     }
3996
3997     pub fn check_decl_initializer(&self,
3998                                   local: &'gcx hir::Local,
3999                                   init: &'gcx hir::Expr) -> Ty<'tcx>
4000     {
4001         let ref_bindings = local.pat.contains_ref_binding();
4002
4003         let local_ty = self.local_ty(init.span, local.id);
4004         if let Some(m) = ref_bindings {
4005             // Somewhat subtle: if we have a `ref` binding in the pattern,
4006             // we want to avoid introducing coercions for the RHS. This is
4007             // both because it helps preserve sanity and, in the case of
4008             // ref mut, for soundness (issue #23116). In particular, in
4009             // the latter case, we need to be clear that the type of the
4010             // referent for the reference that results is *equal to* the
4011             // type of the lvalue it is referencing, and not some
4012             // supertype thereof.
4013             let init_ty = self.check_expr_with_lvalue_pref(init, LvaluePreference::from_mutbl(m));
4014             self.demand_eqtype(init.span, init_ty, local_ty);
4015             init_ty
4016         } else {
4017             self.check_expr_coercable_to_type(init, local_ty)
4018         }
4019     }
4020
4021     pub fn check_decl_local(&self, local: &'gcx hir::Local)  {
4022         let t = self.local_ty(local.span, local.id);
4023         self.write_ty(local.id, t);
4024
4025         if let Some(ref init) = local.init {
4026             let init_ty = self.check_decl_initializer(local, &init);
4027             if init_ty.references_error() {
4028                 self.write_ty(local.id, init_ty);
4029             }
4030         }
4031
4032         self.check_pat(&local.pat, t);
4033         let pat_ty = self.node_ty(local.pat.id);
4034         if pat_ty.references_error() {
4035             self.write_ty(local.id, pat_ty);
4036         }
4037     }
4038
4039     pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) {
4040         // Don't do all the complex logic below for DeclItem.
4041         match stmt.node {
4042             hir::StmtDecl(ref decl, _) => {
4043                 match decl.node {
4044                     hir::DeclLocal(_) => {}
4045                     hir::DeclItem(_) => {
4046                         return;
4047                     }
4048                 }
4049             }
4050             hir::StmtExpr(..) | hir::StmtSemi(..) => {}
4051         }
4052
4053         self.warn_if_unreachable(stmt.node.id(), stmt.span, "statement");
4054
4055         // Hide the outer diverging and has_errors flags.
4056         let old_diverges = self.diverges.get();
4057         let old_has_errors = self.has_errors.get();
4058         self.diverges.set(Diverges::Maybe);
4059         self.has_errors.set(false);
4060
4061         match stmt.node {
4062             hir::StmtDecl(ref decl, _) => {
4063                 match decl.node {
4064                     hir::DeclLocal(ref l) => {
4065                         self.check_decl_local(&l);
4066                     }
4067                     hir::DeclItem(_) => {/* ignore for now */}
4068                 }
4069             }
4070             hir::StmtExpr(ref expr, _) => {
4071                 // Check with expected type of ()
4072                 self.check_expr_has_type(&expr, self.tcx.mk_nil());
4073             }
4074             hir::StmtSemi(ref expr, _) => {
4075                 self.check_expr(&expr);
4076             }
4077         }
4078
4079         // Combine the diverging and has_error flags.
4080         self.diverges.set(self.diverges.get() | old_diverges);
4081         self.has_errors.set(self.has_errors.get() | old_has_errors);
4082     }
4083
4084     pub fn check_block_no_value(&self, blk: &'gcx hir::Block)  {
4085         let unit = self.tcx.mk_nil();
4086         let ty = self.check_block_with_expected(blk, ExpectHasType(unit));
4087
4088         // if the block produces a `!` value, that can always be
4089         // (effectively) coerced to unit.
4090         if !ty.is_never() {
4091             self.demand_suptype(blk.span, unit, ty);
4092         }
4093     }
4094
4095     fn check_block_with_expected(&self,
4096                                  blk: &'gcx hir::Block,
4097                                  expected: Expectation<'tcx>) -> Ty<'tcx> {
4098         let prev = {
4099             let mut fcx_ps = self.ps.borrow_mut();
4100             let unsafety_state = fcx_ps.recurse(blk);
4101             replace(&mut *fcx_ps, unsafety_state)
4102         };
4103
4104         // In some cases, blocks have just one exit, but other blocks
4105         // can be targeted by multiple breaks. This cannot happen in
4106         // normal Rust syntax today, but it can happen when we desugar
4107         // a `do catch { ... }` expression.
4108         //
4109         // Example 1:
4110         //
4111         //    'a: { if true { break 'a Err(()); } Ok(()) }
4112         //
4113         // Here we would wind up with two coercions, one from
4114         // `Err(())` and the other from the tail expression
4115         // `Ok(())`. If the tail expression is omitted, that's a
4116         // "forced unit" -- unless the block diverges, in which
4117         // case we can ignore the tail expression (e.g., `'a: {
4118         // break 'a 22; }` would not force the type of the block
4119         // to be `()`).
4120         let tail_expr = blk.expr.as_ref();
4121         let coerce_to_ty = expected.coercion_target_type(self, blk.span);
4122         let coerce = if blk.targeted_by_break {
4123             CoerceMany::new(coerce_to_ty)
4124         } else {
4125             let tail_expr: &[P<hir::Expr>] = match tail_expr {
4126                 Some(e) => ref_slice(e),
4127                 None => &[],
4128             };
4129             CoerceMany::with_coercion_sites(coerce_to_ty, tail_expr)
4130         };
4131
4132         let ctxt = BreakableCtxt {
4133             coerce: Some(coerce),
4134             may_break: false,
4135         };
4136
4137         let (ctxt, ()) = self.with_breakable_ctxt(blk.id, ctxt, || {
4138             for s in &blk.stmts {
4139                 self.check_stmt(s);
4140             }
4141
4142             // check the tail expression **without** holding the
4143             // `enclosing_breakables` lock below.
4144             let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected));
4145
4146             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4147             let mut ctxt = enclosing_breakables.find_breakable(blk.id);
4148             let mut coerce = ctxt.coerce.as_mut().unwrap();
4149             if let Some(tail_expr_ty) = tail_expr_ty {
4150                 let tail_expr = tail_expr.unwrap();
4151                 coerce.coerce(self,
4152                               &self.misc(tail_expr.span),
4153                               tail_expr,
4154                               tail_expr_ty,
4155                               self.diverges.get());
4156             } else {
4157                 // Subtle: if there is no explicit tail expression,
4158                 // that is typically equivalent to a tail expression
4159                 // of `()` -- except if the block diverges. In that
4160                 // case, there is no value supplied from the tail
4161                 // expression (assuming there are no other breaks,
4162                 // this implies that the type of the block will be
4163                 // `!`).
4164                 //
4165                 // #41425 -- label the implicit `()` as being the
4166                 // "found type" here, rather than the "expected type".
4167                 if !self.diverges.get().always() {
4168                     coerce.coerce_forced_unit(self, &self.misc(blk.span), &mut |err| {
4169                         if let Some(expected_ty) = expected.only_has_type(self) {
4170                             self.consider_hint_about_removing_semicolon(blk,
4171                                                                         expected_ty,
4172                                                                         err);
4173                         }
4174                     }, false);
4175                 }
4176             }
4177         });
4178
4179         let mut ty = ctxt.coerce.unwrap().complete(self);
4180
4181         if self.has_errors.get() || ty.references_error() {
4182             ty = self.tcx.types.err
4183         }
4184
4185         self.write_ty(blk.id, ty);
4186
4187         *self.ps.borrow_mut() = prev;
4188         ty
4189     }
4190
4191     /// A common error is to add an extra semicolon:
4192     ///
4193     /// ```
4194     /// fn foo() -> usize {
4195     ///     22;
4196     /// }
4197     /// ```
4198     ///
4199     /// This routine checks if the final statement in a block is an
4200     /// expression with an explicit semicolon whose type is compatible
4201     /// with `expected_ty`. If so, it suggests removing the semicolon.
4202     fn consider_hint_about_removing_semicolon(&self,
4203                                               blk: &'gcx hir::Block,
4204                                               expected_ty: Ty<'tcx>,
4205                                               err: &mut DiagnosticBuilder) {
4206         // Be helpful when the user wrote `{... expr;}` and
4207         // taking the `;` off is enough to fix the error.
4208         let last_stmt = match blk.stmts.last() {
4209             Some(s) => s,
4210             None => return,
4211         };
4212         let last_expr = match last_stmt.node {
4213             hir::StmtSemi(ref e, _) => e,
4214             _ => return,
4215         };
4216         let last_expr_ty = self.node_ty(last_expr.id);
4217         if self.can_sub(self.param_env, last_expr_ty, expected_ty).is_err() {
4218             return;
4219         }
4220         let original_span = original_sp(last_stmt.span, blk.span);
4221         let span_semi = Span {
4222             lo: original_span.hi - BytePos(1),
4223             hi: original_span.hi,
4224             ctxt: original_span.ctxt,
4225         };
4226         err.span_help(span_semi, "consider removing this semicolon:");
4227     }
4228
4229     // Instantiates the given path, which must refer to an item with the given
4230     // number of type parameters and type.
4231     pub fn instantiate_value_path(&self,
4232                                   segments: &[hir::PathSegment],
4233                                   opt_self_ty: Option<Ty<'tcx>>,
4234                                   def: Def,
4235                                   span: Span,
4236                                   node_id: ast::NodeId)
4237                                   -> Ty<'tcx> {
4238         debug!("instantiate_value_path(path={:?}, def={:?}, node_id={})",
4239                segments,
4240                def,
4241                node_id);
4242
4243         // We need to extract the type parameters supplied by the user in
4244         // the path `path`. Due to the current setup, this is a bit of a
4245         // tricky-process; the problem is that resolve only tells us the
4246         // end-point of the path resolution, and not the intermediate steps.
4247         // Luckily, we can (at least for now) deduce the intermediate steps
4248         // just from the end-point.
4249         //
4250         // There are basically four cases to consider:
4251         //
4252         // 1. Reference to a constructor of enum variant or struct:
4253         //
4254         //        struct Foo<T>(...)
4255         //        enum E<T> { Foo(...) }
4256         //
4257         //    In these cases, the parameters are declared in the type
4258         //    space.
4259         //
4260         // 2. Reference to a fn item or a free constant:
4261         //
4262         //        fn foo<T>() { }
4263         //
4264         //    In this case, the path will again always have the form
4265         //    `a::b::foo::<T>` where only the final segment should have
4266         //    type parameters. However, in this case, those parameters are
4267         //    declared on a value, and hence are in the `FnSpace`.
4268         //
4269         // 3. Reference to a method or an associated constant:
4270         //
4271         //        impl<A> SomeStruct<A> {
4272         //            fn foo<B>(...)
4273         //        }
4274         //
4275         //    Here we can have a path like
4276         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
4277         //    may appear in two places. The penultimate segment,
4278         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
4279         //    final segment, `foo::<B>` contains parameters in fn space.
4280         //
4281         // 4. Reference to a local variable
4282         //
4283         //    Local variables can't have any type parameters.
4284         //
4285         // The first step then is to categorize the segments appropriately.
4286
4287         assert!(!segments.is_empty());
4288
4289         let mut ufcs_associated = None;
4290         let mut type_segment = None;
4291         let mut fn_segment = None;
4292         match def {
4293             // Case 1. Reference to a struct/variant constructor.
4294             Def::StructCtor(def_id, ..) |
4295             Def::VariantCtor(def_id, ..) => {
4296                 // Everything but the final segment should have no
4297                 // parameters at all.
4298                 let mut generics = self.tcx.generics_of(def_id);
4299                 if let Some(def_id) = generics.parent {
4300                     // Variant and struct constructors use the
4301                     // generics of their parent type definition.
4302                     generics = self.tcx.generics_of(def_id);
4303                 }
4304                 type_segment = Some((segments.last().unwrap(), generics));
4305             }
4306
4307             // Case 2. Reference to a top-level value.
4308             Def::Fn(def_id) |
4309             Def::Const(def_id) |
4310             Def::Static(def_id, _) => {
4311                 fn_segment = Some((segments.last().unwrap(),
4312                                    self.tcx.generics_of(def_id)));
4313             }
4314
4315             // Case 3. Reference to a method or associated const.
4316             Def::Method(def_id) |
4317             Def::AssociatedConst(def_id) => {
4318                 let container = self.tcx.associated_item(def_id).container;
4319                 match container {
4320                     ty::TraitContainer(trait_did) => {
4321                         callee::check_legal_trait_for_method_call(self.tcx, span, trait_did)
4322                     }
4323                     ty::ImplContainer(_) => {}
4324                 }
4325
4326                 let generics = self.tcx.generics_of(def_id);
4327                 if segments.len() >= 2 {
4328                     let parent_generics = self.tcx.generics_of(generics.parent.unwrap());
4329                     type_segment = Some((&segments[segments.len() - 2], parent_generics));
4330                 } else {
4331                     // `<T>::assoc` will end up here, and so can `T::assoc`.
4332                     let self_ty = opt_self_ty.expect("UFCS sugared assoc missing Self");
4333                     ufcs_associated = Some((container, self_ty));
4334                 }
4335                 fn_segment = Some((segments.last().unwrap(), generics));
4336             }
4337
4338             // Case 4. Local variable, no generics.
4339             Def::Local(..) | Def::Upvar(..) => {}
4340
4341             _ => bug!("unexpected definition: {:?}", def),
4342         }
4343
4344         debug!("type_segment={:?} fn_segment={:?}", type_segment, fn_segment);
4345
4346         // Now that we have categorized what space the parameters for each
4347         // segment belong to, let's sort out the parameters that the user
4348         // provided (if any) into their appropriate spaces. We'll also report
4349         // errors if type parameters are provided in an inappropriate place.
4350         let poly_segments = type_segment.is_some() as usize +
4351                             fn_segment.is_some() as usize;
4352         AstConv::prohibit_type_params(self, &segments[..segments.len() - poly_segments]);
4353
4354         match def {
4355             Def::Local(def_id) | Def::Upvar(def_id, ..) => {
4356                 let nid = self.tcx.hir.as_local_node_id(def_id).unwrap();
4357                 let ty = self.local_ty(span, nid);
4358                 let ty = self.normalize_associated_types_in(span, &ty);
4359                 self.write_ty(node_id, ty);
4360                 return ty;
4361             }
4362             _ => {}
4363         }
4364
4365         // Now we have to compare the types that the user *actually*
4366         // provided against the types that were *expected*. If the user
4367         // did not provide any types, then we want to substitute inference
4368         // variables. If the user provided some types, we may still need
4369         // to add defaults. If the user provided *too many* types, that's
4370         // a problem.
4371         self.check_path_parameter_count(span, &mut type_segment);
4372         self.check_path_parameter_count(span, &mut fn_segment);
4373
4374         let (fn_start, has_self) = match (type_segment, fn_segment) {
4375             (_, Some((_, generics))) => {
4376                 (generics.parent_count(), generics.has_self)
4377             }
4378             (Some((_, generics)), None) => {
4379                 (generics.own_count(), generics.has_self)
4380             }
4381             (None, None) => (0, false)
4382         };
4383         let substs = Substs::for_item(self.tcx, def.def_id(), |def, _| {
4384             let mut i = def.index as usize;
4385
4386             let segment = if i < fn_start {
4387                 i -= has_self as usize;
4388                 type_segment
4389             } else {
4390                 i -= fn_start;
4391                 fn_segment
4392             };
4393             let lifetimes = match segment.map(|(s, _)| &s.parameters) {
4394                 Some(&hir::AngleBracketedParameters(ref data)) => &data.lifetimes[..],
4395                 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4396                 None => &[]
4397             };
4398
4399             if let Some(lifetime) = lifetimes.get(i) {
4400                 AstConv::ast_region_to_region(self, lifetime, Some(def))
4401             } else {
4402                 self.re_infer(span, Some(def)).unwrap()
4403             }
4404         }, |def, substs| {
4405             let mut i = def.index as usize;
4406
4407             let segment = if i < fn_start {
4408                 // Handle Self first, so we can adjust the index to match the AST.
4409                 if has_self && i == 0 {
4410                     return opt_self_ty.unwrap_or_else(|| {
4411                         self.type_var_for_def(span, def, substs)
4412                     });
4413                 }
4414                 i -= has_self as usize;
4415                 type_segment
4416             } else {
4417                 i -= fn_start;
4418                 fn_segment
4419             };
4420             let (types, infer_types) = match segment.map(|(s, _)| &s.parameters) {
4421                 Some(&hir::AngleBracketedParameters(ref data)) => {
4422                     (&data.types[..], data.infer_types)
4423                 }
4424                 Some(&hir::ParenthesizedParameters(_)) => bug!(),
4425                 None => (&[][..], true)
4426             };
4427
4428             // Skip over the lifetimes in the same segment.
4429             if let Some((_, generics)) = segment {
4430                 i -= generics.regions.len();
4431             }
4432
4433             if let Some(ast_ty) = types.get(i) {
4434                 // A provided type parameter.
4435                 self.to_ty(ast_ty)
4436             } else if !infer_types && def.has_default {
4437                 // No type parameter provided, but a default exists.
4438                 let default = self.tcx.type_of(def.def_id);
4439                 self.normalize_ty(
4440                     span,
4441                     default.subst_spanned(self.tcx, substs, Some(span))
4442                 )
4443             } else {
4444                 // No type parameters were provided, we can infer all.
4445                 // This can also be reached in some error cases:
4446                 // We prefer to use inference variables instead of
4447                 // TyError to let type inference recover somewhat.
4448                 self.type_var_for_def(span, def, substs)
4449             }
4450         });
4451
4452         // The things we are substituting into the type should not contain
4453         // escaping late-bound regions, and nor should the base type scheme.
4454         let ty = self.tcx.type_of(def.def_id());
4455         assert!(!substs.has_escaping_regions());
4456         assert!(!ty.has_escaping_regions());
4457
4458         // Add all the obligations that are required, substituting and
4459         // normalized appropriately.
4460         let bounds = self.instantiate_bounds(span, def.def_id(), &substs);
4461         self.add_obligations_for_parameters(
4462             traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def.def_id())),
4463             &bounds);
4464
4465         // Substitute the values for the type parameters into the type of
4466         // the referenced item.
4467         let ty_substituted = self.instantiate_type_scheme(span, &substs, &ty);
4468
4469         if let Some((ty::ImplContainer(impl_def_id), self_ty)) = ufcs_associated {
4470             // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
4471             // is inherent, there is no `Self` parameter, instead, the impl needs
4472             // type parameters, which we can infer by unifying the provided `Self`
4473             // with the substituted impl type.
4474             let ty = self.tcx.type_of(impl_def_id);
4475
4476             let impl_ty = self.instantiate_type_scheme(span, &substs, &ty);
4477             match self.at(&self.misc(span), self.param_env).sup(impl_ty, self_ty) {
4478                 Ok(ok) => self.register_infer_ok_obligations(ok),
4479                 Err(_) => {
4480                     span_bug!(span,
4481                         "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
4482                         self_ty,
4483                         impl_ty);
4484                 }
4485             }
4486         }
4487
4488         debug!("instantiate_value_path: type of {:?} is {:?}",
4489                node_id,
4490                ty_substituted);
4491         self.write_substs(node_id, substs);
4492         ty_substituted
4493     }
4494
4495     /// Report errors if the provided parameters are too few or too many.
4496     fn check_path_parameter_count(&self,
4497                                   span: Span,
4498                                   segment: &mut Option<(&hir::PathSegment, &ty::Generics)>) {
4499         let (lifetimes, types, infer_types, bindings) = {
4500             match segment.map(|(s, _)| &s.parameters) {
4501                 Some(&hir::AngleBracketedParameters(ref data)) => {
4502                     (&data.lifetimes[..], &data.types[..], data.infer_types, &data.bindings[..])
4503                 }
4504                 Some(&hir::ParenthesizedParameters(_)) => {
4505                     AstConv::prohibit_parenthesized_params(self, &segment.as_ref().unwrap().0,
4506                                                            false);
4507                     (&[][..], &[][..], true, &[][..])
4508                 }
4509                 None => (&[][..], &[][..], true, &[][..])
4510             }
4511         };
4512
4513         let count_lifetime_params = |n| {
4514             format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" })
4515         };
4516         let count_type_params = |n| {
4517             format!("{} type parameter{}", n, if n == 1 { "" } else { "s" })
4518         };
4519
4520         // Check provided lifetime parameters.
4521         let lifetime_defs = segment.map_or(&[][..], |(_, generics)| &generics.regions);
4522         if lifetimes.len() > lifetime_defs.len() {
4523             let expected_text = count_lifetime_params(lifetime_defs.len());
4524             let actual_text = count_lifetime_params(lifetimes.len());
4525             struct_span_err!(self.tcx.sess, span, E0088,
4526                              "too many lifetime parameters provided: \
4527                               expected at most {}, found {}",
4528                              expected_text, actual_text)
4529                 .span_label(span, format!("expected {}", expected_text))
4530                 .emit();
4531         } else if lifetimes.len() > 0 && lifetimes.len() < lifetime_defs.len() {
4532             let expected_text = count_lifetime_params(lifetime_defs.len());
4533             let actual_text = count_lifetime_params(lifetimes.len());
4534             struct_span_err!(self.tcx.sess, span, E0090,
4535                              "too few lifetime parameters provided: \
4536                               expected {}, found {}",
4537                              expected_text, actual_text)
4538                 .span_label(span, format!("expected {}", expected_text))
4539                 .emit();
4540         }
4541
4542         // The case where there is not enough lifetime parameters is not checked,
4543         // because this is not possible - a function never takes lifetime parameters.
4544         // See discussion for Pull Request 36208.
4545
4546         // Check provided type parameters.
4547         let type_defs = segment.map_or(&[][..], |(_, generics)| {
4548             if generics.parent.is_none() {
4549                 &generics.types[generics.has_self as usize..]
4550             } else {
4551                 &generics.types
4552             }
4553         });
4554         let required_len = type_defs.iter().take_while(|d| !d.has_default).count();
4555         if types.len() > type_defs.len() {
4556             let span = types[type_defs.len()].span;
4557             let expected_text = count_type_params(type_defs.len());
4558             let actual_text = count_type_params(types.len());
4559             struct_span_err!(self.tcx.sess, span, E0087,
4560                              "too many type parameters provided: \
4561                               expected at most {}, found {}",
4562                              expected_text, actual_text)
4563                 .span_label(span, format!("expected {}", expected_text))
4564                 .emit();
4565
4566             // To prevent derived errors to accumulate due to extra
4567             // type parameters, we force instantiate_value_path to
4568             // use inference variables instead of the provided types.
4569             *segment = None;
4570         } else if !infer_types && types.len() < required_len {
4571             let expected_text = count_type_params(required_len);
4572             let actual_text = count_type_params(types.len());
4573             struct_span_err!(self.tcx.sess, span, E0089,
4574                              "too few type parameters provided: \
4575                               expected {}, found {}",
4576                              expected_text, actual_text)
4577                 .span_label(span, format!("expected {}", expected_text))
4578                 .emit();
4579         }
4580
4581         if !bindings.is_empty() {
4582             span_err!(self.tcx.sess, bindings[0].span, E0182,
4583                       "unexpected binding of associated item in expression path \
4584                        (only allowed in type paths)");
4585         }
4586     }
4587
4588     fn structurally_resolve_type_or_else<F>(&self, sp: Span, ty: Ty<'tcx>, f: F)
4589                                             -> Ty<'tcx>
4590         where F: Fn() -> Ty<'tcx>
4591     {
4592         let mut ty = self.resolve_type_vars_with_obligations(ty);
4593
4594         if ty.is_ty_var() {
4595             let alternative = f();
4596
4597             // If not, error.
4598             if alternative.is_ty_var() || alternative.references_error() {
4599                 if !self.is_tainted_by_errors() {
4600                     self.type_error_message(sp, |_actual| {
4601                         "the type of this value must be known in this context".to_string()
4602                     }, ty);
4603                 }
4604                 self.demand_suptype(sp, self.tcx.types.err, ty);
4605                 ty = self.tcx.types.err;
4606             } else {
4607                 self.demand_suptype(sp, alternative, ty);
4608                 ty = alternative;
4609             }
4610         }
4611
4612         ty
4613     }
4614
4615     // Resolves `typ` by a single level if `typ` is a type variable.  If no
4616     // resolution is possible, then an error is reported.
4617     pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
4618         self.structurally_resolve_type_or_else(sp, ty, || {
4619             self.tcx.types.err
4620         })
4621     }
4622
4623     fn with_breakable_ctxt<F: FnOnce() -> R, R>(&self, id: ast::NodeId,
4624                                         ctxt: BreakableCtxt<'gcx, 'tcx>, f: F)
4625                                    -> (BreakableCtxt<'gcx, 'tcx>, R) {
4626         let index;
4627         {
4628             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4629             index = enclosing_breakables.stack.len();
4630             enclosing_breakables.by_id.insert(id, index);
4631             enclosing_breakables.stack.push(ctxt);
4632         }
4633         let result = f();
4634         let ctxt = {
4635             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
4636             debug_assert!(enclosing_breakables.stack.len() == index + 1);
4637             enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
4638             enclosing_breakables.stack.pop().expect("missing breakable context")
4639         };
4640         (ctxt, result)
4641     }
4642 }
4643
4644 pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
4645                                        generics: &hir::Generics,
4646                                        ty: Ty<'tcx>) {
4647     debug!("check_bounds_are_used(n_tps={}, ty={:?})",
4648            generics.ty_params.len(),  ty);
4649
4650     // make a vector of booleans initially false, set to true when used
4651     if generics.ty_params.is_empty() { return; }
4652     let mut tps_used = vec![false; generics.ty_params.len()];
4653
4654     for leaf_ty in ty.walk() {
4655         if let ty::TyParam(ParamTy {idx, ..}) = leaf_ty.sty {
4656             debug!("Found use of ty param num {}", idx);
4657             tps_used[idx as usize - generics.lifetimes.len()] = true;
4658         }
4659     }
4660
4661     for (&used, param) in tps_used.iter().zip(&generics.ty_params) {
4662         if !used {
4663             struct_span_err!(tcx.sess, param.span, E0091,
4664                 "type parameter `{}` is unused",
4665                 param.name)
4666                 .span_label(param.span, "unused type parameter")
4667                 .emit();
4668         }
4669     }
4670 }