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