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