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 std::borrow::Cow;
9
10use rustc_abi::{FIRST_VARIANT, FieldIdx};
11use rustc_ast as ast;
12use rustc_ast::util::parser::ExprPrecedence;
13use rustc_attr_ir::find_attr;
14use rustc_attr_ir::lang_items::LangItem;
15use rustc_data_structures::fx::FxHashMap;
16use rustc_data_structures::unord::UnordMap;
17use rustc_errors::codes::*;
18use rustc_errors::{
19    Applicability, Diag, ErrorGuaranteed, StashKey, listify, pluralize, struct_span_code_err,
20};
21use rustc_hir as hir;
22use rustc_hir::def::{DefKind, Res};
23use rustc_hir::{ExprKind, HirId, QPath, is_range_literal};
24use rustc_hir_analysis::diagnostics::NoVariantNamed;
25use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _;
26use rustc_infer::infer::{self, RegionVariableOrigin};
27use rustc_infer::traits::WellFormedLoc;
28use rustc_infer::traits::query::NoSolution;
29use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
30use rustc_middle::ty::error::{ExpectedFound, TypeError};
31use rustc_middle::ty::{self, AdtKind, ConstKind, GenericArgs, Ty, TypeVisitableExt, Unnormalized};
32use rustc_session::diagnostics::feature_err;
33use rustc_span::hygiene::DesugaringKind;
34use rustc_span::{Ident, Span, Spanned, Symbol, bug, kw, span_bug, sym};
35use rustc_trait_selection::infer::InferCtxtExt;
36use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt};
37use tracing::{debug, instrument, trace};
38
39use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation};
40use crate::callee::SplatLoweringInfo;
41use crate::coercion::CoerceMany;
42use crate::diagnostics::{
43    AddressOfTemporaryTaken, BaseExpressionDoubleDot, BaseExpressionDoubleDotAddExpr,
44    BaseExpressionDoubleDotRemove, CantDereference, DelegationInvalidAdtForReturnWrapping,
45    ExprParenthesesNeeded, FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct,
46    NakedAsmOutsideNakedFn, NoFieldOnVariant, ReturnLikeStatementKind, StructExprNonExhaustive,
47    YieldExprOutsideOfCoroutine,
48};
49use crate::op::contains_let_in_chain;
50use crate::{
51    BreakableCtxt, CoroutineTypes, Diverges, FnCtxt, GatherLocalsVisitor, Needs,
52    TupleArgumentsFlag, cast, fatally_break_rust, type_error_struct,
53};
54
55impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
56    pub(crate) fn precedence(&self, expr: &hir::Expr<'_>) -> ExprPrecedence {
57        let has_attr = |id: HirId| -> bool {
58            self.tcx
59                .hir_attrs(id)
60                .iter()
61                .any(rustc_attr_ir::Attribute::is_prefix_attr_for_suggestions)
62        };
63
64        // Special case: range expressions are desugared to struct literals in HIR,
65        // so they would normally return `Unambiguous` precedence in expr.precedence.
66        // we should return `Range` precedence for correct parenthesization in suggestions.
67        if is_range_literal(expr) {
68            return ExprPrecedence::Range;
69        }
70
71        expr.precedence(&has_attr)
72    }
73
74    /// Check an expr with an expectation type, and also demand that the expr's
75    /// evaluated type is a subtype of the expectation at the end. This is a
76    /// *hard* requirement.
77    pub(crate) fn check_expr_has_type_or_error(
78        &self,
79        expr: &'tcx hir::Expr<'tcx>,
80        expected_ty: Ty<'tcx>,
81        extend_err: impl FnOnce(&mut Diag<'_>),
82    ) -> Ty<'tcx> {
83        let mut ty = self.check_expr_with_expectation(expr, ExpectHasType(expected_ty));
84
85        // While we don't allow *arbitrary* coercions here, we *do* allow
86        // coercions from ! to `expected`.
87        if self.deeply_resolve_ignoring_regions_with_obligations(ty).is_never()
88            && self.tcx.expr_guaranteed_to_constitute_read_for_never(expr)
89        {
90            if let Some(adjustments) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
91                let reported = self.dcx().span_delayed_bug(
92                    expr.span,
93                    "expression with never type wound up being adjusted",
94                );
95
96                return if let [Adjustment { kind: Adjust::NeverToAny, target }] = &adjustments[..] {
97                    target.to_owned()
98                } else {
99                    Ty::new_error(self.tcx(), reported)
100                };
101            }
102
103            let adj_ty = self.next_ty_var(expr.span);
104            self.apply_adjustments(
105                expr,
106                ::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 }],
107            );
108            ty = adj_ty;
109        }
110
111        if let Err(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
112            let _ = self.emit_type_mismatch_suggestions(
113                &mut err,
114                expr.peel_drop_temps(),
115                ty,
116                expected_ty,
117                None,
118                None,
119            );
120            extend_err(&mut err);
121            err.emit();
122        }
123        ty
124    }
125
126    /// Check an expr with an expectation type, and also demand that the expr's
127    /// evaluated type is a coercible to the expectation at the end. This is a
128    /// *hard* requirement.
129    pub(super) fn check_expr_coercible_to_type(
130        &self,
131        expr: &'tcx hir::Expr<'tcx>,
132        expected: Ty<'tcx>,
133        expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
134    ) -> Ty<'tcx> {
135        self.check_expr_coercible_to_type_or_error(expr, expected, expected_ty_expr, |_, _| {})
136    }
137
138    pub(crate) fn check_expr_coercible_to_type_or_error(
139        &self,
140        expr: &'tcx hir::Expr<'tcx>,
141        expected: Ty<'tcx>,
142        expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
143        extend_err: impl FnOnce(&mut Diag<'_>, Ty<'tcx>),
144    ) -> Ty<'tcx> {
145        let ty = self.check_expr_with_hint(expr, expected);
146        // checks don't need two phase
147        match self.demand_coerce_diag(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No) {
148            Ok(ty) => ty,
149            Err(mut err) => {
150                extend_err(&mut err, ty);
151                err.emit();
152                // Return the original type instead of an error type here, otherwise the type of `x` in
153                // `let x: u32 = ();` will be a type error, causing all subsequent usages of `x` to not
154                // report errors, even though `x` is definitely `u32`.
155                expected
156            }
157        }
158    }
159
160    /// Check an expr with an expectation type. Don't actually enforce that expectation
161    /// is related to the expr's evaluated type via subtyping or coercion. This is
162    /// usually called because we want to do that subtype/coerce call manually for better
163    /// diagnostics.
164    pub(super) fn check_expr_with_hint(
165        &self,
166        expr: &'tcx hir::Expr<'tcx>,
167        expected: Ty<'tcx>,
168    ) -> Ty<'tcx> {
169        self.check_expr_with_expectation(expr, ExpectHasType(expected))
170    }
171
172    /// Check an expr with an expectation type, and also [`Needs`] which will
173    /// prompt typeck to convert any implicit immutable derefs to mutable derefs.
174    fn check_expr_with_expectation_and_needs(
175        &self,
176        expr: &'tcx hir::Expr<'tcx>,
177        expected: Expectation<'tcx>,
178        needs: Needs,
179    ) -> Ty<'tcx> {
180        let ty = self.check_expr_with_expectation(expr, expected);
181
182        // If the expression is used in a place whether mutable place is required
183        // e.g. LHS of assignment, perform the conversion.
184        if let Needs::MutPlace = needs {
185            self.convert_place_derefs_to_mutable(expr);
186        }
187
188        ty
189    }
190
191    /// Check an expr with no expectations.
192    pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
193        self.check_expr_with_expectation(expr, NoExpectation)
194    }
195
196    /// Check an expr with no expectations, but with [`Needs`] which will
197    /// prompt typeck to convert any implicit immutable derefs to mutable derefs.
198    pub(super) fn check_expr_with_needs(
199        &self,
200        expr: &'tcx hir::Expr<'tcx>,
201        needs: Needs,
202    ) -> Ty<'tcx> {
203        self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
204    }
205
206    /// Check an expr with an expectation type which may be used to eagerly
207    /// guide inference when evaluating that expr.
208    {}
#[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/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(208u32),
                                    ::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")]
209    pub(super) fn check_expr_with_expectation(
210        &self,
211        expr: &'tcx hir::Expr<'tcx>,
212        expected: Expectation<'tcx>,
213    ) -> Ty<'tcx> {
214        self.check_expr_with_expectation_and_args(expr, expected, None)
215    }
216
217    /// Same as [`Self::check_expr_with_expectation`], but allows us to pass in
218    /// the arguments of a [`ExprKind::Call`] when evaluating its callee that
219    /// is an [`ExprKind::Path`]. We use this to refine the spans for certain
220    /// well-formedness guarantees for the path expr.
221    pub(super) fn check_expr_with_expectation_and_args(
222        &self,
223        expr: &'tcx hir::Expr<'tcx>,
224        expected: Expectation<'tcx>,
225        call_expr_and_args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
226    ) -> Ty<'tcx> {
227        if self.tcx().sess.verbose_internals() {
228            // make this code only run with -Zverbose-internals because it is probably slow
229            if let Ok(lint_str) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
230                if !lint_str.contains('\n') {
231                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs:231",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(231u32),
                        ::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}");
232                } else {
233                    let mut lines = lint_str.lines();
234                    if let Some(line0) = lines.next() {
235                        let remaining_lines = lines.count();
236                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs:236",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(236u32),
                        ::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}");
237                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs:237",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(237u32),
                        ::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)");
238                    }
239                }
240            }
241        }
242
243        // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
244        // without the final expr (e.g. `try { return; }`). We don't want to generate an
245        // unreachable_code lint for it since warnings for autogenerated code are confusing.
246        let is_try_block_generated_unit_expr = match expr.kind {
247            ExprKind::Call(_, [arg]) => {
248                expr.span.is_desugaring(DesugaringKind::TryBlock)
249                    && arg.span.is_desugaring(DesugaringKind::TryBlock)
250            }
251            _ => false,
252        };
253
254        // Warn for expressions after diverging siblings.
255        if !is_try_block_generated_unit_expr {
256            self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
257        }
258
259        // Whether a past expression diverges doesn't affect typechecking of this expression, so we
260        // reset `diverges` while checking `expr`.
261        let old_diverges = self.diverges.replace(Diverges::Maybe);
262
263        if self.is_whole_body.replace(false) {
264            // If this expression is the whole body and the function diverges because of its
265            // arguments, we check this here to ensure the body is considered to diverge.
266            self.diverges.set(self.function_diverges_because_of_empty_arguments.get())
267        };
268
269        let ty = match &expr.kind {
270            // Intercept the callee path expr and give it better spans.
271            hir::ExprKind::Path(
272                qpath @ (hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)),
273            ) => self.check_expr_path(qpath, expr, call_expr_and_args),
274            _ => self.check_expr_kind(expr, expected),
275        };
276        let ty = self.deeply_resolve_ignoring_regions(ty);
277
278        // Warn for non-block expressions with diverging children.
279        match expr.kind {
280            ExprKind::Block(..)
281            | ExprKind::If(..)
282            | ExprKind::Let(..)
283            | ExprKind::Loop(..)
284            | ExprKind::Match(..)
285            | ExprKind::Become(..) => {}
286            // Do not warn on `as` casts from never to any,
287            // they are sometimes required to appeal typeck.
288            ExprKind::Cast(_, _) => {}
289            // If `expr` is a result of desugaring the try block and is an ok-wrapped
290            // diverging expression (e.g. it arose from desugaring of `try { return }`),
291            // we skip issuing a warning because it is autogenerated code.
292            ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {}
293            // Likewise, do not lint unreachable code injected via contracts desugaring.
294            ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::Contract) => {}
295            ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"),
296            ExprKind::MethodCall(segment, ..) => {
297                self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call")
298            }
299            _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
300        }
301
302        // Any expression that produces a value of type `!` must have diverged,
303        // unless it's a place expression that isn't being read from, in which case
304        // diverging would be unsound since we may never actually read the `!`.
305        // e.g. `let _ = *never_ptr;` with `never_ptr: *const !`.
306        if self.deeply_resolve_ignoring_regions_with_obligations(ty).is_never()
307            && self.tcx.expr_guaranteed_to_constitute_read_for_never(expr)
308        {
309            self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
310        }
311
312        // Record the type, which applies it effects.
313        // We need to do this after the warning above, so that
314        // we don't warn for the diverging expression itself.
315        self.write_ty(expr.hir_id, ty);
316
317        // Combine the diverging and has_error flags.
318        self.diverges.set(self.diverges.get() | old_diverges);
319
320        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs:320",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(320u32),
                        ::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));
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/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs:321",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/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!("... {0:?}, expected is {1:?}",
                                                    ty, expected) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("... {:?}, expected is {:?}", ty, expected);
322
323        ty
324    }
325
326    {}
#[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/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(326u32),
                                    ::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/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs:332",
                                    "rustc_hir_typeck::expr", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                                    ::tracing_core::__macro_support::Option::Some(332u32),
                                    ::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")]
