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