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