327    fn check_expr_kind(
328        &self,
329        expr: &'tcx hir::Expr<'tcx>,
330        expected: Expectation<'tcx>,
331    ) -> Ty<'tcx> {
332        trace!("expr={:#?}", expr);
333
334        let tcx = self.tcx;
335        match expr.kind {
336            ExprKind::Lit(ref lit) => self.check_expr_lit(lit, expr.hir_id, expected),
337            ExprKind::Binary(op, lhs, rhs) => self.check_expr_binop(expr, op, lhs, rhs, expected),
338            ExprKind::Assign(lhs, rhs, span) => {
339                self.check_expr_assign(expr, expected, lhs, rhs, span)
340            }
341            ExprKind::AssignOp(op, lhs, rhs) => {
342                self.check_expr_assign_op(expr, op, lhs, rhs, expected)
343            }
344            ExprKind::Unary(unop, oprnd) => self.check_expr_unop(unop, oprnd, expected, expr),
345            ExprKind::AddrOf(kind, mutbl, oprnd) => {
346                self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
347            }
348            ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr, None),
349            ExprKind::InlineAsm(asm) => {
350                // We defer some asm checks as we may not have resolved the input and output types yet (they may still be infer vars).
351                self.deferred_asm_checks.borrow_mut().push((asm, expr.hir_id));
352                self.check_expr_asm(asm, expr.span)
353            }
354            ExprKind::OffsetOf(container, fields) => {
355                self.check_expr_offset_of(container, fields, expr)
356            }
357            ExprKind::Break(destination, ref expr_opt) => {
358                self.check_expr_break(destination, expr_opt.as_deref(), expr)
359            }
360            ExprKind::Continue(destination) => self.check_expr_continue(destination, expr),
361            ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
362            ExprKind::Become(call) => self.check_expr_become(call, expr),
363            ExprKind::Let(let_expr) => self.check_expr_let(let_expr, expr.hir_id),
364            ExprKind::Loop(body, _, source, _) => {
365                self.check_expr_loop(body, source, expected, expr)
366            }
367            ExprKind::Match(discrim, arms, match_src) => {
368                self.check_expr_match(expr, discrim, arms, expected, match_src)
369            }
370            ExprKind::Closure(closure) => self.check_expr_closure(closure, expr.span, expected),
371            ExprKind::Block(body, _) => self.check_expr_block(body, expected),
372            ExprKind::Call(callee, args) => self.check_expr_call(expr, callee, args, expected),
373            ExprKind::Use(used_expr, _) => self.check_expr_use(used_expr, expected),
374            ExprKind::MethodCall(segment, receiver, args, _) => {
375                self.check_expr_method_call(expr, segment, receiver, args, expected)
376            }
377            ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr),
378            ExprKind::Type(e, t) => {
379                let ascribed_ty = self.lower_ty_saving_user_provided_ty(t);
380                let ty = self.check_expr_with_hint(e, ascribed_ty);
381                self.demand_eqtype(e.span, ascribed_ty, ty);
382                ascribed_ty
383            }
384            ExprKind::If(cond, then_expr, opt_else_expr) => {
385                self.check_expr_if(expr.hir_id, cond, then_expr, opt_else_expr, expr.span, expected)
386            }
387            ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected),
388            ExprKind::Array(args) => self.check_expr_array(args, expected, expr),
389            ExprKind::ConstBlock(ref block) => self.check_expr_const_block(block, expected),
390            ExprKind::Repeat(element, ref count) => {
391                self.check_expr_repeat(element, count, expected, expr)
392            }
393            ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr),
394            ExprKind::Struct(qpath, fields, ref base_expr) => {
395                self.check_expr_struct(expr, expected, qpath, fields, base_expr)
396            }
397            ExprKind::Field(base, field) => self.check_expr_field(expr, base, field, expected),
398            ExprKind::Index(base, idx, brackets_span) => {
399                self.check_expr_index(base, idx, expr, brackets_span)
400            }
401            ExprKind::Yield(value, _) => self.check_expr_yield(value, expr),
402            ExprKind::UnsafeBinderCast(kind, inner_expr, ty) => {
403                self.check_expr_unsafe_binder_cast(expr.span, kind, inner_expr, ty, expected)
404            }
405            ExprKind::Err(guar) => Ty::new_error(tcx, guar),
406        }
407    }
408
409    fn check_expr_unop(
410        &self,
411        unop: hir::UnOp,
412        oprnd: &'tcx hir::Expr<'tcx>,
413        expected: Expectation<'tcx>,
414        expr: &'tcx hir::Expr<'tcx>,
415    ) -> Ty<'tcx> {
416        let tcx = self.tcx;
417        let expected_inner = match unop {
418            hir::UnOp::Not | hir::UnOp::Neg => expected,
419            hir::UnOp::Deref => NoExpectation,
420        };
421        let oprnd_t = self.check_expr_with_expectation(oprnd, expected_inner);
422
423        if let Err(guar) = oprnd_t.error_reported() {
424            return Ty::new_error(tcx, guar);
425        }
426
427        // Resolve what we can for `Not` and `Neg`, but allow later constraints
428        // to determine an unresolved operand type,
429        // so we call `deeply_resolve_ignoring_regions_with_obligations` for them.
430        match unop {
431            hir::UnOp::Deref => {
432                // Dereferencing must distinguish builtin pointers from
433                // overloaded `Deref`, so it still requires a structurally resolved type.
434                //
435                // This is necessary as raw pointers do not implement `Deref`.
436                let oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t);
437                self.lookup_derefing(expr, oprnd, oprnd_t).unwrap_or_else(|| {
438                    let mut err =
439                        self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t });
440                    let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None);
441                    if let Some(sp) =
442                        tcx.sess.psess.complete_stmt_exprs_before_bin_op_lookalike.borrow().get(&sp)
443                    {
444                        err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
445                    }
446                    // The operand may be an uncalled function, in which case it is its return type
447                    // the user meant to dereference. Only suggest the call when that return type is
448                    // itself dereferenceable, mirroring the checks `lookup_derefing` just failed.
449                    self.suggest_fn_call(&mut err, oprnd, oprnd_t, |output| {
450                        output.builtin_deref(true).is_some()
451                            || self.tcx.lang_items().deref_trait().is_some_and(|deref_trait| {
452                                self.type_implements_trait(deref_trait, [output], self.param_env)
453                                    .may_apply()
454                            })
455                    });
456                    Ty::new_error(tcx, err.emit_err())
457                })
458            }
459            hir::UnOp::Not => {
460                let oprnd_t = self.deeply_resolve_ignoring_regions_with_obligations(oprnd_t);
461                let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
462                // If it's builtin, we can reuse the type, this helps inference.
463                if oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool { oprnd_t } else { result }
464            }
465            hir::UnOp::Neg => {
466                let oprnd_t = self.deeply_resolve_ignoring_regions_with_obligations(oprnd_t);
467                let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
468                // If it's builtin, we can reuse the type, this helps inference.
469                if oprnd_t.is_numeric() { oprnd_t } else { result }
470            }
471        }
472    }
473
474    fn check_expr_addr_of(
475        &self,
476        kind: hir::BorrowKind,
477        mutbl: hir::Mutability,
478        oprnd: &'tcx hir::Expr<'tcx>,
479        expected: Expectation<'tcx>,
480        expr: &'tcx hir::Expr<'tcx>,
481    ) -> Ty<'tcx> {
482        let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
483            match self.deeply_resolve_ignoring_regions_with_obligations(ty).kind() {
484                ty::Ref(_, ty, _) | ty::RawPtr(ty, _) => {
485                    if oprnd.is_syntactic_place_expr() {
486                        // Places may legitimately have unsized types.
487                        // For example, dereferences of a wide pointer and
488                        // the last field of a struct can be unsized.
489                        ExpectHasType(*ty)
490                    } else {
491                        Expectation::rvalue_hint(self, *ty)
492                    }
493                }
494                _ => NoExpectation,
495            }
496        });
497        let ty =
498            self.check_expr_with_expectation_and_needs(oprnd, hint, Needs::maybe_mut_place(mutbl));
499        if let Err(guar) = ty.error_reported() {
500            return Ty::new_error(self.tcx, guar);
501        }
502
503        match kind {
504            hir::BorrowKind::Raw => {
505                self.check_named_place_expr(oprnd);
506                Ty::new_ptr(self.tcx, ty, mutbl)
507            }
508            hir::BorrowKind::Ref | hir::BorrowKind::Pin => {
509                // Note: at this point, we cannot say what the best lifetime
510                // is to use for resulting pointer. We want to use the
511                // shortest lifetime possible so as to avoid spurious borrowck
512                // errors. Moreover, the longest lifetime will depend on the
513                // precise details of the value whose address is being taken
514                // (and how long it is valid), which we don't know yet until
515                // type inference is complete.
516                //
517                // Therefore, here we simply generate a region variable. The
518                // region inferencer will then select a suitable value.
519                // Finally, borrowck will infer the value of the region again,
520                // this time with enough precision to check that the value
521                // whose address was taken can actually be made to live as long
522                // as it needs to live.
523                let region = self.next_region_var(RegionVariableOrigin::BorrowRegion(expr.span));
524                match kind {
525                    hir::BorrowKind::Ref => Ty::new_ref(self.tcx, region, ty, mutbl),
526                    hir::BorrowKind::Pin => Ty::new_pinned_ref(self.tcx, region, ty, mutbl),
527                    _ => ::core::panicking::unreachable_default_msg()unreachable!(),
528                }
529            }
530        }
531    }
532
533    /// Does this expression refer to a place that either:
534    /// * Is based on a local or static.
535    /// * Contains a dereference
536    /// Note that the adjustments for the children of `expr` should already
537    /// have been resolved.
538    fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
539        let is_named = oprnd.is_place_expr(|base| {
540            // Allow raw borrows if there are any deref adjustments.
541            //
542            // const VAL: (i32,) = (0,);
543            // const REF: &(i32,) = &(0,);
544            //
545            // &raw const VAL.0;            // ERROR
546            // &raw const REF.0;            // OK, same as &raw const (*REF).0;
547            //
548            // This is maybe too permissive, since it allows
549            // `let u = &raw const Box::new((1,)).0`, which creates an
550            // immediately dangling raw pointer.
551            self.typeck_results
552                .borrow()
553                .adjustments()
554                .get(base.hir_id)
555                .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(_))))
556        });
557        if !is_named {
558            self.dcx().emit_err(AddressOfTemporaryTaken { span: oprnd.span });
559        }
560    }
561
562    pub(crate) fn check_expr_path(
563        &self,
564        qpath: &'tcx hir::QPath<'tcx>,
565        expr: &'tcx hir::Expr<'tcx>,
566        call_expr_and_args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
567    ) -> Ty<'tcx> {
568        let tcx = self.tcx;
569
570        if let Some((_, [arg])) = call_expr_and_args
571            && let QPath::Resolved(_, path) = qpath
572            && let Res::Def(_, def_id) = path.res
573            && let Some(lang_item) = tcx.lang_items().from_def_id(def_id)
574        {
575            let code = match lang_item {
576                LangItem::IntoFutureIntoFuture
577                    if expr.span.is_desugaring(DesugaringKind::Await) =>
578                {
579                    Some(ObligationCauseCode::AwaitableExpr(arg.hir_id))
580                }
581                LangItem::IntoIterIntoIter | LangItem::IteratorNext
582                    if expr.span.is_desugaring(DesugaringKind::ForLoop) =>
583                {
584                    Some(ObligationCauseCode::ForLoopIterator(arg.hir_id))
585                }
586                LangItem::TryTraitFromOutput
587                    if expr.span.is_desugaring(DesugaringKind::TryBlock) =>
588                {
589                    // FIXME it's a try block, not a question mark
590                    Some(ObligationCauseCode::QuestionMark)
591                }
592                LangItem::TryTraitBranch | LangItem::TryTraitFromResidual
593                    if expr.span.is_desugaring(DesugaringKind::QuestionMark) =>
594                {
595                    Some(ObligationCauseCode::QuestionMark)
596                }
597                _ => None,
598            };
599            if let Some(code) = code {
600                let args = self.fresh_args_for_item(expr.span, def_id);
601                self.add_required_obligations_with_code(expr.span, def_id, args, |_, _| {
602                    code.clone()
603                });
604                return tcx.type_of(def_id).instantiate(tcx, args).skip_norm_wip();
605            }
606        }
607
608        let (res, opt_ty, segs) =
609            self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span);
610        let ty = match res {
611            Res::Err => {
612                self.suggest_assoc_method_call(segs);
613                let e =
614                    self.dcx().span_delayed_bug(qpath.span(), "`Res::Err` but no error emitted");
615                Ty::new_error(tcx, e)
616            }
617            Res::Def(DefKind::Variant, _) => {
618                let e = self.report_unexpected_variant_res(
619                    res,
620                    Some(expr),
621                    &[],
622                    qpath,
623                    expr.span,
624                    E0533,
625                    "value",
626                );
627                Ty::new_error(tcx, e)
628            }
629            _ => {
630                self.instantiate_value_path(
631                    segs,
632                    opt_ty,
633                    res,
634                    call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
635                    expr.span,
636                    expr.hir_id,
637                    call_expr_and_args.map(|(_, args)| args),
638                )
639                .0
640            }
641        };
642
643        if let ty::FnDef(did, args) = *ty.kind() {
644            let fn_sig = ty.fn_sig(tcx);
645
646            if tcx.is_rustc_intrinsic(did, sym::transmute) {
647                let Some(from) = fn_sig.inputs().skip_binder().get(0) else {
648                    ::rustc_span::macros::bug_impl(Some(tcx.def_span(did)),
    format_args!("intrinsic fn `transmute` defined with no parameters"),
    Location::caller());span_bug!(
649                        tcx.def_span(did),
650                        "intrinsic fn `transmute` defined with no parameters"
651                    );
652                };
653                let to = fn_sig.output().skip_binder();
654                // We defer the transmute to the end of typeck, once all inference vars have
655                // been resolved or we errored. This is important as we can only check transmute
656                // on concrete types, but the output type may not be known yet (it would only
657                // be known if explicitly specified via turbofish).
658                self.deferred_transmute_checks.borrow_mut().push((*from, to, expr.hir_id));
659            }
660            if !tcx.sess.opts.unstable_opts.offload.is_empty()
661                && tcx.is_rustc_intrinsic(did, sym::offload)
662            {
663                let args = args.skip_binder();
664                let f = args.type_at(0);
665                let t = args.type_at(1);
666                let r = args.type_at(2);
667                // Defer offload checks to check generics later once types are fully inferred.
668                self.deferred_offload_checks.borrow_mut().push((f, t, r, expr.hir_id));
669            }
670            if !tcx.features().unsized_fn_params() {
671                // We want to remove some Sized bounds from std functions,
672                // but don't want to expose the removal to stable Rust.
673                // i.e., we don't want to allow
674                //
675                // ```rust
676                // drop as fn(str);
677                // ```
678                //
679                // to work in stable even if the Sized bound on `drop` is relaxed.
680                for i in 0..fn_sig.inputs().skip_binder().len() {
681                    // We just want to check sizedness, so instead of introducing
682                    // placeholder lifetimes with probing, we just replace higher lifetimes
683                    // with fresh vars.
684                    let span = call_expr_and_args
685                        .and_then(|(_, args)| args.get(i))
686                        .map_or(expr.span, |arg| arg.span);
687                    let input = self.instantiate_binder_with_fresh_vars(
688                        span,
689                        infer::BoundRegionConversionTime::FnCall,
690                        fn_sig.input(i),
691                    );
692                    self.require_type_is_sized_deferred(
693                        input,
694                        span,
695                        ObligationCauseCode::SizedArgumentType(None),
696                    );
697                }
698            }
699            // Here we want to prevent struct constructors from returning unsized types,
700            // which can happen with fn pointer coercion on stable.
701            // Also, as we just want to check sizedness, instead of introducing
702            // placeholder lifetimes with probing, we just replace higher lifetimes
703            // with fresh vars.
704            let output = self.instantiate_binder_with_fresh_vars(
705                expr.span,
706                infer::BoundRegionConversionTime::FnCall,
707                fn_sig.output(),
708            );
709            self.require_type_is_sized_deferred(
710                output,
711                call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
712                ObligationCauseCode::SizedCallReturnType(expr.hir_id),
713            );
714        }
715
716        // We always require that the type provided as the value for
717        // a type parameter outlives the moment of instantiation.
718        let args = self.typeck_results.borrow().node_args(expr.hir_id);
719        self.add_wf_bounds(args, expr.span, expr.hir_id);
720
721        ty
722    }
723
724    fn check_expr_break(
725        &self,
726        destination: hir::Destination,
727        expr_opt: Option<&'tcx hir::Expr<'tcx>>,
728        expr: &'tcx hir::Expr<'tcx>,
729    ) -> Ty<'tcx> {
730        let tcx = self.tcx;
731        if let Ok(target_id) = destination.target_id {
732            let (e_ty, cause);
733            if let Some(e) = expr_opt {
734                // If this is a break with a value, we need to type-check
735                // the expression. Get an expected type from the loop context.
736                let opt_coerce_to = {
737                    // We should release `enclosing_breakables` before the `check_expr_with_hint`
738                    // below, so can't move this block of code to the enclosing scope and share
739                    // `ctxt` with the second `enclosing_breakables` borrow below.
740                    let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
741                    match enclosing_breakables.opt_find_breakable(target_id) {
742                        Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
743                        None => {
744                            // Avoid ICE when `break` is inside a closure (#65383).
745                            return Ty::new_error_with_message(
746                                tcx,
747                                expr.span,
748                                "break was outside loop, but no error was emitted",
749                            );
750                        }
751                    }
752                };
753
754                // If the loop context is not a `loop { }`, then break with
755                // a value is illegal, and `opt_coerce_to` will be `None`.
756                // Set expectation to error in that case and set tainted
757                // by error (#114529)
758                let coerce_to = opt_coerce_to.unwrap_or_else(|| {
759                    let guar = self.dcx().span_delayed_bug(
760                        expr.span,
761                        "illegal break with value found but no error reported",
762                    );
763                    self.set_tainted_by_errors(guar);
764                    Ty::new_error(tcx, guar)
765                });
766
767                // Recurse without `enclosing_breakables` borrowed.
768                e_ty = self.check_expr_with_hint(e, coerce_to);
769                cause = self.misc(e.span);
770            } else {
771                // Otherwise, this is a break *without* a value. That's
772                // always legal, and is equivalent to `break ()`.
773                e_ty = tcx.types.unit;
774                cause = self.misc(expr.span);
775            }
776
777            // Now that we have type-checked `expr_opt`, borrow
778            // the `enclosing_loops` field and let's coerce the
779            // type of `expr_opt` into what is expected.
780            let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
781            let Some(ctxt) = enclosing_breakables.opt_find_breakable(target_id) else {
782                // Avoid ICE when `break` is inside a closure (#65383).
783                return Ty::new_error_with_message(
784                    tcx,
785                    expr.span,
786                    "break was outside loop, but no error was emitted",
787                );
788            };
789
790            if let Some(ref mut coerce) = ctxt.coerce {
791                if let Some(e) = expr_opt {
792                    coerce.coerce(self, &cause, e, e_ty);
793                } else {
794                    if !e_ty.is_unit() {
    ::core::panicking::panic("assertion failed: e_ty.is_unit()")
};assert!(e_ty.is_unit());
795                    let ty = coerce.expected_ty();
796                    coerce.coerce_forced_unit(
797                        self,
798                        &cause,
799                        |mut err| {
800                            self.suggest_missing_semicolon(&mut err, expr, e_ty, false, false);
801                            self.suggest_mismatched_types_on_tail(
802                                &mut err, expr, ty, e_ty, target_id,
803                            );
804                            let error =
805                                Some(TypeError::Sorts(ExpectedFound { expected: ty, found: e_ty }));
806                            self.annotate_loop_expected_due_to_inference(err, expr, error);
807                            if let Some(val) =
808                                self.err_ctxt().ty_kind_suggestion(self.param_env, ty)
809                            {
810                                err.span_suggestion_verbose(
811                                    expr.span.shrink_to_hi(),
812                                    "give the `break` a value of the expected type",
813                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {0}", val))
    })format!(" {val}"),
814                                    Applicability::HasPlaceholders,
815                                );
816                            }
817                        },
818                        false,
819                    );
820                }
821            } else {
822                // If `ctxt.coerce` is `None`, we can just ignore
823                // the type of the expression. This is because
824                // either this was a break *without* a value, in
825                // which case it is always a legal type (`()`), or
826                // else an error would have been flagged by the
827                // `loops` pass for using break with an expression
828                // where you are not supposed to.
829                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());
830            }
831
832            // If we encountered a `break`, then (no surprise) it may be possible to break from the
833            // loop... unless the value being returned from the loop diverges itself, e.g.
834            // `break return 5` or `break loop {}`.
835            ctxt.may_break |= !self.diverges.get().is_always();
836
837            // the type of a `break` is always `!`, since it diverges
838            tcx.types.never
839        } else {
840            // Otherwise, we failed to find the enclosing loop;
841            // this can only happen if the `break` was not
842            // inside a loop at all, which is caught by the
843            // loop-checking pass.
844            let err = Ty::new_error_with_message(
845                self.tcx,
846                expr.span,
847                "break was outside loop, but no error was emitted",
848            );
849
850            // We still need to assign a type to the inner expression to
851            // prevent the ICE in #43162.
852            if let Some(e) = expr_opt {
853                self.check_expr_with_hint(e, err);
854
855                // ... except when we try to 'break rust;'.
856                // ICE this expression in particular (see #43162).
857                if let ExprKind::Path(QPath::Resolved(_, path)) = e.kind {
858                    if let [segment] = path.segments
859                        && segment.ident.name == sym::rust
860                    {
861                        fatally_break_rust(self.tcx, expr.span);
862                    }
863                }
864            }
865
866            // There was an error; make type-check fail.
867            err
868        }
869    }
870
871    fn check_expr_continue(
872        &self,
873        destination: hir::Destination,
874        expr: &'tcx hir::Expr<'tcx>,
875    ) -> Ty<'tcx> {
876        if let Ok(target_id) = destination.target_id {
877            if let hir::Node::Expr(hir::Expr { kind: ExprKind::Loop(..), .. }) =
878                self.tcx.hir_node(target_id)
879            {
880                self.tcx.types.never
881            } else {
882                // Liveness linting assumes `continue`s all point to loops. We'll report an error
883                // in `check_mod_loops`, but make sure we don't run liveness (#113379, #121623).
884                let guar = self.dcx().span_delayed_bug(
885                    expr.span,
886                    "found `continue` not pointing to loop, but no error reported",
887                );
888                Ty::new_error(self.tcx, guar)
889            }
890        } else {
891            // There was an error; make type-check fail.
892            Ty::new_misc_error(self.tcx)
893        }
894    }
895
896    fn check_expr_return(
897        &self,
898        expr_opt: Option<&'tcx hir::Expr<'tcx>>,
899        expr: &'tcx hir::Expr<'tcx>,
900    ) -> Ty<'tcx> {
901        if self.ret_coercion.is_none() {
902            self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Return);
903
904            if let Some(e) = expr_opt {
905                // We still have to type-check `e` (issue #86188), but calling
906                // `check_return_expr` only works inside fn bodies.
907                self.check_expr(e);
908            }
909        } else if let Some(e) = expr_opt {
910            if self.ret_coercion_span.get().is_none() {
911                self.ret_coercion_span.set(Some(e.span));
912            }
913            self.check_return_or_body_tail(e, true);
914        } else {
915            let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
916            if self.ret_coercion_span.get().is_none() {
917                self.ret_coercion_span.set(Some(expr.span));
918            }
919            let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
920            if let Some((_, fn_decl)) = self.get_fn_decl(expr.hir_id) {
921                coercion.coerce_forced_unit(
922                    self,
923                    &cause,
924                    |db| {
925                        let span = fn_decl.output.span();
926                        if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
927                            db.span_label(
928                                span,
929                                ::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"),
930                            );
931                        }
932                    },
933                    true,
934                );
935            } else {
936                coercion.coerce_forced_unit(self, &cause, |_| (), true);
937            }
938        }
939        self.tcx.types.never
940    }
941
942    fn check_expr_become(
943        &self,
944        call: &'tcx hir::Expr<'tcx>,
945        expr: &'tcx hir::Expr<'tcx>,
946    ) -> Ty<'tcx> {
947        match &self.ret_coercion {
948            Some(ret_coercion) => {
949                let ret_ty = ret_coercion.borrow().expected_ty();
950                let call_expr_ty = self.check_expr_with_hint(call, ret_ty);
951
952                // N.B. don't coerce here, as tail calls can't support most/all coercions
953                // FIXME(explicit_tail_calls): add a diagnostic note that `become` doesn't allow coercions
954                self.demand_suptype(expr.span, ret_ty, call_expr_ty);
955            }
956            None => {
957                self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Become);
958
959                // Fallback to simply type checking `call` without hint/demanding the right types.
960                // Best effort to highlight more errors.
961                self.check_expr(call);
962            }
963        }
964
965        self.tcx.types.never
966    }
967
968    /// Check an expression that _is being returned_.
969    /// For example, this is called with `return_expr: $expr` when `return $expr`
970    /// is encountered.
971    ///
972    /// Note that this function must only be called in function bodies.
973    ///
974    /// `explicit_return` is `true` if we're checking an explicit `return expr`,
975    /// and `false` if we're checking a trailing expression.
976    pub(super) fn check_return_or_body_tail(
977        &self,
978        return_expr: &'tcx hir::Expr<'tcx>,
979        explicit_return: bool,
980    ) {
981        let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
982            ::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")
983        });
984
985        let ret_ty = ret_coercion.borrow().expected_ty();
986        let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
987        let mut span = return_expr.span;
988        let mut hir_id = return_expr.hir_id;
989        // Use the span of the trailing expression for our cause,
990        // not the span of the entire function
991        if !explicit_return
992            && let ExprKind::Block(body, _) = return_expr.kind
993            && let Some(last_expr) = body.expr
994        {
995            span = last_expr.span;
996            hir_id = last_expr.hir_id;
997        }
998        ret_coercion.borrow_mut().coerce(
999            self,
1000            &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
1001            return_expr,
1002            return_expr_ty,
1003        );
1004
1005        if let Some(fn_sig) = self.fn_sig()
1006            && fn_sig.output().has_opaque_types()
1007        {
1008            // Point any obligations that were registered due to opaque type
1009            // inference at the return expression.
1010            self.select_obligations_where_possible(|errors| {
1011                self.point_at_return_for_opaque_ty_error(
1012                    errors,
1013                    hir_id,
1014                    span,
1015                    return_expr_ty,
1016                    return_expr.span,
1017                );
1018            });
1019        }
1020    }
1021
1022    pub(crate) fn check_lhs_assignable(
1023        &self,
1024        lhs: &'tcx hir::Expr<'tcx>,
1025        code: ErrCode,
1026        op_span: Span,
1027        adjust_err: impl FnOnce(&mut Diag<'_>),
1028    ) {
1029        if lhs.is_syntactic_place_expr() {
1030            return;
1031        }
1032
1033        // Skip suggestion if LHS contains a let-chain at this would likely be spurious
1034        // cc: https://github.com/rust-lang/rust/issues/147664
1035        if contains_let_in_chain(lhs) {
1036            return;
1037        }
1038
1039        let mut err = self.dcx().struct_span_err(op_span, "invalid left-hand side of assignment");
1040        err.code(code);
1041        err.span_label(lhs.span, "cannot assign to this expression");
1042
1043        self.comes_from_while_condition(lhs.hir_id, |expr| {
1044            err.span_suggestion_verbose(
1045                expr.span.shrink_to_lo(),
1046                "you might have meant to use pattern destructuring",
1047                "let ",
1048                Applicability::MachineApplicable,
1049            );
1050        });
1051        self.check_for_missing_semi(lhs, &mut err);
1052
1053        adjust_err(&mut err);
1054
1055        err.emit();
1056    }
1057
1058    /// Check if the expression that could not be assigned to was a typoed expression that
1059    pub(crate) fn check_for_missing_semi(
1060        &self,
1061        expr: &'tcx hir::Expr<'tcx>,
1062        err: &mut Diag<'_>,
1063    ) -> bool {
1064        if let hir::ExprKind::Binary(binop, lhs, rhs) = expr.kind
1065            && let hir::BinOpKind::Mul = binop.node
1066            && self.tcx.sess.source_map().is_multiline(lhs.span.between(rhs.span))
1067            && rhs.is_syntactic_place_expr()
1068        {
1069            //      v missing semicolon here
1070            // foo()
1071            // *bar = baz;
1072            // (#80446).
1073            err.span_suggestion_verbose(
1074                lhs.span.shrink_to_hi(),
1075                "you might have meant to write a semicolon here",
1076                ";",
1077                Applicability::MachineApplicable,
1078            );
1079            return true;
1080        }
1081        false
1082    }
1083
1084    // Check if an expression `original_expr_id` comes from the condition of a while loop,
1085    /// as opposed from the body of a while loop, which we can naively check by iterating
1086    /// parents until we find a loop...
1087    pub(super) fn comes_from_while_condition(
1088        &self,
1089        original_expr_id: HirId,
1090        then: impl FnOnce(&hir::Expr<'_>),
1091    ) {
1092        let mut parent = self.tcx.parent_hir_id(original_expr_id);
1093        loop {
1094            let node = self.tcx.hir_node(parent);
1095            match node {
1096                hir::Node::Expr(hir::Expr {
1097                    kind:
1098                        hir::ExprKind::Loop(
1099                            hir::Block {
1100                                expr:
1101                                    Some(hir::Expr {
1102                                        kind:
1103                                            hir::ExprKind::Match(expr, ..) | hir::ExprKind::If(expr, ..),
1104                                        ..
1105                                    }),
1106                                ..
1107                            },
1108                            _,
1109                            hir::LoopSource::While,
1110                            _,
1111                        ),
1112                    ..
1113                }) => {
1114                    // Check if our original expression is a child of the condition of a while loop.
1115                    // If it is, then we have a situation like `while Some(0) = value.get(0) {`,
1116                    // where `while let` was more likely intended.
1117                    if self.tcx.hir_parent_id_iter(original_expr_id).any(|id| id == expr.hir_id) {
1118                        then(expr);
1119                    }
1120                    break;
1121                }
1122                hir::Node::Item(_)
1123                | hir::Node::ImplItem(_)
1124                | hir::Node::TraitItem(_)
1125                | hir::Node::Crate(_) => break,
1126                _ => {
1127                    parent = self.tcx.parent_hir_id(parent);
1128                }
1129            }
1130        }
1131    }
1132
1133    // A generic function for checking the 'then' and 'else' clauses in an 'if'
1134    // or 'if-else' expression.
1135    fn check_expr_if(
1136        &self,
1137        expr_id: HirId,
1138        cond_expr: &'tcx hir::Expr<'tcx>,
1139        then_expr: &'tcx hir::Expr<'tcx>,
1140        opt_else_expr: Option<&'tcx hir::Expr<'tcx>>,
1141        sp: Span,
1142        orig_expected: Expectation<'tcx>,
1143    ) -> Ty<'tcx> {
1144        let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {});
1145
1146        self.warn_if_unreachable(
1147            cond_expr.hir_id,
1148            then_expr.span,
1149            "block in `if` or `while` expression",
1150        );
1151
1152        let cond_diverges = self.diverges.get();
1153        self.diverges.set(Diverges::Maybe);
1154
1155        let expected = orig_expected.try_structurally_resolve_and_adjust_for_branches(self);
1156        let then_ty = self.check_expr_with_expectation(then_expr, expected);
1157        let then_diverges = self.diverges.get();
1158        self.diverges.set(Diverges::Maybe);
1159
1160        // We've already taken the expected type's preferences
1161        // into account when typing the `then` branch. To figure
1162        // out the initial shot at a LUB, we thus only consider
1163        // `expected` if it represents a *hard* constraint
1164        // (`only_has_type`); otherwise, we just go with a
1165        // fresh type variable.
1166        let coerce_to_ty = expected.coercion_target_type(self, sp);
1167        let mut coerce = CoerceMany::with_capacity(coerce_to_ty, 2);
1168
1169        coerce.coerce(self, &self.misc(sp), then_expr, then_ty);
1170
1171        if let Some(else_expr) = opt_else_expr {
1172            let else_ty = self.check_expr_with_expectation(else_expr, expected);
1173            let else_diverges = self.diverges.get();
1174
1175            let tail_defines_return_position_impl_trait =
1176                self.return_position_impl_trait_from_match_expectation(orig_expected);
1177            let if_cause =
1178                self.if_cause(expr_id, else_expr, tail_defines_return_position_impl_trait);
1179
1180            coerce.coerce(self, &if_cause, else_expr, else_ty);
1181
1182            // We won't diverge unless both branches do (or the condition does).
1183            self.diverges.set(cond_diverges | then_diverges & else_diverges);
1184        } else {
1185            self.if_fallback_coercion(sp, cond_expr, then_expr, &mut coerce);
1186
1187            // If the condition is false we can't diverge.
1188            self.diverges.set(cond_diverges);
1189        }
1190
1191        let result_ty = coerce.complete(self);
1192        if let Err(guar) = cond_ty.error_reported() {
1193            Ty::new_error(self.tcx, guar)
1194        } else {
1195            result_ty
1196        }
1197    }
1198
1199    /// Type check assignment expression `expr` of form `lhs = rhs`.
1200    /// The expected type is `()` and is passed to the function for the purposes of diagnostics.
1201    fn check_expr_assign(
1202        &self,
1203        expr: &'tcx hir::Expr<'tcx>,
1204        expected: Expectation<'tcx>,
1205        lhs: &'tcx hir::Expr<'tcx>,
1206        rhs: &'tcx hir::Expr<'tcx>,
1207        span: Span,
1208    ) -> Ty<'tcx> {
1209        let expected_ty = expected.only_has_type(self);
1210        if expected_ty == Some(self.tcx.types.bool) {
1211            let guar = self.expr_assign_expected_bool_error(expr, lhs, rhs, span);
1212            return Ty::new_error(self.tcx, guar);
1213        }
1214
1215        let lhs_ty = self.check_expr_with_needs(lhs, Needs::MutPlace);
1216
1217        let suggest_deref_binop = |err: &mut Diag<'_>, rhs_ty: Ty<'tcx>| {
1218            if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
1219                // Can only assign if the type is sized, so if `DerefMut` yields a type that is
1220                // unsized, do not suggest dereferencing it.
1221                let lhs_deref_ty_is_sized = self
1222                    .infcx
1223                    .type_implements_trait(
1224                        self.tcx.require_lang_item(LangItem::Sized, span),
1225                        [lhs_deref_ty],
1226                        self.param_env,
1227                    )
1228                    .may_apply();
1229                if lhs_deref_ty_is_sized && self.may_coerce(rhs_ty, lhs_deref_ty) {
1230                    err.span_suggestion_verbose(
1231                        lhs.span.shrink_to_lo(),
1232                        "consider dereferencing here to assign to the mutably borrowed value",
1233                        "*",
1234                        Applicability::MachineApplicable,
1235                    );
1236                }
1237            }
1238        };
1239
1240        // This is (basically) inlined `check_expr_coercible_to_type`, but we want
1241        // to suggest an additional fixup here in `suggest_deref_binop`.
1242        let rhs_ty = self.check_expr_with_hint(rhs, lhs_ty);
1243        if let Err(mut diag) =
1244            self.demand_coerce_diag(rhs, rhs_ty, lhs_ty, Some(lhs), AllowTwoPhase::No)
1245        {
1246            suggest_deref_binop(&mut diag, rhs_ty);
1247            diag.emit();
1248        }
1249
1250        self.check_lhs_assignable(lhs, E0070, span, |err| {
1251            if let Some(rhs_ty) = self.typeck_results.borrow().expr_ty_opt(rhs) {
1252                suggest_deref_binop(err, rhs_ty);
1253            }
1254        });
1255
1256        self.require_type_is_sized(lhs_ty, lhs.span, ObligationCauseCode::AssignmentLhsSized);
1257
1258        if let Err(guar) = (lhs_ty, rhs_ty).error_reported() {
1259            Ty::new_error(self.tcx, guar)
1260        } else {
1261            self.tcx.types.unit
1262        }
1263    }
1264
1265    /// The expected type is `bool` but this will result in `()` so we can reasonably
1266    /// say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
1267    /// The likely cause of this is `if foo = bar { .. }`.
1268    fn expr_assign_expected_bool_error(
1269        &self,
1270        expr: &'tcx hir::Expr<'tcx>,
1271        lhs: &'tcx hir::Expr<'tcx>,
1272        rhs: &'tcx hir::Expr<'tcx>,
1273        span: Span,
1274    ) -> ErrorGuaranteed {
1275        let actual_ty = self.tcx.types.unit;
1276        let expected_ty = self.tcx.types.bool;
1277        let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap_err();
1278        let lhs_ty = self.check_expr(lhs);
1279        let rhs_ty = self.check_expr(rhs);
1280        let refs_can_coerce = |lhs: Ty<'tcx>, rhs: Ty<'tcx>| {
1281            let lhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, lhs.peel_refs());
1282            let rhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rhs.peel_refs());
1283            self.may_coerce(rhs, lhs)
1284        };
1285        // Never-to-any coercions do not imply that the operands can be compared, e.g. `String == !`.
1286        let (applicability, eq) = if self.may_coerce_except_never(rhs_ty, lhs_ty) {
1287            (Applicability::MachineApplicable, true)
1288        } else if refs_can_coerce(rhs_ty, lhs_ty) {
1289            // The lhs and rhs are likely missing some references in either side. Subsequent
1290            // suggestions will show up.
1291            (Applicability::MaybeIncorrect, true)
1292        } else if let ExprKind::Binary(
1293            Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1294            _,
1295            rhs_expr,
1296        ) = lhs.kind
1297        {
1298            // if x == 1 && y == 2 { .. }
1299            //                 +
1300            let actual_lhs = self.check_expr(rhs_expr);
1301            let may_eq = self.may_coerce_except_never(rhs_ty, actual_lhs)
1302                || refs_can_coerce(rhs_ty, actual_lhs);
1303            (Applicability::MaybeIncorrect, may_eq)
1304        } else if let ExprKind::Binary(
1305            Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1306            lhs_expr,
1307            _,
1308        ) = rhs.kind
1309        {
1310            // if x == 1 && y == 2 { .. }
1311            //       +
1312            let actual_rhs = self.check_expr(lhs_expr);
1313            let may_eq = self.may_coerce_except_never(actual_rhs, lhs_ty)
1314                || refs_can_coerce(actual_rhs, lhs_ty);
1315            (Applicability::MaybeIncorrect, may_eq)
1316        } else {
1317            (Applicability::MaybeIncorrect, false)
1318        };
1319
1320        if !lhs.is_syntactic_place_expr()
1321            && lhs.is_approximately_pattern()
1322            && !#[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
    hir::ExprKind::Lit(_) => true,
    _ => false,
}matches!(lhs.kind, hir::ExprKind::Lit(_))
1323        {
1324            // Do not suggest `if let x = y` as `==` is way more likely to be the intention.
1325            if let hir::Node::Expr(hir::Expr { kind: ExprKind::If { .. }, .. }) =
1326                self.tcx.parent_hir_node(expr.hir_id)
1327            {
1328                err.span_suggestion_verbose(
1329                    expr.span.shrink_to_lo(),
1330                    "you might have meant to use pattern matching",
1331                    "let ",
1332                    applicability,
1333                );
1334            };
1335        }
1336        if eq {
1337            err.span_suggestion_verbose(
1338                span.shrink_to_hi(),
1339                "you might have meant to compare for equality",
1340                '=',
1341                applicability,
1342            );
1343        }
1344
1345        // If the assignment expression itself is ill-formed, don't
1346        // bother emitting another error
1347        err.emit_err_unless_delay(lhs_ty.references_error() || rhs_ty.references_error())
1348    }
1349
1350    pub(super) fn check_expr_let(
1351        &self,
1352        let_expr: &'tcx hir::LetExpr<'tcx>,
1353        hir_id: HirId,
1354    ) -> Ty<'tcx> {
1355        GatherLocalsVisitor::gather_from_let_expr(self, let_expr, hir_id);
1356
1357        // for let statements, this is done in check_stmt
1358        let init = let_expr.init;
1359        self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression");
1360
1361        // otherwise check exactly as a let statement
1362        self.check_decl((let_expr, hir_id).into());
1363
1364        // but return a bool, for this is a boolean expression
1365        if let ast::Recovered::Yes(error_guaranteed) = let_expr.recovered {
1366            self.set_tainted_by_errors(error_guaranteed);
1367            Ty::new_error(self.tcx, error_guaranteed)
1368        } else {
1369            self.tcx.types.bool
1370        }
1371    }
1372
1373    fn check_expr_loop(
1374        &self,
1375        body: &'tcx hir::Block<'tcx>,
1376        source: hir::LoopSource,
1377        expected: Expectation<'tcx>,
1378        expr: &'tcx hir::Expr<'tcx>,
1379    ) -> Ty<'tcx> {
1380        let coerce = match source {
1381            // you can only use break with a value from a normal `loop { }`
1382            hir::LoopSource::Loop => {
1383                let coerce_to = expected.coercion_target_type(self, body.span);
1384                Some(CoerceMany::new(coerce_to))
1385            }
1386
1387            hir::LoopSource::While | hir::LoopSource::ForLoop => None,
1388        };
1389
1390        let ctxt = BreakableCtxt {
1391            coerce,
1392            may_break: false, // Will get updated if/when we find a `break`.
1393        };
1394
1395        let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
1396            self.check_block_no_value(body);
1397        });
1398
1399        if ctxt.may_break {
1400            // No way to know whether it's diverging because
1401            // of a `break` or an outer `break` or `return`.
1402            self.diverges.set(Diverges::Maybe);
1403        } else {
1404            self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
1405        }
1406
1407        // If we permit break with a value, then result type is
1408        // the LUB of the breaks (possibly ! if none); else, it
1409        // is nil. This makes sense because infinite loops
1410        // (which would have type !) are only possible iff we
1411        // permit break with a value.
1412        if ctxt.coerce.is_none() && !ctxt.may_break {
1413            self.dcx().span_bug(body.span, "no coercion, but loop may not break");
1414        }
1415        ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.types.unit)
1416    }
1417
1418    /// Checks a method call.
1419    fn check_expr_method_call(
1420        &self,
1421        expr: &'tcx hir::Expr<'tcx>,
1422        segment: &'tcx hir::PathSegment<'tcx>,
1423        rcvr: &'tcx hir::Expr<'tcx>,
1424        args: &'tcx [hir::Expr<'tcx>],
1425        expected: Expectation<'tcx>,
1426    ) -> Ty<'tcx> {
1427        let rcvr_t = self.check_expr(rcvr);
1428        let rcvr_t = self.deeply_resolve_ignoring_regions_with_obligations(rcvr_t);
1429
1430        match self.lookup_method(rcvr_t, segment, segment.ident.span, expr, rcvr, args) {
1431            Ok(method) => {
1432                self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
1433
1434                // Handle splatted method arguments
1435                // self is already handled as `rcvr`, so it's never splatted here
1436                let mut method_inputs = Cow::Borrowed(&method.sig.inputs()[1..]);
1437                for (param, pos) in self.tcx.generics_of(method.def_id).own_arg_pos_consts() {
1438                    let ty = self
1439                        .tcx
1440                        .type_of(param.def_id)
1441                        .instantiate(self.tcx, method.args)
1442                        .skip_norm_wip();
1443
1444                    // Insert function argument const param types back into the inputs.
1445                    // We use pos - 1 since method_inputs skips self, but arg_pos counts it.
1446                    method_inputs.to_mut().insert(
1447                        pos.checked_sub(1).expect("pos should always be greater than 0") as usize,
1448                        ty,
1449                    );
1450                }
1451
1452                let method_tuple_args_flag =
1453                    TupleArgumentsFlag::with_fn_sig_kind(method.sig.fn_sig_kind, true);
1454
1455                self.check_argument_types(
1456                    segment.ident.span,
1457                    expr,
1458                    &method_inputs,
1459                    method.sig.output(),
1460                    expected,
1461                    args,
1462                    method.sig.fn_sig_kind.c_variadic(),
1463                    method_tuple_args_flag,
1464                    SplatLoweringInfo::FnDef(method.def_id),
1465                    Some(method.args),
1466                );
1467
1468                self.check_call_abi(method.sig.abi(), expr.span);
1469
1470                method.sig.output()
1471            }
1472            Err(error) => {
1473                let guar = self.report_method_error(expr.hir_id, rcvr_t, error, expected, false);
1474
1475                let err_inputs = self.err_args(args.len(), guar);
1476                let err_ty = Ty::new_error(self.tcx, guar);
1477
1478                self.check_argument_types(
1479                    segment.ident.span,
1480                    expr,
1481                    &err_inputs,
1482                    err_ty,
1483                    NoExpectation,
1484                    args,
1485                    false,
1486                    TupleArgumentsFlag::DontTupleArguments,
1487                    SplatLoweringInfo::Error(guar),
1488                    Some(GenericArgs::default()),
1489                );
1490
1491                err_ty
1492            }
1493        }
1494    }
1495
1496    /// Checks use `x.use`.
1497    fn check_expr_use(
1498        &self,
1499        used_expr: &'tcx hir::Expr<'tcx>,
1500        expected: Expectation<'tcx>,
1501    ) -> Ty<'tcx> {
1502        self.check_expr_with_expectation(used_expr, expected)
1503    }
1504
1505    fn check_expr_cast(
1506        &self,
1507        e: &'tcx hir::Expr<'tcx>,
1508        t: &'tcx hir::Ty<'tcx>,
1509        expr: &'tcx hir::Expr<'tcx>,
1510    ) -> Ty<'tcx> {
1511        // Find the type of `e`. Supply hints based on the type we are casting to,
1512        // if appropriate.
1513        let t_cast = self.lower_ty_saving_user_provided_ty(t);
1514        let t_cast = self.deeply_resolve_ignoring_regions(t_cast);
1515        let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
1516        let t_expr = self.deeply_resolve_ignoring_regions(t_expr);
1517
1518        // Eagerly check for some obvious errors.
1519        if let Err(guar) = (t_expr, t_cast).error_reported() {
1520            Ty::new_error(self.tcx, guar)
1521        } else {
1522            // Defer other checks until we're done type checking.
1523            let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
1524            match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
1525                Ok(cast_check) => {
1526                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs:1526",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(1526u32),
                        ::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!(
1527                        "check_expr_cast: deferring cast from {:?} to {:?}: {:?}",
1528                        t_cast, t_expr, cast_check,
1529                    );
1530                    deferred_cast_checks.push(cast_check);
1531                    t_cast
1532                }
1533                Err(guar) => Ty::new_error(self.tcx, guar),
1534            }
1535        }
1536    }
1537
1538    fn check_expr_unsafe_binder_cast(
1539        &self,
1540        span: Span,
1541        kind: ast::UnsafeBinderCastKind,
1542        inner_expr: &'tcx hir::Expr<'tcx>,
1543        hir_ty: Option<&'tcx hir::Ty<'tcx>>,
1544        expected: Expectation<'tcx>,
1545    ) -> Ty<'tcx> {
1546        match kind {
1547            ast::UnsafeBinderCastKind::Wrap => {
1548                let ascribed_ty =
1549                    hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1550                let expected_ty = expected.only_has_type(self);
1551                let binder_ty = match (ascribed_ty, expected_ty) {
1552                    (Some(ascribed_ty), Some(expected_ty)) => {
1553                        self.demand_eqtype(inner_expr.span, expected_ty, ascribed_ty);
1554                        expected_ty
1555                    }
1556                    (Some(ty), None) | (None, Some(ty)) => ty,
1557                    // This will always cause a structural resolve error, but we do it
1558                    // so we don't need to manually report an E0282 both on this codepath
1559                    // and in the others; it all happens in `structurally_resolve_type`.
1560                    (None, None) => self.next_ty_var(inner_expr.span),
1561                };
1562
1563                let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1564                let hint_ty = match *binder_ty.kind() {
1565                    ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1566                        inner_expr.span,
1567                        infer::BoundRegionConversionTime::HigherRankedType,
1568                        binder.into(),
1569                    ),
1570                    ty::Error(e) => Ty::new_error(self.tcx, e),
1571                    _ => {
1572                        let guar = self
1573                            .dcx()
1574                            .struct_span_err(
1575                                hir_ty.map_or(span, |hir_ty| hir_ty.span),
1576                                ::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!(
1577                                    "`wrap_binder!()` can only wrap into unsafe binder, not {}",
1578                                    binder_ty.sort_string(self.tcx)
1579                                ),
1580                            )
1581                            .with_note("unsafe binders are the only valid output of wrap")
1582                            .emit_err();
1583                        Ty::new_error(self.tcx, guar)
1584                    }
1585                };
1586
1587                self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1588
1589                binder_ty
1590            }
1591            ast::UnsafeBinderCastKind::Unwrap => {
1592                let ascribed_ty =
1593                    hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1594                let hint_ty = ascribed_ty.unwrap_or_else(|| self.next_ty_var(inner_expr.span));
1595                // FIXME(unsafe_binders): coerce here if needed?
1596                let binder_ty = self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1597
1598                // Unwrap the binder. This will be ambiguous if it's an infer var, and will error
1599                // if it's not an unsafe binder.
1600                let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1601                match *binder_ty.kind() {
1602                    ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1603                        inner_expr.span,
1604                        infer::BoundRegionConversionTime::HigherRankedType,
1605                        binder.into(),
1606                    ),
1607                    ty::Error(e) => Ty::new_error(self.tcx, e),
1608                    _ => {
1609                        let guar = self
1610                            .dcx()
1611                            .struct_span_err(
1612                                hir_ty.map_or(inner_expr.span, |hir_ty| hir_ty.span),
1613                                ::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!(
1614                                    "expected unsafe binder, found {} as input of \
1615                                    `unwrap_binder!()`",
1616                                    binder_ty.sort_string(self.tcx)
1617                                ),
1618                            )
1619                            .with_note("only an unsafe binder type can be unwrapped")
1620                            .emit_err();
1621                        Ty::new_error(self.tcx, guar)
1622                    }
1623                }
1624            }
1625        }
1626    }
1627
1628    fn check_expr_array(
1629        &self,
1630        args: &'tcx [hir::Expr<'tcx>],
1631        expected: Expectation<'tcx>,
1632        expr: &'tcx hir::Expr<'tcx>,
1633    ) -> Ty<'tcx> {
1634        let element_ty = if !args.is_empty() {
1635            let coerce_to = expected
1636                .to_option(self)
1637                .and_then(|uty| {
1638                    self.deeply_resolve_ignoring_regions_with_obligations(uty)
1639                        .builtin_index()
1640                        // Avoid using the original type variable as the coerce_to type, as it may resolve
1641                        // during the first coercion instead of being the LUB type.
1642                        .filter(|t| {
1643                            !self.deeply_resolve_ignoring_regions_with_obligations(*t).is_ty_var()
1644                        })
1645                })
1646                .unwrap_or_else(|| self.next_ty_var(expr.span));
1647            let mut coerce = CoerceMany::with_capacity(coerce_to, args.len());
1648
1649            for e in args {
1650                // FIXME: the element expectation should use
1651                // `try_structurally_resolve_and_adjust_for_branches` just like in `if` and `match`.
1652                // While that fixes nested coercion, it will break [some
1653                // code like this](https://github.com/rust-lang/rust/pull/140283#issuecomment-2958776528).
1654                // If we find a way to support recursive tuple coercion, this break can be avoided.
1655                let e_ty = self.check_expr_with_hint(e, coerce_to);
1656                let cause = self.misc(e.span);
1657                coerce.coerce(self, &cause, e, e_ty);
1658            }
1659            coerce.complete(self)
1660        } else {
1661            self.next_ty_var(expr.span)
1662        };
1663        let array_len = args.len() as u64;
1664        Ty::new_array(self.tcx, element_ty, array_len)
1665    }
1666
1667    pub(super) fn check_expr_const_block(
1668        &self,
1669        block: &'tcx hir::ConstBlock,
1670        expected: Expectation<'tcx>,
1671    ) -> Ty<'tcx> {
1672        let body = self.tcx.hir_body(block.body);
1673
1674        // Create a new function context.
1675        let def_id = block.def_id;
1676        let fcx = FnCtxt::new(self, self.param_env, def_id);
1677
1678        let ty = fcx.check_expr_with_expectation(body.value, expected);
1679        fcx.require_type_is_sized(ty, body.value.span, ObligationCauseCode::SizedConstOrStatic);
1680        fcx.write_ty(block.hir_id, ty);
1681        ty
1682    }
1683
1684    fn check_expr_repeat(
1685        &self,
1686        element: &'tcx hir::Expr<'tcx>,
1687        count: &'tcx hir::ConstArg<'tcx>,
1688        expected: Expectation<'tcx>,
1689        expr: &'tcx hir::Expr<'tcx>,
1690    ) -> Ty<'tcx> {
1691        let tcx = self.tcx;
1692        let count_span = count.span;
1693        let count = self.try_structurally_resolve_const(
1694            count_span,
1695            self.normalize(
1696                count_span,
1697                Unnormalized::new_wip(self.lower_const_arg(count, tcx.types.usize)),
1698            ),
1699        );
1700
1701        let uty = match expected {
1702            ExpectHasType(uty) => uty.builtin_index(),
1703            _ => None,
1704        };
1705
1706        let old_diverges = self.diverges.get();
1707
1708        let (element_ty, t) = match uty {
1709            Some(uty) => {
1710                self.check_expr_coercible_to_type(element, uty, None);
1711                (uty, uty)
1712            }
1713            None => {
1714                let ty = self.next_ty_var(element.span);
1715                let element_ty = self.check_expr_has_type_or_error(element, ty, |_| {});
1716                (element_ty, ty)
1717            }
1718        };
1719
1720        // FIXME: remove this workaround for an unsoundness (#165323) once it's no longer needed.
1721        //
1722        // MIR building lowers `[CONST; 0]` to `[]`, making `CONST` not evaluated.
1723        //
1724        // This is a problem, because it means if `CONST` is `const { panic!() }`, the side effect
1725        // of panic / failing compilation never happens. In such cases we need to ignore divergence
1726        // from the `CONST`, as otherwise we can end up executing code that was assumed unreachable.
1727        let count_is_zero = match count.kind() {
1728            // This is the exact check that mir building does
1729            ConstKind::Value(v) => v.try_to_target_usize(tcx) == Some(0),
1730
1731            // An infer const can get inferred to 0.
1732            //
1733            // We could check the expectation here to do ad-hoc inference, but that feels quite
1734            // error prone and annoying.
1735            ConstKind::Infer(_) => true,
1736
1737            // While const generic params can be substituted with 0, mir building specifically
1738            // checks for value 0 before monomorphization, so they (alongside aliases, etc) cannot
1739            // trigger the bug.
1740            ConstKind::Param(_)
1741            | ConstKind::Placeholder(_)
1742            | ConstKind::Alias(..)
1743            | ConstKind::Error(_)
1744            | ConstKind::Expr(_) => false,
1745
1746            ConstKind::Bound(..) => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
1747        };
1748
1749        if count_is_zero && element.is_constant_for_zero_repeat() {
1750            self.diverges.set(old_diverges);
1751        }
1752
1753        if let Err(guar) = element_ty.error_reported() {
1754            return Ty::new_error(tcx, guar);
1755        }
1756
1757        // We defer checking whether the element type is `Copy` as it is possible to have
1758        // an inference variable as a repeat count and it seems unlikely that `Copy` would
1759        // have inference side effects required for type checking to succeed.
1760        self.deferred_repeat_expr_checks.borrow_mut().push((element, element_ty, count));
1761
1762        let ty = Ty::new_array_with_const_len(tcx, t, count);
1763        self.register_wf_obligation(
1764            ty.into(),
1765            expr.span,
1766            ObligationCauseCode::WellFormed(WellFormedLoc::HirId(expr.hir_id)),
1767        );
1768        ty
1769    }
1770
1771    fn check_expr_tuple(
1772        &self,
1773        elements: &'tcx [hir::Expr<'tcx>],
1774        expected: Expectation<'tcx>,
1775        expr: &'tcx hir::Expr<'tcx>,
1776    ) -> Ty<'tcx> {
1777        let mut expectations = expected
1778            .only_has_type(self)
1779            .and_then(|ty| {
1780                self.deeply_resolve_ignoring_regions_with_obligations(ty).opt_tuple_fields()
1781            })
1782            .unwrap_or_default()
1783            .iter();
1784
1785        let elements = elements.iter().map(|e| {
1786            let ty = expectations.next().unwrap_or_else(|| self.next_ty_var(e.span));
1787            self.check_expr_coercible_to_type(e, ty, None);
1788            ty
1789        });
1790
1791        let tuple = Ty::new_tup_from_iter(self.tcx, elements);
1792
1793        if let Err(guar) = tuple.error_reported() {
1794            Ty::new_error(self.tcx, guar)
1795        } else {
1796            self.require_type_is_sized(
1797                tuple,
1798                expr.span,
1799                ObligationCauseCode::TupleInitializerSized,
1800            );
1801            tuple
1802        }
1803    }
1804
1805    fn check_expr_struct(
1806        &self,
1807        expr: &hir::Expr<'tcx>,
1808        expected: Expectation<'tcx>,
1809        qpath: &'tcx QPath<'tcx>,
1810        fields: &'tcx [hir::ExprField<'tcx>],
1811        base_expr: &'tcx hir::StructTailExpr<'tcx>,
1812    ) -> Ty<'tcx> {
1813        // Find the relevant variant
1814        let (variant, adt_ty) = match self.check_struct_path(qpath, expr.hir_id) {
1815            Ok(data) => data,
1816            Err(guar) => {
1817                self.check_struct_fields_on_error(fields, base_expr);
1818                return Ty::new_error(self.tcx, guar);
1819            }
1820        };
1821
1822        // Prohibit struct expressions when non-exhaustive flag is set.
1823        let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1824        if variant.field_list_has_applicable_non_exhaustive() {
1825            self.dcx()
1826                .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() });
1827        }
1828
1829        self.check_expr_struct_fields(
1830            adt_ty,
1831            expected,
1832            expr,
1833            qpath.span(),
1834            variant,
1835            fields,
1836            base_expr,
1837        );
1838
1839        self.require_type_is_sized(adt_ty, expr.span, ObligationCauseCode::StructInitializerSized);
1840        adt_ty
1841    }
1842
1843    fn check_expr_struct_fields(
1844        &self,
1845        adt_ty: Ty<'tcx>,
1846        expected: Expectation<'tcx>,
1847        expr: &hir::Expr<'_>,
1848        path_span: Span,
1849        variant: &'tcx ty::VariantDef,
1850        hir_fields: &'tcx [hir::ExprField<'tcx>],
1851        base_expr: &'tcx hir::StructTailExpr<'tcx>,
1852    ) {
1853        let tcx = self.tcx;
1854
1855        let adt_ty = self.deeply_resolve_ignoring_regions_with_obligations(adt_ty);
1856        let adt_ty_hint = expected.only_has_type(self).and_then(|expected| {
1857            self.fudge_inference_if_ok(|| {
1858                let ocx = ObligationCtxt::new(self);
1859                ocx.sup(&self.misc(path_span), self.param_env, expected, adt_ty)?;
1860                if !ocx.try_evaluate_obligations().no_errors() {
1861                    return Err(TypeError::Mismatch);
1862                }
1863                Ok(self.deeply_resolve_ignoring_regions(adt_ty))
1864            })
1865            .ok()
1866        });
1867        if let Some(adt_ty_hint) = adt_ty_hint {
1868            // re-link the variables that the fudging above can create.
1869            self.demand_eqtype(path_span, adt_ty_hint, adt_ty);
1870        }
1871
1872        let ty::Adt(adt, args) = adt_ty.kind() else {
1873            ::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");
1874        };
1875        let adt_kind = adt.adt_kind();
1876
1877        let get_field_ident = |field: &ty::FieldDef| field.ident(tcx).normalize_to_macros_2_0();
1878        let mut remaining_fields = variant
1879            .fields
1880            .iter_enumerated()
1881            .map(|(i, field)| (get_field_ident(field), (i, field)))
1882            .collect::<UnordMap<_, _>>();
1883
1884        let mut seen_fields = FxHashMap::default();
1885
1886        let mut error_happened = false;
1887
1888        if variant.fields.len() != remaining_fields.len() {
1889            // Some field is defined more than once. Make sure we don't try to
1890            // instantiate this struct in static/const context.
1891            let guar =
1892                self.dcx().span_delayed_bug(expr.span, "struct fields have non-unique names");
1893            self.set_tainted_by_errors(guar);
1894            error_happened = true;
1895        }
1896
1897        // Type-check each field.
1898        for (idx, field) in hir_fields.iter().enumerate() {
1899            let ident = if field.ident.name == kw::Underscore {
1900                // We are processing delegation `Self` mapping field, we expect that it is a struct
1901                // with one field, so if it is not true we emit an error as we can't infer
1902                // what field to use to initialize the struct.
1903                // The `_` is a keyword so if user uses it during struct initialization as a field name
1904                // it will be error anyway.
1905                if let [v_field] = &variant.fields[..] {
1906                    Ok(get_field_ident(v_field))
1907                } else {
1908                    Err(tcx.dcx().emit_err(DelegationInvalidAdtForReturnWrapping {
1909                        span: tcx.def_span(self.body_def_id),
1910                        adt_name: tcx.def_path_str(adt.did()),
1911                    }))
1912                }
1913            } else {
1914                Ok(tcx.adjust_ident(field.ident, variant.def_id))
1915            };
1916
1917            let field_type = ident
1918                .and_then(|ident| {
1919                    if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1920                        seen_fields.insert(ident, field.span);
1921                        self.write_field_index(field.hir_id, i);
1922
1923                        // We don't look at stability attributes on
1924                        // struct-like enums (yet...), but it's definitely not
1925                        // a bug to have constructed one.
1926                        if adt_kind != AdtKind::Enum {
1927                            tcx.check_stability(v_field.did, Some(field.hir_id), field.span, None);
1928                        }
1929
1930                        Ok(self.field_ty(field.span, v_field, *args))
1931                    } else {
1932                        error_happened = true;
1933                        let guar = if let Some(prev_span) = seen_fields.get(&ident) {
1934                            self.dcx().emit_err(FieldMultiplySpecifiedInInitializer {
1935                                span: field.ident.span,
1936                                prev_span: *prev_span,
1937                                ident,
1938                            })
1939                        } else {
1940                            self.report_unknown_field(
1941                                adt_ty,
1942                                variant,
1943                                expr,
1944                                field,
1945                                hir_fields,
1946                                adt.variant_descr(),
1947                            )
1948                        };
1949
1950                        Err(guar)
1951                    }
1952                })
1953                .unwrap_or_else(|err| Ty::new_error(tcx, err));
1954
1955            // Check that the expected field type is WF. Otherwise, we emit no use-site error
1956            // in the case of coercions for non-WF fields, which leads to incorrect error
1957            // tainting. See issue #126272.
1958            self.register_wf_obligation(
1959                field_type.into(),
1960                field.expr.span,
1961                ObligationCauseCode::WellFormed(WellFormedLoc::HirId(field.expr.hir_id)),
1962            );
1963
1964            // Make sure to give a type to the field even if there's
1965            // an error, so we can continue type-checking.
1966            let ty = self.check_expr_with_hint(field.expr, field_type);
1967            let diag = self.demand_coerce_diag(field.expr, ty, field_type, None, AllowTwoPhase::No);
1968
1969            if let Err(diag) = diag {
1970                if idx == hir_fields.len() - 1 {
1971                    if remaining_fields.is_empty() {
1972                        self.suggest_fru_from_range_and_emit(field, variant, *args, diag);
1973                    } else {
1974                        diag.stash(field.span, StashKey::MaybeFruTypo);
1975                    }
1976                } else {
1977                    diag.emit();
1978                }
1979            }
1980        }
1981
1982        // Make sure the programmer specified correct number of fields.
1983        if adt_kind == AdtKind::Union && hir_fields.len() != 1 {
1984            {
    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!(
1985                self.dcx(),
1986                path_span,
1987                E0784,
1988                "union expressions should have exactly one field",
1989            )
1990            .emit();
1991        }
1992
1993        // If check_expr_struct_fields hit an error, do not attempt to populate
1994        // the fields with the base_expr. This could cause us to hit errors later
1995        // when certain fields are assumed to exist that in fact do not.
1996        if error_happened {
1997            if let hir::StructTailExpr::Base(base_expr) = base_expr {
1998                self.check_expr(base_expr);
1999            }
2000            return;
2001        }
2002
2003        match *base_expr {
2004            hir::StructTailExpr::DefaultFields(span) => {
2005                let mut missing_mandatory_fields = Vec::new();
2006                let mut missing_optional_fields = Vec::new();
2007                for f in &variant.fields {
2008                    let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2009                    if let Some(_) = remaining_fields.remove(&ident) {
2010                        if f.value.is_none() {
2011                            missing_mandatory_fields.push(ident);
2012                        } else {
2013                            missing_optional_fields.push(ident);
2014                        }
2015                    }
2016                }
2017                if !self.tcx.features().default_field_values()
2018                    && !span.allows_unstable(sym::default_field_values)
2019                {
2020                    let sugg = self.tcx.crate_level_attribute_injection_span();
2021                    self.dcx().emit_err(BaseExpressionDoubleDot {
2022                        span: span.shrink_to_hi(),
2023                        // We only mention enabling the feature if this is a nightly rustc *and* the
2024                        // expression would make sense with the feature enabled.
2025                        default_field_values_suggestion: if self.tcx.sess.is_nightly_build()
2026                            && missing_mandatory_fields.is_empty()
2027                            && !missing_optional_fields.is_empty()
2028                        {
2029                            Some(sugg)
2030                        } else {
2031                            None
2032                        },
2033                        add_expr: if !missing_mandatory_fields.is_empty()
2034                            || !missing_optional_fields.is_empty()
2035                        {
2036                            Some(BaseExpressionDoubleDotAddExpr { span: span.shrink_to_hi() })
2037                        } else {
2038                            None
2039                        },
2040                        remove_dots: if missing_mandatory_fields.is_empty()
2041                            && missing_optional_fields.is_empty()
2042                        {
2043                            Some(BaseExpressionDoubleDotRemove { span })
2044                        } else {
2045                            None
2046                        },
2047                    });
2048                    return;
2049                }
2050                if variant.fields.is_empty() {
2051                    let mut err = self.dcx().struct_span_err(
2052                        span,
2053                        ::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!(
2054                            "`{adt_ty}` has no fields, `..` needs at least one default field in \
2055                            the struct definition",
2056                        ),
2057                    );
2058                    err.span_label(path_span, "this type has no fields");
2059                    err.emit();
2060                }
2061                if !missing_mandatory_fields.is_empty() {
2062                    let s = if missing_mandatory_fields.len() == 1 { "" } else { "s" }pluralize!(missing_mandatory_fields.len());
2063                    let fields = listify(&missing_mandatory_fields, |f| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", f))
    })format!("`{f}`")).unwrap();
2064                    self.dcx()
2065                        .struct_span_err(
2066                            span.shrink_to_lo(),
2067                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("missing field{0} {1} in initializer",
                s, fields))
    })format!("missing field{s} {fields} in initializer"),
