rustc_hir_typeck/
expr.rs

1// ignore-tidy-filelength
2// FIXME: we should move the field error reporting code somewhere else.
3
4//! Type checking expressions.
5//!
6//! See [`rustc_hir_analysis::check`] for more context on type checking in general.
7
8use rustc_abi::{FIRST_VARIANT, FieldIdx};
9use rustc_ast::util::parser::ExprPrecedence;
10use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11use rustc_data_structures::stack::ensure_sufficient_stack;
12use rustc_data_structures::unord::UnordMap;
13use rustc_errors::codes::*;
14use rustc_errors::{
15    Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, Subdiagnostic, listify, pluralize,
16    struct_span_code_err,
17};
18use rustc_hir::attrs::AttributeKind;
19use rustc_hir::def::{CtorKind, DefKind, Res};
20use rustc_hir::def_id::DefId;
21use rustc_hir::lang_items::LangItem;
22use rustc_hir::{ExprKind, HirId, QPath, find_attr};
23use rustc_hir_analysis::NoVariantNamed;
24use rustc_hir_analysis::hir_ty_lowering::{FeedConstTy, HirTyLowerer as _};
25use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk, RegionVariableOrigin};
26use rustc_infer::traits::query::NoSolution;
27use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
28use rustc_middle::ty::error::{ExpectedFound, TypeError};
29use rustc_middle::ty::{self, AdtKind, GenericArgsRef, Ty, TypeVisitableExt};
30use rustc_middle::{bug, span_bug};
31use rustc_session::errors::ExprParenthesesNeeded;
32use rustc_session::parse::feature_err;
33use rustc_span::edit_distance::find_best_match_for_name;
34use rustc_span::hygiene::DesugaringKind;
35use rustc_span::source_map::Spanned;
36use rustc_span::{Ident, Span, Symbol, kw, sym};
37use rustc_trait_selection::infer::InferCtxtExt;
38use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt};
39use tracing::{debug, instrument, trace};
40use {rustc_ast as ast, rustc_hir as hir};
41
42use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation};
43use crate::coercion::{CoerceMany, DynamicCoerceMany};
44use crate::errors::{
45    AddressOfTemporaryTaken, BaseExpressionDoubleDot, BaseExpressionDoubleDotAddExpr,
46    BaseExpressionDoubleDotRemove, CantDereference, FieldMultiplySpecifiedInInitializer,
47    FunctionalRecordUpdateOnNonStruct, HelpUseLatestEdition, NakedAsmOutsideNakedFn, NoFieldOnType,
48    NoFieldOnVariant, ReturnLikeStatementKind, ReturnStmtOutsideOfFnBody, StructExprNonExhaustive,
49    TypeMismatchFruTypo, YieldExprOutsideOfCoroutine,
50};
51use crate::{
52    BreakableCtxt, CoroutineTypes, Diverges, FnCtxt, GatherLocalsVisitor, Needs,
53    TupleArgumentsFlag, cast, fatally_break_rust, report_unexpected_variant_res, type_error_struct,
54};
55
56impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
57    pub(crate) fn precedence(&self, expr: &hir::Expr<'_>) -> ExprPrecedence {
58        let has_attr = |id: HirId| -> bool {
59            for attr in self.tcx.hir_attrs(id) {
60                // For the purpose of rendering suggestions, disregard attributes
61                // that originate from desugaring of any kind. For example, `x?`
62                // desugars to `#[allow(unreachable_code)] match ...`. Failing to
63                // ignore the prefix attribute in the desugaring would cause this
64                // suggestion:
65                //
66                //     let y: u32 = x?.try_into().unwrap();
67                //                    ++++++++++++++++++++
68                //
69                // to be rendered as:
70                //
71                //     let y: u32 = (x?).try_into().unwrap();
72                //                  +  +++++++++++++++++++++
73                if attr.span().desugaring_kind().is_none() {
74                    return true;
75                }
76            }
77            false
78        };
79        expr.precedence(&has_attr)
80    }
81
82    /// Check an expr with an expectation type, and also demand that the expr's
83    /// evaluated type is a subtype of the expectation at the end. This is a
84    /// *hard* requirement.
85    pub(crate) fn check_expr_has_type_or_error(
86        &self,
87        expr: &'tcx hir::Expr<'tcx>,
88        expected_ty: Ty<'tcx>,
89        extend_err: impl FnOnce(&mut Diag<'_>),
90    ) -> Ty<'tcx> {
91        let mut ty = self.check_expr_with_expectation(expr, ExpectHasType(expected_ty));
92
93        // While we don't allow *arbitrary* coercions here, we *do* allow
94        // coercions from ! to `expected`.
95        if self.try_structurally_resolve_type(expr.span, ty).is_never()
96            && self.expr_guaranteed_to_constitute_read_for_never(expr)
97        {
98            if let Some(adjustments) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
99                let reported = self.dcx().span_delayed_bug(
100                    expr.span,
101                    "expression with never type wound up being adjusted",
102                );
103
104                return if let [Adjustment { kind: Adjust::NeverToAny, target }] = &adjustments[..] {
105                    target.to_owned()
106                } else {
107                    Ty::new_error(self.tcx(), reported)
108                };
109            }
110
111            let adj_ty = self.next_ty_var(expr.span);
112            self.apply_adjustments(
113                expr,
114                vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }],
115            );
116            ty = adj_ty;
117        }
118
119        if let Err(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
120            let _ = self.emit_type_mismatch_suggestions(
121                &mut err,
122                expr.peel_drop_temps(),
123                ty,
124                expected_ty,
125                None,
126                None,
127            );
128            extend_err(&mut err);
129            err.emit();
130        }
131        ty
132    }
133
134    /// Check an expr with an expectation type, and also demand that the expr's
135    /// evaluated type is a coercible to the expectation at the end. This is a
136    /// *hard* requirement.
137    pub(super) fn check_expr_coercible_to_type(
138        &self,
139        expr: &'tcx hir::Expr<'tcx>,
140        expected: Ty<'tcx>,
141        expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
142    ) -> Ty<'tcx> {
143        self.check_expr_coercible_to_type_or_error(expr, expected, expected_ty_expr, |_, _| {})
144    }
145
146    pub(crate) fn check_expr_coercible_to_type_or_error(
147        &self,
148        expr: &'tcx hir::Expr<'tcx>,
149        expected: Ty<'tcx>,
150        expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
151        extend_err: impl FnOnce(&mut Diag<'_>, Ty<'tcx>),
152    ) -> Ty<'tcx> {
153        let ty = self.check_expr_with_hint(expr, expected);
154        // checks don't need two phase
155        match self.demand_coerce_diag(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No) {
156            Ok(ty) => ty,
157            Err(mut err) => {
158                extend_err(&mut err, ty);
159                err.emit();
160                // Return the original type instead of an error type here, otherwise the type of `x` in
161                // `let x: u32 = ();` will be a type error, causing all subsequent usages of `x` to not
162                // report errors, even though `x` is definitely `u32`.
163                expected
164            }
165        }
166    }
167
168    /// Check an expr with an expectation type. Don't actually enforce that expectation
169    /// is related to the expr's evaluated type via subtyping or coercion. This is
170    /// usually called because we want to do that subtype/coerce call manually for better
171    /// diagnostics.
172    pub(super) fn check_expr_with_hint(
173        &self,
174        expr: &'tcx hir::Expr<'tcx>,
175        expected: Ty<'tcx>,
176    ) -> Ty<'tcx> {
177        self.check_expr_with_expectation(expr, ExpectHasType(expected))
178    }
179
180    /// Check an expr with an expectation type, and also [`Needs`] which will
181    /// prompt typeck to convert any implicit immutable derefs to mutable derefs.
182    fn check_expr_with_expectation_and_needs(
183        &self,
184        expr: &'tcx hir::Expr<'tcx>,
185        expected: Expectation<'tcx>,
186        needs: Needs,
187    ) -> Ty<'tcx> {
188        let ty = self.check_expr_with_expectation(expr, expected);
189
190        // If the expression is used in a place whether mutable place is required
191        // e.g. LHS of assignment, perform the conversion.
192        if let Needs::MutPlace = needs {
193            self.convert_place_derefs_to_mutable(expr);
194        }
195
196        ty
197    }
198
199    /// Check an expr with no expectations.
200    pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
201        self.check_expr_with_expectation(expr, NoExpectation)
202    }
203
204    /// Check an expr with no expectations, but with [`Needs`] which will
205    /// prompt typeck to convert any implicit immutable derefs to mutable derefs.
206    pub(super) fn check_expr_with_needs(
207        &self,
208        expr: &'tcx hir::Expr<'tcx>,
209        needs: Needs,
210    ) -> Ty<'tcx> {
211        self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
212    }
213
214    /// Check an expr with an expectation type which may be used to eagerly
215    /// guide inference when evaluating that expr.
216    #[instrument(skip(self, expr), level = "debug")]
217    pub(super) fn check_expr_with_expectation(
218        &self,
219        expr: &'tcx hir::Expr<'tcx>,
220        expected: Expectation<'tcx>,
221    ) -> Ty<'tcx> {
222        self.check_expr_with_expectation_and_args(expr, expected, None)
223    }
224
225    /// Same as [`Self::check_expr_with_expectation`], but allows us to pass in
226    /// the arguments of a [`ExprKind::Call`] when evaluating its callee that
227    /// is an [`ExprKind::Path`]. We use this to refine the spans for certain
228    /// well-formedness guarantees for the path expr.
229    pub(super) fn check_expr_with_expectation_and_args(
230        &self,
231        expr: &'tcx hir::Expr<'tcx>,
232        expected: Expectation<'tcx>,
233        call_expr_and_args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
234    ) -> Ty<'tcx> {
235        if self.tcx().sess.verbose_internals() {
236            // make this code only run with -Zverbose-internals because it is probably slow
237            if let Ok(lint_str) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
238                if !lint_str.contains('\n') {
239                    debug!("expr text: {lint_str}");
240                } else {
241                    let mut lines = lint_str.lines();
242                    if let Some(line0) = lines.next() {
243                        let remaining_lines = lines.count();
244                        debug!("expr text: {line0}");
245                        debug!("expr text: ...(and {remaining_lines} more lines)");
246                    }
247                }
248            }
249        }
250
251        // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
252        // without the final expr (e.g. `try { return; }`). We don't want to generate an
253        // unreachable_code lint for it since warnings for autogenerated code are confusing.
254        let is_try_block_generated_unit_expr = match expr.kind {
255            ExprKind::Call(_, [arg]) => {
256                expr.span.is_desugaring(DesugaringKind::TryBlock)
257                    && arg.span.is_desugaring(DesugaringKind::TryBlock)
258            }
259            _ => false,
260        };
261
262        // Warn for expressions after diverging siblings.
263        if !is_try_block_generated_unit_expr {
264            self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
265        }
266
267        // Whether a past expression diverges doesn't affect typechecking of this expression, so we
268        // reset `diverges` while checking `expr`.
269        let old_diverges = self.diverges.replace(Diverges::Maybe);
270
271        if self.is_whole_body.replace(false) {
272            // If this expression is the whole body and the function diverges because of its
273            // arguments, we check this here to ensure the body is considered to diverge.
274            self.diverges.set(self.function_diverges_because_of_empty_arguments.get())
275        };
276
277        let ty = ensure_sufficient_stack(|| match &expr.kind {
278            // Intercept the callee path expr and give it better spans.
279            hir::ExprKind::Path(
280                qpath @ (hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)),
281            ) => self.check_expr_path(qpath, expr, call_expr_and_args),
282            _ => self.check_expr_kind(expr, expected),
283        });
284        let ty = self.resolve_vars_if_possible(ty);
285
286        // Warn for non-block expressions with diverging children.
287        match expr.kind {
288            ExprKind::Block(..)
289            | ExprKind::If(..)
290            | ExprKind::Let(..)
291            | ExprKind::Loop(..)
292            | ExprKind::Match(..) => {}
293            // Do not warn on `as` casts from never to any,
294            // they are sometimes required to appeal typeck.
295            ExprKind::Cast(_, _) => {}
296            // If `expr` is a result of desugaring the try block and is an ok-wrapped
297            // diverging expression (e.g. it arose from desugaring of `try { return }`),
298            // we skip issuing a warning because it is autogenerated code.
299            ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {}
300            // Likewise, do not lint unreachable code injected via contracts desugaring.
301            ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::Contract) => {}
302            ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"),
303            ExprKind::MethodCall(segment, ..) => {
304                self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call")
305            }
306            _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
307        }
308
309        // Any expression that produces a value of type `!` must have diverged,
310        // unless it's a place expression that isn't being read from, in which case
311        // diverging would be unsound since we may never actually read the `!`.
312        // e.g. `let _ = *never_ptr;` with `never_ptr: *const !`.
313        if self.try_structurally_resolve_type(expr.span, ty).is_never()
314            && self.expr_guaranteed_to_constitute_read_for_never(expr)
315        {
316            self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
317        }
318
319        // Record the type, which applies it effects.
320        // We need to do this after the warning above, so that
321        // we don't warn for the diverging expression itself.
322        self.write_ty(expr.hir_id, ty);
323
324        // Combine the diverging and has_error flags.
325        self.diverges.set(self.diverges.get() | old_diverges);
326
327        debug!("type of {} is...", self.tcx.hir_id_to_string(expr.hir_id));
328        debug!("... {:?}, expected is {:?}", ty, expected);
329
330        ty
331    }
332
333    /// Whether this expression constitutes a read of value of the type that
334    /// it evaluates to.
335    ///
336    /// This is used to determine if we should consider the block to diverge
337    /// if the expression evaluates to `!`, and if we should insert a `NeverToAny`
338    /// coercion for values of type `!`.
339    ///
340    /// This function generally returns `false` if the expression is a place
341    /// expression and the *parent* expression is the scrutinee of a match or
342    /// the pointee of an `&` addr-of expression, since both of those parent
343    /// expressions take a *place* and not a value.
344    pub(super) fn expr_guaranteed_to_constitute_read_for_never(
345        &self,
346        expr: &'tcx hir::Expr<'tcx>,
347    ) -> bool {
348        // We only care about place exprs. Anything else returns an immediate
349        // which would constitute a read. We don't care about distinguishing
350        // "syntactic" place exprs since if the base of a field projection is
351        // not a place then it would've been UB to read from it anyways since
352        // that constitutes a read.
353        if !expr.is_syntactic_place_expr() {
354            return true;
355        }
356
357        let parent_node = self.tcx.parent_hir_node(expr.hir_id);
358        match parent_node {
359            hir::Node::Expr(parent_expr) => {
360                match parent_expr.kind {
361                    // Addr-of, field projections, and LHS of assignment don't constitute reads.
362                    // Assignment does call `drop_in_place`, though, but its safety
363                    // requirements are not the same.
364                    ExprKind::AddrOf(..) | hir::ExprKind::Field(..) => false,
365
366                    // Place-preserving expressions only constitute reads if their
367                    // parent expression constitutes a read.
368                    ExprKind::Type(..) | ExprKind::UnsafeBinderCast(..) => {
369                        self.expr_guaranteed_to_constitute_read_for_never(expr)
370                    }
371
372                    ExprKind::Assign(lhs, _, _) => {
373                        // Only the LHS does not constitute a read
374                        expr.hir_id != lhs.hir_id
375                    }
376
377                    // See note on `PatKind::Or` below for why this is `all`.
378                    ExprKind::Match(scrutinee, arms, _) => {
379                        assert_eq!(scrutinee.hir_id, expr.hir_id);
380                        arms.iter()
381                            .all(|arm| self.pat_guaranteed_to_constitute_read_for_never(arm.pat))
382                    }
383                    ExprKind::Let(hir::LetExpr { init, pat, .. }) => {
384                        assert_eq!(init.hir_id, expr.hir_id);
385                        self.pat_guaranteed_to_constitute_read_for_never(*pat)
386                    }
387
388                    // Any expression child of these expressions constitute reads.
389                    ExprKind::Array(_)
390                    | ExprKind::Call(_, _)
391                    | ExprKind::Use(_, _)
392                    | ExprKind::MethodCall(_, _, _, _)
393                    | ExprKind::Tup(_)
394                    | ExprKind::Binary(_, _, _)
395                    | ExprKind::Unary(_, _)
396                    | ExprKind::Cast(_, _)
397                    | ExprKind::DropTemps(_)
398                    | ExprKind::If(_, _, _)
399                    | ExprKind::Closure(_)
400                    | ExprKind::Block(_, _)
401                    | ExprKind::AssignOp(_, _, _)
402                    | ExprKind::Index(_, _, _)
403                    | ExprKind::Break(_, _)
404                    | ExprKind::Ret(_)
405                    | ExprKind::Become(_)
406                    | ExprKind::InlineAsm(_)
407                    | ExprKind::Struct(_, _, _)
408                    | ExprKind::Repeat(_, _)
409                    | ExprKind::Yield(_, _) => true,
410
411                    // These expressions have no (direct) sub-exprs.
412                    ExprKind::ConstBlock(_)
413                    | ExprKind::Loop(_, _, _, _)
414                    | ExprKind::Lit(_)
415                    | ExprKind::Path(_)
416                    | ExprKind::Continue(_)
417                    | ExprKind::OffsetOf(_, _)
418                    | ExprKind::Err(_) => unreachable!("no sub-expr expected for {:?}", expr.kind),
419                }
420            }
421
422            // If we have a subpattern that performs a read, we want to consider this
423            // to diverge for compatibility to support something like `let x: () = *never_ptr;`.
424            hir::Node::LetStmt(hir::LetStmt { init: Some(target), pat, .. }) => {
425                assert_eq!(target.hir_id, expr.hir_id);
426                self.pat_guaranteed_to_constitute_read_for_never(*pat)
427            }
428
429            // These nodes (if they have a sub-expr) do constitute a read.
430            hir::Node::Block(_)
431            | hir::Node::Arm(_)
432            | hir::Node::ExprField(_)
433            | hir::Node::AnonConst(_)
434            | hir::Node::ConstBlock(_)
435            | hir::Node::ConstArg(_)
436            | hir::Node::Stmt(_)
437            | hir::Node::Item(hir::Item {
438                kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..),
439                ..
440            })
441            | hir::Node::TraitItem(hir::TraitItem {
442                kind: hir::TraitItemKind::Const(..), ..
443            })
444            | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. }) => true,
445
446            hir::Node::TyPat(_) | hir::Node::Pat(_) => {
447                self.dcx().span_delayed_bug(expr.span, "place expr not allowed in pattern");
448                true
449            }
450
451            // These nodes do not have direct sub-exprs.
452            hir::Node::Param(_)
453            | hir::Node::Item(_)
454            | hir::Node::ForeignItem(_)
455            | hir::Node::TraitItem(_)
456            | hir::Node::ImplItem(_)
457            | hir::Node::Variant(_)
458            | hir::Node::Field(_)
459            | hir::Node::PathSegment(_)
460            | hir::Node::Ty(_)
461            | hir::Node::AssocItemConstraint(_)
462            | hir::Node::TraitRef(_)
463            | hir::Node::PatField(_)
464            | hir::Node::PatExpr(_)
465            | hir::Node::LetStmt(_)
466            | hir::Node::Synthetic
467            | hir::Node::Err(_)
468            | hir::Node::Ctor(_)
469            | hir::Node::Lifetime(_)
470            | hir::Node::GenericParam(_)
471            | hir::Node::Crate(_)
472            | hir::Node::Infer(_)
473            | hir::Node::WherePredicate(_)
474            | hir::Node::PreciseCapturingNonLifetimeArg(_)
475            | hir::Node::OpaqueTy(_) => {
476                unreachable!("no sub-expr expected for {parent_node:?}")
477            }
478        }
479    }
480
481    /// Whether this pattern constitutes a read of value of the scrutinee that
482    /// it is matching against. This is used to determine whether we should
483    /// perform `NeverToAny` coercions.
484    ///
485    /// See above for the nuances of what happens when this returns true.
486    pub(super) fn pat_guaranteed_to_constitute_read_for_never(&self, pat: &hir::Pat<'_>) -> bool {
487        match pat.kind {
488            // Does not constitute a read.
489            hir::PatKind::Wild => false,
490
491            // Might not constitute a read, since the condition might be false.
492            hir::PatKind::Guard(_, _) => true,
493
494            // This is unnecessarily restrictive when the pattern that doesn't
495            // constitute a read is unreachable.
496            //
497            // For example `match *never_ptr { value => {}, _ => {} }` or
498            // `match *never_ptr { _ if false => {}, value => {} }`.
499            //
500            // It is however fine to be restrictive here; only returning `true`
501            // can lead to unsoundness.
502            hir::PatKind::Or(subpats) => {
503                subpats.iter().all(|pat| self.pat_guaranteed_to_constitute_read_for_never(pat))
504            }
505
506            // Does constitute a read, since it is equivalent to a discriminant read.
507            hir::PatKind::Never => true,
508
509            // All of these constitute a read, or match on something that isn't `!`,
510            // which would require a `NeverToAny` coercion.
511            hir::PatKind::Missing
512            | hir::PatKind::Binding(_, _, _, _)
513            | hir::PatKind::Struct(_, _, _)
514            | hir::PatKind::TupleStruct(_, _, _)
515            | hir::PatKind::Tuple(_, _)
516            | hir::PatKind::Box(_)
517            | hir::PatKind::Ref(_, _)
518            | hir::PatKind::Deref(_)
519            | hir::PatKind::Expr(_)
520            | hir::PatKind::Range(_, _, _)
521            | hir::PatKind::Slice(_, _, _)
522            | hir::PatKind::Err(_) => true,
523        }
524    }
525
526    #[instrument(skip(self, expr), level = "debug")]
527    fn check_expr_kind(
528        &self,
529        expr: &'tcx hir::Expr<'tcx>,
530        expected: Expectation<'tcx>,
531    ) -> Ty<'tcx> {
532        trace!("expr={:#?}", expr);
533
534        let tcx = self.tcx;
535        match expr.kind {
536            ExprKind::Lit(ref lit) => self.check_expr_lit(lit, expected),
537            ExprKind::Binary(op, lhs, rhs) => self.check_expr_binop(expr, op, lhs, rhs, expected),
538            ExprKind::Assign(lhs, rhs, span) => {
539                self.check_expr_assign(expr, expected, lhs, rhs, span)
540            }
541            ExprKind::AssignOp(op, lhs, rhs) => {
542                self.check_expr_assign_op(expr, op, lhs, rhs, expected)
543            }
544            ExprKind::Unary(unop, oprnd) => self.check_expr_unop(unop, oprnd, expected, expr),
545            ExprKind::AddrOf(kind, mutbl, oprnd) => {
546                self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
547            }
548            ExprKind::Path(QPath::LangItem(lang_item, _)) => {
549                self.check_lang_item_path(lang_item, expr)
550            }
551            ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr, None),
552            ExprKind::InlineAsm(asm) => {
553                // We defer some asm checks as we may not have resolved the input and output types yet (they may still be infer vars).
554                self.deferred_asm_checks.borrow_mut().push((asm, expr.hir_id));
555                self.check_expr_asm(asm, expr.span)
556            }
557            ExprKind::OffsetOf(container, fields) => {
558                self.check_expr_offset_of(container, fields, expr)
559            }
560            ExprKind::Break(destination, ref expr_opt) => {
561                self.check_expr_break(destination, expr_opt.as_deref(), expr)
562            }
563            ExprKind::Continue(destination) => self.check_expr_continue(destination, expr),
564            ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
565            ExprKind::Become(call) => self.check_expr_become(call, expr),
566            ExprKind::Let(let_expr) => self.check_expr_let(let_expr, expr.hir_id),
567            ExprKind::Loop(body, _, source, _) => {
568                self.check_expr_loop(body, source, expected, expr)
569            }
570            ExprKind::Match(discrim, arms, match_src) => {
571                self.check_expr_match(expr, discrim, arms, expected, match_src)
572            }
573            ExprKind::Closure(closure) => self.check_expr_closure(closure, expr.span, expected),
574            ExprKind::Block(body, _) => self.check_expr_block(body, expected),
575            ExprKind::Call(callee, args) => self.check_expr_call(expr, callee, args, expected),
576            ExprKind::Use(used_expr, _) => self.check_expr_use(used_expr, expected),
577            ExprKind::MethodCall(segment, receiver, args, _) => {
578                self.check_expr_method_call(expr, segment, receiver, args, expected)
579            }
580            ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr),
581            ExprKind::Type(e, t) => {
582                let ascribed_ty = self.lower_ty_saving_user_provided_ty(t);
583                let ty = self.check_expr_with_hint(e, ascribed_ty);
584                self.demand_eqtype(e.span, ascribed_ty, ty);
585                ascribed_ty
586            }
587            ExprKind::If(cond, then_expr, opt_else_expr) => {
588                self.check_expr_if(expr.hir_id, cond, then_expr, opt_else_expr, expr.span, expected)
589            }
590            ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected),
591            ExprKind::Array(args) => self.check_expr_array(args, expected, expr),
592            ExprKind::ConstBlock(ref block) => self.check_expr_const_block(block, expected),
593            ExprKind::Repeat(element, ref count) => {
594                self.check_expr_repeat(element, count, expected, expr)
595            }
596            ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr),
597            ExprKind::Struct(qpath, fields, ref base_expr) => {
598                self.check_expr_struct(expr, expected, qpath, fields, base_expr)
599            }
600            ExprKind::Field(base, field) => self.check_expr_field(expr, base, field, expected),
601            ExprKind::Index(base, idx, brackets_span) => {
602                self.check_expr_index(base, idx, expr, brackets_span)
603            }
604            ExprKind::Yield(value, _) => self.check_expr_yield(value, expr),
605            ExprKind::UnsafeBinderCast(kind, inner_expr, ty) => {
606                self.check_expr_unsafe_binder_cast(expr.span, kind, inner_expr, ty, expected)
607            }
608            ExprKind::Err(guar) => Ty::new_error(tcx, guar),
609        }
610    }
611
612    fn check_expr_unop(
613        &self,
614        unop: hir::UnOp,
615        oprnd: &'tcx hir::Expr<'tcx>,
616        expected: Expectation<'tcx>,
617        expr: &'tcx hir::Expr<'tcx>,
618    ) -> Ty<'tcx> {
619        let tcx = self.tcx;
620        let expected_inner = match unop {
621            hir::UnOp::Not | hir::UnOp::Neg => expected,
622            hir::UnOp::Deref => NoExpectation,
623        };
624        let mut oprnd_t = self.check_expr_with_expectation(oprnd, expected_inner);
625
626        if !oprnd_t.references_error() {
627            oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t);
628            match unop {
629                hir::UnOp::Deref => {
630                    if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) {
631                        oprnd_t = ty;
632                    } else {
633                        let mut err =
634                            self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t });
635                        let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None);
636                        if let Some(sp) =
637                            tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp)
638                        {
639                            err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
640                        }
641                        oprnd_t = Ty::new_error(tcx, err.emit());
642                    }
643                }
644                hir::UnOp::Not => {
645                    let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
646                    // If it's builtin, we can reuse the type, this helps inference.
647                    if !(oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool) {
648                        oprnd_t = result;
649                    }
650                }
651                hir::UnOp::Neg => {
652                    let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
653                    // If it's builtin, we can reuse the type, this helps inference.
654                    if !oprnd_t.is_numeric() {
655                        oprnd_t = result;
656                    }
657                }
658            }
659        }
660        oprnd_t
661    }
662
663    fn check_expr_addr_of(
664        &self,
665        kind: hir::BorrowKind,
666        mutbl: hir::Mutability,
667        oprnd: &'tcx hir::Expr<'tcx>,
668        expected: Expectation<'tcx>,
669        expr: &'tcx hir::Expr<'tcx>,
670    ) -> Ty<'tcx> {
671        let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
672            match self.try_structurally_resolve_type(expr.span, ty).kind() {
673                ty::Ref(_, ty, _) | ty::RawPtr(ty, _) => {
674                    if oprnd.is_syntactic_place_expr() {
675                        // Places may legitimately have unsized types.
676                        // For example, dereferences of a wide pointer and
677                        // the last field of a struct can be unsized.
678                        ExpectHasType(*ty)
679                    } else {
680                        Expectation::rvalue_hint(self, *ty)
681                    }
682                }
683                _ => NoExpectation,
684            }
685        });
686        let ty =
687            self.check_expr_with_expectation_and_needs(oprnd, hint, Needs::maybe_mut_place(mutbl));
688
689        match kind {
690            _ if ty.references_error() => Ty::new_misc_error(self.tcx),
691            hir::BorrowKind::Raw => {
692                self.check_named_place_expr(oprnd);
693                Ty::new_ptr(self.tcx, ty, mutbl)
694            }
695            hir::BorrowKind::Ref | hir::BorrowKind::Pin => {
696                // Note: at this point, we cannot say what the best lifetime
697                // is to use for resulting pointer. We want to use the
698                // shortest lifetime possible so as to avoid spurious borrowck
699                // errors. Moreover, the longest lifetime will depend on the
700                // precise details of the value whose address is being taken
701                // (and how long it is valid), which we don't know yet until
702                // type inference is complete.
703                //
704                // Therefore, here we simply generate a region variable. The
705                // region inferencer will then select a suitable value.
706                // Finally, borrowck will infer the value of the region again,
707                // this time with enough precision to check that the value
708                // whose address was taken can actually be made to live as long
709                // as it needs to live.
710                let region = self.next_region_var(RegionVariableOrigin::BorrowRegion(expr.span));
711                match kind {
712                    hir::BorrowKind::Ref => Ty::new_ref(self.tcx, region, ty, mutbl),
713                    hir::BorrowKind::Pin => Ty::new_pinned_ref(self.tcx, region, ty, mutbl),
714                    _ => unreachable!(),
715                }
716            }
717        }
718    }
719
720    /// Does this expression refer to a place that either:
721    /// * Is based on a local or static.
722    /// * Contains a dereference
723    /// Note that the adjustments for the children of `expr` should already
724    /// have been resolved.
725    fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
726        let is_named = oprnd.is_place_expr(|base| {
727            // Allow raw borrows if there are any deref adjustments.
728            //
729            // const VAL: (i32,) = (0,);
730            // const REF: &(i32,) = &(0,);
731            //
732            // &raw const VAL.0;            // ERROR
733            // &raw const REF.0;            // OK, same as &raw const (*REF).0;
734            //
735            // This is maybe too permissive, since it allows
736            // `let u = &raw const Box::new((1,)).0`, which creates an
737            // immediately dangling raw pointer.
738            self.typeck_results
739                .borrow()
740                .adjustments()
741                .get(base.hir_id)
742                .is_some_and(|x| x.iter().any(|adj| matches!(adj.kind, Adjust::Deref(_))))
743        });
744        if !is_named {
745            self.dcx().emit_err(AddressOfTemporaryTaken { span: oprnd.span });
746        }
747    }
748
749    fn check_lang_item_path(
750        &self,
751        lang_item: hir::LangItem,
752        expr: &'tcx hir::Expr<'tcx>,
753    ) -> Ty<'tcx> {
754        self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id).1
755    }
756
757    pub(crate) fn check_expr_path(
758        &self,
759        qpath: &'tcx hir::QPath<'tcx>,
760        expr: &'tcx hir::Expr<'tcx>,
761        call_expr_and_args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
762    ) -> Ty<'tcx> {
763        let tcx = self.tcx;
764        let (res, opt_ty, segs) =
765            self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span);
766        let ty = match res {
767            Res::Err => {
768                self.suggest_assoc_method_call(segs);
769                let e =
770                    self.dcx().span_delayed_bug(qpath.span(), "`Res::Err` but no error emitted");
771                Ty::new_error(tcx, e)
772            }
773            Res::Def(DefKind::Variant, _) => {
774                let e = report_unexpected_variant_res(
775                    tcx,
776                    res,
777                    Some(expr),
778                    qpath,
779                    expr.span,
780                    E0533,
781                    "value",
782                );
783                Ty::new_error(tcx, e)
784            }
785            _ => {
786                self.instantiate_value_path(
787                    segs,
788                    opt_ty,
789                    res,
790                    call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
791                    expr.span,
792                    expr.hir_id,
793                )
794                .0
795            }
796        };
797
798        if let ty::FnDef(did, _) = *ty.kind() {
799            let fn_sig = ty.fn_sig(tcx);
800
801            if tcx.is_intrinsic(did, sym::transmute) {
802                let Some(from) = fn_sig.inputs().skip_binder().get(0) else {
803                    span_bug!(
804                        tcx.def_span(did),
805                        "intrinsic fn `transmute` defined with no parameters"
806                    );
807                };
808                let to = fn_sig.output().skip_binder();
809                // We defer the transmute to the end of typeck, once all inference vars have
810                // been resolved or we errored. This is important as we can only check transmute
811                // on concrete types, but the output type may not be known yet (it would only
812                // be known if explicitly specified via turbofish).
813                self.deferred_transmute_checks.borrow_mut().push((*from, to, expr.hir_id));
814            }
815            if !tcx.features().unsized_fn_params() {
816                // We want to remove some Sized bounds from std functions,
817                // but don't want to expose the removal to stable Rust.
818                // i.e., we don't want to allow
819                //
820                // ```rust
821                // drop as fn(str);
822                // ```
823                //
824                // to work in stable even if the Sized bound on `drop` is relaxed.
825                for i in 0..fn_sig.inputs().skip_binder().len() {
826                    // We just want to check sizedness, so instead of introducing
827                    // placeholder lifetimes with probing, we just replace higher lifetimes
828                    // with fresh vars.
829                    let span = call_expr_and_args
830                        .and_then(|(_, args)| args.get(i))
831                        .map_or(expr.span, |arg| arg.span);
832                    let input = self.instantiate_binder_with_fresh_vars(
833                        span,
834                        infer::BoundRegionConversionTime::FnCall,
835                        fn_sig.input(i),
836                    );
837                    self.require_type_is_sized_deferred(
838                        input,
839                        span,
840                        ObligationCauseCode::SizedArgumentType(None),
841                    );
842                }
843            }
844            // Here we want to prevent struct constructors from returning unsized types,
845            // which can happen with fn pointer coercion on stable.
846            // Also, as we just want to check sizedness, instead of introducing
847            // placeholder lifetimes with probing, we just replace higher lifetimes
848            // with fresh vars.
849            let output = self.instantiate_binder_with_fresh_vars(
850                expr.span,
851                infer::BoundRegionConversionTime::FnCall,
852                fn_sig.output(),
853            );
854            self.require_type_is_sized_deferred(
855                output,
856                call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
857                ObligationCauseCode::SizedCallReturnType,
858            );
859        }
860
861        // We always require that the type provided as the value for
862        // a type parameter outlives the moment of instantiation.
863        let args = self.typeck_results.borrow().node_args(expr.hir_id);
864        self.add_wf_bounds(args, expr.span);
865
866        ty
867    }
868
869    fn check_expr_break(
870        &self,
871        destination: hir::Destination,
872        expr_opt: Option<&'tcx hir::Expr<'tcx>>,
873        expr: &'tcx hir::Expr<'tcx>,
874    ) -> Ty<'tcx> {
875        let tcx = self.tcx;
876        if let Ok(target_id) = destination.target_id {
877            let (e_ty, cause);
878            if let Some(e) = expr_opt {
879                // If this is a break with a value, we need to type-check
880                // the expression. Get an expected type from the loop context.
881                let opt_coerce_to = {
882                    // We should release `enclosing_breakables` before the `check_expr_with_hint`
883                    // below, so can't move this block of code to the enclosing scope and share
884                    // `ctxt` with the second `enclosing_breakables` borrow below.
885                    let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
886                    match enclosing_breakables.opt_find_breakable(target_id) {
887                        Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
888                        None => {
889                            // Avoid ICE when `break` is inside a closure (#65383).
890                            return Ty::new_error_with_message(
891                                tcx,
892                                expr.span,
893                                "break was outside loop, but no error was emitted",
894                            );
895                        }
896                    }
897                };
898
899                // If the loop context is not a `loop { }`, then break with
900                // a value is illegal, and `opt_coerce_to` will be `None`.
901                // Set expectation to error in that case and set tainted
902                // by error (#114529)
903                let coerce_to = opt_coerce_to.unwrap_or_else(|| {
904                    let guar = self.dcx().span_delayed_bug(
905                        expr.span,
906                        "illegal break with value found but no error reported",
907                    );
908                    self.set_tainted_by_errors(guar);
909                    Ty::new_error(tcx, guar)
910                });
911
912                // Recurse without `enclosing_breakables` borrowed.
913                e_ty = self.check_expr_with_hint(e, coerce_to);
914                cause = self.misc(e.span);
915            } else {
916                // Otherwise, this is a break *without* a value. That's
917                // always legal, and is equivalent to `break ()`.
918                e_ty = tcx.types.unit;
919                cause = self.misc(expr.span);
920            }
921
922            // Now that we have type-checked `expr_opt`, borrow
923            // the `enclosing_loops` field and let's coerce the
924            // type of `expr_opt` into what is expected.
925            let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
926            let Some(ctxt) = enclosing_breakables.opt_find_breakable(target_id) else {
927                // Avoid ICE when `break` is inside a closure (#65383).
928                return Ty::new_error_with_message(
929                    tcx,
930                    expr.span,
931                    "break was outside loop, but no error was emitted",
932                );
933            };
934
935            if let Some(ref mut coerce) = ctxt.coerce {
936                if let Some(e) = expr_opt {
937                    coerce.coerce(self, &cause, e, e_ty);
938                } else {
939                    assert!(e_ty.is_unit());
940                    let ty = coerce.expected_ty();
941                    coerce.coerce_forced_unit(
942                        self,
943                        &cause,
944                        |mut err| {
945                            self.suggest_missing_semicolon(&mut err, expr, e_ty, false, false);
946                            self.suggest_mismatched_types_on_tail(
947                                &mut err, expr, ty, e_ty, target_id,
948                            );
949                            let error =
950                                Some(TypeError::Sorts(ExpectedFound { expected: ty, found: e_ty }));
951                            self.annotate_loop_expected_due_to_inference(err, expr, error);
952                            if let Some(val) =
953                                self.err_ctxt().ty_kind_suggestion(self.param_env, ty)
954                            {
955                                err.span_suggestion_verbose(
956                                    expr.span.shrink_to_hi(),
957                                    "give the `break` a value of the expected type",
958                                    format!(" {val}"),
959                                    Applicability::HasPlaceholders,
960                                );
961                            }
962                        },
963                        false,
964                    );
965                }
966            } else {
967                // If `ctxt.coerce` is `None`, we can just ignore
968                // the type of the expression. This is because
969                // either this was a break *without* a value, in
970                // which case it is always a legal type (`()`), or
971                // else an error would have been flagged by the
972                // `loops` pass for using break with an expression
973                // where you are not supposed to.
974                assert!(expr_opt.is_none() || self.tainted_by_errors().is_some());
975            }
976
977            // If we encountered a `break`, then (no surprise) it may be possible to break from the
978            // loop... unless the value being returned from the loop diverges itself, e.g.
979            // `break return 5` or `break loop {}`.
980            ctxt.may_break |= !self.diverges.get().is_always();
981
982            // the type of a `break` is always `!`, since it diverges
983            tcx.types.never
984        } else {
985            // Otherwise, we failed to find the enclosing loop;
986            // this can only happen if the `break` was not
987            // inside a loop at all, which is caught by the
988            // loop-checking pass.
989            let err = Ty::new_error_with_message(
990                self.tcx,
991                expr.span,
992                "break was outside loop, but no error was emitted",
993            );
994
995            // We still need to assign a type to the inner expression to
996            // prevent the ICE in #43162.
997            if let Some(e) = expr_opt {
998                self.check_expr_with_hint(e, err);
999
1000                // ... except when we try to 'break rust;'.
1001                // ICE this expression in particular (see #43162).
1002                if let ExprKind::Path(QPath::Resolved(_, path)) = e.kind {
1003                    if let [segment] = path.segments
1004                        && segment.ident.name == sym::rust
1005                    {
1006                        fatally_break_rust(self.tcx, expr.span);
1007                    }
1008                }
1009            }
1010
1011            // There was an error; make type-check fail.
1012            err
1013        }
1014    }
1015
1016    fn check_expr_continue(
1017        &self,
1018        destination: hir::Destination,
1019        expr: &'tcx hir::Expr<'tcx>,
1020    ) -> Ty<'tcx> {
1021        if let Ok(target_id) = destination.target_id {
1022            if let hir::Node::Expr(hir::Expr { kind: ExprKind::Loop(..), .. }) =
1023                self.tcx.hir_node(target_id)
1024            {
1025                self.tcx.types.never
1026            } else {
1027                // Liveness linting assumes `continue`s all point to loops. We'll report an error
1028                // in `check_mod_loops`, but make sure we don't run liveness (#113379, #121623).
1029                let guar = self.dcx().span_delayed_bug(
1030                    expr.span,
1031                    "found `continue` not pointing to loop, but no error reported",
1032                );
1033                Ty::new_error(self.tcx, guar)
1034            }
1035        } else {
1036            // There was an error; make type-check fail.
1037            Ty::new_misc_error(self.tcx)
1038        }
1039    }
1040
1041    fn check_expr_return(
1042        &self,
1043        expr_opt: Option<&'tcx hir::Expr<'tcx>>,
1044        expr: &'tcx hir::Expr<'tcx>,
1045    ) -> Ty<'tcx> {
1046        if self.ret_coercion.is_none() {
1047            self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Return);
1048
1049            if let Some(e) = expr_opt {
1050                // We still have to type-check `e` (issue #86188), but calling
1051                // `check_return_expr` only works inside fn bodies.
1052                self.check_expr(e);
1053            }
1054        } else if let Some(e) = expr_opt {
1055            if self.ret_coercion_span.get().is_none() {
1056                self.ret_coercion_span.set(Some(e.span));
1057            }
1058            self.check_return_or_body_tail(e, true);
1059        } else {
1060            let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
1061            if self.ret_coercion_span.get().is_none() {
1062                self.ret_coercion_span.set(Some(expr.span));
1063            }
1064            let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
1065            if let Some((_, fn_decl)) = self.get_fn_decl(expr.hir_id) {
1066                coercion.coerce_forced_unit(
1067                    self,
1068                    &cause,
1069                    |db| {
1070                        let span = fn_decl.output.span();
1071                        if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1072                            db.span_label(
1073                                span,
1074                                format!("expected `{snippet}` because of this return type"),
1075                            );
1076                        }
1077                    },
1078                    true,
1079                );
1080            } else {
1081                coercion.coerce_forced_unit(self, &cause, |_| (), true);
1082            }
1083        }
1084        self.tcx.types.never
1085    }
1086
1087    fn check_expr_become(
1088        &self,
1089        call: &'tcx hir::Expr<'tcx>,
1090        expr: &'tcx hir::Expr<'tcx>,
1091    ) -> Ty<'tcx> {
1092        match &self.ret_coercion {
1093            Some(ret_coercion) => {
1094                let ret_ty = ret_coercion.borrow().expected_ty();
1095                let call_expr_ty = self.check_expr_with_hint(call, ret_ty);
1096
1097                // N.B. don't coerce here, as tail calls can't support most/all coercions
1098                // FIXME(explicit_tail_calls): add a diagnostic note that `become` doesn't allow coercions
1099                self.demand_suptype(expr.span, ret_ty, call_expr_ty);
1100            }
1101            None => {
1102                self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Become);
1103
1104                // Fallback to simply type checking `call` without hint/demanding the right types.
1105                // Best effort to highlight more errors.
1106                self.check_expr(call);
1107            }
1108        }
1109
1110        self.tcx.types.never
1111    }
1112
1113    /// Check an expression that _is being returned_.
1114    /// For example, this is called with `return_expr: $expr` when `return $expr`
1115    /// is encountered.
1116    ///
1117    /// Note that this function must only be called in function bodies.
1118    ///
1119    /// `explicit_return` is `true` if we're checking an explicit `return expr`,
1120    /// and `false` if we're checking a trailing expression.
1121    pub(super) fn check_return_or_body_tail(
1122        &self,
1123        return_expr: &'tcx hir::Expr<'tcx>,
1124        explicit_return: bool,
1125    ) {
1126        let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
1127            span_bug!(return_expr.span, "check_return_expr called outside fn body")
1128        });
1129
1130        let ret_ty = ret_coercion.borrow().expected_ty();
1131        let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
1132        let mut span = return_expr.span;
1133        let mut hir_id = return_expr.hir_id;
1134        // Use the span of the trailing expression for our cause,
1135        // not the span of the entire function
1136        if !explicit_return
1137            && let ExprKind::Block(body, _) = return_expr.kind
1138            && let Some(last_expr) = body.expr
1139        {
1140            span = last_expr.span;
1141            hir_id = last_expr.hir_id;
1142        }
1143        ret_coercion.borrow_mut().coerce(
1144            self,
1145            &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
1146            return_expr,
1147            return_expr_ty,
1148        );
1149
1150        if let Some(fn_sig) = self.body_fn_sig()
1151            && fn_sig.output().has_opaque_types()
1152        {
1153            // Point any obligations that were registered due to opaque type
1154            // inference at the return expression.
1155            self.select_obligations_where_possible(|errors| {
1156                self.point_at_return_for_opaque_ty_error(
1157                    errors,
1158                    hir_id,
1159                    span,
1160                    return_expr_ty,
1161                    return_expr.span,
1162                );
1163            });
1164        }
1165    }
1166
1167    /// Emit an error because `return` or `become` is used outside of a function body.
1168    ///
1169    /// `expr` is the `return` (`become`) "statement", `kind` is the kind of the statement
1170    /// either `Return` or `Become`.
1171    fn emit_return_outside_of_fn_body(&self, expr: &hir::Expr<'_>, kind: ReturnLikeStatementKind) {
1172        let mut err = ReturnStmtOutsideOfFnBody {
1173            span: expr.span,
1174            encl_body_span: None,
1175            encl_fn_span: None,
1176            statement_kind: kind,
1177        };
1178
1179        let encl_item_id = self.tcx.hir_get_parent_item(expr.hir_id);
1180
1181        if let hir::Node::Item(hir::Item {
1182            kind: hir::ItemKind::Fn { .. },
1183            span: encl_fn_span,
1184            ..
1185        })
1186        | hir::Node::TraitItem(hir::TraitItem {
1187            kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
1188            span: encl_fn_span,
1189            ..
1190        })
1191        | hir::Node::ImplItem(hir::ImplItem {
1192            kind: hir::ImplItemKind::Fn(..),
1193            span: encl_fn_span,
1194            ..
1195        }) = self.tcx.hir_node_by_def_id(encl_item_id.def_id)
1196        {
1197            // We are inside a function body, so reporting "return statement
1198            // outside of function body" needs an explanation.
1199
1200            let encl_body_owner_id = self.tcx.hir_enclosing_body_owner(expr.hir_id);
1201
1202            // If this didn't hold, we would not have to report an error in
1203            // the first place.
1204            assert_ne!(encl_item_id.def_id, encl_body_owner_id);
1205
1206            let encl_body = self.tcx.hir_body_owned_by(encl_body_owner_id);
1207
1208            err.encl_body_span = Some(encl_body.value.span);
1209            err.encl_fn_span = Some(*encl_fn_span);
1210        }
1211
1212        self.dcx().emit_err(err);
1213    }
1214
1215    fn point_at_return_for_opaque_ty_error(
1216        &self,
1217        errors: &mut Vec<traits::FulfillmentError<'tcx>>,
1218        hir_id: HirId,
1219        span: Span,
1220        return_expr_ty: Ty<'tcx>,
1221        return_span: Span,
1222    ) {
1223        // Don't point at the whole block if it's empty
1224        if span == return_span {
1225            return;
1226        }
1227        for err in errors {
1228            let cause = &mut err.obligation.cause;
1229            if let ObligationCauseCode::OpaqueReturnType(None) = cause.code() {
1230                let new_cause = self.cause(
1231                    cause.span,
1232                    ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, hir_id))),
1233                );
1234                *cause = new_cause;
1235            }
1236        }
1237    }
1238
1239    pub(crate) fn check_lhs_assignable(
1240        &self,
1241        lhs: &'tcx hir::Expr<'tcx>,
1242        code: ErrCode,
1243        op_span: Span,
1244        adjust_err: impl FnOnce(&mut Diag<'_>),
1245    ) {
1246        if lhs.is_syntactic_place_expr() {
1247            return;
1248        }
1249
1250        let mut err = self.dcx().struct_span_err(op_span, "invalid left-hand side of assignment");
1251        err.code(code);
1252        err.span_label(lhs.span, "cannot assign to this expression");
1253
1254        self.comes_from_while_condition(lhs.hir_id, |expr| {
1255            err.span_suggestion_verbose(
1256                expr.span.shrink_to_lo(),
1257                "you might have meant to use pattern destructuring",
1258                "let ",
1259                Applicability::MachineApplicable,
1260            );
1261        });
1262        self.check_for_missing_semi(lhs, &mut err);
1263
1264        adjust_err(&mut err);
1265
1266        err.emit();
1267    }
1268
1269    /// Check if the expression that could not be assigned to was a typoed expression that
1270    pub(crate) fn check_for_missing_semi(
1271        &self,
1272        expr: &'tcx hir::Expr<'tcx>,
1273        err: &mut Diag<'_>,
1274    ) -> bool {
1275        if let hir::ExprKind::Binary(binop, lhs, rhs) = expr.kind
1276            && let hir::BinOpKind::Mul = binop.node
1277            && self.tcx.sess.source_map().is_multiline(lhs.span.between(rhs.span))
1278            && rhs.is_syntactic_place_expr()
1279        {
1280            //      v missing semicolon here
1281            // foo()
1282            // *bar = baz;
1283            // (#80446).
1284            err.span_suggestion_verbose(
1285                lhs.span.shrink_to_hi(),
1286                "you might have meant to write a semicolon here",
1287                ";",
1288                Applicability::MachineApplicable,
1289            );
1290            return true;
1291        }
1292        false
1293    }
1294
1295    // Check if an expression `original_expr_id` comes from the condition of a while loop,
1296    /// as opposed from the body of a while loop, which we can naively check by iterating
1297    /// parents until we find a loop...
1298    pub(super) fn comes_from_while_condition(
1299        &self,
1300        original_expr_id: HirId,
1301        then: impl FnOnce(&hir::Expr<'_>),
1302    ) {
1303        let mut parent = self.tcx.parent_hir_id(original_expr_id);
1304        loop {
1305            let node = self.tcx.hir_node(parent);
1306            match node {
1307                hir::Node::Expr(hir::Expr {
1308                    kind:
1309                        hir::ExprKind::Loop(
1310                            hir::Block {
1311                                expr:
1312                                    Some(hir::Expr {
1313                                        kind:
1314                                            hir::ExprKind::Match(expr, ..) | hir::ExprKind::If(expr, ..),
1315                                        ..
1316                                    }),
1317                                ..
1318                            },
1319                            _,
1320                            hir::LoopSource::While,
1321                            _,
1322                        ),
1323                    ..
1324                }) => {
1325                    // Check if our original expression is a child of the condition of a while loop.
1326                    // If it is, then we have a situation like `while Some(0) = value.get(0) {`,
1327                    // where `while let` was more likely intended.
1328                    if self.tcx.hir_parent_id_iter(original_expr_id).any(|id| id == expr.hir_id) {
1329                        then(expr);
1330                    }
1331                    break;
1332                }
1333                hir::Node::Item(_)
1334                | hir::Node::ImplItem(_)
1335                | hir::Node::TraitItem(_)
1336                | hir::Node::Crate(_) => break,
1337                _ => {
1338                    parent = self.tcx.parent_hir_id(parent);
1339                }
1340            }
1341        }
1342    }
1343
1344    // A generic function for checking the 'then' and 'else' clauses in an 'if'
1345    // or 'if-else' expression.
1346    fn check_expr_if(
1347        &self,
1348        expr_id: HirId,
1349        cond_expr: &'tcx hir::Expr<'tcx>,
1350        then_expr: &'tcx hir::Expr<'tcx>,
1351        opt_else_expr: Option<&'tcx hir::Expr<'tcx>>,
1352        sp: Span,
1353        orig_expected: Expectation<'tcx>,
1354    ) -> Ty<'tcx> {
1355        let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {});
1356
1357        self.warn_if_unreachable(
1358            cond_expr.hir_id,
1359            then_expr.span,
1360            "block in `if` or `while` expression",
1361        );
1362
1363        let cond_diverges = self.diverges.get();
1364        self.diverges.set(Diverges::Maybe);
1365
1366        let expected = orig_expected.try_structurally_resolve_and_adjust_for_branches(self, sp);
1367        let then_ty = self.check_expr_with_expectation(then_expr, expected);
1368        let then_diverges = self.diverges.get();
1369        self.diverges.set(Diverges::Maybe);
1370
1371        // We've already taken the expected type's preferences
1372        // into account when typing the `then` branch. To figure
1373        // out the initial shot at a LUB, we thus only consider
1374        // `expected` if it represents a *hard* constraint
1375        // (`only_has_type`); otherwise, we just go with a
1376        // fresh type variable.
1377        let coerce_to_ty = expected.coercion_target_type(self, sp);
1378        let mut coerce: DynamicCoerceMany<'_> = CoerceMany::new(coerce_to_ty);
1379
1380        coerce.coerce(self, &self.misc(sp), then_expr, then_ty);
1381
1382        if let Some(else_expr) = opt_else_expr {
1383            let else_ty = self.check_expr_with_expectation(else_expr, expected);
1384            let else_diverges = self.diverges.get();
1385
1386            let tail_defines_return_position_impl_trait =
1387                self.return_position_impl_trait_from_match_expectation(orig_expected);
1388            let if_cause =
1389                self.if_cause(expr_id, else_expr, tail_defines_return_position_impl_trait);
1390
1391            coerce.coerce(self, &if_cause, else_expr, else_ty);
1392
1393            // We won't diverge unless both branches do (or the condition does).
1394            self.diverges.set(cond_diverges | then_diverges & else_diverges);
1395        } else {
1396            self.if_fallback_coercion(sp, cond_expr, then_expr, &mut coerce);
1397
1398            // If the condition is false we can't diverge.
1399            self.diverges.set(cond_diverges);
1400        }
1401
1402        let result_ty = coerce.complete(self);
1403        if let Err(guar) = cond_ty.error_reported() {
1404            Ty::new_error(self.tcx, guar)
1405        } else {
1406            result_ty
1407        }
1408    }
1409
1410    /// Type check assignment expression `expr` of form `lhs = rhs`.
1411    /// The expected type is `()` and is passed to the function for the purposes of diagnostics.
1412    fn check_expr_assign(
1413        &self,
1414        expr: &'tcx hir::Expr<'tcx>,
1415        expected: Expectation<'tcx>,
1416        lhs: &'tcx hir::Expr<'tcx>,
1417        rhs: &'tcx hir::Expr<'tcx>,
1418        span: Span,
1419    ) -> Ty<'tcx> {
1420        let expected_ty = expected.only_has_type(self);
1421        if expected_ty == Some(self.tcx.types.bool) {
1422            let guar = self.expr_assign_expected_bool_error(expr, lhs, rhs, span);
1423            return Ty::new_error(self.tcx, guar);
1424        }
1425
1426        let lhs_ty = self.check_expr_with_needs(lhs, Needs::MutPlace);
1427
1428        let suggest_deref_binop = |err: &mut Diag<'_>, rhs_ty: Ty<'tcx>| {
1429            if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
1430                // Can only assign if the type is sized, so if `DerefMut` yields a type that is
1431                // unsized, do not suggest dereferencing it.
1432                let lhs_deref_ty_is_sized = self
1433                    .infcx
1434                    .type_implements_trait(
1435                        self.tcx.require_lang_item(LangItem::Sized, span),
1436                        [lhs_deref_ty],
1437                        self.param_env,
1438                    )
1439                    .may_apply();
1440                if lhs_deref_ty_is_sized && self.may_coerce(rhs_ty, lhs_deref_ty) {
1441                    err.span_suggestion_verbose(
1442                        lhs.span.shrink_to_lo(),
1443                        "consider dereferencing here to assign to the mutably borrowed value",
1444                        "*",
1445                        Applicability::MachineApplicable,
1446                    );
1447                }
1448            }
1449        };
1450
1451        // This is (basically) inlined `check_expr_coercible_to_type`, but we want
1452        // to suggest an additional fixup here in `suggest_deref_binop`.
1453        let rhs_ty = self.check_expr_with_hint(rhs, lhs_ty);
1454        if let Err(mut diag) =
1455            self.demand_coerce_diag(rhs, rhs_ty, lhs_ty, Some(lhs), AllowTwoPhase::No)
1456        {
1457            suggest_deref_binop(&mut diag, rhs_ty);
1458            diag.emit();
1459        }
1460
1461        self.check_lhs_assignable(lhs, E0070, span, |err| {
1462            if let Some(rhs_ty) = self.typeck_results.borrow().expr_ty_opt(rhs) {
1463                suggest_deref_binop(err, rhs_ty);
1464            }
1465        });
1466
1467        self.require_type_is_sized(lhs_ty, lhs.span, ObligationCauseCode::AssignmentLhsSized);
1468
1469        if let Err(guar) = (lhs_ty, rhs_ty).error_reported() {
1470            Ty::new_error(self.tcx, guar)
1471        } else {
1472            self.tcx.types.unit
1473        }
1474    }
1475
1476    /// The expected type is `bool` but this will result in `()` so we can reasonably
1477    /// say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
1478    /// The likely cause of this is `if foo = bar { .. }`.
1479    fn expr_assign_expected_bool_error(
1480        &self,
1481        expr: &'tcx hir::Expr<'tcx>,
1482        lhs: &'tcx hir::Expr<'tcx>,
1483        rhs: &'tcx hir::Expr<'tcx>,
1484        span: Span,
1485    ) -> ErrorGuaranteed {
1486        let actual_ty = self.tcx.types.unit;
1487        let expected_ty = self.tcx.types.bool;
1488        let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap_err();
1489        let lhs_ty = self.check_expr(lhs);
1490        let rhs_ty = self.check_expr(rhs);
1491        let refs_can_coerce = |lhs: Ty<'tcx>, rhs: Ty<'tcx>| {
1492            let lhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, lhs.peel_refs());
1493            let rhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rhs.peel_refs());
1494            self.may_coerce(rhs, lhs)
1495        };
1496        let (applicability, eq) = if self.may_coerce(rhs_ty, lhs_ty) {
1497            (Applicability::MachineApplicable, true)
1498        } else if refs_can_coerce(rhs_ty, lhs_ty) {
1499            // The lhs and rhs are likely missing some references in either side. Subsequent
1500            // suggestions will show up.
1501            (Applicability::MaybeIncorrect, true)
1502        } else if let ExprKind::Binary(
1503            Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1504            _,
1505            rhs_expr,
1506        ) = lhs.kind
1507        {
1508            // if x == 1 && y == 2 { .. }
1509            //                 +
1510            let actual_lhs = self.check_expr(rhs_expr);
1511            let may_eq = self.may_coerce(rhs_ty, actual_lhs) || refs_can_coerce(rhs_ty, actual_lhs);
1512            (Applicability::MaybeIncorrect, may_eq)
1513        } else if let ExprKind::Binary(
1514            Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1515            lhs_expr,
1516            _,
1517        ) = rhs.kind
1518        {
1519            // if x == 1 && y == 2 { .. }
1520            //       +
1521            let actual_rhs = self.check_expr(lhs_expr);
1522            let may_eq = self.may_coerce(actual_rhs, lhs_ty) || refs_can_coerce(actual_rhs, lhs_ty);
1523            (Applicability::MaybeIncorrect, may_eq)
1524        } else {
1525            (Applicability::MaybeIncorrect, false)
1526        };
1527
1528        if !lhs.is_syntactic_place_expr()
1529            && lhs.is_approximately_pattern()
1530            && !matches!(lhs.kind, hir::ExprKind::Lit(_))
1531        {
1532            // Do not suggest `if let x = y` as `==` is way more likely to be the intention.
1533            if let hir::Node::Expr(hir::Expr { kind: ExprKind::If { .. }, .. }) =
1534                self.tcx.parent_hir_node(expr.hir_id)
1535            {
1536                err.span_suggestion_verbose(
1537                    expr.span.shrink_to_lo(),
1538                    "you might have meant to use pattern matching",
1539                    "let ",
1540                    applicability,
1541                );
1542            };
1543        }
1544        if eq {
1545            err.span_suggestion_verbose(
1546                span.shrink_to_hi(),
1547                "you might have meant to compare for equality",
1548                '=',
1549                applicability,
1550            );
1551        }
1552
1553        // If the assignment expression itself is ill-formed, don't
1554        // bother emitting another error
1555        err.emit_unless_delay(lhs_ty.references_error() || rhs_ty.references_error())
1556    }
1557
1558    pub(super) fn check_expr_let(
1559        &self,
1560        let_expr: &'tcx hir::LetExpr<'tcx>,
1561        hir_id: HirId,
1562    ) -> Ty<'tcx> {
1563        GatherLocalsVisitor::gather_from_let_expr(self, let_expr, hir_id);
1564
1565        // for let statements, this is done in check_stmt
1566        let init = let_expr.init;
1567        self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression");
1568
1569        // otherwise check exactly as a let statement
1570        self.check_decl((let_expr, hir_id).into());
1571
1572        // but return a bool, for this is a boolean expression
1573        if let ast::Recovered::Yes(error_guaranteed) = let_expr.recovered {
1574            self.set_tainted_by_errors(error_guaranteed);
1575            Ty::new_error(self.tcx, error_guaranteed)
1576        } else {
1577            self.tcx.types.bool
1578        }
1579    }
1580
1581    fn check_expr_loop(
1582        &self,
1583        body: &'tcx hir::Block<'tcx>,
1584        source: hir::LoopSource,
1585        expected: Expectation<'tcx>,
1586        expr: &'tcx hir::Expr<'tcx>,
1587    ) -> Ty<'tcx> {
1588        let coerce = match source {
1589            // you can only use break with a value from a normal `loop { }`
1590            hir::LoopSource::Loop => {
1591                let coerce_to = expected.coercion_target_type(self, body.span);
1592                Some(CoerceMany::new(coerce_to))
1593            }
1594
1595            hir::LoopSource::While | hir::LoopSource::ForLoop => None,
1596        };
1597
1598        let ctxt = BreakableCtxt {
1599            coerce,
1600            may_break: false, // Will get updated if/when we find a `break`.
1601        };
1602
1603        let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
1604            self.check_block_no_value(body);
1605        });
1606
1607        if ctxt.may_break {
1608            // No way to know whether it's diverging because
1609            // of a `break` or an outer `break` or `return`.
1610            self.diverges.set(Diverges::Maybe);
1611        } else {
1612            self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
1613        }
1614
1615        // If we permit break with a value, then result type is
1616        // the LUB of the breaks (possibly ! if none); else, it
1617        // is nil. This makes sense because infinite loops
1618        // (which would have type !) are only possible iff we
1619        // permit break with a value.
1620        if ctxt.coerce.is_none() && !ctxt.may_break {
1621            self.dcx().span_bug(body.span, "no coercion, but loop may not break");
1622        }
1623        ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.types.unit)
1624    }
1625
1626    /// Checks a method call.
1627    fn check_expr_method_call(
1628        &self,
1629        expr: &'tcx hir::Expr<'tcx>,
1630        segment: &'tcx hir::PathSegment<'tcx>,
1631        rcvr: &'tcx hir::Expr<'tcx>,
1632        args: &'tcx [hir::Expr<'tcx>],
1633        expected: Expectation<'tcx>,
1634    ) -> Ty<'tcx> {
1635        let rcvr_t = self.check_expr(rcvr);
1636        let rcvr_t = self.try_structurally_resolve_type(rcvr.span, rcvr_t);
1637
1638        match self.lookup_method(rcvr_t, segment, segment.ident.span, expr, rcvr, args) {
1639            Ok(method) => {
1640                self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
1641
1642                self.check_argument_types(
1643                    segment.ident.span,
1644                    expr,
1645                    &method.sig.inputs()[1..],
1646                    method.sig.output(),
1647                    expected,
1648                    args,
1649                    method.sig.c_variadic,
1650                    TupleArgumentsFlag::DontTupleArguments,
1651                    Some(method.def_id),
1652                );
1653
1654                self.check_call_abi(method.sig.abi, expr.span);
1655
1656                method.sig.output()
1657            }
1658            Err(error) => {
1659                let guar = self.report_method_error(expr.hir_id, rcvr_t, error, expected, false);
1660
1661                let err_inputs = self.err_args(args.len(), guar);
1662                let err_output = Ty::new_error(self.tcx, guar);
1663
1664                self.check_argument_types(
1665                    segment.ident.span,
1666                    expr,
1667                    &err_inputs,
1668                    err_output,
1669                    NoExpectation,
1670                    args,
1671                    false,
1672                    TupleArgumentsFlag::DontTupleArguments,
1673                    None,
1674                );
1675
1676                err_output
1677            }
1678        }
1679    }
1680
1681    /// Checks use `x.use`.
1682    fn check_expr_use(
1683        &self,
1684        used_expr: &'tcx hir::Expr<'tcx>,
1685        expected: Expectation<'tcx>,
1686    ) -> Ty<'tcx> {
1687        self.check_expr_with_expectation(used_expr, expected)
1688    }
1689
1690    fn check_expr_cast(
1691        &self,
1692        e: &'tcx hir::Expr<'tcx>,
1693        t: &'tcx hir::Ty<'tcx>,
1694        expr: &'tcx hir::Expr<'tcx>,
1695    ) -> Ty<'tcx> {
1696        // Find the type of `e`. Supply hints based on the type we are casting to,
1697        // if appropriate.
1698        let t_cast = self.lower_ty_saving_user_provided_ty(t);
1699        let t_cast = self.resolve_vars_if_possible(t_cast);
1700        let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
1701        let t_expr = self.resolve_vars_if_possible(t_expr);
1702
1703        // Eagerly check for some obvious errors.
1704        if let Err(guar) = (t_expr, t_cast).error_reported() {
1705            Ty::new_error(self.tcx, guar)
1706        } else {
1707            // Defer other checks until we're done type checking.
1708            let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
1709            match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
1710                Ok(cast_check) => {
1711                    debug!(
1712                        "check_expr_cast: deferring cast from {:?} to {:?}: {:?}",
1713                        t_cast, t_expr, cast_check,
1714                    );
1715                    deferred_cast_checks.push(cast_check);
1716                    t_cast
1717                }
1718                Err(guar) => Ty::new_error(self.tcx, guar),
1719            }
1720        }
1721    }
1722
1723    fn check_expr_unsafe_binder_cast(
1724        &self,
1725        span: Span,
1726        kind: ast::UnsafeBinderCastKind,
1727        inner_expr: &'tcx hir::Expr<'tcx>,
1728        hir_ty: Option<&'tcx hir::Ty<'tcx>>,
1729        expected: Expectation<'tcx>,
1730    ) -> Ty<'tcx> {
1731        match kind {
1732            ast::UnsafeBinderCastKind::Wrap => {
1733                let ascribed_ty =
1734                    hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1735                let expected_ty = expected.only_has_type(self);
1736                let binder_ty = match (ascribed_ty, expected_ty) {
1737                    (Some(ascribed_ty), Some(expected_ty)) => {
1738                        self.demand_eqtype(inner_expr.span, expected_ty, ascribed_ty);
1739                        expected_ty
1740                    }
1741                    (Some(ty), None) | (None, Some(ty)) => ty,
1742                    // This will always cause a structural resolve error, but we do it
1743                    // so we don't need to manually report an E0282 both on this codepath
1744                    // and in the others; it all happens in `structurally_resolve_type`.
1745                    (None, None) => self.next_ty_var(inner_expr.span),
1746                };
1747
1748                let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1749                let hint_ty = match *binder_ty.kind() {
1750                    ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1751                        inner_expr.span,
1752                        infer::BoundRegionConversionTime::HigherRankedType,
1753                        binder.into(),
1754                    ),
1755                    ty::Error(e) => Ty::new_error(self.tcx, e),
1756                    _ => {
1757                        let guar = self
1758                            .dcx()
1759                            .struct_span_err(
1760                                hir_ty.map_or(span, |hir_ty| hir_ty.span),
1761                                format!(
1762                                    "`wrap_binder!()` can only wrap into unsafe binder, not {}",
1763                                    binder_ty.sort_string(self.tcx)
1764                                ),
1765                            )
1766                            .with_note("unsafe binders are the only valid output of wrap")
1767                            .emit();
1768                        Ty::new_error(self.tcx, guar)
1769                    }
1770                };
1771
1772                self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1773
1774                binder_ty
1775            }
1776            ast::UnsafeBinderCastKind::Unwrap => {
1777                let ascribed_ty =
1778                    hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1779                let hint_ty = ascribed_ty.unwrap_or_else(|| self.next_ty_var(inner_expr.span));
1780                // FIXME(unsafe_binders): coerce here if needed?
1781                let binder_ty = self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1782
1783                // Unwrap the binder. This will be ambiguous if it's an infer var, and will error
1784                // if it's not an unsafe binder.
1785                let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1786                match *binder_ty.kind() {
1787                    ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1788                        inner_expr.span,
1789                        infer::BoundRegionConversionTime::HigherRankedType,
1790                        binder.into(),
1791                    ),
1792                    ty::Error(e) => Ty::new_error(self.tcx, e),
1793                    _ => {
1794                        let guar = self
1795                            .dcx()
1796                            .struct_span_err(
1797                                hir_ty.map_or(inner_expr.span, |hir_ty| hir_ty.span),
1798                                format!(
1799                                    "expected unsafe binder, found {} as input of \
1800                                    `unwrap_binder!()`",
1801                                    binder_ty.sort_string(self.tcx)
1802                                ),
1803                            )
1804                            .with_note("only an unsafe binder type can be unwrapped")
1805                            .emit();
1806                        Ty::new_error(self.tcx, guar)
1807                    }
1808                }
1809            }
1810        }
1811    }
1812
1813    fn check_expr_array(
1814        &self,
1815        args: &'tcx [hir::Expr<'tcx>],
1816        expected: Expectation<'tcx>,
1817        expr: &'tcx hir::Expr<'tcx>,
1818    ) -> Ty<'tcx> {
1819        let element_ty = if !args.is_empty() {
1820            let coerce_to = expected
1821                .to_option(self)
1822                .and_then(|uty| self.try_structurally_resolve_type(expr.span, uty).builtin_index())
1823                .unwrap_or_else(|| self.next_ty_var(expr.span));
1824            let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
1825            assert_eq!(self.diverges.get(), Diverges::Maybe);
1826            for e in args {
1827                let e_ty = self.check_expr_with_hint(e, coerce_to);
1828                let cause = self.misc(e.span);
1829                coerce.coerce(self, &cause, e, e_ty);
1830            }
1831            coerce.complete(self)
1832        } else {
1833            self.next_ty_var(expr.span)
1834        };
1835        let array_len = args.len() as u64;
1836        self.suggest_array_len(expr, array_len);
1837        Ty::new_array(self.tcx, element_ty, array_len)
1838    }
1839
1840    fn suggest_array_len(&self, expr: &'tcx hir::Expr<'tcx>, array_len: u64) {
1841        let parent_node = self.tcx.hir_parent_iter(expr.hir_id).find(|(_, node)| {
1842            !matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::AddrOf(..), .. }))
1843        });
1844        let Some((_, hir::Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }))) = parent_node else {
1845            return;
1846        };
1847        if let hir::TyKind::Array(_, ct) = ty.peel_refs().kind {
1848            let span = ct.span();
1849            self.dcx().try_steal_modify_and_emit_err(
1850                span,
1851                StashKey::UnderscoreForArrayLengths,
1852                |err| {
1853                    err.span_suggestion(
1854                        span,
1855                        "consider specifying the array length",
1856                        array_len,
1857                        Applicability::MaybeIncorrect,
1858                    );
1859                },
1860            );
1861        }
1862    }
1863
1864    pub(super) fn check_expr_const_block(
1865        &self,
1866        block: &'tcx hir::ConstBlock,
1867        expected: Expectation<'tcx>,
1868    ) -> Ty<'tcx> {
1869        let body = self.tcx.hir_body(block.body);
1870
1871        // Create a new function context.
1872        let def_id = block.def_id;
1873        let fcx = FnCtxt::new(self, self.param_env, def_id);
1874
1875        let ty = fcx.check_expr_with_expectation(body.value, expected);
1876        fcx.require_type_is_sized(ty, body.value.span, ObligationCauseCode::SizedConstOrStatic);
1877        fcx.write_ty(block.hir_id, ty);
1878        ty
1879    }
1880
1881    fn check_expr_repeat(
1882        &self,
1883        element: &'tcx hir::Expr<'tcx>,
1884        count: &'tcx hir::ConstArg<'tcx>,
1885        expected: Expectation<'tcx>,
1886        expr: &'tcx hir::Expr<'tcx>,
1887    ) -> Ty<'tcx> {
1888        let tcx = self.tcx;
1889        let count_span = count.span();
1890        let count = self.try_structurally_resolve_const(
1891            count_span,
1892            self.normalize(count_span, self.lower_const_arg(count, FeedConstTy::No)),
1893        );
1894
1895        if let Some(count) = count.try_to_target_usize(tcx) {
1896            self.suggest_array_len(expr, count);
1897        }
1898
1899        let uty = match expected {
1900            ExpectHasType(uty) => uty.builtin_index(),
1901            _ => None,
1902        };
1903
1904        let (element_ty, t) = match uty {
1905            Some(uty) => {
1906                self.check_expr_coercible_to_type(element, uty, None);
1907                (uty, uty)
1908            }
1909            None => {
1910                let ty = self.next_ty_var(element.span);
1911                let element_ty = self.check_expr_has_type_or_error(element, ty, |_| {});
1912                (element_ty, ty)
1913            }
1914        };
1915
1916        if let Err(guar) = element_ty.error_reported() {
1917            return Ty::new_error(tcx, guar);
1918        }
1919
1920        // We defer checking whether the element type is `Copy` as it is possible to have
1921        // an inference variable as a repeat count and it seems unlikely that `Copy` would
1922        // have inference side effects required for type checking to succeed.
1923        self.deferred_repeat_expr_checks.borrow_mut().push((element, element_ty, count));
1924
1925        let ty = Ty::new_array_with_const_len(tcx, t, count);
1926        self.register_wf_obligation(ty.into(), expr.span, ObligationCauseCode::WellFormed(None));
1927        ty
1928    }
1929
1930    fn check_expr_tuple(
1931        &self,
1932        elts: &'tcx [hir::Expr<'tcx>],
1933        expected: Expectation<'tcx>,
1934        expr: &'tcx hir::Expr<'tcx>,
1935    ) -> Ty<'tcx> {
1936        let flds = expected.only_has_type(self).and_then(|ty| {
1937            let ty = self.try_structurally_resolve_type(expr.span, ty);
1938            match ty.kind() {
1939                ty::Tuple(flds) => Some(&flds[..]),
1940                _ => None,
1941            }
1942        });
1943
1944        let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds {
1945            Some(fs) if i < fs.len() => {
1946                let ety = fs[i];
1947                self.check_expr_coercible_to_type(e, ety, None);
1948                ety
1949            }
1950            _ => self.check_expr_with_expectation(e, NoExpectation),
1951        });
1952        let tuple = Ty::new_tup_from_iter(self.tcx, elt_ts_iter);
1953        if let Err(guar) = tuple.error_reported() {
1954            Ty::new_error(self.tcx, guar)
1955        } else {
1956            self.require_type_is_sized(
1957                tuple,
1958                expr.span,
1959                ObligationCauseCode::TupleInitializerSized,
1960            );
1961            tuple
1962        }
1963    }
1964
1965    fn check_expr_struct(
1966        &self,
1967        expr: &hir::Expr<'tcx>,
1968        expected: Expectation<'tcx>,
1969        qpath: &'tcx QPath<'tcx>,
1970        fields: &'tcx [hir::ExprField<'tcx>],
1971        base_expr: &'tcx hir::StructTailExpr<'tcx>,
1972    ) -> Ty<'tcx> {
1973        // Find the relevant variant
1974        let (variant, adt_ty) = match self.check_struct_path(qpath, expr.hir_id) {
1975            Ok(data) => data,
1976            Err(guar) => {
1977                self.check_struct_fields_on_error(fields, base_expr);
1978                return Ty::new_error(self.tcx, guar);
1979            }
1980        };
1981
1982        // Prohibit struct expressions when non-exhaustive flag is set.
1983        let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1984        if variant.field_list_has_applicable_non_exhaustive() {
1985            self.dcx()
1986                .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() });
1987        }
1988
1989        self.check_expr_struct_fields(
1990            adt_ty,
1991            expected,
1992            expr,
1993            qpath.span(),
1994            variant,
1995            fields,
1996            base_expr,
1997        );
1998
1999        self.require_type_is_sized(adt_ty, expr.span, ObligationCauseCode::StructInitializerSized);
2000        adt_ty
2001    }
2002
2003    fn check_expr_struct_fields(
2004        &self,
2005        adt_ty: Ty<'tcx>,
2006        expected: Expectation<'tcx>,
2007        expr: &hir::Expr<'_>,
2008        path_span: Span,
2009        variant: &'tcx ty::VariantDef,
2010        hir_fields: &'tcx [hir::ExprField<'tcx>],
2011        base_expr: &'tcx hir::StructTailExpr<'tcx>,
2012    ) {
2013        let tcx = self.tcx;
2014
2015        let adt_ty = self.try_structurally_resolve_type(path_span, adt_ty);
2016        let adt_ty_hint = expected.only_has_type(self).and_then(|expected| {
2017            self.fudge_inference_if_ok(|| {
2018                let ocx = ObligationCtxt::new(self);
2019                ocx.sup(&self.misc(path_span), self.param_env, expected, adt_ty)?;
2020                if !ocx.select_where_possible().is_empty() {
2021                    return Err(TypeError::Mismatch);
2022                }
2023                Ok(self.resolve_vars_if_possible(adt_ty))
2024            })
2025            .ok()
2026        });
2027        if let Some(adt_ty_hint) = adt_ty_hint {
2028            // re-link the variables that the fudging above can create.
2029            self.demand_eqtype(path_span, adt_ty_hint, adt_ty);
2030        }
2031
2032        let ty::Adt(adt, args) = adt_ty.kind() else {
2033            span_bug!(path_span, "non-ADT passed to check_expr_struct_fields");
2034        };
2035        let adt_kind = adt.adt_kind();
2036
2037        let mut remaining_fields = variant
2038            .fields
2039            .iter_enumerated()
2040            .map(|(i, field)| (field.ident(tcx).normalize_to_macros_2_0(), (i, field)))
2041            .collect::<UnordMap<_, _>>();
2042
2043        let mut seen_fields = FxHashMap::default();
2044
2045        let mut error_happened = false;
2046
2047        if variant.fields.len() != remaining_fields.len() {
2048            // Some field is defined more than once. Make sure we don't try to
2049            // instantiate this struct in static/const context.
2050            let guar =
2051                self.dcx().span_delayed_bug(expr.span, "struct fields have non-unique names");
2052            self.set_tainted_by_errors(guar);
2053            error_happened = true;
2054        }
2055
2056        // Type-check each field.
2057        for (idx, field) in hir_fields.iter().enumerate() {
2058            let ident = tcx.adjust_ident(field.ident, variant.def_id);
2059            let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
2060                seen_fields.insert(ident, field.span);
2061                self.write_field_index(field.hir_id, i);
2062
2063                // We don't look at stability attributes on
2064                // struct-like enums (yet...), but it's definitely not
2065                // a bug to have constructed one.
2066                if adt_kind != AdtKind::Enum {
2067                    tcx.check_stability(v_field.did, Some(field.hir_id), field.span, None);
2068                }
2069
2070                self.field_ty(field.span, v_field, args)
2071            } else {
2072                error_happened = true;
2073                let guar = if let Some(prev_span) = seen_fields.get(&ident) {
2074                    self.dcx().emit_err(FieldMultiplySpecifiedInInitializer {
2075                        span: field.ident.span,
2076                        prev_span: *prev_span,
2077                        ident,
2078                    })
2079                } else {
2080                    self.report_unknown_field(
2081                        adt_ty,
2082                        variant,
2083                        expr,
2084                        field,
2085                        hir_fields,
2086                        adt.variant_descr(),
2087                    )
2088                };
2089
2090                Ty::new_error(tcx, guar)
2091            };
2092
2093            // Check that the expected field type is WF. Otherwise, we emit no use-site error
2094            // in the case of coercions for non-WF fields, which leads to incorrect error
2095            // tainting. See issue #126272.
2096            self.register_wf_obligation(
2097                field_type.into(),
2098                field.expr.span,
2099                ObligationCauseCode::WellFormed(None),
2100            );
2101
2102            // Make sure to give a type to the field even if there's
2103            // an error, so we can continue type-checking.
2104            let ty = self.check_expr_with_hint(field.expr, field_type);
2105            let diag = self.demand_coerce_diag(field.expr, ty, field_type, None, AllowTwoPhase::No);
2106
2107            if let Err(diag) = diag {
2108                if idx == hir_fields.len() - 1 {
2109                    if remaining_fields.is_empty() {
2110                        self.suggest_fru_from_range_and_emit(field, variant, args, diag);
2111                    } else {
2112                        diag.stash(field.span, StashKey::MaybeFruTypo);
2113                    }
2114                } else {
2115                    diag.emit();
2116                }
2117            }
2118        }
2119
2120        // Make sure the programmer specified correct number of fields.
2121        if adt_kind == AdtKind::Union && hir_fields.len() != 1 {
2122            struct_span_code_err!(
2123                self.dcx(),
2124                path_span,
2125                E0784,
2126                "union expressions should have exactly one field",
2127            )
2128            .emit();
2129        }
2130
2131        // If check_expr_struct_fields hit an error, do not attempt to populate
2132        // the fields with the base_expr. This could cause us to hit errors later
2133        // when certain fields are assumed to exist that in fact do not.
2134        if error_happened {
2135            if let hir::StructTailExpr::Base(base_expr) = base_expr {
2136                self.check_expr(base_expr);
2137            }
2138            return;
2139        }
2140
2141        if let hir::StructTailExpr::DefaultFields(span) = *base_expr {
2142            let mut missing_mandatory_fields = Vec::new();
2143            let mut missing_optional_fields = Vec::new();
2144            for f in &variant.fields {
2145                let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2146                if let Some(_) = remaining_fields.remove(&ident) {
2147                    if f.value.is_none() {
2148                        missing_mandatory_fields.push(ident);
2149                    } else {
2150                        missing_optional_fields.push(ident);
2151                    }
2152                }
2153            }
2154            if !self.tcx.features().default_field_values() {
2155                let sugg = self.tcx.crate_level_attribute_injection_span();
2156                self.dcx().emit_err(BaseExpressionDoubleDot {
2157                    span: span.shrink_to_hi(),
2158                    // We only mention enabling the feature if this is a nightly rustc *and* the
2159                    // expression would make sense with the feature enabled.
2160                    default_field_values_suggestion: if self.tcx.sess.is_nightly_build()
2161                        && missing_mandatory_fields.is_empty()
2162                        && !missing_optional_fields.is_empty()
2163                    {
2164                        Some(sugg)
2165                    } else {
2166                        None
2167                    },
2168                    add_expr: if !missing_mandatory_fields.is_empty()
2169                        || !missing_optional_fields.is_empty()
2170                    {
2171                        Some(BaseExpressionDoubleDotAddExpr { span: span.shrink_to_hi() })
2172                    } else {
2173                        None
2174                    },
2175                    remove_dots: if missing_mandatory_fields.is_empty()
2176                        && missing_optional_fields.is_empty()
2177                    {
2178                        Some(BaseExpressionDoubleDotRemove { span })
2179                    } else {
2180                        None
2181                    },
2182                });
2183                return;
2184            }
2185            if variant.fields.is_empty() {
2186                let mut err = self.dcx().struct_span_err(
2187                    span,
2188                    format!(
2189                        "`{adt_ty}` has no fields, `..` needs at least one default field in the \
2190                         struct definition",
2191                    ),
2192                );
2193                err.span_label(path_span, "this type has no fields");
2194                err.emit();
2195            }
2196            if !missing_mandatory_fields.is_empty() {
2197                let s = pluralize!(missing_mandatory_fields.len());
2198                let fields = listify(&missing_mandatory_fields, |f| format!("`{f}`")).unwrap();
2199                self.dcx()
2200                    .struct_span_err(
2201                        span.shrink_to_lo(),
2202                        format!("missing field{s} {fields} in initializer"),
2203                    )
2204                    .with_span_label(
2205                        span.shrink_to_lo(),
2206                        "fields that do not have a defaulted value must be provided explicitly",
2207                    )
2208                    .emit();
2209                return;
2210            }
2211            let fru_tys = match adt_ty.kind() {
2212                ty::Adt(adt, args) if adt.is_struct() => variant
2213                    .fields
2214                    .iter()
2215                    .map(|f| self.normalize(span, f.ty(self.tcx, args)))
2216                    .collect(),
2217                ty::Adt(adt, args) if adt.is_enum() => variant
2218                    .fields
2219                    .iter()
2220                    .map(|f| self.normalize(span, f.ty(self.tcx, args)))
2221                    .collect(),
2222                _ => {
2223                    self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct { span });
2224                    return;
2225                }
2226            };
2227            self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2228        } else if let hir::StructTailExpr::Base(base_expr) = base_expr {
2229            // FIXME: We are currently creating two branches here in order to maintain
2230            // consistency. But they should be merged as much as possible.
2231            let fru_tys = if self.tcx.features().type_changing_struct_update() {
2232                if adt.is_struct() {
2233                    // Make some fresh generic parameters for our ADT type.
2234                    let fresh_args = self.fresh_args_for_item(base_expr.span, adt.did());
2235                    // We do subtyping on the FRU fields first, so we can
2236                    // learn exactly what types we expect the base expr
2237                    // needs constrained to be compatible with the struct
2238                    // type we expect from the expectation value.
2239                    let fru_tys = variant
2240                        .fields
2241                        .iter()
2242                        .map(|f| {
2243                            let fru_ty = self
2244                                .normalize(expr.span, self.field_ty(base_expr.span, f, fresh_args));
2245                            let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2246                            if let Some(_) = remaining_fields.remove(&ident) {
2247                                let target_ty = self.field_ty(base_expr.span, f, args);
2248                                let cause = self.misc(base_expr.span);
2249                                match self.at(&cause, self.param_env).sup(
2250                                    // We're already using inference variables for any params, and don't allow converting
2251                                    // between different structs, so there is no way this ever actually defines an opaque type.
2252                                    // Thus choosing `Yes` is fine.
2253                                    DefineOpaqueTypes::Yes,
2254                                    target_ty,
2255                                    fru_ty,
2256                                ) {
2257                                    Ok(InferOk { obligations, value: () }) => {
2258                                        self.register_predicates(obligations)
2259                                    }
2260                                    Err(_) => {
2261                                        span_bug!(
2262                                            cause.span,
2263                                            "subtyping remaining fields of type changing FRU failed: {target_ty} != {fru_ty}: {}::{}",
2264                                            variant.name,
2265                                            ident.name,
2266                                        );
2267                                    }
2268                                }
2269                            }
2270                            self.resolve_vars_if_possible(fru_ty)
2271                        })
2272                        .collect();
2273                    // The use of fresh args that we have subtyped against
2274                    // our base ADT type's fields allows us to guide inference
2275                    // along so that, e.g.
2276                    // ```
2277                    // MyStruct<'a, F1, F2, const C: usize> {
2278                    //     f: F1,
2279                    //     // Other fields that reference `'a`, `F2`, and `C`
2280                    // }
2281                    //
2282                    // let x = MyStruct {
2283                    //    f: 1usize,
2284                    //    ..other_struct
2285                    // };
2286                    // ```
2287                    // will have the `other_struct` expression constrained to
2288                    // `MyStruct<'a, _, F2, C>`, as opposed to just `_`...
2289                    // This is important to allow coercions to happen in
2290                    // `other_struct` itself. See `coerce-in-base-expr.rs`.
2291                    let fresh_base_ty = Ty::new_adt(self.tcx, *adt, fresh_args);
2292                    self.check_expr_has_type_or_error(
2293                        base_expr,
2294                        self.resolve_vars_if_possible(fresh_base_ty),
2295                        |_| {},
2296                    );
2297                    fru_tys
2298                } else {
2299                    // Check the base_expr, regardless of a bad expected adt_ty, so we can get
2300                    // type errors on that expression, too.
2301                    self.check_expr(base_expr);
2302                    self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
2303                    return;
2304                }
2305            } else {
2306                self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {
2307                    let base_ty = self.typeck_results.borrow().expr_ty(*base_expr);
2308                    let same_adt = matches!((adt_ty.kind(), base_ty.kind()),
2309                        (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt);
2310                    if self.tcx.sess.is_nightly_build() && same_adt {
2311                        feature_err(
2312                            &self.tcx.sess,
2313                            sym::type_changing_struct_update,
2314                            base_expr.span,
2315                            "type changing struct updating is experimental",
2316                        )
2317                        .emit();
2318                    }
2319                });
2320                match adt_ty.kind() {
2321                    ty::Adt(adt, args) if adt.is_struct() => variant
2322                        .fields
2323                        .iter()
2324                        .map(|f| self.normalize(expr.span, f.ty(self.tcx, args)))
2325                        .collect(),
2326                    _ => {
2327                        self.dcx()
2328                            .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
2329                        return;
2330                    }
2331                }
2332            };
2333            self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2334        } else if adt_kind != AdtKind::Union && !remaining_fields.is_empty() {
2335            debug!(?remaining_fields);
2336            let private_fields: Vec<&ty::FieldDef> = variant
2337                .fields
2338                .iter()
2339                .filter(|field| !field.vis.is_accessible_from(tcx.parent_module(expr.hir_id), tcx))
2340                .collect();
2341
2342            if !private_fields.is_empty() {
2343                self.report_private_fields(
2344                    adt_ty,
2345                    path_span,
2346                    expr.span,
2347                    private_fields,
2348                    hir_fields,
2349                );
2350            } else {
2351                self.report_missing_fields(
2352                    adt_ty,
2353                    path_span,
2354                    expr.span,
2355                    remaining_fields,
2356                    variant,
2357                    hir_fields,
2358                    args,
2359                );
2360            }
2361        }
2362    }
2363
2364    fn check_struct_fields_on_error(
2365        &self,
2366        fields: &'tcx [hir::ExprField<'tcx>],
2367        base_expr: &'tcx hir::StructTailExpr<'tcx>,
2368    ) {
2369        for field in fields {
2370            self.check_expr(field.expr);
2371        }
2372        if let hir::StructTailExpr::Base(base) = *base_expr {
2373            self.check_expr(base);
2374        }
2375    }
2376
2377    /// Report an error for a struct field expression when there are fields which aren't provided.
2378    ///
2379    /// ```text
2380    /// error: missing field `you_can_use_this_field` in initializer of `foo::Foo`
2381    ///  --> src/main.rs:8:5
2382    ///   |
2383    /// 8 |     foo::Foo {};
2384    ///   |     ^^^^^^^^ missing `you_can_use_this_field`
2385    ///
2386    /// error: aborting due to 1 previous error
2387    /// ```
2388    fn report_missing_fields(
2389        &self,
2390        adt_ty: Ty<'tcx>,
2391        span: Span,
2392        full_span: Span,
2393        remaining_fields: UnordMap<Ident, (FieldIdx, &ty::FieldDef)>,
2394        variant: &'tcx ty::VariantDef,
2395        hir_fields: &'tcx [hir::ExprField<'tcx>],
2396        args: GenericArgsRef<'tcx>,
2397    ) {
2398        let len = remaining_fields.len();
2399
2400        let displayable_field_names: Vec<&str> =
2401            remaining_fields.items().map(|(ident, _)| ident.as_str()).into_sorted_stable_ord();
2402
2403        let mut truncated_fields_error = String::new();
2404        let remaining_fields_names = match &displayable_field_names[..] {
2405            [field1] => format!("`{field1}`"),
2406            [field1, field2] => format!("`{field1}` and `{field2}`"),
2407            [field1, field2, field3] => format!("`{field1}`, `{field2}` and `{field3}`"),
2408            _ => {
2409                truncated_fields_error =
2410                    format!(" and {} other field{}", len - 3, pluralize!(len - 3));
2411                displayable_field_names
2412                    .iter()
2413                    .take(3)
2414                    .map(|n| format!("`{n}`"))
2415                    .collect::<Vec<_>>()
2416                    .join(", ")
2417            }
2418        };
2419
2420        let mut err = struct_span_code_err!(
2421            self.dcx(),
2422            span,
2423            E0063,
2424            "missing field{} {}{} in initializer of `{}`",
2425            pluralize!(len),
2426            remaining_fields_names,
2427            truncated_fields_error,
2428            adt_ty
2429        );
2430        err.span_label(span, format!("missing {remaining_fields_names}{truncated_fields_error}"));
2431
2432        if remaining_fields.items().all(|(_, (_, field))| field.value.is_some())
2433            && self.tcx.sess.is_nightly_build()
2434        {
2435            let msg = format!(
2436                "all remaining fields have default values, {you_can} use those values with `..`",
2437                you_can = if self.tcx.features().default_field_values() {
2438                    "you can"
2439                } else {
2440                    "if you added `#![feature(default_field_values)]` to your crate you could"
2441                },
2442            );
2443            if let Some(hir_field) = hir_fields.last() {
2444                err.span_suggestion_verbose(
2445                    hir_field.span.shrink_to_hi(),
2446                    msg,
2447                    ", ..".to_string(),
2448                    Applicability::MachineApplicable,
2449                );
2450            } else if hir_fields.is_empty() {
2451                err.span_suggestion_verbose(
2452                    span.shrink_to_hi().with_hi(full_span.hi()),
2453                    msg,
2454                    " { .. }".to_string(),
2455                    Applicability::MachineApplicable,
2456                );
2457            }
2458        }
2459
2460        if let Some(hir_field) = hir_fields.last() {
2461            self.suggest_fru_from_range_and_emit(hir_field, variant, args, err);
2462        } else {
2463            err.emit();
2464        }
2465    }
2466
2467    /// If the last field is a range literal, but it isn't supposed to be, then they probably
2468    /// meant to use functional update syntax.
2469    fn suggest_fru_from_range_and_emit(
2470        &self,
2471        last_expr_field: &hir::ExprField<'tcx>,
2472        variant: &ty::VariantDef,
2473        args: GenericArgsRef<'tcx>,
2474        mut err: Diag<'_>,
2475    ) {
2476        // I don't use 'is_range_literal' because only double-sided, half-open ranges count.
2477        if let ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [range_start, range_end], _) =
2478            last_expr_field.expr.kind
2479            && let variant_field =
2480                variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident)
2481            && let range_def_id = self.tcx.lang_items().range_struct()
2482            && variant_field
2483                .and_then(|field| field.ty(self.tcx, args).ty_adt_def())
2484                .map(|adt| adt.did())
2485                != range_def_id
2486        {
2487            // Use a (somewhat arbitrary) filtering heuristic to avoid printing
2488            // expressions that are either too long, or have control character
2489            // such as newlines in them.
2490            let expr = self
2491                .tcx
2492                .sess
2493                .source_map()
2494                .span_to_snippet(range_end.expr.span)
2495                .ok()
2496                .filter(|s| s.len() < 25 && !s.contains(|c: char| c.is_control()));
2497
2498            let fru_span = self
2499                .tcx
2500                .sess
2501                .source_map()
2502                .span_extend_while_whitespace(range_start.span)
2503                .shrink_to_hi()
2504                .to(range_end.span);
2505
2506            err.subdiagnostic(TypeMismatchFruTypo { expr_span: range_start.span, fru_span, expr });
2507
2508            // Suppress any range expr type mismatches
2509            self.dcx().try_steal_replace_and_emit_err(
2510                last_expr_field.span,
2511                StashKey::MaybeFruTypo,
2512                err,
2513            );
2514        } else {
2515            err.emit();
2516        }
2517    }
2518
2519    /// Report an error for a struct field expression when there are invisible fields.
2520    ///
2521    /// ```text
2522    /// error: cannot construct `Foo` with struct literal syntax due to private fields
2523    ///  --> src/main.rs:8:5
2524    ///   |
2525    /// 8 |     foo::Foo {};
2526    ///   |     ^^^^^^^^
2527    ///
2528    /// error: aborting due to 1 previous error
2529    /// ```
2530    fn report_private_fields(
2531        &self,
2532        adt_ty: Ty<'tcx>,
2533        span: Span,
2534        expr_span: Span,
2535        private_fields: Vec<&ty::FieldDef>,
2536        used_fields: &'tcx [hir::ExprField<'tcx>],
2537    ) {
2538        let mut err =
2539            self.dcx().struct_span_err(
2540                span,
2541                format!(
2542                    "cannot construct `{adt_ty}` with struct literal syntax due to private fields",
2543                ),
2544            );
2545        let (used_private_fields, remaining_private_fields): (
2546            Vec<(Symbol, Span, bool)>,
2547            Vec<(Symbol, Span, bool)>,
2548        ) = private_fields
2549            .iter()
2550            .map(|field| {
2551                match used_fields.iter().find(|used_field| field.name == used_field.ident.name) {
2552                    Some(used_field) => (field.name, used_field.span, true),
2553                    None => (field.name, self.tcx.def_span(field.did), false),
2554                }
2555            })
2556            .partition(|field| field.2);
2557        err.span_labels(used_private_fields.iter().map(|(_, span, _)| *span), "private field");
2558        if !remaining_private_fields.is_empty() {
2559            let names = if remaining_private_fields.len() > 6 {
2560                String::new()
2561            } else {
2562                format!(
2563                    "{} ",
2564                    listify(&remaining_private_fields, |(name, _, _)| format!("`{name}`"))
2565                        .expect("expected at least one private field to report")
2566                )
2567            };
2568            err.note(format!(
2569                "{}private field{s} {names}that {were} not provided",
2570                if used_fields.is_empty() { "" } else { "...and other " },
2571                s = pluralize!(remaining_private_fields.len()),
2572                were = pluralize!("was", remaining_private_fields.len()),
2573            ));
2574        }
2575
2576        if let ty::Adt(def, _) = adt_ty.kind() {
2577            let def_id = def.did();
2578            let mut items = self
2579                .tcx
2580                .inherent_impls(def_id)
2581                .into_iter()
2582                .flat_map(|i| self.tcx.associated_items(i).in_definition_order())
2583                // Only assoc fn with no receivers.
2584                .filter(|item| item.is_fn() && !item.is_method())
2585                .filter_map(|item| {
2586                    // Only assoc fns that return `Self`
2587                    let fn_sig = self
2588                        .tcx
2589                        .fn_sig(item.def_id)
2590                        .instantiate(self.tcx, self.fresh_args_for_item(span, item.def_id));
2591                    let ret_ty = self.tcx.instantiate_bound_regions_with_erased(fn_sig.output());
2592                    if !self.can_eq(self.param_env, ret_ty, adt_ty) {
2593                        return None;
2594                    }
2595                    let input_len = fn_sig.inputs().skip_binder().len();
2596                    let name = item.name();
2597                    let order = !name.as_str().starts_with("new");
2598                    Some((order, name, input_len))
2599                })
2600                .collect::<Vec<_>>();
2601            items.sort_by_key(|(order, _, _)| *order);
2602            let suggestion = |name, args| {
2603                format!(
2604                    "::{name}({})",
2605                    std::iter::repeat("_").take(args).collect::<Vec<_>>().join(", ")
2606                )
2607            };
2608            match &items[..] {
2609                [] => {}
2610                [(_, name, args)] => {
2611                    err.span_suggestion_verbose(
2612                        span.shrink_to_hi().with_hi(expr_span.hi()),
2613                        format!("you might have meant to use the `{name}` associated function"),
2614                        suggestion(name, *args),
2615                        Applicability::MaybeIncorrect,
2616                    );
2617                }
2618                _ => {
2619                    err.span_suggestions(
2620                        span.shrink_to_hi().with_hi(expr_span.hi()),
2621                        "you might have meant to use an associated function to build this type",
2622                        items.iter().map(|(_, name, args)| suggestion(name, *args)),
2623                        Applicability::MaybeIncorrect,
2624                    );
2625                }
2626            }
2627            if let Some(default_trait) = self.tcx.get_diagnostic_item(sym::Default)
2628                && self
2629                    .infcx
2630                    .type_implements_trait(default_trait, [adt_ty], self.param_env)
2631                    .may_apply()
2632            {
2633                err.multipart_suggestion(
2634                    "consider using the `Default` trait",
2635                    vec![
2636                        (span.shrink_to_lo(), "<".to_string()),
2637                        (
2638                            span.shrink_to_hi().with_hi(expr_span.hi()),
2639                            " as std::default::Default>::default()".to_string(),
2640                        ),
2641                    ],
2642                    Applicability::MaybeIncorrect,
2643                );
2644            }
2645        }
2646
2647        err.emit();
2648    }
2649
2650    fn report_unknown_field(
2651        &self,
2652        ty: Ty<'tcx>,
2653        variant: &'tcx ty::VariantDef,
2654        expr: &hir::Expr<'_>,
2655        field: &hir::ExprField<'_>,
2656        skip_fields: &[hir::ExprField<'_>],
2657        kind_name: &str,
2658    ) -> ErrorGuaranteed {
2659        // we don't care to report errors for a struct if the struct itself is tainted
2660        if let Err(guar) = variant.has_errors() {
2661            return guar;
2662        }
2663        let mut err = self.err_ctxt().type_error_struct_with_diag(
2664            field.ident.span,
2665            |actual| match ty.kind() {
2666                ty::Adt(adt, ..) if adt.is_enum() => struct_span_code_err!(
2667                    self.dcx(),
2668                    field.ident.span,
2669                    E0559,
2670                    "{} `{}::{}` has no field named `{}`",
2671                    kind_name,
2672                    actual,
2673                    variant.name,
2674                    field.ident
2675                ),
2676                _ => struct_span_code_err!(
2677                    self.dcx(),
2678                    field.ident.span,
2679                    E0560,
2680                    "{} `{}` has no field named `{}`",
2681                    kind_name,
2682                    actual,
2683                    field.ident
2684                ),
2685            },
2686            ty,
2687        );
2688
2689        let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap();
2690        match variant.ctor {
2691            Some((CtorKind::Fn, def_id)) => match ty.kind() {
2692                ty::Adt(adt, ..) if adt.is_enum() => {
2693                    err.span_label(
2694                        variant_ident_span,
2695                        format!(
2696                            "`{adt}::{variant}` defined here",
2697                            adt = ty,
2698                            variant = variant.name,
2699                        ),
2700                    );
2701                    err.span_label(field.ident.span, "field does not exist");
2702                    let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity();
2703                    let inputs = fn_sig.inputs().skip_binder();
2704                    let fields = format!(
2705                        "({})",
2706                        inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2707                    );
2708                    let (replace_span, sugg) = match expr.kind {
2709                        hir::ExprKind::Struct(qpath, ..) => {
2710                            (qpath.span().shrink_to_hi().with_hi(expr.span.hi()), fields)
2711                        }
2712                        _ => {
2713                            (expr.span, format!("{ty}::{variant}{fields}", variant = variant.name))
2714                        }
2715                    };
2716                    err.span_suggestion_verbose(
2717                        replace_span,
2718                        format!(
2719                            "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax",
2720                            adt = ty,
2721                            variant = variant.name,
2722                        ),
2723                        sugg,
2724                        Applicability::HasPlaceholders,
2725                    );
2726                }
2727                _ => {
2728                    err.span_label(variant_ident_span, format!("`{ty}` defined here"));
2729                    err.span_label(field.ident.span, "field does not exist");
2730                    let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity();
2731                    let inputs = fn_sig.inputs().skip_binder();
2732                    let fields = format!(
2733                        "({})",
2734                        inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2735                    );
2736                    err.span_suggestion_verbose(
2737                        expr.span,
2738                        format!("`{ty}` is a tuple {kind_name}, use the appropriate syntax",),
2739                        format!("{ty}{fields}"),
2740                        Applicability::HasPlaceholders,
2741                    );
2742                }
2743            },
2744            _ => {
2745                // prevent all specified fields from being suggested
2746                let available_field_names = self.available_field_names(variant, expr, skip_fields);
2747                if let Some(field_name) =
2748                    find_best_match_for_name(&available_field_names, field.ident.name, None)
2749                    && !(field.ident.name.as_str().parse::<usize>().is_ok()
2750                        && field_name.as_str().parse::<usize>().is_ok())
2751                {
2752                    err.span_label(field.ident.span, "unknown field");
2753                    err.span_suggestion_verbose(
2754                        field.ident.span,
2755                        "a field with a similar name exists",
2756                        field_name,
2757                        Applicability::MaybeIncorrect,
2758                    );
2759                } else {
2760                    match ty.kind() {
2761                        ty::Adt(adt, ..) => {
2762                            if adt.is_enum() {
2763                                err.span_label(
2764                                    field.ident.span,
2765                                    format!("`{}::{}` does not have this field", ty, variant.name),
2766                                );
2767                            } else {
2768                                err.span_label(
2769                                    field.ident.span,
2770                                    format!("`{ty}` does not have this field"),
2771                                );
2772                            }
2773                            if available_field_names.is_empty() {
2774                                err.note("all struct fields are already assigned");
2775                            } else {
2776                                err.note(format!(
2777                                    "available fields are: {}",
2778                                    self.name_series_display(available_field_names)
2779                                ));
2780                            }
2781                        }
2782                        _ => bug!("non-ADT passed to report_unknown_field"),
2783                    }
2784                };
2785            }
2786        }
2787        err.emit()
2788    }
2789
2790    fn available_field_names(
2791        &self,
2792        variant: &'tcx ty::VariantDef,
2793        expr: &hir::Expr<'_>,
2794        skip_fields: &[hir::ExprField<'_>],
2795    ) -> Vec<Symbol> {
2796        variant
2797            .fields
2798            .iter()
2799            .filter(|field| {
2800                skip_fields.iter().all(|&skip| skip.ident.name != field.name)
2801                    && self.is_field_suggestable(field, expr.hir_id, expr.span)
2802            })
2803            .map(|field| field.name)
2804            .collect()
2805    }
2806
2807    fn name_series_display(&self, names: Vec<Symbol>) -> String {
2808        // dynamic limit, to never omit just one field
2809        let limit = if names.len() == 6 { 6 } else { 5 };
2810        let mut display =
2811            names.iter().take(limit).map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", ");
2812        if names.len() > limit {
2813            display = format!("{} ... and {} others", display, names.len() - limit);
2814        }
2815        display
2816    }
2817
2818    /// Find the position of a field named `ident` in `base_def`, accounting for unnammed fields.
2819    /// Return whether such a field has been found. The path to it is stored in `nested_fields`.
2820    /// `ident` must have been adjusted beforehand.
2821    fn find_adt_field(
2822        &self,
2823        base_def: ty::AdtDef<'tcx>,
2824        ident: Ident,
2825    ) -> Option<(FieldIdx, &'tcx ty::FieldDef)> {
2826        // No way to find a field in an enum.
2827        if base_def.is_enum() {
2828            return None;
2829        }
2830
2831        for (field_idx, field) in base_def.non_enum_variant().fields.iter_enumerated() {
2832            if field.ident(self.tcx).normalize_to_macros_2_0() == ident {
2833                // We found the field we wanted.
2834                return Some((field_idx, field));
2835            }
2836        }
2837
2838        None
2839    }
2840
2841    /// Check field access expressions, this works for both structs and tuples.
2842    /// Returns the Ty of the field.
2843    ///
2844    /// ```ignore (illustrative)
2845    /// base.field
2846    /// ^^^^^^^^^^ expr
2847    /// ^^^^       base
2848    ///      ^^^^^ field
2849    /// ```
2850    fn check_expr_field(
2851        &self,
2852        expr: &'tcx hir::Expr<'tcx>,
2853        base: &'tcx hir::Expr<'tcx>,
2854        field: Ident,
2855        // The expected type hint of the field.
2856        expected: Expectation<'tcx>,
2857    ) -> Ty<'tcx> {
2858        debug!("check_field(expr: {:?}, base: {:?}, field: {:?})", expr, base, field);
2859        let base_ty = self.check_expr(base);
2860        let base_ty = self.structurally_resolve_type(base.span, base_ty);
2861
2862        // Whether we are trying to access a private field. Used for error reporting.
2863        let mut private_candidate = None;
2864
2865        // Field expressions automatically deref
2866        let mut autoderef = self.autoderef(expr.span, base_ty);
2867        while let Some((deref_base_ty, _)) = autoderef.next() {
2868            debug!("deref_base_ty: {:?}", deref_base_ty);
2869            match deref_base_ty.kind() {
2870                ty::Adt(base_def, args) if !base_def.is_enum() => {
2871                    debug!("struct named {:?}", deref_base_ty);
2872                    // we don't care to report errors for a struct if the struct itself is tainted
2873                    if let Err(guar) = base_def.non_enum_variant().has_errors() {
2874                        return Ty::new_error(self.tcx(), guar);
2875                    }
2876
2877                    let fn_body_hir_id = self.tcx.local_def_id_to_hir_id(self.body_id);
2878                    let (ident, def_scope) =
2879                        self.tcx.adjust_ident_and_get_scope(field, base_def.did(), fn_body_hir_id);
2880
2881                    if let Some((idx, field)) = self.find_adt_field(*base_def, ident) {
2882                        self.write_field_index(expr.hir_id, idx);
2883
2884                        let adjustments = self.adjust_steps(&autoderef);
2885                        if field.vis.is_accessible_from(def_scope, self.tcx) {
2886                            self.apply_adjustments(base, adjustments);
2887                            self.register_predicates(autoderef.into_obligations());
2888
2889                            self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
2890                            return self.field_ty(expr.span, field, args);
2891                        }
2892
2893                        // The field is not accessible, fall through to error reporting.
2894                        private_candidate = Some((adjustments, base_def.did()));
2895                    }
2896                }
2897                ty::Tuple(tys) => {
2898                    if let Ok(index) = field.as_str().parse::<usize>() {
2899                        if field.name == sym::integer(index) {
2900                            if let Some(&field_ty) = tys.get(index) {
2901                                let adjustments = self.adjust_steps(&autoderef);
2902                                self.apply_adjustments(base, adjustments);
2903                                self.register_predicates(autoderef.into_obligations());
2904
2905                                self.write_field_index(expr.hir_id, FieldIdx::from_usize(index));
2906                                return field_ty;
2907                            }
2908                        }
2909                    }
2910                }
2911                _ => {}
2912            }
2913        }
2914        // We failed to check the expression, report an error.
2915
2916        // Emits an error if we deref an infer variable, like calling `.field` on a base type
2917        // of `&_`. We can also use this to suppress unnecessary "missing field" errors that
2918        // will follow ambiguity errors.
2919        let final_ty = self.structurally_resolve_type(autoderef.span(), autoderef.final_ty());
2920        if let ty::Error(_) = final_ty.kind() {
2921            return final_ty;
2922        }
2923
2924        if let Some((adjustments, did)) = private_candidate {
2925            // (#90483) apply adjustments to avoid ExprUseVisitor from
2926            // creating erroneous projection.
2927            self.apply_adjustments(base, adjustments);
2928            let guar = self.ban_private_field_access(
2929                expr,
2930                base_ty,
2931                field,
2932                did,
2933                expected.only_has_type(self),
2934            );
2935            return Ty::new_error(self.tcx(), guar);
2936        }
2937
2938        let guar = if self.method_exists_for_diagnostic(
2939            field,
2940            base_ty,
2941            expr.hir_id,
2942            expected.only_has_type(self),
2943        ) {
2944            // If taking a method instead of calling it
2945            self.ban_take_value_of_method(expr, base_ty, field)
2946        } else if !base_ty.is_primitive_ty() {
2947            self.ban_nonexisting_field(field, base, expr, base_ty)
2948        } else {
2949            let field_name = field.to_string();
2950            let mut err = type_error_struct!(
2951                self.dcx(),
2952                field.span,
2953                base_ty,
2954                E0610,
2955                "`{base_ty}` is a primitive type and therefore doesn't have fields",
2956            );
2957            let is_valid_suffix = |field: &str| {
2958                if field == "f32" || field == "f64" {
2959                    return true;
2960                }
2961                let mut chars = field.chars().peekable();
2962                match chars.peek() {
2963                    Some('e') | Some('E') => {
2964                        chars.next();
2965                        if let Some(c) = chars.peek()
2966                            && !c.is_numeric()
2967                            && *c != '-'
2968                            && *c != '+'
2969                        {
2970                            return false;
2971                        }
2972                        while let Some(c) = chars.peek() {
2973                            if !c.is_numeric() {
2974                                break;
2975                            }
2976                            chars.next();
2977                        }
2978                    }
2979                    _ => (),
2980                }
2981                let suffix = chars.collect::<String>();
2982                suffix.is_empty() || suffix == "f32" || suffix == "f64"
2983            };
2984            let maybe_partial_suffix = |field: &str| -> Option<&str> {
2985                let first_chars = ['f', 'l'];
2986                if field.len() >= 1
2987                    && field.to_lowercase().starts_with(first_chars)
2988                    && field[1..].chars().all(|c| c.is_ascii_digit())
2989                {
2990                    if field.to_lowercase().starts_with(['f']) { Some("f32") } else { Some("f64") }
2991                } else {
2992                    None
2993                }
2994            };
2995            if let ty::Infer(ty::IntVar(_)) = base_ty.kind()
2996                && let ExprKind::Lit(Spanned {
2997                    node: ast::LitKind::Int(_, ast::LitIntType::Unsuffixed),
2998                    ..
2999                }) = base.kind
3000                && !base.span.from_expansion()
3001            {
3002                if is_valid_suffix(&field_name) {
3003                    err.span_suggestion_verbose(
3004                        field.span.shrink_to_lo(),
3005                        "if intended to be a floating point literal, consider adding a `0` after the period",
3006                        '0',
3007                        Applicability::MaybeIncorrect,
3008                    );
3009                } else if let Some(correct_suffix) = maybe_partial_suffix(&field_name) {
3010                    err.span_suggestion_verbose(
3011                        field.span,
3012                        format!("if intended to be a floating point literal, consider adding a `0` after the period and a `{correct_suffix}` suffix"),
3013                        format!("0{correct_suffix}"),
3014                        Applicability::MaybeIncorrect,
3015                    );
3016                }
3017            }
3018            err.emit()
3019        };
3020
3021        Ty::new_error(self.tcx(), guar)
3022    }
3023
3024    fn suggest_await_on_field_access(
3025        &self,
3026        err: &mut Diag<'_>,
3027        field_ident: Ident,
3028        base: &'tcx hir::Expr<'tcx>,
3029        ty: Ty<'tcx>,
3030    ) {
3031        let Some(output_ty) = self.err_ctxt().get_impl_future_output_ty(ty) else {
3032            err.span_label(field_ident.span, "unknown field");
3033            return;
3034        };
3035        let ty::Adt(def, _) = output_ty.kind() else {
3036            err.span_label(field_ident.span, "unknown field");
3037            return;
3038        };
3039        // no field access on enum type
3040        if def.is_enum() {
3041            err.span_label(field_ident.span, "unknown field");
3042            return;
3043        }
3044        if !def.non_enum_variant().fields.iter().any(|field| field.ident(self.tcx) == field_ident) {
3045            err.span_label(field_ident.span, "unknown field");
3046            return;
3047        }
3048        err.span_label(
3049            field_ident.span,
3050            "field not available in `impl Future`, but it is available in its `Output`",
3051        );
3052        match self.tcx.coroutine_kind(self.body_id) {
3053            Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3054                err.span_suggestion_verbose(
3055                    base.span.shrink_to_hi(),
3056                    "consider `await`ing on the `Future` to access the field",
3057                    ".await",
3058                    Applicability::MaybeIncorrect,
3059                );
3060            }
3061            _ => {
3062                let mut span: MultiSpan = base.span.into();
3063                span.push_span_label(self.tcx.def_span(self.body_id), "this is not `async`");
3064                err.span_note(
3065                    span,
3066                    "this implements `Future` and its output type has the field, \
3067                    but the future cannot be awaited in a synchronous function",
3068                );
3069            }
3070        }
3071    }
3072
3073    fn ban_nonexisting_field(
3074        &self,
3075        ident: Ident,
3076        base: &'tcx hir::Expr<'tcx>,
3077        expr: &'tcx hir::Expr<'tcx>,
3078        base_ty: Ty<'tcx>,
3079    ) -> ErrorGuaranteed {
3080        debug!(
3081            "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}",
3082            ident, base, expr, base_ty
3083        );
3084        let mut err = self.no_such_field_err(ident, base_ty, expr);
3085
3086        match *base_ty.peel_refs().kind() {
3087            ty::Array(_, len) => {
3088                self.maybe_suggest_array_indexing(&mut err, base, ident, len);
3089            }
3090            ty::RawPtr(..) => {
3091                self.suggest_first_deref_field(&mut err, base, ident);
3092            }
3093            ty::Param(param_ty) => {
3094                err.span_label(ident.span, "unknown field");
3095                self.point_at_param_definition(&mut err, param_ty);
3096            }
3097            ty::Alias(ty::Opaque, _) => {
3098                self.suggest_await_on_field_access(&mut err, ident, base, base_ty.peel_refs());
3099            }
3100            _ => {
3101                err.span_label(ident.span, "unknown field");
3102            }
3103        }
3104
3105        self.suggest_fn_call(&mut err, base, base_ty, |output_ty| {
3106            if let ty::Adt(def, _) = output_ty.kind()
3107                && !def.is_enum()
3108            {
3109                def.non_enum_variant().fields.iter().any(|field| {
3110                    field.ident(self.tcx) == ident
3111                        && field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
3112                })
3113            } else if let ty::Tuple(tys) = output_ty.kind()
3114                && let Ok(idx) = ident.as_str().parse::<usize>()
3115            {
3116                idx < tys.len()
3117            } else {
3118                false
3119            }
3120        });
3121
3122        if ident.name == kw::Await {
3123            // We know by construction that `<expr>.await` is either on Rust 2015
3124            // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
3125            err.note("to `.await` a `Future`, switch to Rust 2018 or later");
3126            HelpUseLatestEdition::new().add_to_diag(&mut err);
3127        }
3128
3129        err.emit()
3130    }
3131
3132    fn ban_private_field_access(
3133        &self,
3134        expr: &hir::Expr<'tcx>,
3135        expr_t: Ty<'tcx>,
3136        field: Ident,
3137        base_did: DefId,
3138        return_ty: Option<Ty<'tcx>>,
3139    ) -> ErrorGuaranteed {
3140        let mut err = self.private_field_err(field, base_did);
3141
3142        // Also check if an accessible method exists, which is often what is meant.
3143        if self.method_exists_for_diagnostic(field, expr_t, expr.hir_id, return_ty)
3144            && !self.expr_in_place(expr.hir_id)
3145        {
3146            self.suggest_method_call(
3147                &mut err,
3148                format!("a method `{field}` also exists, call it with parentheses"),
3149                field,
3150                expr_t,
3151                expr,
3152                None,
3153            );
3154        }
3155        err.emit()
3156    }
3157
3158    fn ban_take_value_of_method(
3159        &self,
3160        expr: &hir::Expr<'tcx>,
3161        expr_t: Ty<'tcx>,
3162        field: Ident,
3163    ) -> ErrorGuaranteed {
3164        let mut err = type_error_struct!(
3165            self.dcx(),
3166            field.span,
3167            expr_t,
3168            E0615,
3169            "attempted to take value of method `{field}` on type `{expr_t}`",
3170        );
3171        err.span_label(field.span, "method, not a field");
3172        let expr_is_call =
3173            if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) =
3174                self.tcx.parent_hir_node(expr.hir_id)
3175            {
3176                expr.hir_id == callee.hir_id
3177            } else {
3178                false
3179            };
3180        let expr_snippet =
3181            self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_default();
3182        let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')');
3183        let after_open = expr.span.lo() + rustc_span::BytePos(1);
3184        let before_close = expr.span.hi() - rustc_span::BytePos(1);
3185
3186        if expr_is_call && is_wrapped {
3187            err.multipart_suggestion(
3188                "remove wrapping parentheses to call the method",
3189                vec![
3190                    (expr.span.with_hi(after_open), String::new()),
3191                    (expr.span.with_lo(before_close), String::new()),
3192                ],
3193                Applicability::MachineApplicable,
3194            );
3195        } else if !self.expr_in_place(expr.hir_id) {
3196            // Suggest call parentheses inside the wrapping parentheses
3197            let span = if is_wrapped {
3198                expr.span.with_lo(after_open).with_hi(before_close)
3199            } else {
3200                expr.span
3201            };
3202            self.suggest_method_call(
3203                &mut err,
3204                "use parentheses to call the method",
3205                field,
3206                expr_t,
3207                expr,
3208                Some(span),
3209            );
3210        } else if let ty::RawPtr(ptr_ty, _) = expr_t.kind()
3211            && let ty::Adt(adt_def, _) = ptr_ty.kind()
3212            && let ExprKind::Field(base_expr, _) = expr.kind
3213            && let [variant] = &adt_def.variants().raw
3214            && variant.fields.iter().any(|f| f.ident(self.tcx) == field)
3215        {
3216            err.multipart_suggestion(
3217                "to access the field, dereference first",
3218                vec![
3219                    (base_expr.span.shrink_to_lo(), "(*".to_string()),
3220                    (base_expr.span.shrink_to_hi(), ")".to_string()),
3221                ],
3222                Applicability::MaybeIncorrect,
3223            );
3224        } else {
3225            err.help("methods are immutable and cannot be assigned to");
3226        }
3227
3228        // See `StashKey::GenericInFieldExpr` for more info
3229        self.dcx().try_steal_replace_and_emit_err(field.span, StashKey::GenericInFieldExpr, err)
3230    }
3231
3232    fn point_at_param_definition(&self, err: &mut Diag<'_>, param: ty::ParamTy) {
3233        let generics = self.tcx.generics_of(self.body_id);
3234        let generic_param = generics.type_param(param, self.tcx);
3235        if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
3236            return;
3237        }
3238        let param_def_id = generic_param.def_id;
3239        let param_hir_id = match param_def_id.as_local() {
3240            Some(x) => self.tcx.local_def_id_to_hir_id(x),
3241            None => return,
3242        };
3243        let param_span = self.tcx.hir_span(param_hir_id);
3244        let param_name = self.tcx.hir_ty_param_name(param_def_id.expect_local());
3245
3246        err.span_label(param_span, format!("type parameter '{param_name}' declared here"));
3247    }
3248
3249    fn maybe_suggest_array_indexing(
3250        &self,
3251        err: &mut Diag<'_>,
3252        base: &hir::Expr<'_>,
3253        field: Ident,
3254        len: ty::Const<'tcx>,
3255    ) {
3256        err.span_label(field.span, "unknown field");
3257        if let (Some(len), Ok(user_index)) = (
3258            self.try_structurally_resolve_const(base.span, len).try_to_target_usize(self.tcx),
3259            field.as_str().parse::<u64>(),
3260        ) {
3261            let help = "instead of using tuple indexing, use array indexing";
3262            let applicability = if len < user_index {
3263                Applicability::MachineApplicable
3264            } else {
3265                Applicability::MaybeIncorrect
3266            };
3267            err.multipart_suggestion(
3268                help,
3269                vec![
3270                    (base.span.between(field.span), "[".to_string()),
3271                    (field.span.shrink_to_hi(), "]".to_string()),
3272                ],
3273                applicability,
3274            );
3275        }
3276    }
3277
3278    fn suggest_first_deref_field(&self, err: &mut Diag<'_>, base: &hir::Expr<'_>, field: Ident) {
3279        err.span_label(field.span, "unknown field");
3280        let val = if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span)
3281            && base.len() < 20
3282        {
3283            format!("`{base}`")
3284        } else {
3285            "the value".to_string()
3286        };
3287        err.multipart_suggestion(
3288            format!("{val} is a raw pointer; try dereferencing it"),
3289            vec![
3290                (base.span.shrink_to_lo(), "(*".into()),
3291                (base.span.between(field.span), format!(").")),
3292            ],
3293            Applicability::MaybeIncorrect,
3294        );
3295    }
3296
3297    fn no_such_field_err(
3298        &self,
3299        field: Ident,
3300        base_ty: Ty<'tcx>,
3301        expr: &hir::Expr<'tcx>,
3302    ) -> Diag<'_> {
3303        let span = field.span;
3304        debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, base_ty);
3305
3306        let mut err = self.dcx().create_err(NoFieldOnType { span, ty: base_ty, field });
3307        if base_ty.references_error() {
3308            err.downgrade_to_delayed_bug();
3309        }
3310
3311        if let Some(within_macro_span) = span.within_macro(expr.span, self.tcx.sess.source_map()) {
3312            err.span_label(within_macro_span, "due to this macro variable");
3313        }
3314
3315        // try to add a suggestion in case the field is a nested field of a field of the Adt
3316        let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id();
3317        let (ty, unwrap) = if let ty::Adt(def, args) = base_ty.kind()
3318            && (self.tcx.is_diagnostic_item(sym::Result, def.did())
3319                || self.tcx.is_diagnostic_item(sym::Option, def.did()))
3320            && let Some(arg) = args.get(0)
3321            && let Some(ty) = arg.as_type()
3322        {
3323            (ty, "unwrap().")
3324        } else {
3325            (base_ty, "")
3326        };
3327        for found_fields in
3328            self.get_field_candidates_considering_privacy_for_diag(span, ty, mod_id, expr.hir_id)
3329        {
3330            let field_names = found_fields.iter().map(|field| field.0.name).collect::<Vec<_>>();
3331            let mut candidate_fields: Vec<_> = found_fields
3332                .into_iter()
3333                .filter_map(|candidate_field| {
3334                    self.check_for_nested_field_satisfying_condition_for_diag(
3335                        span,
3336                        &|candidate_field, _| candidate_field == field,
3337                        candidate_field,
3338                        vec![],
3339                        mod_id,
3340                        expr.hir_id,
3341                    )
3342                })
3343                .map(|mut field_path| {
3344                    field_path.pop();
3345                    field_path.iter().map(|id| format!("{}.", id)).collect::<String>()
3346                })
3347                .collect::<Vec<_>>();
3348            candidate_fields.sort();
3349
3350            let len = candidate_fields.len();
3351            // Don't suggest `.field` if the base expr is from a different
3352            // syntax context than the field.
3353            if len > 0 && expr.span.eq_ctxt(field.span) {
3354                err.span_suggestions(
3355                    field.span.shrink_to_lo(),
3356                    format!(
3357                        "{} of the expressions' fields {} a field of the same name",
3358                        if len > 1 { "some" } else { "one" },
3359                        if len > 1 { "have" } else { "has" },
3360                    ),
3361                    candidate_fields.iter().map(|path| format!("{unwrap}{path}")),
3362                    Applicability::MaybeIncorrect,
3363                );
3364            } else if let Some(field_name) =
3365                find_best_match_for_name(&field_names, field.name, None)
3366                && !(field.name.as_str().parse::<usize>().is_ok()
3367                    && field_name.as_str().parse::<usize>().is_ok())
3368            {
3369                err.span_suggestion_verbose(
3370                    field.span,
3371                    "a field with a similar name exists",
3372                    format!("{unwrap}{}", field_name),
3373                    Applicability::MaybeIncorrect,
3374                );
3375            } else if !field_names.is_empty() {
3376                let is = if field_names.len() == 1 { " is" } else { "s are" };
3377                err.note(
3378                    format!("available field{is}: {}", self.name_series_display(field_names),),
3379                );
3380            }
3381        }
3382        err
3383    }
3384
3385    fn private_field_err(&self, field: Ident, base_did: DefId) -> Diag<'_> {
3386        let struct_path = self.tcx().def_path_str(base_did);
3387        let kind_name = self.tcx().def_descr(base_did);
3388        struct_span_code_err!(
3389            self.dcx(),
3390            field.span,
3391            E0616,
3392            "field `{field}` of {kind_name} `{struct_path}` is private",
3393        )
3394        .with_span_label(field.span, "private field")
3395    }
3396
3397    pub(crate) fn get_field_candidates_considering_privacy_for_diag(
3398        &self,
3399        span: Span,
3400        base_ty: Ty<'tcx>,
3401        mod_id: DefId,
3402        hir_id: HirId,
3403    ) -> Vec<Vec<(Ident, Ty<'tcx>)>> {
3404        debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_ty);
3405
3406        let mut autoderef = self.autoderef(span, base_ty).silence_errors();
3407        let deref_chain: Vec<_> = autoderef.by_ref().collect();
3408
3409        // Don't probe if we hit the recursion limit, since it may result in
3410        // quadratic blowup if we then try to further deref the results of this
3411        // function. This is a best-effort method, after all.
3412        if autoderef.reached_recursion_limit() {
3413            return vec![];
3414        }
3415
3416        deref_chain
3417            .into_iter()
3418            .filter_map(move |(base_t, _)| {
3419                match base_t.kind() {
3420                    ty::Adt(base_def, args) if !base_def.is_enum() => {
3421                        let tcx = self.tcx;
3422                        let fields = &base_def.non_enum_variant().fields;
3423                        // Some struct, e.g. some that impl `Deref`, have all private fields
3424                        // because you're expected to deref them to access the _real_ fields.
3425                        // This, for example, will help us suggest accessing a field through a `Box<T>`.
3426                        if fields.iter().all(|field| !field.vis.is_accessible_from(mod_id, tcx)) {
3427                            return None;
3428                        }
3429                        return Some(
3430                            fields
3431                                .iter()
3432                                .filter(move |field| {
3433                                    field.vis.is_accessible_from(mod_id, tcx)
3434                                        && self.is_field_suggestable(field, hir_id, span)
3435                                })
3436                                // For compile-time reasons put a limit on number of fields we search
3437                                .take(100)
3438                                .map(|field_def| {
3439                                    (
3440                                        field_def.ident(self.tcx).normalize_to_macros_2_0(),
3441                                        field_def.ty(self.tcx, args),
3442                                    )
3443                                })
3444                                .collect::<Vec<_>>(),
3445                        );
3446                    }
3447                    ty::Tuple(types) => {
3448                        return Some(
3449                            types
3450                                .iter()
3451                                .enumerate()
3452                                // For compile-time reasons put a limit on number of fields we search
3453                                .take(100)
3454                                .map(|(i, ty)| (Ident::from_str(&i.to_string()), ty))
3455                                .collect::<Vec<_>>(),
3456                        );
3457                    }
3458                    _ => None,
3459                }
3460            })
3461            .collect()
3462    }
3463
3464    /// This method is called after we have encountered a missing field error to recursively
3465    /// search for the field
3466    #[instrument(skip(self, matches, mod_id, hir_id), level = "debug")]
3467    pub(crate) fn check_for_nested_field_satisfying_condition_for_diag(
3468        &self,
3469        span: Span,
3470        matches: &impl Fn(Ident, Ty<'tcx>) -> bool,
3471        (candidate_name, candidate_ty): (Ident, Ty<'tcx>),
3472        mut field_path: Vec<Ident>,
3473        mod_id: DefId,
3474        hir_id: HirId,
3475    ) -> Option<Vec<Ident>> {
3476        if field_path.len() > 3 {
3477            // For compile-time reasons and to avoid infinite recursion we only check for fields
3478            // up to a depth of three
3479            return None;
3480        }
3481        field_path.push(candidate_name);
3482        if matches(candidate_name, candidate_ty) {
3483            return Some(field_path);
3484        }
3485        for nested_fields in self.get_field_candidates_considering_privacy_for_diag(
3486            span,
3487            candidate_ty,
3488            mod_id,
3489            hir_id,
3490        ) {
3491            // recursively search fields of `candidate_field` if it's a ty::Adt
3492            for field in nested_fields {
3493                if let Some(field_path) = self.check_for_nested_field_satisfying_condition_for_diag(
3494                    span,
3495                    matches,
3496                    field,
3497                    field_path.clone(),
3498                    mod_id,
3499                    hir_id,
3500                ) {
3501                    return Some(field_path);
3502                }
3503            }
3504        }
3505        None
3506    }
3507
3508    fn check_expr_index(
3509        &self,
3510        base: &'tcx hir::Expr<'tcx>,
3511        idx: &'tcx hir::Expr<'tcx>,
3512        expr: &'tcx hir::Expr<'tcx>,
3513        brackets_span: Span,
3514    ) -> Ty<'tcx> {
3515        let base_t = self.check_expr(base);
3516        let idx_t = self.check_expr(idx);
3517
3518        if base_t.references_error() {
3519            base_t
3520        } else if idx_t.references_error() {
3521            idx_t
3522        } else {
3523            let base_t = self.structurally_resolve_type(base.span, base_t);
3524            match self.lookup_indexing(expr, base, base_t, idx, idx_t) {
3525                Some((index_ty, element_ty)) => {
3526                    // two-phase not needed because index_ty is never mutable
3527                    self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3528                    self.select_obligations_where_possible(|errors| {
3529                        self.point_at_index(errors, idx.span);
3530                    });
3531                    element_ty
3532                }
3533                None => {
3534                    // Attempt to *shallowly* search for an impl which matches,
3535                    // but has nested obligations which are unsatisfied.
3536                    for (base_t, _) in self.autoderef(base.span, base_t).silence_errors() {
3537                        if let Some((_, index_ty, element_ty)) =
3538                            self.find_and_report_unsatisfied_index_impl(base, base_t)
3539                        {
3540                            self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3541                            return element_ty;
3542                        }
3543                    }
3544
3545                    let mut err = type_error_struct!(
3546                        self.dcx(),
3547                        brackets_span,
3548                        base_t,
3549                        E0608,
3550                        "cannot index into a value of type `{base_t}`",
3551                    );
3552                    // Try to give some advice about indexing tuples.
3553                    if let ty::Tuple(types) = base_t.kind() {
3554                        let mut needs_note = true;
3555                        // If the index is an integer, we can show the actual
3556                        // fixed expression:
3557                        if let ExprKind::Lit(lit) = idx.kind
3558                            && let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node
3559                            && i.get()
3560                                < types
3561                                    .len()
3562                                    .try_into()
3563                                    .expect("expected tuple index to be < usize length")
3564                        {
3565                            err.span_suggestion(
3566                                brackets_span,
3567                                "to access tuple elements, use",
3568                                format!(".{i}"),
3569                                Applicability::MachineApplicable,
3570                            );
3571                            needs_note = false;
3572                        } else if let ExprKind::Path(..) = idx.peel_borrows().kind {
3573                            err.span_label(
3574                                idx.span,
3575                                "cannot access tuple elements at a variable index",
3576                            );
3577                        }
3578                        if needs_note {
3579                            err.help(
3580                                "to access tuple elements, use tuple indexing \
3581                                        syntax (e.g., `tuple.0`)",
3582                            );
3583                        }
3584                    }
3585
3586                    if base_t.is_raw_ptr() && idx_t.is_integral() {
3587                        err.multipart_suggestion(
3588                            "consider using `wrapping_add` or `add` for indexing into raw pointer",
3589                            vec![
3590                                (base.span.between(idx.span), ".wrapping_add(".to_owned()),
3591                                (
3592                                    idx.span.shrink_to_hi().until(expr.span.shrink_to_hi()),
3593                                    ")".to_owned(),
3594                                ),
3595                            ],
3596                            Applicability::MaybeIncorrect,
3597                        );
3598                    }
3599
3600                    let reported = err.emit();
3601                    Ty::new_error(self.tcx, reported)
3602                }
3603            }
3604        }
3605    }
3606
3607    /// Try to match an implementation of `Index` against a self type, and report
3608    /// the unsatisfied predicates that result from confirming this impl.
3609    ///
3610    /// Given an index expression, sometimes the `Self` type shallowly but does not
3611    /// deeply satisfy an impl predicate. Instead of simply saying that the type
3612    /// does not support being indexed, we want to point out exactly what nested
3613    /// predicates cause this to be, so that the user can add them to fix their code.
3614    fn find_and_report_unsatisfied_index_impl(
3615        &self,
3616        base_expr: &hir::Expr<'_>,
3617        base_ty: Ty<'tcx>,
3618    ) -> Option<(ErrorGuaranteed, Ty<'tcx>, Ty<'tcx>)> {
3619        let index_trait_def_id = self.tcx.lang_items().index_trait()?;
3620        let index_trait_output_def_id = self.tcx.get_diagnostic_item(sym::IndexOutput)?;
3621
3622        let mut relevant_impls = vec![];
3623        self.tcx.for_each_relevant_impl(index_trait_def_id, base_ty, |impl_def_id| {
3624            relevant_impls.push(impl_def_id);
3625        });
3626        let [impl_def_id] = relevant_impls[..] else {
3627            // Only report unsatisfied impl predicates if there's one impl
3628            return None;
3629        };
3630
3631        self.commit_if_ok(|snapshot| {
3632            let outer_universe = self.universe();
3633
3634            let ocx = ObligationCtxt::new_with_diagnostics(self);
3635            let impl_args = self.fresh_args_for_item(base_expr.span, impl_def_id);
3636            let impl_trait_ref =
3637                self.tcx.impl_trait_ref(impl_def_id).unwrap().instantiate(self.tcx, impl_args);
3638            let cause = self.misc(base_expr.span);
3639
3640            // Match the impl self type against the base ty. If this fails,
3641            // we just skip this impl, since it's not particularly useful.
3642            let impl_trait_ref = ocx.normalize(&cause, self.param_env, impl_trait_ref);
3643            ocx.eq(&cause, self.param_env, base_ty, impl_trait_ref.self_ty())?;
3644
3645            // Register the impl's predicates. One of these predicates
3646            // must be unsatisfied, or else we wouldn't have gotten here
3647            // in the first place.
3648            ocx.register_obligations(traits::predicates_for_generics(
3649                |idx, span| {
3650                    cause.clone().derived_cause(
3651                        ty::Binder::dummy(ty::TraitPredicate {
3652                            trait_ref: impl_trait_ref,
3653                            polarity: ty::PredicatePolarity::Positive,
3654                        }),
3655                        |derived| {
3656                            ObligationCauseCode::ImplDerived(Box::new(traits::ImplDerivedCause {
3657                                derived,
3658                                impl_or_alias_def_id: impl_def_id,
3659                                impl_def_predicate_index: Some(idx),
3660                                span,
3661                            }))
3662                        },
3663                    )
3664                },
3665                self.param_env,
3666                self.tcx.predicates_of(impl_def_id).instantiate(self.tcx, impl_args),
3667            ));
3668
3669            // Normalize the output type, which we can use later on as the
3670            // return type of the index expression...
3671            let element_ty = ocx.normalize(
3672                &cause,
3673                self.param_env,
3674                Ty::new_projection_from_args(
3675                    self.tcx,
3676                    index_trait_output_def_id,
3677                    impl_trait_ref.args,
3678                ),
3679            );
3680
3681            let true_errors = ocx.select_where_possible();
3682
3683            // Do a leak check -- we can't really report a useful error here,
3684            // but it at least avoids an ICE when the error has to do with higher-ranked
3685            // lifetimes.
3686            self.leak_check(outer_universe, Some(snapshot))?;
3687
3688            // Bail if we have ambiguity errors, which we can't report in a useful way.
3689            let ambiguity_errors = ocx.select_all_or_error();
3690            if true_errors.is_empty() && !ambiguity_errors.is_empty() {
3691                return Err(NoSolution);
3692            }
3693
3694            // There should be at least one error reported. If not, we
3695            // will still delay a span bug in `report_fulfillment_errors`.
3696            Ok::<_, NoSolution>((
3697                self.err_ctxt().report_fulfillment_errors(true_errors),
3698                impl_trait_ref.args.type_at(1),
3699                element_ty,
3700            ))
3701        })
3702        .ok()
3703    }
3704
3705    fn point_at_index(&self, errors: &mut Vec<traits::FulfillmentError<'tcx>>, span: Span) {
3706        let mut seen_preds = FxHashSet::default();
3707        // We re-sort here so that the outer most root obligations comes first, as we have the
3708        // subsequent weird logic to identify *every* relevant obligation for proper deduplication
3709        // of diagnostics.
3710        errors.sort_by_key(|error| error.root_obligation.recursion_depth);
3711        for error in errors {
3712            match (
3713                error.root_obligation.predicate.kind().skip_binder(),
3714                error.obligation.predicate.kind().skip_binder(),
3715            ) {
3716                (ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)), _)
3717                    if self.tcx.is_lang_item(predicate.trait_ref.def_id, LangItem::Index) =>
3718                {
3719                    seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3720                }
3721                (_, ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)))
3722                    if self.tcx.is_diagnostic_item(sym::SliceIndex, predicate.trait_ref.def_id) =>
3723                {
3724                    seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3725                }
3726                (root, pred) if seen_preds.contains(&pred) || seen_preds.contains(&root) => {}
3727                _ => continue,
3728            }
3729            error.obligation.cause.span = span;
3730        }
3731    }
3732
3733    fn check_expr_yield(
3734        &self,
3735        value: &'tcx hir::Expr<'tcx>,
3736        expr: &'tcx hir::Expr<'tcx>,
3737    ) -> Ty<'tcx> {
3738        match self.coroutine_types {
3739            Some(CoroutineTypes { resume_ty, yield_ty }) => {
3740                self.check_expr_coercible_to_type(value, yield_ty, None);
3741
3742                resume_ty
3743            }
3744            _ => {
3745                self.dcx().emit_err(YieldExprOutsideOfCoroutine { span: expr.span });
3746                // Avoid expressions without types during writeback (#78653).
3747                self.check_expr(value);
3748                self.tcx.types.unit
3749            }
3750        }
3751    }
3752
3753    fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
3754        let needs = if is_input { Needs::None } else { Needs::MutPlace };
3755        let ty = self.check_expr_with_needs(expr, needs);
3756        self.require_type_is_sized(ty, expr.span, ObligationCauseCode::InlineAsmSized);
3757
3758        if !is_input && !expr.is_syntactic_place_expr() {
3759            self.dcx()
3760                .struct_span_err(expr.span, "invalid asm output")
3761                .with_span_label(expr.span, "cannot assign to this expression")
3762                .emit();
3763        }
3764
3765        // If this is an input value, we require its type to be fully resolved
3766        // at this point. This allows us to provide helpful coercions which help
3767        // pass the type candidate list in a later pass.
3768        //
3769        // We don't require output types to be resolved at this point, which
3770        // allows them to be inferred based on how they are used later in the
3771        // function.
3772        if is_input {
3773            let ty = self.structurally_resolve_type(expr.span, ty);
3774            match *ty.kind() {
3775                ty::FnDef(..) => {
3776                    let fnptr_ty = Ty::new_fn_ptr(self.tcx, ty.fn_sig(self.tcx));
3777                    self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
3778                }
3779                ty::Ref(_, base_ty, mutbl) => {
3780                    let ptr_ty = Ty::new_ptr(self.tcx, base_ty, mutbl);
3781                    self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
3782                }
3783                _ => {}
3784            }
3785        }
3786    }
3787
3788    fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) -> Ty<'tcx> {
3789        if let rustc_ast::AsmMacro::NakedAsm = asm.asm_macro {
3790            if !find_attr!(self.tcx.get_all_attrs(self.body_id), AttributeKind::Naked(..)) {
3791                self.tcx.dcx().emit_err(NakedAsmOutsideNakedFn { span });
3792            }
3793        }
3794
3795        let mut diverge = asm.asm_macro.diverges(asm.options);
3796
3797        for (op, _op_sp) in asm.operands {
3798            match *op {
3799                hir::InlineAsmOperand::In { expr, .. } => {
3800                    self.check_expr_asm_operand(expr, true);
3801                }
3802                hir::InlineAsmOperand::Out { expr: Some(expr), .. }
3803                | hir::InlineAsmOperand::InOut { expr, .. } => {
3804                    self.check_expr_asm_operand(expr, false);
3805                }
3806                hir::InlineAsmOperand::Out { expr: None, .. } => {}
3807                hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
3808                    self.check_expr_asm_operand(in_expr, true);
3809                    if let Some(out_expr) = out_expr {
3810                        self.check_expr_asm_operand(out_expr, false);
3811                    }
3812                }
3813                hir::InlineAsmOperand::Const { ref anon_const } => {
3814                    self.check_expr_const_block(anon_const, Expectation::NoExpectation);
3815                }
3816                hir::InlineAsmOperand::SymFn { expr } => {
3817                    self.check_expr(expr);
3818                }
3819                hir::InlineAsmOperand::SymStatic { .. } => {}
3820                hir::InlineAsmOperand::Label { block } => {
3821                    let previous_diverges = self.diverges.get();
3822
3823                    // The label blocks should have unit return value or diverge.
3824                    let ty = self.check_expr_block(block, ExpectHasType(self.tcx.types.unit));
3825                    if !ty.is_never() {
3826                        self.demand_suptype(block.span, self.tcx.types.unit, ty);
3827                        diverge = false;
3828                    }
3829
3830                    // We need this to avoid false unreachable warning when a label diverges.
3831                    self.diverges.set(previous_diverges);
3832                }
3833            }
3834        }
3835
3836        if diverge { self.tcx.types.never } else { self.tcx.types.unit }
3837    }
3838
3839    fn check_expr_offset_of(
3840        &self,
3841        container: &'tcx hir::Ty<'tcx>,
3842        fields: &[Ident],
3843        expr: &'tcx hir::Expr<'tcx>,
3844    ) -> Ty<'tcx> {
3845        let container = self.lower_ty(container).normalized;
3846
3847        let mut field_indices = Vec::with_capacity(fields.len());
3848        let mut current_container = container;
3849        let mut fields = fields.into_iter();
3850
3851        while let Some(&field) = fields.next() {
3852            let container = self.structurally_resolve_type(expr.span, current_container);
3853
3854            match container.kind() {
3855                ty::Adt(container_def, args) if container_def.is_enum() => {
3856                    let block = self.tcx.local_def_id_to_hir_id(self.body_id);
3857                    let (ident, _def_scope) =
3858                        self.tcx.adjust_ident_and_get_scope(field, container_def.did(), block);
3859
3860                    if !self.tcx.features().offset_of_enum() {
3861                        rustc_session::parse::feature_err(
3862                            &self.tcx.sess,
3863                            sym::offset_of_enum,
3864                            ident.span,
3865                            "using enums in offset_of is experimental",
3866                        )
3867                        .emit();
3868                    }
3869
3870                    let Some((index, variant)) = container_def
3871                        .variants()
3872                        .iter_enumerated()
3873                        .find(|(_, v)| v.ident(self.tcx).normalize_to_macros_2_0() == ident)
3874                    else {
3875                        self.dcx()
3876                            .create_err(NoVariantNamed { span: ident.span, ident, ty: container })
3877                            .with_span_label(field.span, "variant not found")
3878                            .emit_unless_delay(container.references_error());
3879                        break;
3880                    };
3881                    let Some(&subfield) = fields.next() else {
3882                        type_error_struct!(
3883                            self.dcx(),
3884                            ident.span,
3885                            container,
3886                            E0795,
3887                            "`{ident}` is an enum variant; expected field at end of `offset_of`",
3888                        )
3889                        .with_span_label(field.span, "enum variant")
3890                        .emit();
3891                        break;
3892                    };
3893                    let (subident, sub_def_scope) =
3894                        self.tcx.adjust_ident_and_get_scope(subfield, variant.def_id, block);
3895
3896                    let Some((subindex, field)) = variant
3897                        .fields
3898                        .iter_enumerated()
3899                        .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == subident)
3900                    else {
3901                        self.dcx()
3902                            .create_err(NoFieldOnVariant {
3903                                span: ident.span,
3904                                container,
3905                                ident,
3906                                field: subfield,
3907                                enum_span: field.span,
3908                                field_span: subident.span,
3909                            })
3910                            .emit_unless_delay(container.references_error());
3911                        break;
3912                    };
3913
3914                    let field_ty = self.field_ty(expr.span, field, args);
3915
3916                    // Enums are anyway always sized. But just to safeguard against future
3917                    // language extensions, let's double-check.
3918                    self.require_type_is_sized(
3919                        field_ty,
3920                        expr.span,
3921                        ObligationCauseCode::FieldSized {
3922                            adt_kind: AdtKind::Enum,
3923                            span: self.tcx.def_span(field.did),
3924                            last: false,
3925                        },
3926                    );
3927
3928                    if field.vis.is_accessible_from(sub_def_scope, self.tcx) {
3929                        self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3930                    } else {
3931                        self.private_field_err(ident, container_def.did()).emit();
3932                    }
3933
3934                    // Save the index of all fields regardless of their visibility in case
3935                    // of error recovery.
3936                    field_indices.push((index, subindex));
3937                    current_container = field_ty;
3938
3939                    continue;
3940                }
3941                ty::Adt(container_def, args) => {
3942                    let block = self.tcx.local_def_id_to_hir_id(self.body_id);
3943                    let (ident, def_scope) =
3944                        self.tcx.adjust_ident_and_get_scope(field, container_def.did(), block);
3945
3946                    let fields = &container_def.non_enum_variant().fields;
3947                    if let Some((index, field)) = fields
3948                        .iter_enumerated()
3949                        .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == ident)
3950                    {
3951                        let field_ty = self.field_ty(expr.span, field, args);
3952
3953                        if self.tcx.features().offset_of_slice() {
3954                            self.require_type_has_static_alignment(field_ty, expr.span);
3955                        } else {
3956                            self.require_type_is_sized(
3957                                field_ty,
3958                                expr.span,
3959                                ObligationCauseCode::Misc,
3960                            );
3961                        }
3962
3963                        if field.vis.is_accessible_from(def_scope, self.tcx) {
3964                            self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3965                        } else {
3966                            self.private_field_err(ident, container_def.did()).emit();
3967                        }
3968
3969                        // Save the index of all fields regardless of their visibility in case
3970                        // of error recovery.
3971                        field_indices.push((FIRST_VARIANT, index));
3972                        current_container = field_ty;
3973
3974                        continue;
3975                    }
3976                }
3977                ty::Tuple(tys) => {
3978                    if let Ok(index) = field.as_str().parse::<usize>()
3979                        && field.name == sym::integer(index)
3980                    {
3981                        if let Some(&field_ty) = tys.get(index) {
3982                            if self.tcx.features().offset_of_slice() {
3983                                self.require_type_has_static_alignment(field_ty, expr.span);
3984                            } else {
3985                                self.require_type_is_sized(
3986                                    field_ty,
3987                                    expr.span,
3988                                    ObligationCauseCode::Misc,
3989                                );
3990                            }
3991
3992                            field_indices.push((FIRST_VARIANT, index.into()));
3993                            current_container = field_ty;
3994
3995                            continue;
3996                        }
3997                    }
3998                }
3999                _ => (),
4000            };
4001
4002            self.no_such_field_err(field, container, expr).emit();
4003
4004            break;
4005        }
4006
4007        self.typeck_results
4008            .borrow_mut()
4009            .offset_of_data_mut()
4010            .insert(expr.hir_id, (container, field_indices));
4011
4012        self.tcx.types.usize
4013    }
4014}