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