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