1use std::borrow::Cow;
9
10use rustc_abi::{FIRST_VARIANT, FieldIdx};
11use rustc_ast as ast;
12use rustc_ast::util::parser::ExprPrecedence;
13use rustc_attr_ir::find_attr;
14use rustc_attr_ir::lang_items::LangItem;
15use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16use rustc_data_structures::thin_vec::ThinVec;
17use rustc_data_structures::unord::UnordMap;
18use rustc_errors::codes::*;
19use rustc_errors::{
20 Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, Subdiagnostic, listify, pluralize,
21 struct_span_code_err,
22};
23use rustc_hir as hir;
24use rustc_hir::def::{CtorKind, DefKind, Res};
25use rustc_hir::def_id::DefId;
26use rustc_hir::{ExprKind, HirId, QPath, is_range_literal};
27use rustc_hir_analysis::diagnostics::{NoFieldOnType, NoVariantNamed};
28use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _;
29use rustc_infer::infer::{self, RegionVariableOrigin};
30use rustc_infer::traits::WellFormedLoc;
31use rustc_infer::traits::query::NoSolution;
32use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
33use rustc_middle::ty::error::{ExpectedFound, TypeError};
34use rustc_middle::ty::{self, AdtKind, ConstKind, GenericArgs, Ty, TypeVisitableExt, Unnormalized};
35use rustc_session::diagnostics::feature_err;
36use rustc_span::edit_distance::find_best_match_for_name;
37use rustc_span::hygiene::DesugaringKind;
38use rustc_span::{Ident, Span, Spanned, Symbol, bug, kw, span_bug, sym};
39use rustc_trait_selection::infer::InferCtxtExt;
40use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt};
41use tracing::{debug, instrument, trace};
42
43use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation};
44use crate::callee::SplatLoweringInfo;
45use crate::coercion::CoerceMany;
46use crate::diagnostics::{
47 AddressOfTemporaryTaken, BaseExpressionDoubleDot, BaseExpressionDoubleDotAddExpr,
48 BaseExpressionDoubleDotRemove, CantDereference, DelegationInvalidAdtForReturnWrapping,
49 ExprParenthesesNeeded, FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct,
50 HelpUseLatestEdition, NakedAsmOutsideNakedFn, NoFieldOnVariant, ReturnLikeStatementKind,
51 ReturnStmtOutsideOfFnBody, StructExprNonExhaustive, TypeMismatchFruTypo,
52 YieldExprOutsideOfCoroutine,
53};
54use crate::op::contains_let_in_chain;
55use crate::{
56 BreakableCtxt, CoroutineTypes, Diverges, FnCtxt, GatherLocalsVisitor, Needs,
57 TupleArgumentsFlag, cast, fatally_break_rust, type_error_struct,
58};
59
60impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
61 pub(crate) fn precedence(&self, expr: &hir::Expr<'_>) -> ExprPrecedence {
62 let has_attr = |id: HirId| -> bool {
63 self.tcx
64 .hir_attrs(id)
65 .iter()
66 .any(rustc_attr_ir::Attribute::is_prefix_attr_for_suggestions)
67 };
68
69 if is_range_literal(expr) {
73 return ExprPrecedence::Range;
74 }
75
76 expr.precedence(&has_attr)
77 }
78
79 pub(crate) fn check_expr_has_type_or_error(
83 &self,
84 expr: &'tcx hir::Expr<'tcx>,
85 expected_ty: Ty<'tcx>,
86 extend_err: impl FnOnce(&mut Diag<'_>),
87 ) -> Ty<'tcx> {
88 let mut ty = self.check_expr_with_expectation(expr, ExpectHasType(expected_ty));
89
90 if self.deeply_resolve_ignoring_regions_with_obligations(ty).is_never()
93 && self.tcx.expr_guaranteed_to_constitute_read_for_never(expr)
94 {
95 if let Some(adjustments) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
96 let reported = self.dcx().span_delayed_bug(
97 expr.span,
98 "expression with never type wound up being adjusted",
99 );
100
101 return if let [Adjustment { kind: Adjust::NeverToAny, target }] = &adjustments[..] {
102 target.to_owned()
103 } else {
104 Ty::new_error(self.tcx(), reported)
105 };
106 }
107
108 let adj_ty = self.next_ty_var(expr.span);
109 self.apply_adjustments(
110 expr,
111 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Adjustment { kind: Adjust::NeverToAny, target: adj_ty }]))vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }],
112 );
113 ty = adj_ty;
114 }
115
116 if let Err(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
117 let _ = self.emit_type_mismatch_suggestions(
118 &mut err,
119 expr.peel_drop_temps(),
120 ty,
121 expected_ty,
122 None,
123 None,
124 );
125 extend_err(&mut err);
126 err.emit();
127 }
128 ty
129 }
130
131 pub(super) fn check_expr_coercible_to_type(
135 &self,
136 expr: &'tcx hir::Expr<'tcx>,
137 expected: Ty<'tcx>,
138 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
139 ) -> Ty<'tcx> {
140 self.check_expr_coercible_to_type_or_error(expr, expected, expected_ty_expr, |_, _| {})
141 }
142
143 pub(crate) fn check_expr_coercible_to_type_or_error(
144 &self,
145 expr: &'tcx hir::Expr<'tcx>,
146 expected: Ty<'tcx>,
147 expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
148 extend_err: impl FnOnce(&mut Diag<'_>, Ty<'tcx>),
149 ) -> Ty<'tcx> {
150 let ty = self.check_expr_with_hint(expr, expected);
151 match self.demand_coerce_diag(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No) {
153 Ok(ty) => ty,
154 Err(mut err) => {
155 extend_err(&mut err, ty);
156 err.emit();
157 expected
161 }
162 }
163 }
164
165 pub(super) fn check_expr_with_hint(
170 &self,
171 expr: &'tcx hir::Expr<'tcx>,
172 expected: Ty<'tcx>,
173 ) -> Ty<'tcx> {
174 self.check_expr_with_expectation(expr, ExpectHasType(expected))
175 }
176
177 fn check_expr_with_expectation_and_needs(
180 &self,
181 expr: &'tcx hir::Expr<'tcx>,
182 expected: Expectation<'tcx>,
183 needs: Needs,
184 ) -> Ty<'tcx> {
185 let ty = self.check_expr_with_expectation(expr, expected);
186
187 if let Needs::MutPlace = needs {
190 self.convert_place_derefs_to_mutable(expr);
191 }
192
193 ty
194 }
195
196 pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
198 self.check_expr_with_expectation(expr, NoExpectation)
199 }
200
201 pub(super) fn check_expr_with_needs(
204 &self,
205 expr: &'tcx hir::Expr<'tcx>,
206 needs: Needs,
207 ) -> Ty<'tcx> {
208 self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
209 }
210
211 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_expr_with_expectation",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(213u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected")
}> =
::tracing::__macro_support::FieldName::new("expected");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{ self.check_expr_with_expectation_and_args(expr, expected, None) }
}
}#[instrument(skip(self, expr), level = "debug")]
214 pub(super) fn check_expr_with_expectation(
215 &self,
216 expr: &'tcx hir::Expr<'tcx>,
217 expected: Expectation<'tcx>,
218 ) -> Ty<'tcx> {
219 self.check_expr_with_expectation_and_args(expr, expected, None)
220 }
221
222 pub(super) fn check_expr_with_expectation_and_args(
227 &self,
228 expr: &'tcx hir::Expr<'tcx>,
229 expected: Expectation<'tcx>,
230 call_expr_and_args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
231 ) -> Ty<'tcx> {
232 if self.tcx().sess.verbose_internals() {
233 if let Ok(lint_str) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
235 if !lint_str.contains('\n') {
236 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:236",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(236u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("expr text: {0}",
lint_str) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("expr text: {lint_str}");
237 } else {
238 let mut lines = lint_str.lines();
239 if let Some(line0) = lines.next() {
240 let remaining_lines = lines.count();
241 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:241",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(241u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("expr text: {0}",
line0) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("expr text: {line0}");
242 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:242",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(242u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("expr text: ...(and {0} more lines)",
remaining_lines) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("expr text: ...(and {remaining_lines} more lines)");
243 }
244 }
245 }
246 }
247
248 let is_try_block_generated_unit_expr = match expr.kind {
252 ExprKind::Call(_, [arg]) => {
253 expr.span.is_desugaring(DesugaringKind::TryBlock)
254 && arg.span.is_desugaring(DesugaringKind::TryBlock)
255 }
256 _ => false,
257 };
258
259 if !is_try_block_generated_unit_expr {
261 self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
262 }
263
264 let old_diverges = self.diverges.replace(Diverges::Maybe);
267
268 if self.is_whole_body.replace(false) {
269 self.diverges.set(self.function_diverges_because_of_empty_arguments.get())
272 };
273
274 let ty = match &expr.kind {
275 hir::ExprKind::Path(
277 qpath @ (hir::QPath::Resolved(..) | hir::QPath::TypeRelative(..)),
278 ) => self.check_expr_path(qpath, expr, call_expr_and_args),
279 _ => self.check_expr_kind(expr, expected),
280 };
281 let ty = self.deeply_resolve_ignoring_regions(ty);
282
283 match expr.kind {
285 ExprKind::Block(..)
286 | ExprKind::If(..)
287 | ExprKind::Let(..)
288 | ExprKind::Loop(..)
289 | ExprKind::Match(..)
290 | ExprKind::Become(..) => {}
291 ExprKind::Cast(_, _) => {}
294 ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {}
298 ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::Contract) => {}
300 ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"),
301 ExprKind::MethodCall(segment, ..) => {
302 self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call")
303 }
304 _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
305 }
306
307 if self.deeply_resolve_ignoring_regions_with_obligations(ty).is_never()
312 && self.tcx.expr_guaranteed_to_constitute_read_for_never(expr)
313 {
314 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
315 }
316
317 self.write_ty(expr.hir_id, ty);
321
322 self.diverges.set(self.diverges.get() | old_diverges);
324
325 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:325",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(325u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("type of {0} is...",
self.tcx.hir_id_to_string(expr.hir_id)) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("type of {} is...", self.tcx.hir_id_to_string(expr.hir_id));
326 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:326",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(326u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("... {0:?}, expected is {1:?}",
ty, expected) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("... {:?}, expected is {:?}", ty, expected);
327
328 ty
329 }
330
331 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_expr_kind",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(331u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expected")
}> =
::tracing::__macro_support::FieldName::new("expected");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:337",
"rustc_hir_typeck::expr", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(337u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("expr={0:#?}",
expr) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let tcx = self.tcx;
match expr.kind {
ExprKind::Lit(ref lit) =>
self.check_expr_lit(lit, expr.hir_id, expected),
ExprKind::Binary(op, lhs, rhs) =>
self.check_expr_binop(expr, op, lhs, rhs, expected),
ExprKind::Assign(lhs, rhs, span) => {
self.check_expr_assign(expr, expected, lhs, rhs, span)
}
ExprKind::AssignOp(op, lhs, rhs) => {
self.check_expr_assign_op(expr, op, lhs, rhs, expected)
}
ExprKind::Unary(unop, oprnd) =>
self.check_expr_unop(unop, oprnd, expected, expr),
ExprKind::AddrOf(kind, mutbl, oprnd) => {
self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
}
ExprKind::Path(ref qpath) =>
self.check_expr_path(qpath, expr, None),
ExprKind::InlineAsm(asm) => {
self.deferred_asm_checks.borrow_mut().push((asm,
expr.hir_id));
self.check_expr_asm(asm, expr.span)
}
ExprKind::OffsetOf(container, fields) => {
self.check_expr_offset_of(container, fields, expr)
}
ExprKind::Break(destination, ref expr_opt) => {
self.check_expr_break(destination, expr_opt.as_deref(),
expr)
}
ExprKind::Continue(destination) =>
self.check_expr_continue(destination, expr),
ExprKind::Ret(ref expr_opt) =>
self.check_expr_return(expr_opt.as_deref(), expr),
ExprKind::Become(call) => self.check_expr_become(call, expr),
ExprKind::Let(let_expr) =>
self.check_expr_let(let_expr, expr.hir_id),
ExprKind::Loop(body, _, source, _) => {
self.check_expr_loop(body, source, expected, expr)
}
ExprKind::Match(discrim, arms, match_src) => {
self.check_expr_match(expr, discrim, arms, expected,
match_src)
}
ExprKind::Closure(closure) =>
self.check_expr_closure(closure, expr.span, expected),
ExprKind::Block(body, _) =>
self.check_expr_block(body, expected),
ExprKind::Call(callee, args) =>
self.check_expr_call(expr, callee, args, expected),
ExprKind::Use(used_expr, _) =>
self.check_expr_use(used_expr, expected),
ExprKind::MethodCall(segment, receiver, args, _) => {
self.check_expr_method_call(expr, segment, receiver, args,
expected)
}
ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr),
ExprKind::Type(e, t) => {
let ascribed_ty = self.lower_ty_saving_user_provided_ty(t);
let ty = self.check_expr_with_hint(e, ascribed_ty);
self.demand_eqtype(e.span, ascribed_ty, ty);
ascribed_ty
}
ExprKind::If(cond, then_expr, opt_else_expr) => {
self.check_expr_if(expr.hir_id, cond, then_expr,
opt_else_expr, expr.span, expected)
}
ExprKind::DropTemps(e) =>
self.check_expr_with_expectation(e, expected),
ExprKind::Array(args) =>
self.check_expr_array(args, expected, expr),
ExprKind::ConstBlock(ref block) =>
self.check_expr_const_block(block, expected),
ExprKind::Repeat(element, ref count) => {
self.check_expr_repeat(element, count, expected, expr)
}
ExprKind::Tup(elts) =>
self.check_expr_tuple(elts, expected, expr),
ExprKind::Struct(qpath, fields, ref base_expr) => {
self.check_expr_struct(expr, expected, qpath, fields,
base_expr)
}
ExprKind::Field(base, field) =>
self.check_expr_field(expr, base, field, expected),
ExprKind::Index(base, idx, brackets_span) => {
self.check_expr_index(base, idx, expr, brackets_span)
}
ExprKind::Yield(value, _) =>
self.check_expr_yield(value, expr),
ExprKind::UnsafeBinderCast(kind, inner_expr, ty) => {
self.check_expr_unsafe_binder_cast(expr.span, kind,
inner_expr, ty, expected)
}
ExprKind::Err(guar) => Ty::new_error(tcx, guar),
}
}
}
}#[instrument(skip(self, expr), level = "debug")]
332 fn check_expr_kind(
333 &self,
334 expr: &'tcx hir::Expr<'tcx>,
335 expected: Expectation<'tcx>,
336 ) -> Ty<'tcx> {
337 trace!("expr={:#?}", expr);
338
339 let tcx = self.tcx;
340 match expr.kind {
341 ExprKind::Lit(ref lit) => self.check_expr_lit(lit, expr.hir_id, expected),
342 ExprKind::Binary(op, lhs, rhs) => self.check_expr_binop(expr, op, lhs, rhs, expected),
343 ExprKind::Assign(lhs, rhs, span) => {
344 self.check_expr_assign(expr, expected, lhs, rhs, span)
345 }
346 ExprKind::AssignOp(op, lhs, rhs) => {
347 self.check_expr_assign_op(expr, op, lhs, rhs, expected)
348 }
349 ExprKind::Unary(unop, oprnd) => self.check_expr_unop(unop, oprnd, expected, expr),
350 ExprKind::AddrOf(kind, mutbl, oprnd) => {
351 self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
352 }
353 ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr, None),
354 ExprKind::InlineAsm(asm) => {
355 self.deferred_asm_checks.borrow_mut().push((asm, expr.hir_id));
357 self.check_expr_asm(asm, expr.span)
358 }
359 ExprKind::OffsetOf(container, fields) => {
360 self.check_expr_offset_of(container, fields, expr)
361 }
362 ExprKind::Break(destination, ref expr_opt) => {
363 self.check_expr_break(destination, expr_opt.as_deref(), expr)
364 }
365 ExprKind::Continue(destination) => self.check_expr_continue(destination, expr),
366 ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
367 ExprKind::Become(call) => self.check_expr_become(call, expr),
368 ExprKind::Let(let_expr) => self.check_expr_let(let_expr, expr.hir_id),
369 ExprKind::Loop(body, _, source, _) => {
370 self.check_expr_loop(body, source, expected, expr)
371 }
372 ExprKind::Match(discrim, arms, match_src) => {
373 self.check_expr_match(expr, discrim, arms, expected, match_src)
374 }
375 ExprKind::Closure(closure) => self.check_expr_closure(closure, expr.span, expected),
376 ExprKind::Block(body, _) => self.check_expr_block(body, expected),
377 ExprKind::Call(callee, args) => self.check_expr_call(expr, callee, args, expected),
378 ExprKind::Use(used_expr, _) => self.check_expr_use(used_expr, expected),
379 ExprKind::MethodCall(segment, receiver, args, _) => {
380 self.check_expr_method_call(expr, segment, receiver, args, expected)
381 }
382 ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr),
383 ExprKind::Type(e, t) => {
384 let ascribed_ty = self.lower_ty_saving_user_provided_ty(t);
385 let ty = self.check_expr_with_hint(e, ascribed_ty);
386 self.demand_eqtype(e.span, ascribed_ty, ty);
387 ascribed_ty
388 }
389 ExprKind::If(cond, then_expr, opt_else_expr) => {
390 self.check_expr_if(expr.hir_id, cond, then_expr, opt_else_expr, expr.span, expected)
391 }
392 ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected),
393 ExprKind::Array(args) => self.check_expr_array(args, expected, expr),
394 ExprKind::ConstBlock(ref block) => self.check_expr_const_block(block, expected),
395 ExprKind::Repeat(element, ref count) => {
396 self.check_expr_repeat(element, count, expected, expr)
397 }
398 ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr),
399 ExprKind::Struct(qpath, fields, ref base_expr) => {
400 self.check_expr_struct(expr, expected, qpath, fields, base_expr)
401 }
402 ExprKind::Field(base, field) => self.check_expr_field(expr, base, field, expected),
403 ExprKind::Index(base, idx, brackets_span) => {
404 self.check_expr_index(base, idx, expr, brackets_span)
405 }
406 ExprKind::Yield(value, _) => self.check_expr_yield(value, expr),
407 ExprKind::UnsafeBinderCast(kind, inner_expr, ty) => {
408 self.check_expr_unsafe_binder_cast(expr.span, kind, inner_expr, ty, expected)
409 }
410 ExprKind::Err(guar) => Ty::new_error(tcx, guar),
411 }
412 }
413
414 fn check_expr_unop(
415 &self,
416 unop: hir::UnOp,
417 oprnd: &'tcx hir::Expr<'tcx>,
418 expected: Expectation<'tcx>,
419 expr: &'tcx hir::Expr<'tcx>,
420 ) -> Ty<'tcx> {
421 let tcx = self.tcx;
422 let expected_inner = match unop {
423 hir::UnOp::Not | hir::UnOp::Neg => expected,
424 hir::UnOp::Deref => NoExpectation,
425 };
426 let oprnd_t = self.check_expr_with_expectation(oprnd, expected_inner);
427
428 if let Err(guar) = oprnd_t.error_reported() {
429 return Ty::new_error(tcx, guar);
430 }
431
432 match unop {
436 hir::UnOp::Deref => {
437 let oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t);
442 self.lookup_derefing(expr, oprnd, oprnd_t).unwrap_or_else(|| {
443 let mut err =
444 self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t });
445 let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None);
446 if let Some(sp) =
447 tcx.sess.psess.complete_stmt_exprs_before_bin_op_lookalike.borrow().get(&sp)
448 {
449 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
450 }
451 self.suggest_fn_call(&mut err, oprnd, oprnd_t, |output| {
455 output.builtin_deref(true).is_some()
456 || self.tcx.lang_items().deref_trait().is_some_and(|deref_trait| {
457 self.type_implements_trait(deref_trait, [output], self.param_env)
458 .may_apply()
459 })
460 });
461 Ty::new_error(tcx, err.emit_err())
462 })
463 }
464 hir::UnOp::Not => {
465 let oprnd_t = self.deeply_resolve_ignoring_regions_with_obligations(oprnd_t);
466 let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
467 if oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool { oprnd_t } else { result }
469 }
470 hir::UnOp::Neg => {
471 let oprnd_t = self.deeply_resolve_ignoring_regions_with_obligations(oprnd_t);
472 let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
473 if oprnd_t.is_numeric() { oprnd_t } else { result }
475 }
476 }
477 }
478
479 fn check_expr_addr_of(
480 &self,
481 kind: hir::BorrowKind,
482 mutbl: hir::Mutability,
483 oprnd: &'tcx hir::Expr<'tcx>,
484 expected: Expectation<'tcx>,
485 expr: &'tcx hir::Expr<'tcx>,
486 ) -> Ty<'tcx> {
487 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
488 match self.deeply_resolve_ignoring_regions_with_obligations(ty).kind() {
489 ty::Ref(_, ty, _) | ty::RawPtr(ty, _) => {
490 if oprnd.is_syntactic_place_expr() {
491 ExpectHasType(*ty)
495 } else {
496 Expectation::rvalue_hint(self, *ty)
497 }
498 }
499 _ => NoExpectation,
500 }
501 });
502 let ty =
503 self.check_expr_with_expectation_and_needs(oprnd, hint, Needs::maybe_mut_place(mutbl));
504 if let Err(guar) = ty.error_reported() {
505 return Ty::new_error(self.tcx, guar);
506 }
507
508 match kind {
509 hir::BorrowKind::Raw => {
510 self.check_named_place_expr(oprnd);
511 Ty::new_ptr(self.tcx, ty, mutbl)
512 }
513 hir::BorrowKind::Ref | hir::BorrowKind::Pin => {
514 let region = self.next_region_var(RegionVariableOrigin::BorrowRegion(expr.span));
529 match kind {
530 hir::BorrowKind::Ref => Ty::new_ref(self.tcx, region, ty, mutbl),
531 hir::BorrowKind::Pin => Ty::new_pinned_ref(self.tcx, region, ty, mutbl),
532 _ => ::core::panicking::unreachable_default_msg()unreachable!(),
533 }
534 }
535 }
536 }
537
538 fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
544 let is_named = oprnd.is_place_expr(|base| {
545 self.typeck_results
557 .borrow()
558 .adjustments()
559 .get(base.hir_id)
560 .is_some_and(|x| x.iter().any(|adj| #[allow(non_exhaustive_omitted_patterns)] match adj.kind {
Adjust::Deref(_) => true,
_ => false,
}matches!(adj.kind, Adjust::Deref(_))))
561 });
562 if !is_named {
563 self.dcx().emit_err(AddressOfTemporaryTaken { span: oprnd.span });
564 }
565 }
566
567 pub(crate) fn check_expr_path(
568 &self,
569 qpath: &'tcx hir::QPath<'tcx>,
570 expr: &'tcx hir::Expr<'tcx>,
571 call_expr_and_args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
572 ) -> Ty<'tcx> {
573 let tcx = self.tcx;
574
575 if let Some((_, [arg])) = call_expr_and_args
576 && let QPath::Resolved(_, path) = qpath
577 && let Res::Def(_, def_id) = path.res
578 && let Some(lang_item) = tcx.lang_items().from_def_id(def_id)
579 {
580 let code = match lang_item {
581 LangItem::IntoFutureIntoFuture
582 if expr.span.is_desugaring(DesugaringKind::Await) =>
583 {
584 Some(ObligationCauseCode::AwaitableExpr(arg.hir_id))
585 }
586 LangItem::IntoIterIntoIter | LangItem::IteratorNext
587 if expr.span.is_desugaring(DesugaringKind::ForLoop) =>
588 {
589 Some(ObligationCauseCode::ForLoopIterator(arg.hir_id))
590 }
591 LangItem::TryTraitFromOutput
592 if expr.span.is_desugaring(DesugaringKind::TryBlock) =>
593 {
594 Some(ObligationCauseCode::QuestionMark)
596 }
597 LangItem::TryTraitBranch | LangItem::TryTraitFromResidual
598 if expr.span.is_desugaring(DesugaringKind::QuestionMark) =>
599 {
600 Some(ObligationCauseCode::QuestionMark)
601 }
602 _ => None,
603 };
604 if let Some(code) = code {
605 let args = self.fresh_args_for_item(expr.span, def_id);
606 self.add_required_obligations_with_code(expr.span, def_id, args, |_, _| {
607 code.clone()
608 });
609 return tcx.type_of(def_id).instantiate(tcx, args).skip_norm_wip();
610 }
611 }
612
613 let (res, opt_ty, segs) =
614 self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span);
615 let ty = match res {
616 Res::Err => {
617 self.suggest_assoc_method_call(segs);
618 let e =
619 self.dcx().span_delayed_bug(qpath.span(), "`Res::Err` but no error emitted");
620 Ty::new_error(tcx, e)
621 }
622 Res::Def(DefKind::Variant, _) => {
623 let e = self.report_unexpected_variant_res(
624 res,
625 Some(expr),
626 &[],
627 qpath,
628 expr.span,
629 E0533,
630 "value",
631 );
632 Ty::new_error(tcx, e)
633 }
634 _ => {
635 self.instantiate_value_path(
636 segs,
637 opt_ty,
638 res,
639 call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
640 expr.span,
641 expr.hir_id,
642 call_expr_and_args.map(|(_, args)| args),
643 )
644 .0
645 }
646 };
647
648 if let ty::FnDef(did, args) = *ty.kind() {
649 let fn_sig = ty.fn_sig(tcx);
650
651 if tcx.is_intrinsic(did, sym::transmute) {
652 let Some(from) = fn_sig.inputs().skip_binder().get(0) else {
653 ::rustc_span::macros::bug_impl(Some(tcx.def_span(did)),
format_args!("intrinsic fn `transmute` defined with no parameters"),
Location::caller());span_bug!(
654 tcx.def_span(did),
655 "intrinsic fn `transmute` defined with no parameters"
656 );
657 };
658 let to = fn_sig.output().skip_binder();
659 self.deferred_transmute_checks.borrow_mut().push((*from, to, expr.hir_id));
664 }
665 if !tcx.sess.opts.unstable_opts.offload.is_empty()
666 && tcx.is_intrinsic(did, sym::offload)
667 {
668 let args = args.skip_binder();
669 let f = args.type_at(0);
670 let t = args.type_at(1);
671 let r = args.type_at(2);
672 self.deferred_offload_checks.borrow_mut().push((f, t, r, expr.hir_id));
674 }
675 if !tcx.features().unsized_fn_params() {
676 for i in 0..fn_sig.inputs().skip_binder().len() {
686 let span = call_expr_and_args
690 .and_then(|(_, args)| args.get(i))
691 .map_or(expr.span, |arg| arg.span);
692 let input = self.instantiate_binder_with_fresh_vars(
693 span,
694 infer::BoundRegionConversionTime::FnCall,
695 fn_sig.input(i),
696 );
697 self.require_type_is_sized_deferred(
698 input,
699 span,
700 ObligationCauseCode::SizedArgumentType(None),
701 );
702 }
703 }
704 let output = self.instantiate_binder_with_fresh_vars(
710 expr.span,
711 infer::BoundRegionConversionTime::FnCall,
712 fn_sig.output(),
713 );
714 self.require_type_is_sized_deferred(
715 output,
716 call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
717 ObligationCauseCode::SizedCallReturnType(expr.hir_id),
718 );
719 }
720
721 let args = self.typeck_results.borrow().node_args(expr.hir_id);
724 self.add_wf_bounds(args, expr.span, expr.hir_id);
725
726 ty
727 }
728
729 fn check_expr_break(
730 &self,
731 destination: hir::Destination,
732 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
733 expr: &'tcx hir::Expr<'tcx>,
734 ) -> Ty<'tcx> {
735 let tcx = self.tcx;
736 if let Ok(target_id) = destination.target_id {
737 let (e_ty, cause);
738 if let Some(e) = expr_opt {
739 let opt_coerce_to = {
742 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
746 match enclosing_breakables.opt_find_breakable(target_id) {
747 Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
748 None => {
749 return Ty::new_error_with_message(
751 tcx,
752 expr.span,
753 "break was outside loop, but no error was emitted",
754 );
755 }
756 }
757 };
758
759 let coerce_to = opt_coerce_to.unwrap_or_else(|| {
764 let guar = self.dcx().span_delayed_bug(
765 expr.span,
766 "illegal break with value found but no error reported",
767 );
768 self.set_tainted_by_errors(guar);
769 Ty::new_error(tcx, guar)
770 });
771
772 e_ty = self.check_expr_with_hint(e, coerce_to);
774 cause = self.misc(e.span);
775 } else {
776 e_ty = tcx.types.unit;
779 cause = self.misc(expr.span);
780 }
781
782 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
786 let Some(ctxt) = enclosing_breakables.opt_find_breakable(target_id) else {
787 return Ty::new_error_with_message(
789 tcx,
790 expr.span,
791 "break was outside loop, but no error was emitted",
792 );
793 };
794
795 if let Some(ref mut coerce) = ctxt.coerce {
796 if let Some(e) = expr_opt {
797 coerce.coerce(self, &cause, e, e_ty);
798 } else {
799 if !e_ty.is_unit() {
::core::panicking::panic("assertion failed: e_ty.is_unit()")
};assert!(e_ty.is_unit());
800 let ty = coerce.expected_ty();
801 coerce.coerce_forced_unit(
802 self,
803 &cause,
804 |mut err| {
805 self.suggest_missing_semicolon(&mut err, expr, e_ty, false, false);
806 self.suggest_mismatched_types_on_tail(
807 &mut err, expr, ty, e_ty, target_id,
808 );
809 let error =
810 Some(TypeError::Sorts(ExpectedFound { expected: ty, found: e_ty }));
811 self.annotate_loop_expected_due_to_inference(err, expr, error);
812 if let Some(val) =
813 self.err_ctxt().ty_kind_suggestion(self.param_env, ty)
814 {
815 err.span_suggestion_verbose(
816 expr.span.shrink_to_hi(),
817 "give the `break` a value of the expected type",
818 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", val))
})format!(" {val}"),
819 Applicability::HasPlaceholders,
820 );
821 }
822 },
823 false,
824 );
825 }
826 } else {
827 if !(expr_opt.is_none() || self.tainted_by_errors().is_some()) {
::core::panicking::panic("assertion failed: expr_opt.is_none() || self.tainted_by_errors().is_some()")
};assert!(expr_opt.is_none() || self.tainted_by_errors().is_some());
835 }
836
837 ctxt.may_break |= !self.diverges.get().is_always();
841
842 tcx.types.never
844 } else {
845 let err = Ty::new_error_with_message(
850 self.tcx,
851 expr.span,
852 "break was outside loop, but no error was emitted",
853 );
854
855 if let Some(e) = expr_opt {
858 self.check_expr_with_hint(e, err);
859
860 if let ExprKind::Path(QPath::Resolved(_, path)) = e.kind {
863 if let [segment] = path.segments
864 && segment.ident.name == sym::rust
865 {
866 fatally_break_rust(self.tcx, expr.span);
867 }
868 }
869 }
870
871 err
873 }
874 }
875
876 fn check_expr_continue(
877 &self,
878 destination: hir::Destination,
879 expr: &'tcx hir::Expr<'tcx>,
880 ) -> Ty<'tcx> {
881 if let Ok(target_id) = destination.target_id {
882 if let hir::Node::Expr(hir::Expr { kind: ExprKind::Loop(..), .. }) =
883 self.tcx.hir_node(target_id)
884 {
885 self.tcx.types.never
886 } else {
887 let guar = self.dcx().span_delayed_bug(
890 expr.span,
891 "found `continue` not pointing to loop, but no error reported",
892 );
893 Ty::new_error(self.tcx, guar)
894 }
895 } else {
896 Ty::new_misc_error(self.tcx)
898 }
899 }
900
901 fn check_expr_return(
902 &self,
903 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
904 expr: &'tcx hir::Expr<'tcx>,
905 ) -> Ty<'tcx> {
906 if self.ret_coercion.is_none() {
907 self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Return);
908
909 if let Some(e) = expr_opt {
910 self.check_expr(e);
913 }
914 } else if let Some(e) = expr_opt {
915 if self.ret_coercion_span.get().is_none() {
916 self.ret_coercion_span.set(Some(e.span));
917 }
918 self.check_return_or_body_tail(e, true);
919 } else {
920 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
921 if self.ret_coercion_span.get().is_none() {
922 self.ret_coercion_span.set(Some(expr.span));
923 }
924 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
925 if let Some((_, fn_decl)) = self.get_fn_decl(expr.hir_id) {
926 coercion.coerce_forced_unit(
927 self,
928 &cause,
929 |db| {
930 let span = fn_decl.output.span();
931 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
932 db.span_label(
933 span,
934 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` because of this return type",
snippet))
})format!("expected `{snippet}` because of this return type"),
935 );
936 }
937 },
938 true,
939 );
940 } else {
941 coercion.coerce_forced_unit(self, &cause, |_| (), true);
942 }
943 }
944 self.tcx.types.never
945 }
946
947 fn check_expr_become(
948 &self,
949 call: &'tcx hir::Expr<'tcx>,
950 expr: &'tcx hir::Expr<'tcx>,
951 ) -> Ty<'tcx> {
952 match &self.ret_coercion {
953 Some(ret_coercion) => {
954 let ret_ty = ret_coercion.borrow().expected_ty();
955 let call_expr_ty = self.check_expr_with_hint(call, ret_ty);
956
957 self.demand_suptype(expr.span, ret_ty, call_expr_ty);
960 }
961 None => {
962 self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Become);
963
964 self.check_expr(call);
967 }
968 }
969
970 self.tcx.types.never
971 }
972
973 pub(super) fn check_return_or_body_tail(
982 &self,
983 return_expr: &'tcx hir::Expr<'tcx>,
984 explicit_return: bool,
985 ) {
986 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
987 ::rustc_span::macros::bug_impl(Some(return_expr.span),
format_args!("check_return_expr called outside fn body"),
Location::caller())span_bug!(return_expr.span, "check_return_expr called outside fn body")
988 });
989
990 let ret_ty = ret_coercion.borrow().expected_ty();
991 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
992 let mut span = return_expr.span;
993 let mut hir_id = return_expr.hir_id;
994 if !explicit_return
997 && let ExprKind::Block(body, _) = return_expr.kind
998 && let Some(last_expr) = body.expr
999 {
1000 span = last_expr.span;
1001 hir_id = last_expr.hir_id;
1002 }
1003 ret_coercion.borrow_mut().coerce(
1004 self,
1005 &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
1006 return_expr,
1007 return_expr_ty,
1008 );
1009
1010 if let Some(fn_sig) = self.fn_sig()
1011 && fn_sig.output().has_opaque_types()
1012 {
1013 self.select_obligations_where_possible(|errors| {
1016 self.point_at_return_for_opaque_ty_error(
1017 errors,
1018 hir_id,
1019 span,
1020 return_expr_ty,
1021 return_expr.span,
1022 );
1023 });
1024 }
1025 }
1026
1027 fn emit_return_outside_of_fn_body(&self, expr: &hir::Expr<'_>, kind: ReturnLikeStatementKind) {
1032 let mut err = ReturnStmtOutsideOfFnBody {
1033 span: expr.span,
1034 encl_body_span: None,
1035 encl_fn_span: None,
1036 statement_kind: kind,
1037 };
1038
1039 let encl_item_id = self.tcx.hir_get_parent_item(expr.hir_id);
1040
1041 if let hir::Node::Item(hir::Item {
1042 kind: hir::ItemKind::Fn { .. },
1043 span: encl_fn_span,
1044 ..
1045 })
1046 | hir::Node::TraitItem(hir::TraitItem {
1047 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
1048 span: encl_fn_span,
1049 ..
1050 })
1051 | hir::Node::ImplItem(hir::ImplItem {
1052 kind: hir::ImplItemKind::Fn(..),
1053 span: encl_fn_span,
1054 ..
1055 }) = self.tcx.hir_node_by_def_id(encl_item_id.def_id)
1056 {
1057 let encl_body_owner_id = self.tcx.hir_enclosing_body_owner(expr.hir_id);
1061
1062 {
match (&encl_item_id.def_id, &encl_body_owner_id) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_ne!(encl_item_id.def_id, encl_body_owner_id);
1065
1066 let encl_body = self.tcx.hir_body_owned_by(encl_body_owner_id);
1067
1068 err.encl_body_span = Some(encl_body.value.span);
1069 err.encl_fn_span = Some(*encl_fn_span);
1070 }
1071
1072 self.dcx().emit_err(err);
1073 }
1074
1075 fn point_at_return_for_opaque_ty_error(
1076 &self,
1077 errors: &mut ThinVec<traits::FulfillmentError<'tcx>>,
1078 hir_id: HirId,
1079 span: Span,
1080 return_expr_ty: Ty<'tcx>,
1081 return_span: Span,
1082 ) {
1083 if span == return_span {
1085 return;
1086 }
1087 for err in errors {
1088 let cause = &mut err.obligation.cause;
1089 if let ObligationCauseCode::OpaqueReturnType(None) = cause.code() {
1090 let new_cause = self.cause(
1091 cause.span,
1092 ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, hir_id))),
1093 );
1094 *cause = new_cause;
1095 }
1096 }
1097 }
1098
1099 pub(crate) fn check_lhs_assignable(
1100 &self,
1101 lhs: &'tcx hir::Expr<'tcx>,
1102 code: ErrCode,
1103 op_span: Span,
1104 adjust_err: impl FnOnce(&mut Diag<'_>),
1105 ) {
1106 if lhs.is_syntactic_place_expr() {
1107 return;
1108 }
1109
1110 if contains_let_in_chain(lhs) {
1113 return;
1114 }
1115
1116 let mut err = self.dcx().struct_span_err(op_span, "invalid left-hand side of assignment");
1117 err.code(code);
1118 err.span_label(lhs.span, "cannot assign to this expression");
1119
1120 self.comes_from_while_condition(lhs.hir_id, |expr| {
1121 err.span_suggestion_verbose(
1122 expr.span.shrink_to_lo(),
1123 "you might have meant to use pattern destructuring",
1124 "let ",
1125 Applicability::MachineApplicable,
1126 );
1127 });
1128 self.check_for_missing_semi(lhs, &mut err);
1129
1130 adjust_err(&mut err);
1131
1132 err.emit();
1133 }
1134
1135 pub(crate) fn check_for_missing_semi(
1137 &self,
1138 expr: &'tcx hir::Expr<'tcx>,
1139 err: &mut Diag<'_>,
1140 ) -> bool {
1141 if let hir::ExprKind::Binary(binop, lhs, rhs) = expr.kind
1142 && let hir::BinOpKind::Mul = binop.node
1143 && self.tcx.sess.source_map().is_multiline(lhs.span.between(rhs.span))
1144 && rhs.is_syntactic_place_expr()
1145 {
1146 err.span_suggestion_verbose(
1151 lhs.span.shrink_to_hi(),
1152 "you might have meant to write a semicolon here",
1153 ";",
1154 Applicability::MachineApplicable,
1155 );
1156 return true;
1157 }
1158 false
1159 }
1160
1161 pub(super) fn comes_from_while_condition(
1165 &self,
1166 original_expr_id: HirId,
1167 then: impl FnOnce(&hir::Expr<'_>),
1168 ) {
1169 let mut parent = self.tcx.parent_hir_id(original_expr_id);
1170 loop {
1171 let node = self.tcx.hir_node(parent);
1172 match node {
1173 hir::Node::Expr(hir::Expr {
1174 kind:
1175 hir::ExprKind::Loop(
1176 hir::Block {
1177 expr:
1178 Some(hir::Expr {
1179 kind:
1180 hir::ExprKind::Match(expr, ..) | hir::ExprKind::If(expr, ..),
1181 ..
1182 }),
1183 ..
1184 },
1185 _,
1186 hir::LoopSource::While,
1187 _,
1188 ),
1189 ..
1190 }) => {
1191 if self.tcx.hir_parent_id_iter(original_expr_id).any(|id| id == expr.hir_id) {
1195 then(expr);
1196 }
1197 break;
1198 }
1199 hir::Node::Item(_)
1200 | hir::Node::ImplItem(_)
1201 | hir::Node::TraitItem(_)
1202 | hir::Node::Crate(_) => break,
1203 _ => {
1204 parent = self.tcx.parent_hir_id(parent);
1205 }
1206 }
1207 }
1208 }
1209
1210 fn check_expr_if(
1213 &self,
1214 expr_id: HirId,
1215 cond_expr: &'tcx hir::Expr<'tcx>,
1216 then_expr: &'tcx hir::Expr<'tcx>,
1217 opt_else_expr: Option<&'tcx hir::Expr<'tcx>>,
1218 sp: Span,
1219 orig_expected: Expectation<'tcx>,
1220 ) -> Ty<'tcx> {
1221 let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {});
1222
1223 self.warn_if_unreachable(
1224 cond_expr.hir_id,
1225 then_expr.span,
1226 "block in `if` or `while` expression",
1227 );
1228
1229 let cond_diverges = self.diverges.get();
1230 self.diverges.set(Diverges::Maybe);
1231
1232 let expected = orig_expected.try_structurally_resolve_and_adjust_for_branches(self);
1233 let then_ty = self.check_expr_with_expectation(then_expr, expected);
1234 let then_diverges = self.diverges.get();
1235 self.diverges.set(Diverges::Maybe);
1236
1237 let coerce_to_ty = expected.coercion_target_type(self, sp);
1244 let mut coerce = CoerceMany::with_capacity(coerce_to_ty, 2);
1245
1246 coerce.coerce(self, &self.misc(sp), then_expr, then_ty);
1247
1248 if let Some(else_expr) = opt_else_expr {
1249 let else_ty = self.check_expr_with_expectation(else_expr, expected);
1250 let else_diverges = self.diverges.get();
1251
1252 let tail_defines_return_position_impl_trait =
1253 self.return_position_impl_trait_from_match_expectation(orig_expected);
1254 let if_cause =
1255 self.if_cause(expr_id, else_expr, tail_defines_return_position_impl_trait);
1256
1257 coerce.coerce(self, &if_cause, else_expr, else_ty);
1258
1259 self.diverges.set(cond_diverges | then_diverges & else_diverges);
1261 } else {
1262 self.if_fallback_coercion(sp, cond_expr, then_expr, &mut coerce);
1263
1264 self.diverges.set(cond_diverges);
1266 }
1267
1268 let result_ty = coerce.complete(self);
1269 if let Err(guar) = cond_ty.error_reported() {
1270 Ty::new_error(self.tcx, guar)
1271 } else {
1272 result_ty
1273 }
1274 }
1275
1276 fn check_expr_assign(
1279 &self,
1280 expr: &'tcx hir::Expr<'tcx>,
1281 expected: Expectation<'tcx>,
1282 lhs: &'tcx hir::Expr<'tcx>,
1283 rhs: &'tcx hir::Expr<'tcx>,
1284 span: Span,
1285 ) -> Ty<'tcx> {
1286 let expected_ty = expected.only_has_type(self);
1287 if expected_ty == Some(self.tcx.types.bool) {
1288 let guar = self.expr_assign_expected_bool_error(expr, lhs, rhs, span);
1289 return Ty::new_error(self.tcx, guar);
1290 }
1291
1292 let lhs_ty = self.check_expr_with_needs(lhs, Needs::MutPlace);
1293
1294 let suggest_deref_binop = |err: &mut Diag<'_>, rhs_ty: Ty<'tcx>| {
1295 if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
1296 let lhs_deref_ty_is_sized = self
1299 .infcx
1300 .type_implements_trait(
1301 self.tcx.require_lang_item(LangItem::Sized, span),
1302 [lhs_deref_ty],
1303 self.param_env,
1304 )
1305 .may_apply();
1306 if lhs_deref_ty_is_sized && self.may_coerce(rhs_ty, lhs_deref_ty) {
1307 err.span_suggestion_verbose(
1308 lhs.span.shrink_to_lo(),
1309 "consider dereferencing here to assign to the mutably borrowed value",
1310 "*",
1311 Applicability::MachineApplicable,
1312 );
1313 }
1314 }
1315 };
1316
1317 let rhs_ty = self.check_expr_with_hint(rhs, lhs_ty);
1320 if let Err(mut diag) =
1321 self.demand_coerce_diag(rhs, rhs_ty, lhs_ty, Some(lhs), AllowTwoPhase::No)
1322 {
1323 suggest_deref_binop(&mut diag, rhs_ty);
1324 diag.emit();
1325 }
1326
1327 self.check_lhs_assignable(lhs, E0070, span, |err| {
1328 if let Some(rhs_ty) = self.typeck_results.borrow().expr_ty_opt(rhs) {
1329 suggest_deref_binop(err, rhs_ty);
1330 }
1331 });
1332
1333 self.require_type_is_sized(lhs_ty, lhs.span, ObligationCauseCode::AssignmentLhsSized);
1334
1335 if let Err(guar) = (lhs_ty, rhs_ty).error_reported() {
1336 Ty::new_error(self.tcx, guar)
1337 } else {
1338 self.tcx.types.unit
1339 }
1340 }
1341
1342 fn expr_assign_expected_bool_error(
1346 &self,
1347 expr: &'tcx hir::Expr<'tcx>,
1348 lhs: &'tcx hir::Expr<'tcx>,
1349 rhs: &'tcx hir::Expr<'tcx>,
1350 span: Span,
1351 ) -> ErrorGuaranteed {
1352 let actual_ty = self.tcx.types.unit;
1353 let expected_ty = self.tcx.types.bool;
1354 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap_err();
1355 let lhs_ty = self.check_expr(lhs);
1356 let rhs_ty = self.check_expr(rhs);
1357 let refs_can_coerce = |lhs: Ty<'tcx>, rhs: Ty<'tcx>| {
1358 let lhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, lhs.peel_refs());
1359 let rhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rhs.peel_refs());
1360 self.may_coerce(rhs, lhs)
1361 };
1362 let (applicability, eq) = if self.may_coerce_except_never(rhs_ty, lhs_ty) {
1364 (Applicability::MachineApplicable, true)
1365 } else if refs_can_coerce(rhs_ty, lhs_ty) {
1366 (Applicability::MaybeIncorrect, true)
1369 } else if let ExprKind::Binary(
1370 Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1371 _,
1372 rhs_expr,
1373 ) = lhs.kind
1374 {
1375 let actual_lhs = self.check_expr(rhs_expr);
1378 let may_eq = self.may_coerce_except_never(rhs_ty, actual_lhs)
1379 || refs_can_coerce(rhs_ty, actual_lhs);
1380 (Applicability::MaybeIncorrect, may_eq)
1381 } else if let ExprKind::Binary(
1382 Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1383 lhs_expr,
1384 _,
1385 ) = rhs.kind
1386 {
1387 let actual_rhs = self.check_expr(lhs_expr);
1390 let may_eq = self.may_coerce_except_never(actual_rhs, lhs_ty)
1391 || refs_can_coerce(actual_rhs, lhs_ty);
1392 (Applicability::MaybeIncorrect, may_eq)
1393 } else {
1394 (Applicability::MaybeIncorrect, false)
1395 };
1396
1397 if !lhs.is_syntactic_place_expr()
1398 && lhs.is_approximately_pattern()
1399 && !#[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
hir::ExprKind::Lit(_) => true,
_ => false,
}matches!(lhs.kind, hir::ExprKind::Lit(_))
1400 {
1401 if let hir::Node::Expr(hir::Expr { kind: ExprKind::If { .. }, .. }) =
1403 self.tcx.parent_hir_node(expr.hir_id)
1404 {
1405 err.span_suggestion_verbose(
1406 expr.span.shrink_to_lo(),
1407 "you might have meant to use pattern matching",
1408 "let ",
1409 applicability,
1410 );
1411 };
1412 }
1413 if eq {
1414 err.span_suggestion_verbose(
1415 span.shrink_to_hi(),
1416 "you might have meant to compare for equality",
1417 '=',
1418 applicability,
1419 );
1420 }
1421
1422 err.emit_err_unless_delay(lhs_ty.references_error() || rhs_ty.references_error())
1425 }
1426
1427 pub(super) fn check_expr_let(
1428 &self,
1429 let_expr: &'tcx hir::LetExpr<'tcx>,
1430 hir_id: HirId,
1431 ) -> Ty<'tcx> {
1432 GatherLocalsVisitor::gather_from_let_expr(self, let_expr, hir_id);
1433
1434 let init = let_expr.init;
1436 self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression");
1437
1438 self.check_decl((let_expr, hir_id).into());
1440
1441 if let ast::Recovered::Yes(error_guaranteed) = let_expr.recovered {
1443 self.set_tainted_by_errors(error_guaranteed);
1444 Ty::new_error(self.tcx, error_guaranteed)
1445 } else {
1446 self.tcx.types.bool
1447 }
1448 }
1449
1450 fn check_expr_loop(
1451 &self,
1452 body: &'tcx hir::Block<'tcx>,
1453 source: hir::LoopSource,
1454 expected: Expectation<'tcx>,
1455 expr: &'tcx hir::Expr<'tcx>,
1456 ) -> Ty<'tcx> {
1457 let coerce = match source {
1458 hir::LoopSource::Loop => {
1460 let coerce_to = expected.coercion_target_type(self, body.span);
1461 Some(CoerceMany::new(coerce_to))
1462 }
1463
1464 hir::LoopSource::While | hir::LoopSource::ForLoop => None,
1465 };
1466
1467 let ctxt = BreakableCtxt {
1468 coerce,
1469 may_break: false, };
1471
1472 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
1473 self.check_block_no_value(body);
1474 });
1475
1476 if ctxt.may_break {
1477 self.diverges.set(Diverges::Maybe);
1480 } else {
1481 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
1482 }
1483
1484 if ctxt.coerce.is_none() && !ctxt.may_break {
1490 self.dcx().span_bug(body.span, "no coercion, but loop may not break");
1491 }
1492 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.types.unit)
1493 }
1494
1495 fn check_expr_method_call(
1497 &self,
1498 expr: &'tcx hir::Expr<'tcx>,
1499 segment: &'tcx hir::PathSegment<'tcx>,
1500 rcvr: &'tcx hir::Expr<'tcx>,
1501 args: &'tcx [hir::Expr<'tcx>],
1502 expected: Expectation<'tcx>,
1503 ) -> Ty<'tcx> {
1504 let rcvr_t = self.check_expr(rcvr);
1505 let rcvr_t = self.deeply_resolve_ignoring_regions_with_obligations(rcvr_t);
1506
1507 match self.lookup_method(rcvr_t, segment, segment.ident.span, expr, rcvr, args) {
1508 Ok(method) => {
1509 self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
1510
1511 let mut method_inputs = Cow::Borrowed(&method.sig.inputs()[1..]);
1514 for (param, pos) in self.tcx.generics_of(method.def_id).own_arg_pos_consts() {
1515 let ty = self
1516 .tcx
1517 .type_of(param.def_id)
1518 .instantiate(self.tcx, method.args)
1519 .skip_norm_wip();
1520
1521 method_inputs.to_mut().insert(
1524 pos.checked_sub(1).expect("pos should always be greater than 0") as usize,
1525 ty,
1526 );
1527 }
1528
1529 let method_tuple_args_flag =
1530 TupleArgumentsFlag::with_fn_sig_kind(method.sig.fn_sig_kind, true);
1531
1532 self.check_argument_types(
1533 segment.ident.span,
1534 expr,
1535 &method_inputs,
1536 method.sig.output(),
1537 expected,
1538 args,
1539 method.sig.fn_sig_kind.c_variadic(),
1540 method_tuple_args_flag,
1541 SplatLoweringInfo::FnDef(method.def_id),
1542 Some(method.args),
1543 );
1544
1545 self.check_call_abi(method.sig.abi(), expr.span);
1546
1547 method.sig.output()
1548 }
1549 Err(error) => {
1550 let guar = self.report_method_error(expr.hir_id, rcvr_t, error, expected, false);
1551
1552 let err_inputs = self.err_args(args.len(), guar);
1553 let err_ty = Ty::new_error(self.tcx, guar);
1554
1555 self.check_argument_types(
1556 segment.ident.span,
1557 expr,
1558 &err_inputs,
1559 err_ty,
1560 NoExpectation,
1561 args,
1562 false,
1563 TupleArgumentsFlag::DontTupleArguments,
1564 SplatLoweringInfo::Error(guar),
1565 Some(GenericArgs::default()),
1566 );
1567
1568 err_ty
1569 }
1570 }
1571 }
1572
1573 fn check_expr_use(
1575 &self,
1576 used_expr: &'tcx hir::Expr<'tcx>,
1577 expected: Expectation<'tcx>,
1578 ) -> Ty<'tcx> {
1579 self.check_expr_with_expectation(used_expr, expected)
1580 }
1581
1582 fn check_expr_cast(
1583 &self,
1584 e: &'tcx hir::Expr<'tcx>,
1585 t: &'tcx hir::Ty<'tcx>,
1586 expr: &'tcx hir::Expr<'tcx>,
1587 ) -> Ty<'tcx> {
1588 let t_cast = self.lower_ty_saving_user_provided_ty(t);
1591 let t_cast = self.deeply_resolve_ignoring_regions(t_cast);
1592 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
1593 let t_expr = self.deeply_resolve_ignoring_regions(t_expr);
1594
1595 if let Err(guar) = (t_expr, t_cast).error_reported() {
1597 Ty::new_error(self.tcx, guar)
1598 } else {
1599 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
1601 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
1602 Ok(cast_check) => {
1603 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:1603",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(1603u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_expr_cast: deferring cast from {0:?} to {1:?}: {2:?}",
t_cast, t_expr, cast_check) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1604 "check_expr_cast: deferring cast from {:?} to {:?}: {:?}",
1605 t_cast, t_expr, cast_check,
1606 );
1607 deferred_cast_checks.push(cast_check);
1608 t_cast
1609 }
1610 Err(guar) => Ty::new_error(self.tcx, guar),
1611 }
1612 }
1613 }
1614
1615 fn check_expr_unsafe_binder_cast(
1616 &self,
1617 span: Span,
1618 kind: ast::UnsafeBinderCastKind,
1619 inner_expr: &'tcx hir::Expr<'tcx>,
1620 hir_ty: Option<&'tcx hir::Ty<'tcx>>,
1621 expected: Expectation<'tcx>,
1622 ) -> Ty<'tcx> {
1623 match kind {
1624 ast::UnsafeBinderCastKind::Wrap => {
1625 let ascribed_ty =
1626 hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1627 let expected_ty = expected.only_has_type(self);
1628 let binder_ty = match (ascribed_ty, expected_ty) {
1629 (Some(ascribed_ty), Some(expected_ty)) => {
1630 self.demand_eqtype(inner_expr.span, expected_ty, ascribed_ty);
1631 expected_ty
1632 }
1633 (Some(ty), None) | (None, Some(ty)) => ty,
1634 (None, None) => self.next_ty_var(inner_expr.span),
1638 };
1639
1640 let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1641 let hint_ty = match *binder_ty.kind() {
1642 ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1643 inner_expr.span,
1644 infer::BoundRegionConversionTime::HigherRankedType,
1645 binder.into(),
1646 ),
1647 ty::Error(e) => Ty::new_error(self.tcx, e),
1648 _ => {
1649 let guar = self
1650 .dcx()
1651 .struct_span_err(
1652 hir_ty.map_or(span, |hir_ty| hir_ty.span),
1653 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`wrap_binder!()` can only wrap into unsafe binder, not {0}",
binder_ty.sort_string(self.tcx)))
})format!(
1654 "`wrap_binder!()` can only wrap into unsafe binder, not {}",
1655 binder_ty.sort_string(self.tcx)
1656 ),
1657 )
1658 .with_note("unsafe binders are the only valid output of wrap")
1659 .emit_err();
1660 Ty::new_error(self.tcx, guar)
1661 }
1662 };
1663
1664 self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1665
1666 binder_ty
1667 }
1668 ast::UnsafeBinderCastKind::Unwrap => {
1669 let ascribed_ty =
1670 hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1671 let hint_ty = ascribed_ty.unwrap_or_else(|| self.next_ty_var(inner_expr.span));
1672 let binder_ty = self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1674
1675 let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1678 match *binder_ty.kind() {
1679 ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1680 inner_expr.span,
1681 infer::BoundRegionConversionTime::HigherRankedType,
1682 binder.into(),
1683 ),
1684 ty::Error(e) => Ty::new_error(self.tcx, e),
1685 _ => {
1686 let guar = self
1687 .dcx()
1688 .struct_span_err(
1689 hir_ty.map_or(inner_expr.span, |hir_ty| hir_ty.span),
1690 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected unsafe binder, found {0} as input of `unwrap_binder!()`",
binder_ty.sort_string(self.tcx)))
})format!(
1691 "expected unsafe binder, found {} as input of \
1692 `unwrap_binder!()`",
1693 binder_ty.sort_string(self.tcx)
1694 ),
1695 )
1696 .with_note("only an unsafe binder type can be unwrapped")
1697 .emit_err();
1698 Ty::new_error(self.tcx, guar)
1699 }
1700 }
1701 }
1702 }
1703 }
1704
1705 fn check_expr_array(
1706 &self,
1707 args: &'tcx [hir::Expr<'tcx>],
1708 expected: Expectation<'tcx>,
1709 expr: &'tcx hir::Expr<'tcx>,
1710 ) -> Ty<'tcx> {
1711 let element_ty = if !args.is_empty() {
1712 let coerce_to = expected
1713 .to_option(self)
1714 .and_then(|uty| {
1715 self.deeply_resolve_ignoring_regions_with_obligations(uty)
1716 .builtin_index()
1717 .filter(|t| {
1720 !self.deeply_resolve_ignoring_regions_with_obligations(*t).is_ty_var()
1721 })
1722 })
1723 .unwrap_or_else(|| self.next_ty_var(expr.span));
1724 let mut coerce = CoerceMany::with_capacity(coerce_to, args.len());
1725
1726 for e in args {
1727 let e_ty = self.check_expr_with_hint(e, coerce_to);
1733 let cause = self.misc(e.span);
1734 coerce.coerce(self, &cause, e, e_ty);
1735 }
1736 coerce.complete(self)
1737 } else {
1738 self.next_ty_var(expr.span)
1739 };
1740 let array_len = args.len() as u64;
1741 Ty::new_array(self.tcx, element_ty, array_len)
1742 }
1743
1744 pub(super) fn check_expr_const_block(
1745 &self,
1746 block: &'tcx hir::ConstBlock,
1747 expected: Expectation<'tcx>,
1748 ) -> Ty<'tcx> {
1749 let body = self.tcx.hir_body(block.body);
1750
1751 let def_id = block.def_id;
1753 let fcx = FnCtxt::new(self, self.param_env, def_id);
1754
1755 let ty = fcx.check_expr_with_expectation(body.value, expected);
1756 fcx.require_type_is_sized(ty, body.value.span, ObligationCauseCode::SizedConstOrStatic);
1757 fcx.write_ty(block.hir_id, ty);
1758 ty
1759 }
1760
1761 fn check_expr_repeat(
1762 &self,
1763 element: &'tcx hir::Expr<'tcx>,
1764 count: &'tcx hir::ConstArg<'tcx>,
1765 expected: Expectation<'tcx>,
1766 expr: &'tcx hir::Expr<'tcx>,
1767 ) -> Ty<'tcx> {
1768 let tcx = self.tcx;
1769 let count_span = count.span;
1770 let count = self.try_structurally_resolve_const(
1771 count_span,
1772 self.normalize(
1773 count_span,
1774 Unnormalized::new_wip(self.lower_const_arg(count, tcx.types.usize)),
1775 ),
1776 );
1777
1778 let uty = match expected {
1779 ExpectHasType(uty) => uty.builtin_index(),
1780 _ => None,
1781 };
1782
1783 let old_diverges = self.diverges.get();
1784
1785 let (element_ty, t) = match uty {
1786 Some(uty) => {
1787 self.check_expr_coercible_to_type(element, uty, None);
1788 (uty, uty)
1789 }
1790 None => {
1791 let ty = self.next_ty_var(element.span);
1792 let element_ty = self.check_expr_has_type_or_error(element, ty, |_| {});
1793 (element_ty, ty)
1794 }
1795 };
1796
1797 let count_is_zero = match count.kind() {
1805 ConstKind::Value(v) => v.try_to_target_usize(tcx) == Some(0),
1807
1808 ConstKind::Infer(_) => true,
1813
1814 ConstKind::Param(_)
1818 | ConstKind::Placeholder(_)
1819 | ConstKind::Alias(..)
1820 | ConstKind::Error(_)
1821 | ConstKind::Expr(_) => false,
1822
1823 ConstKind::Bound(..) => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
1824 };
1825
1826 if count_is_zero && element.is_constant_for_zero_repeat() {
1827 self.diverges.set(old_diverges);
1828 }
1829
1830 if let Err(guar) = element_ty.error_reported() {
1831 return Ty::new_error(tcx, guar);
1832 }
1833
1834 self.deferred_repeat_expr_checks.borrow_mut().push((element, element_ty, count));
1838
1839 let ty = Ty::new_array_with_const_len(tcx, t, count);
1840 self.register_wf_obligation(
1841 ty.into(),
1842 expr.span,
1843 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(expr.hir_id)),
1844 );
1845 ty
1846 }
1847
1848 fn check_expr_tuple(
1849 &self,
1850 elements: &'tcx [hir::Expr<'tcx>],
1851 expected: Expectation<'tcx>,
1852 expr: &'tcx hir::Expr<'tcx>,
1853 ) -> Ty<'tcx> {
1854 let mut expectations = expected
1855 .only_has_type(self)
1856 .and_then(|ty| {
1857 self.deeply_resolve_ignoring_regions_with_obligations(ty).opt_tuple_fields()
1858 })
1859 .unwrap_or_default()
1860 .iter();
1861
1862 let elements = elements.iter().map(|e| {
1863 let ty = expectations.next().unwrap_or_else(|| self.next_ty_var(e.span));
1864 self.check_expr_coercible_to_type(e, ty, None);
1865 ty
1866 });
1867
1868 let tuple = Ty::new_tup_from_iter(self.tcx, elements);
1869
1870 if let Err(guar) = tuple.error_reported() {
1871 Ty::new_error(self.tcx, guar)
1872 } else {
1873 self.require_type_is_sized(
1874 tuple,
1875 expr.span,
1876 ObligationCauseCode::TupleInitializerSized,
1877 );
1878 tuple
1879 }
1880 }
1881
1882 fn check_expr_struct(
1883 &self,
1884 expr: &hir::Expr<'tcx>,
1885 expected: Expectation<'tcx>,
1886 qpath: &'tcx QPath<'tcx>,
1887 fields: &'tcx [hir::ExprField<'tcx>],
1888 base_expr: &'tcx hir::StructTailExpr<'tcx>,
1889 ) -> Ty<'tcx> {
1890 let (variant, adt_ty) = match self.check_struct_path(qpath, expr.hir_id) {
1892 Ok(data) => data,
1893 Err(guar) => {
1894 self.check_struct_fields_on_error(fields, base_expr);
1895 return Ty::new_error(self.tcx, guar);
1896 }
1897 };
1898
1899 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1901 if variant.field_list_has_applicable_non_exhaustive() {
1902 self.dcx()
1903 .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() });
1904 }
1905
1906 self.check_expr_struct_fields(
1907 adt_ty,
1908 expected,
1909 expr,
1910 qpath.span(),
1911 variant,
1912 fields,
1913 base_expr,
1914 );
1915
1916 self.require_type_is_sized(adt_ty, expr.span, ObligationCauseCode::StructInitializerSized);
1917 adt_ty
1918 }
1919
1920 fn check_expr_struct_fields(
1921 &self,
1922 adt_ty: Ty<'tcx>,
1923 expected: Expectation<'tcx>,
1924 expr: &hir::Expr<'_>,
1925 path_span: Span,
1926 variant: &'tcx ty::VariantDef,
1927 hir_fields: &'tcx [hir::ExprField<'tcx>],
1928 base_expr: &'tcx hir::StructTailExpr<'tcx>,
1929 ) {
1930 let tcx = self.tcx;
1931
1932 let adt_ty = self.deeply_resolve_ignoring_regions_with_obligations(adt_ty);
1933 let adt_ty_hint = expected.only_has_type(self).and_then(|expected| {
1934 self.fudge_inference_if_ok(|| {
1935 let ocx = ObligationCtxt::new(self);
1936 ocx.sup(&self.misc(path_span), self.param_env, expected, adt_ty)?;
1937 if !ocx.try_evaluate_obligations().no_errors() {
1938 return Err(TypeError::Mismatch);
1939 }
1940 Ok(self.deeply_resolve_ignoring_regions(adt_ty))
1941 })
1942 .ok()
1943 });
1944 if let Some(adt_ty_hint) = adt_ty_hint {
1945 self.demand_eqtype(path_span, adt_ty_hint, adt_ty);
1947 }
1948
1949 let ty::Adt(adt, args) = adt_ty.kind() else {
1950 ::rustc_span::macros::bug_impl(Some(path_span),
format_args!("non-ADT passed to check_expr_struct_fields"),
Location::caller());span_bug!(path_span, "non-ADT passed to check_expr_struct_fields");
1951 };
1952 let adt_kind = adt.adt_kind();
1953
1954 let get_field_ident = |field: &ty::FieldDef| field.ident(tcx).normalize_to_macros_2_0();
1955 let mut remaining_fields = variant
1956 .fields
1957 .iter_enumerated()
1958 .map(|(i, field)| (get_field_ident(field), (i, field)))
1959 .collect::<UnordMap<_, _>>();
1960
1961 let mut seen_fields = FxHashMap::default();
1962
1963 let mut error_happened = false;
1964
1965 if variant.fields.len() != remaining_fields.len() {
1966 let guar =
1969 self.dcx().span_delayed_bug(expr.span, "struct fields have non-unique names");
1970 self.set_tainted_by_errors(guar);
1971 error_happened = true;
1972 }
1973
1974 for (idx, field) in hir_fields.iter().enumerate() {
1976 let ident = if field.ident.name == kw::Underscore {
1977 if let [v_field] = &variant.fields[..] {
1983 Ok(get_field_ident(v_field))
1984 } else {
1985 Err(tcx.dcx().emit_err(DelegationInvalidAdtForReturnWrapping {
1986 span: tcx.def_span(self.body_def_id),
1987 adt_name: tcx.def_path_str(adt.did()),
1988 }))
1989 }
1990 } else {
1991 Ok(tcx.adjust_ident(field.ident, variant.def_id))
1992 };
1993
1994 let field_type = ident
1995 .and_then(|ident| {
1996 if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1997 seen_fields.insert(ident, field.span);
1998 self.write_field_index(field.hir_id, i);
1999
2000 if adt_kind != AdtKind::Enum {
2004 tcx.check_stability(v_field.did, Some(field.hir_id), field.span, None);
2005 }
2006
2007 Ok(self.field_ty(field.span, v_field, *args))
2008 } else {
2009 error_happened = true;
2010 let guar = if let Some(prev_span) = seen_fields.get(&ident) {
2011 self.dcx().emit_err(FieldMultiplySpecifiedInInitializer {
2012 span: field.ident.span,
2013 prev_span: *prev_span,
2014 ident,
2015 })
2016 } else {
2017 self.report_unknown_field(
2018 adt_ty,
2019 variant,
2020 expr,
2021 field,
2022 hir_fields,
2023 adt.variant_descr(),
2024 )
2025 };
2026
2027 Err(guar)
2028 }
2029 })
2030 .unwrap_or_else(|err| Ty::new_error(tcx, err));
2031
2032 self.register_wf_obligation(
2036 field_type.into(),
2037 field.expr.span,
2038 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(field.expr.hir_id)),
2039 );
2040
2041 let ty = self.check_expr_with_hint(field.expr, field_type);
2044 let diag = self.demand_coerce_diag(field.expr, ty, field_type, None, AllowTwoPhase::No);
2045
2046 if let Err(diag) = diag {
2047 if idx == hir_fields.len() - 1 {
2048 if remaining_fields.is_empty() {
2049 self.suggest_fru_from_range_and_emit(field, variant, *args, diag);
2050 } else {
2051 diag.stash(field.span, StashKey::MaybeFruTypo);
2052 }
2053 } else {
2054 diag.emit();
2055 }
2056 }
2057 }
2058
2059 if adt_kind == AdtKind::Union && hir_fields.len() != 1 {
2061 {
self.dcx().struct_span_err(path_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("union expressions should have exactly one field"))
})).with_code(E0784)
}struct_span_code_err!(
2062 self.dcx(),
2063 path_span,
2064 E0784,
2065 "union expressions should have exactly one field",
2066 )
2067 .emit();
2068 }
2069
2070 if error_happened {
2074 if let hir::StructTailExpr::Base(base_expr) = base_expr {
2075 self.check_expr(base_expr);
2076 }
2077 return;
2078 }
2079
2080 match *base_expr {
2081 hir::StructTailExpr::DefaultFields(span) => {
2082 let mut missing_mandatory_fields = Vec::new();
2083 let mut missing_optional_fields = Vec::new();
2084 for f in &variant.fields {
2085 let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2086 if let Some(_) = remaining_fields.remove(&ident) {
2087 if f.value.is_none() {
2088 missing_mandatory_fields.push(ident);
2089 } else {
2090 missing_optional_fields.push(ident);
2091 }
2092 }
2093 }
2094 if !self.tcx.features().default_field_values() {
2095 let sugg = self.tcx.crate_level_attribute_injection_span();
2096 self.dcx().emit_err(BaseExpressionDoubleDot {
2097 span: span.shrink_to_hi(),
2098 default_field_values_suggestion: if self.tcx.sess.is_nightly_build()
2101 && missing_mandatory_fields.is_empty()
2102 && !missing_optional_fields.is_empty()
2103 {
2104 Some(sugg)
2105 } else {
2106 None
2107 },
2108 add_expr: if !missing_mandatory_fields.is_empty()
2109 || !missing_optional_fields.is_empty()
2110 {
2111 Some(BaseExpressionDoubleDotAddExpr { span: span.shrink_to_hi() })
2112 } else {
2113 None
2114 },
2115 remove_dots: if missing_mandatory_fields.is_empty()
2116 && missing_optional_fields.is_empty()
2117 {
2118 Some(BaseExpressionDoubleDotRemove { span })
2119 } else {
2120 None
2121 },
2122 });
2123 return;
2124 }
2125 if variant.fields.is_empty() {
2126 let mut err = self.dcx().struct_span_err(
2127 span,
2128 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has no fields, `..` needs at least one default field in the struct definition",
adt_ty))
})format!(
2129 "`{adt_ty}` has no fields, `..` needs at least one default field in \
2130 the struct definition",
2131 ),
2132 );
2133 err.span_label(path_span, "this type has no fields");
2134 err.emit();
2135 }
2136 if !missing_mandatory_fields.is_empty() {
2137 let s = if missing_mandatory_fields.len() == 1 { "" } else { "s" }pluralize!(missing_mandatory_fields.len());
2138 let fields = listify(&missing_mandatory_fields, |f| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", f))
})format!("`{f}`")).unwrap();
2139 self.dcx()
2140 .struct_span_err(
2141 span.shrink_to_lo(),
2142 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing field{0} {1} in initializer",
s, fields))
})format!("missing field{s} {fields} in initializer"),
2143 )
2144 .with_span_label(
2145 span.shrink_to_lo(),
2146 "fields that do not have a defaulted value must be provided explicitly",
2147 )
2148 .emit();
2149 return;
2150 }
2151 let fru_tys = match adt_ty.kind() {
2152 ty::Adt(adt, args) if adt.is_struct() => variant
2153 .fields
2154 .iter()
2155 .map(|f| self.normalize(span, f.ty(self.tcx, *args)))
2156 .collect(),
2157 ty::Adt(adt, args) if adt.is_enum() => variant
2158 .fields
2159 .iter()
2160 .map(|f| self.normalize(span, f.ty(self.tcx, *args)))
2161 .collect(),
2162 _ => {
2163 self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct { span });
2164 return;
2165 }
2166 };
2167 self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2168 }
2169 hir::StructTailExpr::Base(base_expr) => {
2170 let fru_tys = if self.tcx.features().type_changing_struct_update() {
2173 if adt.is_struct() {
2174 let fresh_args = self.fresh_args_for_item(base_expr.span, adt.did());
2176 let fru_tys = variant
2181 .fields
2182 .iter()
2183 .map(|f| {
2184 let fru_ty = self.normalize(
2185 expr.span,
2186 Unnormalized::new_wip(self.field_ty(
2187 base_expr.span,
2188 f,
2189 fresh_args,
2190 )),
2191 );
2192 let ident =
2193 self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2194 if let Some(_) = remaining_fields.remove(&ident) {
2195 let target_ty = self.field_ty(base_expr.span, f, *args);
2196 let cause = self.misc(base_expr.span);
2197 if let Err(diag) =
2198 self.demand_suptype_diag(cause.span, target_ty, fru_ty)
2199 {
2200 diag.delay_as_bug();
2201 }
2202 }
2203 self.deeply_resolve_ignoring_regions(fru_ty)
2204 })
2205 .collect();
2206 let fresh_base_ty = Ty::new_adt(self.tcx, *adt, fresh_args);
2225 self.check_expr_has_type_or_error(
2226 base_expr,
2227 self.deeply_resolve_ignoring_regions(fresh_base_ty),
2228 |_| {},
2229 );
2230 fru_tys
2231 } else {
2232 self.check_expr(base_expr);
2235 self.dcx()
2236 .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
2237 return;
2238 }
2239 } else {
2240 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {
2241 let base_ty = self.typeck_results.borrow().expr_ty(base_expr);
2242 let same_adt = #[allow(non_exhaustive_omitted_patterns)] match (adt_ty.kind(),
base_ty.kind()) {
(ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt => true,
_ => false,
}matches!((adt_ty.kind(), base_ty.kind()),
2243 (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt);
2244 if self.tcx.sess.is_nightly_build() && same_adt {
2245 feature_err(
2246 &self.tcx.sess,
2247 sym::type_changing_struct_update,
2248 base_expr.span,
2249 "type changing struct updating is experimental",
2250 )
2251 .emit();
2252 }
2253 });
2254 match adt_ty.kind() {
2255 ty::Adt(adt, args) if adt.is_struct() => variant
2256 .fields
2257 .iter()
2258 .map(|f| self.normalize(expr.span, f.ty(self.tcx, *args)))
2259 .collect(),
2260 _ => {
2261 self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct {
2262 span: base_expr.span,
2263 });
2264 return;
2265 }
2266 }
2267 };
2268 self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2269 }
2270 rustc_hir::StructTailExpr::NoneWithError(guaranteed) => {
2271 self.infcx.set_tainted_by_errors(guaranteed);
2282 }
2283 rustc_hir::StructTailExpr::None => {
2284 if adt_kind != AdtKind::Union
2285 && !remaining_fields.is_empty()
2286 && !variant.field_list_has_applicable_non_exhaustive()
2288 {
2289 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:2289",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2289u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("remaining_fields")
}> =
::tracing::__macro_support::FieldName::new("remaining_fields");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&remaining_fields)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?remaining_fields);
2290
2291 let private_fields: Vec<&ty::FieldDef> = variant
2294 .fields
2295 .iter()
2296 .filter(|field| !field.vis.is_accessible_from(self.mod_id, tcx))
2297 .collect();
2298
2299 if !private_fields.is_empty() {
2300 self.report_private_fields(
2301 adt_ty,
2302 path_span,
2303 expr.span,
2304 private_fields,
2305 hir_fields,
2306 );
2307 } else {
2308 self.report_missing_fields(
2309 adt_ty,
2310 path_span,
2311 expr.span,
2312 remaining_fields,
2313 variant,
2314 hir_fields,
2315 *args,
2316 );
2317 }
2318 }
2319 }
2320 }
2321 }
2322
2323 fn check_struct_fields_on_error(
2324 &self,
2325 fields: &'tcx [hir::ExprField<'tcx>],
2326 base_expr: &'tcx hir::StructTailExpr<'tcx>,
2327 ) {
2328 for field in fields {
2329 self.check_expr(field.expr);
2330 }
2331 if let hir::StructTailExpr::Base(base) = *base_expr {
2332 self.check_expr(base);
2333 }
2334 }
2335
2336 fn report_missing_fields(
2348 &self,
2349 adt_ty: Ty<'tcx>,
2350 span: Span,
2351 full_span: Span,
2352 remaining_fields: UnordMap<Ident, (FieldIdx, &ty::FieldDef)>,
2353 variant: &'tcx ty::VariantDef,
2354 hir_fields: &'tcx [hir::ExprField<'tcx>],
2355 args: GenericArgs<'tcx>,
2356 ) {
2357 let len = remaining_fields.len();
2358
2359 let displayable_field_names: Vec<&str> =
2360 remaining_fields.items().map(|(ident, _)| ident.as_str()).into_sorted_stable_ord();
2361
2362 let mut truncated_fields_error = String::new();
2363 let remaining_fields_names = match &displayable_field_names[..] {
2364 [field1] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", field1))
})format!("`{field1}`"),
2365 [field1, field2] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and `{1}`", field1, field2))
})format!("`{field1}` and `{field2}`"),
2366 [field1, field2, field3] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`, `{1}` and `{2}`", field1,
field2, field3))
})format!("`{field1}`, `{field2}` and `{field3}`"),
2367 _ => {
2368 truncated_fields_error =
2369 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" and {0} other field{1}", len - 3,
if len - 3 == 1 { "" } else { "s" }))
})format!(" and {} other field{}", len - 3, pluralize!(len - 3));
2370 displayable_field_names
2371 .iter()
2372 .take(3)
2373 .map(|n| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`"))
2374 .collect::<Vec<_>>()
2375 .join(", ")
2376 }
2377 };
2378
2379 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing field{0} {1}{2} in initializer of `{3}`",
if len == 1 { "" } else { "s" }, remaining_fields_names,
truncated_fields_error, adt_ty))
})).with_code(E0063)
}struct_span_code_err!(
2380 self.dcx(),
2381 span,
2382 E0063,
2383 "missing field{} {}{} in initializer of `{}`",
2384 pluralize!(len),
2385 remaining_fields_names,
2386 truncated_fields_error,
2387 adt_ty
2388 );
2389 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing {0}{1}",
remaining_fields_names, truncated_fields_error))
})format!("missing {remaining_fields_names}{truncated_fields_error}"));
2390
2391 if remaining_fields.items().all(|(_, (_, field))| field.value.is_some())
2392 && self.tcx.sess.is_nightly_build()
2393 {
2394 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("all remaining fields have default values, {0} use those values with `..`",
if self.tcx.features().default_field_values() {
"you can"
} else {
"if you added `#![feature(default_field_values)]` to your crate you could"
}))
})format!(
2395 "all remaining fields have default values, {you_can} use those values with `..`",
2396 you_can = if self.tcx.features().default_field_values() {
2397 "you can"
2398 } else {
2399 "if you added `#![feature(default_field_values)]` to your crate you could"
2400 },
2401 );
2402 if let Some(hir_field) = hir_fields.last() {
2403 err.span_suggestion_verbose(
2404 hir_field.span.shrink_to_hi(),
2405 msg,
2406 ", ..".to_string(),
2407 Applicability::MachineApplicable,
2408 );
2409 } else if hir_fields.is_empty() {
2410 err.span_suggestion_verbose(
2411 span.shrink_to_hi().with_hi(full_span.hi()),
2412 msg,
2413 " { .. }".to_string(),
2414 Applicability::MachineApplicable,
2415 );
2416 }
2417 }
2418
2419 if let Some(hir_field) = hir_fields.last() {
2420 self.suggest_fru_from_range_and_emit(hir_field, variant, args, err);
2421 } else {
2422 err.emit();
2423 }
2424 }
2425
2426 fn suggest_fru_from_range_and_emit(
2429 &self,
2430 last_expr_field: &hir::ExprField<'tcx>,
2431 variant: &ty::VariantDef,
2432 args: GenericArgs<'tcx>,
2433 mut err: Diag<'_>,
2434 ) {
2435 if is_range_literal(last_expr_field.expr)
2436 && let ExprKind::Struct(&qpath, [range_start, range_end], _) = last_expr_field.expr.kind
2437 && self.tcx.qpath_is_lang_item(qpath, LangItem::Range)
2438 && let variant_field =
2439 variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident)
2440 && let range_def_id = self.tcx.lang_items().range_struct()
2441 && variant_field
2442 .and_then(|field| field.ty(self.tcx, args).skip_norm_wip().ty_adt_def())
2443 .map(|adt| adt.did())
2444 != range_def_id
2445 {
2446 let expr = self
2450 .tcx
2451 .sess
2452 .source_map()
2453 .span_to_snippet(range_end.expr.span)
2454 .ok()
2455 .filter(|s| s.len() < 25 && !s.contains(|c: char| c.is_control()));
2456
2457 let fru_span = self
2458 .tcx
2459 .sess
2460 .source_map()
2461 .span_extend_while_whitespace(range_start.expr.span)
2462 .shrink_to_hi()
2463 .to(range_end.expr.span);
2464
2465 err.subdiagnostic(TypeMismatchFruTypo {
2466 expr_span: range_start.expr.span,
2467 fru_span,
2468 expr,
2469 });
2470
2471 self.dcx().try_steal_replace_and_emit_err(
2473 last_expr_field.span,
2474 StashKey::MaybeFruTypo,
2475 err,
2476 );
2477 } else {
2478 err.emit();
2479 }
2480 }
2481
2482 fn report_private_fields(
2494 &self,
2495 adt_ty: Ty<'tcx>,
2496 span: Span,
2497 expr_span: Span,
2498 private_fields: Vec<&ty::FieldDef>,
2499 used_fields: &'tcx [hir::ExprField<'tcx>],
2500 ) {
2501 let mut err =
2502 self.dcx().struct_span_err(
2503 span,
2504 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot construct `{0}` with struct literal syntax due to private fields",
adt_ty))
})format!(
2505 "cannot construct `{adt_ty}` with struct literal syntax due to private fields",
2506 ),
2507 );
2508 let (used_private_fields, remaining_private_fields): (
2509 Vec<(Symbol, Span, bool)>,
2510 Vec<(Symbol, Span, bool)>,
2511 ) = private_fields
2512 .iter()
2513 .map(|field| {
2514 match used_fields.iter().find(|used_field| field.name == used_field.ident.name) {
2515 Some(used_field) => (field.name, used_field.span, true),
2516 None => (field.name, self.tcx.def_span(field.did), false),
2517 }
2518 })
2519 .partition(|field| field.2);
2520 err.span_labels(used_private_fields.iter().map(|(_, span, _)| *span), "private field");
2521
2522 if let ty::Adt(def, _) = adt_ty.kind() {
2523 if (def.did().is_local() || !used_fields.is_empty())
2524 && !remaining_private_fields.is_empty()
2525 {
2526 let names = if remaining_private_fields.len() > 6 {
2527 String::new()
2528 } else {
2529 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ",
listify(&remaining_private_fields,
|(name, _, _)|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", name))
})).expect("expected at least one private field to report")))
})format!(
2530 "{} ",
2531 listify(&remaining_private_fields, |(name, _, _)| format!("`{name}`"))
2532 .expect("expected at least one private field to report")
2533 )
2534 };
2535 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}private field{1} {3}that {2} not provided",
if used_fields.is_empty() { "" } else { "...and other " },
if remaining_private_fields.len() == 1 { "" } else { "s" },
if remaining_private_fields.len() == 1 {
"was"
} else { "were" }, names))
})format!(
2536 "{}private field{s} {names}that {were} not provided",
2537 if used_fields.is_empty() { "" } else { "...and other " },
2538 s = pluralize!(remaining_private_fields.len()),
2539 were = pluralize!("was", remaining_private_fields.len()),
2540 ));
2541 }
2542
2543 let def_id = def.did();
2544 let mut items = self
2545 .tcx
2546 .inherent_impls(def_id)
2547 .into_iter()
2548 .flat_map(|&i| self.tcx.associated_items(i).in_definition_order())
2549 .filter(|item| item.is_fn() && !item.is_method())
2551 .filter_map(|item| {
2552 let fn_sig = self
2554 .tcx
2555 .fn_sig(item.def_id)
2556 .instantiate(self.tcx, self.fresh_args_for_item(span, item.def_id))
2557 .skip_norm_wip();
2558 let ret_ty = self.tcx.instantiate_bound_regions_with_erased(fn_sig.output());
2559 if !self.can_eq(self.param_env, ret_ty, adt_ty) {
2560 return None;
2561 }
2562 let input_len = fn_sig.inputs().skip_binder().len();
2563 let name = item.name();
2564 let order = !name.as_str().starts_with("new");
2565 Some((order, name, input_len))
2566 })
2567 .collect::<Vec<_>>();
2568 items.sort_by_key(|(order, _, _)| *order);
2569 let suggestion = |name, args| {
2570 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{1}({0})",
std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "),
name))
})format!(
2571 "::{name}({})",
2572 std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", ")
2573 )
2574 };
2575 match &items[..] {
2576 [] => {}
2577 [(_, name, args)] => {
2578 err.span_suggestion_verbose(
2579 span.shrink_to_hi().with_hi(expr_span.hi()),
2580 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you might have meant to use the `{0}` associated function",
name))
})format!("you might have meant to use the `{name}` associated function"),
2581 suggestion(name, *args),
2582 Applicability::MaybeIncorrect,
2583 );
2584 }
2585 _ => {
2586 err.span_suggestions(
2587 span.shrink_to_hi().with_hi(expr_span.hi()),
2588 "you might have meant to use an associated function to build this type",
2589 items.iter().map(|(_, name, args)| suggestion(name, *args)),
2590 Applicability::MaybeIncorrect,
2591 );
2592 }
2593 }
2594 if let Some(default_trait) = self.tcx.get_diagnostic_item(sym::Default)
2595 && self
2596 .infcx
2597 .type_implements_trait(default_trait, [adt_ty], self.param_env)
2598 .may_apply()
2599 {
2600 err.multipart_suggestion(
2601 "consider using the `Default` trait",
2602 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span.shrink_to_lo(), "<".to_string()),
(span.shrink_to_hi().with_hi(expr_span.hi()),
" as std::default::Default>::default()".to_string())]))vec![
2603 (span.shrink_to_lo(), "<".to_string()),
2604 (
2605 span.shrink_to_hi().with_hi(expr_span.hi()),
2606 " as std::default::Default>::default()".to_string(),
2607 ),
2608 ],
2609 Applicability::MaybeIncorrect,
2610 );
2611 }
2612 }
2613
2614 err.emit();
2615 }
2616
2617 fn report_unknown_field(
2618 &self,
2619 ty: Ty<'tcx>,
2620 variant: &'tcx ty::VariantDef,
2621 expr: &hir::Expr<'_>,
2622 field: &hir::ExprField<'_>,
2623 skip_fields: &[hir::ExprField<'_>],
2624 kind_name: &str,
2625 ) -> ErrorGuaranteed {
2626 if let Err(guar) = variant.has_errors() {
2628 return guar;
2629 }
2630 let mut err = self.err_ctxt().type_error_struct_with_diag(
2631 field.ident.span,
2632 |actual| match ty.kind() {
2633 ty::Adt(adt, ..) if adt.is_enum() => {
self.dcx().struct_span_err(field.ident.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}::{2}` has no field named `{3}`",
kind_name, actual, variant.name, field.ident))
})).with_code(E0559)
}struct_span_code_err!(
2634 self.dcx(),
2635 field.ident.span,
2636 E0559,
2637 "{} `{}::{}` has no field named `{}`",
2638 kind_name,
2639 actual,
2640 variant.name,
2641 field.ident
2642 ),
2643 _ => {
self.dcx().struct_span_err(field.ident.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` has no field named `{2}`",
kind_name, actual, field.ident))
})).with_code(E0560)
}struct_span_code_err!(
2644 self.dcx(),
2645 field.ident.span,
2646 E0560,
2647 "{} `{}` has no field named `{}`",
2648 kind_name,
2649 actual,
2650 field.ident
2651 ),
2652 },
2653 ty,
2654 );
2655
2656 let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap();
2657 match variant.ctor {
2658 Some((CtorKind::Fn, def_id)) => match ty.kind() {
2659 ty::Adt(adt, ..) if adt.is_enum() => {
2660 err.span_context(self.tcx.def_span(adt.did()).shrink_to_lo());
2661 err.span_label(
2662 variant_ident_span,
2663 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}::{1}` defined here", ty,
variant.name))
})format!(
2664 "`{adt}::{variant}` defined here",
2665 adt = ty,
2666 variant = variant.name,
2667 ),
2668 );
2669 err.span_label(field.ident.span, "field does not exist");
2670 let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
2671 let inputs = fn_sig.inputs().skip_binder();
2672 let fields = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})",
inputs.iter().map(|i|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", i))
})).collect::<Vec<_>>().join(", ")))
})format!(
2673 "({})",
2674 inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2675 );
2676 let (replace_span, sugg) = match expr.kind {
2677 hir::ExprKind::Struct(qpath, ..) => {
2678 (qpath.span().shrink_to_hi().with_hi(expr.span.hi()), fields)
2679 }
2680 _ => {
2681 (expr.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}::{0}{2}", variant.name, ty,
fields))
})format!("{ty}::{variant}{fields}", variant = variant.name))
2682 }
2683 };
2684 err.span_suggestion_verbose(
2685 replace_span,
2686 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}::{1}` is a tuple {2}, use the appropriate syntax",
ty, variant.name, kind_name))
})format!(
2687 "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax",
2688 adt = ty,
2689 variant = variant.name,
2690 ),
2691 sugg,
2692 Applicability::HasPlaceholders,
2693 );
2694 }
2695 _ => {
2696 err.span_label(variant_ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", ty))
})format!("`{ty}` defined here"));
2697 err.span_label(field.ident.span, "field does not exist");
2698 let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
2699 let inputs = fn_sig.inputs().skip_binder();
2700 let fields = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})",
inputs.iter().map(|i|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/* {0} */", i))
})).collect::<Vec<_>>().join(", ")))
})format!(
2701 "({})",
2702 inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2703 );
2704 err.span_suggestion_verbose(
2705 expr.span,
2706 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is a tuple {1}, use the appropriate syntax",
ty, kind_name))
})format!("`{ty}` is a tuple {kind_name}, use the appropriate syntax",),
2707 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", ty, fields))
})format!("{ty}{fields}"),
2708 Applicability::HasPlaceholders,
2709 );
2710 }
2711 },
2712 _ => {
2713 let available_field_names = self.available_field_names(variant, expr, skip_fields);
2715 if let Some(field_name) =
2716 find_best_match_for_name(&available_field_names, field.ident.name, None)
2717 && !(field.ident.name.as_str().parse::<usize>().is_ok()
2718 && field_name.as_str().parse::<usize>().is_ok())
2719 {
2720 err.span_label(field.ident.span, "unknown field");
2721 err.span_suggestion_verbose(
2722 field.ident.span,
2723 "a field with a similar name exists",
2724 field_name,
2725 Applicability::MaybeIncorrect,
2726 );
2727 } else {
2728 match ty.kind() {
2729 ty::Adt(adt, ..) => {
2730 if adt.is_enum() {
2731 err.span_label(
2732 field.ident.span,
2733 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}::{1}` does not have this field",
ty, variant.name))
})format!("`{}::{}` does not have this field", ty, variant.name),
2734 );
2735 } else {
2736 err.span_label(
2737 field.ident.span,
2738 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` does not have this field",
ty))
})format!("`{ty}` does not have this field"),
2739 );
2740 }
2741 if available_field_names.is_empty() {
2742 err.note("all struct fields are already assigned");
2743 } else {
2744 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("available fields are: {0}",
self.name_series_display(available_field_names)))
})format!(
2745 "available fields are: {}",
2746 self.name_series_display(available_field_names)
2747 ));
2748 }
2749 }
2750 _ => ::rustc_span::macros::bug_impl(None,
format_args!("non-ADT passed to report_unknown_field"),
Location::caller())bug!("non-ADT passed to report_unknown_field"),
2751 }
2752 };
2753 }
2754 }
2755 err.emit_err()
2756 }
2757
2758 fn available_field_names(
2759 &self,
2760 variant: &'tcx ty::VariantDef,
2761 expr: &hir::Expr<'_>,
2762 skip_fields: &[hir::ExprField<'_>],
2763 ) -> Vec<Symbol> {
2764 variant
2765 .fields
2766 .iter()
2767 .filter(|field| {
2768 skip_fields.iter().all(|&skip| skip.ident.name != field.name)
2769 && self.is_field_suggestable(field, expr.span)
2770 })
2771 .map(|field| field.name)
2772 .collect()
2773 }
2774
2775 fn name_series_display(&self, names: Vec<Symbol>) -> String {
2776 let limit = if names.len() == 6 { 6 } else { 5 };
2778 let mut display =
2779 names.iter().take(limit).map(|n| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`")).collect::<Vec<_>>().join(", ");
2780 if names.len() > limit {
2781 display = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} ... and {1} others", display,
names.len() - limit))
})format!("{} ... and {} others", display, names.len() - limit);
2782 }
2783 display
2784 }
2785
2786 fn find_adt_field(
2790 &self,
2791 base_def: ty::AdtDef<'tcx>,
2792 ident: Ident,
2793 ) -> Option<(FieldIdx, &'tcx ty::FieldDef)> {
2794 if base_def.is_enum() {
2796 return None;
2797 }
2798
2799 for (field_idx, field) in base_def.non_enum_variant().fields.iter_enumerated() {
2800 if field.ident(self.tcx).normalize_to_macros_2_0() == ident {
2801 return Some((field_idx, field));
2803 }
2804 }
2805
2806 None
2807 }
2808
2809 fn check_expr_field(
2819 &self,
2820 expr: &'tcx hir::Expr<'tcx>,
2821 base: &'tcx hir::Expr<'tcx>,
2822 field: Ident,
2823 expected: Expectation<'tcx>,
2825 ) -> Ty<'tcx> {
2826 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:2826",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2826u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("check_field(expr: {0:?}, base: {1:?}, field: {2:?})",
expr, base, field) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("check_field(expr: {:?}, base: {:?}, field: {:?})", expr, base, field);
2827 let base_ty = self.check_expr(base);
2828 let base_ty = self.structurally_resolve_type(base.span, base_ty);
2829
2830 let mut private_candidate = None;
2832
2833 let mut autoderef = self.autoderef(expr.span, base_ty);
2835 while let Some((deref_base_ty, _)) = autoderef.next() {
2836 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:2836",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2836u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("deref_base_ty: {0:?}",
deref_base_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("deref_base_ty: {:?}", deref_base_ty);
2837 match deref_base_ty.kind() {
2838 ty::Adt(base_def, args) if !base_def.is_enum() => {
2839 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:2839",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2839u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("struct named {0:?}",
deref_base_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("struct named {:?}", deref_base_ty);
2840 if let Err(guar) = base_def.non_enum_variant().has_errors() {
2842 return Ty::new_error(self.tcx(), guar);
2843 }
2844
2845 let (ident, def_scope) =
2846 self.tcx.adjust_ident_and_get_scope(field, base_def.did(), self.mod_id);
2847
2848 if let Some((idx, field)) = self.find_adt_field(*base_def, ident) {
2849 self.write_field_index(expr.hir_id, idx);
2850
2851 let adjustments = self.adjust_steps(&autoderef);
2852 if field.vis.is_accessible_from(def_scope, self.tcx) {
2853 self.apply_adjustments(base, adjustments);
2854 self.register_predicates(autoderef.into_obligations());
2855
2856 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
2857 return self.field_ty(expr.span, field, *args);
2858 }
2859
2860 private_candidate = Some((adjustments, base_def.did()));
2862 }
2863 }
2864 ty::Tuple(tys) => {
2865 if let Ok(index) = field.as_str().parse::<usize>() {
2866 if field.name == sym::integer(index) {
2867 if let Some(&field_ty) = tys.get(index) {
2868 let adjustments = self.adjust_steps(&autoderef);
2869 self.apply_adjustments(base, adjustments);
2870 self.register_predicates(autoderef.into_obligations());
2871
2872 self.write_field_index(expr.hir_id, FieldIdx::from_usize(index));
2873 return field_ty;
2874 }
2875 }
2876 }
2877 }
2878 _ => {}
2879 }
2880 }
2881 let final_ty = self.structurally_resolve_type(autoderef.span(), autoderef.final_ty());
2887 if let ty::Error(_) = final_ty.kind() {
2888 return final_ty;
2889 }
2890
2891 if let Some((adjustments, did)) = private_candidate {
2892 self.apply_adjustments(base, adjustments);
2895 let guar = self.ban_private_field_access(
2896 expr,
2897 base_ty,
2898 field,
2899 did,
2900 expected.only_has_type(self),
2901 );
2902 return Ty::new_error(self.tcx(), guar);
2903 }
2904
2905 let guar = if self.method_exists_for_diagnostic(
2906 field,
2907 base_ty,
2908 expr.hir_id,
2909 expected.only_has_type(self),
2910 ) {
2911 self.ban_take_value_of_method(expr, base_ty, field)
2913 } else if !base_ty.is_primitive_ty() {
2914 self.ban_nonexisting_field(field, base, expr, base_ty)
2915 } else {
2916 let field_name = field.to_string();
2917 let mut err = {
let mut err =
{
self.dcx().struct_span_err(field.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is a primitive type and therefore doesn\'t have fields",
base_ty))
})).with_code(E0610)
};
if base_ty.references_error() { err.downgrade_to_delayed_bug(); }
err
}type_error_struct!(
2918 self.dcx(),
2919 field.span,
2920 base_ty,
2921 E0610,
2922 "`{base_ty}` is a primitive type and therefore doesn't have fields",
2923 );
2924 let is_valid_suffix = |field: &str| {
2925 if field == "f32" || field == "f64" {
2926 return true;
2927 }
2928 let mut chars = field.chars().peekable();
2929 match chars.peek() {
2930 Some('e') | Some('E') => {
2931 chars.next();
2932 if let Some(c) = chars.peek()
2933 && !c.is_numeric()
2934 && *c != '-'
2935 && *c != '+'
2936 {
2937 return false;
2938 }
2939 while let Some(c) = chars.peek() {
2940 if !c.is_numeric() {
2941 break;
2942 }
2943 chars.next();
2944 }
2945 }
2946 _ => (),
2947 }
2948 let suffix = chars.collect::<String>();
2949 suffix.is_empty() || suffix == "f32" || suffix == "f64"
2950 };
2951 let maybe_partial_suffix = |field: &str| -> Option<&str> {
2952 let first_chars = ['f', 'l'];
2953 if field.len() >= 1
2954 && field.to_lowercase().starts_with(first_chars)
2955 && field[1..].chars().all(|c| c.is_ascii_digit())
2956 {
2957 if field.to_lowercase().starts_with(['f']) { Some("f32") } else { Some("f64") }
2958 } else {
2959 None
2960 }
2961 };
2962 if let ty::Infer(ty::IntVar(_)) = base_ty.kind()
2963 && let ExprKind::Lit(Spanned {
2964 node: ast::LitKind::Int(_, ast::LitIntType::Unsuffixed),
2965 ..
2966 }) = base.kind
2967 && !base.span.from_expansion()
2968 {
2969 if is_valid_suffix(&field_name) {
2970 err.span_suggestion_verbose(
2971 field.span.shrink_to_lo(),
2972 "if intended to be a floating point literal, consider adding a `0` after the period",
2973 '0',
2974 Applicability::MaybeIncorrect,
2975 );
2976 } else if let Some(correct_suffix) = maybe_partial_suffix(&field_name) {
2977 err.span_suggestion_verbose(
2978 field.span,
2979 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if intended to be a floating point literal, consider adding a `0` after the period and a `{0}` suffix",
correct_suffix))
})format!("if intended to be a floating point literal, consider adding a `0` after the period and a `{correct_suffix}` suffix"),
2980 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("0{0}", correct_suffix))
})format!("0{correct_suffix}"),
2981 Applicability::MaybeIncorrect,
2982 );
2983 }
2984 }
2985 err.emit_err()
2986 };
2987
2988 Ty::new_error(self.tcx(), guar)
2989 }
2990
2991 fn suggest_await_on_field_access(
2992 &self,
2993 err: &mut Diag<'_>,
2994 field_ident: Ident,
2995 base: &'tcx hir::Expr<'tcx>,
2996 ty: Ty<'tcx>,
2997 ) {
2998 let Some(output_ty) = self.tcx.get_impl_future_output_ty(ty) else {
2999 err.span_label(field_ident.span, "unknown field");
3000 return;
3001 };
3002 let ty::Adt(def, _) = output_ty.kind() else {
3003 err.span_label(field_ident.span, "unknown field");
3004 return;
3005 };
3006 if def.is_enum() {
3008 err.span_label(field_ident.span, "unknown field");
3009 return;
3010 }
3011 if !def.non_enum_variant().fields.iter().any(|field| field.ident(self.tcx) == field_ident) {
3012 err.span_label(field_ident.span, "unknown field");
3013 return;
3014 }
3015 err.span_label(
3016 field_ident.span,
3017 "field not available in `impl Future`, but it is available in its `Output`",
3018 );
3019 match self.tcx.coroutine_kind(self.body_def_id) {
3020 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
3021 err.span_suggestion_verbose(
3022 base.span.shrink_to_hi(),
3023 "consider `await`ing on the `Future` to access the field",
3024 ".await",
3025 Applicability::MaybeIncorrect,
3026 );
3027 }
3028 _ => {
3029 let mut span: MultiSpan = base.span.into();
3030 span.push_span_label(self.tcx.def_span(self.body_def_id), "this is not `async`");
3031 err.span_note(
3032 span,
3033 "this implements `Future` and its output type has the field, \
3034 but the future cannot be awaited in a synchronous function",
3035 );
3036 }
3037 }
3038 }
3039
3040 fn ban_nonexisting_field(
3041 &self,
3042 ident: Ident,
3043 base: &'tcx hir::Expr<'tcx>,
3044 expr: &'tcx hir::Expr<'tcx>,
3045 base_ty: Ty<'tcx>,
3046 ) -> ErrorGuaranteed {
3047 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:3047",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(3047u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ban_nonexisting_field: field={0:?}, base={1:?}, expr={2:?}, base_ty={3:?}",
ident, base, expr, base_ty) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
3048 "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}",
3049 ident, base, expr, base_ty
3050 );
3051 let mut err = self.no_such_field_err(ident, base_ty, expr);
3052
3053 match *base_ty.peel_refs().kind() {
3054 ty::Array(_, len) => {
3055 self.maybe_suggest_array_indexing(&mut err, base, ident, len);
3056 }
3057 ty::RawPtr(..) => {
3058 self.suggest_first_deref_field(&mut err, base, ident);
3059 }
3060 ty::Param(param_ty) => {
3061 err.span_label(ident.span, "unknown field");
3062 self.point_at_param_definition(&mut err, param_ty);
3063 }
3064 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => {
3065 self.suggest_await_on_field_access(&mut err, ident, base, base_ty.peel_refs());
3066 }
3067 _ => {
3068 err.span_label(ident.span, "unknown field");
3069 }
3070 }
3071
3072 self.suggest_fn_call(&mut err, base, base_ty, |output_ty| {
3073 if let ty::Adt(def, _) = output_ty.kind()
3074 && !def.is_enum()
3075 {
3076 def.non_enum_variant().fields.iter().any(|field| {
3077 field.ident(self.tcx) == ident
3078 && field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
3079 })
3080 } else if let ty::Tuple(tys) = output_ty.kind()
3081 && let Ok(idx) = ident.as_str().parse::<usize>()
3082 {
3083 idx < tys.len()
3084 } else {
3085 false
3086 }
3087 });
3088
3089 if ident.name == kw::Await {
3090 err.note("to `.await` a `Future`, switch to Rust 2018 or later");
3093 HelpUseLatestEdition::new().add_to_diag(&mut err);
3094 }
3095
3096 err.emit_err()
3097 }
3098
3099 fn ban_private_field_access(
3100 &self,
3101 expr: &hir::Expr<'tcx>,
3102 expr_t: Ty<'tcx>,
3103 field: Ident,
3104 base_did: DefId,
3105 return_ty: Option<Ty<'tcx>>,
3106 ) -> ErrorGuaranteed {
3107 let mut err = self.private_field_err(field, base_did);
3108
3109 if self.method_exists_for_diagnostic(field, expr_t, expr.hir_id, return_ty)
3111 && !self.expr_in_place(expr.hir_id)
3112 {
3113 self.suggest_method_call(
3114 &mut err,
3115 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a method `{0}` also exists, call it with parentheses",
field))
})format!("a method `{field}` also exists, call it with parentheses"),
3116 field,
3117 expr_t,
3118 expr,
3119 None,
3120 );
3121 }
3122 err.emit_err()
3123 }
3124
3125 fn ban_take_value_of_method(
3126 &self,
3127 expr: &hir::Expr<'tcx>,
3128 expr_t: Ty<'tcx>,
3129 field: Ident,
3130 ) -> ErrorGuaranteed {
3131 let mut err = {
let mut err =
{
self.dcx().struct_span_err(field.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("attempted to take value of method `{0}` on type `{1}`",
field, expr_t))
})).with_code(E0615)
};
if expr_t.references_error() { err.downgrade_to_delayed_bug(); }
err
}type_error_struct!(
3132 self.dcx(),
3133 field.span,
3134 expr_t,
3135 E0615,
3136 "attempted to take value of method `{field}` on type `{expr_t}`",
3137 );
3138 err.span_label(field.span, "method, not a field");
3139 let expr_is_call =
3140 if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) =
3141 self.tcx.parent_hir_node(expr.hir_id)
3142 {
3143 expr.hir_id == callee.hir_id
3144 } else {
3145 false
3146 };
3147 let expr_snippet =
3148 self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_default();
3149 let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')');
3150 let after_open = expr.span.lo() + rustc_span::BytePos(1);
3151 let before_close = expr.span.hi() - rustc_span::BytePos(1);
3152
3153 if expr_is_call && is_wrapped {
3154 err.multipart_suggestion(
3155 "remove wrapping parentheses to call the method",
3156 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(expr.span.with_hi(after_open), String::new()),
(expr.span.with_lo(before_close), String::new())]))vec![
3157 (expr.span.with_hi(after_open), String::new()),
3158 (expr.span.with_lo(before_close), String::new()),
3159 ],
3160 Applicability::MachineApplicable,
3161 );
3162 } else if !self.expr_in_place(expr.hir_id) {
3163 let span = if is_wrapped {
3165 expr.span.with_lo(after_open).with_hi(before_close)
3166 } else {
3167 expr.span
3168 };
3169 self.suggest_method_call(
3170 &mut err,
3171 "use parentheses to call the method",
3172 field,
3173 expr_t,
3174 expr,
3175 Some(span),
3176 );
3177 } else if let ty::RawPtr(ptr_ty, _) = expr_t.kind()
3178 && let ty::Adt(adt_def, _) = ptr_ty.kind()
3179 && let ExprKind::Field(base_expr, _) = expr.kind
3180 && let [variant] = &adt_def.variants().raw
3181 && variant.fields.iter().any(|f| f.ident(self.tcx) == field)
3182 {
3183 err.multipart_suggestion(
3184 "to access the field, dereference first",
3185 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(base_expr.span.shrink_to_lo(), "(*".to_string()),
(base_expr.span.shrink_to_hi(), ")".to_string())]))vec![
3186 (base_expr.span.shrink_to_lo(), "(*".to_string()),
3187 (base_expr.span.shrink_to_hi(), ")".to_string()),
3188 ],
3189 Applicability::MaybeIncorrect,
3190 );
3191 } else {
3192 err.help("methods are immutable and cannot be assigned to");
3193 }
3194
3195 self.dcx().try_steal_replace_and_emit_err(field.span, StashKey::GenericInFieldExpr, err)
3197 }
3198
3199 fn point_at_param_definition(&self, err: &mut Diag<'_>, param: ty::ParamTy) {
3200 let generics = self.tcx.generics_of(self.body_def_id);
3201 let generic_param = generics.type_param(param, self.tcx);
3202 if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
3203 return;
3204 }
3205 let param_def_id = generic_param.def_id;
3206 let param_hir_id = match param_def_id.as_local() {
3207 Some(x) => self.tcx.local_def_id_to_hir_id(x),
3208 None => return,
3209 };
3210 let param_span = self.tcx.hir_span(param_hir_id);
3211 let param_name = self.tcx.hir_ty_param_name(param_def_id.expect_local());
3212
3213 err.span_label(param_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type parameter \'{0}\' declared here",
param_name))
})format!("type parameter '{param_name}' declared here"));
3214 }
3215
3216 fn maybe_suggest_array_indexing(
3217 &self,
3218 err: &mut Diag<'_>,
3219 base: &hir::Expr<'_>,
3220 field: Ident,
3221 len: ty::Const<'tcx>,
3222 ) {
3223 err.span_label(field.span, "unknown field");
3224 if let (Some(len), Ok(user_index)) = (
3225 self.try_structurally_resolve_const(base.span, len).try_to_target_usize(self.tcx),
3226 field.as_str().parse::<u64>(),
3227 ) {
3228 let help = "instead of using tuple indexing, use array indexing";
3229 let applicability = if len < user_index {
3230 Applicability::MachineApplicable
3231 } else {
3232 Applicability::MaybeIncorrect
3233 };
3234 err.multipart_suggestion(
3235 help,
3236 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(base.span.between(field.span), "[".to_string()),
(field.span.shrink_to_hi(), "]".to_string())]))vec![
3237 (base.span.between(field.span), "[".to_string()),
3238 (field.span.shrink_to_hi(), "]".to_string()),
3239 ],
3240 applicability,
3241 );
3242 }
3243 }
3244
3245 fn suggest_first_deref_field(&self, err: &mut Diag<'_>, base: &hir::Expr<'_>, field: Ident) {
3246 err.span_label(field.span, "unknown field");
3247 if base.span.from_expansion() || field.span.from_expansion() {
3248 return;
3249 }
3250 let val = if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span)
3251 && base.len() < 20
3252 {
3253 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", base))
})format!("`{base}`")
3254 } else {
3255 "the value".to_string()
3256 };
3257 err.multipart_suggestion(
3258 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is a raw pointer; try dereferencing it",
val))
})format!("{val} is a raw pointer; try dereferencing it"),
3259 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(base.span.shrink_to_lo(), "(*".into()),
(base.span.between(field.span),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(")."))
}))]))vec![
3260 (base.span.shrink_to_lo(), "(*".into()),
3261 (base.span.between(field.span), format!(").")),
3262 ],
3263 Applicability::MaybeIncorrect,
3264 );
3265 }
3266
3267 fn no_such_field_err(
3268 &self,
3269 field: Ident,
3270 base_ty: Ty<'tcx>,
3271 expr: &hir::Expr<'tcx>,
3272 ) -> Diag<'_> {
3273 let span = field.span;
3274 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:3274",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(3274u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("no_such_field_err(span: {0:?}, field: {1:?}, expr_t: {2:?})",
span, field, base_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, base_ty);
3275
3276 let mut err = self.dcx().create_err(NoFieldOnType { span, ty: base_ty, field });
3277 if base_ty.references_error() {
3278 err.downgrade_to_delayed_bug();
3279 }
3280
3281 if let Some(within_macro_span) = span.within_macro(expr.span, self.tcx.sess.source_map()) {
3282 err.span_label(within_macro_span, "due to this macro variable");
3283 }
3284
3285 if let Some(def_id) = base_ty.peel_refs().ty_adt_def().map(|d| d.did()) {
3287 for &impl_def_id in self.tcx.inherent_impls(def_id) {
3288 for item in self.tcx.associated_items(impl_def_id).in_definition_order() {
3289 if let ExprKind::Field(base_expr, _) = expr.kind
3290 && item.name() == field.name
3291 && #[allow(non_exhaustive_omitted_patterns)] match item.kind {
ty::AssocKind::Fn { has_self: false, .. } => true,
_ => false,
}matches!(item.kind, ty::AssocKind::Fn { has_self: false, .. })
3292 {
3293 err.span_label(field.span, "this is an associated function, not a method");
3294 err.note("found the following associated function; to be used as method, it must have a `self` parameter");
3295 let impl_ty =
3296 self.tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip();
3297 err.span_note(
3298 self.tcx.def_span(item.def_id),
3299 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the candidate is defined in an impl for the type `{0}`",
impl_ty))
})format!("the candidate is defined in an impl for the type `{impl_ty}`"),
3300 );
3301
3302 let ty_str = match base_ty.peel_refs().kind() {
3303 ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), *args),
3304 _ => base_ty.peel_refs().to_string(),
3305 };
3306 err.multipart_suggestion(
3307 "use associated function syntax instead",
3308 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(base_expr.span, ty_str),
(base_expr.span.between(field.span), "::".to_string())]))vec![
3309 (base_expr.span, ty_str),
3310 (base_expr.span.between(field.span), "::".to_string()),
3311 ],
3312 Applicability::MaybeIncorrect,
3313 );
3314 return err;
3315 }
3316 }
3317 }
3318 }
3319
3320 let (ty, unwrap) = if let ty::Adt(def, args) = base_ty.kind()
3322 && (self.tcx.is_diagnostic_item(sym::Result, def.did())
3323 || self.tcx.is_diagnostic_item(sym::Option, def.did()))
3324 && let Some(arg) = args.get(0)
3325 && let Some(ty) = arg.as_type()
3326 {
3327 (ty, "unwrap().")
3328 } else {
3329 (base_ty, "")
3330 };
3331 for found_fields in self.get_field_candidates_considering_privacy_for_diag(span, ty) {
3332 let field_names = found_fields.iter().map(|field| field.0.name).collect::<Vec<_>>();
3333 let mut candidate_fields: Vec<_> = found_fields
3334 .into_iter()
3335 .filter_map(|candidate_field| {
3336 self.check_for_nested_field_satisfying_condition_for_diag(
3337 span,
3338 &|candidate_field, _| candidate_field == field,
3339 candidate_field,
3340 ::alloc::vec::Vec::new()vec![],
3341 )
3342 })
3343 .map(|mut field_path| {
3344 field_path.pop();
3345 field_path.iter().map(|id| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.", id))
})format!("{}.", id)).collect::<String>()
3346 })
3347 .collect::<Vec<_>>();
3348 candidate_fields.sort();
3349
3350 let len = candidate_fields.len();
3351 if len > 0 && expr.span.ctxt() == field.span.ctxt() {
3354 err.span_suggestions(
3355 field.span.shrink_to_lo(),
3356 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} of the expressions\' fields {1} a field of the same name",
if len > 1 { "some" } else { "one" },
if len > 1 { "have" } else { "has" }))
})format!(
3357 "{} of the expressions' fields {} a field of the same name",
3358 if len > 1 { "some" } else { "one" },
3359 if len > 1 { "have" } else { "has" },
3360 ),
3361 candidate_fields.iter().map(|path| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", unwrap, path))
})format!("{unwrap}{path}")),
3362 Applicability::MaybeIncorrect,
3363 );
3364 } else if let Some(field_name) =
3365 find_best_match_for_name(&field_names, field.name, None)
3366 && !(field.name.as_str().parse::<usize>().is_ok()
3367 && field_name.as_str().parse::<usize>().is_ok())
3368 {
3369 err.span_suggestion_verbose(
3370 field.span,
3371 "a field with a similar name exists",
3372 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}", field_name, unwrap))
})format!("{unwrap}{}", field_name),
3373 Applicability::MaybeIncorrect,
3374 );
3375 } else if !field_names.is_empty() {
3376 let is = if field_names.len() == 1 { " is" } else { "s are" };
3377 err.note(
3378 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("available field{1}: {0}",
self.name_series_display(field_names), is))
})format!("available field{is}: {}", self.name_series_display(field_names),),
3379 );
3380 }
3381 }
3382 err
3383 }
3384
3385 fn private_field_err(&self, field: Ident, base_did: DefId) -> Diag<'_> {
3386 let struct_path = self.tcx().def_path_str(base_did);
3387 let kind_name = self.tcx().def_descr(base_did);
3388 {
self.dcx().struct_span_err(field.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("field `{0}` of {1} `{2}` is private",
field, kind_name, struct_path))
})).with_code(E0616)
}struct_span_code_err!(
3389 self.dcx(),
3390 field.span,
3391 E0616,
3392 "field `{field}` of {kind_name} `{struct_path}` is private",
3393 )
3394 .with_span_label(field.span, "private field")
3395 }
3396
3397 pub(crate) fn get_field_candidates_considering_privacy_for_diag(
3398 &self,
3399 span: Span,
3400 base_ty: Ty<'tcx>,
3401 ) -> Vec<Vec<(Ident, Ty<'tcx>)>> {
3402 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs:3402",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(3402u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("get_field_candidates(span: {0:?}, base_t: {1:?}",
span, base_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_ty);
3403
3404 let mut autoderef = self.autoderef(span, base_ty).silence_errors();
3405 let deref_chain: Vec<_> = autoderef.by_ref().collect();
3406
3407 if autoderef.reached_recursion_limit() {
3411 return ::alloc::vec::Vec::new()vec![];
3412 }
3413
3414 deref_chain
3415 .into_iter()
3416 .filter_map(move |(base_t, _)| {
3417 match base_t.kind() {
3418 ty::Adt(base_def, args) if !base_def.is_enum() => {
3419 let tcx = self.tcx;
3420 let fields = &base_def.non_enum_variant().fields;
3421 if fields
3425 .iter()
3426 .all(|field| !field.vis.is_accessible_from(self.mod_id, tcx))
3427 {
3428 return None;
3429 }
3430 return Some(
3431 fields
3432 .iter()
3433 .filter(move |field| {
3434 field.vis.is_accessible_from(self.mod_id, tcx)
3435 && self.is_field_suggestable(field, span)
3436 })
3437 .take(100)
3439 .map(|field_def| {
3440 (
3441 field_def.ident(self.tcx).normalize_to_macros_2_0(),
3442 field_def.ty(self.tcx, *args).skip_norm_wip(),
3443 )
3444 })
3445 .collect::<Vec<_>>(),
3446 );
3447 }
3448 ty::Tuple(types) => {
3449 return Some(
3450 types
3451 .iter()
3452 .enumerate()
3453 .take(100)
3455 .map(|(i, ty)| (Ident::from_str(&i.to_string()), ty))
3456 .collect::<Vec<_>>(),
3457 );
3458 }
3459 _ => None,
3460 }
3461 })
3462 .collect()
3463 }
3464
3465 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_for_nested_field_satisfying_condition_for_diag",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(3467u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::expr"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("candidate_name")
}> =
::tracing::__macro_support::FieldName::new("candidate_name");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("candidate_ty")
}> =
::tracing::__macro_support::FieldName::new("candidate_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("field_path")
}> =
::tracing::__macro_support::FieldName::new("field_path");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate_name)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidate_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&field_path)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Option<Vec<Ident>> = loop {};
return __tracing_attr_fake_return;
}
{
if field_path.len() > 3 { return None; }
field_path.push(candidate_name);
if matches(candidate_name, candidate_ty) {
return Some(field_path);
}
for nested_fields in
self.get_field_candidates_considering_privacy_for_diag(span,
candidate_ty) {
for field in nested_fields {
if let Some(field_path) =
self.check_for_nested_field_satisfying_condition_for_diag(span,
matches, field, field_path.clone()) {
return Some(field_path);
}
}
}
None
}
}
}#[instrument(skip(self, matches), level = "debug")]
3468 pub(crate) fn check_for_nested_field_satisfying_condition_for_diag(
3469 &self,
3470 span: Span,
3471 matches: &impl Fn(Ident, Ty<'tcx>) -> bool,
3472 (candidate_name, candidate_ty): (Ident, Ty<'tcx>),
3473 mut field_path: Vec<Ident>,
3474 ) -> Option<Vec<Ident>> {
3475 if field_path.len() > 3 {
3476 return None;
3479 }
3480 field_path.push(candidate_name);
3481 if matches(candidate_name, candidate_ty) {
3482 return Some(field_path);
3483 }
3484 for nested_fields in
3485 self.get_field_candidates_considering_privacy_for_diag(span, candidate_ty)
3486 {
3487 for field in nested_fields {
3489 if let Some(field_path) = self.check_for_nested_field_satisfying_condition_for_diag(
3490 span,
3491 matches,
3492 field,
3493 field_path.clone(),
3494 ) {
3495 return Some(field_path);
3496 }
3497 }
3498 }
3499 None
3500 }
3501
3502 fn check_expr_index(
3503 &self,
3504 base: &'tcx hir::Expr<'tcx>,
3505 idx: &'tcx hir::Expr<'tcx>,
3506 expr: &'tcx hir::Expr<'tcx>,
3507 brackets_span: Span,
3508 ) -> Ty<'tcx> {
3509 let base_t = self.check_expr(base);
3510 let idx_t = self.check_expr(idx);
3511
3512 if base_t.references_error() {
3513 base_t
3514 } else if idx_t.references_error() {
3515 idx_t
3516 } else {
3517 let base_t = self.structurally_resolve_type(base.span, base_t);
3518 match self.lookup_indexing(expr, base, base_t, idx, idx_t) {
3519 Some((index_ty, element_ty)) => {
3520 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3522 self.select_obligations_where_possible(|errors| {
3523 self.point_at_index(errors, idx.span);
3524 });
3525 element_ty
3526 }
3527 None => {
3528 for (base_t, _) in self.autoderef(base.span, base_t).silence_errors() {
3531 if let Some((_, index_ty, element_ty)) =
3532 self.find_and_report_unsatisfied_index_impl(base, base_t)
3533 {
3534 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3535 return element_ty;
3536 }
3537 }
3538
3539 let mut err = {
let mut err =
{
self.dcx().struct_span_err(brackets_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot index into a value of type `{0}`",
base_t))
})).with_code(E0608)
};
if base_t.references_error() { err.downgrade_to_delayed_bug(); }
err
}type_error_struct!(
3540 self.dcx(),
3541 brackets_span,
3542 base_t,
3543 E0608,
3544 "cannot index into a value of type `{base_t}`",
3545 );
3546 if let ty::Tuple(types) = base_t.kind() {
3548 err.help(
3549 "tuples are indexed with a dot and a literal index: `tuple.0`, `tuple.1`, etc.",
3550 );
3551 if let ExprKind::Lit(lit) = idx.kind
3553 && let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node
3554 && i.get() < types.len().try_into().expect("tuple length fits in u128")
3555 {
3556 err.span_suggestion(
3557 brackets_span,
3558 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to access tuple element `{0}`, use",
i))
})format!("to access tuple element `{i}`, use"),
3559 ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!(".{0}", i)) })format!(".{i}"),
3560 Applicability::MachineApplicable,
3561 );
3562 }
3563 }
3564
3565 if base_t.is_raw_ptr() && idx_t.is_integral() {
3566 err.multipart_suggestion(
3567 "consider using `wrapping_add` or `add` for indexing into raw pointer",
3568 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(base.span.between(idx.span), ".wrapping_add(".to_owned()),
(idx.span.shrink_to_hi().until(expr.span.shrink_to_hi()),
")".to_owned())]))vec![
3569 (base.span.between(idx.span), ".wrapping_add(".to_owned()),
3570 (
3571 idx.span.shrink_to_hi().until(expr.span.shrink_to_hi()),
3572 ")".to_owned(),
3573 ),
3574 ],
3575 Applicability::MaybeIncorrect,
3576 );
3577 }
3578
3579 let guar = err.emit_err();
3580 Ty::new_error(self.tcx, guar)
3581 }
3582 }
3583 }
3584 }
3585
3586 fn find_and_report_unsatisfied_index_impl(
3594 &self,
3595 base_expr: &hir::Expr<'_>,
3596 base_ty: Ty<'tcx>,
3597 ) -> Option<(ErrorGuaranteed, Ty<'tcx>, Ty<'tcx>)> {
3598 let index_trait_def_id = self.tcx.lang_items().index_trait()?;
3599 let index_trait_output_def_id = self.tcx.get_diagnostic_item(sym::IndexOutput)?;
3600
3601 let mut relevant_impls = ::alloc::vec::Vec::new()vec![];
3602 self.tcx.for_each_relevant_impl(index_trait_def_id, base_ty, |impl_def_id| {
3603 relevant_impls.push(impl_def_id);
3604 });
3605 let [impl_def_id] = relevant_impls[..] else {
3606 return None;
3608 };
3609
3610 self.commit_if_ok(|snapshot| {
3611 let outer_universe = self.universe();
3612
3613 let ocx = ObligationCtxt::new_with_diagnostics(self);
3614 let impl_args = self.fresh_args_for_item(base_expr.span, impl_def_id);
3615 let impl_trait_ref =
3616 self.tcx.impl_trait_ref(impl_def_id).instantiate(self.tcx, impl_args);
3617 let cause = self.misc(base_expr.span);
3618
3619 let impl_trait_ref = ocx.normalize(&cause, self.param_env, impl_trait_ref);
3622 ocx.eq(&cause, self.param_env, base_ty, impl_trait_ref.self_ty())?;
3623
3624 let unnormalized_clauses =
3628 self.tcx.clauses_of(impl_def_id).instantiate(self.tcx, impl_args);
3629 ocx.register_obligations(traits::predicates_for_generics(
3630 |idx, span| {
3631 cause.clone().derived_cause(
3632 ty::Binder::dummy(ty::TraitClause {
3633 trait_ref: impl_trait_ref,
3634 polarity: ty::ClausePolarity::Positive,
3635 }),
3636 |derived| {
3637 ObligationCauseCode::ImplDerived(Box::new(traits::ImplDerivedCause {
3638 derived,
3639 impl_or_alias_def_id: impl_def_id,
3640 impl_def_clause_index: Some(idx),
3641 span,
3642 }))
3643 },
3644 )
3645 },
3646 |clause| ocx.normalize(&cause, self.param_env, clause),
3647 self.param_env,
3648 unnormalized_clauses,
3649 ));
3650
3651 let element_ty = ocx.normalize(
3654 &cause,
3655 self.param_env,
3656 Unnormalized::new(Ty::new_projection_from_args(
3657 self.tcx,
3658 ty::IsRigid::No,
3659 index_trait_output_def_id,
3660 impl_trait_ref.args,
3661 )),
3662 );
3663
3664 let true_errors = ocx.try_evaluate_obligations();
3665
3666 self.leak_check(outer_universe, Some(snapshot))?;
3670
3671 let ambiguity_errors = ocx.evaluate_obligations_error_on_ambiguity();
3673 if true_errors.no_errors() && ambiguity_errors.has_errors() {
3674 return Err(NoSolution);
3675 }
3676
3677 Ok::<_, NoSolution>((
3680 self.err_ctxt().report_fulfillment_errors(true_errors.into_thin_vec()),
3681 impl_trait_ref.args.type_at(1),
3682 element_ty,
3683 ))
3684 })
3685 .ok()
3686 }
3687
3688 fn point_at_index(&self, errors: &mut ThinVec<traits::FulfillmentError<'tcx>>, span: Span) {
3689 let mut seen_preds = FxHashSet::default();
3690 errors.sort_by_key(|error| error.root_obligation.recursion_depth);
3694 for error in errors {
3695 match (
3696 error.root_obligation.predicate.kind().skip_binder(),
3697 error.obligation.predicate.kind().skip_binder(),
3698 ) {
3699 (ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)), _)
3700 if self.tcx.is_lang_item(predicate.trait_ref.def_id, LangItem::Index) =>
3701 {
3702 seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3703 }
3704 (_, ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)))
3705 if self.tcx.is_diagnostic_item(sym::SliceIndex, predicate.trait_ref.def_id) =>
3706 {
3707 seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3708 }
3709 (root, pred) if seen_preds.contains(&pred) || seen_preds.contains(&root) => {}
3710 _ => continue,
3711 }
3712 error.obligation.cause.span = span;
3713 }
3714 }
3715
3716 fn check_expr_yield(
3717 &self,
3718 value: &'tcx hir::Expr<'tcx>,
3719 expr: &'tcx hir::Expr<'tcx>,
3720 ) -> Ty<'tcx> {
3721 match self.coroutine_types {
3722 Some(CoroutineTypes { resume_ty, yield_ty }) => {
3723 self.check_expr_coercible_to_type(value, yield_ty, None);
3724
3725 resume_ty
3726 }
3727 _ => {
3728 self.dcx().emit_err(YieldExprOutsideOfCoroutine { span: expr.span });
3729 self.check_expr(value);
3731 self.tcx.types.unit
3732 }
3733 }
3734 }
3735
3736 fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
3737 let needs = if is_input { Needs::None } else { Needs::MutPlace };
3738 let ty = self.check_expr_with_needs(expr, needs);
3739 self.require_type_is_sized(ty, expr.span, ObligationCauseCode::InlineAsmSized);
3740
3741 if !is_input && !expr.is_syntactic_place_expr() {
3742 self.dcx()
3743 .struct_span_err(expr.span, "invalid asm output")
3744 .with_span_label(expr.span, "cannot assign to this expression")
3745 .emit();
3746 }
3747
3748 if is_input {
3756 let ty = self.structurally_resolve_type(expr.span, ty);
3757 match *ty.kind() {
3758 ty::FnDef(..) => {
3759 let fnptr_ty = Ty::new_fn_ptr(self.tcx, ty.fn_sig(self.tcx));
3760 self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
3761 }
3762 ty::Ref(_, base_ty, mutbl) => {
3763 let ptr_ty = Ty::new_ptr(self.tcx, base_ty, mutbl);
3764 self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
3765 }
3766 _ => {}
3767 }
3768 }
3769 }
3770
3771 fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) -> Ty<'tcx> {
3772 if let rustc_ast::AsmMacro::NakedAsm = asm.asm_macro {
3773 if !{
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(self.body_def_id,
&self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Naked(..)) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, self.body_def_id, Naked(..)) {
3774 self.tcx.dcx().emit_err(NakedAsmOutsideNakedFn { span });
3775 }
3776 }
3777
3778 let mut diverge = asm.asm_macro.diverges(asm.options);
3779
3780 for (op, _op_sp) in asm.operands {
3781 match *op {
3782 hir::InlineAsmOperand::In { expr, .. } => {
3783 self.check_expr_asm_operand(expr, true);
3784 }
3785 hir::InlineAsmOperand::Out { expr: Some(expr), .. }
3786 | hir::InlineAsmOperand::InOut { expr, .. } => {
3787 self.check_expr_asm_operand(expr, false);
3788 }
3789 hir::InlineAsmOperand::Out { expr: None, .. } => {}
3790 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
3791 self.check_expr_asm_operand(in_expr, true);
3792 if let Some(out_expr) = out_expr {
3793 self.check_expr_asm_operand(out_expr, false);
3794 }
3795 }
3796 hir::InlineAsmOperand::Const { ref anon_const } => {
3797 let body = self.tcx.hir_body(anon_const.body);
3801
3802 let fcx = FnCtxt::new(self, self.param_env, anon_const.def_id);
3803 let ty = fcx.check_expr(body.value);
3804 let target_ty = match self.structurally_resolve_type(body.value.span, ty).kind()
3805 {
3806 ty::FnDef(..) => {
3807 let fn_sig = ty.fn_sig(self.tcx());
3808 Ty::new_fn_ptr(self.tcx(), fn_sig)
3809 }
3810 ty::Closure(_, args) => {
3811 let closure_sig = args.as_closure().sig();
3812 let fn_sig =
3813 self.tcx().signature_unclosure(closure_sig, hir::Safety::Safe);
3814 Ty::new_fn_ptr(self.tcx(), fn_sig)
3815 }
3816 _ => ty,
3817 };
3818
3819 if let Err(diag) =
3820 self.demand_coerce_diag(&body.value, ty, target_ty, None, AllowTwoPhase::No)
3821 {
3822 diag.emit();
3823 }
3824
3825 fcx.require_type_is_sized(
3826 target_ty,
3827 body.value.span,
3828 ObligationCauseCode::SizedConstOrStatic,
3829 );
3830 fcx.write_ty(anon_const.hir_id, target_ty);
3831 }
3832 hir::InlineAsmOperand::SymFn { expr } => {
3833 self.check_expr(expr);
3834 }
3835 hir::InlineAsmOperand::SymStatic { .. } => {}
3836 hir::InlineAsmOperand::Label { block } => {
3837 let previous_diverges = self.diverges.get();
3838
3839 let ty = self.check_expr_block(block, ExpectHasType(self.tcx.types.unit));
3841 if !ty.is_never() {
3842 self.demand_suptype(block.span, self.tcx.types.unit, ty);
3843 diverge = false;
3844 }
3845
3846 self.diverges.set(previous_diverges);
3848 }
3849 }
3850 }
3851
3852 if diverge { self.tcx.types.never } else { self.tcx.types.unit }
3853 }
3854
3855 fn check_expr_offset_of(
3856 &self,
3857 container: &'tcx hir::Ty<'tcx>,
3858 fields: &[Ident],
3859 expr: &'tcx hir::Expr<'tcx>,
3860 ) -> Ty<'tcx> {
3861 let mut current_container = self.lower_ty(container).normalized;
3862 let mut field_indices = Vec::with_capacity(fields.len());
3863 let mut fields = fields.into_iter();
3864
3865 while let Some(&field) = fields.next() {
3866 let container = self.structurally_resolve_type(expr.span, current_container);
3867
3868 match container.kind() {
3869 ty::Adt(container_def, args) if container_def.is_enum() => {
3870 let ident = self.tcx.adjust_ident(field, container_def.did());
3871
3872 if !self.tcx.features().offset_of_enum() {
3873 rustc_session::diagnostics::feature_err(
3874 &self.tcx.sess,
3875 sym::offset_of_enum,
3876 ident.span,
3877 "using enums in offset_of is experimental",
3878 )
3879 .emit();
3880 }
3881
3882 let Some((index, variant)) = container_def
3883 .variants()
3884 .iter_enumerated()
3885 .find(|(_, v)| v.ident(self.tcx).normalize_to_macros_2_0() == ident)
3886 else {
3887 self.dcx()
3888 .create_err(NoVariantNamed { span: ident.span, ident, ty: container })
3889 .with_span_label(field.span, "variant not found")
3890 .emit_err_unless_delay(container.references_error());
3891 break;
3892 };
3893 let Some(&subfield) = fields.next() else {
3894 {
let mut err =
{
self.dcx().struct_span_err(ident.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is an enum variant; expected field at end of `offset_of`",
ident))
})).with_code(E0795)
};
if container.references_error() { err.downgrade_to_delayed_bug(); }
err
}type_error_struct!(
3895 self.dcx(),
3896 ident.span,
3897 container,
3898 E0795,
3899 "`{ident}` is an enum variant; expected field at end of `offset_of`",
3900 )
3901 .with_span_label(field.span, "enum variant")
3902 .emit();
3903 break;
3904 };
3905 let (subident, sub_def_scope) =
3906 self.tcx.adjust_ident_and_get_scope(subfield, variant.def_id, self.mod_id);
3907
3908 let Some((subindex, field)) = variant
3909 .fields
3910 .iter_enumerated()
3911 .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == subident)
3912 else {
3913 self.dcx()
3914 .create_err(NoFieldOnVariant {
3915 span: ident.span,
3916 container,
3917 ident,
3918 field: subfield,
3919 enum_span: field.span,
3920 field_span: subident.span,
3921 })
3922 .emit_err_unless_delay(container.references_error());
3923 break;
3924 };
3925
3926 let field_ty = self.field_ty(expr.span, field, *args);
3927
3928 self.require_type_is_sized(
3931 field_ty,
3932 expr.span,
3933 ObligationCauseCode::FieldSized {
3934 adt_kind: AdtKind::Enum,
3935 span: self.tcx.def_span(field.did),
3936 last: false,
3937 },
3938 );
3939
3940 if field.vis.is_accessible_from(sub_def_scope, self.tcx) {
3941 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3942 } else {
3943 self.private_field_err(ident, container_def.did()).emit();
3944 }
3945
3946 field_indices.push((current_container, index, subindex));
3949 current_container = field_ty;
3950
3951 continue;
3952 }
3953 ty::Adt(container_def, args) => {
3954 let (ident, def_scope) = self.tcx.adjust_ident_and_get_scope(
3955 field,
3956 container_def.did(),
3957 self.mod_id,
3958 );
3959
3960 let fields = &container_def.non_enum_variant().fields;
3961 if let Some((index, field)) = fields
3962 .iter_enumerated()
3963 .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == ident)
3964 {
3965 let field_ty = self.field_ty(expr.span, field, *args);
3966
3967 if self.tcx.features().offset_of_slice() {
3968 self.require_type_has_static_alignment(field_ty, expr.span);
3969 } else {
3970 self.require_type_is_sized(
3971 field_ty,
3972 expr.span,
3973 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(expr.hir_id)),
3974 );
3975 }
3976
3977 if field.vis.is_accessible_from(def_scope, self.tcx) {
3978 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3979 } else {
3980 self.private_field_err(ident, container_def.did()).emit();
3981 }
3982
3983 field_indices.push((current_container, FIRST_VARIANT, index));
3986 current_container = field_ty;
3987
3988 continue;
3989 }
3990 }
3991 ty::Tuple(tys) => {
3992 if let Ok(index) = field.as_str().parse::<usize>()
3993 && field.name == sym::integer(index)
3994 {
3995 if let Some(&field_ty) = tys.get(index) {
3996 if self.tcx.features().offset_of_slice() {
3997 self.require_type_has_static_alignment(field_ty, expr.span);
3998 } else {
3999 self.require_type_is_sized(
4000 field_ty,
4001 expr.span,
4002 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(
4003 expr.hir_id,
4004 )),
4005 );
4006 }
4007
4008 field_indices.push((current_container, FIRST_VARIANT, index.into()));
4009 current_container = field_ty;
4010
4011 continue;
4012 }
4013 }
4014 }
4015 _ => (),
4016 };
4017
4018 self.no_such_field_err(field, container, expr).emit();
4019
4020 break;
4021 }
4022
4023 self.typeck_results.borrow_mut().offset_of_data_mut().insert(expr.hir_id, field_indices);
4024
4025 self.tcx.types.usize
4026 }
4027}