2068                        )
2069                        .with_span_label(
2070                            span.shrink_to_lo(),
2071                            "fields that do not have a defaulted value must be provided explicitly",
2072                        )
2073                        .emit();
2074                    return;
2075                }
2076                let fru_tys = match adt_ty.kind() {
2077                    ty::Adt(adt, args) if adt.is_struct() => variant
2078                        .fields
2079                        .iter()
2080                        .map(|f| self.normalize(span, f.ty(self.tcx, *args)))
2081                        .collect(),
2082                    ty::Adt(adt, args) if adt.is_enum() => variant
2083                        .fields
2084                        .iter()
2085                        .map(|f| self.normalize(span, f.ty(self.tcx, *args)))
2086                        .collect(),
2087                    _ => {
2088                        self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct { span });
2089                        return;
2090                    }
2091                };
2092                self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2093            }
2094            hir::StructTailExpr::Base(base_expr) => {
2095                // FIXME: We are currently creating two branches here in order to maintain
2096                // consistency. But they should be merged as much as possible.
2097                let fru_tys = if self.tcx.features().type_changing_struct_update() {
2098                    if adt.is_struct() {
2099                        // Make some fresh generic parameters for our ADT type.
2100                        let fresh_args = self.fresh_args_for_item(base_expr.span, adt.did());
2101                        // We do subtyping on the FRU fields first, so we can
2102                        // learn exactly what types we expect the base expr
2103                        // needs constrained to be compatible with the struct
2104                        // type we expect from the expectation value.
2105                        let fru_tys = variant
2106                            .fields
2107                            .iter()
2108                            .map(|f| {
2109                                let fru_ty = self.normalize(
2110                                    expr.span,
2111                                    Unnormalized::new_wip(self.field_ty(
2112                                        base_expr.span,
2113                                        f,
2114                                        fresh_args,
2115                                    )),
2116                                );
2117                                let ident =
2118                                    self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2119                                if let Some(_) = remaining_fields.remove(&ident) {
2120                                    let target_ty = self.field_ty(base_expr.span, f, *args);
2121                                    let cause = self.misc(base_expr.span);
2122                                    if let Err(diag) =
2123                                        self.demand_suptype_diag(cause.span, target_ty, fru_ty)
2124                                    {
2125                                        diag.delay_as_bug();
2126                                    }
2127                                }
2128                                self.deeply_resolve_ignoring_regions(fru_ty)
2129                            })
2130                            .collect();
2131                        // The use of fresh args that we have subtyped against
2132                        // our base ADT type's fields allows us to guide inference
2133                        // along so that, e.g.
2134                        // ```
2135                        // MyStruct<'a, F1, F2, const C: usize> {
2136                        //     f: F1,
2137                        //     // Other fields that reference `'a`, `F2`, and `C`
2138                        // }
2139                        //
2140                        // let x = MyStruct {
2141                        //    f: 1usize,
2142                        //    ..other_struct
2143                        // };
2144                        // ```
2145                        // will have the `other_struct` expression constrained to
2146                        // `MyStruct<'a, _, F2, C>`, as opposed to just `_`...
2147                        // This is important to allow coercions to happen in
2148                        // `other_struct` itself. See `coerce-in-base-expr.rs`.
2149                        let fresh_base_ty = Ty::new_adt(self.tcx, *adt, fresh_args);
2150                        self.check_expr_has_type_or_error(
2151                            base_expr,
2152                            self.deeply_resolve_ignoring_regions(fresh_base_ty),
2153                            |_| {},
2154                        );
2155                        fru_tys
2156                    } else {
2157                        // Check the base_expr, regardless of a bad expected adt_ty, so we can get
2158                        // type errors on that expression, too.
2159                        self.check_expr(base_expr);
2160                        self.dcx()
2161                            .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
2162                        return;
2163                    }
2164                } else {
2165                    self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {
2166                        let base_ty = self.typeck_results.borrow().expr_ty(base_expr);
2167                        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()),
2168                            (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt);
2169                        if self.tcx.sess.is_nightly_build() && same_adt {
2170                            feature_err(
2171                                &self.tcx.sess,
2172                                sym::type_changing_struct_update,
2173                                base_expr.span,
2174                                "type changing struct updating is experimental",
2175                            )
2176                            .emit();
2177                        }
2178                    });
2179                    match adt_ty.kind() {
2180                        ty::Adt(adt, args) if adt.is_struct() => variant
2181                            .fields
2182                            .iter()
2183                            .map(|f| self.normalize(expr.span, f.ty(self.tcx, *args)))
2184                            .collect(),
2185                        _ => {
2186                            self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct {
2187                                span: base_expr.span,
2188                            });
2189                            return;
2190                        }
2191                    }
2192                };
2193                self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2194            }
2195            rustc_hir::StructTailExpr::NoneWithError(guaranteed) => {
2196                // If parsing the struct recovered from a syntax error, do not report missing
2197                // fields. This prevents spurious errors when a field is intended to be present
2198                // but a preceding syntax error caused it not to be parsed. For example, if a
2199                // struct type `StructName` has fields `foo` and `bar`, then
2200                //     StructName { foo(), bar: 2 }
2201                // will not successfully parse a field `foo`, but we will not mention that,
2202                // since the syntax error has already been reported.
2203
2204                // Signal that type checking has failed, even though we haven’t emitted a diagnostic
2205                // about it ourselves.
2206                self.infcx.set_tainted_by_errors(guaranteed);
2207            }
2208            rustc_hir::StructTailExpr::None => {
2209                if adt_kind != AdtKind::Union
2210                    && !remaining_fields.is_empty()
2211                    //~ non_exhaustive already reported, which will only happen for extern modules
2212                    && !variant.field_list_has_applicable_non_exhaustive()
2213                {
2214                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs:2214",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(2214u32),
                        ::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);
2215
2216                    // Report missing fields.
2217
2218                    let private_fields: Vec<&ty::FieldDef> = variant
2219                        .fields
2220                        .iter()
2221                        .filter(|field| !field.vis.is_accessible_from(self.mod_id, tcx))
2222                        .collect();
2223
2224                    if !private_fields.is_empty() {
2225                        self.report_private_fields(
2226                            adt_ty,
2227                            path_span,
2228                            expr.span,
2229                            private_fields,
2230                            hir_fields,
2231                        );
2232                    } else {
2233                        self.report_missing_fields(
2234                            adt_ty,
2235                            path_span,
2236                            expr.span,
2237                            remaining_fields,
2238                            variant,
2239                            hir_fields,
2240                            *args,
2241                        );
2242                    }
2243                }
2244            }
2245        }
2246    }
2247
2248    fn check_struct_fields_on_error(
2249        &self,
2250        fields: &'tcx [hir::ExprField<'tcx>],
2251        base_expr: &'tcx hir::StructTailExpr<'tcx>,
2252    ) {
2253        for field in fields {
2254            self.check_expr(field.expr);
2255        }
2256        if let hir::StructTailExpr::Base(base) = *base_expr {
2257            self.check_expr(base);
2258        }
2259    }
2260
2261    pub(crate) fn available_field_names(
2262        &self,
2263        variant: &'tcx ty::VariantDef,
2264        expr: &hir::Expr<'_>,
2265        skip_fields: &[hir::ExprField<'_>],
2266    ) -> Vec<Symbol> {
2267        variant
2268            .fields
2269            .iter()
2270            .filter(|field| {
2271                skip_fields.iter().all(|&skip| skip.ident.name != field.name)
2272                    && self.is_field_suggestable(field, expr.span)
2273            })
2274            .map(|field| field.name)
2275            .collect()
2276    }
2277
2278    /// Find the position of a field named `ident` in `base_def`, accounting for unnammed fields.
2279    /// Return whether such a field has been found. The path to it is stored in `nested_fields`.
2280    /// `ident` must have been adjusted beforehand.
2281    fn find_adt_field(
2282        &self,
2283        base_def: ty::AdtDef<'tcx>,
2284        ident: Ident,
2285    ) -> Option<(FieldIdx, &'tcx ty::FieldDef)> {
2286        // No way to find a field in an enum.
2287        if base_def.is_enum() {
2288            return None;
2289        }
2290
2291        for (field_idx, field) in base_def.non_enum_variant().fields.iter_enumerated() {
2292            if field.ident(self.tcx).normalize_to_macros_2_0() == ident {
2293                // We found the field we wanted.
2294                return Some((field_idx, field));
2295            }
2296        }
2297
2298        None
2299    }
2300
2301    /// Check field access expressions, this works for both structs and tuples.
2302    /// Returns the Ty of the field.
2303    ///
2304    /// ```ignore (illustrative)
2305    /// base.field
2306    /// ^^^^^^^^^^ expr
2307    /// ^^^^       base
2308    ///      ^^^^^ field
2309    /// ```
2310    fn check_expr_field(
2311        &self,
2312        expr: &'tcx hir::Expr<'tcx>,
2313        base: &'tcx hir::Expr<'tcx>,
2314        field: Ident,
2315        // The expected type hint of the field.
2316        expected: Expectation<'tcx>,
2317    ) -> Ty<'tcx> {
2318        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs:2318",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(2318u32),
                        ::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);
