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