Skip to main content

rustc_hir_typeck/
expr.rs

1// ignore-tidy-file-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 as ast;
10use rustc_ast::util::parser::ExprPrecedence;
11use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12use rustc_data_structures::stack::ensure_sufficient_stack;
13use rustc_data_structures::unord::UnordMap;
14use rustc_errors::codes::*;
15use rustc_errors::{
16    Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, Subdiagnostic, listify, pluralize,
17    struct_span_code_err,
18};
19use rustc_hir as hir;
20use rustc_hir::def::{CtorKind, DefKind, Res};
21use rustc_hir::def_id::DefId;
22use rustc_hir::lang_items::LangItem;
23use rustc_hir::{ExprKind, HirId, QPath, find_attr, is_range_literal};
24use rustc_hir_analysis::NoVariantNamed;
25use rustc_hir_analysis::diagnostics::NoFieldOnType;
26use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _;
27use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk, RegionVariableOrigin};
28use rustc_infer::traits::query::NoSolution;
29use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
30use rustc_middle::ty::error::{ExpectedFound, TypeError};
31use rustc_middle::ty::{self, AdtKind, GenericArgsRef, Ty, TypeVisitableExt, Unnormalized};
32use rustc_middle::{bug, span_bug};
33use rustc_session::diagnostics::{ExprParenthesesNeeded, feature_err};
34use rustc_span::edit_distance::find_best_match_for_name;
35use rustc_span::hygiene::DesugaringKind;
36use rustc_span::{Ident, Span, Spanned, Symbol, kw, sym};
37use rustc_trait_selection::infer::InferCtxtExt;
38use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt};
39use tracing::{debug, instrument, trace};
40
41use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation};
42use crate::coercion::CoerceMany;
43use crate::diagnostics::{
44    AddressOfTemporaryTaken, BaseExpressionDoubleDot, BaseExpressionDoubleDotAddExpr,
45    BaseExpressionDoubleDotRemove, CantDereference, FieldMultiplySpecifiedInInitializer,
46    FunctionalRecordUpdateOnNonStruct, HelpUseLatestEdition, NakedAsmOutsideNakedFn,
47    NoFieldOnVariant, ReturnLikeStatementKind, ReturnStmtOutsideOfFnBody, StructExprNonExhaustive,
48    TypeMismatchFruTypo, YieldExprOutsideOfCoroutine,
49};
50use crate::op::contains_let_in_chain;
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            self.tcx.hir_attrs(id).iter().any(hir::Attribute::is_prefix_attr_for_suggestions)
60        };
61
62        // Special case: range expressions are desugared to struct literals in HIR,
63        // so they would normally return `Unambiguous` precedence in expr.precedence.
64        // we should return `Range` precedence for correct parenthesization in suggestions.
65        if is_range_literal(expr) {
66            return ExprPrecedence::Range;
67        }
68
69        expr.precedence(&has_attr)
70    }
71
72    /// Check an expr with an expectation type, and also demand that the expr's
73    /// evaluated type is a subtype of the expectation at the end. This is a
74    /// *hard* requirement.
75    pub(crate) fn check_expr_has_type_or_error(
76        &self,
77        expr: &'tcx hir::Expr<'tcx>,
78        expected_ty: Ty<'tcx>,
79        extend_err: impl FnOnce(&mut Diag<'_>),
80    ) -> Ty<'tcx> {
81        let mut ty = self.check_expr_with_expectation(expr, ExpectHasType(expected_ty));
82
83        // While we don't allow *arbitrary* coercions here, we *do* allow
84        // coercions from ! to `expected`.
85        if self.resolve_vars_with_obligations(ty).is_never()
86            && self.tcx.expr_guaranteed_to_constitute_read_for_never(expr)
87        {
88            if let Some(adjustments) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
89                let reported = self.dcx().span_delayed_bug(
90                    expr.span,
91                    "expression with never type wound up being adjusted",
92                );
93
94                return if let [Adjustment { kind: Adjust::NeverToAny, target }] = &adjustments[..] {
95                    target.to_owned()
96                } else {
97                    Ty::new_error(self.tcx(), reported)
98                };
99            }
100
101            let adj_ty = self.next_ty_var(expr.span);
102            self.apply_adjustments(
103                expr,
104                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Adjustment { kind: Adjust::NeverToAny, target: adj_ty }]))vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }],
105            );
106            ty = adj_ty;
107        }
108
109        if let Err(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
110            let _ = self.emit_type_mismatch_suggestions(
111                &mut err,
112                expr.peel_drop_temps(),
113                ty,
114                expected_ty,
115                None,
116                None,
117            );
118            extend_err(&mut err);
119            err.emit();
120        }
121        ty
122    }
123
124    /// Check an expr with an expectation type, and also demand that the expr's
125    /// evaluated type is a coercible to the expectation at the end. This is a
126    /// *hard* requirement.
127    pub(super) fn check_expr_coercible_to_type(
128        &self,
129        expr: &'tcx hir::Expr<'tcx>,
130        expected: Ty<'tcx>,
131        expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
132    ) -> Ty<'tcx> {
133        self.check_expr_coercible_to_type_or_error(expr, expected, expected_ty_expr, |_, _| {})
134    }
135
136    pub(crate) fn check_expr_coercible_to_type_or_error(
137        &self,
138        expr: &'tcx hir::Expr<'tcx>,
139        expected: Ty<'tcx>,
140        expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
141        extend_err: impl FnOnce(&mut Diag<'_>, Ty<'tcx>),
142    ) -> Ty<'tcx> {
143        let ty = self.check_expr_with_hint(expr, expected);
144        // checks don't need two phase
145        match self.demand_coerce_diag(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No) {
146            Ok(ty) => ty,
147            Err(mut err) => {
148                extend_err(&mut err, ty);
149                err.emit();
150                // Return the original type instead of an error type here, otherwise the type of `x` in
151                // `let x: u32 = ();` will be a type error, causing all subsequent usages of `x` to not
152                // report errors, even though `x` is definitely `u32`.
153                expected
154            }
155        }
156    }
157
158    /// Check an expr with an expectation type. Don't actually enforce that expectation
159    /// is related to the expr's evaluated type via subtyping or coercion. This is
160    /// usually called because we want to do that subtype/coerce call manually for better
161    /// diagnostics.
162    pub(super) fn check_expr_with_hint(
163        &self,
164        expr: &'tcx hir::Expr<'tcx>,
165        expected: Ty<'tcx>,
166    ) -> Ty<'tcx> {
167        self.check_expr_with_expectation(expr, ExpectHasType(expected))
168    }
169
170    /// Check an expr with an expectation type, and also [`Needs`] which will
171    /// prompt typeck to convert any implicit immutable derefs to mutable derefs.
172    fn check_expr_with_expectation_and_needs(
173        &self,
174        expr: &'tcx hir::Expr<'tcx>,
175        expected: Expectation<'tcx>,
176        needs: Needs,
177    ) -> Ty<'tcx> {
178        let ty = self.check_expr_with_expectation(expr, expected);
179
180        // If the expression is used in a place whether mutable place is required
181        // e.g. LHS of assignment, perform the conversion.
182        if let Needs::MutPlace = needs {
183            self.convert_place_derefs_to_mutable(expr);
184        }
185
186        ty
187    }
188
189    /// Check an expr with no expectations.
190    pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
191        self.check_expr_with_expectation(expr, NoExpectation)
192    }
193
194    /// Check an expr with no expectations, but with [`Needs`] which will
195    /// prompt typeck to convert any implicit immutable derefs to mutable derefs.
196    pub(super) fn check_expr_with_needs(
197        &self,
198        expr: &'tcx hir::Expr<'tcx>,
199        needs: Needs,
200    ) -> Ty<'tcx> {
201        self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
202    }
203
204    /// Check an expr with an expectation type which may be used to eagerly
205    /// guide inference when evaluating that expr.
206    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_expr_with_expectation",
                                    "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(206u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                                    ::tracing_core::field::FieldSet::new(&["expected"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        { self.check_expr_with_expectation_and_args(expr, expected, None) }
    }
}#[instrument(skip(self, expr), level = "debug")]
207    pub(super) fn check_expr_with_expectation(
208        &self,
209        expr: &'tcx hir::Expr<'tcx>,
210        expected: Expectation<'tcx>,
211    ) -> Ty<'tcx> {
212        self.check_expr_with_expectation_and_args(expr, expected, None)
213    }
214
215    /// Same as [`Self::check_expr_with_expectation`], but allows us to pass in
216    /// the arguments of a [`ExprKind::Call`] when evaluating its callee that
217    /// is an [`ExprKind::Path`]. We use this to refine the spans for certain
218    /// well-formedness guarantees for the path expr.
219    pub(super) fn check_expr_with_expectation_and_args(
220        &self,
221        expr: &'tcx hir::Expr<'tcx>,
222        expected: Expectation<'tcx>,
223        call_expr_and_args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
224    ) -> Ty<'tcx> {
225        if self.tcx().sess.verbose_internals() {
226            // make this code only run with -Zverbose-internals because it is probably slow
227            if let Ok(lint_str) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
228                if !lint_str.contains('\n') {
229                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:229",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(229u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("expr text: {0}",
                                                    lint_str) as &dyn Value))])
            });
    } else { ; }
};debug!("expr text: {lint_str}");
230                } else {
231                    let mut lines = lint_str.lines();
232                    if let Some(line0) = lines.next() {
233                        let remaining_lines = lines.count();
234                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:234",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(234u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("expr text: {0}",
                                                    line0) as &dyn Value))])
            });
    } else { ; }
};debug!("expr text: {line0}");
235                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:235",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(235u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("expr text: ...(and {0} more lines)",
                                                    remaining_lines) as &dyn Value))])
            });
    } else { ; }
};debug!("expr text: ...(and {remaining_lines} more lines)");
236                    }
237                }
238            }
239        }
240
241        // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
242        // without the final expr (e.g. `try { return; }`). We don't want to generate an
243        // unreachable_code lint for it since warnings for autogenerated code are confusing.
244        let is_try_block_generated_unit_expr = match expr.kind {
245            ExprKind::Call(_, [arg]) => {
246                expr.span.is_desugaring(DesugaringKind::TryBlock)
247                    && arg.span.is_desugaring(DesugaringKind::TryBlock)
248            }
249            _ => false,
250        };
251
252        // Warn for expressions after diverging siblings.
253        if !is_try_block_generated_unit_expr {
254            self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
255        }
256
257        // Whether a past expression diverges doesn't affect typechecking of this expression, so we
258        // reset `diverges` while checking `expr`.
259        let old_diverges = self.diverges.replace(Diverges::Maybe);
260
261        if self.is_whole_body.replace(false) {
262            // If this expression is the whole body and the function diverges because of its
263            // arguments, we check this here to ensure the body is considered to diverge.
264            self.diverges.set(self.function_diverges_because_of_empty_arguments.get())
265        };
266
267        let ty = ensure_sufficient_stack(|| match &expr.kind {
268            // Intercept the callee path expr and give it better spans.
269            hir::ExprKind::Path(
270                qpath @ (hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)),
271            ) => self.check_expr_path(qpath, expr, call_expr_and_args),
272            _ => self.check_expr_kind(expr, expected),
273        });
274        let ty = self.resolve_vars_if_possible(ty);
275
276        // Warn for non-block expressions with diverging children.
277        match expr.kind {
278            ExprKind::Block(..)
279            | ExprKind::If(..)
280            | ExprKind::Let(..)
281            | ExprKind::Loop(..)
282            | ExprKind::Match(..) => {}
283            // Do not warn on `as` casts from never to any,
284            // they are sometimes required to appeal typeck.
285            ExprKind::Cast(_, _) => {}
286            // If `expr` is a result of desugaring the try block and is an ok-wrapped
287            // diverging expression (e.g. it arose from desugaring of `try { return }`),
288            // we skip issuing a warning because it is autogenerated code.
289            ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {}
290            // Likewise, do not lint unreachable code injected via contracts desugaring.
291            ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::Contract) => {}
292            ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"),
293            ExprKind::MethodCall(segment, ..) => {
294                self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call")
295            }
296            _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
297        }
298
299        // Any expression that produces a value of type `!` must have diverged,
300        // unless it's a place expression that isn't being read from, in which case
301        // diverging would be unsound since we may never actually read the `!`.
302        // e.g. `let _ = *never_ptr;` with `never_ptr: *const !`.
303        if self.resolve_vars_with_obligations(ty).is_never()
304            && self.tcx.expr_guaranteed_to_constitute_read_for_never(expr)
305        {
306            self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
307        }
308
309        // Record the type, which applies it effects.
310        // We need to do this after the warning above, so that
311        // we don't warn for the diverging expression itself.
312        self.write_ty(expr.hir_id, ty);
313
314        // Combine the diverging and has_error flags.
315        self.diverges.set(self.diverges.get() | old_diverges);
316
317        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:317",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(317u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("type of {0} is...",
                                                    self.tcx.hir_id_to_string(expr.hir_id)) as &dyn Value))])
            });
    } else { ; }
};debug!("type of {} is...", self.tcx.hir_id_to_string(expr.hir_id));
318        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:318",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(318u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("... {0:?}, expected is {1:?}",
                                                    ty, expected) as &dyn Value))])
            });
    } else { ; }
};debug!("... {:?}, expected is {:?}", ty, expected);
319
320        ty
321    }
322
323    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_expr_kind",
                                    "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(323u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                                    ::tracing_core::field::FieldSet::new(&["expected"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Ty<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:329",
                                    "rustc_hir_typeck::expr", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(329u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("expr={0:#?}",
                                                                expr) as &dyn Value))])
                        });
                } else { ; }
            };
            let tcx = self.tcx;
            match expr.kind {
                ExprKind::Lit(ref lit) =>
                    self.check_expr_lit(lit, expr.hir_id, expected),
                ExprKind::Binary(op, lhs, rhs) =>
                    self.check_expr_binop(expr, op, lhs, rhs, expected),
                ExprKind::Assign(lhs, rhs, span) => {
                    self.check_expr_assign(expr, expected, lhs, rhs, span)
                }
                ExprKind::AssignOp(op, lhs, rhs) => {
                    self.check_expr_assign_op(expr, op, lhs, rhs, expected)
                }
                ExprKind::Unary(unop, oprnd) =>
                    self.check_expr_unop(unop, oprnd, expected, expr),
                ExprKind::AddrOf(kind, mutbl, oprnd) => {
                    self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
                }
                ExprKind::Path(ref qpath) =>
                    self.check_expr_path(qpath, expr, None),
                ExprKind::InlineAsm(asm) => {
                    self.deferred_asm_checks.borrow_mut().push((asm,
                            expr.hir_id));
                    self.check_expr_asm(asm, expr.span)
                }
                ExprKind::OffsetOf(container, fields) => {
                    self.check_expr_offset_of(container, fields, expr)
                }
                ExprKind::Break(destination, ref expr_opt) => {
                    self.check_expr_break(destination, expr_opt.as_deref(),
                        expr)
                }
                ExprKind::Continue(destination) =>
                    self.check_expr_continue(destination, expr),
                ExprKind::Ret(ref expr_opt) =>
                    self.check_expr_return(expr_opt.as_deref(), expr),
                ExprKind::Become(call) => self.check_expr_become(call, expr),
                ExprKind::Let(let_expr) =>
                    self.check_expr_let(let_expr, expr.hir_id),
                ExprKind::Loop(body, _, source, _) => {
                    self.check_expr_loop(body, source, expected, expr)
                }
                ExprKind::Match(discrim, arms, match_src) => {
                    self.check_expr_match(expr, discrim, arms, expected,
                        match_src)
                }
                ExprKind::Closure(closure) =>
                    self.check_expr_closure(closure, expr.span, expected),
                ExprKind::Block(body, _) =>
                    self.check_expr_block(body, expected),
                ExprKind::Call(callee, args) =>
                    self.check_expr_call(expr, callee, args, expected),
                ExprKind::Use(used_expr, _) =>
                    self.check_expr_use(used_expr, expected),
                ExprKind::MethodCall(segment, receiver, args, _) => {
                    self.check_expr_method_call(expr, segment, receiver, args,
                        expected)
                }
                ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr),
                ExprKind::Type(e, t) => {
                    let ascribed_ty = self.lower_ty_saving_user_provided_ty(t);
                    let ty = self.check_expr_with_hint(e, ascribed_ty);
                    self.demand_eqtype(e.span, ascribed_ty, ty);
                    ascribed_ty
                }
                ExprKind::If(cond, then_expr, opt_else_expr) => {
                    self.check_expr_if(expr.hir_id, cond, then_expr,
                        opt_else_expr, expr.span, expected)
                }
                ExprKind::DropTemps(e) =>
                    self.check_expr_with_expectation(e, expected),
                ExprKind::Array(args) =>
                    self.check_expr_array(args, expected, expr),
                ExprKind::ConstBlock(ref block) =>
                    self.check_expr_const_block(block, expected),
                ExprKind::Repeat(element, ref count) => {
                    self.check_expr_repeat(element, count, expected, expr)
                }
                ExprKind::Tup(elts) =>
                    self.check_expr_tuple(elts, expected, expr),
                ExprKind::Struct(qpath, fields, ref base_expr) => {
                    self.check_expr_struct(expr, expected, qpath, fields,
                        base_expr)
                }
                ExprKind::Field(base, field) =>
                    self.check_expr_field(expr, base, field, expected),
                ExprKind::Index(base, idx, brackets_span) => {
                    self.check_expr_index(base, idx, expr, brackets_span)
                }
                ExprKind::Yield(value, _) =>
                    self.check_expr_yield(value, expr),
                ExprKind::UnsafeBinderCast(kind, inner_expr, ty) => {
                    self.check_expr_unsafe_binder_cast(expr.span, kind,
                        inner_expr, ty, expected)
                }
                ExprKind::Err(guar) => Ty::new_error(tcx, guar),
            }
        }
    }
}#[instrument(skip(self, expr), level = "debug")]
324    fn check_expr_kind(
325        &self,
326        expr: &'tcx hir::Expr<'tcx>,
327        expected: Expectation<'tcx>,
328    ) -> Ty<'tcx> {
329        trace!("expr={:#?}", expr);
330
331        let tcx = self.tcx;
332        match expr.kind {
333            ExprKind::Lit(ref lit) => self.check_expr_lit(lit, expr.hir_id, expected),
334            ExprKind::Binary(op, lhs, rhs) => self.check_expr_binop(expr, op, lhs, rhs, expected),
335            ExprKind::Assign(lhs, rhs, span) => {
336                self.check_expr_assign(expr, expected, lhs, rhs, span)
337            }
338            ExprKind::AssignOp(op, lhs, rhs) => {
339                self.check_expr_assign_op(expr, op, lhs, rhs, expected)
340            }
341            ExprKind::Unary(unop, oprnd) => self.check_expr_unop(unop, oprnd, expected, expr),
342            ExprKind::AddrOf(kind, mutbl, oprnd) => {
343                self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
344            }
345            ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr, None),
346            ExprKind::InlineAsm(asm) => {
347                // We defer some asm checks as we may not have resolved the input and output types yet (they may still be infer vars).
348                self.deferred_asm_checks.borrow_mut().push((asm, expr.hir_id));
349                self.check_expr_asm(asm, expr.span)
350            }
351            ExprKind::OffsetOf(container, fields) => {
352                self.check_expr_offset_of(container, fields, expr)
353            }
354            ExprKind::Break(destination, ref expr_opt) => {
355                self.check_expr_break(destination, expr_opt.as_deref(), expr)
356            }
357            ExprKind::Continue(destination) => self.check_expr_continue(destination, expr),
358            ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
359            ExprKind::Become(call) => self.check_expr_become(call, expr),
360            ExprKind::Let(let_expr) => self.check_expr_let(let_expr, expr.hir_id),
361            ExprKind::Loop(body, _, source, _) => {
362                self.check_expr_loop(body, source, expected, expr)
363            }
364            ExprKind::Match(discrim, arms, match_src) => {
365                self.check_expr_match(expr, discrim, arms, expected, match_src)
366            }
367            ExprKind::Closure(closure) => self.check_expr_closure(closure, expr.span, expected),
368            ExprKind::Block(body, _) => self.check_expr_block(body, expected),
369            ExprKind::Call(callee, args) => self.check_expr_call(expr, callee, args, expected),
370            ExprKind::Use(used_expr, _) => self.check_expr_use(used_expr, expected),
371            ExprKind::MethodCall(segment, receiver, args, _) => {
372                self.check_expr_method_call(expr, segment, receiver, args, expected)
373            }
374            ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr),
375            ExprKind::Type(e, t) => {
376                let ascribed_ty = self.lower_ty_saving_user_provided_ty(t);
377                let ty = self.check_expr_with_hint(e, ascribed_ty);
378                self.demand_eqtype(e.span, ascribed_ty, ty);
379                ascribed_ty
380            }
381            ExprKind::If(cond, then_expr, opt_else_expr) => {
382                self.check_expr_if(expr.hir_id, cond, then_expr, opt_else_expr, expr.span, expected)
383            }
384            ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected),
385            ExprKind::Array(args) => self.check_expr_array(args, expected, expr),
386            ExprKind::ConstBlock(ref block) => self.check_expr_const_block(block, expected),
387            ExprKind::Repeat(element, ref count) => {
388                self.check_expr_repeat(element, count, expected, expr)
389            }
390            ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr),
391            ExprKind::Struct(qpath, fields, ref base_expr) => {
392                self.check_expr_struct(expr, expected, qpath, fields, base_expr)
393            }
394            ExprKind::Field(base, field) => self.check_expr_field(expr, base, field, expected),
395            ExprKind::Index(base, idx, brackets_span) => {
396                self.check_expr_index(base, idx, expr, brackets_span)
397            }
398            ExprKind::Yield(value, _) => self.check_expr_yield(value, expr),
399            ExprKind::UnsafeBinderCast(kind, inner_expr, ty) => {
400                self.check_expr_unsafe_binder_cast(expr.span, kind, inner_expr, ty, expected)
401            }
402            ExprKind::Err(guar) => Ty::new_error(tcx, guar),
403        }
404    }
405
406    fn check_expr_unop(
407        &self,
408        unop: hir::UnOp,
409        oprnd: &'tcx hir::Expr<'tcx>,
410        expected: Expectation<'tcx>,
411        expr: &'tcx hir::Expr<'tcx>,
412    ) -> Ty<'tcx> {
413        let tcx = self.tcx;
414        let expected_inner = match unop {
415            hir::UnOp::Not | hir::UnOp::Neg => expected,
416            hir::UnOp::Deref => NoExpectation,
417        };
418        let oprnd_t = self.check_expr_with_expectation(oprnd, expected_inner);
419
420        if let Err(guar) = oprnd_t.error_reported() {
421            return Ty::new_error(tcx, guar);
422        }
423
424        let oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t);
425        match unop {
426            hir::UnOp::Deref => self.lookup_derefing(expr, oprnd, oprnd_t).unwrap_or_else(|| {
427                let mut err =
428                    self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t });
429                let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None);
430                if let Some(sp) = tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
431                    err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
432                }
433                Ty::new_error(tcx, err.emit())
434            }),
435            hir::UnOp::Not => {
436                let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
437                // If it's builtin, we can reuse the type, this helps inference.
438                if oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool { oprnd_t } else { result }
439            }
440            hir::UnOp::Neg => {
441                let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
442                // If it's builtin, we can reuse the type, this helps inference.
443                if oprnd_t.is_numeric() { oprnd_t } else { result }
444            }
445        }
446    }
447
448    fn check_expr_addr_of(
449        &self,
450        kind: hir::BorrowKind,
451        mutbl: hir::Mutability,
452        oprnd: &'tcx hir::Expr<'tcx>,
453        expected: Expectation<'tcx>,
454        expr: &'tcx hir::Expr<'tcx>,
455    ) -> Ty<'tcx> {
456        let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
457            match self.resolve_vars_with_obligations(ty).kind() {
458                ty::Ref(_, ty, _) | ty::RawPtr(ty, _) => {
459                    if oprnd.is_syntactic_place_expr() {
460                        // Places may legitimately have unsized types.
461                        // For example, dereferences of a wide pointer and
462                        // the last field of a struct can be unsized.
463                        ExpectHasType(*ty)
464                    } else {
465                        Expectation::rvalue_hint(self, *ty)
466                    }
467                }
468                _ => NoExpectation,
469            }
470        });
471        let ty =
472            self.check_expr_with_expectation_and_needs(oprnd, hint, Needs::maybe_mut_place(mutbl));
473        if let Err(guar) = ty.error_reported() {
474            return Ty::new_error(self.tcx, guar);
475        }
476
477        match kind {
478            hir::BorrowKind::Raw => {
479                self.check_named_place_expr(oprnd);
480                Ty::new_ptr(self.tcx, ty, mutbl)
481            }
482            hir::BorrowKind::Ref | hir::BorrowKind::Pin => {
483                // Note: at this point, we cannot say what the best lifetime
484                // is to use for resulting pointer. We want to use the
485                // shortest lifetime possible so as to avoid spurious borrowck
486                // errors. Moreover, the longest lifetime will depend on the
487                // precise details of the value whose address is being taken
488                // (and how long it is valid), which we don't know yet until
489                // type inference is complete.
490                //
491                // Therefore, here we simply generate a region variable. The
492                // region inferencer will then select a suitable value.
493                // Finally, borrowck will infer the value of the region again,
494                // this time with enough precision to check that the value
495                // whose address was taken can actually be made to live as long
496                // as it needs to live.
497                let region = self.next_region_var(RegionVariableOrigin::BorrowRegion(expr.span));
498                match kind {
499                    hir::BorrowKind::Ref => Ty::new_ref(self.tcx, region, ty, mutbl),
500                    hir::BorrowKind::Pin => Ty::new_pinned_ref(self.tcx, region, ty, mutbl),
501                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
502                }
503            }
504        }
505    }
506
507    /// Does this expression refer to a place that either:
508    /// * Is based on a local or static.
509    /// * Contains a dereference
510    /// Note that the adjustments for the children of `expr` should already
511    /// have been resolved.
512    fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
513        let is_named = oprnd.is_place_expr(|base| {
514            // Allow raw borrows if there are any deref adjustments.
515            //
516            // const VAL: (i32,) = (0,);
517            // const REF: &(i32,) = &(0,);
518            //
519            // &raw const VAL.0;            // ERROR
520            // &raw const REF.0;            // OK, same as &raw const (*REF).0;
521            //
522            // This is maybe too permissive, since it allows
523            // `let u = &raw const Box::new((1,)).0`, which creates an
524            // immediately dangling raw pointer.
525            self.typeck_results
526                .borrow()
527                .adjustments()
528                .get(base.hir_id)
529                .is_some_and(|x| x.iter().any(|adj| #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
    Adjust::Deref(_) => true,
    _ => false,
}matches!(adj.kind, Adjust::Deref(_))))
530        });
531        if !is_named {
532            self.dcx().emit_err(AddressOfTemporaryTaken { span: oprnd.span });
533        }
534    }
535
536    pub(crate) fn check_expr_path(
537        &self,
538        qpath: &'tcx hir::QPath<'tcx>,
539        expr: &'tcx hir::Expr<'tcx>,
540        call_expr_and_args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
541    ) -> Ty<'tcx> {
542        let tcx = self.tcx;
543
544        if let Some((_, [arg])) = call_expr_and_args
545            && let QPath::Resolved(_, path) = qpath
546            && let Res::Def(_, def_id) = path.res
547            && let Some(lang_item) = tcx.lang_items().from_def_id(def_id)
548        {
549            let code = match lang_item {
550                LangItem::IntoFutureIntoFuture
551                    if expr.span.is_desugaring(DesugaringKind::Await) =>
552                {
553                    Some(ObligationCauseCode::AwaitableExpr(arg.hir_id))
554                }
555                LangItem::IntoIterIntoIter | LangItem::IteratorNext
556                    if expr.span.is_desugaring(DesugaringKind::ForLoop) =>
557                {
558                    Some(ObligationCauseCode::ForLoopIterator)
559                }
560                LangItem::TryTraitFromOutput
561                    if expr.span.is_desugaring(DesugaringKind::TryBlock) =>
562                {
563                    // FIXME it's a try block, not a question mark
564                    Some(ObligationCauseCode::QuestionMark)
565                }
566                LangItem::TryTraitBranch | LangItem::TryTraitFromResidual
567                    if expr.span.is_desugaring(DesugaringKind::QuestionMark) =>
568                {
569                    Some(ObligationCauseCode::QuestionMark)
570                }
571                _ => None,
572            };
573            if let Some(code) = code {
574                let args = self.fresh_args_for_item(expr.span, def_id);
575                self.add_required_obligations_with_code(expr.span, def_id, args, |_, _| {
576                    code.clone()
577                });
578                return tcx.type_of(def_id).instantiate(tcx, args).skip_norm_wip();
579            }
580        }
581
582        let (res, opt_ty, segs) =
583            self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span);
584        let ty = match res {
585            Res::Err => {
586                self.suggest_assoc_method_call(segs);
587                let e =
588                    self.dcx().span_delayed_bug(qpath.span(), "`Res::Err` but no error emitted");
589                Ty::new_error(tcx, e)
590            }
591            Res::Def(DefKind::Variant, _) => {
592                let e = report_unexpected_variant_res(
593                    tcx,
594                    res,
595                    Some(expr),
596                    qpath,
597                    expr.span,
598                    E0533,
599                    "value",
600                );
601                Ty::new_error(tcx, e)
602            }
603            _ => {
604                self.instantiate_value_path(
605                    segs,
606                    opt_ty,
607                    res,
608                    call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
609                    expr.span,
610                    expr.hir_id,
611                )
612                .0
613            }
614        };
615
616        if let ty::FnDef(did, _) = *ty.kind() {
617            let fn_sig = ty.fn_sig(tcx);
618
619            if tcx.is_intrinsic(did, sym::transmute) {
620                let Some(from) = fn_sig.inputs().skip_binder().get(0) else {
621                    ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(did),
    format_args!("intrinsic fn `transmute` defined with no parameters"));span_bug!(
622                        tcx.def_span(did),
623                        "intrinsic fn `transmute` defined with no parameters"
624                    );
625                };
626                let to = fn_sig.output().skip_binder();
627                // We defer the transmute to the end of typeck, once all inference vars have
628                // been resolved or we errored. This is important as we can only check transmute
629                // on concrete types, but the output type may not be known yet (it would only
630                // be known if explicitly specified via turbofish).
631                self.deferred_transmute_checks.borrow_mut().push((*from, to, expr.hir_id));
632            }
633            if !tcx.features().unsized_fn_params() {
634                // We want to remove some Sized bounds from std functions,
635                // but don't want to expose the removal to stable Rust.
636                // i.e., we don't want to allow
637                //
638                // ```rust
639                // drop as fn(str);
640                // ```
641                //
642                // to work in stable even if the Sized bound on `drop` is relaxed.
643                for i in 0..fn_sig.inputs().skip_binder().len() {
644                    // We just want to check sizedness, so instead of introducing
645                    // placeholder lifetimes with probing, we just replace higher lifetimes
646                    // with fresh vars.
647                    let span = call_expr_and_args
648                        .and_then(|(_, args)| args.get(i))
649                        .map_or(expr.span, |arg| arg.span);
650                    let input = self.instantiate_binder_with_fresh_vars(
651                        span,
652                        infer::BoundRegionConversionTime::FnCall,
653                        fn_sig.input(i),
654                    );
655                    self.require_type_is_sized_deferred(
656                        input,
657                        span,
658                        ObligationCauseCode::SizedArgumentType(None),
659                    );
660                }
661            }
662            // Here we want to prevent struct constructors from returning unsized types,
663            // which can happen with fn pointer coercion on stable.
664            // Also, as we just want to check sizedness, instead of introducing
665            // placeholder lifetimes with probing, we just replace higher lifetimes
666            // with fresh vars.
667            let output = self.instantiate_binder_with_fresh_vars(
668                expr.span,
669                infer::BoundRegionConversionTime::FnCall,
670                fn_sig.output(),
671            );
672            self.require_type_is_sized_deferred(
673                output,
674                call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
675                ObligationCauseCode::SizedCallReturnType,
676            );
677        }
678
679        // We always require that the type provided as the value for
680        // a type parameter outlives the moment of instantiation.
681        let args = self.typeck_results.borrow().node_args(expr.hir_id);
682        self.add_wf_bounds(args, expr.span);
683
684        ty
685    }
686
687    fn check_expr_break(
688        &self,
689        destination: hir::Destination,
690        expr_opt: Option<&'tcx hir::Expr<'tcx>>,
691        expr: &'tcx hir::Expr<'tcx>,
692    ) -> Ty<'tcx> {
693        let tcx = self.tcx;
694        if let Ok(target_id) = destination.target_id {
695            let (e_ty, cause);
696            if let Some(e) = expr_opt {
697                // If this is a break with a value, we need to type-check
698                // the expression. Get an expected type from the loop context.
699                let opt_coerce_to = {
700                    // We should release `enclosing_breakables` before the `check_expr_with_hint`
701                    // below, so can't move this block of code to the enclosing scope and share
702                    // `ctxt` with the second `enclosing_breakables` borrow below.
703                    let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
704                    match enclosing_breakables.opt_find_breakable(target_id) {
705                        Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
706                        None => {
707                            // Avoid ICE when `break` is inside a closure (#65383).
708                            return Ty::new_error_with_message(
709                                tcx,
710                                expr.span,
711                                "break was outside loop, but no error was emitted",
712                            );
713                        }
714                    }
715                };
716
717                // If the loop context is not a `loop { }`, then break with
718                // a value is illegal, and `opt_coerce_to` will be `None`.
719                // Set expectation to error in that case and set tainted
720                // by error (#114529)
721                let coerce_to = opt_coerce_to.unwrap_or_else(|| {
722                    let guar = self.dcx().span_delayed_bug(
723                        expr.span,
724                        "illegal break with value found but no error reported",
725                    );
726                    self.set_tainted_by_errors(guar);
727                    Ty::new_error(tcx, guar)
728                });
729
730                // Recurse without `enclosing_breakables` borrowed.
731                e_ty = self.check_expr_with_hint(e, coerce_to);
732                cause = self.misc(e.span);
733            } else {
734                // Otherwise, this is a break *without* a value. That's
735                // always legal, and is equivalent to `break ()`.
736                e_ty = tcx.types.unit;
737                cause = self.misc(expr.span);
738            }
739
740            // Now that we have type-checked `expr_opt`, borrow
741            // the `enclosing_loops` field and let's coerce the
742            // type of `expr_opt` into what is expected.
743            let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
744            let Some(ctxt) = enclosing_breakables.opt_find_breakable(target_id) else {
745                // Avoid ICE when `break` is inside a closure (#65383).
746                return Ty::new_error_with_message(
747                    tcx,
748                    expr.span,
749                    "break was outside loop, but no error was emitted",
750                );
751            };
752
753            if let Some(ref mut coerce) = ctxt.coerce {
754                if let Some(e) = expr_opt {
755                    coerce.coerce(self, &cause, e, e_ty);
756                } else {
757                    if !e_ty.is_unit() {
    ::core::panicking::panic("assertion failed: e_ty.is_unit()")
};assert!(e_ty.is_unit());
758                    let ty = coerce.expected_ty();
759                    coerce.coerce_forced_unit(
760                        self,
761                        &cause,
762                        |mut err| {
763                            self.suggest_missing_semicolon(&mut err, expr, e_ty, false, false);
764                            self.suggest_mismatched_types_on_tail(
765                                &mut err, expr, ty, e_ty, target_id,
766                            );
767                            let error =
768                                Some(TypeError::Sorts(ExpectedFound { expected: ty, found: e_ty }));
769                            self.annotate_loop_expected_due_to_inference(err, expr, error);
770                            if let Some(val) =
771                                self.err_ctxt().ty_kind_suggestion(self.param_env, ty)
772                            {
773                                err.span_suggestion_verbose(
774                                    expr.span.shrink_to_hi(),
775                                    "give the `break` a value of the expected type",
776                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {0}", val))
    })format!(" {val}"),
777                                    Applicability::HasPlaceholders,
778                                );
779                            }
780                        },
781                        false,
782                    );
783                }
784            } else {
785                // If `ctxt.coerce` is `None`, we can just ignore
786                // the type of the expression. This is because
787                // either this was a break *without* a value, in
788                // which case it is always a legal type (`()`), or
789                // else an error would have been flagged by the
790                // `loops` pass for using break with an expression
791                // where you are not supposed to.
792                if !(expr_opt.is_none() || self.tainted_by_errors().is_some()) {
    ::core::panicking::panic("assertion failed: expr_opt.is_none() || self.tainted_by_errors().is_some()")
};assert!(expr_opt.is_none() || self.tainted_by_errors().is_some());
793            }
794
795            // If we encountered a `break`, then (no surprise) it may be possible to break from the
796            // loop... unless the value being returned from the loop diverges itself, e.g.
797            // `break return 5` or `break loop {}`.
798            ctxt.may_break |= !self.diverges.get().is_always();
799
800            // the type of a `break` is always `!`, since it diverges
801            tcx.types.never
802        } else {
803            // Otherwise, we failed to find the enclosing loop;
804            // this can only happen if the `break` was not
805            // inside a loop at all, which is caught by the
806            // loop-checking pass.
807            let err = Ty::new_error_with_message(
808                self.tcx,
809                expr.span,
810                "break was outside loop, but no error was emitted",
811            );
812
813            // We still need to assign a type to the inner expression to
814            // prevent the ICE in #43162.
815            if let Some(e) = expr_opt {
816                self.check_expr_with_hint(e, err);
817
818                // ... except when we try to 'break rust;'.
819                // ICE this expression in particular (see #43162).
820                if let ExprKind::Path(QPath::Resolved(_, path)) = e.kind {
821                    if let [segment] = path.segments
822                        && segment.ident.name == sym::rust
823                    {
824                        fatally_break_rust(self.tcx, expr.span);
825                    }
826                }
827            }
828
829            // There was an error; make type-check fail.
830            err
831        }
832    }
833
834    fn check_expr_continue(
835        &self,
836        destination: hir::Destination,
837        expr: &'tcx hir::Expr<'tcx>,
838    ) -> Ty<'tcx> {
839        if let Ok(target_id) = destination.target_id {
840            if let hir::Node::Expr(hir::Expr { kind: ExprKind::Loop(..), .. }) =
841                self.tcx.hir_node(target_id)
842            {
843                self.tcx.types.never
844            } else {
845                // Liveness linting assumes `continue`s all point to loops. We'll report an error
846                // in `check_mod_loops`, but make sure we don't run liveness (#113379, #121623).
847                let guar = self.dcx().span_delayed_bug(
848                    expr.span,
849                    "found `continue` not pointing to loop, but no error reported",
850                );
851                Ty::new_error(self.tcx, guar)
852            }
853        } else {
854            // There was an error; make type-check fail.
855            Ty::new_misc_error(self.tcx)
856        }
857    }
858
859    fn check_expr_return(
860        &self,
861        expr_opt: Option<&'tcx hir::Expr<'tcx>>,
862        expr: &'tcx hir::Expr<'tcx>,
863    ) -> Ty<'tcx> {
864        if self.ret_coercion.is_none() {
865            self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Return);
866
867            if let Some(e) = expr_opt {
868                // We still have to type-check `e` (issue #86188), but calling
869                // `check_return_expr` only works inside fn bodies.
870                self.check_expr(e);
871            }
872        } else if let Some(e) = expr_opt {
873            if self.ret_coercion_span.get().is_none() {
874                self.ret_coercion_span.set(Some(e.span));
875            }
876            self.check_return_or_body_tail(e, true);
877        } else {
878            let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
879            if self.ret_coercion_span.get().is_none() {
880                self.ret_coercion_span.set(Some(expr.span));
881            }
882            let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
883            if let Some((_, fn_decl)) = self.get_fn_decl(expr.hir_id) {
884                coercion.coerce_forced_unit(
885                    self,
886                    &cause,
887                    |db| {
888                        let span = fn_decl.output.span();
889                        if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
890                            db.span_label(
891                                span,
892                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected `{0}` because of this return type",
                snippet))
    })format!("expected `{snippet}` because of this return type"),
893                            );
894                        }
895                    },
896                    true,
897                );
898            } else {
899                coercion.coerce_forced_unit(self, &cause, |_| (), true);
900            }
901        }
902        self.tcx.types.never
903    }
904
905    fn check_expr_become(
906        &self,
907        call: &'tcx hir::Expr<'tcx>,
908        expr: &'tcx hir::Expr<'tcx>,
909    ) -> Ty<'tcx> {
910        match &self.ret_coercion {
911            Some(ret_coercion) => {
912                let ret_ty = ret_coercion.borrow().expected_ty();
913                let call_expr_ty = self.check_expr_with_hint(call, ret_ty);
914
915                // N.B. don't coerce here, as tail calls can't support most/all coercions
916                // FIXME(explicit_tail_calls): add a diagnostic note that `become` doesn't allow coercions
917                self.demand_suptype(expr.span, ret_ty, call_expr_ty);
918            }
919            None => {
920                self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Become);
921
922                // Fallback to simply type checking `call` without hint/demanding the right types.
923                // Best effort to highlight more errors.
924                self.check_expr(call);
925            }
926        }
927
928        self.tcx.types.never
929    }
930
931    /// Check an expression that _is being returned_.
932    /// For example, this is called with `return_expr: $expr` when `return $expr`
933    /// is encountered.
934    ///
935    /// Note that this function must only be called in function bodies.
936    ///
937    /// `explicit_return` is `true` if we're checking an explicit `return expr`,
938    /// and `false` if we're checking a trailing expression.
939    pub(super) fn check_return_or_body_tail(
940        &self,
941        return_expr: &'tcx hir::Expr<'tcx>,
942        explicit_return: bool,
943    ) {
944        let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
945            ::rustc_middle::util::bug::span_bug_fmt(return_expr.span,
    format_args!("check_return_expr called outside fn body"))span_bug!(return_expr.span, "check_return_expr called outside fn body")
946        });
947
948        let ret_ty = ret_coercion.borrow().expected_ty();
949        let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
950        let mut span = return_expr.span;
951        let mut hir_id = return_expr.hir_id;
952        // Use the span of the trailing expression for our cause,
953        // not the span of the entire function
954        if !explicit_return
955            && let ExprKind::Block(body, _) = return_expr.kind
956            && let Some(last_expr) = body.expr
957        {
958            span = last_expr.span;
959            hir_id = last_expr.hir_id;
960        }
961        ret_coercion.borrow_mut().coerce(
962            self,
963            &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
964            return_expr,
965            return_expr_ty,
966        );
967
968        if let Some(fn_sig) = self.fn_sig()
969            && fn_sig.output().has_opaque_types()
970        {
971            // Point any obligations that were registered due to opaque type
972            // inference at the return expression.
973            self.select_obligations_where_possible(|errors| {
974                self.point_at_return_for_opaque_ty_error(
975                    errors,
976                    hir_id,
977                    span,
978                    return_expr_ty,
979                    return_expr.span,
980                );
981            });
982        }
983    }
984
985    /// Emit an error because `return` or `become` is used outside of a function body.
986    ///
987    /// `expr` is the `return` (`become`) "statement", `kind` is the kind of the statement
988    /// either `Return` or `Become`.
989    fn emit_return_outside_of_fn_body(&self, expr: &hir::Expr<'_>, kind: ReturnLikeStatementKind) {
990        let mut err = ReturnStmtOutsideOfFnBody {
991            span: expr.span,
992            encl_body_span: None,
993            encl_fn_span: None,
994            statement_kind: kind,
995        };
996
997        let encl_item_id = self.tcx.hir_get_parent_item(expr.hir_id);
998
999        if let hir::Node::Item(hir::Item {
1000            kind: hir::ItemKind::Fn { .. },
1001            span: encl_fn_span,
1002            ..
1003        })
1004        | hir::Node::TraitItem(hir::TraitItem {
1005            kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
1006            span: encl_fn_span,
1007            ..
1008        })
1009        | hir::Node::ImplItem(hir::ImplItem {
1010            kind: hir::ImplItemKind::Fn(..),
1011            span: encl_fn_span,
1012            ..
1013        }) = self.tcx.hir_node_by_def_id(encl_item_id.def_id)
1014        {
1015            // We are inside a function body, so reporting "return statement
1016            // outside of function body" needs an explanation.
1017
1018            let encl_body_owner_id = self.tcx.hir_enclosing_body_owner(expr.hir_id);
1019
1020            // If this didn't hold, we would not have to report an error in
1021            // the first place.
1022            {
    match (&encl_item_id.def_id, &encl_body_owner_id) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_ne!(encl_item_id.def_id, encl_body_owner_id);
1023
1024            let encl_body = self.tcx.hir_body_owned_by(encl_body_owner_id);
1025
1026            err.encl_body_span = Some(encl_body.value.span);
1027            err.encl_fn_span = Some(*encl_fn_span);
1028        }
1029
1030        self.dcx().emit_err(err);
1031    }
1032
1033    fn point_at_return_for_opaque_ty_error(
1034        &self,
1035        errors: &mut Vec<traits::FulfillmentError<'tcx>>,
1036        hir_id: HirId,
1037        span: Span,
1038        return_expr_ty: Ty<'tcx>,
1039        return_span: Span,
1040    ) {
1041        // Don't point at the whole block if it's empty
1042        if span == return_span {
1043            return;
1044        }
1045        for err in errors {
1046            let cause = &mut err.obligation.cause;
1047            if let ObligationCauseCode::OpaqueReturnType(None) = cause.code() {
1048                let new_cause = self.cause(
1049                    cause.span,
1050                    ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, hir_id))),
1051                );
1052                *cause = new_cause;
1053            }
1054        }
1055    }
1056
1057    pub(crate) fn check_lhs_assignable(
1058        &self,
1059        lhs: &'tcx hir::Expr<'tcx>,
1060        code: ErrCode,
1061        op_span: Span,
1062        adjust_err: impl FnOnce(&mut Diag<'_>),
1063    ) {
1064        if lhs.is_syntactic_place_expr() {
1065            return;
1066        }
1067
1068        // Skip suggestion if LHS contains a let-chain at this would likely be spurious
1069        // cc: https://github.com/rust-lang/rust/issues/147664
1070        if contains_let_in_chain(lhs) {
1071            return;
1072        }
1073
1074        let mut err = self.dcx().struct_span_err(op_span, "invalid left-hand side of assignment");
1075        err.code(code);
1076        err.span_label(lhs.span, "cannot assign to this expression");
1077
1078        self.comes_from_while_condition(lhs.hir_id, |expr| {
1079            err.span_suggestion_verbose(
1080                expr.span.shrink_to_lo(),
1081                "you might have meant to use pattern destructuring",
1082                "let ",
1083                Applicability::MachineApplicable,
1084            );
1085        });
1086        self.check_for_missing_semi(lhs, &mut err);
1087
1088        adjust_err(&mut err);
1089
1090        err.emit();
1091    }
1092
1093    /// Check if the expression that could not be assigned to was a typoed expression that
1094    pub(crate) fn check_for_missing_semi(
1095        &self,
1096        expr: &'tcx hir::Expr<'tcx>,
1097        err: &mut Diag<'_>,
1098    ) -> bool {
1099        if let hir::ExprKind::Binary(binop, lhs, rhs) = expr.kind
1100            && let hir::BinOpKind::Mul = binop.node
1101            && self.tcx.sess.source_map().is_multiline(lhs.span.between(rhs.span))
1102            && rhs.is_syntactic_place_expr()
1103        {
1104            //      v missing semicolon here
1105            // foo()
1106            // *bar = baz;
1107            // (#80446).
1108            err.span_suggestion_verbose(
1109                lhs.span.shrink_to_hi(),
1110                "you might have meant to write a semicolon here",
1111                ";",
1112                Applicability::MachineApplicable,
1113            );
1114            return true;
1115        }
1116        false
1117    }
1118
1119    // Check if an expression `original_expr_id` comes from the condition of a while loop,
1120    /// as opposed from the body of a while loop, which we can naively check by iterating
1121    /// parents until we find a loop...
1122    pub(super) fn comes_from_while_condition(
1123        &self,
1124        original_expr_id: HirId,
1125        then: impl FnOnce(&hir::Expr<'_>),
1126    ) {
1127        let mut parent = self.tcx.parent_hir_id(original_expr_id);
1128        loop {
1129            let node = self.tcx.hir_node(parent);
1130            match node {
1131                hir::Node::Expr(hir::Expr {
1132                    kind:
1133                        hir::ExprKind::Loop(
1134                            hir::Block {
1135                                expr:
1136                                    Some(hir::Expr {
1137                                        kind:
1138                                            hir::ExprKind::Match(expr, ..) | hir::ExprKind::If(expr, ..),
1139                                        ..
1140                                    }),
1141                                ..
1142                            },
1143                            _,
1144                            hir::LoopSource::While,
1145                            _,
1146                        ),
1147                    ..
1148                }) => {
1149                    // Check if our original expression is a child of the condition of a while loop.
1150                    // If it is, then we have a situation like `while Some(0) = value.get(0) {`,
1151                    // where `while let` was more likely intended.
1152                    if self.tcx.hir_parent_id_iter(original_expr_id).any(|id| id == expr.hir_id) {
1153                        then(expr);
1154                    }
1155                    break;
1156                }
1157                hir::Node::Item(_)
1158                | hir::Node::ImplItem(_)
1159                | hir::Node::TraitItem(_)
1160                | hir::Node::Crate(_) => break,
1161                _ => {
1162                    parent = self.tcx.parent_hir_id(parent);
1163                }
1164            }
1165        }
1166    }
1167
1168    // A generic function for checking the 'then' and 'else' clauses in an 'if'
1169    // or 'if-else' expression.
1170    fn check_expr_if(
1171        &self,
1172        expr_id: HirId,
1173        cond_expr: &'tcx hir::Expr<'tcx>,
1174        then_expr: &'tcx hir::Expr<'tcx>,
1175        opt_else_expr: Option<&'tcx hir::Expr<'tcx>>,
1176        sp: Span,
1177        orig_expected: Expectation<'tcx>,
1178    ) -> Ty<'tcx> {
1179        let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {});
1180
1181        self.warn_if_unreachable(
1182            cond_expr.hir_id,
1183            then_expr.span,
1184            "block in `if` or `while` expression",
1185        );
1186
1187        let cond_diverges = self.diverges.get();
1188        self.diverges.set(Diverges::Maybe);
1189
1190        let expected = orig_expected.try_structurally_resolve_and_adjust_for_branches(self);
1191        let then_ty = self.check_expr_with_expectation(then_expr, expected);
1192        let then_diverges = self.diverges.get();
1193        self.diverges.set(Diverges::Maybe);
1194
1195        // We've already taken the expected type's preferences
1196        // into account when typing the `then` branch. To figure
1197        // out the initial shot at a LUB, we thus only consider
1198        // `expected` if it represents a *hard* constraint
1199        // (`only_has_type`); otherwise, we just go with a
1200        // fresh type variable.
1201        let coerce_to_ty = expected.coercion_target_type(self, sp);
1202        let mut coerce = CoerceMany::with_capacity(coerce_to_ty, 2);
1203
1204        coerce.coerce(self, &self.misc(sp), then_expr, then_ty);
1205
1206        if let Some(else_expr) = opt_else_expr {
1207            let else_ty = self.check_expr_with_expectation(else_expr, expected);
1208            let else_diverges = self.diverges.get();
1209
1210            let tail_defines_return_position_impl_trait =
1211                self.return_position_impl_trait_from_match_expectation(orig_expected);
1212            let if_cause =
1213                self.if_cause(expr_id, else_expr, tail_defines_return_position_impl_trait);
1214
1215            coerce.coerce(self, &if_cause, else_expr, else_ty);
1216
1217            // We won't diverge unless both branches do (or the condition does).
1218            self.diverges.set(cond_diverges | then_diverges & else_diverges);
1219        } else {
1220            self.if_fallback_coercion(sp, cond_expr, then_expr, &mut coerce);
1221
1222            // If the condition is false we can't diverge.
1223            self.diverges.set(cond_diverges);
1224        }
1225
1226        let result_ty = coerce.complete(self);
1227        if let Err(guar) = cond_ty.error_reported() {
1228            Ty::new_error(self.tcx, guar)
1229        } else {
1230            result_ty
1231        }
1232    }
1233
1234    /// Type check assignment expression `expr` of form `lhs = rhs`.
1235    /// The expected type is `()` and is passed to the function for the purposes of diagnostics.
1236    fn check_expr_assign(
1237        &self,
1238        expr: &'tcx hir::Expr<'tcx>,
1239        expected: Expectation<'tcx>,
1240        lhs: &'tcx hir::Expr<'tcx>,
1241        rhs: &'tcx hir::Expr<'tcx>,
1242        span: Span,
1243    ) -> Ty<'tcx> {
1244        let expected_ty = expected.only_has_type(self);
1245        if expected_ty == Some(self.tcx.types.bool) {
1246            let guar = self.expr_assign_expected_bool_error(expr, lhs, rhs, span);
1247            return Ty::new_error(self.tcx, guar);
1248        }
1249
1250        let lhs_ty = self.check_expr_with_needs(lhs, Needs::MutPlace);
1251
1252        let suggest_deref_binop = |err: &mut Diag<'_>, rhs_ty: Ty<'tcx>| {
1253            if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
1254                // Can only assign if the type is sized, so if `DerefMut` yields a type that is
1255                // unsized, do not suggest dereferencing it.
1256                let lhs_deref_ty_is_sized = self
1257                    .infcx
1258                    .type_implements_trait(
1259                        self.tcx.require_lang_item(LangItem::Sized, span),
1260                        [lhs_deref_ty],
1261                        self.param_env,
1262                    )
1263                    .may_apply();
1264                if lhs_deref_ty_is_sized && self.may_coerce(rhs_ty, lhs_deref_ty) {
1265                    err.span_suggestion_verbose(
1266                        lhs.span.shrink_to_lo(),
1267                        "consider dereferencing here to assign to the mutably borrowed value",
1268                        "*",
1269                        Applicability::MachineApplicable,
1270                    );
1271                }
1272            }
1273        };
1274
1275        // This is (basically) inlined `check_expr_coercible_to_type`, but we want
1276        // to suggest an additional fixup here in `suggest_deref_binop`.
1277        let rhs_ty = self.check_expr_with_hint(rhs, lhs_ty);
1278        if let Err(mut diag) =
1279            self.demand_coerce_diag(rhs, rhs_ty, lhs_ty, Some(lhs), AllowTwoPhase::No)
1280        {
1281            suggest_deref_binop(&mut diag, rhs_ty);
1282            diag.emit();
1283        }
1284
1285        self.check_lhs_assignable(lhs, E0070, span, |err| {
1286            if let Some(rhs_ty) = self.typeck_results.borrow().expr_ty_opt(rhs) {
1287                suggest_deref_binop(err, rhs_ty);
1288            }
1289        });
1290
1291        self.require_type_is_sized(lhs_ty, lhs.span, ObligationCauseCode::AssignmentLhsSized);
1292
1293        if let Err(guar) = (lhs_ty, rhs_ty).error_reported() {
1294            Ty::new_error(self.tcx, guar)
1295        } else {
1296            self.tcx.types.unit
1297        }
1298    }
1299
1300    /// The expected type is `bool` but this will result in `()` so we can reasonably
1301    /// say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
1302    /// The likely cause of this is `if foo = bar { .. }`.
1303    fn expr_assign_expected_bool_error(
1304        &self,
1305        expr: &'tcx hir::Expr<'tcx>,
1306        lhs: &'tcx hir::Expr<'tcx>,
1307        rhs: &'tcx hir::Expr<'tcx>,
1308        span: Span,
1309    ) -> ErrorGuaranteed {
1310        let actual_ty = self.tcx.types.unit;
1311        let expected_ty = self.tcx.types.bool;
1312        let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap_err();
1313        let lhs_ty = self.check_expr(lhs);
1314        let rhs_ty = self.check_expr(rhs);
1315        let refs_can_coerce = |lhs: Ty<'tcx>, rhs: Ty<'tcx>| {
1316            let lhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, lhs.peel_refs());
1317            let rhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rhs.peel_refs());
1318            self.may_coerce(rhs, lhs)
1319        };
1320        let (applicability, eq) = if self.may_coerce(rhs_ty, lhs_ty) {
1321            (Applicability::MachineApplicable, true)
1322        } else if refs_can_coerce(rhs_ty, lhs_ty) {
1323            // The lhs and rhs are likely missing some references in either side. Subsequent
1324            // suggestions will show up.
1325            (Applicability::MaybeIncorrect, true)
1326        } else if let ExprKind::Binary(
1327            Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1328            _,
1329            rhs_expr,
1330        ) = lhs.kind
1331        {
1332            // if x == 1 && y == 2 { .. }
1333            //                 +
1334            let actual_lhs = self.check_expr(rhs_expr);
1335            let may_eq = self.may_coerce(rhs_ty, actual_lhs) || refs_can_coerce(rhs_ty, actual_lhs);
1336            (Applicability::MaybeIncorrect, may_eq)
1337        } else if let ExprKind::Binary(
1338            Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1339            lhs_expr,
1340            _,
1341        ) = rhs.kind
1342        {
1343            // if x == 1 && y == 2 { .. }
1344            //       +
1345            let actual_rhs = self.check_expr(lhs_expr);
1346            let may_eq = self.may_coerce(actual_rhs, lhs_ty) || refs_can_coerce(actual_rhs, lhs_ty);
1347            (Applicability::MaybeIncorrect, may_eq)
1348        } else {
1349            (Applicability::MaybeIncorrect, false)
1350        };
1351
1352        if !lhs.is_syntactic_place_expr()
1353            && lhs.is_approximately_pattern()
1354            && !#[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
    hir::ExprKind::Lit(_) => true,
    _ => false,
}matches!(lhs.kind, hir::ExprKind::Lit(_))
1355        {
1356            // Do not suggest `if let x = y` as `==` is way more likely to be the intention.
1357            if let hir::Node::Expr(hir::Expr { kind: ExprKind::If { .. }, .. }) =
1358                self.tcx.parent_hir_node(expr.hir_id)
1359            {
1360                err.span_suggestion_verbose(
1361                    expr.span.shrink_to_lo(),
1362                    "you might have meant to use pattern matching",
1363                    "let ",
1364                    applicability,
1365                );
1366            };
1367        }
1368        if eq {
1369            err.span_suggestion_verbose(
1370                span.shrink_to_hi(),
1371                "you might have meant to compare for equality",
1372                '=',
1373                applicability,
1374            );
1375        }
1376
1377        // If the assignment expression itself is ill-formed, don't
1378        // bother emitting another error
1379        err.emit_unless_delay(lhs_ty.references_error() || rhs_ty.references_error())
1380    }
1381
1382    pub(super) fn check_expr_let(
1383        &self,
1384        let_expr: &'tcx hir::LetExpr<'tcx>,
1385        hir_id: HirId,
1386    ) -> Ty<'tcx> {
1387        GatherLocalsVisitor::gather_from_let_expr(self, let_expr, hir_id);
1388
1389        // for let statements, this is done in check_stmt
1390        let init = let_expr.init;
1391        self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression");
1392
1393        // otherwise check exactly as a let statement
1394        self.check_decl((let_expr, hir_id).into());
1395
1396        // but return a bool, for this is a boolean expression
1397        if let ast::Recovered::Yes(error_guaranteed) = let_expr.recovered {
1398            self.set_tainted_by_errors(error_guaranteed);
1399            Ty::new_error(self.tcx, error_guaranteed)
1400        } else {
1401            self.tcx.types.bool
1402        }
1403    }
1404
1405    fn check_expr_loop(
1406        &self,
1407        body: &'tcx hir::Block<'tcx>,
1408        source: hir::LoopSource,
1409        expected: Expectation<'tcx>,
1410        expr: &'tcx hir::Expr<'tcx>,
1411    ) -> Ty<'tcx> {
1412        let coerce = match source {
1413            // you can only use break with a value from a normal `loop { }`
1414            hir::LoopSource::Loop => {
1415                let coerce_to = expected.coercion_target_type(self, body.span);
1416                Some(CoerceMany::new(coerce_to))
1417            }
1418
1419            hir::LoopSource::While | hir::LoopSource::ForLoop => None,
1420        };
1421
1422        let ctxt = BreakableCtxt {
1423            coerce,
1424            may_break: false, // Will get updated if/when we find a `break`.
1425        };
1426
1427        let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
1428            self.check_block_no_value(body);
1429        });
1430
1431        if ctxt.may_break {
1432            // No way to know whether it's diverging because
1433            // of a `break` or an outer `break` or `return`.
1434            self.diverges.set(Diverges::Maybe);
1435        } else {
1436            self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
1437        }
1438
1439        // If we permit break with a value, then result type is
1440        // the LUB of the breaks (possibly ! if none); else, it
1441        // is nil. This makes sense because infinite loops
1442        // (which would have type !) are only possible iff we
1443        // permit break with a value.
1444        if ctxt.coerce.is_none() && !ctxt.may_break {
1445            self.dcx().span_bug(body.span, "no coercion, but loop may not break");
1446        }
1447        ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.types.unit)
1448    }
1449
1450    /// Checks a method call.
1451    fn check_expr_method_call(
1452        &self,
1453        expr: &'tcx hir::Expr<'tcx>,
1454        segment: &'tcx hir::PathSegment<'tcx>,
1455        rcvr: &'tcx hir::Expr<'tcx>,
1456        args: &'tcx [hir::Expr<'tcx>],
1457        expected: Expectation<'tcx>,
1458    ) -> Ty<'tcx> {
1459        let rcvr_t = self.check_expr(rcvr);
1460        let rcvr_t = self.resolve_vars_with_obligations(rcvr_t);
1461
1462        match self.lookup_method(rcvr_t, segment, segment.ident.span, expr, rcvr, args) {
1463            Ok(method) => {
1464                self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
1465
1466                // Handle splatted method arguments
1467                // self is already handled as `rcvr`, so it's never splatted here
1468                let method_inputs = &method.sig.inputs()[1..];
1469                let method_tuple_args_flag =
1470                    TupleArgumentsFlag::with_fn_sig_kind(method.sig.fn_sig_kind, true);
1471
1472                self.check_argument_types(
1473                    segment.ident.span,
1474                    expr,
1475                    method_inputs,
1476                    method.sig.output(),
1477                    expected,
1478                    args,
1479                    method.sig.fn_sig_kind.c_variadic(),
1480                    method_tuple_args_flag,
1481                    Some(method.def_id),
1482                    Some(method.args),
1483                );
1484
1485                self.check_call_abi(method.sig.abi(), expr.span);
1486
1487                method.sig.output()
1488            }
1489            Err(error) => {
1490                let guar = self.report_method_error(expr.hir_id, rcvr_t, error, expected, false);
1491
1492                let err_inputs = self.err_args(args.len(), guar);
1493                let err_output = Ty::new_error(self.tcx, guar);
1494
1495                self.check_argument_types(
1496                    segment.ident.span,
1497                    expr,
1498                    &err_inputs,
1499                    err_output,
1500                    NoExpectation,
1501                    args,
1502                    false,
1503                    TupleArgumentsFlag::DontTupleArguments,
1504                    None,
1505                    Some(GenericArgsRef::default()),
1506                );
1507
1508                err_output
1509            }
1510        }
1511    }
1512
1513    /// Checks use `x.use`.
1514    fn check_expr_use(
1515        &self,
1516        used_expr: &'tcx hir::Expr<'tcx>,
1517        expected: Expectation<'tcx>,
1518    ) -> Ty<'tcx> {
1519        self.check_expr_with_expectation(used_expr, expected)
1520    }
1521
1522    fn check_expr_cast(
1523        &self,
1524        e: &'tcx hir::Expr<'tcx>,
1525        t: &'tcx hir::Ty<'tcx>,
1526        expr: &'tcx hir::Expr<'tcx>,
1527    ) -> Ty<'tcx> {
1528        // Find the type of `e`. Supply hints based on the type we are casting to,
1529        // if appropriate.
1530        let t_cast = self.lower_ty_saving_user_provided_ty(t);
1531        let t_cast = self.resolve_vars_if_possible(t_cast);
1532        let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
1533        let t_expr = self.resolve_vars_if_possible(t_expr);
1534
1535        // Eagerly check for some obvious errors.
1536        if let Err(guar) = (t_expr, t_cast).error_reported() {
1537            Ty::new_error(self.tcx, guar)
1538        } else {
1539            // Defer other checks until we're done type checking.
1540            let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
1541            match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
1542                Ok(cast_check) => {
1543                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:1543",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(1543u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_expr_cast: deferring cast from {0:?} to {1:?}: {2:?}",
                                                    t_cast, t_expr, cast_check) as &dyn Value))])
            });
    } else { ; }
};debug!(
1544                        "check_expr_cast: deferring cast from {:?} to {:?}: {:?}",
1545                        t_cast, t_expr, cast_check,
1546                    );
1547                    deferred_cast_checks.push(cast_check);
1548                    t_cast
1549                }
1550                Err(guar) => Ty::new_error(self.tcx, guar),
1551            }
1552        }
1553    }
1554
1555    fn check_expr_unsafe_binder_cast(
1556        &self,
1557        span: Span,
1558        kind: ast::UnsafeBinderCastKind,
1559        inner_expr: &'tcx hir::Expr<'tcx>,
1560        hir_ty: Option<&'tcx hir::Ty<'tcx>>,
1561        expected: Expectation<'tcx>,
1562    ) -> Ty<'tcx> {
1563        match kind {
1564            ast::UnsafeBinderCastKind::Wrap => {
1565                let ascribed_ty =
1566                    hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1567                let expected_ty = expected.only_has_type(self);
1568                let binder_ty = match (ascribed_ty, expected_ty) {
1569                    (Some(ascribed_ty), Some(expected_ty)) => {
1570                        self.demand_eqtype(inner_expr.span, expected_ty, ascribed_ty);
1571                        expected_ty
1572                    }
1573                    (Some(ty), None) | (None, Some(ty)) => ty,
1574                    // This will always cause a structural resolve error, but we do it
1575                    // so we don't need to manually report an E0282 both on this codepath
1576                    // and in the others; it all happens in `structurally_resolve_type`.
1577                    (None, None) => self.next_ty_var(inner_expr.span),
1578                };
1579
1580                let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1581                let hint_ty = match *binder_ty.kind() {
1582                    ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1583                        inner_expr.span,
1584                        infer::BoundRegionConversionTime::HigherRankedType,
1585                        binder.into(),
1586                    ),
1587                    ty::Error(e) => Ty::new_error(self.tcx, e),
1588                    _ => {
1589                        let guar = self
1590                            .dcx()
1591                            .struct_span_err(
1592                                hir_ty.map_or(span, |hir_ty| hir_ty.span),
1593                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`wrap_binder!()` can only wrap into unsafe binder, not {0}",
                binder_ty.sort_string(self.tcx)))
    })format!(
1594                                    "`wrap_binder!()` can only wrap into unsafe binder, not {}",
1595                                    binder_ty.sort_string(self.tcx)
1596                                ),
1597                            )
1598                            .with_note("unsafe binders are the only valid output of wrap")
1599                            .emit();
1600                        Ty::new_error(self.tcx, guar)
1601                    }
1602                };
1603
1604                self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1605
1606                binder_ty
1607            }
1608            ast::UnsafeBinderCastKind::Unwrap => {
1609                let ascribed_ty =
1610                    hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1611                let hint_ty = ascribed_ty.unwrap_or_else(|| self.next_ty_var(inner_expr.span));
1612                // FIXME(unsafe_binders): coerce here if needed?
1613                let binder_ty = self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1614
1615                // Unwrap the binder. This will be ambiguous if it's an infer var, and will error
1616                // if it's not an unsafe binder.
1617                let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1618                match *binder_ty.kind() {
1619                    ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1620                        inner_expr.span,
1621                        infer::BoundRegionConversionTime::HigherRankedType,
1622                        binder.into(),
1623                    ),
1624                    ty::Error(e) => Ty::new_error(self.tcx, e),
1625                    _ => {
1626                        let guar = self
1627                            .dcx()
1628                            .struct_span_err(
1629                                hir_ty.map_or(inner_expr.span, |hir_ty| hir_ty.span),
1630                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected unsafe binder, found {0} as input of `unwrap_binder!()`",
                binder_ty.sort_string(self.tcx)))
    })format!(
1631                                    "expected unsafe binder, found {} as input of \
1632                                    `unwrap_binder!()`",
1633                                    binder_ty.sort_string(self.tcx)
1634                                ),
1635                            )
1636                            .with_note("only an unsafe binder type can be unwrapped")
1637                            .emit();
1638                        Ty::new_error(self.tcx, guar)
1639                    }
1640                }
1641            }
1642        }
1643    }
1644
1645    fn check_expr_array(
1646        &self,
1647        args: &'tcx [hir::Expr<'tcx>],
1648        expected: Expectation<'tcx>,
1649        expr: &'tcx hir::Expr<'tcx>,
1650    ) -> Ty<'tcx> {
1651        let element_ty = if !args.is_empty() {
1652            let coerce_to = expected
1653                .to_option(self)
1654                .and_then(|uty| {
1655                    self.resolve_vars_with_obligations(uty)
1656                        .builtin_index()
1657                        // Avoid using the original type variable as the coerce_to type, as it may resolve
1658                        // during the first coercion instead of being the LUB type.
1659                        .filter(|t| !self.resolve_vars_with_obligations(*t).is_ty_var())
1660                })
1661                .unwrap_or_else(|| self.next_ty_var(expr.span));
1662            let mut coerce = CoerceMany::with_capacity(coerce_to, args.len());
1663
1664            for e in args {
1665                // FIXME: the element expectation should use
1666                // `try_structurally_resolve_and_adjust_for_branches` just like in `if` and `match`.
1667                // While that fixes nested coercion, it will break [some
1668                // code like this](https://github.com/rust-lang/rust/pull/140283#issuecomment-2958776528).
1669                // If we find a way to support recursive tuple coercion, this break can be avoided.
1670                let e_ty = self.check_expr_with_hint(e, coerce_to);
1671                let cause = self.misc(e.span);
1672                coerce.coerce(self, &cause, e, e_ty);
1673            }
1674            coerce.complete(self)
1675        } else {
1676            self.next_ty_var(expr.span)
1677        };
1678        let array_len = args.len() as u64;
1679        self.suggest_array_len(expr, array_len);
1680        Ty::new_array(self.tcx, element_ty, array_len)
1681    }
1682
1683    fn suggest_array_len(&self, expr: &'tcx hir::Expr<'tcx>, array_len: u64) {
1684        let parent_node = self.tcx.hir_parent_iter(expr.hir_id).find(|(_, node)| {
1685            !#[allow(non_exhaustive_omitted_patterns)] match node {
    hir::Node::Expr(hir::Expr { kind: hir::ExprKind::AddrOf(..), .. }) =>
        true,
    _ => false,
}matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::AddrOf(..), .. }))
1686        });
1687        let Some((_, hir::Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }))) = parent_node else {
1688            return;
1689        };
1690        if let hir::TyKind::Array(_, ct) = ty.peel_refs().kind {
1691            let span = ct.span;
1692            self.dcx().try_steal_modify_and_emit_err(
1693                span,
1694                StashKey::UnderscoreForArrayLengths,
1695                |err| {
1696                    err.span_suggestion(
1697                        span,
1698                        "consider specifying the array length",
1699                        array_len,
1700                        Applicability::MaybeIncorrect,
1701                    );
1702                },
1703            );
1704        }
1705    }
1706
1707    pub(super) fn check_expr_const_block(
1708        &self,
1709        block: &'tcx hir::ConstBlock,
1710        expected: Expectation<'tcx>,
1711    ) -> Ty<'tcx> {
1712        let body = self.tcx.hir_body(block.body);
1713
1714        // Create a new function context.
1715        let def_id = block.def_id;
1716        let fcx = FnCtxt::new(self, self.param_env, def_id);
1717
1718        let ty = fcx.check_expr_with_expectation(body.value, expected);
1719        fcx.require_type_is_sized(ty, body.value.span, ObligationCauseCode::SizedConstOrStatic);
1720        fcx.write_ty(block.hir_id, ty);
1721        ty
1722    }
1723
1724    fn check_expr_repeat(
1725        &self,
1726        element: &'tcx hir::Expr<'tcx>,
1727        count: &'tcx hir::ConstArg<'tcx>,
1728        expected: Expectation<'tcx>,
1729        expr: &'tcx hir::Expr<'tcx>,
1730    ) -> Ty<'tcx> {
1731        let tcx = self.tcx;
1732        let count_span = count.span;
1733        let count = self.try_structurally_resolve_const(
1734            count_span,
1735            self.normalize(
1736                count_span,
1737                Unnormalized::new_wip(self.lower_const_arg(count, tcx.types.usize)),
1738            ),
1739        );
1740
1741        if let Some(count) = count.try_to_target_usize(tcx) {
1742            self.suggest_array_len(expr, count);
1743        }
1744
1745        let uty = match expected {
1746            ExpectHasType(uty) => uty.builtin_index(),
1747            _ => None,
1748        };
1749
1750        let (element_ty, t) = match uty {
1751            Some(uty) => {
1752                self.check_expr_coercible_to_type(element, uty, None);
1753                (uty, uty)
1754            }
1755            None => {
1756                let ty = self.next_ty_var(element.span);
1757                let element_ty = self.check_expr_has_type_or_error(element, ty, |_| {});
1758                (element_ty, ty)
1759            }
1760        };
1761
1762        if let Err(guar) = element_ty.error_reported() {
1763            return Ty::new_error(tcx, guar);
1764        }
1765
1766        // We defer checking whether the element type is `Copy` as it is possible to have
1767        // an inference variable as a repeat count and it seems unlikely that `Copy` would
1768        // have inference side effects required for type checking to succeed.
1769        self.deferred_repeat_expr_checks.borrow_mut().push((element, element_ty, count));
1770
1771        let ty = Ty::new_array_with_const_len(tcx, t, count);
1772        self.register_wf_obligation(ty.into(), expr.span, ObligationCauseCode::WellFormed(None));
1773        ty
1774    }
1775
1776    fn check_expr_tuple(
1777        &self,
1778        elements: &'tcx [hir::Expr<'tcx>],
1779        expected: Expectation<'tcx>,
1780        expr: &'tcx hir::Expr<'tcx>,
1781    ) -> Ty<'tcx> {
1782        let mut expectations = expected
1783            .only_has_type(self)
1784            .and_then(|ty| self.resolve_vars_with_obligations(ty).opt_tuple_fields())
1785            .unwrap_or_default()
1786            .iter();
1787
1788        let elements = elements.iter().map(|e| {
1789            let ty = expectations.next().unwrap_or_else(|| self.next_ty_var(e.span));
1790            self.check_expr_coercible_to_type(e, ty, None);
1791            ty
1792        });
1793
1794        let tuple = Ty::new_tup_from_iter(self.tcx, elements);
1795
1796        if let Err(guar) = tuple.error_reported() {
1797            Ty::new_error(self.tcx, guar)
1798        } else {
1799            self.require_type_is_sized(
1800                tuple,
1801                expr.span,
1802                ObligationCauseCode::TupleInitializerSized,
1803            );
1804            tuple
1805        }
1806    }
1807
1808    fn check_expr_struct(
1809        &self,
1810        expr: &hir::Expr<'tcx>,
1811        expected: Expectation<'tcx>,
1812        qpath: &'tcx QPath<'tcx>,
1813        fields: &'tcx [hir::ExprField<'tcx>],
1814        base_expr: &'tcx hir::StructTailExpr<'tcx>,
1815    ) -> Ty<'tcx> {
1816        // Find the relevant variant
1817        let (variant, adt_ty) = match self.check_struct_path(qpath, expr.hir_id) {
1818            Ok(data) => data,
1819            Err(guar) => {
1820                self.check_struct_fields_on_error(fields, base_expr);
1821                return Ty::new_error(self.tcx, guar);
1822            }
1823        };
1824
1825        // Prohibit struct expressions when non-exhaustive flag is set.
1826        let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1827        if variant.field_list_has_applicable_non_exhaustive() {
1828            self.dcx()
1829                .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() });
1830        }
1831
1832        self.check_expr_struct_fields(
1833            adt_ty,
1834            expected,
1835            expr,
1836            qpath.span(),
1837            variant,
1838            fields,
1839            base_expr,
1840        );
1841
1842        self.require_type_is_sized(adt_ty, expr.span, ObligationCauseCode::StructInitializerSized);
1843        adt_ty
1844    }
1845
1846    fn check_expr_struct_fields(
1847        &self,
1848        adt_ty: Ty<'tcx>,
1849        expected: Expectation<'tcx>,
1850        expr: &hir::Expr<'_>,
1851        path_span: Span,
1852        variant: &'tcx ty::VariantDef,
1853        hir_fields: &'tcx [hir::ExprField<'tcx>],
1854        base_expr: &'tcx hir::StructTailExpr<'tcx>,
1855    ) {
1856        let tcx = self.tcx;
1857
1858        let adt_ty = self.resolve_vars_with_obligations(adt_ty);
1859        let adt_ty_hint = expected.only_has_type(self).and_then(|expected| {
1860            self.fudge_inference_if_ok(|| {
1861                let ocx = ObligationCtxt::new(self);
1862                ocx.sup(&self.misc(path_span), self.param_env, expected, adt_ty)?;
1863                if !ocx.try_evaluate_obligations().is_empty() {
1864                    return Err(TypeError::Mismatch);
1865                }
1866                Ok(self.resolve_vars_if_possible(adt_ty))
1867            })
1868            .ok()
1869        });
1870        if let Some(adt_ty_hint) = adt_ty_hint {
1871            // re-link the variables that the fudging above can create.
1872            self.demand_eqtype(path_span, adt_ty_hint, adt_ty);
1873        }
1874
1875        let ty::Adt(adt, args) = adt_ty.kind() else {
1876            ::rustc_middle::util::bug::span_bug_fmt(path_span,
    format_args!("non-ADT passed to check_expr_struct_fields"));span_bug!(path_span, "non-ADT passed to check_expr_struct_fields");
1877        };
1878        let adt_kind = adt.adt_kind();
1879
1880        let mut remaining_fields = variant
1881            .fields
1882            .iter_enumerated()
1883            .map(|(i, field)| (field.ident(tcx).normalize_to_macros_2_0(), (i, field)))
1884            .collect::<UnordMap<_, _>>();
1885
1886        let mut seen_fields = FxHashMap::default();
1887
1888        let mut error_happened = false;
1889
1890        if variant.fields.len() != remaining_fields.len() {
1891            // Some field is defined more than once. Make sure we don't try to
1892            // instantiate this struct in static/const context.
1893            let guar =
1894                self.dcx().span_delayed_bug(expr.span, "struct fields have non-unique names");
1895            self.set_tainted_by_errors(guar);
1896            error_happened = true;
1897        }
1898
1899        // Type-check each field.
1900        for (idx, field) in hir_fields.iter().enumerate() {
1901            let ident = tcx.adjust_ident(field.ident, variant.def_id);
1902            let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1903                seen_fields.insert(ident, field.span);
1904                self.write_field_index(field.hir_id, i);
1905
1906                // We don't look at stability attributes on
1907                // struct-like enums (yet...), but it's definitely not
1908                // a bug to have constructed one.
1909                if adt_kind != AdtKind::Enum {
1910                    tcx.check_stability(v_field.did, Some(field.hir_id), field.span, None);
1911                }
1912
1913                self.field_ty(field.span, v_field, args)
1914            } else {
1915                error_happened = true;
1916                let guar = if let Some(prev_span) = seen_fields.get(&ident) {
1917                    self.dcx().emit_err(FieldMultiplySpecifiedInInitializer {
1918                        span: field.ident.span,
1919                        prev_span: *prev_span,
1920                        ident,
1921                    })
1922                } else {
1923                    self.report_unknown_field(
1924                        adt_ty,
1925                        variant,
1926                        expr,
1927                        field,
1928                        hir_fields,
1929                        adt.variant_descr(),
1930                    )
1931                };
1932
1933                Ty::new_error(tcx, guar)
1934            };
1935
1936            // Check that the expected field type is WF. Otherwise, we emit no use-site error
1937            // in the case of coercions for non-WF fields, which leads to incorrect error
1938            // tainting. See issue #126272.
1939            self.register_wf_obligation(
1940                field_type.into(),
1941                field.expr.span,
1942                ObligationCauseCode::WellFormed(None),
1943            );
1944
1945            // Make sure to give a type to the field even if there's
1946            // an error, so we can continue type-checking.
1947            let ty = self.check_expr_with_hint(field.expr, field_type);
1948            let diag = self.demand_coerce_diag(field.expr, ty, field_type, None, AllowTwoPhase::No);
1949
1950            if let Err(diag) = diag {
1951                if idx == hir_fields.len() - 1 {
1952                    if remaining_fields.is_empty() {
1953                        self.suggest_fru_from_range_and_emit(field, variant, args, diag);
1954                    } else {
1955                        diag.stash(field.span, StashKey::MaybeFruTypo);
1956                    }
1957                } else {
1958                    diag.emit();
1959                }
1960            }
1961        }
1962
1963        // Make sure the programmer specified correct number of fields.
1964        if adt_kind == AdtKind::Union && hir_fields.len() != 1 {
1965            {
    self.dcx().struct_span_err(path_span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("union expressions should have exactly one field"))
                })).with_code(E0784)
}struct_span_code_err!(
1966                self.dcx(),
1967                path_span,
1968                E0784,
1969                "union expressions should have exactly one field",
1970            )
1971            .emit();
1972        }
1973
1974        // If check_expr_struct_fields hit an error, do not attempt to populate
1975        // the fields with the base_expr. This could cause us to hit errors later
1976        // when certain fields are assumed to exist that in fact do not.
1977        if error_happened {
1978            if let hir::StructTailExpr::Base(base_expr) = base_expr {
1979                self.check_expr(base_expr);
1980            }
1981            return;
1982        }
1983
1984        match *base_expr {
1985            hir::StructTailExpr::DefaultFields(span) => {
1986                let mut missing_mandatory_fields = Vec::new();
1987                let mut missing_optional_fields = Vec::new();
1988                for f in &variant.fields {
1989                    let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
1990                    if let Some(_) = remaining_fields.remove(&ident) {
1991                        if f.value.is_none() {
1992                            missing_mandatory_fields.push(ident);
1993                        } else {
1994                            missing_optional_fields.push(ident);
1995                        }
1996                    }
1997                }
1998                if !self.tcx.features().default_field_values() {
1999                    let sugg = self.tcx.crate_level_attribute_injection_span();
2000                    self.dcx().emit_err(BaseExpressionDoubleDot {
2001                        span: span.shrink_to_hi(),
2002                        // We only mention enabling the feature if this is a nightly rustc *and* the
2003                        // expression would make sense with the feature enabled.
2004                        default_field_values_suggestion: if self.tcx.sess.is_nightly_build()
2005                            && missing_mandatory_fields.is_empty()
2006                            && !missing_optional_fields.is_empty()
2007                        {
2008                            Some(sugg)
2009                        } else {
2010                            None
2011                        },
2012                        add_expr: if !missing_mandatory_fields.is_empty()
2013                            || !missing_optional_fields.is_empty()
2014                        {
2015                            Some(BaseExpressionDoubleDotAddExpr { span: span.shrink_to_hi() })
2016                        } else {
2017                            None
2018                        },
2019                        remove_dots: if missing_mandatory_fields.is_empty()
2020                            && missing_optional_fields.is_empty()
2021                        {
2022                            Some(BaseExpressionDoubleDotRemove { span })
2023                        } else {
2024                            None
2025                        },
2026                    });
2027                    return;
2028                }
2029                if variant.fields.is_empty() {
2030                    let mut err = self.dcx().struct_span_err(
2031                        span,
2032                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` has no fields, `..` needs at least one default field in the struct definition",
                adt_ty))
    })format!(
2033                            "`{adt_ty}` has no fields, `..` needs at least one default field in \
2034                            the struct definition",
2035                        ),
2036                    );
2037                    err.span_label(path_span, "this type has no fields");
2038                    err.emit();
2039                }
2040                if !missing_mandatory_fields.is_empty() {
2041                    let s = if missing_mandatory_fields.len() == 1 { "" } else { "s" }pluralize!(missing_mandatory_fields.len());
2042                    let fields = listify(&missing_mandatory_fields, |f| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", f))
    })format!("`{f}`")).unwrap();
2043                    self.dcx()
2044                        .struct_span_err(
2045                            span.shrink_to_lo(),
2046                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("missing field{0} {1} in initializer",
                s, fields))
    })format!("missing field{s} {fields} in initializer"),
2047                        )
2048                        .with_span_label(
2049                            span.shrink_to_lo(),
2050                            "fields that do not have a defaulted value must be provided explicitly",
2051                        )
2052                        .emit();
2053                    return;
2054                }
2055                let fru_tys = match adt_ty.kind() {
2056                    ty::Adt(adt, args) if adt.is_struct() => variant
2057                        .fields
2058                        .iter()
2059                        .map(|f| self.normalize(span, f.ty(self.tcx, args)))
2060                        .collect(),
2061                    ty::Adt(adt, args) if adt.is_enum() => variant
2062                        .fields
2063                        .iter()
2064                        .map(|f| self.normalize(span, f.ty(self.tcx, args)))
2065                        .collect(),
2066                    _ => {
2067                        self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct { span });
2068                        return;
2069                    }
2070                };
2071                self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2072            }
2073            hir::StructTailExpr::Base(base_expr) => {
2074                // FIXME: We are currently creating two branches here in order to maintain
2075                // consistency. But they should be merged as much as possible.
2076                let fru_tys = if self.tcx.features().type_changing_struct_update() {
2077                    if adt.is_struct() {
2078                        // Make some fresh generic parameters for our ADT type.
2079                        let fresh_args = self.fresh_args_for_item(base_expr.span, adt.did());
2080                        // We do subtyping on the FRU fields first, so we can
2081                        // learn exactly what types we expect the base expr
2082                        // needs constrained to be compatible with the struct
2083                        // type we expect from the expectation value.
2084                        let fru_tys = variant
2085                            .fields
2086                            .iter()
2087                            .map(|f| {
2088                                let fru_ty = self.normalize(
2089                                    expr.span,
2090                                    Unnormalized::new_wip(self.field_ty(
2091                                        base_expr.span,
2092                                        f,
2093                                        fresh_args,
2094                                    )),
2095                                );
2096                                let ident =
2097                                    self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2098                                if let Some(_) = remaining_fields.remove(&ident) {
2099                                    let target_ty = self.field_ty(base_expr.span, f, args);
2100                                    let cause = self.misc(base_expr.span);
2101                                    match self.at(&cause, self.param_env).sup(
2102                                        // We're already using inference variables for any params,
2103                                        // and don't allow converting between different structs,
2104                                        // so there is no way this ever actually defines an opaque
2105                                        // type. Thus choosing `Yes` is fine.
2106                                        DefineOpaqueTypes::Yes,
2107                                        target_ty,
2108                                        fru_ty,
2109                                    ) {
2110                                        Ok(InferOk { obligations, value: () }) => {
2111                                            self.register_predicates(obligations)
2112                                        }
2113                                        Err(_) => {
2114                                            ::rustc_middle::util::bug::span_bug_fmt(cause.span,
    format_args!("subtyping remaining fields of type changing FRU failed: {2} != {3}: {0}::{1}",
        variant.name, ident.name, target_ty, fru_ty));span_bug!(
2115                                                cause.span,
2116                                                "subtyping remaining fields of type changing FRU \
2117                                                failed: {target_ty} != {fru_ty}: {}::{}",
2118                                                variant.name,
2119                                                ident.name,
2120                                            );
2121                                        }
2122                                    }
2123                                }
2124                                self.resolve_vars_if_possible(fru_ty)
2125                            })
2126                            .collect();
2127                        // The use of fresh args that we have subtyped against
2128                        // our base ADT type's fields allows us to guide inference
2129                        // along so that, e.g.
2130                        // ```
2131                        // MyStruct<'a, F1, F2, const C: usize> {
2132                        //     f: F1,
2133                        //     // Other fields that reference `'a`, `F2`, and `C`
2134                        // }
2135                        //
2136                        // let x = MyStruct {
2137                        //    f: 1usize,
2138                        //    ..other_struct
2139                        // };
2140                        // ```
2141                        // will have the `other_struct` expression constrained to
2142                        // `MyStruct<'a, _, F2, C>`, as opposed to just `_`...
2143                        // This is important to allow coercions to happen in
2144                        // `other_struct` itself. See `coerce-in-base-expr.rs`.
2145                        let fresh_base_ty = Ty::new_adt(self.tcx, *adt, fresh_args);
2146                        self.check_expr_has_type_or_error(
2147                            base_expr,
2148                            self.resolve_vars_if_possible(fresh_base_ty),
2149                            |_| {},
2150                        );
2151                        fru_tys
2152                    } else {
2153                        // Check the base_expr, regardless of a bad expected adt_ty, so we can get
2154                        // type errors on that expression, too.
2155                        self.check_expr(base_expr);
2156                        self.dcx()
2157                            .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
2158                        return;
2159                    }
2160                } else {
2161                    self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {
2162                        let base_ty = self.typeck_results.borrow().expr_ty(base_expr);
2163                        let same_adt = #[allow(non_exhaustive_omitted_patterns)] match (adt_ty.kind(),
        base_ty.kind()) {
    (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt => true,
    _ => false,
}matches!((adt_ty.kind(), base_ty.kind()),
2164                            (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt);
2165                        if self.tcx.sess.is_nightly_build() && same_adt {
2166                            feature_err(
2167                                &self.tcx.sess,
2168                                sym::type_changing_struct_update,
2169                                base_expr.span,
2170                                "type changing struct updating is experimental",
2171                            )
2172                            .emit();
2173                        }
2174                    });
2175                    match adt_ty.kind() {
2176                        ty::Adt(adt, args) if adt.is_struct() => variant
2177                            .fields
2178                            .iter()
2179                            .map(|f| self.normalize(expr.span, f.ty(self.tcx, args)))
2180                            .collect(),
2181                        _ => {
2182                            self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct {
2183                                span: base_expr.span,
2184                            });
2185                            return;
2186                        }
2187                    }
2188                };
2189                self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2190            }
2191            rustc_hir::StructTailExpr::NoneWithError(guaranteed) => {
2192                // If parsing the struct recovered from a syntax error, do not report missing
2193                // fields. This prevents spurious errors when a field is intended to be present
2194                // but a preceding syntax error caused it not to be parsed. For example, if a
2195                // struct type `StructName` has fields `foo` and `bar`, then
2196                //     StructName { foo(), bar: 2 }
2197                // will not successfully parse a field `foo`, but we will not mention that,
2198                // since the syntax error has already been reported.
2199
2200                // Signal that type checking has failed, even though we haven’t emitted a diagnostic
2201                // about it ourselves.
2202                self.infcx.set_tainted_by_errors(guaranteed);
2203            }
2204            rustc_hir::StructTailExpr::None => {
2205                if adt_kind != AdtKind::Union
2206                    && !remaining_fields.is_empty()
2207                    //~ non_exhaustive already reported, which will only happen for extern modules
2208                    && !variant.field_list_has_applicable_non_exhaustive()
2209                {
2210                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:2210",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(2210u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["remaining_fields"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&remaining_fields)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?remaining_fields);
2211
2212                    // Report missing fields.
2213
2214                    let private_fields: Vec<&ty::FieldDef> = variant
2215                        .fields
2216                        .iter()
2217                        .filter(|field| {
2218                            !field.vis.is_accessible_from(tcx.parent_module(expr.hir_id), tcx)
2219                        })
2220                        .collect();
2221
2222                    if !private_fields.is_empty() {
2223                        self.report_private_fields(
2224                            adt_ty,
2225                            path_span,
2226                            expr.span,
2227                            private_fields,
2228                            hir_fields,
2229                        );
2230                    } else {
2231                        self.report_missing_fields(
2232                            adt_ty,
2233                            path_span,
2234                            expr.span,
2235                            remaining_fields,
2236                            variant,
2237                            hir_fields,
2238                            args,
2239                        );
2240                    }
2241                }
2242            }
2243        }
2244    }
2245
2246    fn check_struct_fields_on_error(
2247        &self,
2248        fields: &'tcx [hir::ExprField<'tcx>],
2249        base_expr: &'tcx hir::StructTailExpr<'tcx>,
2250    ) {
2251        for field in fields {
2252            self.check_expr(field.expr);
2253        }
2254        if let hir::StructTailExpr::Base(base) = *base_expr {
2255            self.check_expr(base);
2256        }
2257    }
2258
2259    /// Report an error for a struct field expression when there are fields which aren't provided.
2260    ///
2261    /// ```text
2262    /// error: missing field `you_can_use_this_field` in initializer of `foo::Foo`
2263    ///  --> src/main.rs:8:5
2264    ///   |
2265    /// 8 |     foo::Foo {};
2266    ///   |     ^^^^^^^^ missing `you_can_use_this_field`
2267    ///
2268    /// error: aborting due to 1 previous error
2269    /// ```
2270    fn report_missing_fields(
2271        &self,
2272        adt_ty: Ty<'tcx>,
2273        span: Span,
2274        full_span: Span,
2275        remaining_fields: UnordMap<Ident, (FieldIdx, &ty::FieldDef)>,
2276        variant: &'tcx ty::VariantDef,
2277        hir_fields: &'tcx [hir::ExprField<'tcx>],
2278        args: GenericArgsRef<'tcx>,
2279    ) {
2280        let len = remaining_fields.len();
2281
2282        let displayable_field_names: Vec<&str> =
2283            remaining_fields.items().map(|(ident, _)| ident.as_str()).into_sorted_stable_ord();
2284
2285        let mut truncated_fields_error = String::new();
2286        let remaining_fields_names = match &displayable_field_names[..] {
2287            [field1] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", field1))
    })format!("`{field1}`"),
