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