rustc_hir_typeck/
expr.rs

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