2288            [field1, field2] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` and `{1}`", field1, field2))
    })format!("`{field1}` and `{field2}`"),
2289            [field1, field2, field3] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`, `{1}` and `{2}`", field1,
                field2, field3))
    })format!("`{field1}`, `{field2}` and `{field3}`"),
2290            _ => {
2291                truncated_fields_error =
2292                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" and {0} other field{1}", len - 3,
                if len - 3 == 1 { "" } else { "s" }))
    })format!(" and {} other field{}", len - 3, pluralize!(len - 3));
2293                displayable_field_names
2294                    .iter()
2295                    .take(3)
2296                    .map(|n| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`"))
2297                    .collect::<Vec<_>>()
2298                    .join(", ")
2299            }
2300        };
2301
2302        let mut err = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("missing field{0} {1}{2} in initializer of `{3}`",
                            if len == 1 { "" } else { "s" }, remaining_fields_names,
                            truncated_fields_error, adt_ty))
                })).with_code(E0063)
}struct_span_code_err!(
2303            self.dcx(),
2304            span,
2305            E0063,
2306            "missing field{} {}{} in initializer of `{}`",
2307            pluralize!(len),
2308            remaining_fields_names,
2309            truncated_fields_error,
2310            adt_ty
2311        );
2312        err.span_label(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("missing {0}{1}",
                remaining_fields_names, truncated_fields_error))
    })format!("missing {remaining_fields_names}{truncated_fields_error}"));
2313
2314        if remaining_fields.items().all(|(_, (_, field))| field.value.is_some())
2315            && self.tcx.sess.is_nightly_build()
2316        {
2317            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("all remaining fields have default values, {0} use those values with `..`",
                if self.tcx.features().default_field_values() {
                    "you can"
                } else {
                    "if you added `#![feature(default_field_values)]` to your crate you could"
                }))
    })format!(
2318                "all remaining fields have default values, {you_can} use those values with `..`",
2319                you_can = if self.tcx.features().default_field_values() {
2320                    "you can"
2321                } else {
2322                    "if you added `#![feature(default_field_values)]` to your crate you could"
2323                },
2324            );
2325            if let Some(hir_field) = hir_fields.last() {
2326                err.span_suggestion_verbose(
2327                    hir_field.span.shrink_to_hi(),
2328                    msg,
2329                    ", ..".to_string(),
2330                    Applicability::MachineApplicable,
2331                );
2332            } else if hir_fields.is_empty() {
2333                err.span_suggestion_verbose(
2334                    span.shrink_to_hi().with_hi(full_span.hi()),
2335                    msg,
2336                    " { .. }".to_string(),
2337                    Applicability::MachineApplicable,
2338                );
2339            }
2340        }
2341
2342        if let Some(hir_field) = hir_fields.last() {
2343            self.suggest_fru_from_range_and_emit(hir_field, variant, args, err);
2344        } else {
2345            err.emit();
2346        }
2347    }
2348
2349    /// If the last field is a range literal, but it isn't supposed to be, then they probably
2350    /// meant to use functional update syntax.
2351    fn suggest_fru_from_range_and_emit(
2352        &self,
2353        last_expr_field: &hir::ExprField<'tcx>,
2354        variant: &ty::VariantDef,
2355        args: GenericArgsRef<'tcx>,
2356        mut err: Diag<'_>,
2357    ) {
2358        if is_range_literal(last_expr_field.expr)
2359            && let ExprKind::Struct(&qpath, [range_start, range_end], _) = last_expr_field.expr.kind
2360            && self.tcx.qpath_is_lang_item(qpath, LangItem::Range)
2361            && let variant_field =
2362                variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident)
2363            && let range_def_id = self.tcx.lang_items().range_struct()
2364            && variant_field
2365                .and_then(|field| field.ty(self.tcx, args).skip_norm_wip().ty_adt_def())
2366                .map(|adt| adt.did())
2367                != range_def_id
2368        {
2369            // Use a (somewhat arbitrary) filtering heuristic to avoid printing
2370            // expressions that are either too long, or have control character
2371            // such as newlines in them.
2372            let expr = self
2373                .tcx
2374                .sess
2375                .source_map()
2376                .span_to_snippet(range_end.expr.span)
2377                .ok()
2378                .filter(|s| s.len() < 25 && !s.contains(|c: char| c.is_control()));
2379
2380            let fru_span = self
2381                .tcx
2382                .sess
2383                .source_map()
2384                .span_extend_while_whitespace(range_start.expr.span)
2385                .shrink_to_hi()
2386                .to(range_end.expr.span);
2387
2388            err.subdiagnostic(TypeMismatchFruTypo {
2389                expr_span: range_start.expr.span,
2390                fru_span,
2391                expr,
2392            });
2393
2394            // Suppress any range expr type mismatches
2395            self.dcx().try_steal_replace_and_emit_err(
2396                last_expr_field.span,
2397                StashKey::MaybeFruTypo,
2398                err,
2399            );
2400        } else {
2401            err.emit();
2402        }
2403    }
2404
2405    /// Report an error for a struct field expression when there are invisible fields.
2406    ///
2407    /// ```text
2408    /// error: cannot construct `Foo` with struct literal syntax due to private fields
2409    ///  --> src/main.rs:8:5
2410    ///   |
2411    /// 8 |     foo::Foo {};
2412    ///   |     ^^^^^^^^
2413    ///
2414    /// error: aborting due to 1 previous error
2415    /// ```
2416    fn report_private_fields(
2417        &self,
2418        adt_ty: Ty<'tcx>,
2419        span: Span,
2420        expr_span: Span,
2421        private_fields: Vec<&ty::FieldDef>,
2422        used_fields: &'tcx [hir::ExprField<'tcx>],
2423    ) {
2424        let mut err =
2425            self.dcx().struct_span_err(
2426                span,
2427                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot construct `{0}` with struct literal syntax due to private fields",
                adt_ty))
    })format!(
2428                    "cannot construct `{adt_ty}` with struct literal syntax due to private fields",
2429                ),
2430            );
2431        let (used_private_fields, remaining_private_fields): (
2432            Vec<(Symbol, Span, bool)>,
2433            Vec<(Symbol, Span, bool)>,
2434        ) = private_fields
2435            .iter()
2436            .map(|field| {
2437                match used_fields.iter().find(|used_field| field.name == used_field.ident.name) {
2438                    Some(used_field) => (field.name, used_field.span, true),
2439                    None => (field.name, self.tcx.def_span(field.did), false),
2440                }
2441            })
2442            .partition(|field| field.2);
2443        err.span_labels(used_private_fields.iter().map(|(_, span, _)| *span), "private field");
2444
2445        if let ty::Adt(def, _) = adt_ty.kind() {
2446            if (def.did().is_local() || !used_fields.is_empty())
2447                && !remaining_private_fields.is_empty()
2448            {
2449                let names = if remaining_private_fields.len() > 6 {
2450                    String::new()
2451                } else {
2452                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ",
                listify(&remaining_private_fields,
                        |(name, _, _)|
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("`{0}`", name))
                                })).expect("expected at least one private field to report")))
    })format!(
2453                        "{} ",
2454                        listify(&remaining_private_fields, |(name, _, _)| format!("`{name}`"))
2455                            .expect("expected at least one private field to report")
2456                    )
2457                };
2458                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}private field{1} {3}that {2} not provided",
                if used_fields.is_empty() { "" } else { "...and other " },
                if remaining_private_fields.len() == 1 { "" } else { "s" },
                if remaining_private_fields.len() == 1 {
                    "was"
                } else { "were" }, names))
    })format!(
2459                    "{}private field{s} {names}that {were} not provided",
2460                    if used_fields.is_empty() { "" } else { "...and other " },
2461                    s = pluralize!(remaining_private_fields.len()),
2462                    were = pluralize!("was", remaining_private_fields.len()),
2463                ));
2464            }
2465
2466            let def_id = def.did();
2467            let mut items = self
2468                .tcx
2469                .inherent_impls(def_id)
2470                .into_iter()
2471                .flat_map(|&i| self.tcx.associated_items(i).in_definition_order())
2472                // Only assoc fn with no receivers.
2473                .filter(|item| item.is_fn() && !item.is_method())
2474                .filter_map(|item| {
2475                    // Only assoc fns that return `Self`
2476                    let fn_sig = self
2477                        .tcx
2478                        .fn_sig(item.def_id)
2479                        .instantiate(self.tcx, self.fresh_args_for_item(span, item.def_id))
2480                        .skip_norm_wip();
2481                    let ret_ty = self.tcx.instantiate_bound_regions_with_erased(fn_sig.output());
2482                    if !self.can_eq(self.param_env, ret_ty, adt_ty) {
2483                        return None;
2484                    }
2485                    let input_len = fn_sig.inputs().skip_binder().len();
2486                    let name = item.name();
2487                    let order = !name.as_str().starts_with("new");
2488                    Some((order, name, input_len))
2489                })
2490                .collect::<Vec<_>>();
2491            items.sort_by_key(|(order, _, _)| *order);
2492            let suggestion = |name, args| {
2493                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("::{1}({0})",
                std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "),
                name))
    })format!(
2494                    "::{name}({})",
2495                    std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", ")
2496                )
2497            };
2498            match &items[..] {
2499                [] => {}
2500                [(_, name, args)] => {
2501                    err.span_suggestion_verbose(
2502                        span.shrink_to_hi().with_hi(expr_span.hi()),
2503                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might have meant to use the `{0}` associated function",
                name))
    })format!("you might have meant to use the `{name}` associated function"),
