]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/expr.rs
Use the appropriate number of type arguments in suggestion
[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                 let sig = self.tcx.fn_sig(method.def_id);
875                 // We could add a "consider `foo::<params>`" suggestion here, but I wasn't able to
876                 // trigger this codepath causing `structuraly_resolved_type` to emit an error.
877
878                 // We could do this only when type params are present in the method to reducte
879                 // memory usage, but doing it unconditionally lets us also point at the method
880                 // expression and state the resolved return value:
881                 // ```
882                 // error[E0282]: type annotations needed
883                 //    --> $DIR/issue-65611.rs:59:20
884                 //    |
885                 // LL |     let x = buffer.last().unwrap().0.clone();
886                 //    |             -------^^^^--
887                 //    |             |      |
888                 //    |             |      cannot infer type for `T`
889                 //    |             this method call resolves to `std::option::Option<&T>`
890                 //    |
891                 //    = note: type must be known at this point
892                 // ```
893                 self.tables.borrow_mut().node_method_sig_mut().insert(expr.hir_id, sig);
894
895                 self.write_method_call(expr.hir_id, method);
896                 Ok(method)
897             }
898             Err(error) => {
899                 if segment.ident.name != kw::Invalid {
900                     self.report_extended_method_error(segment, span, args, rcvr_t, error);
901                 }
902                 Err(())
903             }
904         };
905
906         // Call the generic checker.
907         self.check_method_argument_types(
908             span,
909             expr,
910             method,
911             &args[1..],
912             DontTupleArguments,
913             expected,
914         )
915     }
916
917     fn report_extended_method_error(
918         &self,
919         segment: &hir::PathSegment,
920         span: Span,
921         args: &'tcx [hir::Expr],
922         rcvr_t: Ty<'tcx>,
923         error: MethodError<'tcx>
924     ) {
925         let rcvr = &args[0];
926         let try_alt_rcvr = |err: &mut DiagnosticBuilder<'_>, rcvr_t, lang_item| {
927             if let Some(new_rcvr_t) = self.tcx.mk_lang_item(rcvr_t, lang_item) {
928                 if let Ok(pick) = self.lookup_probe(
929                     span,
930                     segment.ident,
931                     new_rcvr_t,
932                     rcvr,
933                     probe::ProbeScope::AllTraits,
934                 ) {
935                     err.span_label(
936                         pick.item.ident.span,
937                         &format!("the method is available for `{}` here", new_rcvr_t),
938                     );
939                 }
940             }
941         };
942
943         if let Some(mut err) = self.report_method_error(
944             span,
945             rcvr_t,
946             segment.ident,
947             SelfSource::MethodCall(rcvr),
948             error,
949             Some(args),
950         ) {
951             if let ty::Adt(..) = rcvr_t.kind {
952                 // Try alternative arbitrary self types that could fulfill this call.
953                 // FIXME: probe for all types that *could* be arbitrary self-types, not
954                 // just this whitelist.
955                 try_alt_rcvr(&mut err, rcvr_t, lang_items::OwnedBoxLangItem);
956                 try_alt_rcvr(&mut err, rcvr_t, lang_items::PinTypeLangItem);
957                 try_alt_rcvr(&mut err, rcvr_t, lang_items::Arc);
958                 try_alt_rcvr(&mut err, rcvr_t, lang_items::Rc);
959             }
960             err.emit();
961         }
962     }
963
964     fn check_expr_cast(
965         &self,
966         e: &'tcx hir::Expr,
967         t: &'tcx hir::Ty,
968         expr: &'tcx hir::Expr,
969     ) -> Ty<'tcx> {
970         // Find the type of `e`. Supply hints based on the type we are casting to,
971         // if appropriate.
972         let t_cast = self.to_ty_saving_user_provided_ty(t);
973         let t_cast = self.resolve_vars_if_possible(&t_cast);
974         let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
975         let t_cast = self.resolve_vars_if_possible(&t_cast);
976
977         // Eagerly check for some obvious errors.
978         if t_expr.references_error() || t_cast.references_error() {
979             self.tcx.types.err
980         } else {
981             // Defer other checks until we're done type checking.
982             let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
983             match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
984                 Ok(cast_check) => {
985                     deferred_cast_checks.push(cast_check);
986                     t_cast
987                 }
988                 Err(ErrorReported) => {
989                     self.tcx.types.err
990                 }
991             }
992         }
993     }
994
995     fn check_expr_array(
996         &self,
997         args: &'tcx [hir::Expr],
998         expected: Expectation<'tcx>,
999         expr: &'tcx hir::Expr
1000     ) -> Ty<'tcx> {
1001         let uty = expected.to_option(self).and_then(|uty| {
1002             match uty.kind {
1003                 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1004                 _ => None
1005             }
1006         });
1007
1008         let element_ty = if !args.is_empty() {
1009             let coerce_to = uty.unwrap_or_else(|| {
1010                 self.next_ty_var(TypeVariableOrigin {
1011                     kind: TypeVariableOriginKind::TypeInference,
1012                     span: expr.span,
1013                 })
1014             });
1015             let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
1016             assert_eq!(self.diverges.get(), Diverges::Maybe);
1017             for e in args {
1018                 let e_ty = self.check_expr_with_hint(e, coerce_to);
1019                 let cause = self.misc(e.span);
1020                 coerce.coerce(self, &cause, e, e_ty);
1021             }
1022             coerce.complete(self)
1023         } else {
1024             self.next_ty_var(TypeVariableOrigin {
1025                 kind: TypeVariableOriginKind::TypeInference,
1026                 span: expr.span,
1027             })
1028         };
1029         self.tcx.mk_array(element_ty, args.len() as u64)
1030     }
1031
1032     fn check_expr_repeat(
1033         &self,
1034         element: &'tcx hir::Expr,
1035         count: &'tcx hir::AnonConst,
1036         expected: Expectation<'tcx>,
1037         _expr: &'tcx hir::Expr,
1038     ) -> Ty<'tcx> {
1039         let tcx = self.tcx;
1040         let count_def_id = tcx.hir().local_def_id(count.hir_id);
1041         let count = if self.const_param_def_id(count).is_some() {
1042             Ok(self.to_const(count, tcx.type_of(count_def_id)))
1043         } else {
1044             let param_env = ty::ParamEnv::empty();
1045             let substs = InternalSubsts::identity_for_item(tcx, count_def_id);
1046             let instance = ty::Instance::resolve(
1047                 tcx,
1048                 param_env,
1049                 count_def_id,
1050                 substs,
1051             ).unwrap();
1052             let global_id = GlobalId {
1053                 instance,
1054                 promoted: None
1055             };
1056
1057             tcx.const_eval(param_env.and(global_id))
1058         };
1059
1060         let uty = match expected {
1061             ExpectHasType(uty) => {
1062                 match uty.kind {
1063                     ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1064                     _ => None
1065                 }
1066             }
1067             _ => None
1068         };
1069
1070         let (element_ty, t) = match uty {
1071             Some(uty) => {
1072                 self.check_expr_coercable_to_type(&element, uty);
1073                 (uty, uty)
1074             }
1075             None => {
1076                 let ty = self.next_ty_var(TypeVariableOrigin {
1077                     kind: TypeVariableOriginKind::MiscVariable,
1078                     span: element.span,
1079                 });
1080                 let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
1081                 (element_ty, ty)
1082             }
1083         };
1084
1085         if element_ty.references_error() {
1086             tcx.types.err
1087         } else if let Ok(count) = count {
1088             tcx.mk_ty(ty::Array(t, count))
1089         } else {
1090             tcx.types.err
1091         }
1092     }
1093
1094     fn check_expr_tuple(
1095         &self,
1096         elts: &'tcx [hir::Expr],
1097         expected: Expectation<'tcx>,
1098         expr: &'tcx hir::Expr,
1099     ) -> Ty<'tcx> {
1100         let flds = expected.only_has_type(self).and_then(|ty| {
1101             let ty = self.resolve_vars_with_obligations(ty);
1102             match ty.kind {
1103                 ty::Tuple(ref flds) => Some(&flds[..]),
1104                 _ => None
1105             }
1106         });
1107
1108         let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
1109             let t = match flds {
1110                 Some(ref fs) if i < fs.len() => {
1111                     let ety = fs[i].expect_ty();
1112                     self.check_expr_coercable_to_type(&e, ety);
1113                     ety
1114                 }
1115                 _ => {
1116                     self.check_expr_with_expectation(&e, NoExpectation)
1117                 }
1118             };
1119             t
1120         });
1121         let tuple = self.tcx.mk_tup(elt_ts_iter);
1122         if tuple.references_error() {
1123             self.tcx.types.err
1124         } else {
1125             self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1126             tuple
1127         }
1128     }
1129
1130     fn check_expr_struct(
1131         &self,
1132         expr: &hir::Expr,
1133         expected: Expectation<'tcx>,
1134         qpath: &QPath,
1135         fields: &'tcx [hir::Field],
1136         base_expr: &'tcx Option<P<hir::Expr>>,
1137     ) -> Ty<'tcx> {
1138         // Find the relevant variant
1139         let (variant, adt_ty) =
1140             if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) {
1141                 variant_ty
1142             } else {
1143                 self.check_struct_fields_on_error(fields, base_expr);
1144                 return self.tcx.types.err;
1145             };
1146
1147         let path_span = match *qpath {
1148             QPath::Resolved(_, ref path) => path.span,
1149             QPath::TypeRelative(ref qself, _) => qself.span
1150         };
1151
1152         // Prohibit struct expressions when non-exhaustive flag is set.
1153         let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1154         if !adt.did.is_local() && variant.is_field_list_non_exhaustive() {
1155             span_err!(self.tcx.sess, expr.span, E0639,
1156                       "cannot create non-exhaustive {} using struct expression",
1157                       adt.variant_descr());
1158         }
1159
1160         let error_happened = self.check_expr_struct_fields(adt_ty, expected, expr.hir_id, path_span,
1161                                                            variant, fields, base_expr.is_none());
1162         if let &Some(ref base_expr) = base_expr {
1163             // If check_expr_struct_fields hit an error, do not attempt to populate
1164             // the fields with the base_expr. This could cause us to hit errors later
1165             // when certain fields are assumed to exist that in fact do not.
1166             if !error_happened {
1167                 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {});
1168                 match adt_ty.kind {
1169                     ty::Adt(adt, substs) if adt.is_struct() => {
1170                         let fru_field_types = adt.non_enum_variant().fields.iter().map(|f| {
1171                             self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs))
1172                         }).collect();
1173
1174                         self.tables
1175                             .borrow_mut()
1176                             .fru_field_types_mut()
1177                             .insert(expr.hir_id, fru_field_types);
1178                     }
1179                     _ => {
1180                         span_err!(self.tcx.sess, base_expr.span, E0436,
1181                                   "functional record update syntax requires a struct");
1182                     }
1183                 }
1184             }
1185         }
1186         self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1187         adt_ty
1188     }
1189
1190     fn check_expr_struct_fields(
1191         &self,
1192         adt_ty: Ty<'tcx>,
1193         expected: Expectation<'tcx>,
1194         expr_id: hir::HirId,
1195         span: Span,
1196         variant: &'tcx ty::VariantDef,
1197         ast_fields: &'tcx [hir::Field],
1198         check_completeness: bool,
1199     ) -> bool {
1200         let tcx = self.tcx;
1201
1202         let adt_ty_hint =
1203             self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
1204                 .get(0).cloned().unwrap_or(adt_ty);
1205         // re-link the regions that EIfEO can erase.
1206         self.demand_eqtype(span, adt_ty_hint, adt_ty);
1207
1208         let (substs, adt_kind, kind_name) = match &adt_ty.kind {
1209             &ty::Adt(adt, substs) => {
1210                 (substs, adt.adt_kind(), adt.variant_descr())
1211             }
1212             _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
1213         };
1214
1215         let mut remaining_fields = variant.fields.iter().enumerate().map(|(i, field)|
1216             (field.ident.modern(), (i, field))
1217         ).collect::<FxHashMap<_, _>>();
1218
1219         let mut seen_fields = FxHashMap::default();
1220
1221         let mut error_happened = false;
1222
1223         // Type-check each field.
1224         for field in ast_fields {
1225             let ident = tcx.adjust_ident(field.ident, variant.def_id);
1226             let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1227                 seen_fields.insert(ident, field.span);
1228                 self.write_field_index(field.hir_id, i);
1229
1230                 // We don't look at stability attributes on
1231                 // struct-like enums (yet...), but it's definitely not
1232                 // a bug to have constructed one.
1233                 if adt_kind != AdtKind::Enum {
1234                     tcx.check_stability(v_field.did, Some(expr_id), field.span);
1235                 }
1236
1237                 self.field_ty(field.span, v_field, substs)
1238             } else {
1239                 error_happened = true;
1240                 if let Some(prev_span) = seen_fields.get(&ident) {
1241                     let mut err = struct_span_err!(self.tcx.sess,
1242                                                    field.ident.span,
1243                                                    E0062,
1244                                                    "field `{}` specified more than once",
1245                                                    ident);
1246
1247                     err.span_label(field.ident.span, "used more than once");
1248                     err.span_label(*prev_span, format!("first use of `{}`", ident));
1249
1250                     err.emit();
1251                 } else {
1252                     self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name, span);
1253                 }
1254
1255                 tcx.types.err
1256             };
1257
1258             // Make sure to give a type to the field even if there's
1259             // an error, so we can continue type-checking.
1260             self.check_expr_coercable_to_type(&field.expr, field_type);
1261         }
1262
1263         // Make sure the programmer specified correct number of fields.
1264         if kind_name == "union" {
1265             if ast_fields.len() != 1 {
1266                 tcx.sess.span_err(span, "union expressions should have exactly one field");
1267             }
1268         } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
1269             let len = remaining_fields.len();
1270
1271             let mut displayable_field_names = remaining_fields
1272                                               .keys()
1273                                               .map(|ident| ident.as_str())
1274                                               .collect::<Vec<_>>();
1275
1276             displayable_field_names.sort();
1277
1278             let truncated_fields_error = if len <= 3 {
1279                 String::new()
1280             } else {
1281                 format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
1282             };
1283
1284             let remaining_fields_names = displayable_field_names.iter().take(3)
1285                                         .map(|n| format!("`{}`", n))
1286                                         .collect::<Vec<_>>()
1287                                         .join(", ");
1288
1289             struct_span_err!(tcx.sess, span, E0063,
1290                              "missing field{} {}{} in initializer of `{}`",
1291                              pluralize!(remaining_fields.len()),
1292                              remaining_fields_names,
1293                              truncated_fields_error,
1294                              adt_ty)
1295                 .span_label(span, format!("missing {}{}",
1296                                           remaining_fields_names,
1297                                           truncated_fields_error))
1298                 .emit();
1299         }
1300         error_happened
1301     }
1302
1303     fn check_struct_fields_on_error(
1304         &self,
1305         fields: &'tcx [hir::Field],
1306         base_expr: &'tcx Option<P<hir::Expr>>,
1307     ) {
1308         for field in fields {
1309             self.check_expr(&field.expr);
1310         }
1311         if let Some(ref base) = *base_expr {
1312             self.check_expr(&base);
1313         }
1314     }
1315
1316     fn report_unknown_field(
1317         &self,
1318         ty: Ty<'tcx>,
1319         variant: &'tcx ty::VariantDef,
1320         field: &hir::Field,
1321         skip_fields: &[hir::Field],
1322         kind_name: &str,
1323         ty_span: Span
1324     ) {
1325         if variant.recovered {
1326             return;
1327         }
1328         let mut err = self.type_error_struct_with_diag(
1329             field.ident.span,
1330             |actual| match ty.kind {
1331                 ty::Adt(adt, ..) if adt.is_enum() => {
1332                     struct_span_err!(self.tcx.sess, field.ident.span, E0559,
1333                                      "{} `{}::{}` has no field named `{}`",
1334                                      kind_name, actual, variant.ident, field.ident)
1335                 }
1336                 _ => {
1337                     struct_span_err!(self.tcx.sess, field.ident.span, E0560,
1338                                      "{} `{}` has no field named `{}`",
1339                                      kind_name, actual, field.ident)
1340                 }
1341             },
1342             ty);
1343         match variant.ctor_kind {
1344             CtorKind::Fn => {
1345                 err.span_label(variant.ident.span, format!("`{adt}` defined here", adt=ty));
1346                 err.span_label(field.ident.span, "field does not exist");
1347                 err.span_label(ty_span, format!(
1348                         "`{adt}` is a tuple {kind_name}, \
1349                          use the appropriate syntax: `{adt}(/* fields */)`",
1350                     adt=ty,
1351                     kind_name=kind_name
1352                 ));
1353             }
1354             _ => {
1355                 // prevent all specified fields from being suggested
1356                 let skip_fields = skip_fields.iter().map(|ref x| x.ident.name);
1357                 if let Some(field_name) = Self::suggest_field_name(
1358                     variant,
1359                     &field.ident.as_str(),
1360                     skip_fields.collect()
1361                 ) {
1362                     err.span_suggestion(
1363                         field.ident.span,
1364                         "a field with a similar name exists",
1365                         field_name.to_string(),
1366                         Applicability::MaybeIncorrect,
1367                     );
1368                 } else {
1369                     match ty.kind {
1370                         ty::Adt(adt, ..) => {
1371                             if adt.is_enum() {
1372                                 err.span_label(field.ident.span, format!(
1373                                     "`{}::{}` does not have this field",
1374                                     ty,
1375                                     variant.ident
1376                                 ));
1377                             } else {
1378                                 err.span_label(field.ident.span, format!(
1379                                     "`{}` does not have this field",
1380                                     ty
1381                                 ));
1382                             }
1383                             let available_field_names = self.available_field_names(variant);
1384                             if !available_field_names.is_empty() {
1385                                 err.note(&format!("available fields are: {}",
1386                                                   self.name_series_display(available_field_names)));
1387                             }
1388                         }
1389                         _ => bug!("non-ADT passed to report_unknown_field")
1390                     }
1391                 };
1392             }
1393         }
1394         err.emit();
1395     }
1396
1397     // Return an hint about the closest match in field names
1398     fn suggest_field_name(variant: &'tcx ty::VariantDef,
1399                           field: &str,
1400                           skip: Vec<Symbol>)
1401                           -> Option<Symbol> {
1402         let names = variant.fields.iter().filter_map(|field| {
1403             // ignore already set fields and private fields from non-local crates
1404             if skip.iter().any(|&x| x == field.ident.name) ||
1405                (!variant.def_id.is_local() && field.vis != Visibility::Public)
1406             {
1407                 None
1408             } else {
1409                 Some(&field.ident.name)
1410             }
1411         });
1412
1413         find_best_match_for_name(names, field, None)
1414     }
1415
1416     fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<ast::Name> {
1417         variant.fields.iter().filter(|field| {
1418             let def_scope =
1419                 self.tcx.adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id).1;
1420             field.vis.is_accessible_from(def_scope, self.tcx)
1421         })
1422         .map(|field| field.ident.name)
1423         .collect()
1424     }
1425
1426     fn name_series_display(&self, names: Vec<ast::Name>) -> String {
1427         // dynamic limit, to never omit just one field
1428         let limit = if names.len() == 6 { 6 } else { 5 };
1429         let mut display = names.iter().take(limit)
1430             .map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1431         if names.len() > limit {
1432             display = format!("{} ... and {} others", display, names.len() - limit);
1433         }
1434         display
1435     }
1436
1437     // Check field access expressions
1438     fn check_field(
1439         &self,
1440         expr: &'tcx hir::Expr,
1441         needs: Needs,
1442         base: &'tcx hir::Expr,
1443         field: ast::Ident,
1444     ) -> Ty<'tcx> {
1445         let expr_t = self.check_expr_with_needs(base, needs);
1446         let expr_t = self.structurally_resolved_type(base.span,
1447                                                      expr_t);
1448         let mut private_candidate = None;
1449         let mut autoderef = self.autoderef(expr.span, expr_t);
1450         while let Some((base_t, _)) = autoderef.next() {
1451             match base_t.kind {
1452                 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1453                     debug!("struct named {:?}",  base_t);
1454                     let (ident, def_scope) =
1455                         self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id);
1456                     let fields = &base_def.non_enum_variant().fields;
1457                     if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) {
1458                         let field = &fields[index];
1459                         let field_ty = self.field_ty(expr.span, field, substs);
1460                         // Save the index of all fields regardless of their visibility in case
1461                         // of error recovery.
1462                         self.write_field_index(expr.hir_id, index);
1463                         if field.vis.is_accessible_from(def_scope, self.tcx) {
1464                             let adjustments = autoderef.adjust_steps(self, needs);
1465                             self.apply_adjustments(base, adjustments);
1466                             autoderef.finalize(self);
1467
1468                             self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span);
1469                             return field_ty;
1470                         }
1471                         private_candidate = Some((base_def.did, field_ty));
1472                     }
1473                 }
1474                 ty::Tuple(ref tys) => {
1475                     let fstr = field.as_str();
1476                     if let Ok(index) = fstr.parse::<usize>() {
1477                         if fstr == index.to_string() {
1478                             if let Some(field_ty) = tys.get(index) {
1479                                 let adjustments = autoderef.adjust_steps(self, needs);
1480                                 self.apply_adjustments(base, adjustments);
1481                                 autoderef.finalize(self);
1482
1483                                 self.write_field_index(expr.hir_id, index);
1484                                 return field_ty.expect_ty();
1485                             }
1486                         }
1487                     }
1488                 }
1489                 _ => {}
1490             }
1491         }
1492         autoderef.unambiguous_final_ty(self);
1493
1494         if let Some((did, field_ty)) = private_candidate {
1495             self.ban_private_field_access(expr, expr_t, field, did);
1496             return field_ty;
1497         }
1498
1499         if field.name == kw::Invalid {
1500         } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1501             self.ban_take_value_of_method(expr, expr_t, field);
1502         } else if !expr_t.is_primitive_ty() {
1503             self.ban_nonexisting_field(field, base, expr, expr_t);
1504         } else {
1505             type_error_struct!(
1506                 self.tcx().sess,
1507                 field.span,
1508                 expr_t,
1509                 E0610,
1510                 "`{}` is a primitive type and therefore doesn't have fields",
1511                 expr_t
1512             )
1513             .emit();
1514         }
1515
1516         self.tcx().types.err
1517     }
1518
1519     fn ban_nonexisting_field(
1520         &self,
1521         field: ast::Ident,
1522         base: &'tcx hir::Expr,
1523         expr: &'tcx hir::Expr,
1524         expr_t: Ty<'tcx>,
1525     ) {
1526         let mut err = self.no_such_field_err(field.span, field, expr_t);
1527
1528         match expr_t.peel_refs().kind {
1529             ty::Array(_, len) => {
1530                 self.maybe_suggest_array_indexing(&mut err, expr, base, field, len);
1531             }
1532             ty::RawPtr(..) => {
1533                 self.suggest_first_deref_field(&mut err, expr, base, field);
1534             }
1535             ty::Adt(def, _) if !def.is_enum() => {
1536                 self.suggest_fields_on_recordish(&mut err, def, field);
1537             }
1538             ty::Param(param_ty) => {
1539                 self.point_at_param_definition(&mut err, param_ty);
1540             }
1541             _ => {}
1542         }
1543
1544         if field.name == kw::Await {
1545             // We know by construction that `<expr>.await` is either on Rust 2015
1546             // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
1547             err.note("to `.await` a `Future`, switch to Rust 2018");
1548             err.help("set `edition = \"2018\"` in `Cargo.toml`");
1549             err.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
1550         }
1551
1552         err.emit();
1553     }
1554
1555     fn ban_private_field_access(
1556         &self,
1557         expr: &hir::Expr,
1558         expr_t: Ty<'tcx>,
1559         field: ast::Ident,
1560         base_did: DefId,
1561     ) {
1562         let struct_path = self.tcx().def_path_str(base_did);
1563         let kind_name = match self.tcx().def_kind(base_did) {
1564             Some(def_kind) => def_kind.descr(base_did),
1565             _ => " ",
1566         };
1567         let mut err = struct_span_err!(
1568             self.tcx().sess,
1569             expr.span,
1570             E0616,
1571             "field `{}` of {} `{}` is private",
1572             field,
1573             kind_name,
1574             struct_path
1575         );
1576         // Also check if an accessible method exists, which is often what is meant.
1577         if self.method_exists(field, expr_t, expr.hir_id, false)
1578             && !self.expr_in_place(expr.hir_id)
1579         {
1580             self.suggest_method_call(
1581                 &mut err,
1582                 &format!("a method `{}` also exists, call it with parentheses", field),
1583                 field,
1584                 expr_t,
1585                 expr.hir_id,
1586             );
1587         }
1588         err.emit();
1589     }
1590
1591     fn ban_take_value_of_method(&self, expr: &hir::Expr, expr_t: Ty<'tcx>, field: ast::Ident) {
1592         let mut err = type_error_struct!(
1593             self.tcx().sess,
1594             field.span,
1595             expr_t,
1596             E0615,
1597             "attempted to take value of method `{}` on type `{}`",
1598             field,
1599             expr_t
1600         );
1601
1602         if !self.expr_in_place(expr.hir_id) {
1603             self.suggest_method_call(
1604                 &mut err,
1605                 "use parentheses to call the method",
1606                 field,
1607                 expr_t,
1608                 expr.hir_id
1609             );
1610         } else {
1611             err.help("methods are immutable and cannot be assigned to");
1612         }
1613
1614         err.emit();
1615     }
1616
1617     fn point_at_param_definition(&self, err: &mut DiagnosticBuilder<'_>, param: ty::ParamTy) {
1618         let generics = self.tcx.generics_of(self.body_id.owner_def_id());
1619         let generic_param = generics.type_param(&param, self.tcx);
1620         if let ty::GenericParamDefKind::Type{synthetic: Some(..), ..} = generic_param.kind {
1621             return;
1622         }
1623         let param_def_id = generic_param.def_id;
1624         let param_hir_id = match self.tcx.hir().as_local_hir_id(param_def_id) {
1625             Some(x) => x,
1626             None    => return,
1627         };
1628         let param_span = self.tcx.hir().span(param_hir_id);
1629         let param_name = self.tcx.hir().ty_param_name(param_hir_id);
1630
1631         err.span_label(param_span, &format!("type parameter '{}' declared here", param_name));
1632     }
1633
1634     fn suggest_fields_on_recordish(
1635         &self,
1636         err: &mut DiagnosticBuilder<'_>,
1637         def: &'tcx ty::AdtDef,
1638         field: ast::Ident,
1639     ) {
1640         if let Some(suggested_field_name) =
1641             Self::suggest_field_name(def.non_enum_variant(), &field.as_str(), vec![])
1642         {
1643             err.span_suggestion(
1644                 field.span,
1645                 "a field with a similar name exists",
1646                 suggested_field_name.to_string(),
1647                 Applicability::MaybeIncorrect,
1648             );
1649         } else {
1650             err.span_label(field.span, "unknown field");
1651             let struct_variant_def = def.non_enum_variant();
1652             let field_names = self.available_field_names(struct_variant_def);
1653             if !field_names.is_empty() {
1654                 err.note(&format!(
1655                     "available fields are: {}",
1656                     self.name_series_display(field_names),
1657                 ));
1658             }
1659         }
1660     }
1661
1662     fn maybe_suggest_array_indexing(
1663         &self,
1664         err: &mut DiagnosticBuilder<'_>,
1665         expr: &hir::Expr,
1666         base: &hir::Expr,
1667         field: ast::Ident,
1668         len: &ty::Const<'tcx>,
1669     ) {
1670         if let (Some(len), Ok(user_index)) = (
1671             len.try_eval_usize(self.tcx, self.param_env),
1672             field.as_str().parse::<u64>()
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 help = "instead of using tuple indexing, use array indexing";
1678             let suggestion = format!("{}[{}]", base, field);
1679             let applicability = if len < user_index {
1680                 Applicability::MachineApplicable
1681             } else {
1682                 Applicability::MaybeIncorrect
1683             };
1684             err.span_suggestion(expr.span, help, suggestion, applicability);
1685         }
1686     }
1687
1688     fn suggest_first_deref_field(
1689         &self,
1690         err: &mut DiagnosticBuilder<'_>,
1691         expr: &hir::Expr,
1692         base: &hir::Expr,
1693         field: ast::Ident,
1694     ) {
1695         let base = self.tcx.sess.source_map()
1696             .span_to_snippet(base.span)
1697             .unwrap_or_else(|_| self.tcx.hir().hir_to_pretty_string(base.hir_id));
1698         let msg = format!("`{}` is a raw pointer; try dereferencing it", base);
1699         let suggestion = format!("(*{}).{}", base, field);
1700         err.span_suggestion(
1701             expr.span,
1702             &msg,
1703             suggestion,
1704             Applicability::MaybeIncorrect,
1705         );
1706     }
1707
1708     fn no_such_field_err<T: Display>(&self, span: Span, field: T, expr_t: &ty::TyS<'_>)
1709         -> DiagnosticBuilder<'_> {
1710         type_error_struct!(self.tcx().sess, span, expr_t, E0609,
1711                            "no field `{}` on type `{}`",
1712                            field, expr_t)
1713     }
1714
1715     fn check_expr_index(
1716         &self,
1717         base: &'tcx hir::Expr,
1718         idx: &'tcx hir::Expr,
1719         needs: Needs,
1720         expr: &'tcx hir::Expr,
1721     ) -> Ty<'tcx> {
1722         let base_t = self.check_expr_with_needs(&base, needs);
1723         let idx_t = self.check_expr(&idx);
1724
1725         if base_t.references_error() {
1726             base_t
1727         } else if idx_t.references_error() {
1728             idx_t
1729         } else {
1730             let base_t = self.structurally_resolved_type(base.span, base_t);
1731             match self.lookup_indexing(expr, base, base_t, idx_t, needs) {
1732                 Some((index_ty, element_ty)) => {
1733                     // two-phase not needed because index_ty is never mutable
1734                     self.demand_coerce(idx, idx_t, index_ty, AllowTwoPhase::No);
1735                     element_ty
1736                 }
1737                 None => {
1738                     let mut err =
1739                         type_error_struct!(self.tcx.sess, expr.span, base_t, E0608,
1740                                             "cannot index into a value of type `{}`",
1741                                             base_t);
1742                     // Try to give some advice about indexing tuples.
1743                     if let ty::Tuple(..) = base_t.kind {
1744                         let mut needs_note = true;
1745                         // If the index is an integer, we can show the actual
1746                         // fixed expression:
1747                         if let ExprKind::Lit(ref lit) = idx.kind {
1748                             if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
1749                                 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
1750                                 if let Ok(snip) = snip {
1751                                     err.span_suggestion(
1752                                         expr.span,
1753                                         "to access tuple elements, use",
1754                                         format!("{}.{}", snip, i),
1755                                         Applicability::MachineApplicable,
1756                                     );
1757                                     needs_note = false;
1758                                 }
1759                             }
1760                         }
1761                         if needs_note {
1762                             err.help("to access tuple elements, use tuple indexing \
1763                                         syntax (e.g., `tuple.0`)");
1764                         }
1765                     }
1766                     err.emit();
1767                     self.tcx.types.err
1768                 }
1769             }
1770         }
1771     }
1772
1773     fn check_expr_yield(
1774         &self,
1775         value: &'tcx hir::Expr,
1776         expr: &'tcx hir::Expr,
1777         src: &'tcx hir::YieldSource
1778     ) -> Ty<'tcx> {
1779         match self.yield_ty {
1780             Some(ty) => {
1781                 self.check_expr_coercable_to_type(&value, ty);
1782             }
1783             // Given that this `yield` expression was generated as a result of lowering a `.await`,
1784             // we know that the yield type must be `()`; however, the context won't contain this
1785             // information. Hence, we check the source of the yield expression here and check its
1786             // value's type against `()` (this check should always hold).
1787             None if src == &hir::YieldSource::Await => {
1788                 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit());
1789             }
1790             _ => {
1791                 struct_span_err!(self.tcx.sess, expr.span, E0627,
1792                                     "yield statement outside of generator literal").emit();
1793             }
1794         }
1795         self.tcx.mk_unit()
1796     }
1797 }
1798
1799 pub(super) fn ty_kind_suggestion(ty: Ty<'_>) -> Option<&'static str> {
1800     Some(match ty.kind {
1801         ty::Bool => "true",
1802         ty::Char => "'a'",
1803         ty::Int(_) | ty::Uint(_) => "42",
1804         ty::Float(_) => "3.14159",
1805         ty::Error | ty::Never => return None,
1806         _ => "value",
1807     })
1808 }