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