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