]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/expr.rs
typeck/expr.rs: move check_field + struct helpers here.
[rust.git] / src / librustc_typeck / check / expr.rs
1 //! Type checking expressions.
2 //!
3 //! See `mod.rs` for more context on type checking in general.
4
5 use crate::check::BreakableCtxt;
6 use crate::check::cast;
7 use crate::check::coercion::CoerceMany;
8 use crate::check::Diverges;
9 use crate::check::FnCtxt;
10 use crate::check::Expectation::{self, NoExpectation, ExpectHasType, ExpectCastableToType};
11 use crate::check::fatally_break_rust;
12 use crate::check::report_unexpected_variant_res;
13 use crate::check::Needs;
14 use crate::check::TupleArgumentsFlag::DontTupleArguments;
15 use crate::check::method::SelfSource;
16 use crate::middle::lang_items;
17 use crate::util::common::ErrorReported;
18 use crate::util::nodemap::FxHashMap;
19 use crate::astconv::AstConv as _;
20
21 use errors::{Applicability, DiagnosticBuilder};
22 use syntax::ast;
23 use syntax::ptr::P;
24 use syntax::symbol::{Symbol, LocalInternedString, kw, sym};
25 use syntax::source_map::Span;
26 use syntax::util::lev_distance::find_best_match_for_name;
27 use rustc::hir;
28 use rustc::hir::{ExprKind, QPath};
29 use rustc::hir::def::{CtorKind, Res, DefKind};
30 use rustc::infer;
31 use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
32 use rustc::mir::interpret::GlobalId;
33 use rustc::ty;
34 use rustc::ty::adjustment::{
35     Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability,
36 };
37 use rustc::ty::{AdtKind, Visibility};
38 use rustc::ty::Ty;
39 use rustc::ty::TypeFoldable;
40 use rustc::ty::subst::InternalSubsts;
41 use rustc::traits::{self, ObligationCauseCode};
42
43 use std::fmt::Display;
44
45 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
46     fn check_expr_eq_type(&self, expr: &'tcx hir::Expr, expected: Ty<'tcx>) {
47         let ty = self.check_expr_with_hint(expr, expected);
48         self.demand_eqtype(expr.span, expected, ty);
49     }
50
51     pub fn check_expr_has_type_or_error(
52         &self,
53         expr: &'tcx hir::Expr,
54         expected: Ty<'tcx>,
55     ) -> Ty<'tcx> {
56         self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected))
57     }
58
59     fn check_expr_meets_expectation_or_error(
60         &self,
61         expr: &'tcx hir::Expr,
62         expected: Expectation<'tcx>,
63     ) -> Ty<'tcx> {
64         let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
65         let mut ty = self.check_expr_with_expectation(expr, expected);
66
67         // While we don't allow *arbitrary* coercions here, we *do* allow
68         // coercions from ! to `expected`.
69         if ty.is_never() {
70             assert!(!self.tables.borrow().adjustments().contains_key(expr.hir_id),
71                     "expression with never type wound up being adjusted");
72             let adj_ty = self.next_diverging_ty_var(
73                 TypeVariableOrigin {
74                     kind: TypeVariableOriginKind::AdjustmentType,
75                     span: expr.span,
76                 },
77             );
78             self.apply_adjustments(expr, vec![Adjustment {
79                 kind: Adjust::NeverToAny,
80                 target: adj_ty
81             }]);
82             ty = adj_ty;
83         }
84
85         if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
86             let expr = match &expr.node {
87                 ExprKind::DropTemps(expr) => expr,
88                 _ => expr,
89             };
90             // Error possibly reported in `check_assign` so avoid emitting error again.
91             err.emit_unless(self.is_assign_to_bool(expr, expected_ty));
92         }
93         ty
94     }
95
96     pub(super) fn check_expr_coercable_to_type(
97         &self,
98         expr: &'tcx hir::Expr,
99         expected: Ty<'tcx>
100     ) -> Ty<'tcx> {
101         let ty = self.check_expr_with_hint(expr, expected);
102         // checks don't need two phase
103         self.demand_coerce(expr, ty, expected, AllowTwoPhase::No)
104     }
105
106     pub(super) fn check_expr_with_hint(
107         &self,
108         expr: &'tcx hir::Expr,
109         expected: Ty<'tcx>
110     ) -> Ty<'tcx> {
111         self.check_expr_with_expectation(expr, ExpectHasType(expected))
112     }
113
114     pub(super) fn check_expr_with_expectation(
115         &self,
116         expr: &'tcx hir::Expr,
117         expected: Expectation<'tcx>,
118     ) -> Ty<'tcx> {
119         self.check_expr_with_expectation_and_needs(expr, expected, Needs::None)
120     }
121
122     pub(super) fn check_expr(&self, expr: &'tcx hir::Expr) -> Ty<'tcx> {
123         self.check_expr_with_expectation(expr, NoExpectation)
124     }
125
126     pub(super) fn check_expr_with_needs(&self, expr: &'tcx hir::Expr, needs: Needs) -> Ty<'tcx> {
127         self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
128     }
129
130     /// Invariant:
131     /// If an expression has any sub-expressions that result in a type error,
132     /// inspecting that expression's type with `ty.references_error()` will return
133     /// true. Likewise, if an expression is known to diverge, inspecting its
134     /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
135     /// strict, _|_ can appear in the type of an expression that does not,
136     /// itself, diverge: for example, fn() -> _|_.)
137     /// Note that inspecting a type's structure *directly* may expose the fact
138     /// that there are actually multiple representations for `Error`, so avoid
139     /// that when err needs to be handled differently.
140     fn check_expr_with_expectation_and_needs(
141         &self,
142         expr: &'tcx hir::Expr,
143         expected: Expectation<'tcx>,
144         needs: Needs,
145     ) -> Ty<'tcx> {
146         debug!(">> type-checking: expr={:?} expected={:?}",
147                expr, expected);
148
149         // Warn for expressions after diverging siblings.
150         self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
151
152         // Hide the outer diverging and has_errors flags.
153         let old_diverges = self.diverges.get();
154         let old_has_errors = self.has_errors.get();
155         self.diverges.set(Diverges::Maybe);
156         self.has_errors.set(false);
157
158         let ty = self.check_expr_kind(expr, expected, needs);
159
160         // Warn for non-block expressions with diverging children.
161         match expr.node {
162             ExprKind::Block(..) |
163             ExprKind::Loop(..) | ExprKind::While(..) |
164             ExprKind::Match(..) => {}
165
166             _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression")
167         }
168
169         // Any expression that produces a value of type `!` must have diverged
170         if ty.is_never() {
171             self.diverges.set(self.diverges.get() | Diverges::Always);
172         }
173
174         // Record the type, which applies it effects.
175         // We need to do this after the warning above, so that
176         // we don't warn for the diverging expression itself.
177         self.write_ty(expr.hir_id, ty);
178
179         // Combine the diverging and has_error flags.
180         self.diverges.set(self.diverges.get() | old_diverges);
181         self.has_errors.set(self.has_errors.get() | old_has_errors);
182
183         debug!("type of {} is...", self.tcx.hir().hir_to_string(expr.hir_id));
184         debug!("... {:?}, expected is {:?}", ty, expected);
185
186         ty
187     }
188
189     fn check_expr_kind(
190         &self,
191         expr: &'tcx hir::Expr,
192         expected: Expectation<'tcx>,
193         needs: Needs,
194     ) -> Ty<'tcx> {
195         debug!(
196             "check_expr_kind(expr={:?}, expected={:?}, needs={:?})",
197             expr,
198             expected,
199             needs,
200         );
201
202         let tcx = self.tcx;
203         match expr.node {
204             ExprKind::Box(ref subexpr) => {
205                 self.check_expr_box(subexpr, expected)
206             }
207             ExprKind::Lit(ref lit) => {
208                 self.check_lit(&lit, expected)
209             }
210             ExprKind::Binary(op, ref lhs, ref rhs) => {
211                 self.check_binop(expr, op, lhs, rhs)
212             }
213             ExprKind::AssignOp(op, ref lhs, ref rhs) => {
214                 self.check_binop_assign(expr, op, lhs, rhs)
215             }
216             ExprKind::Unary(unop, ref oprnd) => {
217                 self.check_expr_unary(unop, oprnd, expected, needs, expr)
218             }
219             ExprKind::AddrOf(mutbl, ref oprnd) => {
220                 self.check_expr_addr_of(mutbl, oprnd, expected, expr)
221             }
222             ExprKind::Path(ref qpath) => {
223                 self.check_expr_path(qpath, expr)
224             }
225             ExprKind::InlineAsm(_, ref outputs, ref inputs) => {
226                 for expr in outputs.iter().chain(inputs.iter()) {
227                     self.check_expr(expr);
228                 }
229                 tcx.mk_unit()
230             }
231             ExprKind::Break(destination, ref expr_opt) => {
232                 self.check_expr_break(destination, expr_opt.deref(), expr)
233             }
234             ExprKind::Continue(destination) => {
235                 if destination.target_id.is_ok() {
236                     tcx.types.never
237                 } else {
238                     // There was an error; make type-check fail.
239                     tcx.types.err
240                 }
241             }
242             ExprKind::Ret(ref expr_opt) => {
243                 self.check_expr_return(expr_opt.deref(), expr)
244             }
245             ExprKind::Assign(ref lhs, ref rhs) => {
246                 self.check_expr_assign(expr, expected, lhs, rhs)
247             }
248             ExprKind::While(ref cond, ref body, _) => {
249                 self.check_expr_while(cond, body, expr)
250             }
251             ExprKind::Loop(ref body, _, source) => {
252                 self.check_expr_loop(body, source, expected, expr)
253             }
254             ExprKind::Match(ref discrim, ref arms, match_src) => {
255                 self.check_match(expr, &discrim, arms, expected, match_src)
256             }
257             ExprKind::Closure(capture, ref decl, body_id, _, gen) => {
258                 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
259             }
260             ExprKind::Block(ref body, _) => {
261                 self.check_block_with_expected(&body, expected)
262             }
263             ExprKind::Call(ref callee, ref args) => {
264                 self.check_call(expr, &callee, args, expected)
265             }
266             ExprKind::MethodCall(ref segment, span, ref args) => {
267                 self.check_method_call(expr, segment, span, args, expected, needs)
268             }
269             ExprKind::Cast(ref e, ref t) => {
270                 self.check_expr_cast(e, t, expr)
271             }
272             ExprKind::Type(ref e, ref t) => {
273                 let ty = self.to_ty_saving_user_provided_ty(&t);
274                 self.check_expr_eq_type(&e, ty);
275                 ty
276             }
277             ExprKind::DropTemps(ref e) => {
278                 self.check_expr_with_expectation(e, expected)
279             }
280             ExprKind::Array(ref args) => {
281                 self.check_expr_array(args, expected, expr)
282             }
283             ExprKind::Repeat(ref element, ref count) => {
284                 self.check_expr_repeat(element, count, expected, expr)
285             }
286             ExprKind::Tup(ref elts) => {
287                 self.check_expr_tuple(elts, expected, expr)
288             }
289             ExprKind::Struct(ref qpath, ref fields, ref base_expr) => {
290                 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
291             }
292             ExprKind::Field(ref base, field) => {
293                 self.check_field(expr, needs, &base, field)
294             }
295             ExprKind::Index(ref base, ref idx) => {
296                 self.check_expr_index(base, idx, needs, expr)
297             }
298             ExprKind::Yield(ref value) => {
299                 self.check_expr_yield(value, expr)
300             }
301             hir::ExprKind::Err => {
302                 tcx.types.err
303             }
304         }
305     }
306
307     fn check_expr_box(&self, expr: &'tcx hir::Expr, expected: Expectation<'tcx>) -> Ty<'tcx> {
308         let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
309             match ty.sty {
310                 ty::Adt(def, _) if def.is_box()
311                     => Expectation::rvalue_hint(self, ty.boxed_ty()),
312                 _ => NoExpectation
313             }
314         });
315         let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
316         self.tcx.mk_box(referent_ty)
317     }
318
319     fn check_expr_unary(
320         &self,
321         unop: hir::UnOp,
322         oprnd: &'tcx hir::Expr,
323         expected: Expectation<'tcx>,
324         needs: Needs,
325         expr: &'tcx hir::Expr,
326     ) -> Ty<'tcx> {
327         let tcx = self.tcx;
328         let expected_inner = match unop {
329             hir::UnNot | hir::UnNeg => expected,
330             hir::UnDeref => NoExpectation,
331         };
332         let needs = match unop {
333             hir::UnDeref => needs,
334             _ => Needs::None
335         };
336         let mut oprnd_t = self.check_expr_with_expectation_and_needs(&oprnd, expected_inner, needs);
337
338         if !oprnd_t.references_error() {
339             oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
340             match unop {
341                 hir::UnDeref => {
342                     if let Some(mt) = oprnd_t.builtin_deref(true) {
343                         oprnd_t = mt.ty;
344                     } else if let Some(ok) = self.try_overloaded_deref(
345                             expr.span, oprnd_t, needs) {
346                         let method = self.register_infer_ok_obligations(ok);
347                         if let ty::Ref(region, _, mutbl) = method.sig.inputs()[0].sty {
348                             let mutbl = match mutbl {
349                                 hir::MutImmutable => AutoBorrowMutability::Immutable,
350                                 hir::MutMutable => AutoBorrowMutability::Mutable {
351                                     // (It shouldn't actually matter for unary ops whether
352                                     // we enable two-phase borrows or not, since a unary
353                                     // op has no additional operands.)
354                                     allow_two_phase_borrow: AllowTwoPhase::No,
355                                 }
356                             };
357                             self.apply_adjustments(oprnd, vec![Adjustment {
358                                 kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
359                                 target: method.sig.inputs()[0]
360                             }]);
361                         }
362                         oprnd_t = self.make_overloaded_place_return_type(method).ty;
363                         self.write_method_call(expr.hir_id, method);
364                     } else {
365                         let mut err = type_error_struct!(
366                             tcx.sess,
367                             expr.span,
368                             oprnd_t,
369                             E0614,
370                             "type `{}` cannot be dereferenced",
371                             oprnd_t,
372                         );
373                         let sp = tcx.sess.source_map().start_point(expr.span);
374                         if let Some(sp) = tcx.sess.parse_sess.ambiguous_block_expr_parse
375                             .borrow().get(&sp)
376                         {
377                             tcx.sess.parse_sess.expr_parentheses_needed(
378                                 &mut err,
379                                 *sp,
380                                 None,
381                             );
382                         }
383                         err.emit();
384                         oprnd_t = tcx.types.err;
385                     }
386                 }
387                 hir::UnNot => {
388                     let result = self.check_user_unop(expr, oprnd_t, unop);
389                     // If it's builtin, we can reuse the type, this helps inference.
390                     if !(oprnd_t.is_integral() || oprnd_t.sty == ty::Bool) {
391                         oprnd_t = result;
392                     }
393                 }
394                 hir::UnNeg => {
395                     let result = self.check_user_unop(expr, oprnd_t, unop);
396                     // If it's builtin, we can reuse the type, this helps inference.
397                     if !oprnd_t.is_numeric() {
398                         oprnd_t = result;
399                     }
400                 }
401             }
402         }
403         oprnd_t
404     }
405
406     fn check_expr_addr_of(
407         &self,
408         mutbl: hir::Mutability,
409         oprnd: &'tcx hir::Expr,
410         expected: Expectation<'tcx>,
411         expr: &'tcx hir::Expr,
412     ) -> Ty<'tcx> {
413         let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
414             match ty.sty {
415                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
416                     if oprnd.is_place_expr() {
417                         // Places may legitimately have unsized types.
418                         // For example, dereferences of a fat pointer and
419                         // the last field of a struct can be unsized.
420                         ExpectHasType(ty)
421                     } else {
422                         Expectation::rvalue_hint(self, ty)
423                     }
424                 }
425                 _ => NoExpectation
426             }
427         });
428         let needs = Needs::maybe_mut_place(mutbl);
429         let ty = self.check_expr_with_expectation_and_needs(&oprnd, hint, needs);
430
431         let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
432         if tm.ty.references_error() {
433             self.tcx.types.err
434         } else {
435             // Note: at this point, we cannot say what the best lifetime
436             // is to use for resulting pointer.  We want to use the
437             // shortest lifetime possible so as to avoid spurious borrowck
438             // errors.  Moreover, the longest lifetime will depend on the
439             // precise details of the value whose address is being taken
440             // (and how long it is valid), which we don't know yet until type
441             // inference is complete.
442             //
443             // Therefore, here we simply generate a region variable.  The
444             // region inferencer will then select the ultimate value.
445             // Finally, borrowck is charged with guaranteeing that the
446             // value whose address was taken can actually be made to live
447             // as long as it needs to live.
448             let region = self.next_region_var(infer::AddrOfRegion(expr.span));
449             self.tcx.mk_ref(region, tm)
450         }
451     }
452
453     fn check_expr_path(&self, qpath: &hir::QPath, expr: &'tcx hir::Expr) -> Ty<'tcx> {
454         let tcx = self.tcx;
455         let (res, opt_ty, segs) = self.resolve_ty_and_res_ufcs(qpath, expr.hir_id, expr.span);
456         let ty = match res {
457             Res::Err => {
458                 self.set_tainted_by_errors();
459                 tcx.types.err
460             }
461             Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
462                 report_unexpected_variant_res(tcx, res, expr.span, qpath);
463                 tcx.types.err
464             }
465             _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
466         };
467
468         if let ty::FnDef(..) = ty.sty {
469             let fn_sig = ty.fn_sig(tcx);
470             if !tcx.features().unsized_locals {
471                 // We want to remove some Sized bounds from std functions,
472                 // but don't want to expose the removal to stable Rust.
473                 // i.e., we don't want to allow
474                 //
475                 // ```rust
476                 // drop as fn(str);
477                 // ```
478                 //
479                 // to work in stable even if the Sized bound on `drop` is relaxed.
480                 for i in 0..fn_sig.inputs().skip_binder().len() {
481                     // We just want to check sizedness, so instead of introducing
482                     // placeholder lifetimes with probing, we just replace higher lifetimes
483                     // with fresh vars.
484                     let input = self.replace_bound_vars_with_fresh_vars(
485                         expr.span,
486                         infer::LateBoundRegionConversionTime::FnCall,
487                         &fn_sig.input(i)).0;
488                     self.require_type_is_sized_deferred(input, expr.span,
489                                                         traits::SizedArgumentType);
490                 }
491             }
492             // Here we want to prevent struct constructors from returning unsized types.
493             // There were two cases this happened: fn pointer coercion in stable
494             // and usual function call in presense of unsized_locals.
495             // Also, as we just want to check sizedness, instead of introducing
496             // placeholder lifetimes with probing, we just replace higher lifetimes
497             // with fresh vars.
498             let output = self.replace_bound_vars_with_fresh_vars(
499                 expr.span,
500                 infer::LateBoundRegionConversionTime::FnCall,
501                 &fn_sig.output()).0;
502             self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
503         }
504
505         // We always require that the type provided as the value for
506         // a type parameter outlives the moment of instantiation.
507         let substs = self.tables.borrow().node_substs(expr.hir_id);
508         self.add_wf_bounds(substs, expr);
509
510         ty
511     }
512
513     fn check_expr_break(
514         &self,
515         destination: hir::Destination,
516         expr_opt: Option<&'tcx hir::Expr>,
517         expr: &'tcx hir::Expr,
518     ) -> Ty<'tcx> {
519         let tcx = self.tcx;
520         if let Ok(target_id) = destination.target_id {
521             let (e_ty, cause);
522             if let Some(ref e) = expr_opt {
523                 // If this is a break with a value, we need to type-check
524                 // the expression. Get an expected type from the loop context.
525                 let opt_coerce_to = {
526                     let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
527                     enclosing_breakables.find_breakable(target_id)
528                                         .coerce
529                                         .as_ref()
530                                         .map(|coerce| coerce.expected_ty())
531                 };
532
533                 // If the loop context is not a `loop { }`, then break with
534                 // a value is illegal, and `opt_coerce_to` will be `None`.
535                 // Just set expectation to error in that case.
536                 let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
537
538                 // Recurse without `enclosing_breakables` borrowed.
539                 e_ty = self.check_expr_with_hint(e, coerce_to);
540                 cause = self.misc(e.span);
541             } else {
542                 // Otherwise, this is a break *without* a value. That's
543                 // always legal, and is equivalent to `break ()`.
544                 e_ty = tcx.mk_unit();
545                 cause = self.misc(expr.span);
546             }
547
548             // Now that we have type-checked `expr_opt`, borrow
549             // the `enclosing_loops` field and let's coerce the
550             // type of `expr_opt` into what is expected.
551             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
552             let ctxt = enclosing_breakables.find_breakable(target_id);
553             if let Some(ref mut coerce) = ctxt.coerce {
554                 if let Some(ref e) = expr_opt {
555                     coerce.coerce(self, &cause, e, e_ty);
556                 } else {
557                     assert!(e_ty.is_unit());
558                     coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
559                 }
560             } else {
561                 // If `ctxt.coerce` is `None`, we can just ignore
562                 // the type of the expresison.  This is because
563                 // either this was a break *without* a value, in
564                 // which case it is always a legal type (`()`), or
565                 // else an error would have been flagged by the
566                 // `loops` pass for using break with an expression
567                 // where you are not supposed to.
568                 assert!(expr_opt.is_none() || self.tcx.sess.err_count() > 0);
569             }
570
571             ctxt.may_break = true;
572
573             // the type of a `break` is always `!`, since it diverges
574             tcx.types.never
575         } else {
576             // Otherwise, we failed to find the enclosing loop;
577             // this can only happen if the `break` was not
578             // inside a loop at all, which is caught by the
579             // loop-checking pass.
580             if self.tcx.sess.err_count() == 0 {
581                 self.tcx.sess.delay_span_bug(expr.span,
582                     "break was outside loop, but no error was emitted");
583             }
584
585             // We still need to assign a type to the inner expression to
586             // prevent the ICE in #43162.
587             if let Some(ref e) = expr_opt {
588                 self.check_expr_with_hint(e, tcx.types.err);
589
590                 // ... except when we try to 'break rust;'.
591                 // ICE this expression in particular (see #43162).
592                 if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.node {
593                     if path.segments.len() == 1 &&
594                         path.segments[0].ident.name == sym::rust {
595                         fatally_break_rust(self.tcx.sess);
596                     }
597                 }
598             }
599             // There was an error; make type-check fail.
600             tcx.types.err
601         }
602     }
603
604     fn check_expr_return(
605         &self,
606         expr_opt: Option<&'tcx hir::Expr>,
607         expr: &'tcx hir::Expr
608     ) -> Ty<'tcx> {
609         if self.ret_coercion.is_none() {
610             struct_span_err!(self.tcx.sess, expr.span, E0572,
611                                 "return statement outside of function body").emit();
612         } else if let Some(ref e) = expr_opt {
613             if self.ret_coercion_span.borrow().is_none() {
614                 *self.ret_coercion_span.borrow_mut() = Some(e.span);
615             }
616             self.check_return_expr(e);
617         } else {
618             let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
619             if self.ret_coercion_span.borrow().is_none() {
620                 *self.ret_coercion_span.borrow_mut() = Some(expr.span);
621             }
622             let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
623             if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
624                 coercion.coerce_forced_unit(
625                     self,
626                     &cause,
627                     &mut |db| {
628                         db.span_label(
629                             fn_decl.output.span(),
630                             format!(
631                                 "expected `{}` because of this return type",
632                                 fn_decl.output,
633                             ),
634                         );
635                     },
636                     true,
637                 );
638             } else {
639                 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
640             }
641         }
642         self.tcx.types.never
643     }
644
645     pub(super) fn check_return_expr(&self, return_expr: &'tcx hir::Expr) {
646         let ret_coercion =
647             self.ret_coercion
648                 .as_ref()
649                 .unwrap_or_else(|| span_bug!(return_expr.span,
650                                              "check_return_expr called outside fn body"));
651
652         let ret_ty = ret_coercion.borrow().expected_ty();
653         let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone());
654         ret_coercion.borrow_mut()
655                     .coerce(self,
656                             &self.cause(return_expr.span,
657                                         ObligationCauseCode::ReturnType(return_expr.hir_id)),
658                             return_expr,
659                             return_expr_ty);
660     }
661
662     /// Type check assignment expression `expr` of form `lhs = rhs`.
663     /// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
664     fn check_expr_assign(
665         &self,
666         expr: &'tcx hir::Expr,
667         expected: Expectation<'tcx>,
668         lhs: &'tcx hir::Expr,
669         rhs: &'tcx hir::Expr,
670     ) -> Ty<'tcx> {
671         let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
672         let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
673
674         let expected_ty = expected.coercion_target_type(self, expr.span);
675         if expected_ty == self.tcx.types.bool {
676             // The expected type is `bool` but this will result in `()` so we can reasonably
677             // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
678             // The likely cause of this is `if foo = bar { .. }`.
679             let actual_ty = self.tcx.mk_unit();
680             let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
681             let msg = "try comparing for equality";
682             let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
683             let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
684             if let (Ok(left), Ok(right)) = (left, right) {
685                 let help = format!("{} == {}", left, right);
686                 err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
687             } else {
688                 err.help(msg);
689             }
690             err.emit();
691         } else if !lhs.is_place_expr() {
692             struct_span_err!(self.tcx.sess, expr.span, E0070,
693                                 "invalid left-hand side expression")
694                 .span_label(expr.span, "left-hand of expression not valid")
695                 .emit();
696         }
697
698         self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
699
700         if lhs_ty.references_error() || rhs_ty.references_error() {
701             self.tcx.types.err
702         } else {
703             self.tcx.mk_unit()
704         }
705     }
706
707     fn check_expr_while(
708         &self,
709         cond: &'tcx hir::Expr,
710         body: &'tcx hir::Block,
711         expr: &'tcx hir::Expr
712     ) -> Ty<'tcx> {
713         let ctxt = BreakableCtxt {
714             // Cannot use break with a value from a while loop.
715             coerce: None,
716             may_break: false, // Will get updated if/when we find a `break`.
717         };
718
719         let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
720             self.check_expr_has_type_or_error(&cond, self.tcx.types.bool);
721             let cond_diverging = self.diverges.get();
722             self.check_block_no_value(&body);
723
724             // We may never reach the body so it diverging means nothing.
725             self.diverges.set(cond_diverging);
726         });
727
728         if ctxt.may_break {
729             // No way to know whether it's diverging because
730             // of a `break` or an outer `break` or `return`.
731             self.diverges.set(Diverges::Maybe);
732         }
733
734         self.tcx.mk_unit()
735     }
736
737     fn check_expr_loop(
738         &self,
739         body: &'tcx hir::Block,
740         source: hir::LoopSource,
741         expected: Expectation<'tcx>,
742         expr: &'tcx hir::Expr,
743     ) -> Ty<'tcx> {
744         let coerce = match source {
745             // you can only use break with a value from a normal `loop { }`
746             hir::LoopSource::Loop => {
747                 let coerce_to = expected.coercion_target_type(self, body.span);
748                 Some(CoerceMany::new(coerce_to))
749             }
750
751             hir::LoopSource::WhileLet |
752             hir::LoopSource::ForLoop => {
753                 None
754             }
755         };
756
757         let ctxt = BreakableCtxt {
758             coerce,
759             may_break: false, // Will get updated if/when we find a `break`.
760         };
761
762         let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
763             self.check_block_no_value(&body);
764         });
765
766         if ctxt.may_break {
767             // No way to know whether it's diverging because
768             // of a `break` or an outer `break` or `return`.
769             self.diverges.set(Diverges::Maybe);
770         }
771
772         // If we permit break with a value, then result type is
773         // the LUB of the breaks (possibly ! if none); else, it
774         // is nil. This makes sense because infinite loops
775         // (which would have type !) are only possible iff we
776         // permit break with a value [1].
777         if ctxt.coerce.is_none() && !ctxt.may_break {
778             // [1]
779             self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
780         }
781         ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
782     }
783
784     /// Checks a method call.
785     fn check_method_call(
786         &self,
787         expr: &'tcx hir::Expr,
788         segment: &hir::PathSegment,
789         span: Span,
790         args: &'tcx [hir::Expr],
791         expected: Expectation<'tcx>,
792         needs: Needs,
793     ) -> Ty<'tcx> {
794         let rcvr = &args[0];
795         let rcvr_t = self.check_expr_with_needs(&rcvr, needs);
796         // no need to check for bot/err -- callee does that
797         let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
798
799         let method = match self.lookup_method(rcvr_t,
800                                               segment,
801                                               span,
802                                               expr,
803                                               rcvr) {
804             Ok(method) => {
805                 self.write_method_call(expr.hir_id, method);
806                 Ok(method)
807             }
808             Err(error) => {
809                 if segment.ident.name != kw::Invalid {
810                     self.report_method_error(span,
811                                              rcvr_t,
812                                              segment.ident,
813                                              SelfSource::MethodCall(rcvr),
814                                              error,
815                                              Some(args));
816                 }
817                 Err(())
818             }
819         };
820
821         // Call the generic checker.
822         self.check_method_argument_types(span,
823                                          expr.span,
824                                          method,
825                                          &args[1..],
826                                          DontTupleArguments,
827                                          expected)
828     }
829
830     fn check_expr_cast(
831         &self,
832         e: &'tcx hir::Expr,
833         t: &'tcx hir::Ty,
834         expr: &'tcx hir::Expr,
835     ) -> Ty<'tcx> {
836         // Find the type of `e`. Supply hints based on the type we are casting to,
837         // if appropriate.
838         let t_cast = self.to_ty_saving_user_provided_ty(t);
839         let t_cast = self.resolve_vars_if_possible(&t_cast);
840         let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
841         let t_cast = self.resolve_vars_if_possible(&t_cast);
842
843         // Eagerly check for some obvious errors.
844         if t_expr.references_error() || t_cast.references_error() {
845             self.tcx.types.err
846         } else {
847             // Defer other checks until we're done type checking.
848             let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
849             match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
850                 Ok(cast_check) => {
851                     deferred_cast_checks.push(cast_check);
852                     t_cast
853                 }
854                 Err(ErrorReported) => {
855                     self.tcx.types.err
856                 }
857             }
858         }
859     }
860
861     fn check_expr_array(
862         &self,
863         args: &'tcx [hir::Expr],
864         expected: Expectation<'tcx>,
865         expr: &'tcx hir::Expr
866     ) -> Ty<'tcx> {
867         let uty = expected.to_option(self).and_then(|uty| {
868             match uty.sty {
869                 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
870                 _ => None
871             }
872         });
873
874         let element_ty = if !args.is_empty() {
875             let coerce_to = uty.unwrap_or_else(|| {
876                 self.next_ty_var(TypeVariableOrigin {
877                     kind: TypeVariableOriginKind::TypeInference,
878                     span: expr.span,
879                 })
880             });
881             let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
882             assert_eq!(self.diverges.get(), Diverges::Maybe);
883             for e in args {
884                 let e_ty = self.check_expr_with_hint(e, coerce_to);
885                 let cause = self.misc(e.span);
886                 coerce.coerce(self, &cause, e, e_ty);
887             }
888             coerce.complete(self)
889         } else {
890             self.next_ty_var(TypeVariableOrigin {
891                 kind: TypeVariableOriginKind::TypeInference,
892                 span: expr.span,
893             })
894         };
895         self.tcx.mk_array(element_ty, args.len() as u64)
896     }
897
898     fn check_expr_repeat(
899         &self,
900         element: &'tcx hir::Expr,
901         count: &'tcx hir::AnonConst,
902         expected: Expectation<'tcx>,
903         expr: &'tcx hir::Expr,
904     ) -> Ty<'tcx> {
905         let tcx = self.tcx;
906         let count_def_id = tcx.hir().local_def_id_from_hir_id(count.hir_id);
907         let count = if self.const_param_def_id(count).is_some() {
908             Ok(self.to_const(count, tcx.type_of(count_def_id)))
909         } else {
910             let param_env = ty::ParamEnv::empty();
911             let substs = InternalSubsts::identity_for_item(tcx.global_tcx(), count_def_id);
912             let instance = ty::Instance::resolve(
913                 tcx.global_tcx(),
914                 param_env,
915                 count_def_id,
916                 substs,
917             ).unwrap();
918             let global_id = GlobalId {
919                 instance,
920                 promoted: None
921             };
922
923             tcx.const_eval(param_env.and(global_id))
924         };
925
926         let uty = match expected {
927             ExpectHasType(uty) => {
928                 match uty.sty {
929                     ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
930                     _ => None
931                 }
932             }
933             _ => None
934         };
935
936         let (element_ty, t) = match uty {
937             Some(uty) => {
938                 self.check_expr_coercable_to_type(&element, uty);
939                 (uty, uty)
940             }
941             None => {
942                 let ty = self.next_ty_var(TypeVariableOrigin {
943                     kind: TypeVariableOriginKind::MiscVariable,
944                     span: element.span,
945                 });
946                 let element_ty = self.check_expr_has_type_or_error(&element, ty);
947                 (element_ty, ty)
948             }
949         };
950
951         if let Ok(count) = count {
952             let zero_or_one = count.assert_usize(tcx).map_or(false, |count| count <= 1);
953             if !zero_or_one {
954                 // For [foo, ..n] where n > 1, `foo` must have
955                 // Copy type:
956                 let lang_item = tcx.require_lang_item(lang_items::CopyTraitLangItem);
957                 self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
958             }
959         }
960
961         if element_ty.references_error() {
962             tcx.types.err
963         } else if let Ok(count) = count {
964             tcx.mk_ty(ty::Array(t, count))
965         } else {
966             tcx.types.err
967         }
968     }
969
970     fn check_expr_tuple(
971         &self,
972         elts: &'tcx [hir::Expr],
973         expected: Expectation<'tcx>,
974         expr: &'tcx hir::Expr,
975     ) -> Ty<'tcx> {
976         let flds = expected.only_has_type(self).and_then(|ty| {
977             let ty = self.resolve_type_vars_with_obligations(ty);
978             match ty.sty {
979                 ty::Tuple(ref flds) => Some(&flds[..]),
980                 _ => None
981             }
982         });
983
984         let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
985             let t = match flds {
986                 Some(ref fs) if i < fs.len() => {
987                     let ety = fs[i].expect_ty();
988                     self.check_expr_coercable_to_type(&e, ety);
989                     ety
990                 }
991                 _ => {
992                     self.check_expr_with_expectation(&e, NoExpectation)
993                 }
994             };
995             t
996         });
997         let tuple = self.tcx.mk_tup(elt_ts_iter);
998         if tuple.references_error() {
999             self.tcx.types.err
1000         } else {
1001             self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1002             tuple
1003         }
1004     }
1005
1006     fn check_expr_struct(
1007         &self,
1008         expr: &hir::Expr,
1009         expected: Expectation<'tcx>,
1010         qpath: &QPath,
1011         fields: &'tcx [hir::Field],
1012         base_expr: &'tcx Option<P<hir::Expr>>,
1013     ) -> Ty<'tcx> {
1014         // Find the relevant variant
1015         let (variant, adt_ty) =
1016             if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) {
1017                 variant_ty
1018             } else {
1019                 self.check_struct_fields_on_error(fields, base_expr);
1020                 return self.tcx.types.err;
1021             };
1022
1023         let path_span = match *qpath {
1024             QPath::Resolved(_, ref path) => path.span,
1025             QPath::TypeRelative(ref qself, _) => qself.span
1026         };
1027
1028         // Prohibit struct expressions when non-exhaustive flag is set.
1029         let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1030         if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1031             span_err!(self.tcx.sess, expr.span, E0639,
1032                       "cannot create non-exhaustive {} using struct expression",
1033                       adt.variant_descr());
1034         }
1035
1036         let error_happened = self.check_expr_struct_fields(adt_ty, expected, expr.hir_id, path_span,
1037                                                            variant, fields, base_expr.is_none());
1038         if let &Some(ref base_expr) = base_expr {
1039             // If check_expr_struct_fields hit an error, do not attempt to populate
1040             // the fields with the base_expr. This could cause us to hit errors later
1041             // when certain fields are assumed to exist that in fact do not.
1042             if !error_happened {
1043                 self.check_expr_has_type_or_error(base_expr, adt_ty);
1044                 match adt_ty.sty {
1045                     ty::Adt(adt, substs) if adt.is_struct() => {
1046                         let fru_field_types = adt.non_enum_variant().fields.iter().map(|f| {
1047                             self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
1048                         }).collect();
1049
1050                         self.tables
1051                             .borrow_mut()
1052                             .fru_field_types_mut()
1053                             .insert(expr.hir_id, fru_field_types);
1054                     }
1055                     _ => {
1056                         span_err!(self.tcx.sess, base_expr.span, E0436,
1057                                   "functional record update syntax requires a struct");
1058                     }
1059                 }
1060             }
1061         }
1062         self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1063         adt_ty
1064     }
1065
1066     fn check_expr_struct_fields(
1067         &self,
1068         adt_ty: Ty<'tcx>,
1069         expected: Expectation<'tcx>,
1070         expr_id: hir::HirId,
1071         span: Span,
1072         variant: &'tcx ty::VariantDef,
1073         ast_fields: &'tcx [hir::Field],
1074         check_completeness: bool,
1075     ) -> bool {
1076         let tcx = self.tcx;
1077
1078         let adt_ty_hint =
1079             self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1080                 .get(0).cloned().unwrap_or(adt_ty);
1081         // re-link the regions that EIfEO can erase.
1082         self.demand_eqtype(span, adt_ty_hint, adt_ty);
1083
1084         let (substs, adt_kind, kind_name) = match &adt_ty.sty {
1085             &ty::Adt(adt, substs) => {
1086                 (substs, adt.adt_kind(), adt.variant_descr())
1087             }
1088             _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
1089         };
1090
1091         let mut remaining_fields = variant.fields.iter().enumerate().map(|(i, field)|
1092             (field.ident.modern(), (i, field))
1093         ).collect::<FxHashMap<_, _>>();
1094
1095         let mut seen_fields = FxHashMap::default();
1096
1097         let mut error_happened = false;
1098
1099         // Type-check each field.
1100         for field in ast_fields {
1101             let ident = tcx.adjust_ident(field.ident, variant.def_id);
1102             let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1103                 seen_fields.insert(ident, field.span);
1104                 self.write_field_index(field.hir_id, i);
1105
1106                 // We don't look at stability attributes on
1107                 // struct-like enums (yet...), but it's definitely not
1108                 // a bug to have constructed one.
1109                 if adt_kind != AdtKind::Enum {
1110                     tcx.check_stability(v_field.did, Some(expr_id), field.span);
1111                 }
1112
1113                 self.field_ty(field.span, v_field, substs)
1114             } else {
1115                 error_happened = true;
1116                 if let Some(prev_span) = seen_fields.get(&ident) {
1117                     let mut err = struct_span_err!(self.tcx.sess,
1118                                                    field.ident.span,
1119                                                    E0062,
1120                                                    "field `{}` specified more than once",
1121                                                    ident);
1122
1123                     err.span_label(field.ident.span, "used more than once");
1124                     err.span_label(*prev_span, format!("first use of `{}`", ident));
1125
1126                     err.emit();
1127                 } else {
1128                     self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name);
1129                 }
1130
1131                 tcx.types.err
1132             };
1133
1134             // Make sure to give a type to the field even if there's
1135             // an error, so we can continue type-checking.
1136             self.check_expr_coercable_to_type(&field.expr, field_type);
1137         }
1138
1139         // Make sure the programmer specified correct number of fields.
1140         if kind_name == "union" {
1141             if ast_fields.len() != 1 {
1142                 tcx.sess.span_err(span, "union expressions should have exactly one field");
1143             }
1144         } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1145             let len = remaining_fields.len();
1146
1147             let mut displayable_field_names = remaining_fields
1148                                               .keys()
1149                                               .map(|ident| ident.as_str())
1150                                               .collect::<Vec<_>>();
1151
1152             displayable_field_names.sort();
1153
1154             let truncated_fields_error = if len <= 3 {
1155                 String::new()
1156             } else {
1157                 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
1158             };
1159
1160             let remaining_fields_names = displayable_field_names.iter().take(3)
1161                                         .map(|n| format!("`{}`", n))
1162                                         .collect::<Vec<_>>()
1163                                         .join(", ");
1164
1165             struct_span_err!(tcx.sess, span, E0063,
1166                              "missing field{} {}{} in initializer of `{}`",
1167                              if remaining_fields.len() == 1 { "" } else { "s" },
1168                              remaining_fields_names,
1169                              truncated_fields_error,
1170                              adt_ty)
1171                 .span_label(span, format!("missing {}{}",
1172                                           remaining_fields_names,
1173                                           truncated_fields_error))
1174                 .emit();
1175         }
1176         error_happened
1177     }
1178
1179     fn check_struct_fields_on_error(
1180         &self,
1181         fields: &'tcx [hir::Field],
1182         base_expr: &'tcx Option<P<hir::Expr>>,
1183     ) {
1184         for field in fields {
1185             self.check_expr(&field.expr);
1186         }
1187         if let Some(ref base) = *base_expr {
1188             self.check_expr(&base);
1189         }
1190     }
1191
1192     fn report_unknown_field(
1193         &self,
1194         ty: Ty<'tcx>,
1195         variant: &'tcx ty::VariantDef,
1196         field: &hir::Field,
1197         skip_fields: &[hir::Field],
1198         kind_name: &str,
1199     ) {
1200         if variant.recovered {
1201             return;
1202         }
1203         let mut err = self.type_error_struct_with_diag(
1204             field.ident.span,
1205             |actual| match ty.sty {
1206                 ty::Adt(adt, ..) if adt.is_enum() => {
1207                     struct_span_err!(self.tcx.sess, field.ident.span, E0559,
1208                                      "{} `{}::{}` has no field named `{}`",
1209                                      kind_name, actual, variant.ident, field.ident)
1210                 }
1211                 _ => {
1212                     struct_span_err!(self.tcx.sess, field.ident.span, E0560,
1213                                      "{} `{}` has no field named `{}`",
1214                                      kind_name, actual, field.ident)
1215                 }
1216             },
1217             ty);
1218         // prevent all specified fields from being suggested
1219         let skip_fields = skip_fields.iter().map(|ref x| x.ident.as_str());
1220         if let Some(field_name) = Self::suggest_field_name(variant,
1221                                                            &field.ident.as_str(),
1222                                                            skip_fields.collect()) {
1223             err.span_suggestion(
1224                 field.ident.span,
1225                 "a field with a similar name exists",
1226                 field_name.to_string(),
1227                 Applicability::MaybeIncorrect,
1228             );
1229         } else {
1230             match ty.sty {
1231                 ty::Adt(adt, ..) => {
1232                     if adt.is_enum() {
1233                         err.span_label(field.ident.span,
1234                                        format!("`{}::{}` does not have this field",
1235                                                ty, variant.ident));
1236                     } else {
1237                         err.span_label(field.ident.span,
1238                                        format!("`{}` does not have this field", ty));
1239                     }
1240                     let available_field_names = self.available_field_names(variant);
1241                     if !available_field_names.is_empty() {
1242                         err.note(&format!("available fields are: {}",
1243                                           self.name_series_display(available_field_names)));
1244                     }
1245                 }
1246                 _ => bug!("non-ADT passed to report_unknown_field")
1247             }
1248         };
1249         err.emit();
1250     }
1251
1252     // Return an hint about the closest match in field names
1253     fn suggest_field_name(variant: &'tcx ty::VariantDef,
1254                           field: &str,
1255                           skip: Vec<LocalInternedString>)
1256                           -> Option<Symbol> {
1257         let names = variant.fields.iter().filter_map(|field| {
1258             // ignore already set fields and private fields from non-local crates
1259             if skip.iter().any(|x| *x == field.ident.as_str()) ||
1260                (!variant.def_id.is_local() && field.vis != Visibility::Public)
1261             {
1262                 None
1263             } else {
1264                 Some(&field.ident.name)
1265             }
1266         });
1267
1268         find_best_match_for_name(names, field, None)
1269     }
1270
1271     fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<ast::Name> {
1272         variant.fields.iter().filter(|field| {
1273             let def_scope =
1274                 self.tcx.adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id).1;
1275             field.vis.is_accessible_from(def_scope, self.tcx)
1276         })
1277         .map(|field| field.ident.name)
1278         .collect()
1279     }
1280
1281     fn name_series_display(&self, names: Vec<ast::Name>) -> String {
1282         // dynamic limit, to never omit just one field
1283         let limit = if names.len() == 6 { 6 } else { 5 };
1284         let mut display = names.iter().take(limit)
1285             .map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1286         if names.len() > limit {
1287             display = format!("{} ... and {} others", display, names.len() - limit);
1288         }
1289         display
1290     }
1291
1292     // Check field access expressions
1293     fn check_field(
1294         &self,
1295         expr: &'tcx hir::Expr,
1296         needs: Needs,
1297         base: &'tcx hir::Expr,
1298         field: ast::Ident,
1299     ) -> Ty<'tcx> {
1300         let expr_t = self.check_expr_with_needs(base, needs);
1301         let expr_t = self.structurally_resolved_type(base.span,
1302                                                      expr_t);
1303         let mut private_candidate = None;
1304         let mut autoderef = self.autoderef(expr.span, expr_t);
1305         while let Some((base_t, _)) = autoderef.next() {
1306             match base_t.sty {
1307                 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1308                     debug!("struct named {:?}",  base_t);
1309                     let (ident, def_scope) =
1310                         self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1311                     let fields = &base_def.non_enum_variant().fields;
1312                     if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) {
1313                         let field = &fields[index];
1314                         let field_ty = self.field_ty(expr.span, field, substs);
1315                         // Save the index of all fields regardless of their visibility in case
1316                         // of error recovery.
1317                         self.write_field_index(expr.hir_id, index);
1318                         if field.vis.is_accessible_from(def_scope, self.tcx) {
1319                             let adjustments = autoderef.adjust_steps(self, needs);
1320                             self.apply_adjustments(base, adjustments);
1321                             autoderef.finalize(self);
1322
1323                             self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1324                             return field_ty;
1325                         }
1326                         private_candidate = Some((base_def.did, field_ty));
1327                     }
1328                 }
1329                 ty::Tuple(ref tys) => {
1330                     let fstr = field.as_str();
1331                     if let Ok(index) = fstr.parse::<usize>() {
1332                         if fstr == index.to_string() {
1333                             if let Some(field_ty) = tys.get(index) {
1334                                 let adjustments = autoderef.adjust_steps(self, needs);
1335                                 self.apply_adjustments(base, adjustments);
1336                                 autoderef.finalize(self);
1337
1338                                 self.write_field_index(expr.hir_id, index);
1339                                 return field_ty.expect_ty();
1340                             }
1341                         }
1342                     }
1343                 }
1344                 _ => {}
1345             }
1346         }
1347         autoderef.unambiguous_final_ty(self);
1348
1349         if let Some((did, field_ty)) = private_candidate {
1350             let struct_path = self.tcx().def_path_str(did);
1351             let mut err = struct_span_err!(self.tcx().sess, expr.span, E0616,
1352                                            "field `{}` of struct `{}` is private",
1353                                            field, struct_path);
1354             // Also check if an accessible method exists, which is often what is meant.
1355             if self.method_exists(field, expr_t, expr.hir_id, false)
1356                 && !self.expr_in_place(expr.hir_id)
1357             {
1358                 self.suggest_method_call(
1359                     &mut err,
1360                     &format!("a method `{}` also exists, call it with parentheses", field),
1361                     field,
1362                     expr_t,
1363                     expr.hir_id,
1364                 );
1365             }
1366             err.emit();
1367             field_ty
1368         } else if field.name == kw::Invalid {
1369             self.tcx().types.err
1370         } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1371             let mut err = type_error_struct!(self.tcx().sess, field.span, expr_t, E0615,
1372                                "attempted to take value of method `{}` on type `{}`",
1373                                field, expr_t);
1374
1375             if !self.expr_in_place(expr.hir_id) {
1376                 self.suggest_method_call(
1377                     &mut err,
1378                     "use parentheses to call the method",
1379                     field,
1380                     expr_t,
1381                     expr.hir_id
1382                 );
1383             } else {
1384                 err.help("methods are immutable and cannot be assigned to");
1385             }
1386
1387             err.emit();
1388             self.tcx().types.err
1389         } else {
1390             if !expr_t.is_primitive_ty() {
1391                 let mut err = self.no_such_field_err(field.span, field, expr_t);
1392
1393                 match expr_t.sty {
1394                     ty::Adt(def, _) if !def.is_enum() => {
1395                         if let Some(suggested_field_name) =
1396                             Self::suggest_field_name(def.non_enum_variant(),
1397                                                      &field.as_str(), vec![]) {
1398                                 err.span_suggestion(
1399                                     field.span,
1400                                     "a field with a similar name exists",
1401                                     suggested_field_name.to_string(),
1402                                     Applicability::MaybeIncorrect,
1403                                 );
1404                             } else {
1405                                 err.span_label(field.span, "unknown field");
1406                                 let struct_variant_def = def.non_enum_variant();
1407                                 let field_names = self.available_field_names(struct_variant_def);
1408                                 if !field_names.is_empty() {
1409                                     err.note(&format!("available fields are: {}",
1410                                                       self.name_series_display(field_names)));
1411                                 }
1412                             };
1413                     }
1414                     ty::Array(_, len) => {
1415                         if let (Some(len), Ok(user_index)) = (
1416                             len.assert_usize(self.tcx),
1417                             field.as_str().parse::<u64>()
1418                         ) {
1419                             let base = self.tcx.sess.source_map()
1420                                 .span_to_snippet(base.span)
1421                                 .unwrap_or_else(|_|
1422                                     self.tcx.hir().hir_to_pretty_string(base.hir_id));
1423                             let help = "instead of using tuple indexing, use array indexing";
1424                             let suggestion = format!("{}[{}]", base, field);
1425                             let applicability = if len < user_index {
1426                                 Applicability::MachineApplicable
1427                             } else {
1428                                 Applicability::MaybeIncorrect
1429                             };
1430                             err.span_suggestion(
1431                                 expr.span, help, suggestion, applicability
1432                             );
1433                         }
1434                     }
1435                     ty::RawPtr(..) => {
1436                         let base = self.tcx.sess.source_map()
1437                             .span_to_snippet(base.span)
1438                             .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1439                         let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1440                         let suggestion = format!("(*{}).{}", base, field);
1441                         err.span_suggestion(
1442                             expr.span,
1443                             &msg,
1444                             suggestion,
1445                             Applicability::MaybeIncorrect,
1446                         );
1447                     }
1448                     _ => {}
1449                 }
1450                 err
1451             } else {
1452                 type_error_struct!(self.tcx().sess, field.span, expr_t, E0610,
1453                                    "`{}` is a primitive type and therefore doesn't have fields",
1454                                    expr_t)
1455             }.emit();
1456             self.tcx().types.err
1457         }
1458     }
1459
1460     fn no_such_field_err<T: Display>(&self, span: Span, field: T, expr_t: &ty::TyS<'_>)
1461         -> DiagnosticBuilder<'_> {
1462         type_error_struct!(self.tcx().sess, span, expr_t, E0609,
1463                            "no field `{}` on type `{}`",
1464                            field, expr_t)
1465     }
1466
1467     fn check_expr_index(
1468         &self,
1469         base: &'tcx hir::Expr,
1470         idx: &'tcx hir::Expr,
1471         needs: Needs,
1472         expr: &'tcx hir::Expr,
1473     ) -> Ty<'tcx> {
1474         let base_t = self.check_expr_with_needs(&base, needs);
1475         let idx_t = self.check_expr(&idx);
1476
1477         if base_t.references_error() {
1478             base_t
1479         } else if idx_t.references_error() {
1480             idx_t
1481         } else {
1482             let base_t = self.structurally_resolved_type(base.span, base_t);
1483             match self.lookup_indexing(expr, base, base_t, idx_t, needs) {
1484                 Some((index_ty, element_ty)) => {
1485                     // two-phase not needed because index_ty is never mutable
1486                     self.demand_coerce(idx, idx_t, index_ty, AllowTwoPhase::No);
1487                     element_ty
1488                 }
1489                 None => {
1490                     let mut err =
1491                         type_error_struct!(self.tcx.sess, expr.span, base_t, E0608,
1492                                             "cannot index into a value of type `{}`",
1493                                             base_t);
1494                     // Try to give some advice about indexing tuples.
1495                     if let ty::Tuple(..) = base_t.sty {
1496                         let mut needs_note = true;
1497                         // If the index is an integer, we can show the actual
1498                         // fixed expression:
1499                         if let ExprKind::Lit(ref lit) = idx.node {
1500                             if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1501                                 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1502                                 if let Ok(snip) = snip {
1503                                     err.span_suggestion(
1504                                         expr.span,
1505                                         "to access tuple elements, use",
1506                                         format!("{}.{}", snip, i),
1507                                         Applicability::MachineApplicable,
1508                                     );
1509                                     needs_note = false;
1510                                 }
1511                             }
1512                         }
1513                         if needs_note {
1514                             err.help("to access tuple elements, use tuple indexing \
1515                                         syntax (e.g., `tuple.0`)");
1516                         }
1517                     }
1518                     err.emit();
1519                     self.tcx.types.err
1520                 }
1521             }
1522         }
1523     }
1524
1525     fn check_expr_yield(&self, value: &'tcx hir::Expr, expr: &'tcx hir::Expr) -> Ty<'tcx> {
1526         match self.yield_ty {
1527             Some(ty) => {
1528                 self.check_expr_coercable_to_type(&value, ty);
1529             }
1530             None => {
1531                 struct_span_err!(self.tcx.sess, expr.span, E0627,
1532                                     "yield statement outside of generator literal").emit();
1533             }
1534         }
1535         self.tcx.mk_unit()
1536     }
1537 }