2504                        suggestion(name, *args),
2505                        Applicability::MaybeIncorrect,
2506                    );
2507                }
2508                _ => {
2509                    err.span_suggestions(
2510                        span.shrink_to_hi().with_hi(expr_span.hi()),
2511                        "you might have meant to use an associated function to build this type",
2512                        items.iter().map(|(_, name, args)| suggestion(name, *args)),
2513                        Applicability::MaybeIncorrect,
2514                    );
2515                }
2516            }
2517            if let Some(default_trait) = self.tcx.get_diagnostic_item(sym::Default)
2518                && self
2519                    .infcx
2520                    .type_implements_trait(default_trait, [adt_ty], self.param_env)
2521                    .may_apply()
2522            {
2523                err.multipart_suggestion(
2524                    "consider using the `Default` trait",
2525                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.shrink_to_lo(), "<".to_string()),
                (span.shrink_to_hi().with_hi(expr_span.hi()),
                    " as std::default::Default>::default()".to_string())]))vec![
2526                        (span.shrink_to_lo(), "<".to_string()),
2527                        (
2528                            span.shrink_to_hi().with_hi(expr_span.hi()),
2529                            " as std::default::Default>::default()".to_string(),
2530                        ),
2531                    ],
2532                    Applicability::MaybeIncorrect,
2533                );
2534            }
2535        }
2536
2537        err.emit();
2538    }
2539
2540    fn report_unknown_field(
2541        &self,
2542        ty: Ty<'tcx>,
2543        variant: &'tcx ty::VariantDef,
2544        expr: &hir::Expr<'_>,
2545        field: &hir::ExprField<'_>,
2546        skip_fields: &[hir::ExprField<'_>],
2547        kind_name: &str,
2548    ) -> ErrorGuaranteed {
2549        // we don't care to report errors for a struct if the struct itself is tainted
2550        if let Err(guar) = variant.has_errors() {
2551            return guar;
2552        }
2553        let mut err = self.err_ctxt().type_error_struct_with_diag(
2554            field.ident.span,
2555            |actual| match ty.kind() {
2556                ty::Adt(adt, ..) if adt.is_enum() => {
    self.dcx().struct_span_err(field.ident.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} `{1}::{2}` has no field named `{3}`",
                            kind_name, actual, variant.name, field.ident))
                })).with_code(E0559)
}struct_span_code_err!(
2557                    self.dcx(),
2558                    field.ident.span,
2559                    E0559,
2560                    "{} `{}::{}` has no field named `{}`",
2561                    kind_name,
2562                    actual,
2563                    variant.name,
2564                    field.ident
2565                ),
2566                _ => {
    self.dcx().struct_span_err(field.ident.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0} `{1}` has no field named `{2}`",
                            kind_name, actual, field.ident))
                })).with_code(E0560)
}struct_span_code_err!(
2567                    self.dcx(),
2568                    field.ident.span,
2569                    E0560,
2570                    "{} `{}` has no field named `{}`",
2571                    kind_name,
2572                    actual,
2573                    field.ident
2574                ),
2575            },
2576            ty,
2577        );
2578
2579        let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap();
2580        match variant.ctor {
2581            Some((CtorKind::Fn, def_id)) => match ty.kind() {
2582                ty::Adt(adt, ..) if adt.is_enum() => {
2583                    err.span_label(
2584                        variant_ident_span,
2585                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::{1}` defined here", ty,
                variant.name))
    })format!(
2586                            "`{adt}::{variant}` defined here",
2587                            adt = ty,
2588                            variant = variant.name,
2589                        ),
2590                    );
2591                    err.span_label(field.ident.span, "field does not exist");
2592                    let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
2593                    let inputs = fn_sig.inputs().skip_binder();
2594                    let fields = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})",
                inputs.iter().map(|i|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("/* {0} */", i))
                                    })).collect::<Vec<_>>().join(", ")))
    })format!(
2595                        "({})",
2596                        inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2597                    );
2598                    let (replace_span, sugg) = match expr.kind {
2599                        hir::ExprKind::Struct(qpath, ..) => {
2600                            (qpath.span().shrink_to_hi().with_hi(expr.span.hi()), fields)
2601                        }
2602                        _ => {
2603                            (expr.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}::{0}{2}", variant.name, ty,
                fields))
    })format!("{ty}::{variant}{fields}", variant = variant.name))
2604                        }
2605                    };
2606                    err.span_suggestion_verbose(
2607                        replace_span,
2608                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::{1}` is a tuple {2}, use the appropriate syntax",
                ty, variant.name, kind_name))
    })format!(
2609                            "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax",
2610                            adt = ty,
2611                            variant = variant.name,
2612                        ),
2613                        sugg,
2614                        Applicability::HasPlaceholders,
2615                    );
2616                }
2617                _ => {
2618                    err.span_label(variant_ident_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` defined here", ty))
    })format!("`{ty}` defined here"));
2619                    err.span_label(field.ident.span, "field does not exist");
2620                    let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
2621                    let inputs = fn_sig.inputs().skip_binder();
2622                    let fields = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})",
                inputs.iter().map(|i|
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("/* {0} */", i))
                                    })).collect::<Vec<_>>().join(", ")))
    })format!(
2623                        "({})",
2624                        inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2625                    );
2626                    err.span_suggestion_verbose(
2627                        expr.span,
2628                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is a tuple {1}, use the appropriate syntax",
                ty, kind_name))
    })format!("`{ty}` is a tuple {kind_name}, use the appropriate syntax",),
2629                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", ty, fields))
    })format!("{ty}{fields}"),
2630                        Applicability::HasPlaceholders,
2631                    );
2632                }
2633            },
2634            _ => {
2635                // prevent all specified fields from being suggested
2636                let available_field_names = self.available_field_names(variant, expr, skip_fields);
2637                if let Some(field_name) =
2638                    find_best_match_for_name(&available_field_names, field.ident.name, None)
2639                    && !(field.ident.name.as_str().parse::<usize>().is_ok()
2640                        && field_name.as_str().parse::<usize>().is_ok())
2641                {
2642                    err.span_label(field.ident.span, "unknown field");
2643                    err.span_suggestion_verbose(
2644                        field.ident.span,
2645                        "a field with a similar name exists",
2646                        field_name,
2647                        Applicability::MaybeIncorrect,
2648                    );
2649                } else {
2650                    match ty.kind() {
2651                        ty::Adt(adt, ..) => {
2652                            if adt.is_enum() {
2653                                err.span_label(
2654                                    field.ident.span,
2655                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::{1}` does not have this field",
                ty, variant.name))
    })format!("`{}::{}` does not have this field", ty, variant.name),
