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