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