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