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