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