]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/expr.rs
Rollup merge of #94022 - jongiddy:cow-into-owned-docs, r=Dylan-DPC
[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::SelfSource;
10 use crate::check::report_unexpected_variant_res;
11 use crate::check::BreakableCtxt;
12 use crate::check::Diverges;
13 use crate::check::DynamicCoerceMany;
14 use crate::check::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation};
15 use crate::check::FnCtxt;
16 use crate::check::Needs;
17 use crate::check::TupleArgumentsFlag::DontTupleArguments;
18 use crate::errors::{
19     FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct,
20     YieldExprOutsideOfGenerator,
21 };
22 use crate::type_error_struct;
23
24 use crate::errors::{AddressOfTemporaryTaken, ReturnStmtOutsideOfFnBody, StructExprNonExhaustive};
25 use rustc_ast as ast;
26 use rustc_data_structures::fx::FxHashMap;
27 use rustc_data_structures::stack::ensure_sufficient_stack;
28 use rustc_errors::Diagnostic;
29 use rustc_errors::ErrorGuaranteed;
30 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, DiagnosticId};
31 use rustc_hir as hir;
32 use rustc_hir::def::{CtorKind, DefKind, Res};
33 use rustc_hir::def_id::DefId;
34 use rustc_hir::intravisit::Visitor;
35 use rustc_hir::lang_items::LangItem;
36 use rustc_hir::{ExprKind, HirId, QPath};
37 use rustc_infer::infer;
38 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
39 use rustc_infer::infer::InferOk;
40 use rustc_middle::middle::stability;
41 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
42 use rustc_middle::ty::error::ExpectedFound;
43 use rustc_middle::ty::error::TypeError::{FieldMisMatch, Sorts};
44 use rustc_middle::ty::subst::SubstsRef;
45 use rustc_middle::ty::{self, AdtKind, Ty, TypeFoldable};
46 use rustc_session::parse::feature_err;
47 use rustc_span::hygiene::DesugaringKind;
48 use rustc_span::lev_distance::find_best_match_for_name;
49 use rustc_span::source_map::Span;
50 use rustc_span::symbol::{kw, sym, Ident, Symbol};
51 use rustc_span::{BytePos, Pos};
52 use rustc_trait_selection::traits::{self, ObligationCauseCode};
53
54 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
55     fn check_expr_eq_type(&self, expr: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>) {
56         let ty = self.check_expr_with_hint(expr, expected);
57         self.demand_eqtype(expr.span, expected, ty);
58     }
59
60     pub fn check_expr_has_type_or_error(
61         &self,
62         expr: &'tcx hir::Expr<'tcx>,
63         expected: Ty<'tcx>,
64         extend_err: impl Fn(&mut Diagnostic),
65     ) -> Ty<'tcx> {
66         self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err)
67     }
68
69     fn check_expr_meets_expectation_or_error(
70         &self,
71         expr: &'tcx hir::Expr<'tcx>,
72         expected: Expectation<'tcx>,
73         extend_err: impl Fn(&mut Diagnostic),
74     ) -> Ty<'tcx> {
75         let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
76         let mut ty = self.check_expr_with_expectation(expr, expected);
77
78         // While we don't allow *arbitrary* coercions here, we *do* allow
79         // coercions from ! to `expected`.
80         if ty.is_never() {
81             if let Some(adjustments) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
82                 self.tcx().sess.delay_span_bug(
83                     expr.span,
84                     "expression with never type wound up being adjusted",
85                 );
86                 return if let [Adjustment { kind: Adjust::NeverToAny, target }] = &adjustments[..] {
87                     target.to_owned()
88                 } else {
89                     self.tcx().ty_error()
90                 };
91             }
92
93             let adj_ty = self.next_ty_var(TypeVariableOrigin {
94                 kind: TypeVariableOriginKind::AdjustmentType,
95                 span: expr.span,
96             });
97             self.apply_adjustments(
98                 expr,
99                 vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }],
100             );
101             ty = adj_ty;
102         }
103
104         if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
105             let expr = expr.peel_drop_temps();
106             self.suggest_deref_ref_or_into(&mut err, expr, expected_ty, ty, None);
107             extend_err(&mut err);
108             err.emit();
109         }
110         ty
111     }
112
113     pub(super) fn check_expr_coercable_to_type(
114         &self,
115         expr: &'tcx hir::Expr<'tcx>,
116         expected: Ty<'tcx>,
117         expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
118     ) -> Ty<'tcx> {
119         let ty = self.check_expr_with_hint(expr, expected);
120         // checks don't need two phase
121         self.demand_coerce(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No)
122     }
123
124     pub(super) fn check_expr_with_hint(
125         &self,
126         expr: &'tcx hir::Expr<'tcx>,
127         expected: Ty<'tcx>,
128     ) -> Ty<'tcx> {
129         self.check_expr_with_expectation(expr, ExpectHasType(expected))
130     }
131
132     fn check_expr_with_expectation_and_needs(
133         &self,
134         expr: &'tcx hir::Expr<'tcx>,
135         expected: Expectation<'tcx>,
136         needs: Needs,
137     ) -> Ty<'tcx> {
138         let ty = self.check_expr_with_expectation(expr, expected);
139
140         // If the expression is used in a place whether mutable place is required
141         // e.g. LHS of assignment, perform the conversion.
142         if let Needs::MutPlace = needs {
143             self.convert_place_derefs_to_mutable(expr);
144         }
145
146         ty
147     }
148
149     pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
150         self.check_expr_with_expectation(expr, NoExpectation)
151     }
152
153     pub(super) fn check_expr_with_needs(
154         &self,
155         expr: &'tcx hir::Expr<'tcx>,
156         needs: Needs,
157     ) -> Ty<'tcx> {
158         self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
159     }
160
161     /// Invariant:
162     /// If an expression has any sub-expressions that result in a type error,
163     /// inspecting that expression's type with `ty.references_error()` will return
164     /// true. Likewise, if an expression is known to diverge, inspecting its
165     /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
166     /// strict, _|_ can appear in the type of an expression that does not,
167     /// itself, diverge: for example, fn() -> _|_.)
168     /// Note that inspecting a type's structure *directly* may expose the fact
169     /// that there are actually multiple representations for `Error`, so avoid
170     /// that when err needs to be handled differently.
171     #[instrument(skip(self, expr), level = "debug")]
172     pub(super) fn check_expr_with_expectation(
173         &self,
174         expr: &'tcx hir::Expr<'tcx>,
175         expected: Expectation<'tcx>,
176     ) -> Ty<'tcx> {
177         self.check_expr_with_expectation_and_args(expr, expected, &[])
178     }
179
180     /// Same as `check_expr_with_expectation`, but allows us to pass in the arguments of a
181     /// `ExprKind::Call` when evaluating its callee when it is an `ExprKind::Path`.
182     pub(super) fn check_expr_with_expectation_and_args(
183         &self,
184         expr: &'tcx hir::Expr<'tcx>,
185         expected: Expectation<'tcx>,
186         args: &'tcx [hir::Expr<'tcx>],
187     ) -> Ty<'tcx> {
188         if self.tcx().sess.verbose() {
189             // make this code only run with -Zverbose because it is probably slow
190             if let Ok(lint_str) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
191                 if !lint_str.contains('\n') {
192                     debug!("expr text: {lint_str}");
193                 } else {
194                     let mut lines = lint_str.lines();
195                     if let Some(line0) = lines.next() {
196                         let remaining_lines = lines.count();
197                         debug!("expr text: {line0}");
198                         debug!("expr text: ...(and {remaining_lines} more lines)");
199                     }
200                 }
201             }
202         }
203
204         // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
205         // without the final expr (e.g. `try { return; }`). We don't want to generate an
206         // unreachable_code lint for it since warnings for autogenerated code are confusing.
207         let is_try_block_generated_unit_expr = match expr.kind {
208             ExprKind::Call(_, args) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {
209                 args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock)
210             }
211
212             _ => false,
213         };
214
215         // Warn for expressions after diverging siblings.
216         if !is_try_block_generated_unit_expr {
217             self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
218         }
219
220         // Hide the outer diverging and has_errors flags.
221         let old_diverges = self.diverges.replace(Diverges::Maybe);
222         let old_has_errors = self.has_errors.replace(false);
223
224         let ty = ensure_sufficient_stack(|| match &expr.kind {
225             hir::ExprKind::Path(
226                 qpath @ hir::QPath::Resolved(..) | qpath @ hir::QPath::TypeRelative(..),
227             ) => self.check_expr_path(qpath, expr, args),
228             _ => self.check_expr_kind(expr, expected),
229         });
230
231         // Warn for non-block expressions with diverging children.
232         match expr.kind {
233             ExprKind::Block(..)
234             | ExprKind::If(..)
235             | ExprKind::Let(..)
236             | ExprKind::Loop(..)
237             | ExprKind::Match(..) => {}
238             // If `expr` is a result of desugaring the try block and is an ok-wrapped
239             // diverging expression (e.g. it arose from desugaring of `try { return }`),
240             // we skip issuing a warning because it is autogenerated code.
241             ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {}
242             ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"),
243             ExprKind::MethodCall(segment, ..) => {
244                 self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call")
245             }
246             _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
247         }
248
249         // Any expression that produces a value of type `!` must have diverged
250         if ty.is_never() {
251             self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
252         }
253
254         // Record the type, which applies it effects.
255         // We need to do this after the warning above, so that
256         // we don't warn for the diverging expression itself.
257         self.write_ty(expr.hir_id, ty);
258
259         // Combine the diverging and has_error flags.
260         self.diverges.set(self.diverges.get() | old_diverges);
261         self.has_errors.set(self.has_errors.get() | old_has_errors);
262
263         debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
264         debug!("... {:?}, expected is {:?}", ty, expected);
265
266         ty
267     }
268
269     #[instrument(skip(self, expr), level = "debug")]
270     pub(super) fn check_expr_kind(
271         &self,
272         expr: &'tcx hir::Expr<'tcx>,
273         expected: Expectation<'tcx>,
274     ) -> Ty<'tcx> {
275         trace!("expr={:#?}", expr);
276
277         let tcx = self.tcx;
278         match expr.kind {
279             ExprKind::Box(subexpr) => self.check_expr_box(subexpr, expected),
280             ExprKind::Lit(ref lit) => self.check_lit(&lit, expected),
281             ExprKind::Binary(op, lhs, rhs) => self.check_binop(expr, op, lhs, rhs),
282             ExprKind::Assign(lhs, rhs, span) => {
283                 self.check_expr_assign(expr, expected, lhs, rhs, span)
284             }
285             ExprKind::AssignOp(op, lhs, rhs) => self.check_binop_assign(expr, op, lhs, rhs),
286             ExprKind::Unary(unop, oprnd) => self.check_expr_unary(unop, oprnd, expected, expr),
287             ExprKind::AddrOf(kind, mutbl, oprnd) => {
288                 self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
289             }
290             ExprKind::Path(QPath::LangItem(lang_item, _, hir_id)) => {
291                 self.check_lang_item_path(lang_item, expr, hir_id)
292             }
293             ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr, &[]),
294             ExprKind::InlineAsm(asm) => self.check_expr_asm(asm),
295             ExprKind::Break(destination, ref expr_opt) => {
296                 self.check_expr_break(destination, expr_opt.as_deref(), expr)
297             }
298             ExprKind::Continue(destination) => {
299                 if destination.target_id.is_ok() {
300                     tcx.types.never
301                 } else {
302                     // There was an error; make type-check fail.
303                     tcx.ty_error()
304                 }
305             }
306             ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
307             ExprKind::Let(let_expr) => self.check_expr_let(let_expr),
308             ExprKind::Loop(body, _, source, _) => {
309                 self.check_expr_loop(body, source, expected, expr)
310             }
311             ExprKind::Match(discrim, arms, match_src) => {
312                 self.check_match(expr, &discrim, arms, expected, match_src)
313             }
314             ExprKind::Closure(capture, decl, body_id, _, gen) => {
315                 self.check_expr_closure(expr, capture, &decl, body_id, gen, expected)
316             }
317             ExprKind::Block(body, _) => self.check_block_with_expected(&body, expected),
318             ExprKind::Call(callee, args) => self.check_call(expr, &callee, args, expected),
319             ExprKind::MethodCall(segment, args, _) => {
320                 self.check_method_call(expr, segment, args, expected)
321             }
322             ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr),
323             ExprKind::Type(e, t) => {
324                 let ty = self.to_ty_saving_user_provided_ty(&t);
325                 self.check_expr_eq_type(&e, ty);
326                 ty
327             }
328             ExprKind::If(cond, then_expr, opt_else_expr) => {
329                 self.check_then_else(cond, then_expr, opt_else_expr, expr.span, expected)
330             }
331             ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected),
332             ExprKind::Array(args) => self.check_expr_array(args, expected, expr),
333             ExprKind::ConstBlock(ref anon_const) => {
334                 self.check_expr_const_block(anon_const, expected, expr)
335             }
336             ExprKind::Repeat(element, ref count) => {
337                 self.check_expr_repeat(element, count, expected, expr)
338             }
339             ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr),
340             ExprKind::Struct(qpath, fields, ref base_expr) => {
341                 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
342             }
343             ExprKind::Field(base, field) => self.check_field(expr, &base, field),
344             ExprKind::Index(base, idx) => self.check_expr_index(base, idx, expr),
345             ExprKind::Yield(value, ref src) => self.check_expr_yield(value, expr, src),
346             hir::ExprKind::Err => tcx.ty_error(),
347         }
348     }
349
350     fn check_expr_box(&self, expr: &'tcx hir::Expr<'tcx>, expected: Expectation<'tcx>) -> Ty<'tcx> {
351         let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| match ty.kind() {
352             ty::Adt(def, _) if def.is_box() => Expectation::rvalue_hint(self, ty.boxed_ty()),
353             _ => NoExpectation,
354         });
355         let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
356         self.require_type_is_sized(referent_ty, expr.span, traits::SizedBoxType);
357         self.tcx.mk_box(referent_ty)
358     }
359
360     fn check_expr_unary(
361         &self,
362         unop: hir::UnOp,
363         oprnd: &'tcx hir::Expr<'tcx>,
364         expected: Expectation<'tcx>,
365         expr: &'tcx hir::Expr<'tcx>,
366     ) -> Ty<'tcx> {
367         let tcx = self.tcx;
368         let expected_inner = match unop {
369             hir::UnOp::Not | hir::UnOp::Neg => expected,
370             hir::UnOp::Deref => NoExpectation,
371         };
372         let mut oprnd_t = self.check_expr_with_expectation(&oprnd, expected_inner);
373
374         if !oprnd_t.references_error() {
375             oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
376             match unop {
377                 hir::UnOp::Deref => {
378                     if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) {
379                         oprnd_t = ty;
380                     } else {
381                         let mut err = type_error_struct!(
382                             tcx.sess,
383                             expr.span,
384                             oprnd_t,
385                             E0614,
386                             "type `{oprnd_t}` cannot be dereferenced",
387                         );
388                         let sp = tcx.sess.source_map().start_point(expr.span);
389                         if let Some(sp) =
390                             tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
391                         {
392                             tcx.sess.parse_sess.expr_parentheses_needed(&mut err, *sp);
393                         }
394                         err.emit();
395                         oprnd_t = tcx.ty_error();
396                     }
397                 }
398                 hir::UnOp::Not => {
399                     let result = self.check_user_unop(expr, oprnd_t, unop);
400                     // If it's builtin, we can reuse the type, this helps inference.
401                     if !(oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool) {
402                         oprnd_t = result;
403                     }
404                 }
405                 hir::UnOp::Neg => {
406                     let result = self.check_user_unop(expr, oprnd_t, unop);
407                     // If it's builtin, we can reuse the type, this helps inference.
408                     if !oprnd_t.is_numeric() {
409                         oprnd_t = result;
410                     }
411                 }
412             }
413         }
414         oprnd_t
415     }
416
417     fn check_expr_addr_of(
418         &self,
419         kind: hir::BorrowKind,
420         mutbl: hir::Mutability,
421         oprnd: &'tcx hir::Expr<'tcx>,
422         expected: Expectation<'tcx>,
423         expr: &'tcx hir::Expr<'tcx>,
424     ) -> Ty<'tcx> {
425         let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
426             match ty.kind() {
427                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
428                     if oprnd.is_syntactic_place_expr() {
429                         // Places may legitimately have unsized types.
430                         // For example, dereferences of a fat pointer and
431                         // the last field of a struct can be unsized.
432                         ExpectHasType(*ty)
433                     } else {
434                         Expectation::rvalue_hint(self, *ty)
435                     }
436                 }
437                 _ => NoExpectation,
438             }
439         });
440         let ty =
441             self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl));
442
443         let tm = ty::TypeAndMut { ty, mutbl };
444         match kind {
445             _ if tm.ty.references_error() => self.tcx.ty_error(),
446             hir::BorrowKind::Raw => {
447                 self.check_named_place_expr(oprnd);
448                 self.tcx.mk_ptr(tm)
449             }
450             hir::BorrowKind::Ref => {
451                 // Note: at this point, we cannot say what the best lifetime
452                 // is to use for resulting pointer.  We want to use the
453                 // shortest lifetime possible so as to avoid spurious borrowck
454                 // errors.  Moreover, the longest lifetime will depend on the
455                 // precise details of the value whose address is being taken
456                 // (and how long it is valid), which we don't know yet until
457                 // type inference is complete.
458                 //
459                 // Therefore, here we simply generate a region variable. The
460                 // region inferencer will then select a suitable value.
461                 // Finally, borrowck will infer the value of the region again,
462                 // this time with enough precision to check that the value
463                 // whose address was taken can actually be made to live as long
464                 // as it needs to live.
465                 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
466                 self.tcx.mk_ref(region, tm)
467             }
468         }
469     }
470
471     /// Does this expression refer to a place that either:
472     /// * Is based on a local or static.
473     /// * Contains a dereference
474     /// Note that the adjustments for the children of `expr` should already
475     /// have been resolved.
476     fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
477         let is_named = oprnd.is_place_expr(|base| {
478             // Allow raw borrows if there are any deref adjustments.
479             //
480             // const VAL: (i32,) = (0,);
481             // const REF: &(i32,) = &(0,);
482             //
483             // &raw const VAL.0;            // ERROR
484             // &raw const REF.0;            // OK, same as &raw const (*REF).0;
485             //
486             // This is maybe too permissive, since it allows
487             // `let u = &raw const Box::new((1,)).0`, which creates an
488             // immediately dangling raw pointer.
489             self.typeck_results
490                 .borrow()
491                 .adjustments()
492                 .get(base.hir_id)
493                 .map_or(false, |x| x.iter().any(|adj| matches!(adj.kind, Adjust::Deref(_))))
494         });
495         if !is_named {
496             self.tcx.sess.emit_err(AddressOfTemporaryTaken { span: oprnd.span });
497         }
498     }
499
500     fn check_lang_item_path(
501         &self,
502         lang_item: hir::LangItem,
503         expr: &'tcx hir::Expr<'tcx>,
504         hir_id: Option<hir::HirId>,
505     ) -> Ty<'tcx> {
506         self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id, hir_id).1
507     }
508
509     pub(crate) fn check_expr_path(
510         &self,
511         qpath: &'tcx hir::QPath<'tcx>,
512         expr: &'tcx hir::Expr<'tcx>,
513         args: &'tcx [hir::Expr<'tcx>],
514     ) -> Ty<'tcx> {
515         let tcx = self.tcx;
516         let (res, opt_ty, segs) =
517             self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span);
518         let ty = match res {
519             Res::Err => {
520                 self.set_tainted_by_errors();
521                 tcx.ty_error()
522             }
523             Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
524                 report_unexpected_variant_res(tcx, res, expr.span);
525                 tcx.ty_error()
526             }
527             _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
528         };
529
530         if let ty::FnDef(..) = ty.kind() {
531             let fn_sig = ty.fn_sig(tcx);
532             if !tcx.features().unsized_fn_params {
533                 // We want to remove some Sized bounds from std functions,
534                 // but don't want to expose the removal to stable Rust.
535                 // i.e., we don't want to allow
536                 //
537                 // ```rust
538                 // drop as fn(str);
539                 // ```
540                 //
541                 // to work in stable even if the Sized bound on `drop` is relaxed.
542                 for i in 0..fn_sig.inputs().skip_binder().len() {
543                     // We just want to check sizedness, so instead of introducing
544                     // placeholder lifetimes with probing, we just replace higher lifetimes
545                     // with fresh vars.
546                     let span = args.get(i).map(|a| a.span).unwrap_or(expr.span);
547                     let input = self
548                         .replace_bound_vars_with_fresh_vars(
549                             span,
550                             infer::LateBoundRegionConversionTime::FnCall,
551                             fn_sig.input(i),
552                         )
553                         .0;
554                     self.require_type_is_sized_deferred(
555                         input,
556                         span,
557                         traits::SizedArgumentType(None),
558                     );
559                 }
560             }
561             // Here we want to prevent struct constructors from returning unsized types.
562             // There were two cases this happened: fn pointer coercion in stable
563             // and usual function call in presence of unsized_locals.
564             // Also, as we just want to check sizedness, instead of introducing
565             // placeholder lifetimes with probing, we just replace higher lifetimes
566             // with fresh vars.
567             let output = self
568                 .replace_bound_vars_with_fresh_vars(
569                     expr.span,
570                     infer::LateBoundRegionConversionTime::FnCall,
571                     fn_sig.output(),
572                 )
573                 .0;
574             self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
575         }
576
577         // We always require that the type provided as the value for
578         // a type parameter outlives the moment of instantiation.
579         let substs = self.typeck_results.borrow().node_substs(expr.hir_id);
580         self.add_wf_bounds(substs, expr);
581
582         ty
583     }
584
585     fn check_expr_break(
586         &self,
587         destination: hir::Destination,
588         expr_opt: Option<&'tcx hir::Expr<'tcx>>,
589         expr: &'tcx hir::Expr<'tcx>,
590     ) -> Ty<'tcx> {
591         let tcx = self.tcx;
592         if let Ok(target_id) = destination.target_id {
593             let (e_ty, cause);
594             if let Some(e) = expr_opt {
595                 // If this is a break with a value, we need to type-check
596                 // the expression. Get an expected type from the loop context.
597                 let opt_coerce_to = {
598                     // We should release `enclosing_breakables` before the `check_expr_with_hint`
599                     // below, so can't move this block of code to the enclosing scope and share
600                     // `ctxt` with the second `enclosing_breakables` borrow below.
601                     let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
602                     match enclosing_breakables.opt_find_breakable(target_id) {
603                         Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
604                         None => {
605                             // Avoid ICE when `break` is inside a closure (#65383).
606                             return tcx.ty_error_with_message(
607                                 expr.span,
608                                 "break was outside loop, but no error was emitted",
609                             );
610                         }
611                     }
612                 };
613
614                 // If the loop context is not a `loop { }`, then break with
615                 // a value is illegal, and `opt_coerce_to` will be `None`.
616                 // Just set expectation to error in that case.
617                 let coerce_to = opt_coerce_to.unwrap_or_else(|| tcx.ty_error());
618
619                 // Recurse without `enclosing_breakables` borrowed.
620                 e_ty = self.check_expr_with_hint(e, coerce_to);
621                 cause = self.misc(e.span);
622             } else {
623                 // Otherwise, this is a break *without* a value. That's
624                 // always legal, and is equivalent to `break ()`.
625                 e_ty = tcx.mk_unit();
626                 cause = self.misc(expr.span);
627             }
628
629             // Now that we have type-checked `expr_opt`, borrow
630             // the `enclosing_loops` field and let's coerce the
631             // type of `expr_opt` into what is expected.
632             let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
633             let Some(ctxt) = enclosing_breakables.opt_find_breakable(target_id) else {
634                 // Avoid ICE when `break` is inside a closure (#65383).
635                 return tcx.ty_error_with_message(
636                     expr.span,
637                     "break was outside loop, but no error was emitted",
638                 );
639             };
640
641             if let Some(ref mut coerce) = ctxt.coerce {
642                 if let Some(ref e) = expr_opt {
643                     coerce.coerce(self, &cause, e, e_ty);
644                 } else {
645                     assert!(e_ty.is_unit());
646                     let ty = coerce.expected_ty();
647                     coerce.coerce_forced_unit(
648                         self,
649                         &cause,
650                         &mut |mut err| {
651                             self.suggest_mismatched_types_on_tail(
652                                 &mut err, expr, ty, e_ty, target_id,
653                             );
654                             if let Some(val) = ty_kind_suggestion(ty) {
655                                 let label = destination
656                                     .label
657                                     .map(|l| format!(" {}", l.ident))
658                                     .unwrap_or_else(String::new);
659                                 err.span_suggestion(
660                                     expr.span,
661                                     "give it a value of the expected type",
662                                     format!("break{label} {val}"),
663                                     Applicability::HasPlaceholders,
664                                 );
665                             }
666                         },
667                         false,
668                     );
669                 }
670             } else {
671                 // If `ctxt.coerce` is `None`, we can just ignore
672                 // the type of the expression.  This is because
673                 // either this was a break *without* a value, in
674                 // which case it is always a legal type (`()`), or
675                 // else an error would have been flagged by the
676                 // `loops` pass for using break with an expression
677                 // where you are not supposed to.
678                 assert!(expr_opt.is_none() || self.tcx.sess.has_errors().is_some());
679             }
680
681             // If we encountered a `break`, then (no surprise) it may be possible to break from the
682             // loop... unless the value being returned from the loop diverges itself, e.g.
683             // `break return 5` or `break loop {}`.
684             ctxt.may_break |= !self.diverges.get().is_always();
685
686             // the type of a `break` is always `!`, since it diverges
687             tcx.types.never
688         } else {
689             // Otherwise, we failed to find the enclosing loop;
690             // this can only happen if the `break` was not
691             // inside a loop at all, which is caught by the
692             // loop-checking pass.
693             let err = self.tcx.ty_error_with_message(
694                 expr.span,
695                 "break was outside loop, but no error was emitted",
696             );
697
698             // We still need to assign a type to the inner expression to
699             // prevent the ICE in #43162.
700             if let Some(e) = expr_opt {
701                 self.check_expr_with_hint(e, err);
702
703                 // ... except when we try to 'break rust;'.
704                 // ICE this expression in particular (see #43162).
705                 if let ExprKind::Path(QPath::Resolved(_, path)) = e.kind {
706                     if path.segments.len() == 1 && path.segments[0].ident.name == sym::rust {
707                         fatally_break_rust(self.tcx.sess);
708                     }
709                 }
710             }
711
712             // There was an error; make type-check fail.
713             err
714         }
715     }
716
717     fn check_expr_return(
718         &self,
719         expr_opt: Option<&'tcx hir::Expr<'tcx>>,
720         expr: &'tcx hir::Expr<'tcx>,
721     ) -> Ty<'tcx> {
722         if self.ret_coercion.is_none() {
723             let mut err = ReturnStmtOutsideOfFnBody {
724                 span: expr.span,
725                 encl_body_span: None,
726                 encl_fn_span: None,
727             };
728
729             let encl_item_id = self.tcx.hir().get_parent_item(expr.hir_id);
730
731             if let Some(hir::Node::Item(hir::Item {
732                 kind: hir::ItemKind::Fn(..),
733                 span: encl_fn_span,
734                 ..
735             }))
736             | Some(hir::Node::TraitItem(hir::TraitItem {
737                 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
738                 span: encl_fn_span,
739                 ..
740             }))
741             | Some(hir::Node::ImplItem(hir::ImplItem {
742                 kind: hir::ImplItemKind::Fn(..),
743                 span: encl_fn_span,
744                 ..
745             })) = self.tcx.hir().find_by_def_id(encl_item_id)
746             {
747                 // We are inside a function body, so reporting "return statement
748                 // outside of function body" needs an explanation.
749
750                 let encl_body_owner_id = self.tcx.hir().enclosing_body_owner(expr.hir_id);
751
752                 // If this didn't hold, we would not have to report an error in
753                 // the first place.
754                 assert_ne!(hir::HirId::make_owner(encl_item_id), encl_body_owner_id);
755
756                 let encl_body_id = self.tcx.hir().body_owned_by(encl_body_owner_id);
757                 let encl_body = self.tcx.hir().body(encl_body_id);
758
759                 err.encl_body_span = Some(encl_body.value.span);
760                 err.encl_fn_span = Some(*encl_fn_span);
761             }
762
763             self.tcx.sess.emit_err(err);
764
765             if let Some(e) = expr_opt {
766                 // We still have to type-check `e` (issue #86188), but calling
767                 // `check_return_expr` only works inside fn bodies.
768                 self.check_expr(e);
769             }
770         } else if let Some(e) = expr_opt {
771             if self.ret_coercion_span.get().is_none() {
772                 self.ret_coercion_span.set(Some(e.span));
773             }
774             self.check_return_expr(e, true);
775         } else {
776             let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
777             if self.ret_coercion_span.get().is_none() {
778                 self.ret_coercion_span.set(Some(expr.span));
779             }
780             let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
781             if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
782                 coercion.coerce_forced_unit(
783                     self,
784                     &cause,
785                     &mut |db| {
786                         let span = fn_decl.output.span();
787                         if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
788                             db.span_label(
789                                 span,
790                                 format!("expected `{snippet}` because of this return type"),
791                             );
792                         }
793                     },
794                     true,
795                 );
796             } else {
797                 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
798             }
799         }
800         self.tcx.types.never
801     }
802
803     /// `explicit_return` is `true` if we're checking an explicit `return expr`,
804     /// and `false` if we're checking a trailing expression.
805     pub(super) fn check_return_expr(
806         &self,
807         return_expr: &'tcx hir::Expr<'tcx>,
808         explicit_return: bool,
809     ) {
810         let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
811             span_bug!(return_expr.span, "check_return_expr called outside fn body")
812         });
813
814         let ret_ty = ret_coercion.borrow().expected_ty();
815         let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
816         let mut span = return_expr.span;
817         // Use the span of the trailing expression for our cause,
818         // not the span of the entire function
819         if !explicit_return {
820             if let ExprKind::Block(body, _) = return_expr.kind && let Some(last_expr) = body.expr {
821                 span = last_expr.span;
822             }
823         }
824         ret_coercion.borrow_mut().coerce(
825             self,
826             &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
827             return_expr,
828             return_expr_ty,
829         );
830     }
831
832     pub(crate) fn check_lhs_assignable(
833         &self,
834         lhs: &'tcx hir::Expr<'tcx>,
835         err_code: &'static str,
836         op_span: Span,
837     ) {
838         if lhs.is_syntactic_place_expr() {
839             return;
840         }
841
842         // FIXME: Make this use SessionDiagnostic once error codes can be dynamically set.
843         let mut err = self.tcx.sess.struct_span_err_with_code(
844             op_span,
845             "invalid left-hand side of assignment",
846             DiagnosticId::Error(err_code.into()),
847         );
848         err.span_label(lhs.span, "cannot assign to this expression");
849
850         self.comes_from_while_condition(lhs.hir_id, |expr| {
851             err.span_suggestion_verbose(
852                 expr.span.shrink_to_lo(),
853                 "you might have meant to use pattern destructuring",
854                 "let ".to_string(),
855                 Applicability::MachineApplicable,
856             );
857         });
858
859         err.emit();
860     }
861
862     // Check if an expression `original_expr_id` comes from the condition of a while loop,
863     // as opposed from the body of a while loop, which we can naively check by iterating
864     // parents until we find a loop...
865     pub(super) fn comes_from_while_condition(
866         &self,
867         original_expr_id: HirId,
868         then: impl FnOnce(&hir::Expr<'_>),
869     ) {
870         let mut parent = self.tcx.hir().get_parent_node(original_expr_id);
871         while let Some(node) = self.tcx.hir().find(parent) {
872             match node {
873                 hir::Node::Expr(hir::Expr {
874                     kind:
875                         hir::ExprKind::Loop(
876                             hir::Block {
877                                 expr:
878                                     Some(hir::Expr {
879                                         kind:
880                                             hir::ExprKind::Match(expr, ..) | hir::ExprKind::If(expr, ..),
881                                         ..
882                                     }),
883                                 ..
884                             },
885                             _,
886                             hir::LoopSource::While,
887                             _,
888                         ),
889                     ..
890                 }) => {
891                     // Check if our original expression is a child of the condition of a while loop
892                     let expr_is_ancestor = std::iter::successors(Some(original_expr_id), |id| {
893                         self.tcx.hir().find_parent_node(*id)
894                     })
895                     .take_while(|id| *id != parent)
896                     .any(|id| id == expr.hir_id);
897                     // if it is, then we have a situation like `while Some(0) = value.get(0) {`,
898                     // where `while let` was more likely intended.
899                     if expr_is_ancestor {
900                         then(expr);
901                     }
902                     break;
903                 }
904                 hir::Node::Item(_)
905                 | hir::Node::ImplItem(_)
906                 | hir::Node::TraitItem(_)
907                 | hir::Node::Crate(_) => break,
908                 _ => {
909                     parent = self.tcx.hir().get_parent_node(parent);
910                 }
911             }
912         }
913     }
914
915     // A generic function for checking the 'then' and 'else' clauses in an 'if'
916     // or 'if-else' expression.
917     fn check_then_else(
918         &self,
919         cond_expr: &'tcx hir::Expr<'tcx>,
920         then_expr: &'tcx hir::Expr<'tcx>,
921         opt_else_expr: Option<&'tcx hir::Expr<'tcx>>,
922         sp: Span,
923         orig_expected: Expectation<'tcx>,
924     ) -> Ty<'tcx> {
925         let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {});
926
927         self.warn_if_unreachable(
928             cond_expr.hir_id,
929             then_expr.span,
930             "block in `if` or `while` expression",
931         );
932
933         let cond_diverges = self.diverges.get();
934         self.diverges.set(Diverges::Maybe);
935
936         let expected = orig_expected.adjust_for_branches(self);
937         let then_ty = self.check_expr_with_expectation(then_expr, expected);
938         let then_diverges = self.diverges.get();
939         self.diverges.set(Diverges::Maybe);
940
941         // We've already taken the expected type's preferences
942         // into account when typing the `then` branch. To figure
943         // out the initial shot at a LUB, we thus only consider
944         // `expected` if it represents a *hard* constraint
945         // (`only_has_type`); otherwise, we just go with a
946         // fresh type variable.
947         let coerce_to_ty = expected.coercion_target_type(self, sp);
948         let mut coerce: DynamicCoerceMany<'_> = CoerceMany::new(coerce_to_ty);
949
950         coerce.coerce(self, &self.misc(sp), then_expr, then_ty);
951
952         if let Some(else_expr) = opt_else_expr {
953             let else_ty = if sp.desugaring_kind() == Some(DesugaringKind::LetElse) {
954                 // todo introduce `check_expr_with_expectation(.., Expectation::LetElse)`
955                 //   for errors that point to the offending expression rather than the entire block.
956                 //   We could use `check_expr_eq_type(.., tcx.types.never)`, but then there is no
957                 //   way to detect that the expected type originated from let-else and provide
958                 //   a customized error.
959                 let else_ty = self.check_expr(else_expr);
960                 let cause = self.cause(else_expr.span, ObligationCauseCode::LetElse);
961
962                 if let Some(mut err) =
963                     self.demand_eqtype_with_origin(&cause, self.tcx.types.never, else_ty)
964                 {
965                     err.emit();
966                     self.tcx.ty_error()
967                 } else {
968                     else_ty
969                 }
970             } else {
971                 self.check_expr_with_expectation(else_expr, expected)
972             };
973             let else_diverges = self.diverges.get();
974
975             let opt_suggest_box_span = self.opt_suggest_box_span(else_ty, orig_expected);
976             let if_cause =
977                 self.if_cause(sp, then_expr, else_expr, then_ty, else_ty, opt_suggest_box_span);
978
979             coerce.coerce(self, &if_cause, else_expr, else_ty);
980
981             // We won't diverge unless both branches do (or the condition does).
982             self.diverges.set(cond_diverges | then_diverges & else_diverges);
983         } else {
984             self.if_fallback_coercion(sp, then_expr, &mut coerce);
985
986             // If the condition is false we can't diverge.
987             self.diverges.set(cond_diverges);
988         }
989
990         let result_ty = coerce.complete(self);
991         if cond_ty.references_error() { self.tcx.ty_error() } else { result_ty }
992     }
993
994     /// Type check assignment expression `expr` of form `lhs = rhs`.
995     /// The expected type is `()` and is passed to the function for the purposes of diagnostics.
996     fn check_expr_assign(
997         &self,
998         expr: &'tcx hir::Expr<'tcx>,
999         expected: Expectation<'tcx>,
1000         lhs: &'tcx hir::Expr<'tcx>,
1001         rhs: &'tcx hir::Expr<'tcx>,
1002         span: Span,
1003     ) -> Ty<'tcx> {
1004         let expected_ty = expected.coercion_target_type(self, expr.span);
1005         if expected_ty == self.tcx.types.bool {
1006             // The expected type is `bool` but this will result in `()` so we can reasonably
1007             // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
1008             // The likely cause of this is `if foo = bar { .. }`.
1009             let actual_ty = self.tcx.mk_unit();
1010             let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
1011             let lhs_ty = self.check_expr(&lhs);
1012             let rhs_ty = self.check_expr(&rhs);
1013             let (applicability, eq) = if self.can_coerce(rhs_ty, lhs_ty) {
1014                 (Applicability::MachineApplicable, true)
1015             } else {
1016                 (Applicability::MaybeIncorrect, false)
1017             };
1018             if !lhs.is_syntactic_place_expr() && !matches!(lhs.kind, hir::ExprKind::Lit(_)) {
1019                 // Do not suggest `if let x = y` as `==` is way more likely to be the intention.
1020                 let hir = self.tcx.hir();
1021                 if let hir::Node::Expr(hir::Expr { kind: ExprKind::If { .. }, .. }) =
1022                     hir.get(hir.get_parent_node(hir.get_parent_node(expr.hir_id)))
1023                 {
1024                     err.span_suggestion_verbose(
1025                         expr.span.shrink_to_lo(),
1026                         "you might have meant to use pattern matching",
1027                         "let ".to_string(),
1028                         applicability,
1029                     );
1030                 };
1031             }
1032             if eq {
1033                 err.span_suggestion_verbose(
1034                     span,
1035                     "you might have meant to compare for equality",
1036                     "==".to_string(),
1037                     applicability,
1038                 );
1039             }
1040
1041             // If the assignment expression itself is ill-formed, don't
1042             // bother emitting another error
1043             if lhs_ty.references_error() || rhs_ty.references_error() {
1044                 err.delay_as_bug()
1045             } else {
1046                 err.emit();
1047             }
1048             return self.tcx.ty_error();
1049         }
1050
1051         self.check_lhs_assignable(lhs, "E0070", span);
1052
1053         let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
1054         let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty, Some(lhs));
1055
1056         self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
1057
1058         if lhs_ty.references_error() || rhs_ty.references_error() {
1059             self.tcx.ty_error()
1060         } else {
1061             self.tcx.mk_unit()
1062         }
1063     }
1064
1065     fn check_expr_let(&self, let_expr: &'tcx hir::Let<'tcx>) -> Ty<'tcx> {
1066         // for let statements, this is done in check_stmt
1067         let init = let_expr.init;
1068         self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression");
1069         // otherwise check exactly as a let statement
1070         self.check_decl(let_expr.into());
1071         // but return a bool, for this is a boolean expression
1072         self.tcx.types.bool
1073     }
1074
1075     fn check_expr_loop(
1076         &self,
1077         body: &'tcx hir::Block<'tcx>,
1078         source: hir::LoopSource,
1079         expected: Expectation<'tcx>,
1080         expr: &'tcx hir::Expr<'tcx>,
1081     ) -> Ty<'tcx> {
1082         let coerce = match source {
1083             // you can only use break with a value from a normal `loop { }`
1084             hir::LoopSource::Loop => {
1085                 let coerce_to = expected.coercion_target_type(self, body.span);
1086                 Some(CoerceMany::new(coerce_to))
1087             }
1088
1089             hir::LoopSource::While | hir::LoopSource::ForLoop => None,
1090         };
1091
1092         let ctxt = BreakableCtxt {
1093             coerce,
1094             may_break: false, // Will get updated if/when we find a `break`.
1095         };
1096
1097         let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
1098             self.check_block_no_value(&body);
1099         });
1100
1101         if ctxt.may_break {
1102             // No way to know whether it's diverging because
1103             // of a `break` or an outer `break` or `return`.
1104             self.diverges.set(Diverges::Maybe);
1105         }
1106
1107         // If we permit break with a value, then result type is
1108         // the LUB of the breaks (possibly ! if none); else, it
1109         // is nil. This makes sense because infinite loops
1110         // (which would have type !) are only possible iff we
1111         // permit break with a value [1].
1112         if ctxt.coerce.is_none() && !ctxt.may_break {
1113             // [1]
1114             self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
1115         }
1116         ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
1117     }
1118
1119     /// Checks a method call.
1120     fn check_method_call(
1121         &self,
1122         expr: &'tcx hir::Expr<'tcx>,
1123         segment: &hir::PathSegment<'_>,
1124         args: &'tcx [hir::Expr<'tcx>],
1125         expected: Expectation<'tcx>,
1126     ) -> Ty<'tcx> {
1127         let rcvr = &args[0];
1128         let rcvr_t = self.check_expr(&rcvr);
1129         // no need to check for bot/err -- callee does that
1130         let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t);
1131         let span = segment.ident.span;
1132
1133         let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr, args) {
1134             Ok(method) => {
1135                 // We could add a "consider `foo::<params>`" suggestion here, but I wasn't able to
1136                 // trigger this codepath causing `structurally_resolved_type` to emit an error.
1137
1138                 self.write_method_call(expr.hir_id, method);
1139                 Ok(method)
1140             }
1141             Err(error) => {
1142                 if segment.ident.name != kw::Empty {
1143                     if let Some(mut err) = self.report_method_error(
1144                         span,
1145                         rcvr_t,
1146                         segment.ident,
1147                         SelfSource::MethodCall(&args[0]),
1148                         error,
1149                         Some(args),
1150                     ) {
1151                         err.emit();
1152                     }
1153                 }
1154                 Err(())
1155             }
1156         };
1157
1158         // Call the generic checker.
1159         self.check_method_argument_types(
1160             span,
1161             expr,
1162             method,
1163             &args[1..],
1164             DontTupleArguments,
1165             expected,
1166         )
1167     }
1168
1169     fn check_expr_cast(
1170         &self,
1171         e: &'tcx hir::Expr<'tcx>,
1172         t: &'tcx hir::Ty<'tcx>,
1173         expr: &'tcx hir::Expr<'tcx>,
1174     ) -> Ty<'tcx> {
1175         // Find the type of `e`. Supply hints based on the type we are casting to,
1176         // if appropriate.
1177         let t_cast = self.to_ty_saving_user_provided_ty(t);
1178         let t_cast = self.resolve_vars_if_possible(t_cast);
1179         let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
1180         let t_expr = self.resolve_vars_if_possible(t_expr);
1181
1182         // Eagerly check for some obvious errors.
1183         if t_expr.references_error() || t_cast.references_error() {
1184             self.tcx.ty_error()
1185         } else {
1186             // Defer other checks until we're done type checking.
1187             let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
1188             match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
1189                 Ok(cast_check) => {
1190                     debug!(
1191                         "check_expr_cast: deferring cast from {:?} to {:?}: {:?}",
1192                         t_cast, t_expr, cast_check,
1193                     );
1194                     deferred_cast_checks.push(cast_check);
1195                     t_cast
1196                 }
1197                 Err(_) => self.tcx.ty_error(),
1198             }
1199         }
1200     }
1201
1202     fn check_expr_array(
1203         &self,
1204         args: &'tcx [hir::Expr<'tcx>],
1205         expected: Expectation<'tcx>,
1206         expr: &'tcx hir::Expr<'tcx>,
1207     ) -> Ty<'tcx> {
1208         let element_ty = if !args.is_empty() {
1209             let coerce_to = expected
1210                 .to_option(self)
1211                 .and_then(|uty| match *uty.kind() {
1212                     ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1213                     _ => None,
1214                 })
1215                 .unwrap_or_else(|| {
1216                     self.next_ty_var(TypeVariableOrigin {
1217                         kind: TypeVariableOriginKind::TypeInference,
1218                         span: expr.span,
1219                     })
1220                 });
1221             let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
1222             assert_eq!(self.diverges.get(), Diverges::Maybe);
1223             for e in args {
1224                 let e_ty = self.check_expr_with_hint(e, coerce_to);
1225                 let cause = self.misc(e.span);
1226                 coerce.coerce(self, &cause, e, e_ty);
1227             }
1228             coerce.complete(self)
1229         } else {
1230             self.next_ty_var(TypeVariableOrigin {
1231                 kind: TypeVariableOriginKind::TypeInference,
1232                 span: expr.span,
1233             })
1234         };
1235         self.tcx.mk_array(element_ty, args.len() as u64)
1236     }
1237
1238     fn check_expr_const_block(
1239         &self,
1240         anon_const: &'tcx hir::AnonConst,
1241         expected: Expectation<'tcx>,
1242         _expr: &'tcx hir::Expr<'tcx>,
1243     ) -> Ty<'tcx> {
1244         let body = self.tcx.hir().body(anon_const.body);
1245
1246         // Create a new function context.
1247         let fcx = FnCtxt::new(self, self.param_env.with_const(), body.value.hir_id);
1248         crate::check::GatherLocalsVisitor::new(&fcx).visit_body(body);
1249
1250         let ty = fcx.check_expr_with_expectation(&body.value, expected);
1251         fcx.require_type_is_sized(ty, body.value.span, traits::ConstSized);
1252         fcx.write_ty(anon_const.hir_id, ty);
1253         ty
1254     }
1255
1256     fn check_expr_repeat(
1257         &self,
1258         element: &'tcx hir::Expr<'tcx>,
1259         count: &'tcx hir::ArrayLen,
1260         expected: Expectation<'tcx>,
1261         _expr: &'tcx hir::Expr<'tcx>,
1262     ) -> Ty<'tcx> {
1263         let tcx = self.tcx;
1264         let count = self.array_length_to_const(count);
1265
1266         let uty = match expected {
1267             ExpectHasType(uty) => match *uty.kind() {
1268                 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1269                 _ => None,
1270             },
1271             _ => None,
1272         };
1273
1274         let (element_ty, t) = match uty {
1275             Some(uty) => {
1276                 self.check_expr_coercable_to_type(&element, uty, None);
1277                 (uty, uty)
1278             }
1279             None => {
1280                 let ty = self.next_ty_var(TypeVariableOrigin {
1281                     kind: TypeVariableOriginKind::MiscVariable,
1282                     span: element.span,
1283                 });
1284                 let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
1285                 (element_ty, ty)
1286             }
1287         };
1288
1289         if element_ty.references_error() {
1290             return tcx.ty_error();
1291         }
1292
1293         tcx.mk_ty(ty::Array(t, count))
1294     }
1295
1296     fn check_expr_tuple(
1297         &self,
1298         elts: &'tcx [hir::Expr<'tcx>],
1299         expected: Expectation<'tcx>,
1300         expr: &'tcx hir::Expr<'tcx>,
1301     ) -> Ty<'tcx> {
1302         let flds = expected.only_has_type(self).and_then(|ty| {
1303             let ty = self.resolve_vars_with_obligations(ty);
1304             match ty.kind() {
1305                 ty::Tuple(flds) => Some(&flds[..]),
1306                 _ => None,
1307             }
1308         });
1309
1310         let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds {
1311             Some(fs) if i < fs.len() => {
1312                 let ety = fs[i];
1313                 self.check_expr_coercable_to_type(&e, ety, None);
1314                 ety
1315             }
1316             _ => self.check_expr_with_expectation(&e, NoExpectation),
1317         });
1318         let tuple = self.tcx.mk_tup(elt_ts_iter);
1319         if tuple.references_error() {
1320             self.tcx.ty_error()
1321         } else {
1322             self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1323             tuple
1324         }
1325     }
1326
1327     fn check_expr_struct(
1328         &self,
1329         expr: &hir::Expr<'_>,
1330         expected: Expectation<'tcx>,
1331         qpath: &QPath<'_>,
1332         fields: &'tcx [hir::ExprField<'tcx>],
1333         base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1334     ) -> Ty<'tcx> {
1335         // Find the relevant variant
1336         let Some((variant, adt_ty)) = self.check_struct_path(qpath, expr.hir_id) else {
1337             self.check_struct_fields_on_error(fields, base_expr);
1338             return self.tcx.ty_error();
1339         };
1340
1341         // Prohibit struct expressions when non-exhaustive flag is set.
1342         let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1343         if !adt.did().is_local() && variant.is_field_list_non_exhaustive() {
1344             self.tcx
1345                 .sess
1346                 .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() });
1347         }
1348
1349         self.check_expr_struct_fields(
1350             adt_ty,
1351             expected,
1352             expr.hir_id,
1353             qpath.span(),
1354             variant,
1355             fields,
1356             base_expr,
1357             expr.span,
1358         );
1359
1360         self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1361         adt_ty
1362     }
1363
1364     fn check_expr_struct_fields(
1365         &self,
1366         adt_ty: Ty<'tcx>,
1367         expected: Expectation<'tcx>,
1368         expr_id: hir::HirId,
1369         span: Span,
1370         variant: &'tcx ty::VariantDef,
1371         ast_fields: &'tcx [hir::ExprField<'tcx>],
1372         base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1373         expr_span: Span,
1374     ) {
1375         let tcx = self.tcx;
1376
1377         let expected_inputs =
1378             self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty]);
1379         let adt_ty_hint = if let Some(expected_inputs) = expected_inputs {
1380             expected_inputs.get(0).cloned().unwrap_or(adt_ty)
1381         } else {
1382             adt_ty
1383         };
1384         // re-link the regions that EIfEO can erase.
1385         self.demand_eqtype(span, adt_ty_hint, adt_ty);
1386
1387         let (substs, adt_kind, kind_name) = match adt_ty.kind() {
1388             ty::Adt(adt, substs) => (substs, adt.adt_kind(), adt.variant_descr()),
1389             _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields"),
1390         };
1391
1392         let mut remaining_fields = variant
1393             .fields
1394             .iter()
1395             .enumerate()
1396             .map(|(i, field)| (field.ident(tcx).normalize_to_macros_2_0(), (i, field)))
1397             .collect::<FxHashMap<_, _>>();
1398
1399         let mut seen_fields = FxHashMap::default();
1400
1401         let mut error_happened = false;
1402
1403         // Type-check each field.
1404         for field in ast_fields {
1405             let ident = tcx.adjust_ident(field.ident, variant.def_id);
1406             let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1407                 seen_fields.insert(ident, field.span);
1408                 self.write_field_index(field.hir_id, i);
1409
1410                 // We don't look at stability attributes on
1411                 // struct-like enums (yet...), but it's definitely not
1412                 // a bug to have constructed one.
1413                 if adt_kind != AdtKind::Enum {
1414                     tcx.check_stability(v_field.did, Some(expr_id), field.span, None);
1415                 }
1416
1417                 self.field_ty(field.span, v_field, substs)
1418             } else {
1419                 error_happened = true;
1420                 if let Some(prev_span) = seen_fields.get(&ident) {
1421                     tcx.sess.emit_err(FieldMultiplySpecifiedInInitializer {
1422                         span: field.ident.span,
1423                         prev_span: *prev_span,
1424                         ident,
1425                     });
1426                 } else {
1427                     self.report_unknown_field(
1428                         adt_ty, variant, field, ast_fields, kind_name, expr_span,
1429                     );
1430                 }
1431
1432                 tcx.ty_error()
1433             };
1434
1435             // Make sure to give a type to the field even if there's
1436             // an error, so we can continue type-checking.
1437             self.check_expr_coercable_to_type(&field.expr, field_type, None);
1438         }
1439
1440         // Make sure the programmer specified correct number of fields.
1441         if kind_name == "union" {
1442             if ast_fields.len() != 1 {
1443                 struct_span_err!(
1444                     tcx.sess,
1445                     span,
1446                     E0784,
1447                     "union expressions should have exactly one field",
1448                 )
1449                 .emit();
1450             }
1451         }
1452
1453         // If check_expr_struct_fields hit an error, do not attempt to populate
1454         // the fields with the base_expr. This could cause us to hit errors later
1455         // when certain fields are assumed to exist that in fact do not.
1456         if error_happened {
1457             return;
1458         }
1459
1460         if let Some(base_expr) = base_expr {
1461             // FIXME: We are currently creating two branches here in order to maintain
1462             // consistency. But they should be merged as much as possible.
1463             let fru_tys = if self.tcx.features().type_changing_struct_update {
1464                 let base_ty = self.check_expr(base_expr);
1465                 match adt_ty.kind() {
1466                     ty::Adt(adt, substs) if adt.is_struct() => {
1467                         match base_ty.kind() {
1468                             ty::Adt(base_adt, base_subs) if adt == base_adt => {
1469                                 variant
1470                                     .fields
1471                                     .iter()
1472                                     .map(|f| {
1473                                         let fru_ty = self.normalize_associated_types_in(
1474                                             expr_span,
1475                                             self.field_ty(base_expr.span, f, base_subs),
1476                                         );
1477                                         let ident = self
1478                                             .tcx
1479                                             .adjust_ident(f.ident(self.tcx), variant.def_id);
1480                                         if let Some(_) = remaining_fields.remove(&ident) {
1481                                             let target_ty =
1482                                                 self.field_ty(base_expr.span, f, substs);
1483                                             let cause = self.misc(base_expr.span);
1484                                             match self
1485                                                 .at(&cause, self.param_env)
1486                                                 .sup(target_ty, fru_ty)
1487                                             {
1488                                                 Ok(InferOk { obligations, value: () }) => {
1489                                                     self.register_predicates(obligations)
1490                                                 }
1491                                                 // FIXME: Need better diagnostics for `FieldMisMatch` error
1492                                                 Err(_) => {
1493                                                     self.report_mismatched_types(
1494                                                         &cause,
1495                                                         target_ty,
1496                                                         fru_ty,
1497                                                         FieldMisMatch(variant.name, ident.name),
1498                                                     )
1499                                                     .emit();
1500                                                 }
1501                                             }
1502                                         }
1503                                         fru_ty
1504                                     })
1505                                     .collect()
1506                             }
1507                             _ => {
1508                                 self.report_mismatched_types(
1509                                     &self.misc(base_expr.span),
1510                                     adt_ty,
1511                                     base_ty,
1512                                     Sorts(ExpectedFound::new(true, adt_ty, base_ty)),
1513                                 )
1514                                 .emit();
1515                                 return;
1516                             }
1517                         }
1518                     }
1519                     _ => {
1520                         self.tcx
1521                             .sess
1522                             .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
1523                         return;
1524                     }
1525                 }
1526             } else {
1527                 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {
1528                     let base_ty = self.typeck_results.borrow().expr_ty(*base_expr);
1529                     let same_adt = match (adt_ty.kind(), base_ty.kind()) {
1530                         (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt => true,
1531                         _ => false,
1532                     };
1533                     if self.tcx.sess.is_nightly_build() && same_adt {
1534                         feature_err(
1535                             &self.tcx.sess.parse_sess,
1536                             sym::type_changing_struct_update,
1537                             base_expr.span,
1538                             "type changing struct updating is experimental",
1539                         )
1540                         .emit();
1541                     }
1542                 });
1543                 match adt_ty.kind() {
1544                     ty::Adt(adt, substs) if adt.is_struct() => variant
1545                         .fields
1546                         .iter()
1547                         .map(|f| {
1548                             self.normalize_associated_types_in(expr_span, f.ty(self.tcx, substs))
1549                         })
1550                         .collect(),
1551                     _ => {
1552                         self.tcx
1553                             .sess
1554                             .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
1555                         return;
1556                     }
1557                 }
1558             };
1559             self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr_id, fru_tys);
1560         } else if kind_name != "union" && !remaining_fields.is_empty() {
1561             let inaccessible_remaining_fields = remaining_fields.iter().any(|(_, (_, field))| {
1562                 !field.vis.is_accessible_from(tcx.parent_module(expr_id).to_def_id(), tcx)
1563             });
1564
1565             if inaccessible_remaining_fields {
1566                 self.report_inaccessible_fields(adt_ty, span);
1567             } else {
1568                 self.report_missing_fields(
1569                     adt_ty,
1570                     span,
1571                     remaining_fields,
1572                     variant,
1573                     ast_fields,
1574                     substs,
1575                 );
1576             }
1577         }
1578     }
1579
1580     fn check_struct_fields_on_error(
1581         &self,
1582         fields: &'tcx [hir::ExprField<'tcx>],
1583         base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1584     ) {
1585         for field in fields {
1586             self.check_expr(&field.expr);
1587         }
1588         if let Some(base) = *base_expr {
1589             self.check_expr(&base);
1590         }
1591     }
1592
1593     /// Report an error for a struct field expression when there are fields which aren't provided.
1594     ///
1595     /// ```text
1596     /// error: missing field `you_can_use_this_field` in initializer of `foo::Foo`
1597     ///  --> src/main.rs:8:5
1598     ///   |
1599     /// 8 |     foo::Foo {};
1600     ///   |     ^^^^^^^^ missing `you_can_use_this_field`
1601     ///
1602     /// error: aborting due to previous error
1603     /// ```
1604     fn report_missing_fields(
1605         &self,
1606         adt_ty: Ty<'tcx>,
1607         span: Span,
1608         remaining_fields: FxHashMap<Ident, (usize, &ty::FieldDef)>,
1609         variant: &'tcx ty::VariantDef,
1610         ast_fields: &'tcx [hir::ExprField<'tcx>],
1611         substs: SubstsRef<'tcx>,
1612     ) {
1613         let len = remaining_fields.len();
1614
1615         let mut displayable_field_names: Vec<&str> =
1616             remaining_fields.keys().map(|ident| ident.as_str()).collect();
1617         // sorting &str primitives here, sort_unstable is ok
1618         displayable_field_names.sort_unstable();
1619
1620         let mut truncated_fields_error = String::new();
1621         let remaining_fields_names = match &displayable_field_names[..] {
1622             [field1] => format!("`{}`", field1),
1623             [field1, field2] => format!("`{field1}` and `{field2}`"),
1624             [field1, field2, field3] => format!("`{field1}`, `{field2}` and `{field3}`"),
1625             _ => {
1626                 truncated_fields_error =
1627                     format!(" and {} other field{}", len - 3, pluralize!(len - 3));
1628                 displayable_field_names
1629                     .iter()
1630                     .take(3)
1631                     .map(|n| format!("`{n}`"))
1632                     .collect::<Vec<_>>()
1633                     .join(", ")
1634             }
1635         };
1636
1637         let mut err = struct_span_err!(
1638             self.tcx.sess,
1639             span,
1640             E0063,
1641             "missing field{} {}{} in initializer of `{}`",
1642             pluralize!(len),
1643             remaining_fields_names,
1644             truncated_fields_error,
1645             adt_ty
1646         );
1647         err.span_label(span, format!("missing {remaining_fields_names}{truncated_fields_error}"));
1648
1649         // If the last field is a range literal, but it isn't supposed to be, then they probably
1650         // meant to use functional update syntax.
1651         //
1652         // I don't use 'is_range_literal' because only double-sided, half-open ranges count.
1653         if let Some((
1654             last,
1655             ExprKind::Struct(
1656                 QPath::LangItem(LangItem::Range, ..),
1657                 &[ref range_start, ref range_end],
1658                 _,
1659             ),
1660         )) = ast_fields.last().map(|last| (last, &last.expr.kind)) &&
1661         let variant_field =
1662             variant.fields.iter().find(|field| field.ident(self.tcx) == last.ident) &&
1663         let range_def_id = self.tcx.lang_items().range_struct() &&
1664         variant_field
1665             .and_then(|field| field.ty(self.tcx, substs).ty_adt_def())
1666             .map(|adt| adt.did())
1667             != range_def_id
1668         {
1669             let instead = self
1670                 .tcx
1671                 .sess
1672                 .source_map()
1673                 .span_to_snippet(range_end.expr.span)
1674                 .map(|s| format!(" from `{s}`"))
1675                 .unwrap_or(String::new());
1676             err.span_suggestion(
1677                 range_start.span.shrink_to_hi(),
1678                 &format!("to set the remaining fields{instead}, separate the last named field with a comma"),
1679                 ",".to_string(),
1680                 Applicability::MaybeIncorrect,
1681             );
1682         }
1683
1684         err.emit();
1685     }
1686
1687     /// Report an error for a struct field expression when there are invisible fields.
1688     ///
1689     /// ```text
1690     /// error: cannot construct `Foo` with struct literal syntax due to inaccessible fields
1691     ///  --> src/main.rs:8:5
1692     ///   |
1693     /// 8 |     foo::Foo {};
1694     ///   |     ^^^^^^^^
1695     ///
1696     /// error: aborting due to previous error
1697     /// ```
1698     fn report_inaccessible_fields(&self, adt_ty: Ty<'tcx>, span: Span) {
1699         self.tcx.sess.span_err(
1700             span,
1701             &format!(
1702                 "cannot construct `{adt_ty}` with struct literal syntax due to inaccessible fields",
1703             ),
1704         );
1705     }
1706
1707     fn report_unknown_field(
1708         &self,
1709         ty: Ty<'tcx>,
1710         variant: &'tcx ty::VariantDef,
1711         field: &hir::ExprField<'_>,
1712         skip_fields: &[hir::ExprField<'_>],
1713         kind_name: &str,
1714         expr_span: Span,
1715     ) {
1716         if variant.is_recovered() {
1717             self.set_tainted_by_errors();
1718             return;
1719         }
1720         let mut err = self.type_error_struct_with_diag(
1721             field.ident.span,
1722             |actual| match ty.kind() {
1723                 ty::Adt(adt, ..) if adt.is_enum() => struct_span_err!(
1724                     self.tcx.sess,
1725                     field.ident.span,
1726                     E0559,
1727                     "{} `{}::{}` has no field named `{}`",
1728                     kind_name,
1729                     actual,
1730                     variant.name,
1731                     field.ident
1732                 ),
1733                 _ => struct_span_err!(
1734                     self.tcx.sess,
1735                     field.ident.span,
1736                     E0560,
1737                     "{} `{}` has no field named `{}`",
1738                     kind_name,
1739                     actual,
1740                     field.ident
1741                 ),
1742             },
1743             ty,
1744         );
1745
1746         let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap();
1747         match variant.ctor_kind {
1748             CtorKind::Fn => match ty.kind() {
1749                 ty::Adt(adt, ..) if adt.is_enum() => {
1750                     err.span_label(
1751                         variant_ident_span,
1752                         format!(
1753                             "`{adt}::{variant}` defined here",
1754                             adt = ty,
1755                             variant = variant.name,
1756                         ),
1757                     );
1758                     err.span_label(field.ident.span, "field does not exist");
1759                     err.span_suggestion_verbose(
1760                         expr_span,
1761                         &format!(
1762                             "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax",
1763                             adt = ty,
1764                             variant = variant.name,
1765                         ),
1766                         format!(
1767                             "{adt}::{variant}(/* fields */)",
1768                             adt = ty,
1769                             variant = variant.name,
1770                         ),
1771                         Applicability::HasPlaceholders,
1772                     );
1773                 }
1774                 _ => {
1775                     err.span_label(variant_ident_span, format!("`{adt}` defined here", adt = ty));
1776                     err.span_label(field.ident.span, "field does not exist");
1777                     err.span_suggestion_verbose(
1778                         expr_span,
1779                         &format!(
1780                             "`{adt}` is a tuple {kind_name}, use the appropriate syntax",
1781                             adt = ty,
1782                             kind_name = kind_name,
1783                         ),
1784                         format!("{adt}(/* fields */)", adt = ty),
1785                         Applicability::HasPlaceholders,
1786                     );
1787                 }
1788             },
1789             _ => {
1790                 // prevent all specified fields from being suggested
1791                 let skip_fields = skip_fields.iter().map(|x| x.ident.name);
1792                 if let Some(field_name) = self.suggest_field_name(
1793                     variant,
1794                     field.ident.name,
1795                     skip_fields.collect(),
1796                     expr_span,
1797                 ) {
1798                     err.span_suggestion(
1799                         field.ident.span,
1800                         "a field with a similar name exists",
1801                         field_name.to_string(),
1802                         Applicability::MaybeIncorrect,
1803                     );
1804                 } else {
1805                     match ty.kind() {
1806                         ty::Adt(adt, ..) => {
1807                             if adt.is_enum() {
1808                                 err.span_label(
1809                                     field.ident.span,
1810                                     format!("`{}::{}` does not have this field", ty, variant.name),
1811                                 );
1812                             } else {
1813                                 err.span_label(
1814                                     field.ident.span,
1815                                     format!("`{ty}` does not have this field"),
1816                                 );
1817                             }
1818                             let available_field_names =
1819                                 self.available_field_names(variant, expr_span);
1820                             if !available_field_names.is_empty() {
1821                                 err.note(&format!(
1822                                     "available fields are: {}",
1823                                     self.name_series_display(available_field_names)
1824                                 ));
1825                             }
1826                         }
1827                         _ => bug!("non-ADT passed to report_unknown_field"),
1828                     }
1829                 };
1830             }
1831         }
1832         err.emit();
1833     }
1834
1835     // Return a hint about the closest match in field names
1836     fn suggest_field_name(
1837         &self,
1838         variant: &'tcx ty::VariantDef,
1839         field: Symbol,
1840         skip: Vec<Symbol>,
1841         // The span where stability will be checked
1842         span: Span,
1843     ) -> Option<Symbol> {
1844         let names = variant
1845             .fields
1846             .iter()
1847             .filter_map(|field| {
1848                 // ignore already set fields and private fields from non-local crates
1849                 // and unstable fields.
1850                 if skip.iter().any(|&x| x == field.name)
1851                     || (!variant.def_id.is_local() && !field.vis.is_public())
1852                     || matches!(
1853                         self.tcx.eval_stability(field.did, None, span, None),
1854                         stability::EvalResult::Deny { .. }
1855                     )
1856                 {
1857                     None
1858                 } else {
1859                     Some(field.name)
1860                 }
1861             })
1862             .collect::<Vec<Symbol>>();
1863
1864         find_best_match_for_name(&names, field, None)
1865     }
1866
1867     fn available_field_names(
1868         &self,
1869         variant: &'tcx ty::VariantDef,
1870         access_span: Span,
1871     ) -> Vec<Symbol> {
1872         variant
1873             .fields
1874             .iter()
1875             .filter(|field| {
1876                 let def_scope = self
1877                     .tcx
1878                     .adjust_ident_and_get_scope(field.ident(self.tcx), variant.def_id, self.body_id)
1879                     .1;
1880                 field.vis.is_accessible_from(def_scope, self.tcx)
1881                     && !matches!(
1882                         self.tcx.eval_stability(field.did, None, access_span, None),
1883                         stability::EvalResult::Deny { .. }
1884                     )
1885             })
1886             .filter(|field| !self.tcx.is_doc_hidden(field.did))
1887             .map(|field| field.name)
1888             .collect()
1889     }
1890
1891     fn name_series_display(&self, names: Vec<Symbol>) -> String {
1892         // dynamic limit, to never omit just one field
1893         let limit = if names.len() == 6 { 6 } else { 5 };
1894         let mut display =
1895             names.iter().take(limit).map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
1896         if names.len() > limit {
1897             display = format!("{} ... and {} others", display, names.len() - limit);
1898         }
1899         display
1900     }
1901
1902     // Check field access expressions
1903     fn check_field(
1904         &self,
1905         expr: &'tcx hir::Expr<'tcx>,
1906         base: &'tcx hir::Expr<'tcx>,
1907         field: Ident,
1908     ) -> Ty<'tcx> {
1909         debug!("check_field(expr: {:?}, base: {:?}, field: {:?})", expr, base, field);
1910         let expr_t = self.check_expr(base);
1911         let expr_t = self.structurally_resolved_type(base.span, expr_t);
1912         let mut private_candidate = None;
1913         let mut autoderef = self.autoderef(expr.span, expr_t);
1914         while let Some((base_t, _)) = autoderef.next() {
1915             debug!("base_t: {:?}", base_t);
1916             match base_t.kind() {
1917                 ty::Adt(base_def, substs) if !base_def.is_enum() => {
1918                     debug!("struct named {:?}", base_t);
1919                     let (ident, def_scope) =
1920                         self.tcx.adjust_ident_and_get_scope(field, base_def.did(), self.body_id);
1921                     let fields = &base_def.non_enum_variant().fields;
1922                     if let Some(index) = fields
1923                         .iter()
1924                         .position(|f| f.ident(self.tcx).normalize_to_macros_2_0() == ident)
1925                     {
1926                         let field = &fields[index];
1927                         let field_ty = self.field_ty(expr.span, field, substs);
1928                         // Save the index of all fields regardless of their visibility in case
1929                         // of error recovery.
1930                         self.write_field_index(expr.hir_id, index);
1931                         let adjustments = self.adjust_steps(&autoderef);
1932                         if field.vis.is_accessible_from(def_scope, self.tcx) {
1933                             self.apply_adjustments(base, adjustments);
1934                             self.register_predicates(autoderef.into_obligations());
1935
1936                             self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
1937                             return field_ty;
1938                         }
1939                         private_candidate = Some((adjustments, base_def.did(), field_ty));
1940                     }
1941                 }
1942                 ty::Tuple(tys) => {
1943                     let fstr = field.as_str();
1944                     if let Ok(index) = fstr.parse::<usize>() {
1945                         if fstr == index.to_string() {
1946                             if let Some(&field_ty) = tys.get(index) {
1947                                 let adjustments = self.adjust_steps(&autoderef);
1948                                 self.apply_adjustments(base, adjustments);
1949                                 self.register_predicates(autoderef.into_obligations());
1950
1951                                 self.write_field_index(expr.hir_id, index);
1952                                 return field_ty;
1953                             }
1954                         }
1955                     }
1956                 }
1957                 _ => {}
1958             }
1959         }
1960         self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false));
1961
1962         if let Some((adjustments, did, field_ty)) = private_candidate {
1963             // (#90483) apply adjustments to avoid ExprUseVisitor from
1964             // creating erroneous projection.
1965             self.apply_adjustments(base, adjustments);
1966             self.ban_private_field_access(expr, expr_t, field, did);
1967             return field_ty;
1968         }
1969
1970         if field.name == kw::Empty {
1971         } else if self.method_exists(field, expr_t, expr.hir_id, true) {
1972             self.ban_take_value_of_method(expr, expr_t, field);
1973         } else if !expr_t.is_primitive_ty() {
1974             self.ban_nonexisting_field(field, base, expr, expr_t);
1975         } else {
1976             type_error_struct!(
1977                 self.tcx().sess,
1978                 field.span,
1979                 expr_t,
1980                 E0610,
1981                 "`{expr_t}` is a primitive type and therefore doesn't have fields",
1982             )
1983             .emit();
1984         }
1985
1986         self.tcx().ty_error()
1987     }
1988
1989     fn suggest_await_on_field_access(
1990         &self,
1991         err: &mut Diagnostic,
1992         field_ident: Ident,
1993         base: &'tcx hir::Expr<'tcx>,
1994         ty: Ty<'tcx>,
1995     ) {
1996         let output_ty = match self.infcx.get_impl_future_output_ty(ty) {
1997             Some(output_ty) => self.resolve_vars_if_possible(output_ty),
1998             _ => return,
1999         };
2000         let mut add_label = true;
2001         if let ty::Adt(def, _) = output_ty.skip_binder().kind() {
2002             // no field access on enum type
2003             if !def.is_enum() {
2004                 if def
2005                     .non_enum_variant()
2006                     .fields
2007                     .iter()
2008                     .any(|field| field.ident(self.tcx) == field_ident)
2009                 {
2010                     add_label = false;
2011                     err.span_label(
2012                         field_ident.span,
2013                         "field not available in `impl Future`, but it is available in its `Output`",
2014                     );
2015                     err.span_suggestion_verbose(
2016                         base.span.shrink_to_hi(),
2017                         "consider `await`ing on the `Future` and access the field of its `Output`",
2018                         ".await".to_string(),
2019                         Applicability::MaybeIncorrect,
2020                     );
2021                 }
2022             }
2023         }
2024         if add_label {
2025             err.span_label(field_ident.span, &format!("field not found in `{ty}`"));
2026         }
2027     }
2028
2029     fn ban_nonexisting_field(
2030         &self,
2031         field: Ident,
2032         base: &'tcx hir::Expr<'tcx>,
2033         expr: &'tcx hir::Expr<'tcx>,
2034         expr_t: Ty<'tcx>,
2035     ) {
2036         debug!(
2037             "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, expr_ty={:?}",
2038             field, base, expr, expr_t
2039         );
2040         let mut err = self.no_such_field_err(field, expr_t, base.hir_id);
2041
2042         match *expr_t.peel_refs().kind() {
2043             ty::Array(_, len) => {
2044                 self.maybe_suggest_array_indexing(&mut err, expr, base, field, len);
2045             }
2046             ty::RawPtr(..) => {
2047                 self.suggest_first_deref_field(&mut err, expr, base, field);
2048             }
2049             ty::Adt(def, _) if !def.is_enum() => {
2050                 self.suggest_fields_on_recordish(&mut err, def, field, expr.span);
2051             }
2052             ty::Param(param_ty) => {
2053                 self.point_at_param_definition(&mut err, param_ty);
2054             }
2055             ty::Opaque(_, _) => {
2056                 self.suggest_await_on_field_access(&mut err, field, base, expr_t.peel_refs());
2057             }
2058             _ => {}
2059         }
2060
2061         if field.name == kw::Await {
2062             // We know by construction that `<expr>.await` is either on Rust 2015
2063             // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
2064             err.note("to `.await` a `Future`, switch to Rust 2018 or later");
2065             err.help_use_latest_edition();
2066         }
2067
2068         err.emit();
2069     }
2070
2071     fn ban_private_field_access(
2072         &self,
2073         expr: &hir::Expr<'_>,
2074         expr_t: Ty<'tcx>,
2075         field: Ident,
2076         base_did: DefId,
2077     ) {
2078         let struct_path = self.tcx().def_path_str(base_did);
2079         let kind_name = self.tcx().def_kind(base_did).descr(base_did);
2080         let mut err = struct_span_err!(
2081             self.tcx().sess,
2082             field.span,
2083             E0616,
2084             "field `{field}` of {kind_name} `{struct_path}` is private",
2085         );
2086         err.span_label(field.span, "private field");
2087         // Also check if an accessible method exists, which is often what is meant.
2088         if self.method_exists(field, expr_t, expr.hir_id, false) && !self.expr_in_place(expr.hir_id)
2089         {
2090             self.suggest_method_call(
2091                 &mut err,
2092                 &format!("a method `{field}` also exists, call it with parentheses"),
2093                 field,
2094                 expr_t,
2095                 expr,
2096                 None,
2097             );
2098         }
2099         err.emit();
2100     }
2101
2102     fn ban_take_value_of_method(&self, expr: &hir::Expr<'_>, expr_t: Ty<'tcx>, field: Ident) {
2103         let mut err = type_error_struct!(
2104             self.tcx().sess,
2105             field.span,
2106             expr_t,
2107             E0615,
2108             "attempted to take value of method `{field}` on type `{expr_t}`",
2109         );
2110         err.span_label(field.span, "method, not a field");
2111         let expr_is_call =
2112             if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) =
2113                 self.tcx.hir().get(self.tcx.hir().get_parent_node(expr.hir_id))
2114             {
2115                 expr.hir_id == callee.hir_id
2116             } else {
2117                 false
2118             };
2119         let expr_snippet =
2120             self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or(String::new());
2121         let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')');
2122         let after_open = expr.span.lo() + rustc_span::BytePos(1);
2123         let before_close = expr.span.hi() - rustc_span::BytePos(1);
2124
2125         if expr_is_call && is_wrapped {
2126             err.multipart_suggestion(
2127                 "remove wrapping parentheses to call the method",
2128                 vec![
2129                     (expr.span.with_hi(after_open), String::new()),
2130                     (expr.span.with_lo(before_close), String::new()),
2131                 ],
2132                 Applicability::MachineApplicable,
2133             );
2134         } else if !self.expr_in_place(expr.hir_id) {
2135             // Suggest call parentheses inside the wrapping parentheses
2136             let span = if is_wrapped {
2137                 expr.span.with_lo(after_open).with_hi(before_close)
2138             } else {
2139                 expr.span
2140             };
2141             self.suggest_method_call(
2142                 &mut err,
2143                 "use parentheses to call the method",
2144                 field,
2145                 expr_t,
2146                 expr,
2147                 Some(span),
2148             );
2149         } else {
2150             let mut found = false;
2151
2152             if let ty::RawPtr(ty_and_mut) = expr_t.kind()
2153                 && let ty::Adt(adt_def, _) = ty_and_mut.ty.kind()
2154             {
2155                 if adt_def.variants().len() == 1
2156                     && adt_def
2157                         .variants()
2158                         .iter()
2159                         .next()
2160                         .unwrap()
2161                         .fields
2162                         .iter()
2163                         .any(|f| f.ident(self.tcx) == field)
2164                 {
2165                     if let Some(dot_loc) = expr_snippet.rfind('.') {
2166                         found = true;
2167                         err.span_suggestion(
2168                             expr.span.with_hi(expr.span.lo() + BytePos::from_usize(dot_loc)),
2169                             "to access the field, dereference first",
2170                             format!("(*{})", &expr_snippet[0..dot_loc]),
2171                             Applicability::MaybeIncorrect,
2172                         );
2173                     }
2174                 }
2175             }
2176
2177             if !found {
2178                 err.help("methods are immutable and cannot be assigned to");
2179             }
2180         }
2181
2182         err.emit();
2183     }
2184
2185     fn point_at_param_definition(&self, err: &mut Diagnostic, param: ty::ParamTy) {
2186         let generics = self.tcx.generics_of(self.body_id.owner.to_def_id());
2187         let generic_param = generics.type_param(&param, self.tcx);
2188         if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
2189             return;
2190         }
2191         let param_def_id = generic_param.def_id;
2192         let param_hir_id = match param_def_id.as_local() {
2193             Some(x) => self.tcx.hir().local_def_id_to_hir_id(x),
2194             None => return,
2195         };
2196         let param_span = self.tcx.hir().span(param_hir_id);
2197         let param_name = self.tcx.hir().ty_param_name(param_def_id.expect_local());
2198
2199         err.span_label(param_span, &format!("type parameter '{param_name}' declared here"));
2200     }
2201
2202     fn suggest_fields_on_recordish(
2203         &self,
2204         err: &mut Diagnostic,
2205         def: ty::AdtDef<'tcx>,
2206         field: Ident,
2207         access_span: Span,
2208     ) {
2209         if let Some(suggested_field_name) =
2210             self.suggest_field_name(def.non_enum_variant(), field.name, vec![], access_span)
2211         {
2212             err.span_suggestion(
2213                 field.span,
2214                 "a field with a similar name exists",
2215                 suggested_field_name.to_string(),
2216                 Applicability::MaybeIncorrect,
2217             );
2218         } else {
2219             err.span_label(field.span, "unknown field");
2220             let struct_variant_def = def.non_enum_variant();
2221             let field_names = self.available_field_names(struct_variant_def, access_span);
2222             if !field_names.is_empty() {
2223                 err.note(&format!(
2224                     "available fields are: {}",
2225                     self.name_series_display(field_names),
2226                 ));
2227             }
2228         }
2229     }
2230
2231     fn maybe_suggest_array_indexing(
2232         &self,
2233         err: &mut Diagnostic,
2234         expr: &hir::Expr<'_>,
2235         base: &hir::Expr<'_>,
2236         field: Ident,
2237         len: ty::Const<'tcx>,
2238     ) {
2239         if let (Some(len), Ok(user_index)) =
2240             (len.try_eval_usize(self.tcx, self.param_env), field.as_str().parse::<u64>())
2241             && let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span)
2242         {
2243             let help = "instead of using tuple indexing, use array indexing";
2244             let suggestion = format!("{base}[{field}]");
2245             let applicability = if len < user_index {
2246                 Applicability::MachineApplicable
2247             } else {
2248                 Applicability::MaybeIncorrect
2249             };
2250             err.span_suggestion(expr.span, help, suggestion, applicability);
2251         }
2252     }
2253
2254     fn suggest_first_deref_field(
2255         &self,
2256         err: &mut Diagnostic,
2257         expr: &hir::Expr<'_>,
2258         base: &hir::Expr<'_>,
2259         field: Ident,
2260     ) {
2261         if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) {
2262             let msg = format!("`{base}` is a raw pointer; try dereferencing it");
2263             let suggestion = format!("(*{base}).{field}");
2264             err.span_suggestion(expr.span, &msg, suggestion, Applicability::MaybeIncorrect);
2265         }
2266     }
2267
2268     fn no_such_field_err(
2269         &self,
2270         field: Ident,
2271         expr_t: Ty<'tcx>,
2272         id: HirId,
2273     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
2274         let span = field.span;
2275         debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, expr_t);
2276
2277         let mut err = type_error_struct!(
2278             self.tcx().sess,
2279             field.span,
2280             expr_t,
2281             E0609,
2282             "no field `{field}` on type `{expr_t}`",
2283         );
2284
2285         // try to add a suggestion in case the field is a nested field of a field of the Adt
2286         if let Some((fields, substs)) = self.get_field_candidates(span, expr_t) {
2287             for candidate_field in fields.iter() {
2288                 if let Some(field_path) = self.check_for_nested_field(
2289                     span,
2290                     field,
2291                     candidate_field,
2292                     substs,
2293                     vec![],
2294                     self.tcx.parent_module(id).to_def_id(),
2295                 ) {
2296                     let field_path_str = field_path
2297                         .iter()
2298                         .map(|id| id.name.to_ident_string())
2299                         .collect::<Vec<String>>()
2300                         .join(".");
2301                     debug!("field_path_str: {:?}", field_path_str);
2302
2303                     err.span_suggestion_verbose(
2304                         field.span.shrink_to_lo(),
2305                         "one of the expressions' fields has a field of the same name",
2306                         format!("{field_path_str}."),
2307                         Applicability::MaybeIncorrect,
2308                     );
2309                 }
2310             }
2311         }
2312         err
2313     }
2314
2315     fn get_field_candidates(
2316         &self,
2317         span: Span,
2318         base_t: Ty<'tcx>,
2319     ) -> Option<(&Vec<ty::FieldDef>, SubstsRef<'tcx>)> {
2320         debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_t);
2321
2322         for (base_t, _) in self.autoderef(span, base_t) {
2323             match base_t.kind() {
2324                 ty::Adt(base_def, substs) if !base_def.is_enum() => {
2325                     let fields = &base_def.non_enum_variant().fields;
2326                     // For compile-time reasons put a limit on number of fields we search
2327                     if fields.len() > 100 {
2328                         return None;
2329                     }
2330                     return Some((fields, substs));
2331                 }
2332                 _ => {}
2333             }
2334         }
2335         None
2336     }
2337
2338     /// This method is called after we have encountered a missing field error to recursively
2339     /// search for the field
2340     fn check_for_nested_field(
2341         &self,
2342         span: Span,
2343         target_field: Ident,
2344         candidate_field: &ty::FieldDef,
2345         subst: SubstsRef<'tcx>,
2346         mut field_path: Vec<Ident>,
2347         id: DefId,
2348     ) -> Option<Vec<Ident>> {
2349         debug!(
2350             "check_for_nested_field(span: {:?}, candidate_field: {:?}, field_path: {:?}",
2351             span, candidate_field, field_path
2352         );
2353
2354         if candidate_field.ident(self.tcx) == target_field {
2355             Some(field_path)
2356         } else if field_path.len() > 3 {
2357             // For compile-time reasons and to avoid infinite recursion we only check for fields
2358             // up to a depth of three
2359             None
2360         } else {
2361             // recursively search fields of `candidate_field` if it's a ty::Adt
2362
2363             field_path.push(candidate_field.ident(self.tcx).normalize_to_macros_2_0());
2364             let field_ty = candidate_field.ty(self.tcx, subst);
2365             if let Some((nested_fields, subst)) = self.get_field_candidates(span, field_ty) {
2366                 for field in nested_fields.iter() {
2367                     let accessible = field.vis.is_accessible_from(id, self.tcx);
2368                     if accessible {
2369                         let ident = field.ident(self.tcx).normalize_to_macros_2_0();
2370                         if ident == target_field {
2371                             return Some(field_path);
2372                         }
2373                         let field_path = field_path.clone();
2374                         if let Some(path) = self.check_for_nested_field(
2375                             span,
2376                             target_field,
2377                             field,
2378                             subst,
2379                             field_path,
2380                             id,
2381                         ) {
2382                             return Some(path);
2383                         }
2384                     }
2385                 }
2386             }
2387             None
2388         }
2389     }
2390
2391     fn check_expr_index(
2392         &self,
2393         base: &'tcx hir::Expr<'tcx>,
2394         idx: &'tcx hir::Expr<'tcx>,
2395         expr: &'tcx hir::Expr<'tcx>,
2396     ) -> Ty<'tcx> {
2397         let base_t = self.check_expr(&base);
2398         let idx_t = self.check_expr(&idx);
2399
2400         if base_t.references_error() {
2401             base_t
2402         } else if idx_t.references_error() {
2403             idx_t
2404         } else {
2405             let base_t = self.structurally_resolved_type(base.span, base_t);
2406             match self.lookup_indexing(expr, base, base_t, idx, idx_t) {
2407                 Some((index_ty, element_ty)) => {
2408                     // two-phase not needed because index_ty is never mutable
2409                     self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
2410                     element_ty
2411                 }
2412                 None => {
2413                     let mut err = type_error_struct!(
2414                         self.tcx.sess,
2415                         expr.span,
2416                         base_t,
2417                         E0608,
2418                         "cannot index into a value of type `{base_t}`",
2419                     );
2420                     // Try to give some advice about indexing tuples.
2421                     if let ty::Tuple(..) = base_t.kind() {
2422                         let mut needs_note = true;
2423                         // If the index is an integer, we can show the actual
2424                         // fixed expression:
2425                         if let ExprKind::Lit(ref lit) = idx.kind {
2426                             if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
2427                                 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
2428                                 if let Ok(snip) = snip {
2429                                     err.span_suggestion(
2430                                         expr.span,
2431                                         "to access tuple elements, use",
2432                                         format!("{snip}.{i}"),
2433                                         Applicability::MachineApplicable,
2434                                     );
2435                                     needs_note = false;
2436                                 }
2437                             }
2438                         }
2439                         if needs_note {
2440                             err.help(
2441                                 "to access tuple elements, use tuple indexing \
2442                                         syntax (e.g., `tuple.0`)",
2443                             );
2444                         }
2445                     }
2446                     err.emit();
2447                     self.tcx.ty_error()
2448                 }
2449             }
2450         }
2451     }
2452
2453     fn check_expr_yield(
2454         &self,
2455         value: &'tcx hir::Expr<'tcx>,
2456         expr: &'tcx hir::Expr<'tcx>,
2457         src: &'tcx hir::YieldSource,
2458     ) -> Ty<'tcx> {
2459         match self.resume_yield_tys {
2460             Some((resume_ty, yield_ty)) => {
2461                 self.check_expr_coercable_to_type(&value, yield_ty, None);
2462
2463                 resume_ty
2464             }
2465             // Given that this `yield` expression was generated as a result of lowering a `.await`,
2466             // we know that the yield type must be `()`; however, the context won't contain this
2467             // information. Hence, we check the source of the yield expression here and check its
2468             // value's type against `()` (this check should always hold).
2469             None if src.is_await() => {
2470                 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit(), None);
2471                 self.tcx.mk_unit()
2472             }
2473             _ => {
2474                 self.tcx.sess.emit_err(YieldExprOutsideOfGenerator { span: expr.span });
2475                 // Avoid expressions without types during writeback (#78653).
2476                 self.check_expr(value);
2477                 self.tcx.mk_unit()
2478             }
2479         }
2480     }
2481
2482     fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
2483         let needs = if is_input { Needs::None } else { Needs::MutPlace };
2484         let ty = self.check_expr_with_needs(expr, needs);
2485         self.require_type_is_sized(ty, expr.span, traits::InlineAsmSized);
2486
2487         if !is_input && !expr.is_syntactic_place_expr() {
2488             let mut err = self.tcx.sess.struct_span_err(expr.span, "invalid asm output");
2489             err.span_label(expr.span, "cannot assign to this expression");
2490             err.emit();
2491         }
2492
2493         // If this is an input value, we require its type to be fully resolved
2494         // at this point. This allows us to provide helpful coercions which help
2495         // pass the type candidate list in a later pass.
2496         //
2497         // We don't require output types to be resolved at this point, which
2498         // allows them to be inferred based on how they are used later in the
2499         // function.
2500         if is_input {
2501             let ty = self.structurally_resolved_type(expr.span, ty);
2502             match *ty.kind() {
2503                 ty::FnDef(..) => {
2504                     let fnptr_ty = self.tcx.mk_fn_ptr(ty.fn_sig(self.tcx));
2505                     self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
2506                 }
2507                 ty::Ref(_, base_ty, mutbl) => {
2508                     let ptr_ty = self.tcx.mk_ptr(ty::TypeAndMut { ty: base_ty, mutbl });
2509                     self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
2510                 }
2511                 _ => {}
2512             }
2513         }
2514     }
2515
2516     fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>) -> Ty<'tcx> {
2517         for (op, _op_sp) in asm.operands {
2518             match op {
2519                 hir::InlineAsmOperand::In { expr, .. } => {
2520                     self.check_expr_asm_operand(expr, true);
2521                 }
2522                 hir::InlineAsmOperand::Out { expr: Some(expr), .. }
2523                 | hir::InlineAsmOperand::InOut { expr, .. } => {
2524                     self.check_expr_asm_operand(expr, false);
2525                 }
2526                 hir::InlineAsmOperand::Out { expr: None, .. } => {}
2527                 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
2528                     self.check_expr_asm_operand(in_expr, true);
2529                     if let Some(out_expr) = out_expr {
2530                         self.check_expr_asm_operand(out_expr, false);
2531                     }
2532                 }
2533                 hir::InlineAsmOperand::Const { anon_const }
2534                 | hir::InlineAsmOperand::SymFn { anon_const } => {
2535                     self.to_const(anon_const);
2536                 }
2537                 hir::InlineAsmOperand::SymStatic { .. } => {}
2538             }
2539         }
2540         if asm.options.contains(ast::InlineAsmOptions::NORETURN) {
2541             self.tcx.types.never
2542         } else {
2543             self.tcx.mk_unit()
2544         }
2545     }
2546 }
2547
2548 pub(super) fn ty_kind_suggestion(ty: Ty<'_>) -> Option<&'static str> {
2549     Some(match ty.kind() {
2550         ty::Bool => "true",
2551         ty::Char => "'a'",
2552         ty::Int(_) | ty::Uint(_) => "42",
2553         ty::Float(_) => "3.14159",
2554         ty::Error(_) | ty::Never => return None,
2555         _ => "value",
2556     })
2557 }