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