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