2656                                );
2657                            } else {
2658                                err.span_label(
2659                                    field.ident.span,
2660                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` does not have this field",
                ty))
    })format!("`{ty}` does not have this field"),
2661                                );
2662                            }
2663                            if available_field_names.is_empty() {
2664                                err.note("all struct fields are already assigned");
2665                            } else {
2666                                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("available fields are: {0}",
                self.name_series_display(available_field_names)))
    })format!(
2667                                    "available fields are: {}",
2668                                    self.name_series_display(available_field_names)
2669                                ));
2670                            }
2671                        }
2672                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("non-ADT passed to report_unknown_field"))bug!("non-ADT passed to report_unknown_field"),
2673                    }
2674                };
2675            }
2676        }
2677        err.emit()
2678    }
2679
2680    fn available_field_names(
2681        &self,
2682        variant: &'tcx ty::VariantDef,
2683        expr: &hir::Expr<'_>,
2684        skip_fields: &[hir::ExprField<'_>],
2685    ) -> Vec<Symbol> {
2686        variant
2687            .fields
2688            .iter()
2689            .filter(|field| {
2690                skip_fields.iter().all(|&skip| skip.ident.name != field.name)
2691                    && self.is_field_suggestable(field, expr.hir_id, expr.span)
2692            })
2693            .map(|field| field.name)
2694            .collect()
2695    }
2696
2697    fn name_series_display(&self, names: Vec<Symbol>) -> String {
2698        // dynamic limit, to never omit just one field
2699        let limit = if names.len() == 6 { 6 } else { 5 };
2700        let mut display =
2701            names.iter().take(limit).map(|n| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`")).collect::<Vec<_>>().join(", ");
2702        if names.len() > limit {
2703            display = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} ... and {1} others", display,
                names.len() - limit))
    })format!("{} ... and {} others", display, names.len() - limit);
