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