1 //! Type checking expressions.
3 //! See `mod.rs` for more context on type checking in general.
6 use crate::coercion::CoerceMany;
7 use crate::coercion::DynamicCoerceMany;
8 use crate::errors::TypeMismatchFruTypo;
9 use crate::errors::{AddressOfTemporaryTaken, ReturnStmtOutsideOfFnBody, StructExprNonExhaustive};
11 FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct,
12 YieldExprOutsideOfGenerator,
14 use crate::fatally_break_rust;
15 use crate::method::SelfSource;
16 use crate::type_error_struct;
17 use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation};
19 report_unexpected_variant_res, BreakableCtxt, Diverges, FnCtxt, Needs,
20 TupleArgumentsFlag::DontTupleArguments,
23 use rustc_data_structures::fx::FxHashMap;
24 use rustc_data_structures::stack::ensure_sufficient_stack;
26 pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, DiagnosticId,
27 ErrorGuaranteed, StashKey,
30 use rustc_hir::def::{CtorKind, DefKind, Res};
31 use rustc_hir::def_id::DefId;
32 use rustc_hir::intravisit::Visitor;
33 use rustc_hir::lang_items::LangItem;
34 use rustc_hir::{ExprKind, HirId, QPath};
35 use rustc_hir_analysis::astconv::AstConv as _;
36 use rustc_hir_analysis::check::ty_kind_suggestion;
37 use rustc_infer::infer;
38 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
39 use rustc_infer::infer::InferOk;
40 use rustc_infer::traits::ObligationCause;
41 use rustc_middle::middle::stability;
42 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
43 use rustc_middle::ty::error::TypeError::FieldMisMatch;
44 use rustc_middle::ty::subst::SubstsRef;
45 use rustc_middle::ty::{self, AdtKind, Ty, TypeVisitable};
46 use rustc_session::errors::ExprParenthesesNeeded;
47 use rustc_session::parse::feature_err;
48 use rustc_span::hygiene::DesugaringKind;
49 use rustc_span::lev_distance::find_best_match_for_name;
50 use rustc_span::source_map::{Span, Spanned};
51 use rustc_span::symbol::{kw, sym, Ident, Symbol};
52 use rustc_target::spec::abi::Abi::RustIntrinsic;
53 use rustc_trait_selection::infer::InferCtxtExt;
54 use rustc_trait_selection::traits::{self, ObligationCauseCode};
56 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
57 fn check_expr_eq_type(&self, expr: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>) {
58 let ty = self.check_expr_with_hint(expr, expected);
59 self.demand_eqtype(expr.span, expected, ty);
62 pub fn check_expr_has_type_or_error(
64 expr: &'tcx hir::Expr<'tcx>,
66 extend_err: impl FnMut(&mut Diagnostic),
68 self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err)
71 fn check_expr_meets_expectation_or_error(
73 expr: &'tcx hir::Expr<'tcx>,
74 expected: Expectation<'tcx>,
75 mut extend_err: impl FnMut(&mut Diagnostic),
77 let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
78 let mut ty = self.check_expr_with_expectation(expr, expected);
80 // While we don't allow *arbitrary* coercions here, we *do* allow
81 // coercions from ! to `expected`.
83 if let Some(adjustments) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
84 let reported = self.tcx().sess.delay_span_bug(
86 "expression with never type wound up being adjusted",
88 return if let [Adjustment { kind: Adjust::NeverToAny, target }] = &adjustments[..] {
91 self.tcx().ty_error_with_guaranteed(reported)
95 let adj_ty = self.next_ty_var(TypeVariableOrigin {
96 kind: TypeVariableOriginKind::AdjustmentType,
99 self.apply_adjustments(
101 vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }],
106 if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
107 let _ = self.emit_type_mismatch_suggestions(
109 expr.peel_drop_temps(),
115 extend_err(&mut err);
121 pub(super) fn check_expr_coercable_to_type(
123 expr: &'tcx hir::Expr<'tcx>,
125 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
127 let ty = self.check_expr_with_hint(expr, expected);
128 // checks don't need two phase
129 self.demand_coerce(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No)
132 pub(super) fn check_expr_with_hint(
134 expr: &'tcx hir::Expr<'tcx>,
137 self.check_expr_with_expectation(expr, ExpectHasType(expected))
140 fn check_expr_with_expectation_and_needs(
142 expr: &'tcx hir::Expr<'tcx>,
143 expected: Expectation<'tcx>,
146 let ty = self.check_expr_with_expectation(expr, expected);
148 // If the expression is used in a place whether mutable place is required
149 // e.g. LHS of assignment, perform the conversion.
150 if let Needs::MutPlace = needs {
151 self.convert_place_derefs_to_mutable(expr);
157 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
158 self.check_expr_with_expectation(expr, NoExpectation)
161 pub(super) fn check_expr_with_needs(
163 expr: &'tcx hir::Expr<'tcx>,
166 self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
170 /// If an expression has any sub-expressions that result in a type error,
171 /// inspecting that expression's type with `ty.references_error()` will return
172 /// true. Likewise, if an expression is known to diverge, inspecting its
173 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
174 /// strict, _|_ can appear in the type of an expression that does not,
175 /// itself, diverge: for example, fn() -> _|_.)
176 /// Note that inspecting a type's structure *directly* may expose the fact
177 /// that there are actually multiple representations for `Error`, so avoid
178 /// that when err needs to be handled differently.
179 #[instrument(skip(self, expr), level = "debug")]
180 pub(super) fn check_expr_with_expectation(
182 expr: &'tcx hir::Expr<'tcx>,
183 expected: Expectation<'tcx>,
185 self.check_expr_with_expectation_and_args(expr, expected, &[])
188 /// Same as `check_expr_with_expectation`, but allows us to pass in the arguments of a
189 /// `ExprKind::Call` when evaluating its callee when it is an `ExprKind::Path`.
190 pub(super) fn check_expr_with_expectation_and_args(
192 expr: &'tcx hir::Expr<'tcx>,
193 expected: Expectation<'tcx>,
194 args: &'tcx [hir::Expr<'tcx>],
196 if self.tcx().sess.verbose() {
197 // make this code only run with -Zverbose because it is probably slow
198 if let Ok(lint_str) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
199 if !lint_str.contains('\n') {
200 debug!("expr text: {lint_str}");
202 let mut lines = lint_str.lines();
203 if let Some(line0) = lines.next() {
204 let remaining_lines = lines.count();
205 debug!("expr text: {line0}");
206 debug!("expr text: ...(and {remaining_lines} more lines)");
212 // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
213 // without the final expr (e.g. `try { return; }`). We don't want to generate an
214 // unreachable_code lint for it since warnings for autogenerated code are confusing.
215 let is_try_block_generated_unit_expr = match expr.kind {
216 ExprKind::Call(_, args) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {
217 args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock)
223 // Warn for expressions after diverging siblings.
224 if !is_try_block_generated_unit_expr {
225 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
228 // Hide the outer diverging and has_errors flags.
229 let old_diverges = self.diverges.replace(Diverges::Maybe);
231 let ty = ensure_sufficient_stack(|| match &expr.kind {
233 qpath @ hir::QPath::Resolved(..) | qpath @ hir::QPath::TypeRelative(..),
234 ) => self.check_expr_path(qpath, expr, args),
235 _ => self.check_expr_kind(expr, expected),
238 // Warn for non-block expressions with diverging children.
244 | ExprKind::Match(..) => {}
245 // If `expr` is a result of desugaring the try block and is an ok-wrapped
246 // diverging expression (e.g. it arose from desugaring of `try { return }`),
247 // we skip issuing a warning because it is autogenerated code.
248 ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {}
249 ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"),
250 ExprKind::MethodCall(segment, ..) => {
251 self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call")
253 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
256 // Any expression that produces a value of type `!` must have diverged
258 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
261 // Record the type, which applies it effects.
262 // We need to do this after the warning above, so that
263 // we don't warn for the diverging expression itself.
264 self.write_ty(expr.hir_id, ty);
266 // Combine the diverging and has_error flags.
267 self.diverges.set(self.diverges.get() | old_diverges);
269 debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
270 debug!("... {:?}, expected is {:?}", ty, expected);
275 #[instrument(skip(self, expr), level = "debug")]
278 expr: &'tcx hir::Expr<'tcx>,
279 expected: Expectation<'tcx>,
281 trace!("expr={:#?}", expr);
285 ExprKind::Box(subexpr) => self.check_expr_box(subexpr, expected),
286 ExprKind::Lit(ref lit) => self.check_lit(&lit, expected),
287 ExprKind::Binary(op, lhs, rhs) => self.check_binop(expr, op, lhs, rhs, expected),
288 ExprKind::Assign(lhs, rhs, span) => {
289 self.check_expr_assign(expr, expected, lhs, rhs, span)
291 ExprKind::AssignOp(op, lhs, rhs) => {
292 self.check_binop_assign(expr, op, lhs, rhs, expected)
294 ExprKind::Unary(unop, oprnd) => self.check_expr_unary(unop, oprnd, expected, expr),
295 ExprKind::AddrOf(kind, mutbl, oprnd) => {
296 self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
298 ExprKind::Path(QPath::LangItem(lang_item, _, hir_id)) => {
299 self.check_lang_item_path(lang_item, expr, hir_id)
301 ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr, &[]),
302 ExprKind::InlineAsm(asm) => {
303 // We defer some asm checks as we may not have resolved the input and output types yet (they may still be infer vars).
304 self.deferred_asm_checks.borrow_mut().push((asm, expr.hir_id));
305 self.check_expr_asm(asm)
307 ExprKind::Break(destination, ref expr_opt) => {
308 self.check_expr_break(destination, expr_opt.as_deref(), expr)
310 ExprKind::Continue(destination) => {
311 if destination.target_id.is_ok() {
314 // There was an error; make type-check fail.
318 ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
319 ExprKind::Let(let_expr) => self.check_expr_let(let_expr),
320 ExprKind::Loop(body, _, source, _) => {
321 self.check_expr_loop(body, source, expected, expr)
323 ExprKind::Match(discrim, arms, match_src) => {
324 self.check_match(expr, &discrim, arms, expected, match_src)
326 ExprKind::Closure(closure) => self.check_expr_closure(closure, expr.span, expected),
327 ExprKind::Block(body, _) => self.check_block_with_expected(&body, expected),
328 ExprKind::Call(callee, args) => self.check_call(expr, &callee, args, expected),
329 ExprKind::MethodCall(segment, receiver, args, _) => {
330 self.check_method_call(expr, segment, receiver, args, expected)
332 ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr),
333 ExprKind::Type(e, t) => {
334 let ty = self.to_ty_saving_user_provided_ty(&t);
335 self.check_expr_eq_type(&e, ty);
338 ExprKind::If(cond, then_expr, opt_else_expr) => {
339 self.check_then_else(cond, then_expr, opt_else_expr, expr.span, expected)
341 ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected),
342 ExprKind::Array(args) => self.check_expr_array(args, expected, expr),
343 ExprKind::ConstBlock(ref anon_const) => {
344 self.check_expr_const_block(anon_const, expected, expr)
346 ExprKind::Repeat(element, ref count) => {
347 self.check_expr_repeat(element, count, expected, expr)
349 ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr),
350 ExprKind::Struct(qpath, fields, ref base_expr) => {
351 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
353 ExprKind::Field(base, field) => self.check_field(expr, &base, field),
354 ExprKind::Index(base, idx) => self.check_expr_index(base, idx, expr),
355 ExprKind::Yield(value, ref src) => self.check_expr_yield(value, expr, src),
356 hir::ExprKind::Err => tcx.ty_error(),
360 fn check_expr_box(&self, expr: &'tcx hir::Expr<'tcx>, expected: Expectation<'tcx>) -> Ty<'tcx> {
361 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| match ty.kind() {
362 ty::Adt(def, _) if def.is_box() => Expectation::rvalue_hint(self, ty.boxed_ty()),
365 let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
366 self.require_type_is_sized(referent_ty, expr.span, traits::SizedBoxType);
367 self.tcx.mk_box(referent_ty)
373 oprnd: &'tcx hir::Expr<'tcx>,
374 expected: Expectation<'tcx>,
375 expr: &'tcx hir::Expr<'tcx>,
378 let expected_inner = match unop {
379 hir::UnOp::Not | hir::UnOp::Neg => expected,
380 hir::UnOp::Deref => NoExpectation,
382 let mut oprnd_t = self.check_expr_with_expectation(&oprnd, expected_inner);
384 if !oprnd_t.references_error() {
385 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
387 hir::UnOp::Deref => {
388 if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) {
391 let mut err = type_error_struct!(
396 "type `{oprnd_t}` cannot be dereferenced",
398 let sp = tcx.sess.source_map().start_point(expr.span);
400 tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
402 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
404 oprnd_t = tcx.ty_error_with_guaranteed(err.emit());
408 let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
409 // If it's builtin, we can reuse the type, this helps inference.
410 if !(oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool) {
415 let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
416 // If it's builtin, we can reuse the type, this helps inference.
417 if !oprnd_t.is_numeric() {
426 fn check_expr_addr_of(
428 kind: hir::BorrowKind,
429 mutbl: hir::Mutability,
430 oprnd: &'tcx hir::Expr<'tcx>,
431 expected: Expectation<'tcx>,
432 expr: &'tcx hir::Expr<'tcx>,
434 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
436 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
437 if oprnd.is_syntactic_place_expr() {
438 // Places may legitimately have unsized types.
439 // For example, dereferences of a fat pointer and
440 // the last field of a struct can be unsized.
443 Expectation::rvalue_hint(self, *ty)
450 self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl));
452 let tm = ty::TypeAndMut { ty, mutbl };
454 _ if tm.ty.references_error() => self.tcx.ty_error(),
455 hir::BorrowKind::Raw => {
456 self.check_named_place_expr(oprnd);
459 hir::BorrowKind::Ref => {
460 // Note: at this point, we cannot say what the best lifetime
461 // is to use for resulting pointer. We want to use the
462 // shortest lifetime possible so as to avoid spurious borrowck
463 // errors. Moreover, the longest lifetime will depend on the
464 // precise details of the value whose address is being taken
465 // (and how long it is valid), which we don't know yet until
466 // type inference is complete.
468 // Therefore, here we simply generate a region variable. The
469 // region inferencer will then select a suitable value.
470 // Finally, borrowck will infer the value of the region again,
471 // this time with enough precision to check that the value
472 // whose address was taken can actually be made to live as long
473 // as it needs to live.
474 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
475 self.tcx.mk_ref(region, tm)
480 /// Does this expression refer to a place that either:
481 /// * Is based on a local or static.
482 /// * Contains a dereference
483 /// Note that the adjustments for the children of `expr` should already
484 /// have been resolved.
485 fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
486 let is_named = oprnd.is_place_expr(|base| {
487 // Allow raw borrows if there are any deref adjustments.
489 // const VAL: (i32,) = (0,);
490 // const REF: &(i32,) = &(0,);
492 // &raw const VAL.0; // ERROR
493 // &raw const REF.0; // OK, same as &raw const (*REF).0;
495 // This is maybe too permissive, since it allows
496 // `let u = &raw const Box::new((1,)).0`, which creates an
497 // immediately dangling raw pointer.
502 .map_or(false, |x| x.iter().any(|adj| matches!(adj.kind, Adjust::Deref(_))))
505 self.tcx.sess.emit_err(AddressOfTemporaryTaken { span: oprnd.span });
509 fn check_lang_item_path(
511 lang_item: hir::LangItem,
512 expr: &'tcx hir::Expr<'tcx>,
513 hir_id: Option<hir::HirId>,
515 self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id, hir_id).1
518 pub(crate) fn check_expr_path(
520 qpath: &'tcx hir::QPath<'tcx>,
521 expr: &'tcx hir::Expr<'tcx>,
522 args: &'tcx [hir::Expr<'tcx>],
525 let (res, opt_ty, segs) =
526 self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span);
529 self.suggest_assoc_method_call(segs);
531 self.tcx.sess.delay_span_bug(qpath.span(), "`Res::Err` but no error emitted");
532 self.set_tainted_by_errors(e);
533 tcx.ty_error_with_guaranteed(e)
535 Res::Def(DefKind::Variant, _) => {
536 let e = report_unexpected_variant_res(tcx, res, qpath, expr.span, "E0533", "value");
537 tcx.ty_error_with_guaranteed(e)
539 _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
542 if let ty::FnDef(did, ..) = *ty.kind() {
543 let fn_sig = ty.fn_sig(tcx);
544 if tcx.fn_sig(did).abi() == RustIntrinsic && tcx.item_name(did) == sym::transmute {
545 let from = fn_sig.inputs().skip_binder()[0];
546 let to = fn_sig.output().skip_binder();
547 // We defer the transmute to the end of typeck, once all inference vars have
548 // been resolved or we errored. This is important as we can only check transmute
549 // on concrete types, but the output type may not be known yet (it would only
550 // be known if explicitly specified via turbofish).
551 self.deferred_transmute_checks.borrow_mut().push((from, to, expr.hir_id));
553 if !tcx.features().unsized_fn_params {
554 // We want to remove some Sized bounds from std functions,
555 // but don't want to expose the removal to stable Rust.
556 // i.e., we don't want to allow
562 // to work in stable even if the Sized bound on `drop` is relaxed.
563 for i in 0..fn_sig.inputs().skip_binder().len() {
564 // We just want to check sizedness, so instead of introducing
565 // placeholder lifetimes with probing, we just replace higher lifetimes
567 let span = args.get(i).map(|a| a.span).unwrap_or(expr.span);
568 let input = self.replace_bound_vars_with_fresh_vars(
570 infer::LateBoundRegionConversionTime::FnCall,
573 self.require_type_is_sized_deferred(
576 traits::SizedArgumentType(None),
580 // Here we want to prevent struct constructors from returning unsized types.
581 // There were two cases this happened: fn pointer coercion in stable
582 // and usual function call in presence of unsized_locals.
583 // Also, as we just want to check sizedness, instead of introducing
584 // placeholder lifetimes with probing, we just replace higher lifetimes
586 let output = self.replace_bound_vars_with_fresh_vars(
588 infer::LateBoundRegionConversionTime::FnCall,
591 self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
594 // We always require that the type provided as the value for
595 // a type parameter outlives the moment of instantiation.
596 let substs = self.typeck_results.borrow().node_substs(expr.hir_id);
597 self.add_wf_bounds(substs, expr);
604 destination: hir::Destination,
605 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
606 expr: &'tcx hir::Expr<'tcx>,
609 if let Ok(target_id) = destination.target_id {
611 if let Some(e) = expr_opt {
612 // If this is a break with a value, we need to type-check
613 // the expression. Get an expected type from the loop context.
614 let opt_coerce_to = {
615 // We should release `enclosing_breakables` before the `check_expr_with_hint`
616 // below, so can't move this block of code to the enclosing scope and share
617 // `ctxt` with the second `enclosing_breakables` borrow below.
618 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
619 match enclosing_breakables.opt_find_breakable(target_id) {
620 Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
622 // Avoid ICE when `break` is inside a closure (#65383).
623 return tcx.ty_error_with_message(
625 "break was outside loop, but no error was emitted",
631 // If the loop context is not a `loop { }`, then break with
632 // a value is illegal, and `opt_coerce_to` will be `None`.
633 // Just set expectation to error in that case.
634 let coerce_to = opt_coerce_to.unwrap_or_else(|| tcx.ty_error());
636 // Recurse without `enclosing_breakables` borrowed.
637 e_ty = self.check_expr_with_hint(e, coerce_to);
638 cause = self.misc(e.span);
640 // Otherwise, this is a break *without* a value. That's
641 // always legal, and is equivalent to `break ()`.
642 e_ty = tcx.mk_unit();
643 cause = self.misc(expr.span);
646 // Now that we have type-checked `expr_opt`, borrow
647 // the `enclosing_loops` field and let's coerce the
648 // type of `expr_opt` into what is expected.
649 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
650 let Some(ctxt) = enclosing_breakables.opt_find_breakable(target_id) else {
651 // Avoid ICE when `break` is inside a closure (#65383).
652 return tcx.ty_error_with_message(
654 "break was outside loop, but no error was emitted",
658 if let Some(ref mut coerce) = ctxt.coerce {
659 if let Some(ref e) = expr_opt {
660 coerce.coerce(self, &cause, e, e_ty);
662 assert!(e_ty.is_unit());
663 let ty = coerce.expected_ty();
664 coerce.coerce_forced_unit(
668 self.suggest_mismatched_types_on_tail(
669 &mut err, expr, ty, e_ty, target_id,
671 if let Some(val) = ty_kind_suggestion(ty) {
672 let label = destination
674 .map(|l| format!(" {}", l.ident))
675 .unwrap_or_else(String::new);
678 "give it a value of the expected type",
679 format!("break{label} {val}"),
680 Applicability::HasPlaceholders,
688 // If `ctxt.coerce` is `None`, we can just ignore
689 // the type of the expression. This is because
690 // either this was a break *without* a value, in
691 // which case it is always a legal type (`()`), or
692 // else an error would have been flagged by the
693 // `loops` pass for using break with an expression
694 // where you are not supposed to.
695 assert!(expr_opt.is_none() || self.tcx.sess.has_errors().is_some());
698 // If we encountered a `break`, then (no surprise) it may be possible to break from the
699 // loop... unless the value being returned from the loop diverges itself, e.g.
700 // `break return 5` or `break loop {}`.
701 ctxt.may_break |= !self.diverges.get().is_always();
703 // the type of a `break` is always `!`, since it diverges
706 // Otherwise, we failed to find the enclosing loop;
707 // this can only happen if the `break` was not
708 // inside a loop at all, which is caught by the
709 // loop-checking pass.
710 let err = self.tcx.ty_error_with_message(
712 "break was outside loop, but no error was emitted",
715 // We still need to assign a type to the inner expression to
716 // prevent the ICE in #43162.
717 if let Some(e) = expr_opt {
718 self.check_expr_with_hint(e, err);
720 // ... except when we try to 'break rust;'.
721 // ICE this expression in particular (see #43162).
722 if let ExprKind::Path(QPath::Resolved(_, path)) = e.kind {
723 if path.segments.len() == 1 && path.segments[0].ident.name == sym::rust {
724 fatally_break_rust(self.tcx.sess);
729 // There was an error; make type-check fail.
734 fn check_expr_return(
736 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
737 expr: &'tcx hir::Expr<'tcx>,
739 if self.ret_coercion.is_none() {
740 let mut err = ReturnStmtOutsideOfFnBody {
742 encl_body_span: None,
746 let encl_item_id = self.tcx.hir().get_parent_item(expr.hir_id);
748 if let Some(hir::Node::Item(hir::Item {
749 kind: hir::ItemKind::Fn(..),
753 | Some(hir::Node::TraitItem(hir::TraitItem {
754 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
758 | Some(hir::Node::ImplItem(hir::ImplItem {
759 kind: hir::ImplItemKind::Fn(..),
762 })) = self.tcx.hir().find_by_def_id(encl_item_id.def_id)
764 // We are inside a function body, so reporting "return statement
765 // outside of function body" needs an explanation.
767 let encl_body_owner_id = self.tcx.hir().enclosing_body_owner(expr.hir_id);
769 // If this didn't hold, we would not have to report an error in
771 assert_ne!(encl_item_id.def_id, encl_body_owner_id);
773 let encl_body_id = self.tcx.hir().body_owned_by(encl_body_owner_id);
774 let encl_body = self.tcx.hir().body(encl_body_id);
776 err.encl_body_span = Some(encl_body.value.span);
777 err.encl_fn_span = Some(*encl_fn_span);
780 self.tcx.sess.emit_err(err);
782 if let Some(e) = expr_opt {
783 // We still have to type-check `e` (issue #86188), but calling
784 // `check_return_expr` only works inside fn bodies.
787 } else if let Some(e) = expr_opt {
788 if self.ret_coercion_span.get().is_none() {
789 self.ret_coercion_span.set(Some(e.span));
791 self.check_return_expr(e, true);
793 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
794 if self.ret_coercion_span.get().is_none() {
795 self.ret_coercion_span.set(Some(expr.span));
797 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
798 if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
799 coercion.coerce_forced_unit(
803 let span = fn_decl.output.span();
804 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
807 format!("expected `{snippet}` because of this return type"),
814 coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
820 /// `explicit_return` is `true` if we're checking an explicit `return expr`,
821 /// and `false` if we're checking a trailing expression.
822 pub(super) fn check_return_expr(
824 return_expr: &'tcx hir::Expr<'tcx>,
825 explicit_return: bool,
827 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
828 span_bug!(return_expr.span, "check_return_expr called outside fn body")
831 let ret_ty = ret_coercion.borrow().expected_ty();
832 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
833 let mut span = return_expr.span;
834 // Use the span of the trailing expression for our cause,
835 // not the span of the entire function
836 if !explicit_return {
837 if let ExprKind::Block(body, _) = return_expr.kind && let Some(last_expr) = body.expr {
838 span = last_expr.span;
841 ret_coercion.borrow_mut().coerce(
843 &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
848 if let Some(fn_sig) = self.body_fn_sig()
849 && fn_sig.output().has_opaque_types()
851 // Point any obligations that were registered due to opaque type
852 // inference at the return expression.
853 self.select_obligations_where_possible(|errors| {
854 self.point_at_return_for_opaque_ty_error(errors, span, return_expr_ty);
859 fn point_at_return_for_opaque_ty_error(
861 errors: &mut Vec<traits::FulfillmentError<'tcx>>,
863 return_expr_ty: Ty<'tcx>,
865 // Don't point at the whole block if it's empty
866 if span == self.tcx.hir().span(self.body_id) {
870 let cause = &mut err.obligation.cause;
871 if let ObligationCauseCode::OpaqueReturnType(None) = cause.code() {
872 let new_cause = ObligationCause::new(
875 ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, span))),
882 pub(crate) fn check_lhs_assignable(
884 lhs: &'tcx hir::Expr<'tcx>,
885 err_code: &'static str,
887 adjust_err: impl FnOnce(&mut Diagnostic),
889 if lhs.is_syntactic_place_expr() {
893 // FIXME: Make this use Diagnostic once error codes can be dynamically set.
894 let mut err = self.tcx.sess.struct_span_err_with_code(
896 "invalid left-hand side of assignment",
897 DiagnosticId::Error(err_code.into()),
899 err.span_label(lhs.span, "cannot assign to this expression");
901 self.comes_from_while_condition(lhs.hir_id, |expr| {
902 err.span_suggestion_verbose(
903 expr.span.shrink_to_lo(),
904 "you might have meant to use pattern destructuring",
906 Applicability::MachineApplicable,
910 adjust_err(&mut err);
915 // Check if an expression `original_expr_id` comes from the condition of a while loop,
916 /// as opposed from the body of a while loop, which we can naively check by iterating
917 /// parents until we find a loop...
918 pub(super) fn comes_from_while_condition(
920 original_expr_id: HirId,
921 then: impl FnOnce(&hir::Expr<'_>),
923 let mut parent = self.tcx.hir().get_parent_node(original_expr_id);
924 while let Some(node) = self.tcx.hir().find(parent) {
926 hir::Node::Expr(hir::Expr {
933 hir::ExprKind::Match(expr, ..) | hir::ExprKind::If(expr, ..),
939 hir::LoopSource::While,
944 // Check if our original expression is a child of the condition of a while loop
945 let expr_is_ancestor = std::iter::successors(Some(original_expr_id), |id| {
946 self.tcx.hir().find_parent_node(*id)
948 .take_while(|id| *id != parent)
949 .any(|id| id == expr.hir_id);
950 // if it is, then we have a situation like `while Some(0) = value.get(0) {`,
951 // where `while let` was more likely intended.
952 if expr_is_ancestor {
958 | hir::Node::ImplItem(_)
959 | hir::Node::TraitItem(_)
960 | hir::Node::Crate(_) => break,
962 parent = self.tcx.hir().get_parent_node(parent);
968 // A generic function for checking the 'then' and 'else' clauses in an 'if'
969 // or 'if-else' expression.
972 cond_expr: &'tcx hir::Expr<'tcx>,
973 then_expr: &'tcx hir::Expr<'tcx>,
974 opt_else_expr: Option<&'tcx hir::Expr<'tcx>>,
976 orig_expected: Expectation<'tcx>,
978 let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {});
980 self.warn_if_unreachable(
983 "block in `if` or `while` expression",
986 let cond_diverges = self.diverges.get();
987 self.diverges.set(Diverges::Maybe);
989 let expected = orig_expected.adjust_for_branches(self);
990 let then_ty = self.check_expr_with_expectation(then_expr, expected);
991 let then_diverges = self.diverges.get();
992 self.diverges.set(Diverges::Maybe);
994 // We've already taken the expected type's preferences
995 // into account when typing the `then` branch. To figure
996 // out the initial shot at a LUB, we thus only consider
997 // `expected` if it represents a *hard* constraint
998 // (`only_has_type`); otherwise, we just go with a
999 // fresh type variable.
1000 let coerce_to_ty = expected.coercion_target_type(self, sp);
1001 let mut coerce: DynamicCoerceMany<'_> = CoerceMany::new(coerce_to_ty);
1003 coerce.coerce(self, &self.misc(sp), then_expr, then_ty);
1005 if let Some(else_expr) = opt_else_expr {
1006 let else_ty = self.check_expr_with_expectation(else_expr, expected);
1007 let else_diverges = self.diverges.get();
1009 let opt_suggest_box_span = self.opt_suggest_box_span(then_ty, else_ty, orig_expected);
1010 let if_cause = self.if_cause(
1017 opt_suggest_box_span,
1020 coerce.coerce(self, &if_cause, else_expr, else_ty);
1022 // We won't diverge unless both branches do (or the condition does).
1023 self.diverges.set(cond_diverges | then_diverges & else_diverges);
1025 self.if_fallback_coercion(sp, then_expr, &mut coerce);
1027 // If the condition is false we can't diverge.
1028 self.diverges.set(cond_diverges);
1031 let result_ty = coerce.complete(self);
1032 if cond_ty.references_error() { self.tcx.ty_error() } else { result_ty }
1035 /// Type check assignment expression `expr` of form `lhs = rhs`.
1036 /// The expected type is `()` and is passed to the function for the purposes of diagnostics.
1037 fn check_expr_assign(
1039 expr: &'tcx hir::Expr<'tcx>,
1040 expected: Expectation<'tcx>,
1041 lhs: &'tcx hir::Expr<'tcx>,
1042 rhs: &'tcx hir::Expr<'tcx>,
1045 let expected_ty = expected.coercion_target_type(self, expr.span);
1046 if expected_ty == self.tcx.types.bool {
1047 // The expected type is `bool` but this will result in `()` so we can reasonably
1048 // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
1049 // The likely cause of this is `if foo = bar { .. }`.
1050 let actual_ty = self.tcx.mk_unit();
1051 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
1052 let lhs_ty = self.check_expr(&lhs);
1053 let rhs_ty = self.check_expr(&rhs);
1054 let (applicability, eq) = if self.can_coerce(rhs_ty, lhs_ty) {
1055 (Applicability::MachineApplicable, true)
1056 } else if let ExprKind::Binary(
1057 Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1062 // if x == 1 && y == 2 { .. }
1064 let actual_lhs_ty = self.check_expr(&rhs_expr);
1065 (Applicability::MaybeIncorrect, self.can_coerce(rhs_ty, actual_lhs_ty))
1066 } else if let ExprKind::Binary(
1067 Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1072 // if x == 1 && y == 2 { .. }
1074 let actual_rhs_ty = self.check_expr(&lhs_expr);
1075 (Applicability::MaybeIncorrect, self.can_coerce(actual_rhs_ty, lhs_ty))
1077 (Applicability::MaybeIncorrect, false)
1079 if !lhs.is_syntactic_place_expr()
1080 && lhs.is_approximately_pattern()
1081 && !matches!(lhs.kind, hir::ExprKind::Lit(_))
1083 // Do not suggest `if let x = y` as `==` is way more likely to be the intention.
1084 let hir = self.tcx.hir();
1085 if let hir::Node::Expr(hir::Expr { kind: ExprKind::If { .. }, .. }) =
1086 hir.get(hir.get_parent_node(hir.get_parent_node(expr.hir_id)))
1088 err.span_suggestion_verbose(
1089 expr.span.shrink_to_lo(),
1090 "you might have meant to use pattern matching",
1097 err.span_suggestion_verbose(
1098 span.shrink_to_hi(),
1099 "you might have meant to compare for equality",
1105 // If the assignment expression itself is ill-formed, don't
1106 // bother emitting another error
1107 let reported = err.emit_unless(lhs_ty.references_error() || rhs_ty.references_error());
1108 return self.tcx.ty_error_with_guaranteed(reported);
1111 let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
1113 let suggest_deref_binop = |err: &mut Diagnostic, rhs_ty: Ty<'tcx>| {
1114 if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
1115 // Can only assign if the type is sized, so if `DerefMut` yields a type that is
1116 // unsized, do not suggest dereferencing it.
1117 let lhs_deref_ty_is_sized = self
1119 .type_implements_trait(
1120 self.tcx.require_lang_item(LangItem::Sized, None),
1125 if lhs_deref_ty_is_sized && self.can_coerce(rhs_ty, lhs_deref_ty) {
1126 err.span_suggestion_verbose(
1127 lhs.span.shrink_to_lo(),
1128 "consider dereferencing here to assign to the mutably borrowed value",
1130 Applicability::MachineApplicable,
1136 // This is (basically) inlined `check_expr_coercable_to_type`, but we want
1137 // to suggest an additional fixup here in `suggest_deref_binop`.
1138 let rhs_ty = self.check_expr_with_hint(&rhs, lhs_ty);
1139 if let (_, Some(mut diag)) =
1140 self.demand_coerce_diag(rhs, rhs_ty, lhs_ty, Some(lhs), AllowTwoPhase::No)
1142 suggest_deref_binop(&mut diag, rhs_ty);
1146 self.check_lhs_assignable(lhs, "E0070", span, |err| {
1147 if let Some(rhs_ty) = self.typeck_results.borrow().expr_ty_opt(rhs) {
1148 suggest_deref_binop(err, rhs_ty);
1152 self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
1154 if lhs_ty.references_error() || rhs_ty.references_error() {
1161 pub(super) fn check_expr_let(&self, let_expr: &'tcx hir::Let<'tcx>) -> Ty<'tcx> {
1162 // for let statements, this is done in check_stmt
1163 let init = let_expr.init;
1164 self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression");
1165 // otherwise check exactly as a let statement
1166 self.check_decl(let_expr.into());
1167 // but return a bool, for this is a boolean expression
1173 body: &'tcx hir::Block<'tcx>,
1174 source: hir::LoopSource,
1175 expected: Expectation<'tcx>,
1176 expr: &'tcx hir::Expr<'tcx>,
1178 let coerce = match source {
1179 // you can only use break with a value from a normal `loop { }`
1180 hir::LoopSource::Loop => {
1181 let coerce_to = expected.coercion_target_type(self, body.span);
1182 Some(CoerceMany::new(coerce_to))
1185 hir::LoopSource::While | hir::LoopSource::ForLoop => None,
1188 let ctxt = BreakableCtxt {
1190 may_break: false, // Will get updated if/when we find a `break`.
1193 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
1194 self.check_block_no_value(&body);
1198 // No way to know whether it's diverging because
1199 // of a `break` or an outer `break` or `return`.
1200 self.diverges.set(Diverges::Maybe);
1203 // If we permit break with a value, then result type is
1204 // the LUB of the breaks (possibly ! if none); else, it
1205 // is nil. This makes sense because infinite loops
1206 // (which would have type !) are only possible iff we
1207 // permit break with a value [1].
1208 if ctxt.coerce.is_none() && !ctxt.may_break {
1210 self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
1212 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
1215 /// Checks a method call.
1216 fn check_method_call(
1218 expr: &'tcx hir::Expr<'tcx>,
1219 segment: &hir::PathSegment<'_>,
1220 rcvr: &'tcx hir::Expr<'tcx>,
1221 args: &'tcx [hir::Expr<'tcx>],
1222 expected: Expectation<'tcx>,
1224 let rcvr_t = self.check_expr(&rcvr);
1225 // no need to check for bot/err -- callee does that
1226 let rcvr_t = self.structurally_resolved_type(rcvr.span, rcvr_t);
1227 let span = segment.ident.span;
1229 let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr, args) {
1231 // We could add a "consider `foo::<params>`" suggestion here, but I wasn't able to
1232 // trigger this codepath causing `structurally_resolved_type` to emit an error.
1234 self.write_method_call(expr.hir_id, method);
1238 if segment.ident.name != kw::Empty {
1239 if let Some(mut err) = self.report_method_error(
1243 SelfSource::MethodCall(rcvr),
1254 // Call the generic checker.
1255 self.check_method_argument_types(span, expr, method, &args, DontTupleArguments, expected)
1260 e: &'tcx hir::Expr<'tcx>,
1261 t: &'tcx hir::Ty<'tcx>,
1262 expr: &'tcx hir::Expr<'tcx>,
1264 // Find the type of `e`. Supply hints based on the type we are casting to,
1266 let t_cast = self.to_ty_saving_user_provided_ty(t);
1267 let t_cast = self.resolve_vars_if_possible(t_cast);
1268 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
1269 let t_expr = self.resolve_vars_if_possible(t_expr);
1271 // Eagerly check for some obvious errors.
1272 if t_expr.references_error() || t_cast.references_error() {
1275 // Defer other checks until we're done type checking.
1276 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
1277 match cast::CastCheck::new(
1284 self.param_env.constness(),
1288 "check_expr_cast: deferring cast from {:?} to {:?}: {:?}",
1289 t_cast, t_expr, cast_check,
1291 deferred_cast_checks.push(cast_check);
1294 Err(_) => self.tcx.ty_error(),
1299 fn check_expr_array(
1301 args: &'tcx [hir::Expr<'tcx>],
1302 expected: Expectation<'tcx>,
1303 expr: &'tcx hir::Expr<'tcx>,
1305 let element_ty = if !args.is_empty() {
1306 let coerce_to = expected
1308 .and_then(|uty| match *uty.kind() {
1309 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1312 .unwrap_or_else(|| {
1313 self.next_ty_var(TypeVariableOrigin {
1314 kind: TypeVariableOriginKind::TypeInference,
1318 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
1319 assert_eq!(self.diverges.get(), Diverges::Maybe);
1321 let e_ty = self.check_expr_with_hint(e, coerce_to);
1322 let cause = self.misc(e.span);
1323 coerce.coerce(self, &cause, e, e_ty);
1325 coerce.complete(self)
1327 self.next_ty_var(TypeVariableOrigin {
1328 kind: TypeVariableOriginKind::TypeInference,
1332 let array_len = args.len() as u64;
1333 self.suggest_array_len(expr, array_len);
1334 self.tcx.mk_array(element_ty, array_len)
1337 fn suggest_array_len(&self, expr: &'tcx hir::Expr<'tcx>, array_len: u64) {
1338 let parent_node = self.tcx.hir().parent_iter(expr.hir_id).find(|(_, node)| {
1339 !matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::AddrOf(..), .. }))
1342 hir::Node::Local(hir::Local { ty: Some(ty), .. })
1343 | hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, _), .. }))
1344 ) = parent_node else {
1347 if let hir::TyKind::Array(_, length) = ty.peel_refs().kind
1348 && let hir::ArrayLen::Body(hir::AnonConst { hir_id, .. }) = length
1349 && let Some(span) = self.tcx.hir().opt_span(hir_id)
1351 match self.tcx.sess.diagnostic().steal_diagnostic(span, StashKey::UnderscoreForArrayLengths) {
1353 err.span_suggestion(
1355 "consider specifying the array length",
1357 Applicability::MaybeIncorrect,
1366 fn check_expr_const_block(
1368 anon_const: &'tcx hir::AnonConst,
1369 expected: Expectation<'tcx>,
1370 _expr: &'tcx hir::Expr<'tcx>,
1372 let body = self.tcx.hir().body(anon_const.body);
1374 // Create a new function context.
1375 let fcx = FnCtxt::new(self, self.param_env.with_const(), body.value.hir_id);
1376 crate::GatherLocalsVisitor::new(&fcx).visit_body(body);
1378 let ty = fcx.check_expr_with_expectation(&body.value, expected);
1379 fcx.require_type_is_sized(ty, body.value.span, traits::ConstSized);
1380 fcx.write_ty(anon_const.hir_id, ty);
1384 fn check_expr_repeat(
1386 element: &'tcx hir::Expr<'tcx>,
1387 count: &'tcx hir::ArrayLen,
1388 expected: Expectation<'tcx>,
1389 expr: &'tcx hir::Expr<'tcx>,
1392 let count = self.array_length_to_const(count);
1393 if let Some(count) = count.try_eval_usize(tcx, self.param_env) {
1394 self.suggest_array_len(expr, count);
1397 let uty = match expected {
1398 ExpectHasType(uty) => match *uty.kind() {
1399 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1405 let (element_ty, t) = match uty {
1407 self.check_expr_coercable_to_type(&element, uty, None);
1411 let ty = self.next_ty_var(TypeVariableOrigin {
1412 kind: TypeVariableOriginKind::MiscVariable,
1415 let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
1420 if element_ty.references_error() {
1421 return tcx.ty_error();
1424 self.check_repeat_element_needs_copy_bound(element, count, element_ty);
1426 tcx.mk_ty(ty::Array(t, count))
1429 fn check_repeat_element_needs_copy_bound(
1431 element: &hir::Expr<'_>,
1432 count: ty::Const<'tcx>,
1433 element_ty: Ty<'tcx>,
1436 // Actual constants as the repeat element get inserted repeatedly instead of getting copied via Copy.
1437 match &element.kind {
1438 hir::ExprKind::ConstBlock(..) => return,
1439 hir::ExprKind::Path(qpath) => {
1440 let res = self.typeck_results.borrow().qpath_res(qpath, element.hir_id);
1441 if let Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::AnonConst, _) = res
1448 // If someone calls a const fn, they can extract that call out into a separate constant (or a const
1449 // block in the future), so we check that to tell them that in the diagnostic. Does not affect typeck.
1450 let is_const_fn = match element.kind {
1451 hir::ExprKind::Call(func, _args) => match *self.node_ty(func.hir_id).kind() {
1452 ty::FnDef(def_id, _) => tcx.is_const_fn(def_id),
1458 // If the length is 0, we don't create any elements, so we don't copy any. If the length is 1, we
1459 // don't copy that one element, we move it. Only check for Copy if the length is larger.
1460 if count.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1461 let lang_item = self.tcx.require_lang_item(LangItem::Copy, None);
1462 let code = traits::ObligationCauseCode::RepeatElementCopy { is_const_fn };
1463 self.require_type_meets(element_ty, element.span, code, lang_item);
1467 fn check_expr_tuple(
1469 elts: &'tcx [hir::Expr<'tcx>],
1470 expected: Expectation<'tcx>,
1471 expr: &'tcx hir::Expr<'tcx>,
1473 let flds = expected.only_has_type(self).and_then(|ty| {
1474 let ty = self.resolve_vars_with_obligations(ty);
1476 ty::Tuple(flds) => Some(&flds[..]),
1481 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds {
1482 Some(fs) if i < fs.len() => {
1484 self.check_expr_coercable_to_type(&e, ety, None);
1487 _ => self.check_expr_with_expectation(&e, NoExpectation),
1489 let tuple = self.tcx.mk_tup(elt_ts_iter);
1490 if tuple.references_error() {
1493 self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
1498 fn check_expr_struct(
1500 expr: &hir::Expr<'_>,
1501 expected: Expectation<'tcx>,
1503 fields: &'tcx [hir::ExprField<'tcx>],
1504 base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1506 // Find the relevant variant
1507 let Some((variant, adt_ty)) = self.check_struct_path(qpath, expr.hir_id) else {
1508 self.check_struct_fields_on_error(fields, base_expr);
1509 return self.tcx.ty_error();
1512 // Prohibit struct expressions when non-exhaustive flag is set.
1513 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1514 if !adt.did().is_local() && variant.is_field_list_non_exhaustive() {
1517 .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() });
1520 self.check_expr_struct_fields(
1531 self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
1535 fn check_expr_struct_fields(
1538 expected: Expectation<'tcx>,
1539 expr_id: hir::HirId,
1541 variant: &'tcx ty::VariantDef,
1542 ast_fields: &'tcx [hir::ExprField<'tcx>],
1543 base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1548 let expected_inputs =
1549 self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty]);
1550 let adt_ty_hint = if let Some(expected_inputs) = expected_inputs {
1551 expected_inputs.get(0).cloned().unwrap_or(adt_ty)
1555 // re-link the regions that EIfEO can erase.
1556 self.demand_eqtype(span, adt_ty_hint, adt_ty);
1558 let ty::Adt(adt, substs) = adt_ty.kind() else {
1559 span_bug!(span, "non-ADT passed to check_expr_struct_fields");
1561 let adt_kind = adt.adt_kind();
1563 let mut remaining_fields = variant
1567 .map(|(i, field)| (field.ident(tcx).normalize_to_macros_2_0(), (i, field)))
1568 .collect::<FxHashMap<_, _>>();
1570 let mut seen_fields = FxHashMap::default();
1572 let mut error_happened = false;
1574 // Type-check each field.
1575 for (idx, field) in ast_fields.iter().enumerate() {
1576 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1577 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1578 seen_fields.insert(ident, field.span);
1579 self.write_field_index(field.hir_id, i);
1581 // We don't look at stability attributes on
1582 // struct-like enums (yet...), but it's definitely not
1583 // a bug to have constructed one.
1584 if adt_kind != AdtKind::Enum {
1585 tcx.check_stability(v_field.did, Some(expr_id), field.span, None);
1588 self.field_ty(field.span, v_field, substs)
1590 error_happened = true;
1591 if let Some(prev_span) = seen_fields.get(&ident) {
1592 tcx.sess.emit_err(FieldMultiplySpecifiedInInitializer {
1593 span: field.ident.span,
1594 prev_span: *prev_span,
1598 self.report_unknown_field(
1603 adt.variant_descr(),
1611 // Make sure to give a type to the field even if there's
1612 // an error, so we can continue type-checking.
1613 let ty = self.check_expr_with_hint(&field.expr, field_type);
1615 self.demand_coerce_diag(&field.expr, ty, field_type, None, AllowTwoPhase::No);
1617 if let Some(mut diag) = diag {
1618 if idx == ast_fields.len() - 1 {
1619 if remaining_fields.is_empty() {
1620 self.suggest_fru_from_range(field, variant, substs, &mut diag);
1623 diag.stash(field.span, StashKey::MaybeFruTypo);
1631 // Make sure the programmer specified correct number of fields.
1632 if adt_kind == AdtKind::Union {
1633 if ast_fields.len() != 1 {
1638 "union expressions should have exactly one field",
1644 // If check_expr_struct_fields hit an error, do not attempt to populate
1645 // the fields with the base_expr. This could cause us to hit errors later
1646 // when certain fields are assumed to exist that in fact do not.
1648 if let Some(base_expr) = base_expr {
1649 self.check_expr(base_expr);
1654 if let Some(base_expr) = base_expr {
1655 // FIXME: We are currently creating two branches here in order to maintain
1656 // consistency. But they should be merged as much as possible.
1657 let fru_tys = if self.tcx.features().type_changing_struct_update {
1658 if adt.is_struct() {
1659 // Make some fresh substitutions for our ADT type.
1660 let fresh_substs = self.fresh_substs_for_item(base_expr.span, adt.did());
1661 // We do subtyping on the FRU fields first, so we can
1662 // learn exactly what types we expect the base expr
1663 // needs constrained to be compatible with the struct
1664 // type we expect from the expectation value.
1665 let fru_tys = variant
1669 let fru_ty = self.normalize(
1671 self.field_ty(base_expr.span, f, fresh_substs),
1673 let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
1674 if let Some(_) = remaining_fields.remove(&ident) {
1675 let target_ty = self.field_ty(base_expr.span, f, substs);
1676 let cause = self.misc(base_expr.span);
1677 match self.at(&cause, self.param_env).sup(target_ty, fru_ty) {
1678 Ok(InferOk { obligations, value: () }) => {
1679 self.register_predicates(obligations)
1682 // This should never happen, since we're just subtyping the
1683 // remaining_fields, but it's fine to emit this, I guess.
1685 .report_mismatched_types(
1689 FieldMisMatch(variant.name, ident.name),
1695 self.resolve_vars_if_possible(fru_ty)
1698 // The use of fresh substs that we have subtyped against
1699 // our base ADT type's fields allows us to guide inference
1700 // along so that, e.g.
1702 // MyStruct<'a, F1, F2, const C: usize> {
1704 // // Other fields that reference `'a`, `F2`, and `C`
1707 // let x = MyStruct {
1712 // will have the `other_struct` expression constrained to
1713 // `MyStruct<'a, _, F2, C>`, as opposed to just `_`...
1714 // This is important to allow coercions to happen in
1715 // `other_struct` itself. See `coerce-in-base-expr.rs`.
1716 let fresh_base_ty = self.tcx.mk_adt(*adt, fresh_substs);
1717 self.check_expr_has_type_or_error(
1719 self.resolve_vars_if_possible(fresh_base_ty),
1724 // Check the base_expr, regardless of a bad expected adt_ty, so we can get
1725 // type errors on that expression, too.
1726 self.check_expr(base_expr);
1729 .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
1733 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {
1734 let base_ty = self.typeck_results.borrow().expr_ty(*base_expr);
1735 let same_adt = match (adt_ty.kind(), base_ty.kind()) {
1736 (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt => true,
1739 if self.tcx.sess.is_nightly_build() && same_adt {
1741 &self.tcx.sess.parse_sess,
1742 sym::type_changing_struct_update,
1744 "type changing struct updating is experimental",
1749 match adt_ty.kind() {
1750 ty::Adt(adt, substs) if adt.is_struct() => variant
1753 .map(|f| self.normalize(expr_span, f.ty(self.tcx, substs)))
1758 .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
1763 self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr_id, fru_tys);
1764 } else if adt_kind != AdtKind::Union && !remaining_fields.is_empty() {
1765 debug!(?remaining_fields);
1766 let private_fields: Vec<&ty::FieldDef> = variant
1769 .filter(|field| !field.vis.is_accessible_from(tcx.parent_module(expr_id), tcx))
1772 if !private_fields.is_empty() {
1773 self.report_private_fields(adt_ty, span, private_fields, ast_fields);
1775 self.report_missing_fields(
1787 fn check_struct_fields_on_error(
1789 fields: &'tcx [hir::ExprField<'tcx>],
1790 base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
1792 for field in fields {
1793 self.check_expr(&field.expr);
1795 if let Some(base) = *base_expr {
1796 self.check_expr(&base);
1800 /// Report an error for a struct field expression when there are fields which aren't provided.
1803 /// error: missing field `you_can_use_this_field` in initializer of `foo::Foo`
1804 /// --> src/main.rs:8:5
1806 /// 8 | foo::Foo {};
1807 /// | ^^^^^^^^ missing `you_can_use_this_field`
1809 /// error: aborting due to previous error
1811 fn report_missing_fields(
1815 remaining_fields: FxHashMap<Ident, (usize, &ty::FieldDef)>,
1816 variant: &'tcx ty::VariantDef,
1817 ast_fields: &'tcx [hir::ExprField<'tcx>],
1818 substs: SubstsRef<'tcx>,
1820 let len = remaining_fields.len();
1822 let mut displayable_field_names: Vec<&str> =
1823 remaining_fields.keys().map(|ident| ident.as_str()).collect();
1824 // sorting &str primitives here, sort_unstable is ok
1825 displayable_field_names.sort_unstable();
1827 let mut truncated_fields_error = String::new();
1828 let remaining_fields_names = match &displayable_field_names[..] {
1829 [field1] => format!("`{}`", field1),
1830 [field1, field2] => format!("`{field1}` and `{field2}`"),
1831 [field1, field2, field3] => format!("`{field1}`, `{field2}` and `{field3}`"),
1833 truncated_fields_error =
1834 format!(" and {} other field{}", len - 3, pluralize!(len - 3));
1835 displayable_field_names
1838 .map(|n| format!("`{n}`"))
1839 .collect::<Vec<_>>()
1844 let mut err = struct_span_err!(
1848 "missing field{} {}{} in initializer of `{}`",
1850 remaining_fields_names,
1851 truncated_fields_error,
1854 err.span_label(span, format!("missing {remaining_fields_names}{truncated_fields_error}"));
1856 if let Some(last) = ast_fields.last() {
1857 self.suggest_fru_from_range(last, variant, substs, &mut err);
1863 /// If the last field is a range literal, but it isn't supposed to be, then they probably
1864 /// meant to use functional update syntax.
1865 fn suggest_fru_from_range(
1867 last_expr_field: &hir::ExprField<'tcx>,
1868 variant: &ty::VariantDef,
1869 substs: SubstsRef<'tcx>,
1870 err: &mut Diagnostic,
1872 // I don't use 'is_range_literal' because only double-sided, half-open ranges count.
1873 if let ExprKind::Struct(
1874 QPath::LangItem(LangItem::Range, ..),
1875 [range_start, range_end],
1877 ) = last_expr_field.expr.kind
1878 && let variant_field =
1879 variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident)
1880 && let range_def_id = self.tcx.lang_items().range_struct()
1882 .and_then(|field| field.ty(self.tcx, substs).ty_adt_def())
1883 .map(|adt| adt.did())
1886 // Suppress any range expr type mismatches
1887 if let Some(mut diag) = self
1891 .steal_diagnostic(last_expr_field.span, StashKey::MaybeFruTypo)
1893 diag.delay_as_bug();
1896 // Use a (somewhat arbitrary) filtering heuristic to avoid printing
1897 // expressions that are either too long, or have control character
1898 //such as newlines in them.
1903 .span_to_snippet(range_end.expr.span)
1905 .filter(|s| s.len() < 25 && !s.contains(|c: char| c.is_control()));
1911 .span_extend_while(range_start.span, |c| c.is_whitespace())
1912 .unwrap_or(range_start.span).shrink_to_hi().to(range_end.span);
1914 err.subdiagnostic(TypeMismatchFruTypo {
1915 expr_span: range_start.span,
1922 /// Report an error for a struct field expression when there are invisible fields.
1925 /// error: cannot construct `Foo` with struct literal syntax due to private fields
1926 /// --> src/main.rs:8:5
1928 /// 8 | foo::Foo {};
1931 /// error: aborting due to previous error
1933 fn report_private_fields(
1937 private_fields: Vec<&ty::FieldDef>,
1938 used_fields: &'tcx [hir::ExprField<'tcx>],
1940 let mut err = self.tcx.sess.struct_span_err(
1943 "cannot construct `{adt_ty}` with struct literal syntax due to private fields",
1946 let (used_private_fields, remaining_private_fields): (
1947 Vec<(Symbol, Span, bool)>,
1948 Vec<(Symbol, Span, bool)>,
1952 match used_fields.iter().find(|used_field| field.name == used_field.ident.name) {
1953 Some(used_field) => (field.name, used_field.span, true),
1954 None => (field.name, self.tcx.def_span(field.did), false),
1957 .partition(|field| field.2);
1958 err.span_labels(used_private_fields.iter().map(|(_, span, _)| *span), "private field");
1959 if !remaining_private_fields.is_empty() {
1960 let remaining_private_fields_len = remaining_private_fields.len();
1961 let names = match &remaining_private_fields
1963 .map(|(name, _, _)| name)
1964 .collect::<Vec<_>>()[..]
1966 _ if remaining_private_fields_len > 6 => String::new(),
1967 [name] => format!("`{name}` "),
1968 [names @ .., last] => {
1969 let names = names.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>();
1970 format!("{} and `{last}` ", names.join(", "))
1972 [] => unreachable!(),
1975 "... and other private field{s} {names}that {were} not provided",
1976 s = pluralize!(remaining_private_fields_len),
1977 were = pluralize!("was", remaining_private_fields_len),
1983 fn report_unknown_field(
1986 variant: &'tcx ty::VariantDef,
1987 field: &hir::ExprField<'_>,
1988 skip_fields: &[hir::ExprField<'_>],
1992 if variant.is_recovered() {
1993 self.set_tainted_by_errors(
1996 .delay_span_bug(expr_span, "parser recovered but no error was emitted"),
2000 let mut err = self.err_ctxt().type_error_struct_with_diag(
2002 |actual| match ty.kind() {
2003 ty::Adt(adt, ..) if adt.is_enum() => struct_span_err!(
2007 "{} `{}::{}` has no field named `{}`",
2013 _ => struct_span_err!(
2017 "{} `{}` has no field named `{}`",
2026 let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap();
2027 match variant.ctor_kind() {
2028 Some(CtorKind::Fn) => match ty.kind() {
2029 ty::Adt(adt, ..) if adt.is_enum() => {
2033 "`{adt}::{variant}` defined here",
2035 variant = variant.name,
2038 err.span_label(field.ident.span, "field does not exist");
2039 err.span_suggestion_verbose(
2042 "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax",
2044 variant = variant.name,
2047 "{adt}::{variant}(/* fields */)",
2049 variant = variant.name,
2051 Applicability::HasPlaceholders,
2055 err.span_label(variant_ident_span, format!("`{adt}` defined here", adt = ty));
2056 err.span_label(field.ident.span, "field does not exist");
2057 err.span_suggestion_verbose(
2060 "`{adt}` is a tuple {kind_name}, use the appropriate syntax",
2062 kind_name = kind_name,
2064 format!("{adt}(/* fields */)", adt = ty),
2065 Applicability::HasPlaceholders,
2070 // prevent all specified fields from being suggested
2071 let skip_fields = skip_fields.iter().map(|x| x.ident.name);
2072 if let Some(field_name) = self.suggest_field_name(
2075 skip_fields.collect(),
2078 err.span_suggestion(
2080 "a field with a similar name exists",
2082 Applicability::MaybeIncorrect,
2086 ty::Adt(adt, ..) => {
2090 format!("`{}::{}` does not have this field", ty, variant.name),
2095 format!("`{ty}` does not have this field"),
2098 let available_field_names =
2099 self.available_field_names(variant, expr_span);
2100 if !available_field_names.is_empty() {
2102 "available fields are: {}",
2103 self.name_series_display(available_field_names)
2107 _ => bug!("non-ADT passed to report_unknown_field"),
2115 // Return a hint about the closest match in field names
2116 fn suggest_field_name(
2118 variant: &'tcx ty::VariantDef,
2121 // The span where stability will be checked
2123 ) -> Option<Symbol> {
2127 .filter_map(|field| {
2128 // ignore already set fields and private fields from non-local crates
2129 // and unstable fields.
2130 if skip.iter().any(|&x| x == field.name)
2131 || (!variant.def_id.is_local() && !field.vis.is_public())
2133 self.tcx.eval_stability(field.did, None, span, None),
2134 stability::EvalResult::Deny { .. }
2142 .collect::<Vec<Symbol>>();
2144 find_best_match_for_name(&names, field, None)
2147 fn available_field_names(
2149 variant: &'tcx ty::VariantDef,
2156 let def_scope = self
2158 .adjust_ident_and_get_scope(field.ident(self.tcx), variant.def_id, self.body_id)
2160 field.vis.is_accessible_from(def_scope, self.tcx)
2162 self.tcx.eval_stability(field.did, None, access_span, None),
2163 stability::EvalResult::Deny { .. }
2166 .filter(|field| !self.tcx.is_doc_hidden(field.did))
2167 .map(|field| field.name)
2171 fn name_series_display(&self, names: Vec<Symbol>) -> String {
2172 // dynamic limit, to never omit just one field
2173 let limit = if names.len() == 6 { 6 } else { 5 };
2175 names.iter().take(limit).map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
2176 if names.len() > limit {
2177 display = format!("{} ... and {} others", display, names.len() - limit);
2182 // Check field access expressions
2185 expr: &'tcx hir::Expr<'tcx>,
2186 base: &'tcx hir::Expr<'tcx>,
2189 debug!("check_field(expr: {:?}, base: {:?}, field: {:?})", expr, base, field);
2190 let base_ty = self.check_expr(base);
2191 let base_ty = self.structurally_resolved_type(base.span, base_ty);
2192 let mut private_candidate = None;
2193 let mut autoderef = self.autoderef(expr.span, base_ty);
2194 while let Some((deref_base_ty, _)) = autoderef.next() {
2195 debug!("deref_base_ty: {:?}", deref_base_ty);
2196 match deref_base_ty.kind() {
2197 ty::Adt(base_def, substs) if !base_def.is_enum() => {
2198 debug!("struct named {:?}", deref_base_ty);
2199 let (ident, def_scope) =
2200 self.tcx.adjust_ident_and_get_scope(field, base_def.did(), self.body_id);
2201 let fields = &base_def.non_enum_variant().fields;
2202 if let Some(index) = fields
2204 .position(|f| f.ident(self.tcx).normalize_to_macros_2_0() == ident)
2206 let field = &fields[index];
2207 let field_ty = self.field_ty(expr.span, field, substs);
2208 // Save the index of all fields regardless of their visibility in case
2209 // of error recovery.
2210 self.write_field_index(expr.hir_id, index);
2211 let adjustments = self.adjust_steps(&autoderef);
2212 if field.vis.is_accessible_from(def_scope, self.tcx) {
2213 self.apply_adjustments(base, adjustments);
2214 self.register_predicates(autoderef.into_obligations());
2216 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
2219 private_candidate = Some((adjustments, base_def.did(), field_ty));
2223 let fstr = field.as_str();
2224 if let Ok(index) = fstr.parse::<usize>() {
2225 if fstr == index.to_string() {
2226 if let Some(&field_ty) = tys.get(index) {
2227 let adjustments = self.adjust_steps(&autoderef);
2228 self.apply_adjustments(base, adjustments);
2229 self.register_predicates(autoderef.into_obligations());
2231 self.write_field_index(expr.hir_id, index);
2240 self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false));
2242 if let Some((adjustments, did, field_ty)) = private_candidate {
2243 // (#90483) apply adjustments to avoid ExprUseVisitor from
2244 // creating erroneous projection.
2245 self.apply_adjustments(base, adjustments);
2246 self.ban_private_field_access(expr, base_ty, field, did);
2250 if field.name == kw::Empty {
2251 } else if self.method_exists(field, base_ty, expr.hir_id, true) {
2252 self.ban_take_value_of_method(expr, base_ty, field);
2253 } else if !base_ty.is_primitive_ty() {
2254 self.ban_nonexisting_field(field, base, expr, base_ty);
2256 let field_name = field.to_string();
2257 let mut err = type_error_struct!(
2262 "`{base_ty}` is a primitive type and therefore doesn't have fields",
2264 let is_valid_suffix = |field: &str| {
2265 if field == "f32" || field == "f64" {
2268 let mut chars = field.chars().peekable();
2269 match chars.peek() {
2270 Some('e') | Some('E') => {
2272 if let Some(c) = chars.peek()
2273 && !c.is_numeric() && *c != '-' && *c != '+'
2277 while let Some(c) = chars.peek() {
2278 if !c.is_numeric() {
2286 let suffix = chars.collect::<String>();
2287 suffix.is_empty() || suffix == "f32" || suffix == "f64"
2289 let maybe_partial_suffix = |field: &str| -> Option<&str> {
2290 let first_chars = ['f', 'l'];
2292 && field.to_lowercase().starts_with(first_chars)
2293 && field[1..].chars().all(|c| c.is_ascii_digit())
2295 if field.to_lowercase().starts_with(['f']) { Some("f32") } else { Some("f64") }
2300 if let ty::Infer(ty::IntVar(_)) = base_ty.kind()
2301 && let ExprKind::Lit(Spanned {
2302 node: ast::LitKind::Int(_, ast::LitIntType::Unsuffixed),
2305 && !base.span.from_expansion()
2307 if is_valid_suffix(&field_name) {
2308 err.span_suggestion_verbose(
2309 field.span.shrink_to_lo(),
2310 "if intended to be a floating point literal, consider adding a `0` after the period",
2312 Applicability::MaybeIncorrect,
2314 } else if let Some(correct_suffix) = maybe_partial_suffix(&field_name) {
2315 err.span_suggestion_verbose(
2317 format!("if intended to be a floating point literal, consider adding a `0` after the period and a `{correct_suffix}` suffix"),
2318 format!("0{correct_suffix}"),
2319 Applicability::MaybeIncorrect,
2326 self.tcx().ty_error()
2329 fn suggest_await_on_field_access(
2331 err: &mut Diagnostic,
2333 base: &'tcx hir::Expr<'tcx>,
2336 let Some(output_ty) = self.get_impl_future_output_ty(ty) else { return; };
2337 let mut add_label = true;
2338 if let ty::Adt(def, _) = output_ty.kind() {
2339 // no field access on enum type
2345 .any(|field| field.ident(self.tcx) == field_ident)
2350 "field not available in `impl Future`, but it is available in its `Output`",
2352 err.span_suggestion_verbose(
2353 base.span.shrink_to_hi(),
2354 "consider `await`ing on the `Future` and access the field of its `Output`",
2356 Applicability::MaybeIncorrect,
2362 err.span_label(field_ident.span, &format!("field not found in `{ty}`"));
2366 fn ban_nonexisting_field(
2369 base: &'tcx hir::Expr<'tcx>,
2370 expr: &'tcx hir::Expr<'tcx>,
2374 "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}",
2375 ident, base, expr, base_ty
2377 let mut err = self.no_such_field_err(ident, base_ty, base.hir_id);
2379 match *base_ty.peel_refs().kind() {
2380 ty::Array(_, len) => {
2381 self.maybe_suggest_array_indexing(&mut err, expr, base, ident, len);
2384 self.suggest_first_deref_field(&mut err, expr, base, ident);
2386 ty::Adt(def, _) if !def.is_enum() => {
2387 self.suggest_fields_on_recordish(&mut err, def, ident, expr.span);
2389 ty::Param(param_ty) => {
2390 self.point_at_param_definition(&mut err, param_ty);
2392 ty::Alias(ty::Opaque, _) => {
2393 self.suggest_await_on_field_access(&mut err, ident, base, base_ty.peel_refs());
2398 self.suggest_fn_call(&mut err, base, base_ty, |output_ty| {
2399 if let ty::Adt(def, _) = output_ty.kind() && !def.is_enum() {
2400 def.non_enum_variant().fields.iter().any(|field| {
2401 field.ident(self.tcx) == ident
2402 && field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
2404 } else if let ty::Tuple(tys) = output_ty.kind()
2405 && let Ok(idx) = ident.as_str().parse::<usize>()
2413 if ident.name == kw::Await {
2414 // We know by construction that `<expr>.await` is either on Rust 2015
2415 // or results in `ExprKind::Await`. Suggest switching the edition to 2018.
2416 err.note("to `.await` a `Future`, switch to Rust 2018 or later");
2417 err.help_use_latest_edition();
2423 fn ban_private_field_access(
2425 expr: &hir::Expr<'_>,
2430 let struct_path = self.tcx().def_path_str(base_did);
2431 let kind_name = self.tcx().def_kind(base_did).descr(base_did);
2432 let mut err = struct_span_err!(
2436 "field `{field}` of {kind_name} `{struct_path}` is private",
2438 err.span_label(field.span, "private field");
2439 // Also check if an accessible method exists, which is often what is meant.
2440 if self.method_exists(field, expr_t, expr.hir_id, false) && !self.expr_in_place(expr.hir_id)
2442 self.suggest_method_call(
2444 &format!("a method `{field}` also exists, call it with parentheses"),
2454 fn ban_take_value_of_method(&self, expr: &hir::Expr<'_>, expr_t: Ty<'tcx>, field: Ident) {
2455 let mut err = type_error_struct!(
2460 "attempted to take value of method `{field}` on type `{expr_t}`",
2462 err.span_label(field.span, "method, not a field");
2464 if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) =
2465 self.tcx.hir().get(self.tcx.hir().get_parent_node(expr.hir_id))
2467 expr.hir_id == callee.hir_id
2472 self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_default();
2473 let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')');
2474 let after_open = expr.span.lo() + rustc_span::BytePos(1);
2475 let before_close = expr.span.hi() - rustc_span::BytePos(1);
2477 if expr_is_call && is_wrapped {
2478 err.multipart_suggestion(
2479 "remove wrapping parentheses to call the method",
2481 (expr.span.with_hi(after_open), String::new()),
2482 (expr.span.with_lo(before_close), String::new()),
2484 Applicability::MachineApplicable,
2486 } else if !self.expr_in_place(expr.hir_id) {
2487 // Suggest call parentheses inside the wrapping parentheses
2488 let span = if is_wrapped {
2489 expr.span.with_lo(after_open).with_hi(before_close)
2493 self.suggest_method_call(
2495 "use parentheses to call the method",
2501 } else if let ty::RawPtr(ty_and_mut) = expr_t.kind()
2502 && let ty::Adt(adt_def, _) = ty_and_mut.ty.kind()
2503 && let ExprKind::Field(base_expr, _) = expr.kind
2504 && adt_def.variants().len() == 1
2512 .any(|f| f.ident(self.tcx) == field)
2514 err.multipart_suggestion(
2515 "to access the field, dereference first",
2517 (base_expr.span.shrink_to_lo(), "(*".to_string()),
2518 (base_expr.span.shrink_to_hi(), ")".to_string()),
2520 Applicability::MaybeIncorrect,
2523 err.help("methods are immutable and cannot be assigned to");
2529 fn point_at_param_definition(&self, err: &mut Diagnostic, param: ty::ParamTy) {
2530 let generics = self.tcx.generics_of(self.body_id.owner.to_def_id());
2531 let generic_param = generics.type_param(¶m, self.tcx);
2532 if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
2535 let param_def_id = generic_param.def_id;
2536 let param_hir_id = match param_def_id.as_local() {
2537 Some(x) => self.tcx.hir().local_def_id_to_hir_id(x),
2540 let param_span = self.tcx.hir().span(param_hir_id);
2541 let param_name = self.tcx.hir().ty_param_name(param_def_id.expect_local());
2543 err.span_label(param_span, &format!("type parameter '{param_name}' declared here"));
2546 fn suggest_fields_on_recordish(
2548 err: &mut Diagnostic,
2549 def: ty::AdtDef<'tcx>,
2553 if let Some(suggested_field_name) =
2554 self.suggest_field_name(def.non_enum_variant(), field.name, vec![], access_span)
2556 err.span_suggestion(
2558 "a field with a similar name exists",
2559 suggested_field_name,
2560 Applicability::MaybeIncorrect,
2563 err.span_label(field.span, "unknown field");
2564 let struct_variant_def = def.non_enum_variant();
2565 let field_names = self.available_field_names(struct_variant_def, access_span);
2566 if !field_names.is_empty() {
2568 "available fields are: {}",
2569 self.name_series_display(field_names),
2575 fn maybe_suggest_array_indexing(
2577 err: &mut Diagnostic,
2578 expr: &hir::Expr<'_>,
2579 base: &hir::Expr<'_>,
2581 len: ty::Const<'tcx>,
2583 if let (Some(len), Ok(user_index)) =
2584 (len.try_eval_usize(self.tcx, self.param_env), field.as_str().parse::<u64>())
2585 && let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span)
2587 let help = "instead of using tuple indexing, use array indexing";
2588 let suggestion = format!("{base}[{field}]");
2589 let applicability = if len < user_index {
2590 Applicability::MachineApplicable
2592 Applicability::MaybeIncorrect
2594 err.span_suggestion(expr.span, help, suggestion, applicability);
2598 fn suggest_first_deref_field(
2600 err: &mut Diagnostic,
2601 expr: &hir::Expr<'_>,
2602 base: &hir::Expr<'_>,
2605 if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) {
2606 let msg = format!("`{base}` is a raw pointer; try dereferencing it");
2607 let suggestion = format!("(*{base}).{field}");
2608 err.span_suggestion(expr.span, &msg, suggestion, Applicability::MaybeIncorrect);
2612 fn no_such_field_err(
2617 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
2618 let span = field.span;
2619 debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, expr_t);
2621 let mut err = type_error_struct!(
2626 "no field `{field}` on type `{expr_t}`",
2629 // try to add a suggestion in case the field is a nested field of a field of the Adt
2630 let mod_id = self.tcx.parent_module(id).to_def_id();
2631 if let Some((fields, substs)) =
2632 self.get_field_candidates_considering_privacy(span, expr_t, mod_id)
2634 let candidate_fields: Vec<_> = fields
2635 .filter_map(|candidate_field| {
2636 self.check_for_nested_field_satisfying(
2638 &|candidate_field, _| candidate_field.ident(self.tcx()) == field,
2645 .map(|mut field_path| {
2649 .map(|id| id.name.to_ident_string())
2650 .collect::<Vec<String>>()
2653 .collect::<Vec<_>>();
2655 let len = candidate_fields.len();
2657 err.span_suggestions(
2658 field.span.shrink_to_lo(),
2660 "{} of the expressions' fields {} a field of the same name",
2661 if len > 1 { "some" } else { "one" },
2662 if len > 1 { "have" } else { "has" },
2664 candidate_fields.iter().map(|path| format!("{path}.")),
2665 Applicability::MaybeIncorrect,
2672 pub(crate) fn get_field_candidates_considering_privacy(
2677 ) -> Option<(impl Iterator<Item = &'tcx ty::FieldDef> + 'tcx, SubstsRef<'tcx>)> {
2678 debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_ty);
2680 for (base_t, _) in self.autoderef(span, base_ty) {
2681 match base_t.kind() {
2682 ty::Adt(base_def, substs) if !base_def.is_enum() => {
2684 let fields = &base_def.non_enum_variant().fields;
2685 // Some struct, e.g. some that impl `Deref`, have all private fields
2686 // because you're expected to deref them to access the _real_ fields.
2687 // This, for example, will help us suggest accessing a field through a `Box<T>`.
2688 if fields.iter().all(|field| !field.vis.is_accessible_from(mod_id, tcx)) {
2694 .filter(move |field| field.vis.is_accessible_from(mod_id, tcx))
2695 // For compile-time reasons put a limit on number of fields we search
2706 /// This method is called after we have encountered a missing field error to recursively
2707 /// search for the field
2708 pub(crate) fn check_for_nested_field_satisfying(
2711 matches: &impl Fn(&ty::FieldDef, Ty<'tcx>) -> bool,
2712 candidate_field: &ty::FieldDef,
2713 subst: SubstsRef<'tcx>,
2714 mut field_path: Vec<Ident>,
2716 ) -> Option<Vec<Ident>> {
2718 "check_for_nested_field_satisfying(span: {:?}, candidate_field: {:?}, field_path: {:?}",
2719 span, candidate_field, field_path
2722 if field_path.len() > 3 {
2723 // For compile-time reasons and to avoid infinite recursion we only check for fields
2724 // up to a depth of three
2727 field_path.push(candidate_field.ident(self.tcx).normalize_to_macros_2_0());
2728 let field_ty = candidate_field.ty(self.tcx, subst);
2729 if matches(candidate_field, field_ty) {
2730 return Some(field_path);
2731 } else if let Some((nested_fields, subst)) =
2732 self.get_field_candidates_considering_privacy(span, field_ty, mod_id)
2734 // recursively search fields of `candidate_field` if it's a ty::Adt
2735 for field in nested_fields {
2736 if let Some(field_path) = self.check_for_nested_field_satisfying(
2744 return Some(field_path);
2752 fn check_expr_index(
2754 base: &'tcx hir::Expr<'tcx>,
2755 idx: &'tcx hir::Expr<'tcx>,
2756 expr: &'tcx hir::Expr<'tcx>,
2758 let base_t = self.check_expr(&base);
2759 let idx_t = self.check_expr(&idx);
2761 if base_t.references_error() {
2763 } else if idx_t.references_error() {
2766 let base_t = self.structurally_resolved_type(base.span, base_t);
2767 match self.lookup_indexing(expr, base, base_t, idx, idx_t) {
2768 Some((index_ty, element_ty)) => {
2769 // two-phase not needed because index_ty is never mutable
2770 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
2771 self.select_obligations_where_possible(|errors| {
2772 self.point_at_index_if_possible(errors, idx.span)
2777 let mut err = type_error_struct!(
2782 "cannot index into a value of type `{base_t}`",
2784 // Try to give some advice about indexing tuples.
2785 if let ty::Tuple(..) = base_t.kind() {
2786 let mut needs_note = true;
2787 // If the index is an integer, we can show the actual
2788 // fixed expression:
2789 if let ExprKind::Lit(ref lit) = idx.kind {
2790 if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
2791 let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
2792 if let Ok(snip) = snip {
2793 err.span_suggestion(
2795 "to access tuple elements, use",
2796 format!("{snip}.{i}"),
2797 Applicability::MachineApplicable,
2805 "to access tuple elements, use tuple indexing \
2806 syntax (e.g., `tuple.0`)",
2810 let reported = err.emit();
2811 self.tcx.ty_error_with_guaranteed(reported)
2817 fn point_at_index_if_possible(
2819 errors: &mut Vec<traits::FulfillmentError<'tcx>>,
2822 for error in errors {
2823 match error.obligation.predicate.kind().skip_binder() {
2824 ty::PredicateKind::Clause(ty::Clause::Trait(predicate))
2825 if self.tcx.is_diagnostic_item(sym::SliceIndex, predicate.trait_ref.def_id) => {
2829 error.obligation.cause.span = span;
2833 fn check_expr_yield(
2835 value: &'tcx hir::Expr<'tcx>,
2836 expr: &'tcx hir::Expr<'tcx>,
2837 src: &'tcx hir::YieldSource,
2839 match self.resume_yield_tys {
2840 Some((resume_ty, yield_ty)) => {
2841 self.check_expr_coercable_to_type(&value, yield_ty, None);
2845 // Given that this `yield` expression was generated as a result of lowering a `.await`,
2846 // we know that the yield type must be `()`; however, the context won't contain this
2847 // information. Hence, we check the source of the yield expression here and check its
2848 // value's type against `()` (this check should always hold).
2849 None if src.is_await() => {
2850 self.check_expr_coercable_to_type(&value, self.tcx.mk_unit(), None);
2854 self.tcx.sess.emit_err(YieldExprOutsideOfGenerator { span: expr.span });
2855 // Avoid expressions without types during writeback (#78653).
2856 self.check_expr(value);
2862 fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
2863 let needs = if is_input { Needs::None } else { Needs::MutPlace };
2864 let ty = self.check_expr_with_needs(expr, needs);
2865 self.require_type_is_sized(ty, expr.span, traits::InlineAsmSized);
2867 if !is_input && !expr.is_syntactic_place_expr() {
2868 let mut err = self.tcx.sess.struct_span_err(expr.span, "invalid asm output");
2869 err.span_label(expr.span, "cannot assign to this expression");
2873 // If this is an input value, we require its type to be fully resolved
2874 // at this point. This allows us to provide helpful coercions which help
2875 // pass the type candidate list in a later pass.
2877 // We don't require output types to be resolved at this point, which
2878 // allows them to be inferred based on how they are used later in the
2881 let ty = self.structurally_resolved_type(expr.span, ty);
2884 let fnptr_ty = self.tcx.mk_fn_ptr(ty.fn_sig(self.tcx));
2885 self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
2887 ty::Ref(_, base_ty, mutbl) => {
2888 let ptr_ty = self.tcx.mk_ptr(ty::TypeAndMut { ty: base_ty, mutbl });
2889 self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
2896 fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>) -> Ty<'tcx> {
2897 for (op, _op_sp) in asm.operands {
2899 hir::InlineAsmOperand::In { expr, .. } => {
2900 self.check_expr_asm_operand(expr, true);
2902 hir::InlineAsmOperand::Out { expr: Some(expr), .. }
2903 | hir::InlineAsmOperand::InOut { expr, .. } => {
2904 self.check_expr_asm_operand(expr, false);
2906 hir::InlineAsmOperand::Out { expr: None, .. } => {}
2907 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
2908 self.check_expr_asm_operand(in_expr, true);
2909 if let Some(out_expr) = out_expr {
2910 self.check_expr_asm_operand(out_expr, false);
2913 // `AnonConst`s have their own body and is type-checked separately.
2914 // As they don't flow into the type system we don't need them to
2916 hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::SymFn { .. } => {}
2917 hir::InlineAsmOperand::SymStatic { .. } => {}
2920 if asm.options.contains(ast::InlineAsmOptions::NORETURN) {
2921 self.tcx.types.never