2704        }
2705        display
2706    }
2707
2708    /// Find the position of a field named `ident` in `base_def`, accounting for unnammed fields.
2709    /// Return whether such a field has been found. The path to it is stored in `nested_fields`.
2710    /// `ident` must have been adjusted beforehand.
2711    fn find_adt_field(
2712        &self,
2713        base_def: ty::AdtDef<'tcx>,
2714        ident: Ident,
2715    ) -> Option<(FieldIdx, &'tcx ty::FieldDef)> {
2716        // No way to find a field in an enum.
2717        if base_def.is_enum() {
2718            return None;
2719        }
2720
2721        for (field_idx, field) in base_def.non_enum_variant().fields.iter_enumerated() {
2722            if field.ident(self.tcx).normalize_to_macros_2_0() == ident {
2723                // We found the field we wanted.
2724                return Some((field_idx, field));
2725            }
2726        }
2727
2728        None
2729    }
2730
2731    /// Check field access expressions, this works for both structs and tuples.
2732    /// Returns the Ty of the field.
2733    ///
2734    /// ```ignore (illustrative)
2735    /// base.field
2736    /// ^^^^^^^^^^ expr
2737    /// ^^^^       base
2738    ///      ^^^^^ field
2739    /// ```
2740    fn check_expr_field(
2741        &self,
2742        expr: &'tcx hir::Expr<'tcx>,
2743        base: &'tcx hir::Expr<'tcx>,
2744        field: Ident,
2745        // The expected type hint of the field.
2746        expected: Expectation<'tcx>,
2747    ) -> Ty<'tcx> {
2748        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:2748",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(2748u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_field(expr: {0:?}, base: {1:?}, field: {2:?})",
                                                    expr, base, field) as &dyn Value))])
            });
    } else { ; }
};debug!("check_field(expr: {:?}, base: {:?}, field: {:?})", expr, base, field);
2749        let base_ty = self.check_expr(base);
2750        let base_ty = self.structurally_resolve_type(base.span, base_ty);
2751
2752        // Whether we are trying to access a private field. Used for error reporting.
2753        let mut private_candidate = None;
2754
2755        // Field expressions automatically deref
2756        let mut autoderef = self.autoderef(expr.span, base_ty);
2757        while let Some((deref_base_ty, _)) = autoderef.next() {
2758            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:2758",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(2758u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("deref_base_ty: {0:?}",
                                                    deref_base_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("deref_base_ty: {:?}", deref_base_ty);
2759            match deref_base_ty.kind() {
2760                ty::Adt(base_def, args) if !base_def.is_enum() => {
2761                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:2761",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(2761u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("struct named {0:?}",
                                                    deref_base_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("struct named {:?}", deref_base_ty);
2762                    // we don't care to report errors for a struct if the struct itself is tainted
2763                    if let Err(guar) = base_def.non_enum_variant().has_errors() {
2764                        return Ty::new_error(self.tcx(), guar);
2765                    }
2766
2767                    let (ident, def_scope) = self.tcx.adjust_ident_and_get_scope(
2768                        field,
2769                        base_def.did(),
2770                        self.body_def_id,
2771                    );
2772
2773                    if let Some((idx, field)) = self.find_adt_field(*base_def, ident) {
2774                        self.write_field_index(expr.hir_id, idx);
2775
2776                        let adjustments = self.adjust_steps(&autoderef);
2777                        if field.vis.is_accessible_from(def_scope, self.tcx) {
2778                            self.apply_adjustments(base, adjustments);
2779                            self.register_predicates(autoderef.into_obligations());
2780
2781                            self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
2782                            return self.field_ty(expr.span, field, args);
2783                        }
2784
2785                        // The field is not accessible, fall through to error reporting.
2786                        private_candidate = Some((adjustments, base_def.did()));
2787                    }
2788                }
2789                ty::Tuple(tys) => {
2790                    if let Ok(index) = field.as_str().parse::<usize>() {
2791                        if field.name == sym::integer(index) {
2792                            if let Some(&field_ty) = tys.get(index) {
2793                                let adjustments = self.adjust_steps(&autoderef);
2794                                self.apply_adjustments(base, adjustments);
2795                                self.register_predicates(autoderef.into_obligations());
2796
2797                                self.write_field_index(expr.hir_id, FieldIdx::from_usize(index));
2798                                return field_ty;
2799                            }
2800                        }
2801                    }
2802                }
2803                _ => {}
2804            }
2805        }
2806        // We failed to check the expression, report an error.
2807
2808        // Emits an error if we deref an infer variable, like calling `.field` on a base type
2809        // of `&_`. We can also use this to suppress unnecessary "missing field" errors that
2810        // will follow ambiguity errors.
2811        let final_ty = self.structurally_resolve_type(autoderef.span(), autoderef.final_ty());
2812        if let ty::Error(_) = final_ty.kind() {
2813            return final_ty;
2814        }
2815
2816        if let Some((adjustments, did)) = private_candidate {
2817            // (#90483) apply adjustments to avoid ExprUseVisitor from
2818            // creating erroneous projection.
2819            self.apply_adjustments(base, adjustments);
2820            let guar = self.ban_private_field_access(
2821                expr,
2822                base_ty,
2823                field,
2824                did,
2825                expected.only_has_type(self),
2826            );
2827            return Ty::new_error(self.tcx(), guar);
2828        }
2829
2830        let guar = if self.method_exists_for_diagnostic(
2831            field,
2832            base_ty,
2833            expr.hir_id,
2834            expected.only_has_type(self),
2835        ) {
2836            // If taking a method instead of calling it
2837            self.ban_take_value_of_method(expr, base_ty, field)
2838        } else if !base_ty.is_primitive_ty() {
2839            self.ban_nonexisting_field(field, base, expr, base_ty)
2840        } else {
2841            let field_name = field.to_string();
2842            let mut err = {
    let mut err =
        {
            self.dcx().struct_span_err(field.span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` is a primitive type and therefore doesn\'t have fields",
                                    base_ty))
                        })).with_code(E0610)
        };
    if base_ty.references_error() { err.downgrade_to_delayed_bug(); }
    err
}type_error_struct!(
2843                self.dcx(),
2844                field.span,
2845                base_ty,
2846                E0610,
2847                "`{base_ty}` is a primitive type and therefore doesn't have fields",
2848            );
2849            let is_valid_suffix = |field: &str| {
2850                if field == "f32" || field == "f64" {
2851                    return true;
2852                }
2853                let mut chars = field.chars().peekable();
2854                match chars.peek() {
2855                    Some('e') | Some('E') => {
2856                        chars.next();
2857                        if let Some(c) = chars.peek()
2858                            && !c.is_numeric()
2859                            && *c != '-'
2860                            && *c != '+'
2861                        {
2862                            return false;
2863                        }
2864                        while let Some(c) = chars.peek() {
2865                            if !c.is_numeric() {
2866                                break;
2867                            }
2868                            chars.next();
2869                        }
2870                    }
2871                    _ => (),
2872                }
2873                let suffix = chars.collect::<String>();
2874                suffix.is_empty() || suffix == "f32" || suffix == "f64"
2875            };
2876            let maybe_partial_suffix = |field: &str| -> Option<&str> {
2877                let first_chars = ['f', 'l'];
2878                if field.len() >= 1
2879                    && field.to_lowercase().starts_with(first_chars)
2880                    && field[1..].chars().all(|c| c.is_ascii_digit())
2881                {
2882                    if field.to_lowercase().starts_with(['f']) { Some("f32") } else { Some("f64") }
2883                } else {
2884                    None
2885                }
2886            };
2887            if let ty::Infer(ty::IntVar(_)) = base_ty.kind()
2888                && let ExprKind::Lit(Spanned {
2889                    node: ast::LitKind::Int(_, ast::LitIntType::Unsuffixed),
2890                    ..
2891                }) = base.kind
2892                && !base.span.from_expansion()
2893            {
2894                if is_valid_suffix(&field_name) {
2895                    err.span_suggestion_verbose(
2896                        field.span.shrink_to_lo(),
2897                        "if intended to be a floating point literal, consider adding a `0` after the period",
2898                        '0',
2899                        Applicability::MaybeIncorrect,
2900                    );
2901                } else if let Some(correct_suffix) = maybe_partial_suffix(&field_name) {
2902                    err.span_suggestion_verbose(
2903                        field.span,
2904                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if intended to be a floating point literal, consider adding a `0` after the period and a `{0}` suffix",
                correct_suffix))
    })format!("if intended to be a floating point literal, consider adding a `0` after the period and a `{correct_suffix}` suffix"),
2905                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("0{0}", correct_suffix))
    })format!("0{correct_suffix}"),
2906                        Applicability::MaybeIncorrect,
2907                    );
2908                }
2909            }
2910            err.emit()
2911        };
2912
2913        Ty::new_error(self.tcx(), guar)
2914    }
2915
2916    fn suggest_await_on_field_access(
2917        &self,
2918        err: &mut Diag<'_>,
2919        field_ident: Ident,
2920        base: &'tcx hir::Expr<'tcx>,
2921        ty: Ty<'tcx>,
2922    ) {
2923        let Some(output_ty) = self.tcx.get_impl_future_output_ty(ty) else {
2924            err.span_label(field_ident.span, "unknown field");
2925            return;
2926        };
2927        let ty::Adt(def, _) = output_ty.kind() else {
2928            err.span_label(field_ident.span, "unknown field");
2929            return;
2930        };
2931        // no field access on enum type
2932        if def.is_enum() {
2933            err.span_label(field_ident.span, "unknown field");
2934            return;
2935        }
2936        if !def.non_enum_variant().fields.iter().any(|field| field.ident(self.tcx) == field_ident) {
2937            err.span_label(field_ident.span, "unknown field");
2938            return;
2939        }
2940        err.span_label(
2941            field_ident.span,
2942            "field not available in `impl Future`, but it is available in its `Output`",
2943        );
2944        match self.tcx.coroutine_kind(self.body_def_id) {
2945            Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
2946                err.span_suggestion_verbose(
2947                    base.span.shrink_to_hi(),
2948                    "consider `await`ing on the `Future` to access the field",
2949                    ".await",
2950                    Applicability::MaybeIncorrect,
2951                );
2952            }
2953            _ => {
2954                let mut span: MultiSpan = base.span.into();
2955                span.push_span_label(self.tcx.def_span(self.body_def_id), "this is not `async`");
2956                err.span_note(
2957                    span,
2958                    "this implements `Future` and its output type has the field, \
2959                    but the future cannot be awaited in a synchronous function",
2960                );
2961            }
2962        }
2963    }
2964
2965    fn ban_nonexisting_field(
2966        &self,
2967        ident: Ident,
2968        base: &'tcx hir::Expr<'tcx>,
2969        expr: &'tcx hir::Expr<'tcx>,
2970        base_ty: Ty<'tcx>,
2971    ) -> ErrorGuaranteed {
2972        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:2972",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(2972u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("ban_nonexisting_field: field={0:?}, base={1:?}, expr={2:?}, base_ty={3:?}",
                                                    ident, base, expr, base_ty) as &dyn Value))])
            });
    } else { ; }
};debug!(
2973            "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}",
2974            ident, base, expr, base_ty
2975        );
2976        let mut err = self.no_such_field_err(ident, base_ty, expr);
2977
2978        match *base_ty.peel_refs().kind() {
2979            ty::Array(_, len) => {
2980                self.maybe_suggest_array_indexing(&mut err, base, ident, len);
2981            }
2982            ty::RawPtr(..) => {
2983                self.suggest_first_deref_field(&mut err, base, ident);
2984            }
2985            ty::Param(param_ty) => {
2986                err.span_label(ident.span, "unknown field");
2987                self.point_at_param_definition(&mut err, param_ty);
2988            }
2989            ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => {
2990                self.suggest_await_on_field_access(&mut err, ident, base, base_ty.peel_refs());
2991            }
2992            _ => {
2993                err.span_label(ident.span, "unknown field");
2994            }
2995        }
2996
2997        self.suggest_fn_call(&mut err, base, base_ty, |output_ty| {
2998            if let ty::Adt(def, _) = output_ty.kind()
2999                && !def.is_enum()
3000            {
3001                def.non_enum_variant().fields.iter().any(|field| {
3002                    field.ident(self.tcx) == ident
3003                        && field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
3004                })
3005            } else if let ty::Tuple(tys) = output_ty.kind()
3006                && let Ok(idx) = ident.as_str().parse::<usize>()
3007            {
3008                idx < tys.len()
3009            } else {
3010                false
3011            }
3012        });
3013
3014        if ident.name == kw::Await {
3015            // We know by construction that `<expr>.await` is either on Rust 2015
3016            // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
3017            err.note("to `.await` a `Future`, switch to Rust 2018 or later");
3018            HelpUseLatestEdition::new().add_to_diag(&mut err);
3019        }
3020
3021        err.emit()
3022    }
3023
3024    fn ban_private_field_access(
3025        &self,
3026        expr: &hir::Expr<'tcx>,
3027        expr_t: Ty<'tcx>,
3028        field: Ident,
3029        base_did: DefId,
3030        return_ty: Option<Ty<'tcx>>,
3031    ) -> ErrorGuaranteed {
3032        let mut err = self.private_field_err(field, base_did);
3033
3034        // Also check if an accessible method exists, which is often what is meant.
3035        if self.method_exists_for_diagnostic(field, expr_t, expr.hir_id, return_ty)
3036            && !self.expr_in_place(expr.hir_id)
3037        {
3038            self.suggest_method_call(
3039                &mut err,
3040                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a method `{0}` also exists, call it with parentheses",
                field))
    })format!("a method `{field}` also exists, call it with parentheses"),
3041                field,
3042                expr_t,
3043                expr,
3044                None,
3045            );
3046        }
3047        err.emit()
3048    }
3049
3050    fn ban_take_value_of_method(
3051        &self,
3052        expr: &hir::Expr<'tcx>,
3053        expr_t: Ty<'tcx>,
3054        field: Ident,
3055    ) -> ErrorGuaranteed {
3056        let mut err = {
    let mut err =
        {
            self.dcx().struct_span_err(field.span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("attempted to take value of method `{0}` on type `{1}`",
                                    field, expr_t))
                        })).with_code(E0615)
        };
    if expr_t.references_error() { err.downgrade_to_delayed_bug(); }
    err
}type_error_struct!(
3057            self.dcx(),
3058            field.span,
3059            expr_t,
3060            E0615,
3061            "attempted to take value of method `{field}` on type `{expr_t}`",
3062        );
3063        err.span_label(field.span, "method, not a field");
3064        let expr_is_call =
3065            if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) =
3066                self.tcx.parent_hir_node(expr.hir_id)
3067            {
3068                expr.hir_id == callee.hir_id
3069            } else {
3070                false
3071            };
3072        let expr_snippet =
3073            self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_default();
3074        let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')');
3075        let after_open = expr.span.lo() + rustc_span::BytePos(1);
3076        let before_close = expr.span.hi() - rustc_span::BytePos(1);
3077
3078        if expr_is_call && is_wrapped {
3079            err.multipart_suggestion(
3080                "remove wrapping parentheses to call the method",
3081                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.with_hi(after_open), String::new()),
                (expr.span.with_lo(before_close), String::new())]))vec![
3082                    (expr.span.with_hi(after_open), String::new()),
3083                    (expr.span.with_lo(before_close), String::new()),
3084                ],
3085                Applicability::MachineApplicable,
3086            );
3087        } else if !self.expr_in_place(expr.hir_id) {
3088            // Suggest call parentheses inside the wrapping parentheses
3089            let span = if is_wrapped {
3090                expr.span.with_lo(after_open).with_hi(before_close)
3091            } else {
3092                expr.span
3093            };
3094            self.suggest_method_call(
3095                &mut err,
3096                "use parentheses to call the method",
3097                field,
3098                expr_t,
3099                expr,
3100                Some(span),
3101            );
3102        } else if let ty::RawPtr(ptr_ty, _) = expr_t.kind()
3103            && let ty::Adt(adt_def, _) = ptr_ty.kind()
3104            && let ExprKind::Field(base_expr, _) = expr.kind
3105            && let [variant] = &adt_def.variants().raw
3106            && variant.fields.iter().any(|f| f.ident(self.tcx) == field)
3107        {
3108            err.multipart_suggestion(
3109                "to access the field, dereference first",
3110                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(base_expr.span.shrink_to_lo(), "(*".to_string()),
                (base_expr.span.shrink_to_hi(), ")".to_string())]))vec![
3111                    (base_expr.span.shrink_to_lo(), "(*".to_string()),
3112                    (base_expr.span.shrink_to_hi(), ")".to_string()),
3113                ],
3114                Applicability::MaybeIncorrect,
3115            );
3116        } else {
3117            err.help("methods are immutable and cannot be assigned to");
3118        }
3119
3120        // See `StashKey::GenericInFieldExpr` for more info
3121        self.dcx().try_steal_replace_and_emit_err(field.span, StashKey::GenericInFieldExpr, err)
3122    }
3123
3124    fn point_at_param_definition(&self, err: &mut Diag<'_>, param: ty::ParamTy) {
3125        let generics = self.tcx.generics_of(self.body_def_id);
3126        let generic_param = generics.type_param(param, self.tcx);
3127        if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
3128            return;
3129        }
3130        let param_def_id = generic_param.def_id;
3131        let param_hir_id = match param_def_id.as_local() {
3132            Some(x) => self.tcx.local_def_id_to_hir_id(x),
3133            None => return,
3134        };
3135        let param_span = self.tcx.hir_span(param_hir_id);
3136        let param_name = self.tcx.hir_ty_param_name(param_def_id.expect_local());
3137
3138        err.span_label(param_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type parameter \'{0}\' declared here",
                param_name))
    })format!("type parameter '{param_name}' declared here"));
3139    }
3140
3141    fn maybe_suggest_array_indexing(
3142        &self,
3143        err: &mut Diag<'_>,
3144        base: &hir::Expr<'_>,
3145        field: Ident,
3146        len: ty::Const<'tcx>,
3147    ) {
3148        err.span_label(field.span, "unknown field");
3149        if let (Some(len), Ok(user_index)) = (
3150            self.try_structurally_resolve_const(base.span, len).try_to_target_usize(self.tcx),
3151            field.as_str().parse::<u64>(),
3152        ) {
3153            let help = "instead of using tuple indexing, use array indexing";
3154            let applicability = if len < user_index {
3155                Applicability::MachineApplicable
3156            } else {
3157                Applicability::MaybeIncorrect
3158            };
3159            err.multipart_suggestion(
3160                help,
3161                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(base.span.between(field.span), "[".to_string()),
                (field.span.shrink_to_hi(), "]".to_string())]))vec![
3162                    (base.span.between(field.span), "[".to_string()),
3163                    (field.span.shrink_to_hi(), "]".to_string()),
3164                ],
3165                applicability,
3166            );
3167        }
3168    }
3169
3170    fn suggest_first_deref_field(&self, err: &mut Diag<'_>, base: &hir::Expr<'_>, field: Ident) {
3171        err.span_label(field.span, "unknown field");
3172        if base.span.from_expansion() || field.span.from_expansion() {
3173            return;
3174        }
3175        let val = if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span)
3176            && base.len() < 20
3177        {
3178            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", base))
    })format!("`{base}`")
3179        } else {
3180            "the value".to_string()
3181        };
3182        err.multipart_suggestion(
3183            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} is a raw pointer; try dereferencing it",
                val))
    })format!("{val} is a raw pointer; try dereferencing it"),
3184            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(base.span.shrink_to_lo(), "(*".into()),
                (base.span.between(field.span),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(")."))
                        }))]))vec![
3185                (base.span.shrink_to_lo(), "(*".into()),
3186                (base.span.between(field.span), format!(").")),
3187            ],
3188            Applicability::MaybeIncorrect,
3189        );
3190    }
3191
3192    fn no_such_field_err(
3193        &self,
3194        field: Ident,
3195        base_ty: Ty<'tcx>,
3196        expr: &hir::Expr<'tcx>,
3197    ) -> Diag<'_> {
3198        let span = field.span;
3199        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:3199",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(3199u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("no_such_field_err(span: {0:?}, field: {1:?}, expr_t: {2:?})",
                                                    span, field, base_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, base_ty);
3200
3201        let mut err = self.dcx().create_err(NoFieldOnType { span, ty: base_ty, field });
3202        if base_ty.references_error() {
3203            err.downgrade_to_delayed_bug();
3204        }
3205
3206        if let Some(within_macro_span) = span.within_macro(expr.span, self.tcx.sess.source_map()) {
3207            err.span_label(within_macro_span, "due to this macro variable");
3208        }
3209
3210        // Check if there is an associated function with the same name.
3211        if let Some(def_id) = base_ty.peel_refs().ty_adt_def().map(|d| d.did()) {
3212            for &impl_def_id in self.tcx.inherent_impls(def_id) {
3213                for item in self.tcx.associated_items(impl_def_id).in_definition_order() {
3214                    if let ExprKind::Field(base_expr, _) = expr.kind
3215                        && item.name() == field.name
3216                        && #[allow(non_exhaustive_omitted_patterns)] match item.kind {
    ty::AssocKind::Fn { has_self: false, .. } => true,
    _ => false,
}matches!(item.kind, ty::AssocKind::Fn { has_self: false, .. })
3217                    {
3218                        err.span_label(field.span, "this is an associated function, not a method");
3219                        err.note("found the following associated function; to be used as method, it must have a `self` parameter");
3220                        let impl_ty =
3221                            self.tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip();
3222                        err.span_note(
3223                            self.tcx.def_span(item.def_id),
3224                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the candidate is defined in an impl for the type `{0}`",
                impl_ty))
    })format!("the candidate is defined in an impl for the type `{impl_ty}`"),
3225                        );
3226
3227                        let ty_str = match base_ty.peel_refs().kind() {
3228                            ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), args),
3229                            _ => base_ty.peel_refs().to_string(),
3230                        };
3231                        err.multipart_suggestion(
3232                            "use associated function syntax instead",
3233                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(base_expr.span, ty_str),
                (base_expr.span.between(field.span), "::".to_string())]))vec![
3234                                (base_expr.span, ty_str),
3235                                (base_expr.span.between(field.span), "::".to_string()),
3236                            ],
3237                            Applicability::MaybeIncorrect,
3238                        );
3239                        return err;
3240                    }
3241                }
3242            }
3243        }
3244
3245        // try to add a suggestion in case the field is a nested field of a field of the Adt
3246        let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id();
3247        let (ty, unwrap) = if let ty::Adt(def, args) = base_ty.kind()
3248            && (self.tcx.is_diagnostic_item(sym::Result, def.did())
3249                || self.tcx.is_diagnostic_item(sym::Option, def.did()))
3250            && let Some(arg) = args.get(0)
3251            && let Some(ty) = arg.as_type()
3252        {
3253            (ty, "unwrap().")
3254        } else {
3255            (base_ty, "")
3256        };
3257        for found_fields in
3258            self.get_field_candidates_considering_privacy_for_diag(span, ty, mod_id, expr.hir_id)
3259        {
3260            let field_names = found_fields.iter().map(|field| field.0.name).collect::<Vec<_>>();
3261            let mut candidate_fields: Vec<_> = found_fields
3262                .into_iter()
3263                .filter_map(|candidate_field| {
3264                    self.check_for_nested_field_satisfying_condition_for_diag(
3265                        span,
3266                        &|candidate_field, _| candidate_field == field,
3267                        candidate_field,
3268                        ::alloc::vec::Vec::new()vec![],
3269                        mod_id,
3270                        expr.hir_id,
3271                    )
3272                })
3273                .map(|mut field_path| {
3274                    field_path.pop();
3275                    field_path.iter().map(|id| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.", id))
    })format!("{}.", id)).collect::<String>()
3276                })
3277                .collect::<Vec<_>>();
3278            candidate_fields.sort();
3279
3280            let len = candidate_fields.len();
3281            // Don't suggest `.field` if the base expr is from a different
3282            // syntax context than the field.
3283            if len > 0 && expr.span.eq_ctxt(field.span) {
3284                err.span_suggestions(
3285                    field.span.shrink_to_lo(),
3286                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} of the expressions\' fields {1} a field of the same name",
                if len > 1 { "some" } else { "one" },
                if len > 1 { "have" } else { "has" }))
    })format!(
3287                        "{} of the expressions' fields {} a field of the same name",
3288                        if len > 1 { "some" } else { "one" },
3289                        if len > 1 { "have" } else { "has" },
3290                    ),
3291                    candidate_fields.iter().map(|path| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", unwrap, path))
    })format!("{unwrap}{path}")),
3292                    Applicability::MaybeIncorrect,
3293                );
3294            } else if let Some(field_name) =
3295                find_best_match_for_name(&field_names, field.name, None)
3296                && !(field.name.as_str().parse::<usize>().is_ok()
3297                    && field_name.as_str().parse::<usize>().is_ok())
3298            {
3299                err.span_suggestion_verbose(
3300                    field.span,
3301                    "a field with a similar name exists",
3302                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{0}", field_name, unwrap))
    })format!("{unwrap}{}", field_name),
3303                    Applicability::MaybeIncorrect,
3304                );
3305            } else if !field_names.is_empty() {
3306                let is = if field_names.len() == 1 { " is" } else { "s are" };
3307                err.note(
3308                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("available field{1}: {0}",
                self.name_series_display(field_names), is))
    })format!("available field{is}: {}", self.name_series_display(field_names),),
3309                );
3310            }
3311        }
3312        err
3313    }
3314
3315    fn private_field_err(&self, field: Ident, base_did: DefId) -> Diag<'_> {
3316        let struct_path = self.tcx().def_path_str(base_did);
3317        let kind_name = self.tcx().def_descr(base_did);
3318        {
    self.dcx().struct_span_err(field.span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("field `{0}` of {1} `{2}` is private",
                            field, kind_name, struct_path))
                })).with_code(E0616)
}struct_span_code_err!(
3319            self.dcx(),
3320            field.span,
3321            E0616,
3322            "field `{field}` of {kind_name} `{struct_path}` is private",
3323        )
3324        .with_span_label(field.span, "private field")
3325    }
3326
3327    pub(crate) fn get_field_candidates_considering_privacy_for_diag(
3328        &self,
3329        span: Span,
3330        base_ty: Ty<'tcx>,
3331        mod_id: DefId,
3332        hir_id: HirId,
3333    ) -> Vec<Vec<(Ident, Ty<'tcx>)>> {
3334        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:3334",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(3334u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("get_field_candidates(span: {0:?}, base_t: {1:?}",
                                                    span, base_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_ty);
3335
3336        let mut autoderef = self.autoderef(span, base_ty).silence_errors();
3337        let deref_chain: Vec<_> = autoderef.by_ref().collect();
3338
3339        // Don't probe if we hit the recursion limit, since it may result in
3340        // quadratic blowup if we then try to further deref the results of this
3341        // function. This is a best-effort method, after all.
3342        if autoderef.reached_recursion_limit() {
3343            return ::alloc::vec::Vec::new()vec![];
3344        }
3345
3346        deref_chain
3347            .into_iter()
3348            .filter_map(move |(base_t, _)| {
3349                match base_t.kind() {
3350                    ty::Adt(base_def, args) if !base_def.is_enum() => {
3351                        let tcx = self.tcx;
3352                        let fields = &base_def.non_enum_variant().fields;
3353                        // Some struct, e.g. some that impl `Deref`, have all private fields
3354                        // because you're expected to deref them to access the _real_ fields.
3355                        // This, for example, will help us suggest accessing a field through a `Box<T>`.
3356                        if fields.iter().all(|field| !field.vis.is_accessible_from(mod_id, tcx)) {
3357                            return None;
3358                        }
3359                        return Some(
3360                            fields
3361                                .iter()
3362                                .filter(move |field| {
3363                                    field.vis.is_accessible_from(mod_id, tcx)
3364                                        && self.is_field_suggestable(field, hir_id, span)
3365                                })
3366                                // For compile-time reasons put a limit on number of fields we search
3367                                .take(100)
3368                                .map(|field_def| {
3369                                    (
3370                                        field_def.ident(self.tcx).normalize_to_macros_2_0(),
3371                                        field_def.ty(self.tcx, args).skip_norm_wip(),
3372                                    )
3373                                })
3374                                .collect::<Vec<_>>(),
3375                        );
3376                    }
3377                    ty::Tuple(types) => {
3378                        return Some(
3379                            types
3380                                .iter()
3381                                .enumerate()
3382                                // For compile-time reasons put a limit on number of fields we search
3383                                .take(100)
3384                                .map(|(i, ty)| (Ident::from_str(&i.to_string()), ty))
3385                                .collect::<Vec<_>>(),
3386                        );
3387                    }
3388                    _ => None,
3389                }
3390            })
3391            .collect()
3392    }
3393
3394    /// This method is called after we have encountered a missing field error to recursively
3395    /// search for the field
3396    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_for_nested_field_satisfying_condition_for_diag",
                                    "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(3396u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
                                    ::tracing_core::field::FieldSet::new(&["span",
                                                    "candidate_name", "candidate_ty", "field_path"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate_name)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate_ty)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&field_path)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<Vec<Ident>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if field_path.len() > 3 { return None; }
            field_path.push(candidate_name);
            if matches(candidate_name, candidate_ty) {
                return Some(field_path);
            }
            for nested_fields in
                self.get_field_candidates_considering_privacy_for_diag(span,
                    candidate_ty, mod_id, hir_id) {
                for field in nested_fields {
                    if let Some(field_path) =
                            self.check_for_nested_field_satisfying_condition_for_diag(span,
                                matches, field, field_path.clone(), mod_id, hir_id) {
                        return Some(field_path);
                    }
                }
            }
            None
        }
    }
}#[instrument(skip(self, matches, mod_id, hir_id), level = "debug")]
3397    pub(crate) fn check_for_nested_field_satisfying_condition_for_diag(
3398        &self,
3399        span: Span,
3400        matches: &impl Fn(Ident, Ty<'tcx>) -> bool,
3401        (candidate_name, candidate_ty): (Ident, Ty<'tcx>),
3402        mut field_path: Vec<Ident>,
3403        mod_id: DefId,
3404        hir_id: HirId,
3405    ) -> Option<Vec<Ident>> {
3406        if field_path.len() > 3 {
3407            // For compile-time reasons and to avoid infinite recursion we only check for fields
3408            // up to a depth of three
3409            return None;
3410        }
3411        field_path.push(candidate_name);
3412        if matches(candidate_name, candidate_ty) {
3413            return Some(field_path);
3414        }
3415        for nested_fields in self.get_field_candidates_considering_privacy_for_diag(
3416            span,
3417            candidate_ty,
3418            mod_id,
3419            hir_id,
3420        ) {
3421            // recursively search fields of `candidate_field` if it's a ty::Adt
3422            for field in nested_fields {
3423                if let Some(field_path) = self.check_for_nested_field_satisfying_condition_for_diag(
3424                    span,
3425                    matches,
3426                    field,
3427                    field_path.clone(),
3428                    mod_id,
3429                    hir_id,
3430                ) {
3431                    return Some(field_path);
3432                }
3433            }
3434        }
3435        None
3436    }
3437
3438    fn check_expr_index(
3439        &self,
3440        base: &'tcx hir::Expr<'tcx>,
3441        idx: &'tcx hir::Expr<'tcx>,
3442        expr: &'tcx hir::Expr<'tcx>,
3443        brackets_span: Span,
3444    ) -> Ty<'tcx> {
3445        let base_t = self.check_expr(base);
3446        let idx_t = self.check_expr(idx);
3447
3448        if base_t.references_error() {
3449            base_t
3450        } else if idx_t.references_error() {
3451            idx_t
3452        } else {
3453            let base_t = self.structurally_resolve_type(base.span, base_t);
3454            match self.lookup_indexing(expr, base, base_t, idx, idx_t) {
3455                Some((index_ty, element_ty)) => {
3456                    // two-phase not needed because index_ty is never mutable
3457                    self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3458                    self.select_obligations_where_possible(|errors| {
3459                        self.point_at_index(errors, idx.span);
3460                    });
3461                    element_ty
3462                }
3463                None => {
3464                    // Attempt to *shallowly* search for an impl which matches,
3465                    // but has nested obligations which are unsatisfied.
3466                    for (base_t, _) in self.autoderef(base.span, base_t).silence_errors() {
3467                        if let Some((_, index_ty, element_ty)) =
3468                            self.find_and_report_unsatisfied_index_impl(base, base_t)
3469                        {
3470                            self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3471                            return element_ty;
3472                        }
3473                    }
3474
3475                    let mut err = {
    let mut err =
        {
            self.dcx().struct_span_err(brackets_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("cannot index into a value of type `{0}`",
                                    base_t))
                        })).with_code(E0608)
        };
    if base_t.references_error() { err.downgrade_to_delayed_bug(); }
    err
}type_error_struct!(
3476                        self.dcx(),
3477                        brackets_span,
3478                        base_t,
3479                        E0608,
3480                        "cannot index into a value of type `{base_t}`",
3481                    );
3482                    // Try to give some advice about indexing tuples.
3483                    if let ty::Tuple(types) = base_t.kind() {
3484                        err.help(
3485                            "tuples are indexed with a dot and a literal index: `tuple.0`, `tuple.1`, etc.",
3486                        );
3487                        // If index is an unsuffixed integer, show the fixed expression:
3488                        if let ExprKind::Lit(lit) = idx.kind
3489                            && let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node
3490                            && i.get() < types.len().try_into().expect("tuple length fits in u128")
3491                        {
3492                            err.span_suggestion(
3493                                brackets_span,
3494                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to access tuple element `{0}`, use",
                i))
    })format!("to access tuple element `{i}`, use"),
3495                                ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!(".{0}", i)) })format!(".{i}"),
3496                                Applicability::MachineApplicable,
3497                            );
3498                        }
3499                    }
3500
3501                    if base_t.is_raw_ptr() && idx_t.is_integral() {
3502                        err.multipart_suggestion(
3503                            "consider using `wrapping_add` or `add` for indexing into raw pointer",
3504                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(base.span.between(idx.span), ".wrapping_add(".to_owned()),
                (idx.span.shrink_to_hi().until(expr.span.shrink_to_hi()),
                    ")".to_owned())]))vec![
3505                                (base.span.between(idx.span), ".wrapping_add(".to_owned()),
3506                                (
3507                                    idx.span.shrink_to_hi().until(expr.span.shrink_to_hi()),
3508                                    ")".to_owned(),
3509                                ),
3510                            ],
3511                            Applicability::MaybeIncorrect,
3512                        );
3513                    }
3514
3515                    let reported = err.emit();
3516                    Ty::new_error(self.tcx, reported)
3517                }
3518            }
3519        }
3520    }
3521
3522    /// Try to match an implementation of `Index` against a self type, and report
3523    /// the unsatisfied predicates that result from confirming this impl.
3524    ///
3525    /// Given an index expression, sometimes the `Self` type shallowly but does not
3526    /// deeply satisfy an impl predicate. Instead of simply saying that the type
3527    /// does not support being indexed, we want to point out exactly what nested
3528    /// predicates cause this to be, so that the user can add them to fix their code.
3529    fn find_and_report_unsatisfied_index_impl(
3530        &self,
3531        base_expr: &hir::Expr<'_>,
3532        base_ty: Ty<'tcx>,
3533    ) -> Option<(ErrorGuaranteed, Ty<'tcx>, Ty<'tcx>)> {
3534        let index_trait_def_id = self.tcx.lang_items().index_trait()?;
3535        let index_trait_output_def_id = self.tcx.get_diagnostic_item(sym::IndexOutput)?;
3536
3537        let mut relevant_impls = ::alloc::vec::Vec::new()vec![];
3538        self.tcx.for_each_relevant_impl(index_trait_def_id, base_ty, |impl_def_id| {
3539            relevant_impls.push(impl_def_id);
3540        });
3541        let [impl_def_id] = relevant_impls[..] else {
3542            // Only report unsatisfied impl predicates if there's one impl
3543            return None;
3544        };
3545
3546        self.commit_if_ok(|snapshot| {
3547            let outer_universe = self.universe();
3548
3549            let ocx = ObligationCtxt::new_with_diagnostics(self);
3550            let impl_args = self.fresh_args_for_item(base_expr.span, impl_def_id);
3551            let impl_trait_ref =
3552                self.tcx.impl_trait_ref(impl_def_id).instantiate(self.tcx, impl_args);
3553            let cause = self.misc(base_expr.span);
3554
3555            // Match the impl self type against the base ty. If this fails,
3556            // we just skip this impl, since it's not particularly useful.
3557            let impl_trait_ref = ocx.normalize(&cause, self.param_env, impl_trait_ref);
3558            ocx.eq(&cause, self.param_env, base_ty, impl_trait_ref.self_ty())?;
3559
3560            // Register the impl's predicates. One of these predicates
3561            // must be unsatisfied, or else we wouldn't have gotten here
3562            // in the first place.
3563            let unnormalized_predicates =
3564                self.tcx.predicates_of(impl_def_id).instantiate(self.tcx, impl_args);
3565            ocx.register_obligations(traits::predicates_for_generics(
3566                |idx, span| {
3567                    cause.clone().derived_cause(
3568                        ty::Binder::dummy(ty::TraitPredicate {
3569                            trait_ref: impl_trait_ref,
3570                            polarity: ty::PredicatePolarity::Positive,
3571                        }),
3572                        |derived| {
3573                            ObligationCauseCode::ImplDerived(Box::new(traits::ImplDerivedCause {
3574                                derived,
3575                                impl_or_alias_def_id: impl_def_id,
3576                                impl_def_predicate_index: Some(idx),
3577                                span,
3578                            }))
3579                        },
3580                    )
3581                },
3582                |pred| ocx.normalize(&cause, self.param_env, pred),
3583                self.param_env,
3584                unnormalized_predicates,
3585            ));
3586
3587            // Normalize the output type, which we can use later on as the
3588            // return type of the index expression...
3589            let element_ty = ocx.normalize(
3590                &cause,
3591                self.param_env,
3592                Unnormalized::new(Ty::new_projection_from_args(
3593                    self.tcx,
3594                    ty::IsRigid::No,
3595                    index_trait_output_def_id,
3596                    impl_trait_ref.args,
3597                )),
3598            );
3599
3600            let true_errors = ocx.try_evaluate_obligations();
3601
3602            // Do a leak check -- we can't really report a useful error here,
3603            // but it at least avoids an ICE when the error has to do with higher-ranked
3604            // lifetimes.
3605            self.leak_check(outer_universe, Some(snapshot))?;
3606
3607            // Bail if we have ambiguity errors, which we can't report in a useful way.
3608            let ambiguity_errors = ocx.evaluate_obligations_error_on_ambiguity();
3609            if true_errors.is_empty() && !ambiguity_errors.is_empty() {
3610                return Err(NoSolution);
3611            }
3612
3613            // There should be at least one error reported. If not, we
3614            // will still delay a span bug in `report_fulfillment_errors`.
3615            Ok::<_, NoSolution>((
3616                self.err_ctxt().report_fulfillment_errors(true_errors),
3617                impl_trait_ref.args.type_at(1),
3618                element_ty,
3619            ))
3620        })
3621        .ok()
3622    }
3623
3624    fn point_at_index(&self, errors: &mut Vec<traits::FulfillmentError<'tcx>>, span: Span) {
3625        let mut seen_preds = FxHashSet::default();
3626        // We re-sort here so that the outer most root obligations comes first, as we have the
3627        // subsequent weird logic to identify *every* relevant obligation for proper deduplication
3628        // of diagnostics.
3629        errors.sort_by_key(|error| error.root_obligation.recursion_depth);
3630        for error in errors {
3631            match (
3632                error.root_obligation.predicate.kind().skip_binder(),
3633                error.obligation.predicate.kind().skip_binder(),
3634            ) {
3635                (ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)), _)
3636                    if self.tcx.is_lang_item(predicate.trait_ref.def_id, LangItem::Index) =>
3637                {
3638                    seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3639                }
3640                (_, ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)))
3641                    if self.tcx.is_diagnostic_item(sym::SliceIndex, predicate.trait_ref.def_id) =>
3642                {
3643                    seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3644                }
3645                (root, pred) if seen_preds.contains(&pred) || seen_preds.contains(&root) => {}
3646                _ => continue,
3647            }
3648            error.obligation.cause.span = span;
3649        }
3650    }
3651
3652    fn check_expr_yield(
3653        &self,
3654        value: &'tcx hir::Expr<'tcx>,
3655        expr: &'tcx hir::Expr<'tcx>,
3656    ) -> Ty<'tcx> {
3657        match self.coroutine_types {
3658            Some(CoroutineTypes { resume_ty, yield_ty }) => {
3659                self.check_expr_coercible_to_type(value, yield_ty, None);
3660
3661                resume_ty
3662            }
3663            _ => {
3664                self.dcx().emit_err(YieldExprOutsideOfCoroutine { span: expr.span });
3665                // Avoid expressions without types during writeback (#78653).
3666                self.check_expr(value);
3667                self.tcx.types.unit
3668            }
3669        }
3670    }
3671
3672    fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
3673        let needs = if is_input { Needs::None } else { Needs::MutPlace };
3674        let ty = self.check_expr_with_needs(expr, needs);
3675        self.require_type_is_sized(ty, expr.span, ObligationCauseCode::InlineAsmSized);
3676
3677        if !is_input && !expr.is_syntactic_place_expr() {
3678            self.dcx()
3679                .struct_span_err(expr.span, "invalid asm output")
3680                .with_span_label(expr.span, "cannot assign to this expression")
3681                .emit();
3682        }
3683
3684        // If this is an input value, we require its type to be fully resolved
3685        // at this point. This allows us to provide helpful coercions which help
3686        // pass the type candidate list in a later pass.
3687        //
3688        // We don't require output types to be resolved at this point, which
3689        // allows them to be inferred based on how they are used later in the
3690        // function.
3691        if is_input {
3692            let ty = self.structurally_resolve_type(expr.span, ty);
3693            match *ty.kind() {
3694                ty::FnDef(..) => {
3695                    let fnptr_ty = Ty::new_fn_ptr(self.tcx, ty.fn_sig(self.tcx));
3696                    self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
3697                }
3698                ty::Ref(_, base_ty, mutbl) => {
3699                    let ptr_ty = Ty::new_ptr(self.tcx, base_ty, mutbl);
3700                    self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
3701                }
3702                _ => {}
3703            }
3704        }
3705    }
3706
3707    fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) -> Ty<'tcx> {
3708        if let rustc_ast::AsmMacro::NakedAsm = asm.asm_macro {
3709            if !{
        {
            'done:
                {
                for i in
                    ::rustc_hir::attrs::HasAttrs::get_attrs(self.body_def_id,
                        &self.tcx) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(Naked(..)) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self.tcx, self.body_def_id, Naked(..)) {
3710                self.tcx.dcx().emit_err(NakedAsmOutsideNakedFn { span });
3711            }
3712        }
3713
3714        let mut diverge = asm.asm_macro.diverges(asm.options);
3715
3716        for (op, _op_sp) in asm.operands {
3717            match *op {
3718                hir::InlineAsmOperand::In { expr, .. } => {
3719                    self.check_expr_asm_operand(expr, true);
3720                }
3721                hir::InlineAsmOperand::Out { expr: Some(expr), .. }
3722                | hir::InlineAsmOperand::InOut { expr, .. } => {
3723                    self.check_expr_asm_operand(expr, false);
3724                }
3725                hir::InlineAsmOperand::Out { expr: None, .. } => {}
3726                hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
3727                    self.check_expr_asm_operand(in_expr, true);
3728                    if let Some(out_expr) = out_expr {
3729                        self.check_expr_asm_operand(out_expr, false);
3730                    }
3731                }
3732                hir::InlineAsmOperand::Const { ref anon_const } => {
3733                    self.check_expr_const_block(anon_const, Expectation::NoExpectation);
3734                }
3735                hir::InlineAsmOperand::SymFn { expr } => {
3736                    self.check_expr(expr);
3737                }
3738                hir::InlineAsmOperand::SymStatic { .. } => {}
3739                hir::InlineAsmOperand::Label { block } => {
3740                    let previous_diverges = self.diverges.get();
3741
3742                    // The label blocks should have unit return value or diverge.
3743                    let ty = self.check_expr_block(block, ExpectHasType(self.tcx.types.unit));
3744                    if !ty.is_never() {
3745                        self.demand_suptype(block.span, self.tcx.types.unit, ty);
3746                        diverge = false;
3747                    }
3748
3749                    // We need this to avoid false unreachable warning when a label diverges.
3750                    self.diverges.set(previous_diverges);
3751                }
3752            }
3753        }
3754
3755        if diverge { self.tcx.types.never } else { self.tcx.types.unit }
3756    }
3757
3758    fn check_expr_offset_of(
3759        &self,
3760        container: &'tcx hir::Ty<'tcx>,
3761        fields: &[Ident],
3762        expr: &'tcx hir::Expr<'tcx>,
3763    ) -> Ty<'tcx> {
3764        let mut current_container = self.lower_ty(container).normalized;
3765        let mut field_indices = Vec::with_capacity(fields.len());
3766        let mut fields = fields.into_iter();
3767
3768        while let Some(&field) = fields.next() {
3769            let container = self.structurally_resolve_type(expr.span, current_container);
3770
3771            match container.kind() {
3772                ty::Adt(container_def, args) if container_def.is_enum() => {
3773                    let ident = self.tcx.adjust_ident(field, container_def.did());
3774
3775                    if !self.tcx.features().offset_of_enum() {
3776                        rustc_session::diagnostics::feature_err(
3777                            &self.tcx.sess,
3778                            sym::offset_of_enum,
3779                            ident.span,
3780                            "using enums in offset_of is experimental",
3781                        )
3782                        .emit();
3783                    }
3784
3785                    let Some((index, variant)) = container_def
3786                        .variants()
3787                        .iter_enumerated()
3788                        .find(|(_, v)| v.ident(self.tcx).normalize_to_macros_2_0() == ident)
3789                    else {
3790                        self.dcx()
3791                            .create_err(NoVariantNamed { span: ident.span, ident, ty: container })
3792                            .with_span_label(field.span, "variant not found")
3793                            .emit_unless_delay(container.references_error());
3794                        break;
3795                    };
3796                    let Some(&subfield) = fields.next() else {
3797                        {
    let mut err =
        {
            self.dcx().struct_span_err(ident.span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` is an enum variant; expected field at end of `offset_of`",
                                    ident))
                        })).with_code(E0795)
        };
    if container.references_error() { err.downgrade_to_delayed_bug(); }
    err
}type_error_struct!(
3798                            self.dcx(),
3799                            ident.span,
3800                            container,
3801                            E0795,
3802                            "`{ident}` is an enum variant; expected field at end of `offset_of`",
3803                        )
3804                        .with_span_label(field.span, "enum variant")
3805                        .emit();
3806                        break;
3807                    };
3808                    let (subident, sub_def_scope) = self.tcx.adjust_ident_and_get_scope(
3809                        subfield,
3810                        variant.def_id,
3811                        self.body_def_id,
3812                    );
3813
3814                    let Some((subindex, field)) = variant
3815                        .fields
3816                        .iter_enumerated()
3817                        .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == subident)
3818                    else {
3819                        self.dcx()
3820                            .create_err(NoFieldOnVariant {
3821                                span: ident.span,
3822                                container,
3823                                ident,
3824                                field: subfield,
3825                                enum_span: field.span,
3826                                field_span: subident.span,
3827                            })
3828                            .emit_unless_delay(container.references_error());
3829                        break;
3830                    };
3831
3832                    let field_ty = self.field_ty(expr.span, field, args);
3833
3834                    // Enums are anyway always sized. But just to safeguard against future
3835                    // language extensions, let's double-check.
3836                    self.require_type_is_sized(
3837                        field_ty,
3838                        expr.span,
3839                        ObligationCauseCode::FieldSized {
3840                            adt_kind: AdtKind::Enum,
3841                            span: self.tcx.def_span(field.did),
3842                            last: false,
3843                        },
3844                    );
3845
3846                    if field.vis.is_accessible_from(sub_def_scope, self.tcx) {
3847                        self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3848                    } else {
3849                        self.private_field_err(ident, container_def.did()).emit();
3850                    }
3851
3852                    // Save the index of all fields regardless of their visibility in case
3853                    // of error recovery.
3854                    field_indices.push((current_container, index, subindex));
3855                    current_container = field_ty;
3856
3857                    continue;
3858                }
3859                ty::Adt(container_def, args) => {
3860                    let (ident, def_scope) = self.tcx.adjust_ident_and_get_scope(
3861                        field,
3862                        container_def.did(),
3863                        self.body_def_id,
3864                    );
3865
3866                    let fields = &container_def.non_enum_variant().fields;
3867                    if let Some((index, field)) = fields
3868                        .iter_enumerated()
3869                        .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == ident)
3870                    {
3871                        let field_ty = self.field_ty(expr.span, field, args);
3872
3873                        if self.tcx.features().offset_of_slice() {
3874                            self.require_type_has_static_alignment(field_ty, expr.span);
3875                        } else {
3876                            self.require_type_is_sized(
3877                                field_ty,
3878                                expr.span,
3879                                ObligationCauseCode::Misc,
3880                            );
3881                        }
3882
3883                        if field.vis.is_accessible_from(def_scope, self.tcx) {
3884                            self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3885                        } else {
3886                            self.private_field_err(ident, container_def.did()).emit();
3887                        }
3888
3889                        // Save the index of all fields regardless of their visibility in case
3890                        // of error recovery.
3891                        field_indices.push((current_container, FIRST_VARIANT, index));
3892                        current_container = field_ty;
3893
3894                        continue;
3895                    }
3896                }
3897                ty::Tuple(tys) => {
3898                    if let Ok(index) = field.as_str().parse::<usize>()
3899                        && field.name == sym::integer(index)
3900                    {
3901                        if let Some(&field_ty) = tys.get(index) {
3902                            if self.tcx.features().offset_of_slice() {
3903                                self.require_type_has_static_alignment(field_ty, expr.span);
3904                            } else {
3905                                self.require_type_is_sized(
3906                                    field_ty,
3907                                    expr.span,
3908                                    ObligationCauseCode::Misc,
3909                                );
3910                            }
3911
3912                            field_indices.push((current_container, FIRST_VARIANT, index.into()));
3913                            current_container = field_ty;
3914
3915                            continue;
3916                        }
3917                    }
3918                }
3919                _ => (),
3920            };
3921
3922            self.no_such_field_err(field, container, expr).emit();
3923
3924            break;
3925        }
3926
3927        self.typeck_results.borrow_mut().offset_of_data_mut().insert(expr.hir_id, field_indices);
3928
3929        self.tcx.types.usize
3930    }
3931}