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