2319        let base_ty = self.check_expr(base);
2320        let base_ty = self.structurally_resolve_type(base.span, base_ty);
2321
2322        // Whether we are trying to access a private field. Used for error reporting.
2323        let mut private_candidate = None;
2324
2325        // Field expressions automatically deref
2326        let mut autoderef = self.autoderef(expr.span, base_ty);
2327        while let Some((deref_base_ty, _)) = autoderef.next() {
2328            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs:2328",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(2328u32),
                        ::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);
2329            match deref_base_ty.kind() {
2330                ty::Adt(base_def, args) if !base_def.is_enum() => {
2331                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs:2331",
                        "rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6905905bb7727fd0f9223f5fdc9ad4e62236d5a2/compiler/rustc_hir_typeck/src/expr.rs"),
                        ::tracing_core::__macro_support::Option::Some(2331u32),
                        ::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);
2332                    // we don't care to report errors for a struct if the struct itself is tainted
2333                    if let Err(guar) = base_def.non_enum_variant().has_errors() {
2334                        return Ty::new_error(self.tcx(), guar);
2335                    }
2336
2337                    let (ident, def_scope) =
2338                        self.tcx.adjust_ident_and_get_scope(field, base_def.did(), self.mod_id);
2339
2340                    if let Some((idx, field)) = self.find_adt_field(*base_def, ident) {
2341                        self.write_field_index(expr.hir_id, idx);
2342
2343                        let adjustments = self.adjust_steps(&autoderef);
2344                        if field.vis.is_accessible_from(def_scope, self.tcx) {
2345                            self.apply_adjustments(base, adjustments);
2346                            self.register_predicates(autoderef.into_obligations());
2347
2348                            self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
2349                            return self.field_ty(expr.span, field, *args);
2350                        }
2351
2352                        // The field is not accessible, fall through to error reporting.
2353                        private_candidate = Some((adjustments, base_def.did()));
2354                    }
2355                }
2356                ty::Tuple(tys) => {
2357                    if let Ok(index) = field.as_str().parse::<usize>() {
2358                        if field.name == sym::integer(index) {
2359                            if let Some(&field_ty) = tys.get(index) {
2360                                let adjustments = self.adjust_steps(&autoderef);
2361                                self.apply_adjustments(base, adjustments);
2362                                self.register_predicates(autoderef.into_obligations());
2363
2364                                self.write_field_index(expr.hir_id, FieldIdx::from_usize(index));
2365                                return field_ty;
2366                            }
2367                        }
2368                    }
2369                }
2370                _ => {}
2371            }
2372        }
2373        // We failed to check the expression, report an error.
2374
2375        // Emits an error if we deref an infer variable, like calling `.field` on a base type
2376        // of `&_`. We can also use this to suppress unnecessary "missing field" errors that
2377        // will follow ambiguity errors.
2378        let final_ty = self.structurally_resolve_type(autoderef.span(), autoderef.final_ty());
2379        if let ty::Error(_) = final_ty.kind() {
2380            return final_ty;
2381        }
2382
2383        if let Some((adjustments, did)) = private_candidate {
2384            // (#90483) apply adjustments to avoid ExprUseVisitor from
2385            // creating erroneous projection.
2386            self.apply_adjustments(base, adjustments);
2387            let guar = self.ban_private_field_access(
2388                expr,
2389                base_ty,
2390                field,
2391                did,
2392                expected.only_has_type(self),
2393            );
2394            return Ty::new_error(self.tcx(), guar);
2395        }
2396
2397        let guar = if self.method_exists_for_diagnostic(
2398            field,
2399            base_ty,
2400            expr.hir_id,
2401            expected.only_has_type(self),
2402        ) {
2403            // If taking a method instead of calling it
2404            self.ban_take_value_of_method(expr, base_ty, field)
2405        } else if !base_ty.is_primitive_ty() {
2406            self.ban_nonexisting_field(field, base, expr, base_ty)
2407        } else {
2408            let field_name = field.to_string();
2409            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!(
2410                self.dcx(),
2411                field.span,
2412                base_ty,
2413                E0610,
2414                "`{base_ty}` is a primitive type and therefore doesn't have fields",
2415            );
2416            let is_valid_suffix = |field: &str| {
2417                if field == "f32" || field == "f64" {
2418                    return true;
2419                }
2420                let mut chars = field.chars().peekable();
2421                match chars.peek() {
2422                    Some('e') | Some('E') => {
2423                        chars.next();
2424                        if let Some(c) = chars.peek()
2425                            && !c.is_numeric()
2426                            && *c != '-'
2427                            && *c != '+'
2428                        {
2429                            return false;
2430                        }
2431                        while let Some(c) = chars.peek() {
2432                            if !c.is_numeric() {
2433                                break;
2434                            }
2435                            chars.next();
2436                        }
2437                    }
2438                    _ => (),
2439                }
2440                let suffix = chars.collect::<String>();
2441                suffix.is_empty() || suffix == "f32" || suffix == "f64"
2442            };
2443            let maybe_partial_suffix = |field: &str| -> Option<&str> {
2444                let first_chars = ['f', 'l'];
2445                if field.len() >= 1
2446                    && field.to_lowercase().starts_with(first_chars)
2447                    && field[1..].chars().all(|c| c.is_ascii_digit())
2448                {
2449                    if field.to_lowercase().starts_with(['f']) { Some("f32") } else { Some("f64") }
2450                } else {
2451                    None
2452                }
2453            };
2454            if let ty::Infer(ty::IntVar(_)) = base_ty.kind()
2455                && let ExprKind::Lit(Spanned {
2456                    node: ast::LitKind::Int(_, ast::LitIntType::Unsuffixed),
2457                    ..
2458                }) = base.kind
2459                && !base.span.from_expansion()
2460            {
2461                if is_valid_suffix(&field_name) {
2462                    err.span_suggestion_verbose(
2463                        field.span.shrink_to_lo(),
2464                        "if intended to be a floating point literal, consider adding a `0` after the period",
2465                        '0',
2466                        Applicability::MaybeIncorrect,
2467                    );
2468                } else if let Some(correct_suffix) = maybe_partial_suffix(&field_name) {
2469                    err.span_suggestion_verbose(
2470                        field.span,
2471                        ::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"),
2472                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("0{0}", correct_suffix))
    })format!("0{correct_suffix}"),
2473                        Applicability::MaybeIncorrect,
2474                    );
2475                }
2476            }
2477            err.emit_err()
2478        };
2479
2480        Ty::new_error(self.tcx(), guar)
2481    }
2482
2483    fn check_expr_index(
2484        &self,
2485        base: &'tcx hir::Expr<'tcx>,
2486        idx: &'tcx hir::Expr<'tcx>,
2487        expr: &'tcx hir::Expr<'tcx>,
2488        brackets_span: Span,
2489    ) -> Ty<'tcx> {
2490        let base_t = self.check_expr(base);
2491        let idx_t = self.check_expr(idx);
2492
2493        if base_t.references_error() {
2494            base_t
2495        } else if idx_t.references_error() {
2496            idx_t
2497        } else {
2498            let base_t = self.structurally_resolve_type(base.span, base_t);
2499            match self.lookup_indexing(expr, base, base_t, idx, idx_t) {
2500                Some((index_ty, element_ty)) => {
2501                    // two-phase not needed because index_ty is never mutable
2502                    self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
2503                    self.select_obligations_where_possible(|errors| {
2504                        self.point_at_index(errors, idx.span);
2505                    });
2506                    element_ty
2507                }
2508                None => {
2509                    // Attempt to *shallowly* search for an impl which matches,
2510                    // but has nested obligations which are unsatisfied.
2511                    for (base_t, _) in self.autoderef(base.span, base_t).silence_errors() {
2512                        if let Some((_, index_ty, element_ty)) =
2513                            self.find_and_report_unsatisfied_index_impl(base, base_t)
2514                        {
2515                            self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
2516                            return element_ty;
2517                        }
2518                    }
2519
2520                    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!(
2521                        self.dcx(),
2522                        brackets_span,
2523                        base_t,
2524                        E0608,
2525                        "cannot index into a value of type `{base_t}`",
2526                    );
2527                    // Try to give some advice about indexing tuples.
2528                    if let ty::Tuple(types) = base_t.kind() {
2529                        err.help(
2530                            "tuples are indexed with a dot and a literal index: `tuple.0`, `tuple.1`, etc.",
2531                        );
2532                        // If index is an unsuffixed integer, show the fixed expression:
2533                        if let ExprKind::Lit(lit) = idx.kind
2534                            && let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node
2535                            && i.get() < types.len().try_into().expect("tuple length fits in u128")
2536                        {
2537                            err.span_suggestion(
2538                                brackets_span,
2539                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("to access tuple element `{0}`, use",
                i))
    })format!("to access tuple element `{i}`, use"),
2540                                ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!(".{0}", i)) })format!(".{i}"),
2541                                Applicability::MachineApplicable,
2542                            );
2543                        }
2544                    }
2545
2546                    if base_t.is_raw_ptr() && idx_t.is_integral() {
2547                        err.multipart_suggestion(
2548                            "consider using `wrapping_add` or `add` for indexing into raw pointer",
2549                            ::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![
2550                                (base.span.between(idx.span), ".wrapping_add(".to_owned()),
2551                                (
2552                                    idx.span.shrink_to_hi().until(expr.span.shrink_to_hi()),
2553                                    ")".to_owned(),
2554                                ),
2555                            ],
2556                            Applicability::MaybeIncorrect,
2557                        );
2558                    }
2559
2560                    let guar = err.emit_err();
2561                    Ty::new_error(self.tcx, guar)
2562                }
2563            }
2564        }
2565    }
2566
2567    /// Try to match an implementation of `Index` against a self type, and report
2568    /// the unsatisfied predicates that result from confirming this impl.
2569    ///
2570    /// Given an index expression, sometimes the `Self` type shallowly but does not
2571    /// deeply satisfy an impl predicate. Instead of simply saying that the type
2572    /// does not support being indexed, we want to point out exactly what nested
2573    /// predicates cause this to be, so that the user can add them to fix their code.
2574    fn find_and_report_unsatisfied_index_impl(
2575        &self,
2576        base_expr: &hir::Expr<'_>,
2577        base_ty: Ty<'tcx>,
2578    ) -> Option<(ErrorGuaranteed, Ty<'tcx>, Ty<'tcx>)> {
2579        let index_trait_def_id = self.tcx.lang_items().index_trait()?;
2580        let index_trait_output_def_id = self.tcx.get_diagnostic_item(sym::IndexOutput)?;
2581
2582        let mut relevant_impls = ::alloc::vec::Vec::new()vec![];
2583        self.tcx.for_each_relevant_impl(index_trait_def_id, base_ty, |impl_def_id| {
2584            relevant_impls.push(impl_def_id);
2585        });
2586        let [impl_def_id] = relevant_impls[..] else {
2587            // Only report unsatisfied impl predicates if there's one impl
2588            return None;
2589        };
2590
2591        self.commit_if_ok(|snapshot| {
2592            let outer_universe = self.universe();
2593
2594            let ocx = ObligationCtxt::new_with_diagnostics(self);
2595            let impl_args = self.fresh_args_for_item(base_expr.span, impl_def_id);
2596            let impl_trait_ref =
2597                self.tcx.impl_trait_ref(impl_def_id).instantiate(self.tcx, impl_args);
2598            let cause = self.misc(base_expr.span);
2599
2600            // Match the impl self type against the base ty. If this fails,
2601            // we just skip this impl, since it's not particularly useful.
2602            let impl_trait_ref = ocx.normalize(&cause, self.param_env, impl_trait_ref);
2603            ocx.eq(&cause, self.param_env, base_ty, impl_trait_ref.self_ty())?;
2604
2605            // Register the impl's predicates. One of these predicates
2606            // must be unsatisfied, or else we wouldn't have gotten here
2607            // in the first place.
2608            let unnormalized_clauses =
2609                self.tcx.clauses_of(impl_def_id).instantiate(self.tcx, impl_args);
2610            ocx.register_obligations(traits::predicates_for_generics(
2611                |idx, span| {
2612                    cause.clone().derived_cause(
2613                        ty::Binder::dummy(ty::TraitClause {
2614                            trait_ref: impl_trait_ref,
2615                            polarity: ty::ClausePolarity::Positive,
2616                        }),
2617                        |derived| {
2618                            ObligationCauseCode::ImplDerived(Box::new(traits::ImplDerivedCause {
2619                                derived,
2620                                impl_or_alias_def_id: impl_def_id,
2621                                impl_def_clause_index: Some(idx),
2622                                span,
2623                            }))
2624                        },
2625                    )
2626                },
2627                |clause| ocx.normalize(&cause, self.param_env, clause),
2628                self.param_env,
2629                unnormalized_clauses,
2630            ));
2631
2632            // Normalize the output type, which we can use later on as the
2633            // return type of the index expression...
2634            let element_ty = ocx.normalize(
2635                &cause,
2636                self.param_env,
2637                Unnormalized::new(Ty::new_projection_from_args(
2638                    self.tcx,
2639                    ty::IsRigid::No,
2640                    index_trait_output_def_id,
2641                    impl_trait_ref.args,
2642                )),
2643            );
2644
2645            let true_errors = ocx.try_evaluate_obligations();
2646
2647            // Do a leak check -- we can't really report a useful error here,
2648            // but it at least avoids an ICE when the error has to do with higher-ranked
2649            // lifetimes.
2650            self.leak_check(outer_universe, Some(snapshot))?;
2651
2652            // Bail if we have ambiguity errors, which we can't report in a useful way.
2653            let ambiguity_errors = ocx.evaluate_obligations_error_on_ambiguity();
2654            if true_errors.no_errors() && ambiguity_errors.has_errors() {
2655                return Err(NoSolution);
2656            }
2657
2658            // There should be at least one error reported. If not, we
2659            // will still delay a span bug in `report_fulfillment_errors`.
2660            Ok::<_, NoSolution>((
2661                self.err_ctxt().report_fulfillment_errors(true_errors.into_thin_vec()),
2662                impl_trait_ref.args.type_at(1),
2663                element_ty,
2664            ))
2665        })
2666        .ok()
2667    }
2668
2669    fn check_expr_yield(
2670        &self,
2671        value: &'tcx hir::Expr<'tcx>,
2672        expr: &'tcx hir::Expr<'tcx>,
2673    ) -> Ty<'tcx> {
2674        match self.coroutine_types {
2675            Some(CoroutineTypes { resume_ty, yield_ty }) => {
2676                self.check_expr_coercible_to_type(value, yield_ty, None);
2677
2678                resume_ty
2679            }
2680            _ => {
2681                self.dcx().emit_err(YieldExprOutsideOfCoroutine { span: expr.span });
2682                // Avoid expressions without types during writeback (#78653).
2683                self.check_expr(value);
2684                self.tcx.types.unit
2685            }
2686        }
2687    }
2688
2689    fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
2690        let needs = if is_input { Needs::None } else { Needs::MutPlace };
2691        let ty = self.check_expr_with_needs(expr, needs);
2692        self.require_type_is_sized(ty, expr.span, ObligationCauseCode::InlineAsmSized);
2693
2694        if !is_input && !expr.is_syntactic_place_expr() {
2695            self.dcx()
2696                .struct_span_err(expr.span, "invalid asm output")
2697                .with_span_label(expr.span, "cannot assign to this expression")
2698                .emit();
2699        }
2700
2701        // If this is an input value, we require its type to be fully resolved
2702        // at this point. This allows us to provide helpful coercions which help
2703        // pass the type candidate list in a later pass.
2704        //
2705        // We don't require output types to be resolved at this point, which
2706        // allows them to be inferred based on how they are used later in the
2707        // function.
2708        if is_input {
2709            let ty = self.structurally_resolve_type(expr.span, ty);
2710            match *ty.kind() {
2711                ty::FnDef(..) => {
2712                    let fnptr_ty = Ty::new_fn_ptr(self.tcx, ty.fn_sig(self.tcx));
2713                    self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
2714                }
2715                ty::Ref(_, base_ty, mutbl) => {
2716                    let ptr_ty = Ty::new_ptr(self.tcx, base_ty, mutbl);
2717                    self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
2718                }
2719                _ => {}
2720            }
2721        }
2722    }
2723
2724    fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) -> Ty<'tcx> {
2725        if let rustc_ast::AsmMacro::NakedAsm = asm.asm_macro {
2726            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::Tool { .. } |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self.tcx, self.body_def_id, Naked(..)) {
2727                self.tcx.dcx().emit_err(NakedAsmOutsideNakedFn { span });
2728            }
2729        }
2730
2731        let mut diverge = asm.asm_macro.diverges(asm.options);
2732
2733        for (op, _op_sp) in asm.operands {
2734            match *op {
2735                hir::InlineAsmOperand::In { expr, .. } => {
2736                    self.check_expr_asm_operand(expr, true);
2737                }
2738                hir::InlineAsmOperand::Out { expr: Some(expr), .. }
2739                | hir::InlineAsmOperand::InOut { expr, .. } => {
2740                    self.check_expr_asm_operand(expr, false);
2741                }
2742                hir::InlineAsmOperand::Out { expr: None, .. } => {}
2743                hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
2744                    self.check_expr_asm_operand(in_expr, true);
2745                    if let Some(out_expr) = out_expr {
2746                        self.check_expr_asm_operand(out_expr, false);
2747                    }
2748                }
2749                hir::InlineAsmOperand::Const { ref anon_const } => {
2750                    // This is mostly similar to type-checking of inline const expressions `const { ... }`, however
2751                    // asm const has special coercion rules (per RFC 3848) where function items and closures are coerced to
2752                    // function pointers (while pointers and integer remain as-is).
2753                    let body = self.tcx.hir_body(anon_const.body);
2754
2755                    let fcx = FnCtxt::new(self, self.param_env, anon_const.def_id);
2756                    let ty = fcx.check_expr(body.value);
2757                    let target_ty = match self.structurally_resolve_type(body.value.span, ty).kind()
2758                    {
2759                        ty::FnDef(..) => {
2760                            let fn_sig = ty.fn_sig(self.tcx());
2761                            Ty::new_fn_ptr(self.tcx(), fn_sig)
2762                        }
2763                        ty::Closure(_, args) => {
2764                            let closure_sig = args.as_closure().sig();
2765                            let fn_sig =
2766                                self.tcx().signature_unclosure(closure_sig, hir::Safety::Safe);
2767                            Ty::new_fn_ptr(self.tcx(), fn_sig)
2768                        }
2769                        _ => ty,
2770                    };
2771
2772                    if let Err(diag) =
2773                        self.demand_coerce_diag(&body.value, ty, target_ty, None, AllowTwoPhase::No)
2774                    {
2775                        diag.emit();
2776                    }
2777
2778                    fcx.require_type_is_sized(
2779                        target_ty,
2780                        body.value.span,
2781                        ObligationCauseCode::SizedConstOrStatic,
2782                    );
2783                    fcx.write_ty(anon_const.hir_id, target_ty);
2784                }
2785                hir::InlineAsmOperand::SymFn { expr } => {
2786                    self.check_expr(expr);
2787                }
2788                hir::InlineAsmOperand::SymStatic { .. } => {}
2789                hir::InlineAsmOperand::Label { block } => {
2790                    let previous_diverges = self.diverges.get();
2791
2792                    // The label blocks should have unit return value or diverge.
2793                    let ty = self.check_expr_block(block, ExpectHasType(self.tcx.types.unit));
2794                    if !ty.is_never() {
2795                        self.demand_suptype(block.span, self.tcx.types.unit, ty);
2796                        diverge = false;
2797                    }
2798
2799                    // We need this to avoid false unreachable warning when a label diverges.
2800                    self.diverges.set(previous_diverges);
2801                }
2802            }
2803        }
2804
2805        if diverge { self.tcx.types.never } else { self.tcx.types.unit }
2806    }
2807
2808    fn check_expr_offset_of(
2809        &self,
2810        container: &'tcx hir::Ty<'tcx>,
2811        fields: &[Ident],
2812        expr: &'tcx hir::Expr<'tcx>,
2813    ) -> Ty<'tcx> {
2814        let mut current_container = self.lower_ty(container).normalized;
2815        let mut field_indices = Vec::with_capacity(fields.len());
2816        let mut fields = fields.into_iter();
2817
2818        while let Some(&field) = fields.next() {
2819            let container = self.structurally_resolve_type(expr.span, current_container);
2820
2821            match container.kind() {
2822                ty::Adt(container_def, args) if container_def.is_enum() => {
2823                    let ident = self.tcx.adjust_ident(field, container_def.did());
2824
2825                    if !self.tcx.features().offset_of_enum() {
2826                        rustc_session::diagnostics::feature_err(
2827                            &self.tcx.sess,
2828                            sym::offset_of_enum,
2829                            ident.span,
2830                            "using enums in offset_of is experimental",
2831                        )
2832                        .emit();
2833                    }
2834
2835                    let Some((index, variant)) = container_def
2836                        .variants()
2837                        .iter_enumerated()
2838                        .find(|(_, v)| v.ident(self.tcx).normalize_to_macros_2_0() == ident)
2839                    else {
2840                        self.dcx()
2841                            .create_err(NoVariantNamed { span: ident.span, ident, ty: container })
2842                            .with_span_label(field.span, "variant not found")
2843                            .emit_err_unless_delay(container.references_error());
2844                        break;
2845                    };
2846                    let Some(&subfield) = fields.next() else {
2847                        {
    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!(
2848                            self.dcx(),
2849                            ident.span,
2850                            container,
2851                            E0795,
2852                            "`{ident}` is an enum variant; expected field at end of `offset_of`",
2853                        )
2854                        .with_span_label(field.span, "enum variant")
2855                        .emit();
2856                        break;
2857                    };
2858                    let (subident, sub_def_scope) =
2859                        self.tcx.adjust_ident_and_get_scope(subfield, variant.def_id, self.mod_id);
2860
2861                    let Some((subindex, field)) = variant
2862                        .fields
2863                        .iter_enumerated()
2864                        .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == subident)
2865                    else {
2866                        self.dcx()
2867                            .create_err(NoFieldOnVariant {
2868                                span: ident.span,
2869                                container,
2870                                ident,
2871                                field: subfield,
2872                                enum_span: field.span,
2873                                field_span: subident.span,
2874                            })
2875                            .emit_err_unless_delay(container.references_error());
2876                        break;
2877                    };
2878
2879                    let field_ty = self.field_ty(expr.span, field, *args);
2880
2881                    // Enums are anyway always sized. But just to safeguard against future
2882                    // language extensions, let's double-check.
2883                    self.require_type_is_sized(
2884                        field_ty,
2885                        expr.span,
2886                        ObligationCauseCode::FieldSized {
2887                            adt_kind: AdtKind::Enum,
2888                            span: self.tcx.def_span(field.did),
2889                            last: false,
2890                        },
2891                    );
2892
2893                    if field.vis.is_accessible_from(sub_def_scope, self.tcx) {
2894                        self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
2895                    } else {
2896                        self.private_field_err(ident, container_def.did()).emit();
2897                    }
2898
2899                    // Save the index of all fields regardless of their visibility in case
2900                    // of error recovery.
2901                    field_indices.push((current_container, index, subindex));
2902                    current_container = field_ty;
2903
2904                    continue;
2905                }
2906                ty::Adt(container_def, args) => {
2907                    let (ident, def_scope) = self.tcx.adjust_ident_and_get_scope(
2908                        field,
2909                        container_def.did(),
2910                        self.mod_id,
2911                    );
2912
2913                    let fields = &container_def.non_enum_variant().fields;
2914                    if let Some((index, field)) = fields
2915                        .iter_enumerated()
2916                        .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == ident)
2917                    {
2918                        let field_ty = self.field_ty(expr.span, field, *args);
2919
2920                        if self.tcx.features().offset_of_slice() {
2921                            self.require_type_has_static_alignment(field_ty, expr.span);
2922                        } else {
2923                            self.require_type_is_sized(
2924                                field_ty,
2925                                expr.span,
2926                                ObligationCauseCode::WellFormed(WellFormedLoc::HirId(expr.hir_id)),
2927                            );
2928                        }
2929
2930                        if field.vis.is_accessible_from(def_scope, self.tcx) {
2931                            self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
2932                        } else {
2933                            self.private_field_err(ident, container_def.did()).emit();
2934                        }
2935
2936                        // Save the index of all fields regardless of their visibility in case
2937                        // of error recovery.
2938                        field_indices.push((current_container, FIRST_VARIANT, index));
2939                        current_container = field_ty;
2940
2941                        continue;
2942                    }
2943                }
2944                ty::Tuple(tys) => {
2945                    if let Ok(index) = field.as_str().parse::<usize>()
2946                        && field.name == sym::integer(index)
2947                    {
2948                        if let Some(&field_ty) = tys.get(index) {
2949                            if self.tcx.features().offset_of_slice() {
2950                                self.require_type_has_static_alignment(field_ty, expr.span);
2951                            } else {
2952                                self.require_type_is_sized(
2953                                    field_ty,
2954                                    expr.span,
2955                                    ObligationCauseCode::WellFormed(WellFormedLoc::HirId(
2956                                        expr.hir_id,
2957                                    )),
2958                                );
2959                            }
2960
2961                            field_indices.push((current_container, FIRST_VARIANT, index.into()));
2962                            current_container = field_ty;
2963
2964                            continue;
2965                        }
2966                    }
2967                }
2968                _ => (),
2969            };
2970
2971            self.no_such_field_err(field, container, expr).emit();
2972
2973            break;
2974        }
2975
2976        self.typeck_results.borrow_mut().offset_of_data_mut().insert(expr.hir_id, field_indices);
2977
2978        self.tcx.types.usize
2979    }
2980}