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