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