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