1use rustc_abi::{FIRST_VARIANT, FieldIdx};
9use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10use rustc_data_structures::stack::ensure_sufficient_stack;
11use rustc_data_structures::unord::UnordMap;
12use rustc_errors::codes::*;
13use rustc_errors::{
14 Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, Subdiagnostic, listify, pluralize,
15 struct_span_code_err,
16};
17use rustc_hir::def::{CtorKind, DefKind, Res};
18use rustc_hir::def_id::DefId;
19use rustc_hir::lang_items::LangItem;
20use rustc_hir::{ExprKind, HirId, QPath};
21use rustc_hir_analysis::NoVariantNamed;
22use rustc_hir_analysis::hir_ty_lowering::{FeedConstTy, HirTyLowerer as _};
23use rustc_infer::infer;
24use rustc_infer::infer::{DefineOpaqueTypes, InferOk};
25use rustc_infer::traits::query::NoSolution;
26use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
27use rustc_middle::ty::error::{ExpectedFound, TypeError};
28use rustc_middle::ty::{self, AdtKind, GenericArgsRef, Ty, TypeVisitableExt};
29use rustc_middle::{bug, span_bug};
30use rustc_session::errors::ExprParenthesesNeeded;
31use rustc_session::parse::feature_err;
32use rustc_span::edit_distance::find_best_match_for_name;
33use rustc_span::hygiene::DesugaringKind;
34use rustc_span::source_map::Spanned;
35use rustc_span::{Ident, Span, Symbol, kw, sym};
36use rustc_trait_selection::infer::InferCtxtExt;
37use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt};
38use tracing::{debug, instrument, trace};
39use {rustc_ast as ast, rustc_hir as hir};
40
41use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation};
42use crate::coercion::{CoerceMany, DynamicCoerceMany};
43use crate::errors::{
44 AddressOfTemporaryTaken, BaseExpressionDoubleDot, BaseExpressionDoubleDotAddExpr,
45 BaseExpressionDoubleDotEnableDefaultFieldValues, BaseExpressionDoubleDotRemove,
46 CantDereference, FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct,
47 HelpUseLatestEdition, NoFieldOnType, NoFieldOnVariant, ReturnLikeStatementKind,
48 ReturnStmtOutsideOfFnBody, StructExprNonExhaustive, TypeMismatchFruTypo,
49 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 check_expr_has_type_or_error(
61 &self,
62 expr: &'tcx hir::Expr<'tcx>,
63 expected_ty: Ty<'tcx>,
64 extend_err: impl FnOnce(&mut Diag<'_>),
65 ) -> Ty<'tcx> {
66 let mut ty = self.check_expr_with_expectation(expr, ExpectHasType(expected_ty));
67
68 if self.try_structurally_resolve_type(expr.span, ty).is_never()
71 && self.expr_guaranteed_to_constitute_read_for_never(expr)
72 {
73 if let Some(adjustments) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
74 let reported = self.dcx().span_delayed_bug(
75 expr.span,
76 "expression with never type wound up being adjusted",
77 );
78
79 return if let [Adjustment { kind: Adjust::NeverToAny, target }] = &adjustments[..] {
80 target.to_owned()
81 } else {
82 Ty::new_error(self.tcx(), reported)
83 };
84 }
85
86 let adj_ty = self.next_ty_var(expr.span);
87 self.apply_adjustments(
88 expr,
89 vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }],
90 );
91 ty = adj_ty;
92 }
93
94 if let Err(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
95 let _ = self.emit_type_mismatch_suggestions(
96 &mut err,
97 expr.peel_drop_temps(),
98 ty,
99 expected_ty,
100 None,
101 None,
102 );
103 extend_err(&mut err);
104 err.emit();
105 }
106 ty
107 }
108
109 pub(super) fn check_expr_coercible_to_type(
113 &self,
114 expr: &'tcx hir::Expr<'tcx>,
115 expected: Ty<'tcx>,
116 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
117 ) -> Ty<'tcx> {
118 self.check_expr_coercible_to_type_or_error(expr, expected, expected_ty_expr, |_, _| {})
119 }
120
121 pub(crate) fn check_expr_coercible_to_type_or_error(
122 &self,
123 expr: &'tcx hir::Expr<'tcx>,
124 expected: Ty<'tcx>,
125 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
126 extend_err: impl FnOnce(&mut Diag<'_>, Ty<'tcx>),
127 ) -> Ty<'tcx> {
128 let ty = self.check_expr_with_hint(expr, expected);
129 match self.demand_coerce_diag(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No) {
131 Ok(ty) => ty,
132 Err(mut err) => {
133 extend_err(&mut err, ty);
134 err.emit();
135 expected
139 }
140 }
141 }
142
143 pub(super) fn check_expr_with_hint(
148 &self,
149 expr: &'tcx hir::Expr<'tcx>,
150 expected: Ty<'tcx>,
151 ) -> Ty<'tcx> {
152 self.check_expr_with_expectation(expr, ExpectHasType(expected))
153 }
154
155 fn check_expr_with_expectation_and_needs(
158 &self,
159 expr: &'tcx hir::Expr<'tcx>,
160 expected: Expectation<'tcx>,
161 needs: Needs,
162 ) -> Ty<'tcx> {
163 let ty = self.check_expr_with_expectation(expr, expected);
164
165 if let Needs::MutPlace = needs {
168 self.convert_place_derefs_to_mutable(expr);
169 }
170
171 ty
172 }
173
174 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
176 self.check_expr_with_expectation(expr, NoExpectation)
177 }
178
179 pub(super) fn check_expr_with_needs(
182 &self,
183 expr: &'tcx hir::Expr<'tcx>,
184 needs: Needs,
185 ) -> Ty<'tcx> {
186 self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
187 }
188
189 #[instrument(skip(self, expr), level = "debug")]
192 pub(super) fn check_expr_with_expectation(
193 &self,
194 expr: &'tcx hir::Expr<'tcx>,
195 expected: Expectation<'tcx>,
196 ) -> Ty<'tcx> {
197 self.check_expr_with_expectation_and_args(expr, expected, None)
198 }
199
200 pub(super) fn check_expr_with_expectation_and_args(
205 &self,
206 expr: &'tcx hir::Expr<'tcx>,
207 expected: Expectation<'tcx>,
208 call_expr_and_args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
209 ) -> Ty<'tcx> {
210 if self.tcx().sess.verbose_internals() {
211 if let Ok(lint_str) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
213 if !lint_str.contains('\n') {
214 debug!("expr text: {lint_str}");
215 } else {
216 let mut lines = lint_str.lines();
217 if let Some(line0) = lines.next() {
218 let remaining_lines = lines.count();
219 debug!("expr text: {line0}");
220 debug!("expr text: ...(and {remaining_lines} more lines)");
221 }
222 }
223 }
224 }
225
226 let is_try_block_generated_unit_expr = match expr.kind {
230 ExprKind::Call(_, [arg]) => {
231 expr.span.is_desugaring(DesugaringKind::TryBlock)
232 && arg.span.is_desugaring(DesugaringKind::TryBlock)
233 }
234 _ => false,
235 };
236
237 if !is_try_block_generated_unit_expr {
239 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
240 }
241
242 let old_diverges = self.diverges.replace(Diverges::Maybe);
245
246 if self.is_whole_body.replace(false) {
247 self.diverges.set(self.function_diverges_because_of_empty_arguments.get())
250 };
251
252 let ty = ensure_sufficient_stack(|| match &expr.kind {
253 hir::ExprKind::Path(
255 qpath @ (hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)),
256 ) => self.check_expr_path(qpath, expr, call_expr_and_args),
257 _ => self.check_expr_kind(expr, expected),
258 });
259 let ty = self.resolve_vars_if_possible(ty);
260
261 match expr.kind {
263 ExprKind::Block(..)
264 | ExprKind::If(..)
265 | ExprKind::Let(..)
266 | ExprKind::Loop(..)
267 | ExprKind::Match(..) => {}
268 ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {}
272 ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::Contract) => {}
274 ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"),
275 ExprKind::MethodCall(segment, ..) => {
276 self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call")
277 }
278 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
279 }
280
281 if self.try_structurally_resolve_type(expr.span, ty).is_never()
286 && self.expr_guaranteed_to_constitute_read_for_never(expr)
287 {
288 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
289 }
290
291 self.write_ty(expr.hir_id, ty);
295
296 self.diverges.set(self.diverges.get() | old_diverges);
298
299 debug!("type of {} is...", self.tcx.hir_id_to_string(expr.hir_id));
300 debug!("... {:?}, expected is {:?}", ty, expected);
301
302 ty
303 }
304
305 pub(super) fn expr_guaranteed_to_constitute_read_for_never(
317 &self,
318 expr: &'tcx hir::Expr<'tcx>,
319 ) -> bool {
320 if !expr.is_syntactic_place_expr() {
326 return true;
327 }
328
329 let parent_node = self.tcx.parent_hir_node(expr.hir_id);
330 match parent_node {
331 hir::Node::Expr(parent_expr) => {
332 match parent_expr.kind {
333 ExprKind::AddrOf(..) | hir::ExprKind::Field(..) => false,
337
338 ExprKind::Type(..) | ExprKind::UnsafeBinderCast(..) => {
341 self.expr_guaranteed_to_constitute_read_for_never(expr)
342 }
343
344 ExprKind::Assign(lhs, _, _) => {
345 expr.hir_id != lhs.hir_id
347 }
348
349 ExprKind::Match(scrutinee, arms, _) => {
351 assert_eq!(scrutinee.hir_id, expr.hir_id);
352 arms.iter()
353 .all(|arm| self.pat_guaranteed_to_constitute_read_for_never(arm.pat))
354 }
355 ExprKind::Let(hir::LetExpr { init, pat, .. }) => {
356 assert_eq!(init.hir_id, expr.hir_id);
357 self.pat_guaranteed_to_constitute_read_for_never(*pat)
358 }
359
360 ExprKind::Array(_)
362 | ExprKind::Call(_, _)
363 | ExprKind::Use(_, _)
364 | ExprKind::MethodCall(_, _, _, _)
365 | ExprKind::Tup(_)
366 | ExprKind::Binary(_, _, _)
367 | ExprKind::Unary(_, _)
368 | ExprKind::Cast(_, _)
369 | ExprKind::DropTemps(_)
370 | ExprKind::If(_, _, _)
371 | ExprKind::Closure(_)
372 | ExprKind::Block(_, _)
373 | ExprKind::AssignOp(_, _, _)
374 | ExprKind::Index(_, _, _)
375 | ExprKind::Break(_, _)
376 | ExprKind::Ret(_)
377 | ExprKind::Become(_)
378 | ExprKind::InlineAsm(_)
379 | ExprKind::Struct(_, _, _)
380 | ExprKind::Repeat(_, _)
381 | ExprKind::Yield(_, _) => true,
382
383 ExprKind::ConstBlock(_)
385 | ExprKind::Loop(_, _, _, _)
386 | ExprKind::Lit(_)
387 | ExprKind::Path(_)
388 | ExprKind::Continue(_)
389 | ExprKind::OffsetOf(_, _)
390 | ExprKind::Err(_) => unreachable!("no sub-expr expected for {:?}", expr.kind),
391 }
392 }
393
394 hir::Node::LetStmt(hir::LetStmt { init: Some(target), pat, .. }) => {
397 assert_eq!(target.hir_id, expr.hir_id);
398 self.pat_guaranteed_to_constitute_read_for_never(*pat)
399 }
400
401 hir::Node::Block(_)
403 | hir::Node::Arm(_)
404 | hir::Node::ExprField(_)
405 | hir::Node::AnonConst(_)
406 | hir::Node::ConstBlock(_)
407 | hir::Node::ConstArg(_)
408 | hir::Node::Stmt(_)
409 | hir::Node::Item(hir::Item {
410 kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..),
411 ..
412 })
413 | hir::Node::TraitItem(hir::TraitItem {
414 kind: hir::TraitItemKind::Const(..), ..
415 })
416 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. }) => true,
417
418 hir::Node::TyPat(_) | hir::Node::Pat(_) => {
419 self.dcx().span_delayed_bug(expr.span, "place expr not allowed in pattern");
420 true
421 }
422
423 hir::Node::Param(_)
425 | hir::Node::Item(_)
426 | hir::Node::ForeignItem(_)
427 | hir::Node::TraitItem(_)
428 | hir::Node::ImplItem(_)
429 | hir::Node::Variant(_)
430 | hir::Node::Field(_)
431 | hir::Node::PathSegment(_)
432 | hir::Node::Ty(_)
433 | hir::Node::AssocItemConstraint(_)
434 | hir::Node::TraitRef(_)
435 | hir::Node::PatField(_)
436 | hir::Node::PatExpr(_)
437 | hir::Node::LetStmt(_)
438 | hir::Node::Synthetic
439 | hir::Node::Err(_)
440 | hir::Node::Ctor(_)
441 | hir::Node::Lifetime(_)
442 | hir::Node::GenericParam(_)
443 | hir::Node::Crate(_)
444 | hir::Node::Infer(_)
445 | hir::Node::WherePredicate(_)
446 | hir::Node::PreciseCapturingNonLifetimeArg(_)
447 | hir::Node::OpaqueTy(_) => {
448 unreachable!("no sub-expr expected for {parent_node:?}")
449 }
450 }
451 }
452
453 pub(super) fn pat_guaranteed_to_constitute_read_for_never(&self, pat: &hir::Pat<'_>) -> bool {
459 match pat.kind {
460 hir::PatKind::Wild => false,
462
463 hir::PatKind::Guard(_, _) => true,
465
466 hir::PatKind::Or(subpats) => {
475 subpats.iter().all(|pat| self.pat_guaranteed_to_constitute_read_for_never(pat))
476 }
477
478 hir::PatKind::Never => true,
480
481 hir::PatKind::Missing
484 | hir::PatKind::Binding(_, _, _, _)
485 | hir::PatKind::Struct(_, _, _)
486 | hir::PatKind::TupleStruct(_, _, _)
487 | hir::PatKind::Tuple(_, _)
488 | hir::PatKind::Box(_)
489 | hir::PatKind::Ref(_, _)
490 | hir::PatKind::Deref(_)
491 | hir::PatKind::Expr(_)
492 | hir::PatKind::Range(_, _, _)
493 | hir::PatKind::Slice(_, _, _)
494 | hir::PatKind::Err(_) => true,
495 }
496 }
497
498 #[instrument(skip(self, expr), level = "debug")]
499 fn check_expr_kind(
500 &self,
501 expr: &'tcx hir::Expr<'tcx>,
502 expected: Expectation<'tcx>,
503 ) -> Ty<'tcx> {
504 trace!("expr={:#?}", expr);
505
506 let tcx = self.tcx;
507 match expr.kind {
508 ExprKind::Lit(ref lit) => self.check_expr_lit(lit, expected),
509 ExprKind::Binary(op, lhs, rhs) => self.check_expr_binop(expr, op, lhs, rhs, expected),
510 ExprKind::Assign(lhs, rhs, span) => {
511 self.check_expr_assign(expr, expected, lhs, rhs, span)
512 }
513 ExprKind::AssignOp(op, lhs, rhs) => {
514 self.check_expr_assign_op(expr, op, lhs, rhs, expected)
515 }
516 ExprKind::Unary(unop, oprnd) => self.check_expr_unop(unop, oprnd, expected, expr),
517 ExprKind::AddrOf(kind, mutbl, oprnd) => {
518 self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
519 }
520 ExprKind::Path(QPath::LangItem(lang_item, _)) => {
521 self.check_lang_item_path(lang_item, expr)
522 }
523 ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr, None),
524 ExprKind::InlineAsm(asm) => {
525 self.deferred_asm_checks.borrow_mut().push((asm, expr.hir_id));
527 self.check_expr_asm(asm)
528 }
529 ExprKind::OffsetOf(container, fields) => {
530 self.check_expr_offset_of(container, fields, expr)
531 }
532 ExprKind::Break(destination, ref expr_opt) => {
533 self.check_expr_break(destination, expr_opt.as_deref(), expr)
534 }
535 ExprKind::Continue(destination) => {
536 if destination.target_id.is_ok() {
537 tcx.types.never
538 } else {
539 Ty::new_misc_error(tcx)
541 }
542 }
543 ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
544 ExprKind::Become(call) => self.check_expr_become(call, expr),
545 ExprKind::Let(let_expr) => self.check_expr_let(let_expr, expr.hir_id),
546 ExprKind::Loop(body, _, source, _) => {
547 self.check_expr_loop(body, source, expected, expr)
548 }
549 ExprKind::Match(discrim, arms, match_src) => {
550 self.check_expr_match(expr, discrim, arms, expected, match_src)
551 }
552 ExprKind::Closure(closure) => self.check_expr_closure(closure, expr.span, expected),
553 ExprKind::Block(body, _) => self.check_expr_block(body, expected),
554 ExprKind::Call(callee, args) => self.check_expr_call(expr, callee, args, expected),
555 ExprKind::Use(used_expr, _) => self.check_expr_use(used_expr, expected),
556 ExprKind::MethodCall(segment, receiver, args, _) => {
557 self.check_expr_method_call(expr, segment, receiver, args, expected)
558 }
559 ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr),
560 ExprKind::Type(e, t) => {
561 let ascribed_ty = self.lower_ty_saving_user_provided_ty(t);
562 let ty = self.check_expr_with_hint(e, ascribed_ty);
563 self.demand_eqtype(e.span, ascribed_ty, ty);
564 ascribed_ty
565 }
566 ExprKind::If(cond, then_expr, opt_else_expr) => {
567 self.check_expr_if(cond, then_expr, opt_else_expr, expr.span, expected)
568 }
569 ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected),
570 ExprKind::Array(args) => self.check_expr_array(args, expected, expr),
571 ExprKind::ConstBlock(ref block) => self.check_expr_const_block(block, expected),
572 ExprKind::Repeat(element, ref count) => {
573 self.check_expr_repeat(element, count, expected, expr)
574 }
575 ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr),
576 ExprKind::Struct(qpath, fields, ref base_expr) => {
577 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
578 }
579 ExprKind::Field(base, field) => self.check_expr_field(expr, base, field, expected),
580 ExprKind::Index(base, idx, brackets_span) => {
581 self.check_expr_index(base, idx, expr, brackets_span)
582 }
583 ExprKind::Yield(value, _) => self.check_expr_yield(value, expr),
584 ExprKind::UnsafeBinderCast(kind, inner_expr, ty) => {
585 self.check_expr_unsafe_binder_cast(expr.span, kind, inner_expr, ty, expected)
586 }
587 ExprKind::Err(guar) => Ty::new_error(tcx, guar),
588 }
589 }
590
591 fn check_expr_unop(
592 &self,
593 unop: hir::UnOp,
594 oprnd: &'tcx hir::Expr<'tcx>,
595 expected: Expectation<'tcx>,
596 expr: &'tcx hir::Expr<'tcx>,
597 ) -> Ty<'tcx> {
598 let tcx = self.tcx;
599 let expected_inner = match unop {
600 hir::UnOp::Not | hir::UnOp::Neg => expected,
601 hir::UnOp::Deref => NoExpectation,
602 };
603 let mut oprnd_t = self.check_expr_with_expectation(oprnd, expected_inner);
604
605 if !oprnd_t.references_error() {
606 oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t);
607 match unop {
608 hir::UnOp::Deref => {
609 if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) {
610 oprnd_t = ty;
611 } else {
612 let mut err =
613 self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t });
614 let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None);
615 if let Some(sp) =
616 tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp)
617 {
618 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
619 }
620 oprnd_t = Ty::new_error(tcx, err.emit());
621 }
622 }
623 hir::UnOp::Not => {
624 let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
625 if !(oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool) {
627 oprnd_t = result;
628 }
629 }
630 hir::UnOp::Neg => {
631 let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
632 if !oprnd_t.is_numeric() {
634 oprnd_t = result;
635 }
636 }
637 }
638 }
639 oprnd_t
640 }
641
642 fn check_expr_addr_of(
643 &self,
644 kind: hir::BorrowKind,
645 mutbl: hir::Mutability,
646 oprnd: &'tcx hir::Expr<'tcx>,
647 expected: Expectation<'tcx>,
648 expr: &'tcx hir::Expr<'tcx>,
649 ) -> Ty<'tcx> {
650 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
651 match self.try_structurally_resolve_type(expr.span, ty).kind() {
652 ty::Ref(_, ty, _) | ty::RawPtr(ty, _) => {
653 if oprnd.is_syntactic_place_expr() {
654 ExpectHasType(*ty)
658 } else {
659 Expectation::rvalue_hint(self, *ty)
660 }
661 }
662 _ => NoExpectation,
663 }
664 });
665 let ty =
666 self.check_expr_with_expectation_and_needs(oprnd, hint, Needs::maybe_mut_place(mutbl));
667
668 match kind {
669 _ if ty.references_error() => Ty::new_misc_error(self.tcx),
670 hir::BorrowKind::Raw => {
671 self.check_named_place_expr(oprnd);
672 Ty::new_ptr(self.tcx, ty, mutbl)
673 }
674 hir::BorrowKind::Ref => {
675 let region = self.next_region_var(infer::BorrowRegion(expr.span));
690 Ty::new_ref(self.tcx, region, ty, mutbl)
691 }
692 }
693 }
694
695 fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
701 let is_named = oprnd.is_place_expr(|base| {
702 self.typeck_results
714 .borrow()
715 .adjustments()
716 .get(base.hir_id)
717 .is_some_and(|x| x.iter().any(|adj| matches!(adj.kind, Adjust::Deref(_))))
718 });
719 if !is_named {
720 self.dcx().emit_err(AddressOfTemporaryTaken { span: oprnd.span });
721 }
722 }
723
724 fn check_lang_item_path(
725 &self,
726 lang_item: hir::LangItem,
727 expr: &'tcx hir::Expr<'tcx>,
728 ) -> Ty<'tcx> {
729 self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id).1
730 }
731
732 pub(crate) fn check_expr_path(
733 &self,
734 qpath: &'tcx hir::QPath<'tcx>,
735 expr: &'tcx hir::Expr<'tcx>,
736 call_expr_and_args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
737 ) -> Ty<'tcx> {
738 let tcx = self.tcx;
739 let (res, opt_ty, segs) =
740 self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span);
741 let ty = match res {
742 Res::Err => {
743 self.suggest_assoc_method_call(segs);
744 let e =
745 self.dcx().span_delayed_bug(qpath.span(), "`Res::Err` but no error emitted");
746 Ty::new_error(tcx, e)
747 }
748 Res::Def(DefKind::Variant, _) => {
749 let e = report_unexpected_variant_res(
750 tcx,
751 res,
752 Some(expr),
753 qpath,
754 expr.span,
755 E0533,
756 "value",
757 );
758 Ty::new_error(tcx, e)
759 }
760 _ => {
761 self.instantiate_value_path(
762 segs,
763 opt_ty,
764 res,
765 call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
766 expr.span,
767 expr.hir_id,
768 )
769 .0
770 }
771 };
772
773 if let ty::FnDef(did, _) = *ty.kind() {
774 let fn_sig = ty.fn_sig(tcx);
775
776 if tcx.is_intrinsic(did, sym::transmute) {
777 let Some(from) = fn_sig.inputs().skip_binder().get(0) else {
778 span_bug!(
779 tcx.def_span(did),
780 "intrinsic fn `transmute` defined with no parameters"
781 );
782 };
783 let to = fn_sig.output().skip_binder();
784 self.deferred_transmute_checks.borrow_mut().push((*from, to, expr.hir_id));
789 }
790 if !tcx.features().unsized_fn_params() {
791 for i in 0..fn_sig.inputs().skip_binder().len() {
801 let span = call_expr_and_args
805 .and_then(|(_, args)| args.get(i))
806 .map_or(expr.span, |arg| arg.span);
807 let input = self.instantiate_binder_with_fresh_vars(
808 span,
809 infer::BoundRegionConversionTime::FnCall,
810 fn_sig.input(i),
811 );
812 self.require_type_is_sized_deferred(
813 input,
814 span,
815 ObligationCauseCode::SizedArgumentType(None),
816 );
817 }
818 }
819 let output = self.instantiate_binder_with_fresh_vars(
826 expr.span,
827 infer::BoundRegionConversionTime::FnCall,
828 fn_sig.output(),
829 );
830 self.require_type_is_sized_deferred(
831 output,
832 call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
833 ObligationCauseCode::SizedCallReturnType,
834 );
835 }
836
837 let args = self.typeck_results.borrow().node_args(expr.hir_id);
840 self.add_wf_bounds(args, expr.span);
841
842 ty
843 }
844
845 fn check_expr_break(
846 &self,
847 destination: hir::Destination,
848 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
849 expr: &'tcx hir::Expr<'tcx>,
850 ) -> Ty<'tcx> {
851 let tcx = self.tcx;
852 if let Ok(target_id) = destination.target_id {
853 let (e_ty, cause);
854 if let Some(e) = expr_opt {
855 let opt_coerce_to = {
858 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
862 match enclosing_breakables.opt_find_breakable(target_id) {
863 Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
864 None => {
865 return Ty::new_error_with_message(
867 tcx,
868 expr.span,
869 "break was outside loop, but no error was emitted",
870 );
871 }
872 }
873 };
874
875 let coerce_to = opt_coerce_to.unwrap_or_else(|| {
880 let guar = self.dcx().span_delayed_bug(
881 expr.span,
882 "illegal break with value found but no error reported",
883 );
884 self.set_tainted_by_errors(guar);
885 Ty::new_error(tcx, guar)
886 });
887
888 e_ty = self.check_expr_with_hint(e, coerce_to);
890 cause = self.misc(e.span);
891 } else {
892 e_ty = tcx.types.unit;
895 cause = self.misc(expr.span);
896 }
897
898 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
902 let Some(ctxt) = enclosing_breakables.opt_find_breakable(target_id) else {
903 return Ty::new_error_with_message(
905 tcx,
906 expr.span,
907 "break was outside loop, but no error was emitted",
908 );
909 };
910
911 if let Some(ref mut coerce) = ctxt.coerce {
912 if let Some(e) = expr_opt {
913 coerce.coerce(self, &cause, e, e_ty);
914 } else {
915 assert!(e_ty.is_unit());
916 let ty = coerce.expected_ty();
917 coerce.coerce_forced_unit(
918 self,
919 &cause,
920 |mut err| {
921 self.suggest_missing_semicolon(&mut err, expr, e_ty, false);
922 self.suggest_mismatched_types_on_tail(
923 &mut err, expr, ty, e_ty, target_id,
924 );
925 let error =
926 Some(TypeError::Sorts(ExpectedFound { expected: ty, found: e_ty }));
927 self.annotate_loop_expected_due_to_inference(err, expr, error);
928 if let Some(val) =
929 self.err_ctxt().ty_kind_suggestion(self.param_env, ty)
930 {
931 err.span_suggestion_verbose(
932 expr.span.shrink_to_hi(),
933 "give the `break` a value of the expected type",
934 format!(" {val}"),
935 Applicability::HasPlaceholders,
936 );
937 }
938 },
939 false,
940 );
941 }
942 } else {
943 assert!(expr_opt.is_none() || self.tainted_by_errors().is_some());
951 }
952
953 ctxt.may_break |= !self.diverges.get().is_always();
957
958 tcx.types.never
960 } else {
961 let err = Ty::new_error_with_message(
966 self.tcx,
967 expr.span,
968 "break was outside loop, but no error was emitted",
969 );
970
971 if let Some(e) = expr_opt {
974 self.check_expr_with_hint(e, err);
975
976 if let ExprKind::Path(QPath::Resolved(_, path)) = e.kind {
979 if let [segment] = path.segments
980 && segment.ident.name == sym::rust
981 {
982 fatally_break_rust(self.tcx, expr.span);
983 }
984 }
985 }
986
987 err
989 }
990 }
991
992 fn check_expr_return(
993 &self,
994 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
995 expr: &'tcx hir::Expr<'tcx>,
996 ) -> Ty<'tcx> {
997 if self.ret_coercion.is_none() {
998 self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Return);
999
1000 if let Some(e) = expr_opt {
1001 self.check_expr(e);
1004 }
1005 } else if let Some(e) = expr_opt {
1006 if self.ret_coercion_span.get().is_none() {
1007 self.ret_coercion_span.set(Some(e.span));
1008 }
1009 self.check_return_or_body_tail(e, true);
1010 } else {
1011 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
1012 if self.ret_coercion_span.get().is_none() {
1013 self.ret_coercion_span.set(Some(expr.span));
1014 }
1015 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
1016 if let Some((_, fn_decl)) = self.get_fn_decl(expr.hir_id) {
1017 coercion.coerce_forced_unit(
1018 self,
1019 &cause,
1020 |db| {
1021 let span = fn_decl.output.span();
1022 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1023 db.span_label(
1024 span,
1025 format!("expected `{snippet}` because of this return type"),
1026 );
1027 }
1028 },
1029 true,
1030 );
1031 } else {
1032 coercion.coerce_forced_unit(self, &cause, |_| (), true);
1033 }
1034 }
1035 self.tcx.types.never
1036 }
1037
1038 fn check_expr_become(
1039 &self,
1040 call: &'tcx hir::Expr<'tcx>,
1041 expr: &'tcx hir::Expr<'tcx>,
1042 ) -> Ty<'tcx> {
1043 match &self.ret_coercion {
1044 Some(ret_coercion) => {
1045 let ret_ty = ret_coercion.borrow().expected_ty();
1046 let call_expr_ty = self.check_expr_with_hint(call, ret_ty);
1047
1048 self.demand_suptype(expr.span, ret_ty, call_expr_ty);
1051 }
1052 None => {
1053 self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Become);
1054
1055 self.check_expr(call);
1058 }
1059 }
1060
1061 self.tcx.types.never
1062 }
1063
1064 pub(super) fn check_return_or_body_tail(
1073 &self,
1074 return_expr: &'tcx hir::Expr<'tcx>,
1075 explicit_return: bool,
1076 ) {
1077 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
1078 span_bug!(return_expr.span, "check_return_expr called outside fn body")
1079 });
1080
1081 let ret_ty = ret_coercion.borrow().expected_ty();
1082 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
1083 let mut span = return_expr.span;
1084 let mut hir_id = return_expr.hir_id;
1085 if !explicit_return
1088 && let ExprKind::Block(body, _) = return_expr.kind
1089 && let Some(last_expr) = body.expr
1090 {
1091 span = last_expr.span;
1092 hir_id = last_expr.hir_id;
1093 }
1094 ret_coercion.borrow_mut().coerce(
1095 self,
1096 &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
1097 return_expr,
1098 return_expr_ty,
1099 );
1100
1101 if let Some(fn_sig) = self.body_fn_sig()
1102 && fn_sig.output().has_opaque_types()
1103 {
1104 self.select_obligations_where_possible(|errors| {
1107 self.point_at_return_for_opaque_ty_error(
1108 errors,
1109 hir_id,
1110 span,
1111 return_expr_ty,
1112 return_expr.span,
1113 );
1114 });
1115 }
1116 }
1117
1118 fn emit_return_outside_of_fn_body(&self, expr: &hir::Expr<'_>, kind: ReturnLikeStatementKind) {
1123 let mut err = ReturnStmtOutsideOfFnBody {
1124 span: expr.span,
1125 encl_body_span: None,
1126 encl_fn_span: None,
1127 statement_kind: kind,
1128 };
1129
1130 let encl_item_id = self.tcx.hir_get_parent_item(expr.hir_id);
1131
1132 if let hir::Node::Item(hir::Item {
1133 kind: hir::ItemKind::Fn { .. },
1134 span: encl_fn_span,
1135 ..
1136 })
1137 | hir::Node::TraitItem(hir::TraitItem {
1138 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
1139 span: encl_fn_span,
1140 ..
1141 })
1142 | hir::Node::ImplItem(hir::ImplItem {
1143 kind: hir::ImplItemKind::Fn(..),
1144 span: encl_fn_span,
1145 ..
1146 }) = self.tcx.hir_node_by_def_id(encl_item_id.def_id)
1147 {
1148 let encl_body_owner_id = self.tcx.hir_enclosing_body_owner(expr.hir_id);
1152
1153 assert_ne!(encl_item_id.def_id, encl_body_owner_id);
1156
1157 let encl_body = self.tcx.hir_body_owned_by(encl_body_owner_id);
1158
1159 err.encl_body_span = Some(encl_body.value.span);
1160 err.encl_fn_span = Some(*encl_fn_span);
1161 }
1162
1163 self.dcx().emit_err(err);
1164 }
1165
1166 fn point_at_return_for_opaque_ty_error(
1167 &self,
1168 errors: &mut Vec<traits::FulfillmentError<'tcx>>,
1169 hir_id: HirId,
1170 span: Span,
1171 return_expr_ty: Ty<'tcx>,
1172 return_span: Span,
1173 ) {
1174 if span == return_span {
1176 return;
1177 }
1178 for err in errors {
1179 let cause = &mut err.obligation.cause;
1180 if let ObligationCauseCode::OpaqueReturnType(None) = cause.code() {
1181 let new_cause = self.cause(
1182 cause.span,
1183 ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, hir_id))),
1184 );
1185 *cause = new_cause;
1186 }
1187 }
1188 }
1189
1190 pub(crate) fn check_lhs_assignable(
1191 &self,
1192 lhs: &'tcx hir::Expr<'tcx>,
1193 code: ErrCode,
1194 op_span: Span,
1195 adjust_err: impl FnOnce(&mut Diag<'_>),
1196 ) {
1197 if lhs.is_syntactic_place_expr() {
1198 return;
1199 }
1200
1201 let mut err = self.dcx().struct_span_err(op_span, "invalid left-hand side of assignment");
1202 err.code(code);
1203 err.span_label(lhs.span, "cannot assign to this expression");
1204
1205 self.comes_from_while_condition(lhs.hir_id, |expr| {
1206 err.span_suggestion_verbose(
1207 expr.span.shrink_to_lo(),
1208 "you might have meant to use pattern destructuring",
1209 "let ",
1210 Applicability::MachineApplicable,
1211 );
1212 });
1213 self.check_for_missing_semi(lhs, &mut err);
1214
1215 adjust_err(&mut err);
1216
1217 err.emit();
1218 }
1219
1220 pub(crate) fn check_for_missing_semi(
1222 &self,
1223 expr: &'tcx hir::Expr<'tcx>,
1224 err: &mut Diag<'_>,
1225 ) -> bool {
1226 if let hir::ExprKind::Binary(binop, lhs, rhs) = expr.kind
1227 && let hir::BinOpKind::Mul = binop.node
1228 && self.tcx.sess.source_map().is_multiline(lhs.span.between(rhs.span))
1229 && rhs.is_syntactic_place_expr()
1230 {
1231 err.span_suggestion_verbose(
1236 lhs.span.shrink_to_hi(),
1237 "you might have meant to write a semicolon here",
1238 ";",
1239 Applicability::MachineApplicable,
1240 );
1241 return true;
1242 }
1243 false
1244 }
1245
1246 pub(super) fn comes_from_while_condition(
1250 &self,
1251 original_expr_id: HirId,
1252 then: impl FnOnce(&hir::Expr<'_>),
1253 ) {
1254 let mut parent = self.tcx.parent_hir_id(original_expr_id);
1255 loop {
1256 let node = self.tcx.hir_node(parent);
1257 match node {
1258 hir::Node::Expr(hir::Expr {
1259 kind:
1260 hir::ExprKind::Loop(
1261 hir::Block {
1262 expr:
1263 Some(hir::Expr {
1264 kind:
1265 hir::ExprKind::Match(expr, ..) | hir::ExprKind::If(expr, ..),
1266 ..
1267 }),
1268 ..
1269 },
1270 _,
1271 hir::LoopSource::While,
1272 _,
1273 ),
1274 ..
1275 }) => {
1276 if self.tcx.hir_parent_id_iter(original_expr_id).any(|id| id == expr.hir_id) {
1280 then(expr);
1281 }
1282 break;
1283 }
1284 hir::Node::Item(_)
1285 | hir::Node::ImplItem(_)
1286 | hir::Node::TraitItem(_)
1287 | hir::Node::Crate(_) => break,
1288 _ => {
1289 parent = self.tcx.parent_hir_id(parent);
1290 }
1291 }
1292 }
1293 }
1294
1295 fn check_expr_if(
1298 &self,
1299 cond_expr: &'tcx hir::Expr<'tcx>,
1300 then_expr: &'tcx hir::Expr<'tcx>,
1301 opt_else_expr: Option<&'tcx hir::Expr<'tcx>>,
1302 sp: Span,
1303 orig_expected: Expectation<'tcx>,
1304 ) -> Ty<'tcx> {
1305 let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {});
1306
1307 self.warn_if_unreachable(
1308 cond_expr.hir_id,
1309 then_expr.span,
1310 "block in `if` or `while` expression",
1311 );
1312
1313 let cond_diverges = self.diverges.get();
1314 self.diverges.set(Diverges::Maybe);
1315
1316 let expected = orig_expected.try_structurally_resolve_and_adjust_for_branches(self, sp);
1317 let then_ty = self.check_expr_with_expectation(then_expr, expected);
1318 let then_diverges = self.diverges.get();
1319 self.diverges.set(Diverges::Maybe);
1320
1321 let coerce_to_ty = expected.coercion_target_type(self, sp);
1328 let mut coerce: DynamicCoerceMany<'_> = CoerceMany::new(coerce_to_ty);
1329
1330 coerce.coerce(self, &self.misc(sp), then_expr, then_ty);
1331
1332 if let Some(else_expr) = opt_else_expr {
1333 let else_ty = self.check_expr_with_expectation(else_expr, expected);
1334 let else_diverges = self.diverges.get();
1335
1336 let tail_defines_return_position_impl_trait =
1337 self.return_position_impl_trait_from_match_expectation(orig_expected);
1338 let if_cause = self.if_cause(
1339 sp,
1340 cond_expr.span,
1341 then_expr,
1342 else_expr,
1343 then_ty,
1344 else_ty,
1345 tail_defines_return_position_impl_trait,
1346 );
1347
1348 coerce.coerce(self, &if_cause, else_expr, else_ty);
1349
1350 self.diverges.set(cond_diverges | then_diverges & else_diverges);
1352 } else {
1353 self.if_fallback_coercion(sp, cond_expr, then_expr, &mut coerce);
1354
1355 self.diverges.set(cond_diverges);
1357 }
1358
1359 let result_ty = coerce.complete(self);
1360 if let Err(guar) = cond_ty.error_reported() {
1361 Ty::new_error(self.tcx, guar)
1362 } else {
1363 result_ty
1364 }
1365 }
1366
1367 fn check_expr_assign(
1370 &self,
1371 expr: &'tcx hir::Expr<'tcx>,
1372 expected: Expectation<'tcx>,
1373 lhs: &'tcx hir::Expr<'tcx>,
1374 rhs: &'tcx hir::Expr<'tcx>,
1375 span: Span,
1376 ) -> Ty<'tcx> {
1377 let expected_ty = expected.only_has_type(self);
1378 if expected_ty == Some(self.tcx.types.bool) {
1379 let guar = self.expr_assign_expected_bool_error(expr, lhs, rhs, span);
1380 return Ty::new_error(self.tcx, guar);
1381 }
1382
1383 let lhs_ty = self.check_expr_with_needs(lhs, Needs::MutPlace);
1384
1385 let suggest_deref_binop = |err: &mut Diag<'_>, rhs_ty: Ty<'tcx>| {
1386 if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
1387 let lhs_deref_ty_is_sized = self
1390 .infcx
1391 .type_implements_trait(
1392 self.tcx.require_lang_item(LangItem::Sized, None),
1393 [lhs_deref_ty],
1394 self.param_env,
1395 )
1396 .may_apply();
1397 if lhs_deref_ty_is_sized && self.may_coerce(rhs_ty, lhs_deref_ty) {
1398 err.span_suggestion_verbose(
1399 lhs.span.shrink_to_lo(),
1400 "consider dereferencing here to assign to the mutably borrowed value",
1401 "*",
1402 Applicability::MachineApplicable,
1403 );
1404 }
1405 }
1406 };
1407
1408 let rhs_ty = self.check_expr_with_hint(rhs, lhs_ty);
1411 if let Err(mut diag) =
1412 self.demand_coerce_diag(rhs, rhs_ty, lhs_ty, Some(lhs), AllowTwoPhase::No)
1413 {
1414 suggest_deref_binop(&mut diag, rhs_ty);
1415 diag.emit();
1416 }
1417
1418 self.check_lhs_assignable(lhs, E0070, span, |err| {
1419 if let Some(rhs_ty) = self.typeck_results.borrow().expr_ty_opt(rhs) {
1420 suggest_deref_binop(err, rhs_ty);
1421 }
1422 });
1423
1424 self.require_type_is_sized(lhs_ty, lhs.span, ObligationCauseCode::AssignmentLhsSized);
1425
1426 if let Err(guar) = (lhs_ty, rhs_ty).error_reported() {
1427 Ty::new_error(self.tcx, guar)
1428 } else {
1429 self.tcx.types.unit
1430 }
1431 }
1432
1433 fn expr_assign_expected_bool_error(
1437 &self,
1438 expr: &'tcx hir::Expr<'tcx>,
1439 lhs: &'tcx hir::Expr<'tcx>,
1440 rhs: &'tcx hir::Expr<'tcx>,
1441 span: Span,
1442 ) -> ErrorGuaranteed {
1443 let actual_ty = self.tcx.types.unit;
1444 let expected_ty = self.tcx.types.bool;
1445 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap_err();
1446 let lhs_ty = self.check_expr(lhs);
1447 let rhs_ty = self.check_expr(rhs);
1448 let refs_can_coerce = |lhs: Ty<'tcx>, rhs: Ty<'tcx>| {
1449 let lhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, lhs.peel_refs());
1450 let rhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rhs.peel_refs());
1451 self.may_coerce(rhs, lhs)
1452 };
1453 let (applicability, eq) = if self.may_coerce(rhs_ty, lhs_ty) {
1454 (Applicability::MachineApplicable, true)
1455 } else if refs_can_coerce(rhs_ty, lhs_ty) {
1456 (Applicability::MaybeIncorrect, true)
1459 } else if let ExprKind::Binary(
1460 Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1461 _,
1462 rhs_expr,
1463 ) = lhs.kind
1464 {
1465 let actual_lhs = self.check_expr(rhs_expr);
1468 let may_eq = self.may_coerce(rhs_ty, actual_lhs) || refs_can_coerce(rhs_ty, actual_lhs);
1469 (Applicability::MaybeIncorrect, may_eq)
1470 } else if let ExprKind::Binary(
1471 Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1472 lhs_expr,
1473 _,
1474 ) = rhs.kind
1475 {
1476 let actual_rhs = self.check_expr(lhs_expr);
1479 let may_eq = self.may_coerce(actual_rhs, lhs_ty) || refs_can_coerce(actual_rhs, lhs_ty);
1480 (Applicability::MaybeIncorrect, may_eq)
1481 } else {
1482 (Applicability::MaybeIncorrect, false)
1483 };
1484
1485 if !lhs.is_syntactic_place_expr()
1486 && lhs.is_approximately_pattern()
1487 && !matches!(lhs.kind, hir::ExprKind::Lit(_))
1488 {
1489 if let hir::Node::Expr(hir::Expr { kind: ExprKind::If { .. }, .. }) =
1491 self.tcx.parent_hir_node(expr.hir_id)
1492 {
1493 err.span_suggestion_verbose(
1494 expr.span.shrink_to_lo(),
1495 "you might have meant to use pattern matching",
1496 "let ",
1497 applicability,
1498 );
1499 };
1500 }
1501 if eq {
1502 err.span_suggestion_verbose(
1503 span.shrink_to_hi(),
1504 "you might have meant to compare for equality",
1505 '=',
1506 applicability,
1507 );
1508 }
1509
1510 err.emit_unless(lhs_ty.references_error() || rhs_ty.references_error())
1513 }
1514
1515 pub(super) fn check_expr_let(
1516 &self,
1517 let_expr: &'tcx hir::LetExpr<'tcx>,
1518 hir_id: HirId,
1519 ) -> Ty<'tcx> {
1520 GatherLocalsVisitor::gather_from_let_expr(self, let_expr, hir_id);
1521
1522 let init = let_expr.init;
1524 self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression");
1525
1526 self.check_decl((let_expr, hir_id).into());
1528
1529 if let ast::Recovered::Yes(error_guaranteed) = let_expr.recovered {
1531 self.set_tainted_by_errors(error_guaranteed);
1532 Ty::new_error(self.tcx, error_guaranteed)
1533 } else {
1534 self.tcx.types.bool
1535 }
1536 }
1537
1538 fn check_expr_loop(
1539 &self,
1540 body: &'tcx hir::Block<'tcx>,
1541 source: hir::LoopSource,
1542 expected: Expectation<'tcx>,
1543 expr: &'tcx hir::Expr<'tcx>,
1544 ) -> Ty<'tcx> {
1545 let coerce = match source {
1546 hir::LoopSource::Loop => {
1548 let coerce_to = expected.coercion_target_type(self, body.span);
1549 Some(CoerceMany::new(coerce_to))
1550 }
1551
1552 hir::LoopSource::While | hir::LoopSource::ForLoop => None,
1553 };
1554
1555 let ctxt = BreakableCtxt {
1556 coerce,
1557 may_break: false, };
1559
1560 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
1561 self.check_block_no_value(body);
1562 });
1563
1564 if ctxt.may_break {
1565 self.diverges.set(Diverges::Maybe);
1568 } else {
1569 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
1570 }
1571
1572 if ctxt.coerce.is_none() && !ctxt.may_break {
1578 self.dcx().span_bug(body.span, "no coercion, but loop may not break");
1579 }
1580 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.types.unit)
1581 }
1582
1583 fn check_expr_method_call(
1585 &self,
1586 expr: &'tcx hir::Expr<'tcx>,
1587 segment: &'tcx hir::PathSegment<'tcx>,
1588 rcvr: &'tcx hir::Expr<'tcx>,
1589 args: &'tcx [hir::Expr<'tcx>],
1590 expected: Expectation<'tcx>,
1591 ) -> Ty<'tcx> {
1592 let rcvr_t = self.check_expr(rcvr);
1593 let rcvr_t = self.structurally_resolve_type(rcvr.span, rcvr_t);
1595
1596 match self.lookup_method(rcvr_t, segment, segment.ident.span, expr, rcvr, args) {
1597 Ok(method) => {
1598 self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
1599
1600 self.check_argument_types(
1601 segment.ident.span,
1602 expr,
1603 &method.sig.inputs()[1..],
1604 method.sig.output(),
1605 expected,
1606 args,
1607 method.sig.c_variadic,
1608 TupleArgumentsFlag::DontTupleArguments,
1609 Some(method.def_id),
1610 );
1611
1612 method.sig.output()
1613 }
1614 Err(error) => {
1615 let guar = self.report_method_error(expr.hir_id, rcvr_t, error, expected, false);
1616
1617 let err_inputs = self.err_args(args.len(), guar);
1618 let err_output = Ty::new_error(self.tcx, guar);
1619
1620 self.check_argument_types(
1621 segment.ident.span,
1622 expr,
1623 &err_inputs,
1624 err_output,
1625 NoExpectation,
1626 args,
1627 false,
1628 TupleArgumentsFlag::DontTupleArguments,
1629 None,
1630 );
1631
1632 err_output
1633 }
1634 }
1635 }
1636
1637 fn check_expr_use(
1639 &self,
1640 used_expr: &'tcx hir::Expr<'tcx>,
1641 expected: Expectation<'tcx>,
1642 ) -> Ty<'tcx> {
1643 self.check_expr_with_expectation(used_expr, expected)
1644 }
1645
1646 fn check_expr_cast(
1647 &self,
1648 e: &'tcx hir::Expr<'tcx>,
1649 t: &'tcx hir::Ty<'tcx>,
1650 expr: &'tcx hir::Expr<'tcx>,
1651 ) -> Ty<'tcx> {
1652 let t_cast = self.lower_ty_saving_user_provided_ty(t);
1655 let t_cast = self.resolve_vars_if_possible(t_cast);
1656 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
1657 let t_expr = self.resolve_vars_if_possible(t_expr);
1658
1659 if let Err(guar) = (t_expr, t_cast).error_reported() {
1661 Ty::new_error(self.tcx, guar)
1662 } else {
1663 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
1665 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
1666 Ok(cast_check) => {
1667 debug!(
1668 "check_expr_cast: deferring cast from {:?} to {:?}: {:?}",
1669 t_cast, t_expr, cast_check,
1670 );
1671 deferred_cast_checks.push(cast_check);
1672 t_cast
1673 }
1674 Err(guar) => Ty::new_error(self.tcx, guar),
1675 }
1676 }
1677 }
1678
1679 fn check_expr_unsafe_binder_cast(
1680 &self,
1681 span: Span,
1682 kind: ast::UnsafeBinderCastKind,
1683 inner_expr: &'tcx hir::Expr<'tcx>,
1684 hir_ty: Option<&'tcx hir::Ty<'tcx>>,
1685 expected: Expectation<'tcx>,
1686 ) -> Ty<'tcx> {
1687 match kind {
1688 ast::UnsafeBinderCastKind::Wrap => {
1689 let ascribed_ty =
1690 hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1691 let expected_ty = expected.only_has_type(self);
1692 let binder_ty = match (ascribed_ty, expected_ty) {
1693 (Some(ascribed_ty), Some(expected_ty)) => {
1694 self.demand_eqtype(inner_expr.span, expected_ty, ascribed_ty);
1695 expected_ty
1696 }
1697 (Some(ty), None) | (None, Some(ty)) => ty,
1698 (None, None) => self.next_ty_var(inner_expr.span),
1702 };
1703
1704 let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1705 let hint_ty = match *binder_ty.kind() {
1706 ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1707 inner_expr.span,
1708 infer::BoundRegionConversionTime::HigherRankedType,
1709 binder.into(),
1710 ),
1711 ty::Error(e) => Ty::new_error(self.tcx, e),
1712 _ => {
1713 let guar = self
1714 .dcx()
1715 .struct_span_err(
1716 hir_ty.map_or(span, |hir_ty| hir_ty.span),
1717 format!(
1718 "`wrap_binder!()` can only wrap into unsafe binder, not {}",
1719 binder_ty.sort_string(self.tcx)
1720 ),
1721 )
1722 .with_note("unsafe binders are the only valid output of wrap")
1723 .emit();
1724 Ty::new_error(self.tcx, guar)
1725 }
1726 };
1727
1728 self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1729
1730 binder_ty
1731 }
1732 ast::UnsafeBinderCastKind::Unwrap => {
1733 let ascribed_ty =
1734 hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1735 let hint_ty = ascribed_ty.unwrap_or_else(|| self.next_ty_var(inner_expr.span));
1736 let binder_ty = self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1738
1739 let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1742 match *binder_ty.kind() {
1743 ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1744 inner_expr.span,
1745 infer::BoundRegionConversionTime::HigherRankedType,
1746 binder.into(),
1747 ),
1748 ty::Error(e) => Ty::new_error(self.tcx, e),
1749 _ => {
1750 let guar = self
1751 .dcx()
1752 .struct_span_err(
1753 hir_ty.map_or(inner_expr.span, |hir_ty| hir_ty.span),
1754 format!(
1755 "expected unsafe binder, found {} as input of \
1756 `unwrap_binder!()`",
1757 binder_ty.sort_string(self.tcx)
1758 ),
1759 )
1760 .with_note("only an unsafe binder type can be unwrapped")
1761 .emit();
1762 Ty::new_error(self.tcx, guar)
1763 }
1764 }
1765 }
1766 }
1767 }
1768
1769 fn check_expr_array(
1770 &self,
1771 args: &'tcx [hir::Expr<'tcx>],
1772 expected: Expectation<'tcx>,
1773 expr: &'tcx hir::Expr<'tcx>,
1774 ) -> Ty<'tcx> {
1775 let element_ty = if !args.is_empty() {
1776 let coerce_to = expected
1777 .to_option(self)
1778 .and_then(|uty| match *self.try_structurally_resolve_type(expr.span, uty).kind() {
1779 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1780 _ => None,
1781 })
1782 .unwrap_or_else(|| self.next_ty_var(expr.span));
1783 let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
1784 assert_eq!(self.diverges.get(), Diverges::Maybe);
1785 for e in args {
1786 let e_ty = self.check_expr_with_hint(e, coerce_to);
1787 let cause = self.misc(e.span);
1788 coerce.coerce(self, &cause, e, e_ty);
1789 }
1790 coerce.complete(self)
1791 } else {
1792 self.next_ty_var(expr.span)
1793 };
1794 let array_len = args.len() as u64;
1795 self.suggest_array_len(expr, array_len);
1796 Ty::new_array(self.tcx, element_ty, array_len)
1797 }
1798
1799 fn suggest_array_len(&self, expr: &'tcx hir::Expr<'tcx>, array_len: u64) {
1800 let parent_node = self.tcx.hir_parent_iter(expr.hir_id).find(|(_, node)| {
1801 !matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::AddrOf(..), .. }))
1802 });
1803 let Some((_, hir::Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }))) = parent_node else {
1804 return;
1805 };
1806 if let hir::TyKind::Array(_, ct) = ty.peel_refs().kind {
1807 let span = ct.span();
1808 self.dcx().try_steal_modify_and_emit_err(
1809 span,
1810 StashKey::UnderscoreForArrayLengths,
1811 |err| {
1812 err.span_suggestion(
1813 span,
1814 "consider specifying the array length",
1815 array_len,
1816 Applicability::MaybeIncorrect,
1817 );
1818 },
1819 );
1820 }
1821 }
1822
1823 pub(super) fn check_expr_const_block(
1824 &self,
1825 block: &'tcx hir::ConstBlock,
1826 expected: Expectation<'tcx>,
1827 ) -> Ty<'tcx> {
1828 let body = self.tcx.hir_body(block.body);
1829
1830 let def_id = block.def_id;
1832 let fcx = FnCtxt::new(self, self.param_env, def_id);
1833
1834 let ty = fcx.check_expr_with_expectation(body.value, expected);
1835 fcx.require_type_is_sized(ty, body.value.span, ObligationCauseCode::SizedConstOrStatic);
1836 fcx.write_ty(block.hir_id, ty);
1837 ty
1838 }
1839
1840 fn check_expr_repeat(
1841 &self,
1842 element: &'tcx hir::Expr<'tcx>,
1843 count: &'tcx hir::ConstArg<'tcx>,
1844 expected: Expectation<'tcx>,
1845 expr: &'tcx hir::Expr<'tcx>,
1846 ) -> Ty<'tcx> {
1847 let tcx = self.tcx;
1848 let count_span = count.span();
1849 let count = self.try_structurally_resolve_const(
1850 count_span,
1851 self.normalize(count_span, self.lower_const_arg(count, FeedConstTy::No)),
1852 );
1853
1854 if let Some(count) = count.try_to_target_usize(tcx) {
1855 self.suggest_array_len(expr, count);
1856 }
1857
1858 let uty = match expected {
1859 ExpectHasType(uty) => match *uty.kind() {
1860 ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
1861 _ => None,
1862 },
1863 _ => None,
1864 };
1865
1866 let (element_ty, t) = match uty {
1867 Some(uty) => {
1868 self.check_expr_coercible_to_type(element, uty, None);
1869 (uty, uty)
1870 }
1871 None => {
1872 let ty = self.next_ty_var(element.span);
1873 let element_ty = self.check_expr_has_type_or_error(element, ty, |_| {});
1874 (element_ty, ty)
1875 }
1876 };
1877
1878 if let Err(guar) = element_ty.error_reported() {
1879 return Ty::new_error(tcx, guar);
1880 }
1881
1882 if tcx.features().generic_arg_infer() {
1886 self.deferred_repeat_expr_checks.borrow_mut().push((element, element_ty, count));
1887 } else if count.try_to_target_usize(self.tcx).is_none_or(|x| x > 1) {
1891 self.enforce_repeat_element_needs_copy_bound(element, element_ty);
1892 }
1893
1894 let ty = Ty::new_array_with_const_len(tcx, t, count);
1895 self.register_wf_obligation(ty.into(), expr.span, ObligationCauseCode::WellFormed(None));
1896 ty
1897 }
1898
1899 pub(super) fn enforce_repeat_element_needs_copy_bound(
1901 &self,
1902 element: &hir::Expr<'_>,
1903 element_ty: Ty<'tcx>,
1904 ) {
1905 let tcx = self.tcx;
1906 match &element.kind {
1908 hir::ExprKind::ConstBlock(..) => return,
1909 hir::ExprKind::Path(qpath) => {
1910 let res = self.typeck_results.borrow().qpath_res(qpath, element.hir_id);
1911 if let Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::AnonConst, _) = res
1912 {
1913 return;
1914 }
1915 }
1916 _ => {}
1917 }
1918 let is_constable = match element.kind {
1922 hir::ExprKind::Call(func, _args) => match *self.node_ty(func.hir_id).kind() {
1923 ty::FnDef(def_id, _) if tcx.is_stable_const_fn(def_id) => traits::IsConstable::Fn,
1924 _ => traits::IsConstable::No,
1925 },
1926 hir::ExprKind::Path(qpath) => {
1927 match self.typeck_results.borrow().qpath_res(&qpath, element.hir_id) {
1928 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => traits::IsConstable::Ctor,
1929 _ => traits::IsConstable::No,
1930 }
1931 }
1932 _ => traits::IsConstable::No,
1933 };
1934
1935 let lang_item = self.tcx.require_lang_item(LangItem::Copy, None);
1936 let code =
1937 traits::ObligationCauseCode::RepeatElementCopy { is_constable, elt_span: element.span };
1938 self.require_type_meets(element_ty, element.span, code, lang_item);
1939 }
1940
1941 fn check_expr_tuple(
1942 &self,
1943 elts: &'tcx [hir::Expr<'tcx>],
1944 expected: Expectation<'tcx>,
1945 expr: &'tcx hir::Expr<'tcx>,
1946 ) -> Ty<'tcx> {
1947 let flds = expected.only_has_type(self).and_then(|ty| {
1948 let ty = self.try_structurally_resolve_type(expr.span, ty);
1949 match ty.kind() {
1950 ty::Tuple(flds) => Some(&flds[..]),
1951 _ => None,
1952 }
1953 });
1954
1955 let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds {
1956 Some(fs) if i < fs.len() => {
1957 let ety = fs[i];
1958 self.check_expr_coercible_to_type(e, ety, None);
1959 ety
1960 }
1961 _ => self.check_expr_with_expectation(e, NoExpectation),
1962 });
1963 let tuple = Ty::new_tup_from_iter(self.tcx, elt_ts_iter);
1964 if let Err(guar) = tuple.error_reported() {
1965 Ty::new_error(self.tcx, guar)
1966 } else {
1967 self.require_type_is_sized(
1968 tuple,
1969 expr.span,
1970 ObligationCauseCode::TupleInitializerSized,
1971 );
1972 tuple
1973 }
1974 }
1975
1976 fn check_expr_struct(
1977 &self,
1978 expr: &hir::Expr<'tcx>,
1979 expected: Expectation<'tcx>,
1980 qpath: &'tcx QPath<'tcx>,
1981 fields: &'tcx [hir::ExprField<'tcx>],
1982 base_expr: &'tcx hir::StructTailExpr<'tcx>,
1983 ) -> Ty<'tcx> {
1984 let (variant, adt_ty) = match self.check_struct_path(qpath, expr.hir_id) {
1986 Ok(data) => data,
1987 Err(guar) => {
1988 self.check_struct_fields_on_error(fields, base_expr);
1989 return Ty::new_error(self.tcx, guar);
1990 }
1991 };
1992
1993 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1995 if variant.field_list_has_applicable_non_exhaustive() {
1996 self.dcx()
1997 .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() });
1998 }
1999
2000 self.check_expr_struct_fields(
2001 adt_ty,
2002 expected,
2003 expr,
2004 qpath.span(),
2005 variant,
2006 fields,
2007 base_expr,
2008 );
2009
2010 self.require_type_is_sized(adt_ty, expr.span, ObligationCauseCode::StructInitializerSized);
2011 adt_ty
2012 }
2013
2014 fn check_expr_struct_fields(
2015 &self,
2016 adt_ty: Ty<'tcx>,
2017 expected: Expectation<'tcx>,
2018 expr: &hir::Expr<'_>,
2019 path_span: Span,
2020 variant: &'tcx ty::VariantDef,
2021 hir_fields: &'tcx [hir::ExprField<'tcx>],
2022 base_expr: &'tcx hir::StructTailExpr<'tcx>,
2023 ) {
2024 let tcx = self.tcx;
2025
2026 let adt_ty = self.try_structurally_resolve_type(path_span, adt_ty);
2027 let adt_ty_hint = expected.only_has_type(self).and_then(|expected| {
2028 self.fudge_inference_if_ok(|| {
2029 let ocx = ObligationCtxt::new(self);
2030 ocx.sup(&self.misc(path_span), self.param_env, expected, adt_ty)?;
2031 if !ocx.select_where_possible().is_empty() {
2032 return Err(TypeError::Mismatch);
2033 }
2034 Ok(self.resolve_vars_if_possible(adt_ty))
2035 })
2036 .ok()
2037 });
2038 if let Some(adt_ty_hint) = adt_ty_hint {
2039 self.demand_eqtype(path_span, adt_ty_hint, adt_ty);
2041 }
2042
2043 let ty::Adt(adt, args) = adt_ty.kind() else {
2044 span_bug!(path_span, "non-ADT passed to check_expr_struct_fields");
2045 };
2046 let adt_kind = adt.adt_kind();
2047
2048 let mut remaining_fields = variant
2049 .fields
2050 .iter_enumerated()
2051 .map(|(i, field)| (field.ident(tcx).normalize_to_macros_2_0(), (i, field)))
2052 .collect::<UnordMap<_, _>>();
2053
2054 let mut seen_fields = FxHashMap::default();
2055
2056 let mut error_happened = false;
2057
2058 if variant.fields.len() != remaining_fields.len() {
2059 let guar =
2062 self.dcx().span_delayed_bug(expr.span, "struct fields have non-unique names");
2063 self.set_tainted_by_errors(guar);
2064 error_happened = true;
2065 }
2066
2067 for (idx, field) in hir_fields.iter().enumerate() {
2069 let ident = tcx.adjust_ident(field.ident, variant.def_id);
2070 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
2071 seen_fields.insert(ident, field.span);
2072 self.write_field_index(field.hir_id, i);
2073
2074 if adt_kind != AdtKind::Enum {
2078 tcx.check_stability(v_field.did, Some(field.hir_id), field.span, None);
2079 }
2080
2081 self.field_ty(field.span, v_field, args)
2082 } else {
2083 error_happened = true;
2084 let guar = if let Some(prev_span) = seen_fields.get(&ident) {
2085 self.dcx().emit_err(FieldMultiplySpecifiedInInitializer {
2086 span: field.ident.span,
2087 prev_span: *prev_span,
2088 ident,
2089 })
2090 } else {
2091 self.report_unknown_field(
2092 adt_ty,
2093 variant,
2094 expr,
2095 field,
2096 hir_fields,
2097 adt.variant_descr(),
2098 )
2099 };
2100
2101 Ty::new_error(tcx, guar)
2102 };
2103
2104 self.register_wf_obligation(
2108 field_type.into(),
2109 field.expr.span,
2110 ObligationCauseCode::WellFormed(None),
2111 );
2112
2113 let ty = self.check_expr_with_hint(field.expr, field_type);
2116 let diag = self.demand_coerce_diag(field.expr, ty, field_type, None, AllowTwoPhase::No);
2117
2118 if let Err(diag) = diag {
2119 if idx == hir_fields.len() - 1 {
2120 if remaining_fields.is_empty() {
2121 self.suggest_fru_from_range_and_emit(field, variant, args, diag);
2122 } else {
2123 diag.stash(field.span, StashKey::MaybeFruTypo);
2124 }
2125 } else {
2126 diag.emit();
2127 }
2128 }
2129 }
2130
2131 if adt_kind == AdtKind::Union && hir_fields.len() != 1 {
2133 struct_span_code_err!(
2134 self.dcx(),
2135 path_span,
2136 E0784,
2137 "union expressions should have exactly one field",
2138 )
2139 .emit();
2140 }
2141
2142 if error_happened {
2146 if let hir::StructTailExpr::Base(base_expr) = base_expr {
2147 self.check_expr(base_expr);
2148 }
2149 return;
2150 }
2151
2152 if let hir::StructTailExpr::DefaultFields(span) = *base_expr {
2153 let mut missing_mandatory_fields = Vec::new();
2154 let mut missing_optional_fields = Vec::new();
2155 for f in &variant.fields {
2156 let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2157 if let Some(_) = remaining_fields.remove(&ident) {
2158 if f.value.is_none() {
2159 missing_mandatory_fields.push(ident);
2160 } else {
2161 missing_optional_fields.push(ident);
2162 }
2163 }
2164 }
2165 if !self.tcx.features().default_field_values() {
2166 let sugg = self.tcx.crate_level_attribute_injection_span(expr.hir_id);
2167 self.dcx().emit_err(BaseExpressionDoubleDot {
2168 span: span.shrink_to_hi(),
2169 default_field_values_suggestion: if self.tcx.sess.is_nightly_build()
2172 && missing_mandatory_fields.is_empty()
2173 && !missing_optional_fields.is_empty()
2174 && sugg.is_some()
2175 {
2176 sugg
2177 } else {
2178 None
2179 },
2180 default_field_values_help: if self.tcx.sess.is_nightly_build()
2181 && missing_mandatory_fields.is_empty()
2182 && !missing_optional_fields.is_empty()
2183 && sugg.is_none()
2184 {
2185 Some(BaseExpressionDoubleDotEnableDefaultFieldValues)
2186 } else {
2187 None
2188 },
2189 add_expr: if !missing_mandatory_fields.is_empty()
2190 || !missing_optional_fields.is_empty()
2191 {
2192 Some(BaseExpressionDoubleDotAddExpr { span: span.shrink_to_hi() })
2193 } else {
2194 None
2195 },
2196 remove_dots: if missing_mandatory_fields.is_empty()
2197 && missing_optional_fields.is_empty()
2198 {
2199 Some(BaseExpressionDoubleDotRemove { span })
2200 } else {
2201 None
2202 },
2203 });
2204 return;
2205 }
2206 if variant.fields.is_empty() {
2207 let mut err = self.dcx().struct_span_err(
2208 span,
2209 format!(
2210 "`{adt_ty}` has no fields, `..` needs at least one default field in the \
2211 struct definition",
2212 ),
2213 );
2214 err.span_label(path_span, "this type has no fields");
2215 err.emit();
2216 }
2217 if !missing_mandatory_fields.is_empty() {
2218 let s = pluralize!(missing_mandatory_fields.len());
2219 let fields = listify(&missing_mandatory_fields, |f| format!("`{f}`")).unwrap();
2220 self.dcx()
2221 .struct_span_err(
2222 span.shrink_to_lo(),
2223 format!("missing field{s} {fields} in initializer"),
2224 )
2225 .with_span_label(
2226 span.shrink_to_lo(),
2227 "fields that do not have a defaulted value must be provided explicitly",
2228 )
2229 .emit();
2230 return;
2231 }
2232 let fru_tys = match adt_ty.kind() {
2233 ty::Adt(adt, args) if adt.is_struct() => variant
2234 .fields
2235 .iter()
2236 .map(|f| self.normalize(span, f.ty(self.tcx, args)))
2237 .collect(),
2238 ty::Adt(adt, args) if adt.is_enum() => variant
2239 .fields
2240 .iter()
2241 .map(|f| self.normalize(span, f.ty(self.tcx, args)))
2242 .collect(),
2243 _ => {
2244 self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct { span });
2245 return;
2246 }
2247 };
2248 self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2249 } else if let hir::StructTailExpr::Base(base_expr) = base_expr {
2250 let fru_tys = if self.tcx.features().type_changing_struct_update() {
2253 if adt.is_struct() {
2254 let fresh_args = self.fresh_args_for_item(base_expr.span, adt.did());
2256 let fru_tys = variant
2261 .fields
2262 .iter()
2263 .map(|f| {
2264 let fru_ty = self
2265 .normalize(expr.span, self.field_ty(base_expr.span, f, fresh_args));
2266 let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2267 if let Some(_) = remaining_fields.remove(&ident) {
2268 let target_ty = self.field_ty(base_expr.span, f, args);
2269 let cause = self.misc(base_expr.span);
2270 match self.at(&cause, self.param_env).sup(
2271 DefineOpaqueTypes::Yes,
2275 target_ty,
2276 fru_ty,
2277 ) {
2278 Ok(InferOk { obligations, value: () }) => {
2279 self.register_predicates(obligations)
2280 }
2281 Err(_) => {
2282 span_bug!(
2283 cause.span,
2284 "subtyping remaining fields of type changing FRU failed: {target_ty} != {fru_ty}: {}::{}",
2285 variant.name,
2286 ident.name,
2287 );
2288 }
2289 }
2290 }
2291 self.resolve_vars_if_possible(fru_ty)
2292 })
2293 .collect();
2294 let fresh_base_ty = Ty::new_adt(self.tcx, *adt, fresh_args);
2313 self.check_expr_has_type_or_error(
2314 base_expr,
2315 self.resolve_vars_if_possible(fresh_base_ty),
2316 |_| {},
2317 );
2318 fru_tys
2319 } else {
2320 self.check_expr(base_expr);
2323 self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
2324 return;
2325 }
2326 } else {
2327 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {
2328 let base_ty = self.typeck_results.borrow().expr_ty(*base_expr);
2329 let same_adt = matches!((adt_ty.kind(), base_ty.kind()),
2330 (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt);
2331 if self.tcx.sess.is_nightly_build() && same_adt {
2332 feature_err(
2333 &self.tcx.sess,
2334 sym::type_changing_struct_update,
2335 base_expr.span,
2336 "type changing struct updating is experimental",
2337 )
2338 .emit();
2339 }
2340 });
2341 match adt_ty.kind() {
2342 ty::Adt(adt, args) if adt.is_struct() => variant
2343 .fields
2344 .iter()
2345 .map(|f| self.normalize(expr.span, f.ty(self.tcx, args)))
2346 .collect(),
2347 _ => {
2348 self.dcx()
2349 .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
2350 return;
2351 }
2352 }
2353 };
2354 self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2355 } else if adt_kind != AdtKind::Union && !remaining_fields.is_empty() {
2356 debug!(?remaining_fields);
2357 let private_fields: Vec<&ty::FieldDef> = variant
2358 .fields
2359 .iter()
2360 .filter(|field| !field.vis.is_accessible_from(tcx.parent_module(expr.hir_id), tcx))
2361 .collect();
2362
2363 if !private_fields.is_empty() {
2364 self.report_private_fields(
2365 adt_ty,
2366 path_span,
2367 expr.span,
2368 private_fields,
2369 hir_fields,
2370 );
2371 } else {
2372 self.report_missing_fields(
2373 adt_ty,
2374 path_span,
2375 expr.span,
2376 remaining_fields,
2377 variant,
2378 hir_fields,
2379 args,
2380 );
2381 }
2382 }
2383 }
2384
2385 fn check_struct_fields_on_error(
2386 &self,
2387 fields: &'tcx [hir::ExprField<'tcx>],
2388 base_expr: &'tcx hir::StructTailExpr<'tcx>,
2389 ) {
2390 for field in fields {
2391 self.check_expr(field.expr);
2392 }
2393 if let hir::StructTailExpr::Base(base) = *base_expr {
2394 self.check_expr(base);
2395 }
2396 }
2397
2398 fn report_missing_fields(
2410 &self,
2411 adt_ty: Ty<'tcx>,
2412 span: Span,
2413 full_span: Span,
2414 remaining_fields: UnordMap<Ident, (FieldIdx, &ty::FieldDef)>,
2415 variant: &'tcx ty::VariantDef,
2416 hir_fields: &'tcx [hir::ExprField<'tcx>],
2417 args: GenericArgsRef<'tcx>,
2418 ) {
2419 let len = remaining_fields.len();
2420
2421 let displayable_field_names: Vec<&str> =
2422 remaining_fields.items().map(|(ident, _)| ident.as_str()).into_sorted_stable_ord();
2423
2424 let mut truncated_fields_error = String::new();
2425 let remaining_fields_names = match &displayable_field_names[..] {
2426 [field1] => format!("`{field1}`"),
2427 [field1, field2] => format!("`{field1}` and `{field2}`"),
2428 [field1, field2, field3] => format!("`{field1}`, `{field2}` and `{field3}`"),
2429 _ => {
2430 truncated_fields_error =
2431 format!(" and {} other field{}", len - 3, pluralize!(len - 3));
2432 displayable_field_names
2433 .iter()
2434 .take(3)
2435 .map(|n| format!("`{n}`"))
2436 .collect::<Vec<_>>()
2437 .join(", ")
2438 }
2439 };
2440
2441 let mut err = struct_span_code_err!(
2442 self.dcx(),
2443 span,
2444 E0063,
2445 "missing field{} {}{} in initializer of `{}`",
2446 pluralize!(len),
2447 remaining_fields_names,
2448 truncated_fields_error,
2449 adt_ty
2450 );
2451 err.span_label(span, format!("missing {remaining_fields_names}{truncated_fields_error}"));
2452
2453 if remaining_fields.items().all(|(_, (_, field))| field.value.is_some())
2454 && self.tcx.sess.is_nightly_build()
2455 {
2456 let msg = format!(
2457 "all remaining fields have default values, {you_can} use those values with `..`",
2458 you_can = if self.tcx.features().default_field_values() {
2459 "you can"
2460 } else {
2461 "if you added `#![feature(default_field_values)]` to your crate you could"
2462 },
2463 );
2464 if let Some(hir_field) = hir_fields.last() {
2465 err.span_suggestion_verbose(
2466 hir_field.span.shrink_to_hi(),
2467 msg,
2468 ", ..".to_string(),
2469 Applicability::MachineApplicable,
2470 );
2471 } else if hir_fields.is_empty() {
2472 err.span_suggestion_verbose(
2473 span.shrink_to_hi().with_hi(full_span.hi()),
2474 msg,
2475 " { .. }".to_string(),
2476 Applicability::MachineApplicable,
2477 );
2478 }
2479 }
2480
2481 if let Some(hir_field) = hir_fields.last() {
2482 self.suggest_fru_from_range_and_emit(hir_field, variant, args, err);
2483 } else {
2484 err.emit();
2485 }
2486 }
2487
2488 fn suggest_fru_from_range_and_emit(
2491 &self,
2492 last_expr_field: &hir::ExprField<'tcx>,
2493 variant: &ty::VariantDef,
2494 args: GenericArgsRef<'tcx>,
2495 mut err: Diag<'_>,
2496 ) {
2497 if let ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [range_start, range_end], _) =
2499 last_expr_field.expr.kind
2500 && let variant_field =
2501 variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident)
2502 && let range_def_id = self.tcx.lang_items().range_struct()
2503 && variant_field
2504 .and_then(|field| field.ty(self.tcx, args).ty_adt_def())
2505 .map(|adt| adt.did())
2506 != range_def_id
2507 {
2508 let expr = self
2512 .tcx
2513 .sess
2514 .source_map()
2515 .span_to_snippet(range_end.expr.span)
2516 .ok()
2517 .filter(|s| s.len() < 25 && !s.contains(|c: char| c.is_control()));
2518
2519 let fru_span = self
2520 .tcx
2521 .sess
2522 .source_map()
2523 .span_extend_while_whitespace(range_start.span)
2524 .shrink_to_hi()
2525 .to(range_end.span);
2526
2527 err.subdiagnostic(TypeMismatchFruTypo { expr_span: range_start.span, fru_span, expr });
2528
2529 self.dcx().try_steal_replace_and_emit_err(
2531 last_expr_field.span,
2532 StashKey::MaybeFruTypo,
2533 err,
2534 );
2535 } else {
2536 err.emit();
2537 }
2538 }
2539
2540 fn report_private_fields(
2552 &self,
2553 adt_ty: Ty<'tcx>,
2554 span: Span,
2555 expr_span: Span,
2556 private_fields: Vec<&ty::FieldDef>,
2557 used_fields: &'tcx [hir::ExprField<'tcx>],
2558 ) {
2559 let mut err =
2560 self.dcx().struct_span_err(
2561 span,
2562 format!(
2563 "cannot construct `{adt_ty}` with struct literal syntax due to private fields",
2564 ),
2565 );
2566 let (used_private_fields, remaining_private_fields): (
2567 Vec<(Symbol, Span, bool)>,
2568 Vec<(Symbol, Span, bool)>,
2569 ) = private_fields
2570 .iter()
2571 .map(|field| {
2572 match used_fields.iter().find(|used_field| field.name == used_field.ident.name) {
2573 Some(used_field) => (field.name, used_field.span, true),
2574 None => (field.name, self.tcx.def_span(field.did), false),
2575 }
2576 })
2577 .partition(|field| field.2);
2578 err.span_labels(used_private_fields.iter().map(|(_, span, _)| *span), "private field");
2579 if !remaining_private_fields.is_empty() {
2580 let names = if remaining_private_fields.len() > 6 {
2581 String::new()
2582 } else {
2583 format!(
2584 "{} ",
2585 listify(&remaining_private_fields, |(name, _, _)| format!("`{name}`"))
2586 .expect("expected at least one private field to report")
2587 )
2588 };
2589 err.note(format!(
2590 "{}private field{s} {names}that {were} not provided",
2591 if used_fields.is_empty() { "" } else { "...and other " },
2592 s = pluralize!(remaining_private_fields.len()),
2593 were = pluralize!("was", remaining_private_fields.len()),
2594 ));
2595 }
2596
2597 if let ty::Adt(def, _) = adt_ty.kind() {
2598 let def_id = def.did();
2599 let mut items = self
2600 .tcx
2601 .inherent_impls(def_id)
2602 .into_iter()
2603 .flat_map(|i| self.tcx.associated_items(i).in_definition_order())
2604 .filter(|item| item.is_fn() && !item.is_method())
2606 .filter_map(|item| {
2607 let fn_sig = self.tcx.fn_sig(item.def_id).skip_binder();
2609 let ret_ty = fn_sig.output();
2610 let ret_ty = self.tcx.normalize_erasing_late_bound_regions(
2611 self.typing_env(self.param_env),
2612 ret_ty,
2613 );
2614 if !self.can_eq(self.param_env, ret_ty, adt_ty) {
2615 return None;
2616 }
2617 let input_len = fn_sig.inputs().skip_binder().len();
2618 let name = item.name();
2619 let order = !name.as_str().starts_with("new");
2620 Some((order, name, input_len))
2621 })
2622 .collect::<Vec<_>>();
2623 items.sort_by_key(|(order, _, _)| *order);
2624 let suggestion = |name, args| {
2625 format!(
2626 "::{name}({})",
2627 std::iter::repeat("_").take(args).collect::<Vec<_>>().join(", ")
2628 )
2629 };
2630 match &items[..] {
2631 [] => {}
2632 [(_, name, args)] => {
2633 err.span_suggestion_verbose(
2634 span.shrink_to_hi().with_hi(expr_span.hi()),
2635 format!("you might have meant to use the `{name}` associated function"),
2636 suggestion(name, *args),
2637 Applicability::MaybeIncorrect,
2638 );
2639 }
2640 _ => {
2641 err.span_suggestions(
2642 span.shrink_to_hi().with_hi(expr_span.hi()),
2643 "you might have meant to use an associated function to build this type",
2644 items.iter().map(|(_, name, args)| suggestion(name, *args)),
2645 Applicability::MaybeIncorrect,
2646 );
2647 }
2648 }
2649 if let Some(default_trait) = self.tcx.get_diagnostic_item(sym::Default)
2650 && self
2651 .infcx
2652 .type_implements_trait(default_trait, [adt_ty], self.param_env)
2653 .may_apply()
2654 {
2655 err.multipart_suggestion(
2656 "consider using the `Default` trait",
2657 vec![
2658 (span.shrink_to_lo(), "<".to_string()),
2659 (
2660 span.shrink_to_hi().with_hi(expr_span.hi()),
2661 " as std::default::Default>::default()".to_string(),
2662 ),
2663 ],
2664 Applicability::MaybeIncorrect,
2665 );
2666 }
2667 }
2668
2669 err.emit();
2670 }
2671
2672 fn report_unknown_field(
2673 &self,
2674 ty: Ty<'tcx>,
2675 variant: &'tcx ty::VariantDef,
2676 expr: &hir::Expr<'_>,
2677 field: &hir::ExprField<'_>,
2678 skip_fields: &[hir::ExprField<'_>],
2679 kind_name: &str,
2680 ) -> ErrorGuaranteed {
2681 if let Err(guar) = variant.has_errors() {
2683 return guar;
2684 }
2685 let mut err = self.err_ctxt().type_error_struct_with_diag(
2686 field.ident.span,
2687 |actual| match ty.kind() {
2688 ty::Adt(adt, ..) if adt.is_enum() => struct_span_code_err!(
2689 self.dcx(),
2690 field.ident.span,
2691 E0559,
2692 "{} `{}::{}` has no field named `{}`",
2693 kind_name,
2694 actual,
2695 variant.name,
2696 field.ident
2697 ),
2698 _ => struct_span_code_err!(
2699 self.dcx(),
2700 field.ident.span,
2701 E0560,
2702 "{} `{}` has no field named `{}`",
2703 kind_name,
2704 actual,
2705 field.ident
2706 ),
2707 },
2708 ty,
2709 );
2710
2711 let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap();
2712 match variant.ctor {
2713 Some((CtorKind::Fn, def_id)) => match ty.kind() {
2714 ty::Adt(adt, ..) if adt.is_enum() => {
2715 err.span_label(
2716 variant_ident_span,
2717 format!(
2718 "`{adt}::{variant}` defined here",
2719 adt = ty,
2720 variant = variant.name,
2721 ),
2722 );
2723 err.span_label(field.ident.span, "field does not exist");
2724 let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity();
2725 let inputs = fn_sig.inputs().skip_binder();
2726 let fields = format!(
2727 "({})",
2728 inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2729 );
2730 let (replace_span, sugg) = match expr.kind {
2731 hir::ExprKind::Struct(qpath, ..) => {
2732 (qpath.span().shrink_to_hi().with_hi(expr.span.hi()), fields)
2733 }
2734 _ => {
2735 (expr.span, format!("{ty}::{variant}{fields}", variant = variant.name))
2736 }
2737 };
2738 err.span_suggestion_verbose(
2739 replace_span,
2740 format!(
2741 "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax",
2742 adt = ty,
2743 variant = variant.name,
2744 ),
2745 sugg,
2746 Applicability::HasPlaceholders,
2747 );
2748 }
2749 _ => {
2750 err.span_label(variant_ident_span, format!("`{ty}` defined here"));
2751 err.span_label(field.ident.span, "field does not exist");
2752 let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity();
2753 let inputs = fn_sig.inputs().skip_binder();
2754 let fields = format!(
2755 "({})",
2756 inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2757 );
2758 err.span_suggestion_verbose(
2759 expr.span,
2760 format!("`{ty}` is a tuple {kind_name}, use the appropriate syntax",),
2761 format!("{ty}{fields}"),
2762 Applicability::HasPlaceholders,
2763 );
2764 }
2765 },
2766 _ => {
2767 let available_field_names = self.available_field_names(variant, expr, skip_fields);
2769 if let Some(field_name) =
2770 find_best_match_for_name(&available_field_names, field.ident.name, None)
2771 {
2772 err.span_label(field.ident.span, "unknown field");
2773 err.span_suggestion_verbose(
2774 field.ident.span,
2775 "a field with a similar name exists",
2776 field_name,
2777 Applicability::MaybeIncorrect,
2778 );
2779 } else {
2780 match ty.kind() {
2781 ty::Adt(adt, ..) => {
2782 if adt.is_enum() {
2783 err.span_label(
2784 field.ident.span,
2785 format!("`{}::{}` does not have this field", ty, variant.name),
2786 );
2787 } else {
2788 err.span_label(
2789 field.ident.span,
2790 format!("`{ty}` does not have this field"),
2791 );
2792 }
2793 if available_field_names.is_empty() {
2794 err.note("all struct fields are already assigned");
2795 } else {
2796 err.note(format!(
2797 "available fields are: {}",
2798 self.name_series_display(available_field_names)
2799 ));
2800 }
2801 }
2802 _ => bug!("non-ADT passed to report_unknown_field"),
2803 }
2804 };
2805 }
2806 }
2807 err.emit()
2808 }
2809
2810 fn available_field_names(
2811 &self,
2812 variant: &'tcx ty::VariantDef,
2813 expr: &hir::Expr<'_>,
2814 skip_fields: &[hir::ExprField<'_>],
2815 ) -> Vec<Symbol> {
2816 variant
2817 .fields
2818 .iter()
2819 .filter(|field| {
2820 skip_fields.iter().all(|&skip| skip.ident.name != field.name)
2821 && self.is_field_suggestable(field, expr.hir_id, expr.span)
2822 })
2823 .map(|field| field.name)
2824 .collect()
2825 }
2826
2827 fn name_series_display(&self, names: Vec<Symbol>) -> String {
2828 let limit = if names.len() == 6 { 6 } else { 5 };
2830 let mut display =
2831 names.iter().take(limit).map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", ");
2832 if names.len() > limit {
2833 display = format!("{} ... and {} others", display, names.len() - limit);
2834 }
2835 display
2836 }
2837
2838 fn find_adt_field(
2842 &self,
2843 base_def: ty::AdtDef<'tcx>,
2844 ident: Ident,
2845 ) -> Option<(FieldIdx, &'tcx ty::FieldDef)> {
2846 if base_def.is_enum() {
2848 return None;
2849 }
2850
2851 for (field_idx, field) in base_def.non_enum_variant().fields.iter_enumerated() {
2852 if field.ident(self.tcx).normalize_to_macros_2_0() == ident {
2853 return Some((field_idx, field));
2855 }
2856 }
2857
2858 None
2859 }
2860
2861 fn check_expr_field(
2871 &self,
2872 expr: &'tcx hir::Expr<'tcx>,
2873 base: &'tcx hir::Expr<'tcx>,
2874 field: Ident,
2875 expected: Expectation<'tcx>,
2877 ) -> Ty<'tcx> {
2878 debug!("check_field(expr: {:?}, base: {:?}, field: {:?})", expr, base, field);
2879 let base_ty = self.check_expr(base);
2880 let base_ty = self.structurally_resolve_type(base.span, base_ty);
2881
2882 let mut private_candidate = None;
2884
2885 let mut autoderef = self.autoderef(expr.span, base_ty);
2887 while let Some((deref_base_ty, _)) = autoderef.next() {
2888 debug!("deref_base_ty: {:?}", deref_base_ty);
2889 match deref_base_ty.kind() {
2890 ty::Adt(base_def, args) if !base_def.is_enum() => {
2891 debug!("struct named {:?}", deref_base_ty);
2892 if let Err(guar) = base_def.non_enum_variant().has_errors() {
2894 return Ty::new_error(self.tcx(), guar);
2895 }
2896
2897 let fn_body_hir_id = self.tcx.local_def_id_to_hir_id(self.body_id);
2898 let (ident, def_scope) =
2899 self.tcx.adjust_ident_and_get_scope(field, base_def.did(), fn_body_hir_id);
2900
2901 if let Some((idx, field)) = self.find_adt_field(*base_def, ident) {
2902 self.write_field_index(expr.hir_id, idx);
2903
2904 let adjustments = self.adjust_steps(&autoderef);
2905 if field.vis.is_accessible_from(def_scope, self.tcx) {
2906 self.apply_adjustments(base, adjustments);
2907 self.register_predicates(autoderef.into_obligations());
2908
2909 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
2910 return self.field_ty(expr.span, field, args);
2911 }
2912
2913 private_candidate = Some((adjustments, base_def.did()));
2915 }
2916 }
2917 ty::Tuple(tys) => {
2918 if let Ok(index) = field.as_str().parse::<usize>() {
2919 if field.name == sym::integer(index) {
2920 if let Some(&field_ty) = tys.get(index) {
2921 let adjustments = self.adjust_steps(&autoderef);
2922 self.apply_adjustments(base, adjustments);
2923 self.register_predicates(autoderef.into_obligations());
2924
2925 self.write_field_index(expr.hir_id, FieldIdx::from_usize(index));
2926 return field_ty;
2927 }
2928 }
2929 }
2930 }
2931 _ => {}
2932 }
2933 }
2934 let final_ty = self.structurally_resolve_type(autoderef.span(), autoderef.final_ty(false));
2940 if let ty::Error(_) = final_ty.kind() {
2941 return final_ty;
2942 }
2943
2944 if let Some((adjustments, did)) = private_candidate {
2945 self.apply_adjustments(base, adjustments);
2948 let guar = self.ban_private_field_access(
2949 expr,
2950 base_ty,
2951 field,
2952 did,
2953 expected.only_has_type(self),
2954 );
2955 return Ty::new_error(self.tcx(), guar);
2956 }
2957
2958 let guar = if self.method_exists_for_diagnostic(
2959 field,
2960 base_ty,
2961 expr.hir_id,
2962 expected.only_has_type(self),
2963 ) {
2964 self.ban_take_value_of_method(expr, base_ty, field)
2966 } else if !base_ty.is_primitive_ty() {
2967 self.ban_nonexisting_field(field, base, expr, base_ty)
2968 } else {
2969 let field_name = field.to_string();
2970 let mut err = type_error_struct!(
2971 self.dcx(),
2972 field.span,
2973 base_ty,
2974 E0610,
2975 "`{base_ty}` is a primitive type and therefore doesn't have fields",
2976 );
2977 let is_valid_suffix = |field: &str| {
2978 if field == "f32" || field == "f64" {
2979 return true;
2980 }
2981 let mut chars = field.chars().peekable();
2982 match chars.peek() {
2983 Some('e') | Some('E') => {
2984 chars.next();
2985 if let Some(c) = chars.peek()
2986 && !c.is_numeric()
2987 && *c != '-'
2988 && *c != '+'
2989 {
2990 return false;
2991 }
2992 while let Some(c) = chars.peek() {
2993 if !c.is_numeric() {
2994 break;
2995 }
2996 chars.next();
2997 }
2998 }
2999 _ => (),
3000 }
3001 let suffix = chars.collect::<String>();
3002 suffix.is_empty() || suffix == "f32" || suffix == "f64"
3003 };
3004 let maybe_partial_suffix = |field: &str| -> Option<&str> {
3005 let first_chars = ['f', 'l'];
3006 if field.len() >= 1
3007 && field.to_lowercase().starts_with(first_chars)
3008 && field[1..].chars().all(|c| c.is_ascii_digit())
3009 {
3010 if field.to_lowercase().starts_with(['f']) { Some("f32") } else { Some("f64") }
3011 } else {
3012 None
3013 }
3014 };
3015 if let ty::Infer(ty::IntVar(_)) = base_ty.kind()
3016 && let ExprKind::Lit(Spanned {
3017 node: ast::LitKind::Int(_, ast::LitIntType::Unsuffixed),
3018 ..
3019 }) = base.kind
3020 && !base.span.from_expansion()
3021 {
3022 if is_valid_suffix(&field_name) {
3023 err.span_suggestion_verbose(
3024 field.span.shrink_to_lo(),
3025 "if intended to be a floating point literal, consider adding a `0` after the period",
3026 '0',
3027 Applicability::MaybeIncorrect,
3028 );
3029 } else if let Some(correct_suffix) = maybe_partial_suffix(&field_name) {
3030 err.span_suggestion_verbose(
3031 field.span,
3032 format!("if intended to be a floating point literal, consider adding a `0` after the period and a `{correct_suffix}` suffix"),
3033 format!("0{correct_suffix}"),
3034 Applicability::MaybeIncorrect,
3035 );
3036 }
3037 }
3038 err.emit()
3039 };
3040
3041 Ty::new_error(self.tcx(), guar)
3042 }
3043
3044 fn suggest_await_on_field_access(
3045 &self,
3046 err: &mut Diag<'_>,
3047 field_ident: Ident,
3048 base: &'tcx hir::Expr<'tcx>,
3049 ty: Ty<'tcx>,
3050 ) {
3051 let Some(output_ty) = self.err_ctxt().get_impl_future_output_ty(ty) else {
3052 err.span_label(field_ident.span, "unknown field");
3053 return;
3054 };
3055 let ty::Adt(def, _) = output_ty.kind() else {
3056 err.span_label(field_ident.span, "unknown field");
3057 return;
3058 };
3059 if def.is_enum() {
3061 err.span_label(field_ident.span, "unknown field");
3062 return;
3063 }
3064 if !def.non_enum_variant().fields.iter().any(|field| field.ident(self.tcx) == field_ident) {
3065 err.span_label(field_ident.span, "unknown field");
3066 return;
3067 }
3068 err.span_label(
3069 field_ident.span,
3070 "field not available in `impl Future`, but it is available in its `Output`",
3071 );
3072 match self.tcx.coroutine_kind(self.body_id) {
3073 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3074 err.span_suggestion_verbose(
3075 base.span.shrink_to_hi(),
3076 "consider `await`ing on the `Future` to access the field",
3077 ".await",
3078 Applicability::MaybeIncorrect,
3079 );
3080 }
3081 _ => {
3082 let mut span: MultiSpan = base.span.into();
3083 span.push_span_label(self.tcx.def_span(self.body_id), "this is not `async`");
3084 err.span_note(
3085 span,
3086 "this implements `Future` and its output type has the field, \
3087 but the future cannot be awaited in a synchronous function",
3088 );
3089 }
3090 }
3091 }
3092
3093 fn ban_nonexisting_field(
3094 &self,
3095 ident: Ident,
3096 base: &'tcx hir::Expr<'tcx>,
3097 expr: &'tcx hir::Expr<'tcx>,
3098 base_ty: Ty<'tcx>,
3099 ) -> ErrorGuaranteed {
3100 debug!(
3101 "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}",
3102 ident, base, expr, base_ty
3103 );
3104 let mut err = self.no_such_field_err(ident, base_ty, expr);
3105
3106 match *base_ty.peel_refs().kind() {
3107 ty::Array(_, len) => {
3108 self.maybe_suggest_array_indexing(&mut err, base, ident, len);
3109 }
3110 ty::RawPtr(..) => {
3111 self.suggest_first_deref_field(&mut err, base, ident);
3112 }
3113 ty::Param(param_ty) => {
3114 err.span_label(ident.span, "unknown field");
3115 self.point_at_param_definition(&mut err, param_ty);
3116 }
3117 ty::Alias(ty::Opaque, _) => {
3118 self.suggest_await_on_field_access(&mut err, ident, base, base_ty.peel_refs());
3119 }
3120 _ => {
3121 err.span_label(ident.span, "unknown field");
3122 }
3123 }
3124
3125 self.suggest_fn_call(&mut err, base, base_ty, |output_ty| {
3126 if let ty::Adt(def, _) = output_ty.kind()
3127 && !def.is_enum()
3128 {
3129 def.non_enum_variant().fields.iter().any(|field| {
3130 field.ident(self.tcx) == ident
3131 && field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
3132 })
3133 } else if let ty::Tuple(tys) = output_ty.kind()
3134 && let Ok(idx) = ident.as_str().parse::<usize>()
3135 {
3136 idx < tys.len()
3137 } else {
3138 false
3139 }
3140 });
3141
3142 if ident.name == kw::Await {
3143 err.note("to `.await` a `Future`, switch to Rust 2018 or later");
3146 HelpUseLatestEdition::new().add_to_diag(&mut err);
3147 }
3148
3149 err.emit()
3150 }
3151
3152 fn ban_private_field_access(
3153 &self,
3154 expr: &hir::Expr<'tcx>,
3155 expr_t: Ty<'tcx>,
3156 field: Ident,
3157 base_did: DefId,
3158 return_ty: Option<Ty<'tcx>>,
3159 ) -> ErrorGuaranteed {
3160 let mut err = self.private_field_err(field, base_did);
3161
3162 if self.method_exists_for_diagnostic(field, expr_t, expr.hir_id, return_ty)
3164 && !self.expr_in_place(expr.hir_id)
3165 {
3166 self.suggest_method_call(
3167 &mut err,
3168 format!("a method `{field}` also exists, call it with parentheses"),
3169 field,
3170 expr_t,
3171 expr,
3172 None,
3173 );
3174 }
3175 err.emit()
3176 }
3177
3178 fn ban_take_value_of_method(
3179 &self,
3180 expr: &hir::Expr<'tcx>,
3181 expr_t: Ty<'tcx>,
3182 field: Ident,
3183 ) -> ErrorGuaranteed {
3184 let mut err = type_error_struct!(
3185 self.dcx(),
3186 field.span,
3187 expr_t,
3188 E0615,
3189 "attempted to take value of method `{field}` on type `{expr_t}`",
3190 );
3191 err.span_label(field.span, "method, not a field");
3192 let expr_is_call =
3193 if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) =
3194 self.tcx.parent_hir_node(expr.hir_id)
3195 {
3196 expr.hir_id == callee.hir_id
3197 } else {
3198 false
3199 };
3200 let expr_snippet =
3201 self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_default();
3202 let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')');
3203 let after_open = expr.span.lo() + rustc_span::BytePos(1);
3204 let before_close = expr.span.hi() - rustc_span::BytePos(1);
3205
3206 if expr_is_call && is_wrapped {
3207 err.multipart_suggestion(
3208 "remove wrapping parentheses to call the method",
3209 vec![
3210 (expr.span.with_hi(after_open), String::new()),
3211 (expr.span.with_lo(before_close), String::new()),
3212 ],
3213 Applicability::MachineApplicable,
3214 );
3215 } else if !self.expr_in_place(expr.hir_id) {
3216 let span = if is_wrapped {
3218 expr.span.with_lo(after_open).with_hi(before_close)
3219 } else {
3220 expr.span
3221 };
3222 self.suggest_method_call(
3223 &mut err,
3224 "use parentheses to call the method",
3225 field,
3226 expr_t,
3227 expr,
3228 Some(span),
3229 );
3230 } else if let ty::RawPtr(ptr_ty, _) = expr_t.kind()
3231 && let ty::Adt(adt_def, _) = ptr_ty.kind()
3232 && let ExprKind::Field(base_expr, _) = expr.kind
3233 && let [variant] = &adt_def.variants().raw
3234 && variant.fields.iter().any(|f| f.ident(self.tcx) == field)
3235 {
3236 err.multipart_suggestion(
3237 "to access the field, dereference first",
3238 vec![
3239 (base_expr.span.shrink_to_lo(), "(*".to_string()),
3240 (base_expr.span.shrink_to_hi(), ")".to_string()),
3241 ],
3242 Applicability::MaybeIncorrect,
3243 );
3244 } else {
3245 err.help("methods are immutable and cannot be assigned to");
3246 }
3247
3248 self.dcx().try_steal_replace_and_emit_err(field.span, StashKey::GenericInFieldExpr, err)
3250 }
3251
3252 fn point_at_param_definition(&self, err: &mut Diag<'_>, param: ty::ParamTy) {
3253 let generics = self.tcx.generics_of(self.body_id);
3254 let generic_param = generics.type_param(param, self.tcx);
3255 if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
3256 return;
3257 }
3258 let param_def_id = generic_param.def_id;
3259 let param_hir_id = match param_def_id.as_local() {
3260 Some(x) => self.tcx.local_def_id_to_hir_id(x),
3261 None => return,
3262 };
3263 let param_span = self.tcx.hir_span(param_hir_id);
3264 let param_name = self.tcx.hir_ty_param_name(param_def_id.expect_local());
3265
3266 err.span_label(param_span, format!("type parameter '{param_name}' declared here"));
3267 }
3268
3269 fn maybe_suggest_array_indexing(
3270 &self,
3271 err: &mut Diag<'_>,
3272 base: &hir::Expr<'_>,
3273 field: Ident,
3274 len: ty::Const<'tcx>,
3275 ) {
3276 err.span_label(field.span, "unknown field");
3277 if let (Some(len), Ok(user_index)) = (
3278 self.try_structurally_resolve_const(base.span, len).try_to_target_usize(self.tcx),
3279 field.as_str().parse::<u64>(),
3280 ) {
3281 let help = "instead of using tuple indexing, use array indexing";
3282 let applicability = if len < user_index {
3283 Applicability::MachineApplicable
3284 } else {
3285 Applicability::MaybeIncorrect
3286 };
3287 err.multipart_suggestion(
3288 help,
3289 vec![
3290 (base.span.between(field.span), "[".to_string()),
3291 (field.span.shrink_to_hi(), "]".to_string()),
3292 ],
3293 applicability,
3294 );
3295 }
3296 }
3297
3298 fn suggest_first_deref_field(&self, err: &mut Diag<'_>, base: &hir::Expr<'_>, field: Ident) {
3299 err.span_label(field.span, "unknown field");
3300 let val = if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span)
3301 && base.len() < 20
3302 {
3303 format!("`{base}`")
3304 } else {
3305 "the value".to_string()
3306 };
3307 err.multipart_suggestion(
3308 format!("{val} is a raw pointer; try dereferencing it"),
3309 vec![
3310 (base.span.shrink_to_lo(), "(*".into()),
3311 (base.span.between(field.span), format!(").")),
3312 ],
3313 Applicability::MaybeIncorrect,
3314 );
3315 }
3316
3317 fn no_such_field_err(
3318 &self,
3319 field: Ident,
3320 base_ty: Ty<'tcx>,
3321 expr: &hir::Expr<'tcx>,
3322 ) -> Diag<'_> {
3323 let span = field.span;
3324 debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, base_ty);
3325
3326 let mut err = self.dcx().create_err(NoFieldOnType { span, ty: base_ty, field });
3327 if base_ty.references_error() {
3328 err.downgrade_to_delayed_bug();
3329 }
3330
3331 if let Some(within_macro_span) = span.within_macro(expr.span, self.tcx.sess.source_map()) {
3332 err.span_label(within_macro_span, "due to this macro variable");
3333 }
3334
3335 let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id();
3337 let (ty, unwrap) = if let ty::Adt(def, args) = base_ty.kind()
3338 && (self.tcx.is_diagnostic_item(sym::Result, def.did())
3339 || self.tcx.is_diagnostic_item(sym::Option, def.did()))
3340 && let Some(arg) = args.get(0)
3341 && let Some(ty) = arg.as_type()
3342 {
3343 (ty, "unwrap().")
3344 } else {
3345 (base_ty, "")
3346 };
3347 for (found_fields, args) in
3348 self.get_field_candidates_considering_privacy_for_diag(span, ty, mod_id, expr.hir_id)
3349 {
3350 let field_names = found_fields.iter().map(|field| field.name).collect::<Vec<_>>();
3351 let mut candidate_fields: Vec<_> = found_fields
3352 .into_iter()
3353 .filter_map(|candidate_field| {
3354 self.check_for_nested_field_satisfying_condition_for_diag(
3355 span,
3356 &|candidate_field, _| candidate_field.ident(self.tcx()) == field,
3357 candidate_field,
3358 args,
3359 vec![],
3360 mod_id,
3361 expr.hir_id,
3362 )
3363 })
3364 .map(|mut field_path| {
3365 field_path.pop();
3366 field_path.iter().map(|id| format!("{}.", id)).collect::<String>()
3367 })
3368 .collect::<Vec<_>>();
3369 candidate_fields.sort();
3370
3371 let len = candidate_fields.len();
3372 if len > 0 && expr.span.eq_ctxt(field.span) {
3375 err.span_suggestions(
3376 field.span.shrink_to_lo(),
3377 format!(
3378 "{} of the expressions' fields {} a field of the same name",
3379 if len > 1 { "some" } else { "one" },
3380 if len > 1 { "have" } else { "has" },
3381 ),
3382 candidate_fields.iter().map(|path| format!("{unwrap}{path}")),
3383 Applicability::MaybeIncorrect,
3384 );
3385 } else if let Some(field_name) =
3386 find_best_match_for_name(&field_names, field.name, None)
3387 {
3388 err.span_suggestion_verbose(
3389 field.span,
3390 "a field with a similar name exists",
3391 format!("{unwrap}{}", field_name),
3392 Applicability::MaybeIncorrect,
3393 );
3394 } else if !field_names.is_empty() {
3395 let is = if field_names.len() == 1 { " is" } else { "s are" };
3396 err.note(
3397 format!("available field{is}: {}", self.name_series_display(field_names),),
3398 );
3399 }
3400 }
3401 err
3402 }
3403
3404 fn private_field_err(&self, field: Ident, base_did: DefId) -> Diag<'_> {
3405 let struct_path = self.tcx().def_path_str(base_did);
3406 let kind_name = self.tcx().def_descr(base_did);
3407 struct_span_code_err!(
3408 self.dcx(),
3409 field.span,
3410 E0616,
3411 "field `{field}` of {kind_name} `{struct_path}` is private",
3412 )
3413 .with_span_label(field.span, "private field")
3414 }
3415
3416 pub(crate) fn get_field_candidates_considering_privacy_for_diag(
3417 &self,
3418 span: Span,
3419 base_ty: Ty<'tcx>,
3420 mod_id: DefId,
3421 hir_id: HirId,
3422 ) -> Vec<(Vec<&'tcx ty::FieldDef>, GenericArgsRef<'tcx>)> {
3423 debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_ty);
3424
3425 let mut autoderef = self.autoderef(span, base_ty).silence_errors();
3426 let deref_chain: Vec<_> = autoderef.by_ref().collect();
3427
3428 if autoderef.reached_recursion_limit() {
3432 return vec![];
3433 }
3434
3435 deref_chain
3436 .into_iter()
3437 .filter_map(move |(base_t, _)| {
3438 match base_t.kind() {
3439 ty::Adt(base_def, args) if !base_def.is_enum() => {
3440 let tcx = self.tcx;
3441 let fields = &base_def.non_enum_variant().fields;
3442 if fields.iter().all(|field| !field.vis.is_accessible_from(mod_id, tcx)) {
3446 return None;
3447 }
3448 return Some((
3449 fields
3450 .iter()
3451 .filter(move |field| {
3452 field.vis.is_accessible_from(mod_id, tcx)
3453 && self.is_field_suggestable(field, hir_id, span)
3454 })
3455 .take(100)
3457 .collect::<Vec<_>>(),
3458 *args,
3459 ));
3460 }
3461 _ => None,
3462 }
3463 })
3464 .collect()
3465 }
3466
3467 pub(crate) fn check_for_nested_field_satisfying_condition_for_diag(
3470 &self,
3471 span: Span,
3472 matches: &impl Fn(&ty::FieldDef, Ty<'tcx>) -> bool,
3473 candidate_field: &ty::FieldDef,
3474 subst: GenericArgsRef<'tcx>,
3475 mut field_path: Vec<Ident>,
3476 mod_id: DefId,
3477 hir_id: HirId,
3478 ) -> Option<Vec<Ident>> {
3479 debug!(
3480 "check_for_nested_field_satisfying(span: {:?}, candidate_field: {:?}, field_path: {:?}",
3481 span, candidate_field, field_path
3482 );
3483
3484 if field_path.len() > 3 {
3485 None
3488 } else {
3489 field_path.push(candidate_field.ident(self.tcx).normalize_to_macros_2_0());
3490 let field_ty = candidate_field.ty(self.tcx, subst);
3491 if matches(candidate_field, field_ty) {
3492 return Some(field_path);
3493 } else {
3494 for (nested_fields, subst) in self
3495 .get_field_candidates_considering_privacy_for_diag(
3496 span, field_ty, mod_id, hir_id,
3497 )
3498 {
3499 for field in nested_fields {
3501 if let Some(field_path) = self
3502 .check_for_nested_field_satisfying_condition_for_diag(
3503 span,
3504 matches,
3505 field,
3506 subst,
3507 field_path.clone(),
3508 mod_id,
3509 hir_id,
3510 )
3511 {
3512 return Some(field_path);
3513 }
3514 }
3515 }
3516 }
3517 None
3518 }
3519 }
3520
3521 fn check_expr_index(
3522 &self,
3523 base: &'tcx hir::Expr<'tcx>,
3524 idx: &'tcx hir::Expr<'tcx>,
3525 expr: &'tcx hir::Expr<'tcx>,
3526 brackets_span: Span,
3527 ) -> Ty<'tcx> {
3528 let base_t = self.check_expr(base);
3529 let idx_t = self.check_expr(idx);
3530
3531 if base_t.references_error() {
3532 base_t
3533 } else if idx_t.references_error() {
3534 idx_t
3535 } else {
3536 let base_t = self.structurally_resolve_type(base.span, base_t);
3537 match self.lookup_indexing(expr, base, base_t, idx, idx_t) {
3538 Some((index_ty, element_ty)) => {
3539 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3541 self.select_obligations_where_possible(|errors| {
3542 self.point_at_index(errors, idx.span);
3543 });
3544 element_ty
3545 }
3546 None => {
3547 for (base_t, _) in self.autoderef(base.span, base_t).silence_errors() {
3550 if let Some((_, index_ty, element_ty)) =
3551 self.find_and_report_unsatisfied_index_impl(base, base_t)
3552 {
3553 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3554 return element_ty;
3555 }
3556 }
3557
3558 let mut err = type_error_struct!(
3559 self.dcx(),
3560 brackets_span,
3561 base_t,
3562 E0608,
3563 "cannot index into a value of type `{base_t}`",
3564 );
3565 if let ty::Tuple(types) = base_t.kind() {
3567 let mut needs_note = true;
3568 if let ExprKind::Lit(lit) = idx.kind
3571 && let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node
3572 && i.get()
3573 < types
3574 .len()
3575 .try_into()
3576 .expect("expected tuple index to be < usize length")
3577 {
3578 err.span_suggestion(
3579 brackets_span,
3580 "to access tuple elements, use",
3581 format!(".{i}"),
3582 Applicability::MachineApplicable,
3583 );
3584 needs_note = false;
3585 } else if let ExprKind::Path(..) = idx.peel_borrows().kind {
3586 err.span_label(
3587 idx.span,
3588 "cannot access tuple elements at a variable index",
3589 );
3590 }
3591 if needs_note {
3592 err.help(
3593 "to access tuple elements, use tuple indexing \
3594 syntax (e.g., `tuple.0`)",
3595 );
3596 }
3597 }
3598
3599 if base_t.is_raw_ptr() && idx_t.is_integral() {
3600 err.multipart_suggestion(
3601 "consider using `wrapping_add` or `add` for indexing into raw pointer",
3602 vec![
3603 (base.span.between(idx.span), ".wrapping_add(".to_owned()),
3604 (
3605 idx.span.shrink_to_hi().until(expr.span.shrink_to_hi()),
3606 ")".to_owned(),
3607 ),
3608 ],
3609 Applicability::MaybeIncorrect,
3610 );
3611 }
3612
3613 let reported = err.emit();
3614 Ty::new_error(self.tcx, reported)
3615 }
3616 }
3617 }
3618 }
3619
3620 fn find_and_report_unsatisfied_index_impl(
3628 &self,
3629 base_expr: &hir::Expr<'_>,
3630 base_ty: Ty<'tcx>,
3631 ) -> Option<(ErrorGuaranteed, Ty<'tcx>, Ty<'tcx>)> {
3632 let index_trait_def_id = self.tcx.lang_items().index_trait()?;
3633 let index_trait_output_def_id = self.tcx.get_diagnostic_item(sym::IndexOutput)?;
3634
3635 let mut relevant_impls = vec![];
3636 self.tcx.for_each_relevant_impl(index_trait_def_id, base_ty, |impl_def_id| {
3637 relevant_impls.push(impl_def_id);
3638 });
3639 let [impl_def_id] = relevant_impls[..] else {
3640 return None;
3642 };
3643
3644 self.commit_if_ok(|snapshot| {
3645 let outer_universe = self.universe();
3646
3647 let ocx = ObligationCtxt::new_with_diagnostics(self);
3648 let impl_args = self.fresh_args_for_item(base_expr.span, impl_def_id);
3649 let impl_trait_ref =
3650 self.tcx.impl_trait_ref(impl_def_id).unwrap().instantiate(self.tcx, impl_args);
3651 let cause = self.misc(base_expr.span);
3652
3653 let impl_trait_ref = ocx.normalize(&cause, self.param_env, impl_trait_ref);
3656 ocx.eq(&cause, self.param_env, base_ty, impl_trait_ref.self_ty())?;
3657
3658 ocx.register_obligations(traits::predicates_for_generics(
3662 |idx, span| {
3663 cause.clone().derived_cause(
3664 ty::Binder::dummy(ty::TraitPredicate {
3665 trait_ref: impl_trait_ref,
3666 polarity: ty::PredicatePolarity::Positive,
3667 }),
3668 |derived| {
3669 ObligationCauseCode::ImplDerived(Box::new(traits::ImplDerivedCause {
3670 derived,
3671 impl_or_alias_def_id: impl_def_id,
3672 impl_def_predicate_index: Some(idx),
3673 span,
3674 }))
3675 },
3676 )
3677 },
3678 self.param_env,
3679 self.tcx.predicates_of(impl_def_id).instantiate(self.tcx, impl_args),
3680 ));
3681
3682 let element_ty = ocx.normalize(
3685 &cause,
3686 self.param_env,
3687 Ty::new_projection_from_args(
3688 self.tcx,
3689 index_trait_output_def_id,
3690 impl_trait_ref.args,
3691 ),
3692 );
3693
3694 let true_errors = ocx.select_where_possible();
3695
3696 self.leak_check(outer_universe, Some(snapshot))?;
3700
3701 let ambiguity_errors = ocx.select_all_or_error();
3703 if true_errors.is_empty() && !ambiguity_errors.is_empty() {
3704 return Err(NoSolution);
3705 }
3706
3707 Ok::<_, NoSolution>((
3710 self.err_ctxt().report_fulfillment_errors(true_errors),
3711 impl_trait_ref.args.type_at(1),
3712 element_ty,
3713 ))
3714 })
3715 .ok()
3716 }
3717
3718 fn point_at_index(&self, errors: &mut Vec<traits::FulfillmentError<'tcx>>, span: Span) {
3719 let mut seen_preds = FxHashSet::default();
3720 errors.sort_by_key(|error| error.root_obligation.recursion_depth);
3724 for error in errors {
3725 match (
3726 error.root_obligation.predicate.kind().skip_binder(),
3727 error.obligation.predicate.kind().skip_binder(),
3728 ) {
3729 (ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)), _)
3730 if self.tcx.is_lang_item(predicate.trait_ref.def_id, LangItem::Index) =>
3731 {
3732 seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3733 }
3734 (_, ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)))
3735 if self.tcx.is_diagnostic_item(sym::SliceIndex, predicate.trait_ref.def_id) =>
3736 {
3737 seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3738 }
3739 (root, pred) if seen_preds.contains(&pred) || seen_preds.contains(&root) => {}
3740 _ => continue,
3741 }
3742 error.obligation.cause.span = span;
3743 }
3744 }
3745
3746 fn check_expr_yield(
3747 &self,
3748 value: &'tcx hir::Expr<'tcx>,
3749 expr: &'tcx hir::Expr<'tcx>,
3750 ) -> Ty<'tcx> {
3751 match self.coroutine_types {
3752 Some(CoroutineTypes { resume_ty, yield_ty }) => {
3753 self.check_expr_coercible_to_type(value, yield_ty, None);
3754
3755 resume_ty
3756 }
3757 _ => {
3758 self.dcx().emit_err(YieldExprOutsideOfCoroutine { span: expr.span });
3759 self.check_expr(value);
3761 self.tcx.types.unit
3762 }
3763 }
3764 }
3765
3766 fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
3767 let needs = if is_input { Needs::None } else { Needs::MutPlace };
3768 let ty = self.check_expr_with_needs(expr, needs);
3769 self.require_type_is_sized(ty, expr.span, ObligationCauseCode::InlineAsmSized);
3770
3771 if !is_input && !expr.is_syntactic_place_expr() {
3772 self.dcx()
3773 .struct_span_err(expr.span, "invalid asm output")
3774 .with_span_label(expr.span, "cannot assign to this expression")
3775 .emit();
3776 }
3777
3778 if is_input {
3786 let ty = self.structurally_resolve_type(expr.span, ty);
3787 match *ty.kind() {
3788 ty::FnDef(..) => {
3789 let fnptr_ty = Ty::new_fn_ptr(self.tcx, ty.fn_sig(self.tcx));
3790 self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
3791 }
3792 ty::Ref(_, base_ty, mutbl) => {
3793 let ptr_ty = Ty::new_ptr(self.tcx, base_ty, mutbl);
3794 self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
3795 }
3796 _ => {}
3797 }
3798 }
3799 }
3800
3801 fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>) -> Ty<'tcx> {
3802 let mut diverge = asm.asm_macro.diverges(asm.options);
3803
3804 for (op, _op_sp) in asm.operands {
3805 match *op {
3806 hir::InlineAsmOperand::In { expr, .. } => {
3807 self.check_expr_asm_operand(expr, true);
3808 }
3809 hir::InlineAsmOperand::Out { expr: Some(expr), .. }
3810 | hir::InlineAsmOperand::InOut { expr, .. } => {
3811 self.check_expr_asm_operand(expr, false);
3812 }
3813 hir::InlineAsmOperand::Out { expr: None, .. } => {}
3814 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
3815 self.check_expr_asm_operand(in_expr, true);
3816 if let Some(out_expr) = out_expr {
3817 self.check_expr_asm_operand(out_expr, false);
3818 }
3819 }
3820 hir::InlineAsmOperand::Const { ref anon_const } => {
3821 self.check_expr_const_block(anon_const, Expectation::NoExpectation);
3822 }
3823 hir::InlineAsmOperand::SymFn { expr } => {
3824 self.check_expr(expr);
3825 }
3826 hir::InlineAsmOperand::SymStatic { .. } => {}
3827 hir::InlineAsmOperand::Label { block } => {
3828 let previous_diverges = self.diverges.get();
3829
3830 let ty = self.check_expr_block(block, ExpectHasType(self.tcx.types.unit));
3832 if !ty.is_never() {
3833 self.demand_suptype(block.span, self.tcx.types.unit, ty);
3834 diverge = false;
3835 }
3836
3837 self.diverges.set(previous_diverges);
3839 }
3840 }
3841 }
3842
3843 if diverge { self.tcx.types.never } else { self.tcx.types.unit }
3844 }
3845
3846 fn check_expr_offset_of(
3847 &self,
3848 container: &'tcx hir::Ty<'tcx>,
3849 fields: &[Ident],
3850 expr: &'tcx hir::Expr<'tcx>,
3851 ) -> Ty<'tcx> {
3852 let container = self.lower_ty(container).normalized;
3853
3854 let mut field_indices = Vec::with_capacity(fields.len());
3855 let mut current_container = container;
3856 let mut fields = fields.into_iter();
3857
3858 while let Some(&field) = fields.next() {
3859 let container = self.structurally_resolve_type(expr.span, current_container);
3860
3861 match container.kind() {
3862 ty::Adt(container_def, args) if container_def.is_enum() => {
3863 let block = self.tcx.local_def_id_to_hir_id(self.body_id);
3864 let (ident, _def_scope) =
3865 self.tcx.adjust_ident_and_get_scope(field, container_def.did(), block);
3866
3867 if !self.tcx.features().offset_of_enum() {
3868 rustc_session::parse::feature_err(
3869 &self.tcx.sess,
3870 sym::offset_of_enum,
3871 ident.span,
3872 "using enums in offset_of is experimental",
3873 )
3874 .emit();
3875 }
3876
3877 let Some((index, variant)) = container_def
3878 .variants()
3879 .iter_enumerated()
3880 .find(|(_, v)| v.ident(self.tcx).normalize_to_macros_2_0() == ident)
3881 else {
3882 self.dcx()
3883 .create_err(NoVariantNamed { span: ident.span, ident, ty: container })
3884 .with_span_label(field.span, "variant not found")
3885 .emit_unless(container.references_error());
3886 break;
3887 };
3888 let Some(&subfield) = fields.next() else {
3889 type_error_struct!(
3890 self.dcx(),
3891 ident.span,
3892 container,
3893 E0795,
3894 "`{ident}` is an enum variant; expected field at end of `offset_of`",
3895 )
3896 .with_span_label(field.span, "enum variant")
3897 .emit();
3898 break;
3899 };
3900 let (subident, sub_def_scope) =
3901 self.tcx.adjust_ident_and_get_scope(subfield, variant.def_id, block);
3902
3903 let Some((subindex, field)) = variant
3904 .fields
3905 .iter_enumerated()
3906 .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == subident)
3907 else {
3908 self.dcx()
3909 .create_err(NoFieldOnVariant {
3910 span: ident.span,
3911 container,
3912 ident,
3913 field: subfield,
3914 enum_span: field.span,
3915 field_span: subident.span,
3916 })
3917 .emit_unless(container.references_error());
3918 break;
3919 };
3920
3921 let field_ty = self.field_ty(expr.span, field, args);
3922
3923 self.require_type_is_sized(
3926 field_ty,
3927 expr.span,
3928 ObligationCauseCode::FieldSized {
3929 adt_kind: AdtKind::Enum,
3930 span: self.tcx.def_span(field.did),
3931 last: false,
3932 },
3933 );
3934
3935 if field.vis.is_accessible_from(sub_def_scope, self.tcx) {
3936 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3937 } else {
3938 self.private_field_err(ident, container_def.did()).emit();
3939 }
3940
3941 field_indices.push((index, subindex));
3944 current_container = field_ty;
3945
3946 continue;
3947 }
3948 ty::Adt(container_def, args) => {
3949 let block = self.tcx.local_def_id_to_hir_id(self.body_id);
3950 let (ident, def_scope) =
3951 self.tcx.adjust_ident_and_get_scope(field, container_def.did(), block);
3952
3953 let fields = &container_def.non_enum_variant().fields;
3954 if let Some((index, field)) = fields
3955 .iter_enumerated()
3956 .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == ident)
3957 {
3958 let field_ty = self.field_ty(expr.span, field, args);
3959
3960 if self.tcx.features().offset_of_slice() {
3961 self.require_type_has_static_alignment(field_ty, expr.span);
3962 } else {
3963 self.require_type_is_sized(
3964 field_ty,
3965 expr.span,
3966 ObligationCauseCode::Misc,
3967 );
3968 }
3969
3970 if field.vis.is_accessible_from(def_scope, self.tcx) {
3971 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3972 } else {
3973 self.private_field_err(ident, container_def.did()).emit();
3974 }
3975
3976 field_indices.push((FIRST_VARIANT, index));
3979 current_container = field_ty;
3980
3981 continue;
3982 }
3983 }
3984 ty::Tuple(tys) => {
3985 if let Ok(index) = field.as_str().parse::<usize>()
3986 && field.name == sym::integer(index)
3987 {
3988 if let Some(&field_ty) = tys.get(index) {
3989 if self.tcx.features().offset_of_slice() {
3990 self.require_type_has_static_alignment(field_ty, expr.span);
3991 } else {
3992 self.require_type_is_sized(
3993 field_ty,
3994 expr.span,
3995 ObligationCauseCode::Misc,
3996 );
3997 }
3998
3999 field_indices.push((FIRST_VARIANT, index.into()));
4000 current_container = field_ty;
4001
4002 continue;
4003 }
4004 }
4005 }
4006 _ => (),
4007 };
4008
4009 self.no_such_field_err(field, container, expr).emit();
4010
4011 break;
4012 }
4013
4014 self.typeck_results
4015 .borrow_mut()
4016 .offset_of_data_mut()
4017 .insert(expr.hir_id, (container, field_indices));
4018
4019 self.tcx.types.usize
4020 }
4021}