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