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::error::{ExpectedFound, TypeError};
30use rustc_middle::ty::{self, AdtKind, GenericArgsRef, Ty, TypeVisitableExt, Unnormalized};
31use rustc_middle::{bug, span_bug};
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, kw, 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.resolve_vars_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("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 compiler/rustc_hir_typeck/src/expr.rs:229",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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 compiler/rustc_hir_typeck/src/expr.rs:234",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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 compiler/rustc_hir_typeck/src/expr.rs:235",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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.resolve_vars_if_possible(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.resolve_vars_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 compiler/rustc_hir_typeck/src/expr.rs:317",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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 compiler/rustc_hir_typeck/src/expr.rs:318",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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("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 compiler/rustc_hir_typeck/src/expr.rs:329",
"rustc_hir_typeck::expr", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("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 Ty::new_error(tcx, err.emit())
434 }),
435 hir::UnOp::Not => {
436 let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
437 if oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool { oprnd_t } else { result }
439 }
440 hir::UnOp::Neg => {
441 let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
442 if oprnd_t.is_numeric() { oprnd_t } else { result }
444 }
445 }
446 }
447
448 fn check_expr_addr_of(
449 &self,
450 kind: hir::BorrowKind,
451 mutbl: hir::Mutability,
452 oprnd: &'tcx hir::Expr<'tcx>,
453 expected: Expectation<'tcx>,
454 expr: &'tcx hir::Expr<'tcx>,
455 ) -> Ty<'tcx> {
456 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
457 match self.resolve_vars_with_obligations(ty).kind() {
458 ty::Ref(_, ty, _) | ty::RawPtr(ty, _) => {
459 if oprnd.is_syntactic_place_expr() {
460 ExpectHasType(*ty)
464 } else {
465 Expectation::rvalue_hint(self, *ty)
466 }
467 }
468 _ => NoExpectation,
469 }
470 });
471 let ty =
472 self.check_expr_with_expectation_and_needs(oprnd, hint, Needs::maybe_mut_place(mutbl));
473 if let Err(guar) = ty.error_reported() {
474 return Ty::new_error(self.tcx, guar);
475 }
476
477 match kind {
478 hir::BorrowKind::Raw => {
479 self.check_named_place_expr(oprnd);
480 Ty::new_ptr(self.tcx, ty, mutbl)
481 }
482 hir::BorrowKind::Ref | hir::BorrowKind::Pin => {
483 let region = self.next_region_var(RegionVariableOrigin::BorrowRegion(expr.span));
498 match kind {
499 hir::BorrowKind::Ref => Ty::new_ref(self.tcx, region, ty, mutbl),
500 hir::BorrowKind::Pin => Ty::new_pinned_ref(self.tcx, region, ty, mutbl),
501 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
502 }
503 }
504 }
505 }
506
507 fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
513 let is_named = oprnd.is_place_expr(|base| {
514 self.typeck_results
526 .borrow()
527 .adjustments()
528 .get(base.hir_id)
529 .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(_))))
530 });
531 if !is_named {
532 self.dcx().emit_err(AddressOfTemporaryTaken { span: oprnd.span });
533 }
534 }
535
536 pub(crate) fn check_expr_path(
537 &self,
538 qpath: &'tcx hir::QPath<'tcx>,
539 expr: &'tcx hir::Expr<'tcx>,
540 call_expr_and_args: Option<(&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>])>,
541 ) -> Ty<'tcx> {
542 let tcx = self.tcx;
543
544 if let Some((_, [arg])) = call_expr_and_args
545 && let QPath::Resolved(_, path) = qpath
546 && let Res::Def(_, def_id) = path.res
547 && let Some(lang_item) = tcx.lang_items().from_def_id(def_id)
548 {
549 let code = match lang_item {
550 LangItem::IntoFutureIntoFuture
551 if expr.span.is_desugaring(DesugaringKind::Await) =>
552 {
553 Some(ObligationCauseCode::AwaitableExpr(arg.hir_id))
554 }
555 LangItem::IntoIterIntoIter | LangItem::IteratorNext
556 if expr.span.is_desugaring(DesugaringKind::ForLoop) =>
557 {
558 Some(ObligationCauseCode::ForLoopIterator)
559 }
560 LangItem::TryTraitFromOutput
561 if expr.span.is_desugaring(DesugaringKind::TryBlock) =>
562 {
563 Some(ObligationCauseCode::QuestionMark)
565 }
566 LangItem::TryTraitBranch | LangItem::TryTraitFromResidual
567 if expr.span.is_desugaring(DesugaringKind::QuestionMark) =>
568 {
569 Some(ObligationCauseCode::QuestionMark)
570 }
571 _ => None,
572 };
573 if let Some(code) = code {
574 let args = self.fresh_args_for_item(expr.span, def_id);
575 self.add_required_obligations_with_code(expr.span, def_id, args, |_, _| {
576 code.clone()
577 });
578 return tcx.type_of(def_id).instantiate(tcx, args).skip_norm_wip();
579 }
580 }
581
582 let (res, opt_ty, segs) =
583 self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span);
584 let ty = match res {
585 Res::Err => {
586 self.suggest_assoc_method_call(segs);
587 let e =
588 self.dcx().span_delayed_bug(qpath.span(), "`Res::Err` but no error emitted");
589 Ty::new_error(tcx, e)
590 }
591 Res::Def(DefKind::Variant, _) => {
592 let e = self.report_unexpected_variant_res(
593 res,
594 Some(expr),
595 &[],
596 qpath,
597 expr.span,
598 E0533,
599 "value",
600 );
601 Ty::new_error(tcx, e)
602 }
603 _ => {
604 self.instantiate_value_path(
605 segs,
606 opt_ty,
607 res,
608 call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
609 expr.span,
610 expr.hir_id,
611 )
612 .0
613 }
614 };
615
616 if let ty::FnDef(did, args) = *ty.kind() {
617 let fn_sig = ty.fn_sig(tcx);
618
619 if tcx.is_intrinsic(did, sym::transmute) {
620 let Some(from) = fn_sig.inputs().skip_binder().get(0) else {
621 ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(did),
format_args!("intrinsic fn `transmute` defined with no parameters"));span_bug!(
622 tcx.def_span(did),
623 "intrinsic fn `transmute` defined with no parameters"
624 );
625 };
626 let to = fn_sig.output().skip_binder();
627 self.deferred_transmute_checks.borrow_mut().push((*from, to, expr.hir_id));
632 }
633 if !tcx.sess.opts.unstable_opts.offload.is_empty()
634 && tcx.is_intrinsic(did, sym::offload)
635 {
636 let args = args.skip_binder();
637 let f = args.type_at(0);
638 let t = args.type_at(1);
639 let r = args.type_at(2);
640 self.deferred_offload_checks.borrow_mut().push((f, t, r, expr.hir_id));
642 }
643 if !tcx.features().unsized_fn_params() {
644 for i in 0..fn_sig.inputs().skip_binder().len() {
654 let span = call_expr_and_args
658 .and_then(|(_, args)| args.get(i))
659 .map_or(expr.span, |arg| arg.span);
660 let input = self.instantiate_binder_with_fresh_vars(
661 span,
662 infer::BoundRegionConversionTime::FnCall,
663 fn_sig.input(i),
664 );
665 self.require_type_is_sized_deferred(
666 input,
667 span,
668 ObligationCauseCode::SizedArgumentType(None),
669 );
670 }
671 }
672 let output = self.instantiate_binder_with_fresh_vars(
678 expr.span,
679 infer::BoundRegionConversionTime::FnCall,
680 fn_sig.output(),
681 );
682 self.require_type_is_sized_deferred(
683 output,
684 call_expr_and_args.map_or(expr.span, |(e, _)| e.span),
685 ObligationCauseCode::SizedCallReturnType,
686 );
687 }
688
689 let args = self.typeck_results.borrow().node_args(expr.hir_id);
692 self.add_wf_bounds(args, expr.span);
693
694 ty
695 }
696
697 fn check_expr_break(
698 &self,
699 destination: hir::Destination,
700 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
701 expr: &'tcx hir::Expr<'tcx>,
702 ) -> Ty<'tcx> {
703 let tcx = self.tcx;
704 if let Ok(target_id) = destination.target_id {
705 let (e_ty, cause);
706 if let Some(e) = expr_opt {
707 let opt_coerce_to = {
710 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
714 match enclosing_breakables.opt_find_breakable(target_id) {
715 Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
716 None => {
717 return Ty::new_error_with_message(
719 tcx,
720 expr.span,
721 "break was outside loop, but no error was emitted",
722 );
723 }
724 }
725 };
726
727 let coerce_to = opt_coerce_to.unwrap_or_else(|| {
732 let guar = self.dcx().span_delayed_bug(
733 expr.span,
734 "illegal break with value found but no error reported",
735 );
736 self.set_tainted_by_errors(guar);
737 Ty::new_error(tcx, guar)
738 });
739
740 e_ty = self.check_expr_with_hint(e, coerce_to);
742 cause = self.misc(e.span);
743 } else {
744 e_ty = tcx.types.unit;
747 cause = self.misc(expr.span);
748 }
749
750 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
754 let Some(ctxt) = enclosing_breakables.opt_find_breakable(target_id) else {
755 return Ty::new_error_with_message(
757 tcx,
758 expr.span,
759 "break was outside loop, but no error was emitted",
760 );
761 };
762
763 if let Some(ref mut coerce) = ctxt.coerce {
764 if let Some(e) = expr_opt {
765 coerce.coerce(self, &cause, e, e_ty);
766 } else {
767 if !e_ty.is_unit() {
::core::panicking::panic("assertion failed: e_ty.is_unit()")
};assert!(e_ty.is_unit());
768 let ty = coerce.expected_ty();
769 coerce.coerce_forced_unit(
770 self,
771 &cause,
772 |mut err| {
773 self.suggest_missing_semicolon(&mut err, expr, e_ty, false, false);
774 self.suggest_mismatched_types_on_tail(
775 &mut err, expr, ty, e_ty, target_id,
776 );
777 let error =
778 Some(TypeError::Sorts(ExpectedFound { expected: ty, found: e_ty }));
779 self.annotate_loop_expected_due_to_inference(err, expr, error);
780 if let Some(val) =
781 self.err_ctxt().ty_kind_suggestion(self.param_env, ty)
782 {
783 err.span_suggestion_verbose(
784 expr.span.shrink_to_hi(),
785 "give the `break` a value of the expected type",
786 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", val))
})format!(" {val}"),
787 Applicability::HasPlaceholders,
788 );
789 }
790 },
791 false,
792 );
793 }
794 } else {
795 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());
803 }
804
805 ctxt.may_break |= !self.diverges.get().is_always();
809
810 tcx.types.never
812 } else {
813 let err = Ty::new_error_with_message(
818 self.tcx,
819 expr.span,
820 "break was outside loop, but no error was emitted",
821 );
822
823 if let Some(e) = expr_opt {
826 self.check_expr_with_hint(e, err);
827
828 if let ExprKind::Path(QPath::Resolved(_, path)) = e.kind {
831 if let [segment] = path.segments
832 && segment.ident.name == sym::rust
833 {
834 fatally_break_rust(self.tcx, expr.span);
835 }
836 }
837 }
838
839 err
841 }
842 }
843
844 fn check_expr_continue(
845 &self,
846 destination: hir::Destination,
847 expr: &'tcx hir::Expr<'tcx>,
848 ) -> Ty<'tcx> {
849 if let Ok(target_id) = destination.target_id {
850 if let hir::Node::Expr(hir::Expr { kind: ExprKind::Loop(..), .. }) =
851 self.tcx.hir_node(target_id)
852 {
853 self.tcx.types.never
854 } else {
855 let guar = self.dcx().span_delayed_bug(
858 expr.span,
859 "found `continue` not pointing to loop, but no error reported",
860 );
861 Ty::new_error(self.tcx, guar)
862 }
863 } else {
864 Ty::new_misc_error(self.tcx)
866 }
867 }
868
869 fn check_expr_return(
870 &self,
871 expr_opt: Option<&'tcx hir::Expr<'tcx>>,
872 expr: &'tcx hir::Expr<'tcx>,
873 ) -> Ty<'tcx> {
874 if self.ret_coercion.is_none() {
875 self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Return);
876
877 if let Some(e) = expr_opt {
878 self.check_expr(e);
881 }
882 } else if let Some(e) = expr_opt {
883 if self.ret_coercion_span.get().is_none() {
884 self.ret_coercion_span.set(Some(e.span));
885 }
886 self.check_return_or_body_tail(e, true);
887 } else {
888 let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
889 if self.ret_coercion_span.get().is_none() {
890 self.ret_coercion_span.set(Some(expr.span));
891 }
892 let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
893 if let Some((_, fn_decl)) = self.get_fn_decl(expr.hir_id) {
894 coercion.coerce_forced_unit(
895 self,
896 &cause,
897 |db| {
898 let span = fn_decl.output.span();
899 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
900 db.span_label(
901 span,
902 ::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"),
903 );
904 }
905 },
906 true,
907 );
908 } else {
909 coercion.coerce_forced_unit(self, &cause, |_| (), true);
910 }
911 }
912 self.tcx.types.never
913 }
914
915 fn check_expr_become(
916 &self,
917 call: &'tcx hir::Expr<'tcx>,
918 expr: &'tcx hir::Expr<'tcx>,
919 ) -> Ty<'tcx> {
920 match &self.ret_coercion {
921 Some(ret_coercion) => {
922 let ret_ty = ret_coercion.borrow().expected_ty();
923 let call_expr_ty = self.check_expr_with_hint(call, ret_ty);
924
925 self.demand_suptype(expr.span, ret_ty, call_expr_ty);
928 }
929 None => {
930 self.emit_return_outside_of_fn_body(expr, ReturnLikeStatementKind::Become);
931
932 self.check_expr(call);
935 }
936 }
937
938 self.tcx.types.never
939 }
940
941 pub(super) fn check_return_or_body_tail(
950 &self,
951 return_expr: &'tcx hir::Expr<'tcx>,
952 explicit_return: bool,
953 ) {
954 let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
955 ::rustc_middle::util::bug::span_bug_fmt(return_expr.span,
format_args!("check_return_expr called outside fn body"))span_bug!(return_expr.span, "check_return_expr called outside fn body")
956 });
957
958 let ret_ty = ret_coercion.borrow().expected_ty();
959 let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
960 let mut span = return_expr.span;
961 let mut hir_id = return_expr.hir_id;
962 if !explicit_return
965 && let ExprKind::Block(body, _) = return_expr.kind
966 && let Some(last_expr) = body.expr
967 {
968 span = last_expr.span;
969 hir_id = last_expr.hir_id;
970 }
971 ret_coercion.borrow_mut().coerce(
972 self,
973 &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
974 return_expr,
975 return_expr_ty,
976 );
977
978 if let Some(fn_sig) = self.fn_sig()
979 && fn_sig.output().has_opaque_types()
980 {
981 self.select_obligations_where_possible(|errors| {
984 self.point_at_return_for_opaque_ty_error(
985 errors,
986 hir_id,
987 span,
988 return_expr_ty,
989 return_expr.span,
990 );
991 });
992 }
993 }
994
995 fn emit_return_outside_of_fn_body(&self, expr: &hir::Expr<'_>, kind: ReturnLikeStatementKind) {
1000 let mut err = ReturnStmtOutsideOfFnBody {
1001 span: expr.span,
1002 encl_body_span: None,
1003 encl_fn_span: None,
1004 statement_kind: kind,
1005 };
1006
1007 let encl_item_id = self.tcx.hir_get_parent_item(expr.hir_id);
1008
1009 if let hir::Node::Item(hir::Item {
1010 kind: hir::ItemKind::Fn { .. },
1011 span: encl_fn_span,
1012 ..
1013 })
1014 | hir::Node::TraitItem(hir::TraitItem {
1015 kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
1016 span: encl_fn_span,
1017 ..
1018 })
1019 | hir::Node::ImplItem(hir::ImplItem {
1020 kind: hir::ImplItemKind::Fn(..),
1021 span: encl_fn_span,
1022 ..
1023 }) = self.tcx.hir_node_by_def_id(encl_item_id.def_id)
1024 {
1025 let encl_body_owner_id = self.tcx.hir_enclosing_body_owner(expr.hir_id);
1029
1030 {
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);
1033
1034 let encl_body = self.tcx.hir_body_owned_by(encl_body_owner_id);
1035
1036 err.encl_body_span = Some(encl_body.value.span);
1037 err.encl_fn_span = Some(*encl_fn_span);
1038 }
1039
1040 self.dcx().emit_err(err);
1041 }
1042
1043 fn point_at_return_for_opaque_ty_error(
1044 &self,
1045 errors: &mut ThinVec<traits::FulfillmentError<'tcx>>,
1046 hir_id: HirId,
1047 span: Span,
1048 return_expr_ty: Ty<'tcx>,
1049 return_span: Span,
1050 ) {
1051 if span == return_span {
1053 return;
1054 }
1055 for err in errors {
1056 let cause = &mut err.obligation.cause;
1057 if let ObligationCauseCode::OpaqueReturnType(None) = cause.code() {
1058 let new_cause = self.cause(
1059 cause.span,
1060 ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, hir_id))),
1061 );
1062 *cause = new_cause;
1063 }
1064 }
1065 }
1066
1067 pub(crate) fn check_lhs_assignable(
1068 &self,
1069 lhs: &'tcx hir::Expr<'tcx>,
1070 code: ErrCode,
1071 op_span: Span,
1072 adjust_err: impl FnOnce(&mut Diag<'_>),
1073 ) {
1074 if lhs.is_syntactic_place_expr() {
1075 return;
1076 }
1077
1078 if contains_let_in_chain(lhs) {
1081 return;
1082 }
1083
1084 let mut err = self.dcx().struct_span_err(op_span, "invalid left-hand side of assignment");
1085 err.code(code);
1086 err.span_label(lhs.span, "cannot assign to this expression");
1087
1088 self.comes_from_while_condition(lhs.hir_id, |expr| {
1089 err.span_suggestion_verbose(
1090 expr.span.shrink_to_lo(),
1091 "you might have meant to use pattern destructuring",
1092 "let ",
1093 Applicability::MachineApplicable,
1094 );
1095 });
1096 self.check_for_missing_semi(lhs, &mut err);
1097
1098 adjust_err(&mut err);
1099
1100 err.emit();
1101 }
1102
1103 pub(crate) fn check_for_missing_semi(
1105 &self,
1106 expr: &'tcx hir::Expr<'tcx>,
1107 err: &mut Diag<'_>,
1108 ) -> bool {
1109 if let hir::ExprKind::Binary(binop, lhs, rhs) = expr.kind
1110 && let hir::BinOpKind::Mul = binop.node
1111 && self.tcx.sess.source_map().is_multiline(lhs.span.between(rhs.span))
1112 && rhs.is_syntactic_place_expr()
1113 {
1114 err.span_suggestion_verbose(
1119 lhs.span.shrink_to_hi(),
1120 "you might have meant to write a semicolon here",
1121 ";",
1122 Applicability::MachineApplicable,
1123 );
1124 return true;
1125 }
1126 false
1127 }
1128
1129 pub(super) fn comes_from_while_condition(
1133 &self,
1134 original_expr_id: HirId,
1135 then: impl FnOnce(&hir::Expr<'_>),
1136 ) {
1137 let mut parent = self.tcx.parent_hir_id(original_expr_id);
1138 loop {
1139 let node = self.tcx.hir_node(parent);
1140 match node {
1141 hir::Node::Expr(hir::Expr {
1142 kind:
1143 hir::ExprKind::Loop(
1144 hir::Block {
1145 expr:
1146 Some(hir::Expr {
1147 kind:
1148 hir::ExprKind::Match(expr, ..) | hir::ExprKind::If(expr, ..),
1149 ..
1150 }),
1151 ..
1152 },
1153 _,
1154 hir::LoopSource::While,
1155 _,
1156 ),
1157 ..
1158 }) => {
1159 if self.tcx.hir_parent_id_iter(original_expr_id).any(|id| id == expr.hir_id) {
1163 then(expr);
1164 }
1165 break;
1166 }
1167 hir::Node::Item(_)
1168 | hir::Node::ImplItem(_)
1169 | hir::Node::TraitItem(_)
1170 | hir::Node::Crate(_) => break,
1171 _ => {
1172 parent = self.tcx.parent_hir_id(parent);
1173 }
1174 }
1175 }
1176 }
1177
1178 fn check_expr_if(
1181 &self,
1182 expr_id: HirId,
1183 cond_expr: &'tcx hir::Expr<'tcx>,
1184 then_expr: &'tcx hir::Expr<'tcx>,
1185 opt_else_expr: Option<&'tcx hir::Expr<'tcx>>,
1186 sp: Span,
1187 orig_expected: Expectation<'tcx>,
1188 ) -> Ty<'tcx> {
1189 let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {});
1190
1191 self.warn_if_unreachable(
1192 cond_expr.hir_id,
1193 then_expr.span,
1194 "block in `if` or `while` expression",
1195 );
1196
1197 let cond_diverges = self.diverges.get();
1198 self.diverges.set(Diverges::Maybe);
1199
1200 let expected = orig_expected.try_structurally_resolve_and_adjust_for_branches(self);
1201 let then_ty = self.check_expr_with_expectation(then_expr, expected);
1202 let then_diverges = self.diverges.get();
1203 self.diverges.set(Diverges::Maybe);
1204
1205 let coerce_to_ty = expected.coercion_target_type(self, sp);
1212 let mut coerce = CoerceMany::with_capacity(coerce_to_ty, 2);
1213
1214 coerce.coerce(self, &self.misc(sp), then_expr, then_ty);
1215
1216 if let Some(else_expr) = opt_else_expr {
1217 let else_ty = self.check_expr_with_expectation(else_expr, expected);
1218 let else_diverges = self.diverges.get();
1219
1220 let tail_defines_return_position_impl_trait =
1221 self.return_position_impl_trait_from_match_expectation(orig_expected);
1222 let if_cause =
1223 self.if_cause(expr_id, else_expr, tail_defines_return_position_impl_trait);
1224
1225 coerce.coerce(self, &if_cause, else_expr, else_ty);
1226
1227 self.diverges.set(cond_diverges | then_diverges & else_diverges);
1229 } else {
1230 self.if_fallback_coercion(sp, cond_expr, then_expr, &mut coerce);
1231
1232 self.diverges.set(cond_diverges);
1234 }
1235
1236 let result_ty = coerce.complete(self);
1237 if let Err(guar) = cond_ty.error_reported() {
1238 Ty::new_error(self.tcx, guar)
1239 } else {
1240 result_ty
1241 }
1242 }
1243
1244 fn check_expr_assign(
1247 &self,
1248 expr: &'tcx hir::Expr<'tcx>,
1249 expected: Expectation<'tcx>,
1250 lhs: &'tcx hir::Expr<'tcx>,
1251 rhs: &'tcx hir::Expr<'tcx>,
1252 span: Span,
1253 ) -> Ty<'tcx> {
1254 let expected_ty = expected.only_has_type(self);
1255 if expected_ty == Some(self.tcx.types.bool) {
1256 let guar = self.expr_assign_expected_bool_error(expr, lhs, rhs, span);
1257 return Ty::new_error(self.tcx, guar);
1258 }
1259
1260 let lhs_ty = self.check_expr_with_needs(lhs, Needs::MutPlace);
1261
1262 let suggest_deref_binop = |err: &mut Diag<'_>, rhs_ty: Ty<'tcx>| {
1263 if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
1264 let lhs_deref_ty_is_sized = self
1267 .infcx
1268 .type_implements_trait(
1269 self.tcx.require_lang_item(LangItem::Sized, span),
1270 [lhs_deref_ty],
1271 self.param_env,
1272 )
1273 .may_apply();
1274 if lhs_deref_ty_is_sized && self.may_coerce(rhs_ty, lhs_deref_ty) {
1275 err.span_suggestion_verbose(
1276 lhs.span.shrink_to_lo(),
1277 "consider dereferencing here to assign to the mutably borrowed value",
1278 "*",
1279 Applicability::MachineApplicable,
1280 );
1281 }
1282 }
1283 };
1284
1285 let rhs_ty = self.check_expr_with_hint(rhs, lhs_ty);
1288 if let Err(mut diag) =
1289 self.demand_coerce_diag(rhs, rhs_ty, lhs_ty, Some(lhs), AllowTwoPhase::No)
1290 {
1291 suggest_deref_binop(&mut diag, rhs_ty);
1292 diag.emit();
1293 }
1294
1295 self.check_lhs_assignable(lhs, E0070, span, |err| {
1296 if let Some(rhs_ty) = self.typeck_results.borrow().expr_ty_opt(rhs) {
1297 suggest_deref_binop(err, rhs_ty);
1298 }
1299 });
1300
1301 self.require_type_is_sized(lhs_ty, lhs.span, ObligationCauseCode::AssignmentLhsSized);
1302
1303 if let Err(guar) = (lhs_ty, rhs_ty).error_reported() {
1304 Ty::new_error(self.tcx, guar)
1305 } else {
1306 self.tcx.types.unit
1307 }
1308 }
1309
1310 fn expr_assign_expected_bool_error(
1314 &self,
1315 expr: &'tcx hir::Expr<'tcx>,
1316 lhs: &'tcx hir::Expr<'tcx>,
1317 rhs: &'tcx hir::Expr<'tcx>,
1318 span: Span,
1319 ) -> ErrorGuaranteed {
1320 let actual_ty = self.tcx.types.unit;
1321 let expected_ty = self.tcx.types.bool;
1322 let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap_err();
1323 let lhs_ty = self.check_expr(lhs);
1324 let rhs_ty = self.check_expr(rhs);
1325 let refs_can_coerce = |lhs: Ty<'tcx>, rhs: Ty<'tcx>| {
1326 let lhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, lhs.peel_refs());
1327 let rhs = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, rhs.peel_refs());
1328 self.may_coerce(rhs, lhs)
1329 };
1330 let (applicability, eq) = if self.may_coerce(rhs_ty, lhs_ty) {
1331 (Applicability::MachineApplicable, true)
1332 } else if refs_can_coerce(rhs_ty, lhs_ty) {
1333 (Applicability::MaybeIncorrect, true)
1336 } else if let ExprKind::Binary(
1337 Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1338 _,
1339 rhs_expr,
1340 ) = lhs.kind
1341 {
1342 let actual_lhs = self.check_expr(rhs_expr);
1345 let may_eq = self.may_coerce(rhs_ty, actual_lhs) || refs_can_coerce(rhs_ty, actual_lhs);
1346 (Applicability::MaybeIncorrect, may_eq)
1347 } else if let ExprKind::Binary(
1348 Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
1349 lhs_expr,
1350 _,
1351 ) = rhs.kind
1352 {
1353 let actual_rhs = self.check_expr(lhs_expr);
1356 let may_eq = self.may_coerce(actual_rhs, lhs_ty) || refs_can_coerce(actual_rhs, lhs_ty);
1357 (Applicability::MaybeIncorrect, may_eq)
1358 } else {
1359 (Applicability::MaybeIncorrect, false)
1360 };
1361
1362 if !lhs.is_syntactic_place_expr()
1363 && lhs.is_approximately_pattern()
1364 && !#[allow(non_exhaustive_omitted_patterns)] match lhs.kind {
hir::ExprKind::Lit(_) => true,
_ => false,
}matches!(lhs.kind, hir::ExprKind::Lit(_))
1365 {
1366 if let hir::Node::Expr(hir::Expr { kind: ExprKind::If { .. }, .. }) =
1368 self.tcx.parent_hir_node(expr.hir_id)
1369 {
1370 err.span_suggestion_verbose(
1371 expr.span.shrink_to_lo(),
1372 "you might have meant to use pattern matching",
1373 "let ",
1374 applicability,
1375 );
1376 };
1377 }
1378 if eq {
1379 err.span_suggestion_verbose(
1380 span.shrink_to_hi(),
1381 "you might have meant to compare for equality",
1382 '=',
1383 applicability,
1384 );
1385 }
1386
1387 err.emit_unless_delay(lhs_ty.references_error() || rhs_ty.references_error())
1390 }
1391
1392 pub(super) fn check_expr_let(
1393 &self,
1394 let_expr: &'tcx hir::LetExpr<'tcx>,
1395 hir_id: HirId,
1396 ) -> Ty<'tcx> {
1397 GatherLocalsVisitor::gather_from_let_expr(self, let_expr, hir_id);
1398
1399 let init = let_expr.init;
1401 self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression");
1402
1403 self.check_decl((let_expr, hir_id).into());
1405
1406 if let ast::Recovered::Yes(error_guaranteed) = let_expr.recovered {
1408 self.set_tainted_by_errors(error_guaranteed);
1409 Ty::new_error(self.tcx, error_guaranteed)
1410 } else {
1411 self.tcx.types.bool
1412 }
1413 }
1414
1415 fn check_expr_loop(
1416 &self,
1417 body: &'tcx hir::Block<'tcx>,
1418 source: hir::LoopSource,
1419 expected: Expectation<'tcx>,
1420 expr: &'tcx hir::Expr<'tcx>,
1421 ) -> Ty<'tcx> {
1422 let coerce = match source {
1423 hir::LoopSource::Loop => {
1425 let coerce_to = expected.coercion_target_type(self, body.span);
1426 Some(CoerceMany::new(coerce_to))
1427 }
1428
1429 hir::LoopSource::While | hir::LoopSource::ForLoop => None,
1430 };
1431
1432 let ctxt = BreakableCtxt {
1433 coerce,
1434 may_break: false, };
1436
1437 let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
1438 self.check_block_no_value(body);
1439 });
1440
1441 if ctxt.may_break {
1442 self.diverges.set(Diverges::Maybe);
1445 } else {
1446 self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
1447 }
1448
1449 if ctxt.coerce.is_none() && !ctxt.may_break {
1455 self.dcx().span_bug(body.span, "no coercion, but loop may not break");
1456 }
1457 ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.types.unit)
1458 }
1459
1460 fn check_expr_method_call(
1462 &self,
1463 expr: &'tcx hir::Expr<'tcx>,
1464 segment: &'tcx hir::PathSegment<'tcx>,
1465 rcvr: &'tcx hir::Expr<'tcx>,
1466 args: &'tcx [hir::Expr<'tcx>],
1467 expected: Expectation<'tcx>,
1468 ) -> Ty<'tcx> {
1469 let rcvr_t = self.check_expr(rcvr);
1470 let rcvr_t = self.resolve_vars_with_obligations(rcvr_t);
1471
1472 match self.lookup_method(rcvr_t, segment, segment.ident.span, expr, rcvr, args) {
1473 Ok(method) => {
1474 self.write_method_call_and_enforce_effects(expr.hir_id, expr.span, method);
1475
1476 let method_inputs = &method.sig.inputs()[1..];
1479 let method_tuple_args_flag =
1480 TupleArgumentsFlag::with_fn_sig_kind(method.sig.fn_sig_kind, true);
1481
1482 self.check_argument_types(
1483 segment.ident.span,
1484 expr,
1485 method_inputs,
1486 method.sig.output(),
1487 expected,
1488 args,
1489 method.sig.fn_sig_kind.c_variadic(),
1490 method_tuple_args_flag,
1491 SplatLoweringInfo::FnDef(method.def_id),
1492 Some(method.args),
1493 );
1494
1495 self.check_call_abi(method.sig.abi(), expr.span);
1496
1497 method.sig.output()
1498 }
1499 Err(error) => {
1500 let guar = self.report_method_error(expr.hir_id, rcvr_t, error, expected, false);
1501
1502 let err_inputs = self.err_args(args.len(), guar);
1503 let err_ty = Ty::new_error(self.tcx, guar);
1504
1505 self.check_argument_types(
1506 segment.ident.span,
1507 expr,
1508 &err_inputs,
1509 err_ty,
1510 NoExpectation,
1511 args,
1512 false,
1513 TupleArgumentsFlag::DontTupleArguments,
1514 SplatLoweringInfo::Error(guar),
1515 Some(GenericArgsRef::default()),
1516 );
1517
1518 err_ty
1519 }
1520 }
1521 }
1522
1523 fn check_expr_use(
1525 &self,
1526 used_expr: &'tcx hir::Expr<'tcx>,
1527 expected: Expectation<'tcx>,
1528 ) -> Ty<'tcx> {
1529 self.check_expr_with_expectation(used_expr, expected)
1530 }
1531
1532 fn check_expr_cast(
1533 &self,
1534 e: &'tcx hir::Expr<'tcx>,
1535 t: &'tcx hir::Ty<'tcx>,
1536 expr: &'tcx hir::Expr<'tcx>,
1537 ) -> Ty<'tcx> {
1538 let t_cast = self.lower_ty_saving_user_provided_ty(t);
1541 let t_cast = self.resolve_vars_if_possible(t_cast);
1542 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
1543 let t_expr = self.resolve_vars_if_possible(t_expr);
1544
1545 if let Err(guar) = (t_expr, t_cast).error_reported() {
1547 Ty::new_error(self.tcx, guar)
1548 } else {
1549 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
1551 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
1552 Ok(cast_check) => {
1553 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:1553",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(1553u32),
::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!(
1554 "check_expr_cast: deferring cast from {:?} to {:?}: {:?}",
1555 t_cast, t_expr, cast_check,
1556 );
1557 deferred_cast_checks.push(cast_check);
1558 t_cast
1559 }
1560 Err(guar) => Ty::new_error(self.tcx, guar),
1561 }
1562 }
1563 }
1564
1565 fn check_expr_unsafe_binder_cast(
1566 &self,
1567 span: Span,
1568 kind: ast::UnsafeBinderCastKind,
1569 inner_expr: &'tcx hir::Expr<'tcx>,
1570 hir_ty: Option<&'tcx hir::Ty<'tcx>>,
1571 expected: Expectation<'tcx>,
1572 ) -> Ty<'tcx> {
1573 match kind {
1574 ast::UnsafeBinderCastKind::Wrap => {
1575 let ascribed_ty =
1576 hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1577 let expected_ty = expected.only_has_type(self);
1578 let binder_ty = match (ascribed_ty, expected_ty) {
1579 (Some(ascribed_ty), Some(expected_ty)) => {
1580 self.demand_eqtype(inner_expr.span, expected_ty, ascribed_ty);
1581 expected_ty
1582 }
1583 (Some(ty), None) | (None, Some(ty)) => ty,
1584 (None, None) => self.next_ty_var(inner_expr.span),
1588 };
1589
1590 let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1591 let hint_ty = match *binder_ty.kind() {
1592 ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1593 inner_expr.span,
1594 infer::BoundRegionConversionTime::HigherRankedType,
1595 binder.into(),
1596 ),
1597 ty::Error(e) => Ty::new_error(self.tcx, e),
1598 _ => {
1599 let guar = self
1600 .dcx()
1601 .struct_span_err(
1602 hir_ty.map_or(span, |hir_ty| hir_ty.span),
1603 ::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!(
1604 "`wrap_binder!()` can only wrap into unsafe binder, not {}",
1605 binder_ty.sort_string(self.tcx)
1606 ),
1607 )
1608 .with_note("unsafe binders are the only valid output of wrap")
1609 .emit();
1610 Ty::new_error(self.tcx, guar)
1611 }
1612 };
1613
1614 self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1615
1616 binder_ty
1617 }
1618 ast::UnsafeBinderCastKind::Unwrap => {
1619 let ascribed_ty =
1620 hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1621 let hint_ty = ascribed_ty.unwrap_or_else(|| self.next_ty_var(inner_expr.span));
1622 let binder_ty = self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1624
1625 let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1628 match *binder_ty.kind() {
1629 ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1630 inner_expr.span,
1631 infer::BoundRegionConversionTime::HigherRankedType,
1632 binder.into(),
1633 ),
1634 ty::Error(e) => Ty::new_error(self.tcx, e),
1635 _ => {
1636 let guar = self
1637 .dcx()
1638 .struct_span_err(
1639 hir_ty.map_or(inner_expr.span, |hir_ty| hir_ty.span),
1640 ::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!(
1641 "expected unsafe binder, found {} as input of \
1642 `unwrap_binder!()`",
1643 binder_ty.sort_string(self.tcx)
1644 ),
1645 )
1646 .with_note("only an unsafe binder type can be unwrapped")
1647 .emit();
1648 Ty::new_error(self.tcx, guar)
1649 }
1650 }
1651 }
1652 }
1653 }
1654
1655 fn check_expr_array(
1656 &self,
1657 args: &'tcx [hir::Expr<'tcx>],
1658 expected: Expectation<'tcx>,
1659 expr: &'tcx hir::Expr<'tcx>,
1660 ) -> Ty<'tcx> {
1661 let element_ty = if !args.is_empty() {
1662 let coerce_to = expected
1663 .to_option(self)
1664 .and_then(|uty| {
1665 self.resolve_vars_with_obligations(uty)
1666 .builtin_index()
1667 .filter(|t| !self.resolve_vars_with_obligations(*t).is_ty_var())
1670 })
1671 .unwrap_or_else(|| self.next_ty_var(expr.span));
1672 let mut coerce = CoerceMany::with_capacity(coerce_to, args.len());
1673
1674 for e in args {
1675 let e_ty = self.check_expr_with_hint(e, coerce_to);
1681 let cause = self.misc(e.span);
1682 coerce.coerce(self, &cause, e, e_ty);
1683 }
1684 coerce.complete(self)
1685 } else {
1686 self.next_ty_var(expr.span)
1687 };
1688 let array_len = args.len() as u64;
1689 self.suggest_array_len(expr, array_len);
1690 Ty::new_array(self.tcx, element_ty, array_len)
1691 }
1692
1693 fn suggest_array_len(&self, expr: &'tcx hir::Expr<'tcx>, array_len: u64) {
1694 let parent_node = self.tcx.hir_parent_iter(expr.hir_id).find(|(_, node)| {
1695 !#[allow(non_exhaustive_omitted_patterns)] match node {
hir::Node::Expr(hir::Expr { kind: hir::ExprKind::AddrOf(..), .. }) =>
true,
_ => false,
}matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::AddrOf(..), .. }))
1696 });
1697 let Some((_, hir::Node::LetStmt(hir::LetStmt { ty: Some(ty), .. }))) = parent_node else {
1698 return;
1699 };
1700 if let hir::TyKind::Array(_, ct) = ty.peel_refs().kind {
1701 let span = ct.span;
1702 self.dcx().try_steal_modify_and_emit_err(
1703 span,
1704 StashKey::UnderscoreForArrayLengths,
1705 |err| {
1706 err.span_suggestion(
1707 span,
1708 "consider specifying the array length",
1709 array_len,
1710 Applicability::MaybeIncorrect,
1711 );
1712 },
1713 );
1714 }
1715 }
1716
1717 pub(super) fn check_expr_const_block(
1718 &self,
1719 block: &'tcx hir::ConstBlock,
1720 expected: Expectation<'tcx>,
1721 ) -> Ty<'tcx> {
1722 let body = self.tcx.hir_body(block.body);
1723
1724 let def_id = block.def_id;
1726 let fcx = FnCtxt::new(self, self.param_env, def_id);
1727
1728 let ty = fcx.check_expr_with_expectation(body.value, expected);
1729 fcx.require_type_is_sized(ty, body.value.span, ObligationCauseCode::SizedConstOrStatic);
1730 fcx.write_ty(block.hir_id, ty);
1731 ty
1732 }
1733
1734 fn check_expr_repeat(
1735 &self,
1736 element: &'tcx hir::Expr<'tcx>,
1737 count: &'tcx hir::ConstArg<'tcx>,
1738 expected: Expectation<'tcx>,
1739 expr: &'tcx hir::Expr<'tcx>,
1740 ) -> Ty<'tcx> {
1741 let tcx = self.tcx;
1742 let count_span = count.span;
1743 let count = self.try_structurally_resolve_const(
1744 count_span,
1745 self.normalize(
1746 count_span,
1747 Unnormalized::new_wip(self.lower_const_arg(count, tcx.types.usize)),
1748 ),
1749 );
1750
1751 if let Some(count) = count.try_to_target_usize(tcx) {
1752 self.suggest_array_len(expr, count);
1753 }
1754
1755 let uty = match expected {
1756 ExpectHasType(uty) => uty.builtin_index(),
1757 _ => None,
1758 };
1759
1760 let (element_ty, t) = match uty {
1761 Some(uty) => {
1762 self.check_expr_coercible_to_type(element, uty, None);
1763 (uty, uty)
1764 }
1765 None => {
1766 let ty = self.next_ty_var(element.span);
1767 let element_ty = self.check_expr_has_type_or_error(element, ty, |_| {});
1768 (element_ty, ty)
1769 }
1770 };
1771
1772 if let Err(guar) = element_ty.error_reported() {
1773 return Ty::new_error(tcx, guar);
1774 }
1775
1776 self.deferred_repeat_expr_checks.borrow_mut().push((element, element_ty, count));
1780
1781 let ty = Ty::new_array_with_const_len(tcx, t, count);
1782 self.register_wf_obligation(ty.into(), expr.span, ObligationCauseCode::WellFormed(None));
1783 ty
1784 }
1785
1786 fn check_expr_tuple(
1787 &self,
1788 elements: &'tcx [hir::Expr<'tcx>],
1789 expected: Expectation<'tcx>,
1790 expr: &'tcx hir::Expr<'tcx>,
1791 ) -> Ty<'tcx> {
1792 let mut expectations = expected
1793 .only_has_type(self)
1794 .and_then(|ty| self.resolve_vars_with_obligations(ty).opt_tuple_fields())
1795 .unwrap_or_default()
1796 .iter();
1797
1798 let elements = elements.iter().map(|e| {
1799 let ty = expectations.next().unwrap_or_else(|| self.next_ty_var(e.span));
1800 self.check_expr_coercible_to_type(e, ty, None);
1801 ty
1802 });
1803
1804 let tuple = Ty::new_tup_from_iter(self.tcx, elements);
1805
1806 if let Err(guar) = tuple.error_reported() {
1807 Ty::new_error(self.tcx, guar)
1808 } else {
1809 self.require_type_is_sized(
1810 tuple,
1811 expr.span,
1812 ObligationCauseCode::TupleInitializerSized,
1813 );
1814 tuple
1815 }
1816 }
1817
1818 fn check_expr_struct(
1819 &self,
1820 expr: &hir::Expr<'tcx>,
1821 expected: Expectation<'tcx>,
1822 qpath: &'tcx QPath<'tcx>,
1823 fields: &'tcx [hir::ExprField<'tcx>],
1824 base_expr: &'tcx hir::StructTailExpr<'tcx>,
1825 ) -> Ty<'tcx> {
1826 let (variant, adt_ty) = match self.check_struct_path(qpath, expr.hir_id) {
1828 Ok(data) => data,
1829 Err(guar) => {
1830 self.check_struct_fields_on_error(fields, base_expr);
1831 return Ty::new_error(self.tcx, guar);
1832 }
1833 };
1834
1835 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1837 if variant.field_list_has_applicable_non_exhaustive() {
1838 self.dcx()
1839 .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() });
1840 }
1841
1842 self.check_expr_struct_fields(
1843 adt_ty,
1844 expected,
1845 expr,
1846 qpath.span(),
1847 variant,
1848 fields,
1849 base_expr,
1850 );
1851
1852 self.require_type_is_sized(adt_ty, expr.span, ObligationCauseCode::StructInitializerSized);
1853 adt_ty
1854 }
1855
1856 fn check_expr_struct_fields(
1857 &self,
1858 adt_ty: Ty<'tcx>,
1859 expected: Expectation<'tcx>,
1860 expr: &hir::Expr<'_>,
1861 path_span: Span,
1862 variant: &'tcx ty::VariantDef,
1863 hir_fields: &'tcx [hir::ExprField<'tcx>],
1864 base_expr: &'tcx hir::StructTailExpr<'tcx>,
1865 ) {
1866 let tcx = self.tcx;
1867
1868 let adt_ty = self.resolve_vars_with_obligations(adt_ty);
1869 let adt_ty_hint = expected.only_has_type(self).and_then(|expected| {
1870 self.fudge_inference_if_ok(|| {
1871 let ocx = ObligationCtxt::new(self);
1872 ocx.sup(&self.misc(path_span), self.param_env, expected, adt_ty)?;
1873 if !ocx.try_evaluate_obligations().no_errors() {
1874 return Err(TypeError::Mismatch);
1875 }
1876 Ok(self.resolve_vars_if_possible(adt_ty))
1877 })
1878 .ok()
1879 });
1880 if let Some(adt_ty_hint) = adt_ty_hint {
1881 self.demand_eqtype(path_span, adt_ty_hint, adt_ty);
1883 }
1884
1885 let ty::Adt(adt, args) = adt_ty.kind() else {
1886 ::rustc_middle::util::bug::span_bug_fmt(path_span,
format_args!("non-ADT passed to check_expr_struct_fields"));span_bug!(path_span, "non-ADT passed to check_expr_struct_fields");
1887 };
1888 let adt_kind = adt.adt_kind();
1889
1890 let mut remaining_fields = variant
1891 .fields
1892 .iter_enumerated()
1893 .map(|(i, field)| (field.ident(tcx).normalize_to_macros_2_0(), (i, field)))
1894 .collect::<UnordMap<_, _>>();
1895
1896 let mut seen_fields = FxHashMap::default();
1897
1898 let mut error_happened = false;
1899
1900 if variant.fields.len() != remaining_fields.len() {
1901 let guar =
1904 self.dcx().span_delayed_bug(expr.span, "struct fields have non-unique names");
1905 self.set_tainted_by_errors(guar);
1906 error_happened = true;
1907 }
1908
1909 for (idx, field) in hir_fields.iter().enumerate() {
1911 let ident = tcx.adjust_ident(field.ident, variant.def_id);
1912 let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1913 seen_fields.insert(ident, field.span);
1914 self.write_field_index(field.hir_id, i);
1915
1916 if adt_kind != AdtKind::Enum {
1920 tcx.check_stability(v_field.did, Some(field.hir_id), field.span, None);
1921 }
1922
1923 self.field_ty(field.span, v_field, args)
1924 } else {
1925 error_happened = true;
1926 let guar = if let Some(prev_span) = seen_fields.get(&ident) {
1927 self.dcx().emit_err(FieldMultiplySpecifiedInInitializer {
1928 span: field.ident.span,
1929 prev_span: *prev_span,
1930 ident,
1931 })
1932 } else {
1933 self.report_unknown_field(
1934 adt_ty,
1935 variant,
1936 expr,
1937 field,
1938 hir_fields,
1939 adt.variant_descr(),
1940 )
1941 };
1942
1943 Ty::new_error(tcx, guar)
1944 };
1945
1946 self.register_wf_obligation(
1950 field_type.into(),
1951 field.expr.span,
1952 ObligationCauseCode::WellFormed(None),
1953 );
1954
1955 let ty = self.check_expr_with_hint(field.expr, field_type);
1958 let diag = self.demand_coerce_diag(field.expr, ty, field_type, None, AllowTwoPhase::No);
1959
1960 if let Err(diag) = diag {
1961 if idx == hir_fields.len() - 1 {
1962 if remaining_fields.is_empty() {
1963 self.suggest_fru_from_range_and_emit(field, variant, args, diag);
1964 } else {
1965 diag.stash(field.span, StashKey::MaybeFruTypo);
1966 }
1967 } else {
1968 diag.emit();
1969 }
1970 }
1971 }
1972
1973 if adt_kind == AdtKind::Union && hir_fields.len() != 1 {
1975 {
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!(
1976 self.dcx(),
1977 path_span,
1978 E0784,
1979 "union expressions should have exactly one field",
1980 )
1981 .emit();
1982 }
1983
1984 if error_happened {
1988 if let hir::StructTailExpr::Base(base_expr) = base_expr {
1989 self.check_expr(base_expr);
1990 }
1991 return;
1992 }
1993
1994 match *base_expr {
1995 hir::StructTailExpr::DefaultFields(span) => {
1996 let mut missing_mandatory_fields = Vec::new();
1997 let mut missing_optional_fields = Vec::new();
1998 for f in &variant.fields {
1999 let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2000 if let Some(_) = remaining_fields.remove(&ident) {
2001 if f.value.is_none() {
2002 missing_mandatory_fields.push(ident);
2003 } else {
2004 missing_optional_fields.push(ident);
2005 }
2006 }
2007 }
2008 if !self.tcx.features().default_field_values() {
2009 let sugg = self.tcx.crate_level_attribute_injection_span();
2010 self.dcx().emit_err(BaseExpressionDoubleDot {
2011 span: span.shrink_to_hi(),
2012 default_field_values_suggestion: if self.tcx.sess.is_nightly_build()
2015 && missing_mandatory_fields.is_empty()
2016 && !missing_optional_fields.is_empty()
2017 {
2018 Some(sugg)
2019 } else {
2020 None
2021 },
2022 add_expr: if !missing_mandatory_fields.is_empty()
2023 || !missing_optional_fields.is_empty()
2024 {
2025 Some(BaseExpressionDoubleDotAddExpr { span: span.shrink_to_hi() })
2026 } else {
2027 None
2028 },
2029 remove_dots: if missing_mandatory_fields.is_empty()
2030 && missing_optional_fields.is_empty()
2031 {
2032 Some(BaseExpressionDoubleDotRemove { span })
2033 } else {
2034 None
2035 },
2036 });
2037 return;
2038 }
2039 if variant.fields.is_empty() {
2040 let mut err = self.dcx().struct_span_err(
2041 span,
2042 ::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!(
2043 "`{adt_ty}` has no fields, `..` needs at least one default field in \
2044 the struct definition",
2045 ),
2046 );
2047 err.span_label(path_span, "this type has no fields");
2048 err.emit();
2049 }
2050 if !missing_mandatory_fields.is_empty() {
2051 let s = if missing_mandatory_fields.len() == 1 { "" } else { "s" }pluralize!(missing_mandatory_fields.len());
2052 let fields = listify(&missing_mandatory_fields, |f| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", f))
})format!("`{f}`")).unwrap();
2053 self.dcx()
2054 .struct_span_err(
2055 span.shrink_to_lo(),
2056 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing field{0} {1} in initializer",
s, fields))
})format!("missing field{s} {fields} in initializer"),
2057 )
2058 .with_span_label(
2059 span.shrink_to_lo(),
2060 "fields that do not have a defaulted value must be provided explicitly",
2061 )
2062 .emit();
2063 return;
2064 }
2065 let fru_tys = match adt_ty.kind() {
2066 ty::Adt(adt, args) if adt.is_struct() => variant
2067 .fields
2068 .iter()
2069 .map(|f| self.normalize(span, f.ty(self.tcx, args)))
2070 .collect(),
2071 ty::Adt(adt, args) if adt.is_enum() => variant
2072 .fields
2073 .iter()
2074 .map(|f| self.normalize(span, f.ty(self.tcx, args)))
2075 .collect(),
2076 _ => {
2077 self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct { span });
2078 return;
2079 }
2080 };
2081 self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2082 }
2083 hir::StructTailExpr::Base(base_expr) => {
2084 let fru_tys = if self.tcx.features().type_changing_struct_update() {
2087 if adt.is_struct() {
2088 let fresh_args = self.fresh_args_for_item(base_expr.span, adt.did());
2090 let fru_tys = variant
2095 .fields
2096 .iter()
2097 .map(|f| {
2098 let fru_ty = self.normalize(
2099 expr.span,
2100 Unnormalized::new_wip(self.field_ty(
2101 base_expr.span,
2102 f,
2103 fresh_args,
2104 )),
2105 );
2106 let ident =
2107 self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2108 if let Some(_) = remaining_fields.remove(&ident) {
2109 let target_ty = self.field_ty(base_expr.span, f, args);
2110 let cause = self.misc(base_expr.span);
2111 match self.at(&cause, self.param_env).sup(
2112 DefineOpaqueTypes::Yes,
2117 target_ty,
2118 fru_ty,
2119 ) {
2120 Ok(InferOk { obligations, value: () }) => {
2121 self.register_predicates(obligations)
2122 }
2123 Err(_) => {
2124 ::rustc_middle::util::bug::span_bug_fmt(cause.span,
format_args!("subtyping remaining fields of type changing FRU failed: {2} != {3}: {0}::{1}",
variant.name, ident.name, target_ty, fru_ty));span_bug!(
2125 cause.span,
2126 "subtyping remaining fields of type changing FRU \
2127 failed: {target_ty} != {fru_ty}: {}::{}",
2128 variant.name,
2129 ident.name,
2130 );
2131 }
2132 }
2133 }
2134 self.resolve_vars_if_possible(fru_ty)
2135 })
2136 .collect();
2137 let fresh_base_ty = Ty::new_adt(self.tcx, *adt, fresh_args);
2156 self.check_expr_has_type_or_error(
2157 base_expr,
2158 self.resolve_vars_if_possible(fresh_base_ty),
2159 |_| {},
2160 );
2161 fru_tys
2162 } else {
2163 self.check_expr(base_expr);
2166 self.dcx()
2167 .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
2168 return;
2169 }
2170 } else {
2171 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {
2172 let base_ty = self.typeck_results.borrow().expr_ty(base_expr);
2173 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()),
2174 (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt);
2175 if self.tcx.sess.is_nightly_build() && same_adt {
2176 feature_err(
2177 &self.tcx.sess,
2178 sym::type_changing_struct_update,
2179 base_expr.span,
2180 "type changing struct updating is experimental",
2181 )
2182 .emit();
2183 }
2184 });
2185 match adt_ty.kind() {
2186 ty::Adt(adt, args) if adt.is_struct() => variant
2187 .fields
2188 .iter()
2189 .map(|f| self.normalize(expr.span, f.ty(self.tcx, args)))
2190 .collect(),
2191 _ => {
2192 self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct {
2193 span: base_expr.span,
2194 });
2195 return;
2196 }
2197 }
2198 };
2199 self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2200 }
2201 rustc_hir::StructTailExpr::NoneWithError(guaranteed) => {
2202 self.infcx.set_tainted_by_errors(guaranteed);
2213 }
2214 rustc_hir::StructTailExpr::None => {
2215 if adt_kind != AdtKind::Union
2216 && !remaining_fields.is_empty()
2217 && !variant.field_list_has_applicable_non_exhaustive()
2219 {
2220 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:2220",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2220u32),
::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);
2221
2222 let private_fields: Vec<&ty::FieldDef> = variant
2225 .fields
2226 .iter()
2227 .filter(|field| {
2228 !field.vis.is_accessible_from(tcx.parent_module(expr.hir_id), tcx)
2229 })
2230 .collect();
2231
2232 if !private_fields.is_empty() {
2233 self.report_private_fields(
2234 adt_ty,
2235 path_span,
2236 expr.span,
2237 private_fields,
2238 hir_fields,
2239 );
2240 } else {
2241 self.report_missing_fields(
2242 adt_ty,
2243 path_span,
2244 expr.span,
2245 remaining_fields,
2246 variant,
2247 hir_fields,
2248 args,
2249 );
2250 }
2251 }
2252 }
2253 }
2254 }
2255
2256 fn check_struct_fields_on_error(
2257 &self,
2258 fields: &'tcx [hir::ExprField<'tcx>],
2259 base_expr: &'tcx hir::StructTailExpr<'tcx>,
2260 ) {
2261 for field in fields {
2262 self.check_expr(field.expr);
2263 }
2264 if let hir::StructTailExpr::Base(base) = *base_expr {
2265 self.check_expr(base);
2266 }
2267 }
2268
2269 fn report_missing_fields(
2281 &self,
2282 adt_ty: Ty<'tcx>,
2283 span: Span,
2284 full_span: Span,
2285 remaining_fields: UnordMap<Ident, (FieldIdx, &ty::FieldDef)>,
2286 variant: &'tcx ty::VariantDef,
2287 hir_fields: &'tcx [hir::ExprField<'tcx>],
2288 args: GenericArgsRef<'tcx>,
2289 ) {
2290 let len = remaining_fields.len();
2291
2292 let displayable_field_names: Vec<&str> =
2293 remaining_fields.items().map(|(ident, _)| ident.as_str()).into_sorted_stable_ord();
2294
2295 let mut truncated_fields_error = String::new();
2296 let remaining_fields_names = match &displayable_field_names[..] {
2297 [field1] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", field1))
})format!("`{field1}`"),
2298 [field1, field2] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and `{1}`", field1, field2))
})format!("`{field1}` and `{field2}`"),
2299 [field1, field2, field3] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`, `{1}` and `{2}`", field1,
field2, field3))
})format!("`{field1}`, `{field2}` and `{field3}`"),
2300 _ => {
2301 truncated_fields_error =
2302 ::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));
2303 displayable_field_names
2304 .iter()
2305 .take(3)
2306 .map(|n| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`"))
2307 .collect::<Vec<_>>()
2308 .join(", ")
2309 }
2310 };
2311
2312 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!(
2313 self.dcx(),
2314 span,
2315 E0063,
2316 "missing field{} {}{} in initializer of `{}`",
2317 pluralize!(len),
2318 remaining_fields_names,
2319 truncated_fields_error,
2320 adt_ty
2321 );
2322 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}"));
2323
2324 if remaining_fields.items().all(|(_, (_, field))| field.value.is_some())
2325 && self.tcx.sess.is_nightly_build()
2326 {
2327 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!(
2328 "all remaining fields have default values, {you_can} use those values with `..`",
2329 you_can = if self.tcx.features().default_field_values() {
2330 "you can"
2331 } else {
2332 "if you added `#![feature(default_field_values)]` to your crate you could"
2333 },
2334 );
2335 if let Some(hir_field) = hir_fields.last() {
2336 err.span_suggestion_verbose(
2337 hir_field.span.shrink_to_hi(),
2338 msg,
2339 ", ..".to_string(),
2340 Applicability::MachineApplicable,
2341 );
2342 } else if hir_fields.is_empty() {
2343 err.span_suggestion_verbose(
2344 span.shrink_to_hi().with_hi(full_span.hi()),
2345 msg,
2346 " { .. }".to_string(),
2347 Applicability::MachineApplicable,
2348 );
2349 }
2350 }
2351
2352 if let Some(hir_field) = hir_fields.last() {
2353 self.suggest_fru_from_range_and_emit(hir_field, variant, args, err);
2354 } else {
2355 err.emit();
2356 }
2357 }
2358
2359 fn suggest_fru_from_range_and_emit(
2362 &self,
2363 last_expr_field: &hir::ExprField<'tcx>,
2364 variant: &ty::VariantDef,
2365 args: GenericArgsRef<'tcx>,
2366 mut err: Diag<'_>,
2367 ) {
2368 if is_range_literal(last_expr_field.expr)
2369 && let ExprKind::Struct(&qpath, [range_start, range_end], _) = last_expr_field.expr.kind
2370 && self.tcx.qpath_is_lang_item(qpath, LangItem::Range)
2371 && let variant_field =
2372 variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident)
2373 && let range_def_id = self.tcx.lang_items().range_struct()
2374 && variant_field
2375 .and_then(|field| field.ty(self.tcx, args).skip_norm_wip().ty_adt_def())
2376 .map(|adt| adt.did())
2377 != range_def_id
2378 {
2379 let expr = self
2383 .tcx
2384 .sess
2385 .source_map()
2386 .span_to_snippet(range_end.expr.span)
2387 .ok()
2388 .filter(|s| s.len() < 25 && !s.contains(|c: char| c.is_control()));
2389
2390 let fru_span = self
2391 .tcx
2392 .sess
2393 .source_map()
2394 .span_extend_while_whitespace(range_start.expr.span)
2395 .shrink_to_hi()
2396 .to(range_end.expr.span);
2397
2398 err.subdiagnostic(TypeMismatchFruTypo {
2399 expr_span: range_start.expr.span,
2400 fru_span,
2401 expr,
2402 });
2403
2404 self.dcx().try_steal_replace_and_emit_err(
2406 last_expr_field.span,
2407 StashKey::MaybeFruTypo,
2408 err,
2409 );
2410 } else {
2411 err.emit();
2412 }
2413 }
2414
2415 fn report_private_fields(
2427 &self,
2428 adt_ty: Ty<'tcx>,
2429 span: Span,
2430 expr_span: Span,
2431 private_fields: Vec<&ty::FieldDef>,
2432 used_fields: &'tcx [hir::ExprField<'tcx>],
2433 ) {
2434 let mut err =
2435 self.dcx().struct_span_err(
2436 span,
2437 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot construct `{0}` with struct literal syntax due to private fields",
adt_ty))
})format!(
2438 "cannot construct `{adt_ty}` with struct literal syntax due to private fields",
2439 ),
2440 );
2441 let (used_private_fields, remaining_private_fields): (
2442 Vec<(Symbol, Span, bool)>,
2443 Vec<(Symbol, Span, bool)>,
2444 ) = private_fields
2445 .iter()
2446 .map(|field| {
2447 match used_fields.iter().find(|used_field| field.name == used_field.ident.name) {
2448 Some(used_field) => (field.name, used_field.span, true),
2449 None => (field.name, self.tcx.def_span(field.did), false),
2450 }
2451 })
2452 .partition(|field| field.2);
2453 err.span_labels(used_private_fields.iter().map(|(_, span, _)| *span), "private field");
2454
2455 if let ty::Adt(def, _) = adt_ty.kind() {
2456 if (def.did().is_local() || !used_fields.is_empty())
2457 && !remaining_private_fields.is_empty()
2458 {
2459 let names = if remaining_private_fields.len() > 6 {
2460 String::new()
2461 } else {
2462 ::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!(
2463 "{} ",
2464 listify(&remaining_private_fields, |(name, _, _)| format!("`{name}`"))
2465 .expect("expected at least one private field to report")
2466 )
2467 };
2468 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!(
2469 "{}private field{s} {names}that {were} not provided",
2470 if used_fields.is_empty() { "" } else { "...and other " },
2471 s = pluralize!(remaining_private_fields.len()),
2472 were = pluralize!("was", remaining_private_fields.len()),
2473 ));
2474 }
2475
2476 let def_id = def.did();
2477 let mut items = self
2478 .tcx
2479 .inherent_impls(def_id)
2480 .into_iter()
2481 .flat_map(|&i| self.tcx.associated_items(i).in_definition_order())
2482 .filter(|item| item.is_fn() && !item.is_method())
2484 .filter_map(|item| {
2485 let fn_sig = self
2487 .tcx
2488 .fn_sig(item.def_id)
2489 .instantiate(self.tcx, self.fresh_args_for_item(span, item.def_id))
2490 .skip_norm_wip();
2491 let ret_ty = self.tcx.instantiate_bound_regions_with_erased(fn_sig.output());
2492 if !self.can_eq(self.param_env, ret_ty, adt_ty) {
2493 return None;
2494 }
2495 let input_len = fn_sig.inputs().skip_binder().len();
2496 let name = item.name();
2497 let order = !name.as_str().starts_with("new");
2498 Some((order, name, input_len))
2499 })
2500 .collect::<Vec<_>>();
2501 items.sort_by_key(|(order, _, _)| *order);
2502 let suggestion = |name, args| {
2503 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{1}({0})",
std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "),
name))
})format!(
2504 "::{name}({})",
2505 std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", ")
2506 )
2507 };
2508 match &items[..] {
2509 [] => {}
2510 [(_, name, args)] => {
2511 err.span_suggestion_verbose(
2512 span.shrink_to_hi().with_hi(expr_span.hi()),
2513 ::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"),
2514 suggestion(name, *args),
2515 Applicability::MaybeIncorrect,
2516 );
2517 }
2518 _ => {
2519 err.span_suggestions(
2520 span.shrink_to_hi().with_hi(expr_span.hi()),
2521 "you might have meant to use an associated function to build this type",
2522 items.iter().map(|(_, name, args)| suggestion(name, *args)),
2523 Applicability::MaybeIncorrect,
2524 );
2525 }
2526 }
2527 if let Some(default_trait) = self.tcx.get_diagnostic_item(sym::Default)
2528 && self
2529 .infcx
2530 .type_implements_trait(default_trait, [adt_ty], self.param_env)
2531 .may_apply()
2532 {
2533 err.multipart_suggestion(
2534 "consider using the `Default` trait",
2535 ::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![
2536 (span.shrink_to_lo(), "<".to_string()),
2537 (
2538 span.shrink_to_hi().with_hi(expr_span.hi()),
2539 " as std::default::Default>::default()".to_string(),
2540 ),
2541 ],
2542 Applicability::MaybeIncorrect,
2543 );
2544 }
2545 }
2546
2547 err.emit();
2548 }
2549
2550 fn report_unknown_field(
2551 &self,
2552 ty: Ty<'tcx>,
2553 variant: &'tcx ty::VariantDef,
2554 expr: &hir::Expr<'_>,
2555 field: &hir::ExprField<'_>,
2556 skip_fields: &[hir::ExprField<'_>],
2557 kind_name: &str,
2558 ) -> ErrorGuaranteed {
2559 if let Err(guar) = variant.has_errors() {
2561 return guar;
2562 }
2563 let mut err = self.err_ctxt().type_error_struct_with_diag(
2564 field.ident.span,
2565 |actual| match ty.kind() {
2566 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!(
2567 self.dcx(),
2568 field.ident.span,
2569 E0559,
2570 "{} `{}::{}` has no field named `{}`",
2571 kind_name,
2572 actual,
2573 variant.name,
2574 field.ident
2575 ),
2576 _ => {
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!(
2577 self.dcx(),
2578 field.ident.span,
2579 E0560,
2580 "{} `{}` has no field named `{}`",
2581 kind_name,
2582 actual,
2583 field.ident
2584 ),
2585 },
2586 ty,
2587 );
2588
2589 let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap();
2590 match variant.ctor {
2591 Some((CtorKind::Fn, def_id)) => match ty.kind() {
2592 ty::Adt(adt, ..) if adt.is_enum() => {
2593 err.span_label(
2594 variant_ident_span,
2595 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}::{1}` defined here", ty,
variant.name))
})format!(
2596 "`{adt}::{variant}` defined here",
2597 adt = ty,
2598 variant = variant.name,
2599 ),
2600 );
2601 err.span_label(field.ident.span, "field does not exist");
2602 let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
2603 let inputs = fn_sig.inputs().skip_binder();
2604 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!(
2605 "({})",
2606 inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2607 );
2608 let (replace_span, sugg) = match expr.kind {
2609 hir::ExprKind::Struct(qpath, ..) => {
2610 (qpath.span().shrink_to_hi().with_hi(expr.span.hi()), fields)
2611 }
2612 _ => {
2613 (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))
2614 }
2615 };
2616 err.span_suggestion_verbose(
2617 replace_span,
2618 ::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!(
2619 "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax",
2620 adt = ty,
2621 variant = variant.name,
2622 ),
2623 sugg,
2624 Applicability::HasPlaceholders,
2625 );
2626 }
2627 _ => {
2628 err.span_label(variant_ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", ty))
})format!("`{ty}` defined here"));
2629 err.span_label(field.ident.span, "field does not exist");
2630 let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
2631 let inputs = fn_sig.inputs().skip_binder();
2632 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!(
2633 "({})",
2634 inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2635 );
2636 err.span_suggestion_verbose(
2637 expr.span,
2638 ::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",),
2639 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", ty, fields))
})format!("{ty}{fields}"),
2640 Applicability::HasPlaceholders,
2641 );
2642 }
2643 },
2644 _ => {
2645 let available_field_names = self.available_field_names(variant, expr, skip_fields);
2647 if let Some(field_name) =
2648 find_best_match_for_name(&available_field_names, field.ident.name, None)
2649 && !(field.ident.name.as_str().parse::<usize>().is_ok()
2650 && field_name.as_str().parse::<usize>().is_ok())
2651 {
2652 err.span_label(field.ident.span, "unknown field");
2653 err.span_suggestion_verbose(
2654 field.ident.span,
2655 "a field with a similar name exists",
2656 field_name,
2657 Applicability::MaybeIncorrect,
2658 );
2659 } else {
2660 match ty.kind() {
2661 ty::Adt(adt, ..) => {
2662 if adt.is_enum() {
2663 err.span_label(
2664 field.ident.span,
2665 ::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),
2666 );
2667 } else {
2668 err.span_label(
2669 field.ident.span,
2670 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` does not have this field",
ty))
})format!("`{ty}` does not have this field"),
2671 );
2672 }
2673 if available_field_names.is_empty() {
2674 err.note("all struct fields are already assigned");
2675 } else {
2676 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("available fields are: {0}",
self.name_series_display(available_field_names)))
})format!(
2677 "available fields are: {}",
2678 self.name_series_display(available_field_names)
2679 ));
2680 }
2681 }
2682 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("non-ADT passed to report_unknown_field"))bug!("non-ADT passed to report_unknown_field"),
2683 }
2684 };
2685 }
2686 }
2687 err.emit()
2688 }
2689
2690 fn available_field_names(
2691 &self,
2692 variant: &'tcx ty::VariantDef,
2693 expr: &hir::Expr<'_>,
2694 skip_fields: &[hir::ExprField<'_>],
2695 ) -> Vec<Symbol> {
2696 variant
2697 .fields
2698 .iter()
2699 .filter(|field| {
2700 skip_fields.iter().all(|&skip| skip.ident.name != field.name)
2701 && self.is_field_suggestable(field, expr.hir_id, expr.span)
2702 })
2703 .map(|field| field.name)
2704 .collect()
2705 }
2706
2707 fn name_series_display(&self, names: Vec<Symbol>) -> String {
2708 let limit = if names.len() == 6 { 6 } else { 5 };
2710 let mut display =
2711 names.iter().take(limit).map(|n| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`")).collect::<Vec<_>>().join(", ");
2712 if names.len() > limit {
2713 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);
2714 }
2715 display
2716 }
2717
2718 fn find_adt_field(
2722 &self,
2723 base_def: ty::AdtDef<'tcx>,
2724 ident: Ident,
2725 ) -> Option<(FieldIdx, &'tcx ty::FieldDef)> {
2726 if base_def.is_enum() {
2728 return None;
2729 }
2730
2731 for (field_idx, field) in base_def.non_enum_variant().fields.iter_enumerated() {
2732 if field.ident(self.tcx).normalize_to_macros_2_0() == ident {
2733 return Some((field_idx, field));
2735 }
2736 }
2737
2738 None
2739 }
2740
2741 fn check_expr_field(
2751 &self,
2752 expr: &'tcx hir::Expr<'tcx>,
2753 base: &'tcx hir::Expr<'tcx>,
2754 field: Ident,
2755 expected: Expectation<'tcx>,
2757 ) -> Ty<'tcx> {
2758 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:2758",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2758u32),
::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);
2759 let base_ty = self.check_expr(base);
2760 let base_ty = self.structurally_resolve_type(base.span, base_ty);
2761
2762 let mut private_candidate = None;
2764
2765 let mut autoderef = self.autoderef(expr.span, base_ty);
2767 while let Some((deref_base_ty, _)) = autoderef.next() {
2768 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:2768",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2768u32),
::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);
2769 match deref_base_ty.kind() {
2770 ty::Adt(base_def, args) if !base_def.is_enum() => {
2771 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:2771",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2771u32),
::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);
2772 if let Err(guar) = base_def.non_enum_variant().has_errors() {
2774 return Ty::new_error(self.tcx(), guar);
2775 }
2776
2777 let (ident, def_scope) = self.tcx.adjust_ident_and_get_scope(
2778 field,
2779 base_def.did(),
2780 self.body_def_id,
2781 );
2782
2783 if let Some((idx, field)) = self.find_adt_field(*base_def, ident) {
2784 self.write_field_index(expr.hir_id, idx);
2785
2786 let adjustments = self.adjust_steps(&autoderef);
2787 if field.vis.is_accessible_from(def_scope, self.tcx) {
2788 self.apply_adjustments(base, adjustments);
2789 self.register_predicates(autoderef.into_obligations());
2790
2791 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
2792 return self.field_ty(expr.span, field, args);
2793 }
2794
2795 private_candidate = Some((adjustments, base_def.did()));
2797 }
2798 }
2799 ty::Tuple(tys) => {
2800 if let Ok(index) = field.as_str().parse::<usize>() {
2801 if field.name == sym::integer(index) {
2802 if let Some(&field_ty) = tys.get(index) {
2803 let adjustments = self.adjust_steps(&autoderef);
2804 self.apply_adjustments(base, adjustments);
2805 self.register_predicates(autoderef.into_obligations());
2806
2807 self.write_field_index(expr.hir_id, FieldIdx::from_usize(index));
2808 return field_ty;
2809 }
2810 }
2811 }
2812 }
2813 _ => {}
2814 }
2815 }
2816 let final_ty = self.structurally_resolve_type(autoderef.span(), autoderef.final_ty());
2822 if let ty::Error(_) = final_ty.kind() {
2823 return final_ty;
2824 }
2825
2826 if let Some((adjustments, did)) = private_candidate {
2827 self.apply_adjustments(base, adjustments);
2830 let guar = self.ban_private_field_access(
2831 expr,
2832 base_ty,
2833 field,
2834 did,
2835 expected.only_has_type(self),
2836 );
2837 return Ty::new_error(self.tcx(), guar);
2838 }
2839
2840 let guar = if self.method_exists_for_diagnostic(
2841 field,
2842 base_ty,
2843 expr.hir_id,
2844 expected.only_has_type(self),
2845 ) {
2846 self.ban_take_value_of_method(expr, base_ty, field)
2848 } else if !base_ty.is_primitive_ty() {
2849 self.ban_nonexisting_field(field, base, expr, base_ty)
2850 } else {
2851 let field_name = field.to_string();
2852 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!(
2853 self.dcx(),
2854 field.span,
2855 base_ty,
2856 E0610,
2857 "`{base_ty}` is a primitive type and therefore doesn't have fields",
2858 );
2859 let is_valid_suffix = |field: &str| {
2860 if field == "f32" || field == "f64" {
2861 return true;
2862 }
2863 let mut chars = field.chars().peekable();
2864 match chars.peek() {
2865 Some('e') | Some('E') => {
2866 chars.next();
2867 if let Some(c) = chars.peek()
2868 && !c.is_numeric()
2869 && *c != '-'
2870 && *c != '+'
2871 {
2872 return false;
2873 }
2874 while let Some(c) = chars.peek() {
2875 if !c.is_numeric() {
2876 break;
2877 }
2878 chars.next();
2879 }
2880 }
2881 _ => (),
2882 }
2883 let suffix = chars.collect::<String>();
2884 suffix.is_empty() || suffix == "f32" || suffix == "f64"
2885 };
2886 let maybe_partial_suffix = |field: &str| -> Option<&str> {
2887 let first_chars = ['f', 'l'];
2888 if field.len() >= 1
2889 && field.to_lowercase().starts_with(first_chars)
2890 && field[1..].chars().all(|c| c.is_ascii_digit())
2891 {
2892 if field.to_lowercase().starts_with(['f']) { Some("f32") } else { Some("f64") }
2893 } else {
2894 None
2895 }
2896 };
2897 if let ty::Infer(ty::IntVar(_)) = base_ty.kind()
2898 && let ExprKind::Lit(Spanned {
2899 node: ast::LitKind::Int(_, ast::LitIntType::Unsuffixed),
2900 ..
2901 }) = base.kind
2902 && !base.span.from_expansion()
2903 {
2904 if is_valid_suffix(&field_name) {
2905 err.span_suggestion_verbose(
2906 field.span.shrink_to_lo(),
2907 "if intended to be a floating point literal, consider adding a `0` after the period",
2908 '0',
2909 Applicability::MaybeIncorrect,
2910 );
2911 } else if let Some(correct_suffix) = maybe_partial_suffix(&field_name) {
2912 err.span_suggestion_verbose(
2913 field.span,
2914 ::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"),
2915 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("0{0}", correct_suffix))
})format!("0{correct_suffix}"),
2916 Applicability::MaybeIncorrect,
2917 );
2918 }
2919 }
2920 err.emit()
2921 };
2922
2923 Ty::new_error(self.tcx(), guar)
2924 }
2925
2926 fn suggest_await_on_field_access(
2927 &self,
2928 err: &mut Diag<'_>,
2929 field_ident: Ident,
2930 base: &'tcx hir::Expr<'tcx>,
2931 ty: Ty<'tcx>,
2932 ) {
2933 let Some(output_ty) = self.tcx.get_impl_future_output_ty(ty) else {
2934 err.span_label(field_ident.span, "unknown field");
2935 return;
2936 };
2937 let ty::Adt(def, _) = output_ty.kind() else {
2938 err.span_label(field_ident.span, "unknown field");
2939 return;
2940 };
2941 if def.is_enum() {
2943 err.span_label(field_ident.span, "unknown field");
2944 return;
2945 }
2946 if !def.non_enum_variant().fields.iter().any(|field| field.ident(self.tcx) == field_ident) {
2947 err.span_label(field_ident.span, "unknown field");
2948 return;
2949 }
2950 err.span_label(
2951 field_ident.span,
2952 "field not available in `impl Future`, but it is available in its `Output`",
2953 );
2954 match self.tcx.coroutine_kind(self.body_def_id) {
2955 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
2956 err.span_suggestion_verbose(
2957 base.span.shrink_to_hi(),
2958 "consider `await`ing on the `Future` to access the field",
2959 ".await",
2960 Applicability::MaybeIncorrect,
2961 );
2962 }
2963 _ => {
2964 let mut span: MultiSpan = base.span.into();
2965 span.push_span_label(self.tcx.def_span(self.body_def_id), "this is not `async`");
2966 err.span_note(
2967 span,
2968 "this implements `Future` and its output type has the field, \
2969 but the future cannot be awaited in a synchronous function",
2970 );
2971 }
2972 }
2973 }
2974
2975 fn ban_nonexisting_field(
2976 &self,
2977 ident: Ident,
2978 base: &'tcx hir::Expr<'tcx>,
2979 expr: &'tcx hir::Expr<'tcx>,
2980 base_ty: Ty<'tcx>,
2981 ) -> ErrorGuaranteed {
2982 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:2982",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2982u32),
::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!(
2983 "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}",
2984 ident, base, expr, base_ty
2985 );
2986 let mut err = self.no_such_field_err(ident, base_ty, expr);
2987
2988 match *base_ty.peel_refs().kind() {
2989 ty::Array(_, len) => {
2990 self.maybe_suggest_array_indexing(&mut err, base, ident, len);
2991 }
2992 ty::RawPtr(..) => {
2993 self.suggest_first_deref_field(&mut err, base, ident);
2994 }
2995 ty::Param(param_ty) => {
2996 err.span_label(ident.span, "unknown field");
2997 self.point_at_param_definition(&mut err, param_ty);
2998 }
2999 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => {
3000 self.suggest_await_on_field_access(&mut err, ident, base, base_ty.peel_refs());
3001 }
3002 _ => {
3003 err.span_label(ident.span, "unknown field");
3004 }
3005 }
3006
3007 self.suggest_fn_call(&mut err, base, base_ty, |output_ty| {
3008 if let ty::Adt(def, _) = output_ty.kind()
3009 && !def.is_enum()
3010 {
3011 def.non_enum_variant().fields.iter().any(|field| {
3012 field.ident(self.tcx) == ident
3013 && field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
3014 })
3015 } else if let ty::Tuple(tys) = output_ty.kind()
3016 && let Ok(idx) = ident.as_str().parse::<usize>()
3017 {
3018 idx < tys.len()
3019 } else {
3020 false
3021 }
3022 });
3023
3024 if ident.name == kw::Await {
3025 err.note("to `.await` a `Future`, switch to Rust 2018 or later");
3028 HelpUseLatestEdition::new().add_to_diag(&mut err);
3029 }
3030
3031 err.emit()
3032 }
3033
3034 fn ban_private_field_access(
3035 &self,
3036 expr: &hir::Expr<'tcx>,
3037 expr_t: Ty<'tcx>,
3038 field: Ident,
3039 base_did: DefId,
3040 return_ty: Option<Ty<'tcx>>,
3041 ) -> ErrorGuaranteed {
3042 let mut err = self.private_field_err(field, base_did);
3043
3044 if self.method_exists_for_diagnostic(field, expr_t, expr.hir_id, return_ty)
3046 && !self.expr_in_place(expr.hir_id)
3047 {
3048 self.suggest_method_call(
3049 &mut err,
3050 ::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"),
3051 field,
3052 expr_t,
3053 expr,
3054 None,
3055 );
3056 }
3057 err.emit()
3058 }
3059
3060 fn ban_take_value_of_method(
3061 &self,
3062 expr: &hir::Expr<'tcx>,
3063 expr_t: Ty<'tcx>,
3064 field: Ident,
3065 ) -> ErrorGuaranteed {
3066 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!(
3067 self.dcx(),
3068 field.span,
3069 expr_t,
3070 E0615,
3071 "attempted to take value of method `{field}` on type `{expr_t}`",
3072 );
3073 err.span_label(field.span, "method, not a field");
3074 let expr_is_call =
3075 if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) =
3076 self.tcx.parent_hir_node(expr.hir_id)
3077 {
3078 expr.hir_id == callee.hir_id
3079 } else {
3080 false
3081 };
3082 let expr_snippet =
3083 self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_default();
3084 let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')');
3085 let after_open = expr.span.lo() + rustc_span::BytePos(1);
3086 let before_close = expr.span.hi() - rustc_span::BytePos(1);
3087
3088 if expr_is_call && is_wrapped {
3089 err.multipart_suggestion(
3090 "remove wrapping parentheses to call the method",
3091 ::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![
3092 (expr.span.with_hi(after_open), String::new()),
3093 (expr.span.with_lo(before_close), String::new()),
3094 ],
3095 Applicability::MachineApplicable,
3096 );
3097 } else if !self.expr_in_place(expr.hir_id) {
3098 let span = if is_wrapped {
3100 expr.span.with_lo(after_open).with_hi(before_close)
3101 } else {
3102 expr.span
3103 };
3104 self.suggest_method_call(
3105 &mut err,
3106 "use parentheses to call the method",
3107 field,
3108 expr_t,
3109 expr,
3110 Some(span),
3111 );
3112 } else if let ty::RawPtr(ptr_ty, _) = expr_t.kind()
3113 && let ty::Adt(adt_def, _) = ptr_ty.kind()
3114 && let ExprKind::Field(base_expr, _) = expr.kind
3115 && let [variant] = &adt_def.variants().raw
3116 && variant.fields.iter().any(|f| f.ident(self.tcx) == field)
3117 {
3118 err.multipart_suggestion(
3119 "to access the field, dereference first",
3120 ::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![
3121 (base_expr.span.shrink_to_lo(), "(*".to_string()),
3122 (base_expr.span.shrink_to_hi(), ")".to_string()),
3123 ],
3124 Applicability::MaybeIncorrect,
3125 );
3126 } else {
3127 err.help("methods are immutable and cannot be assigned to");
3128 }
3129
3130 self.dcx().try_steal_replace_and_emit_err(field.span, StashKey::GenericInFieldExpr, err)
3132 }
3133
3134 fn point_at_param_definition(&self, err: &mut Diag<'_>, param: ty::ParamTy) {
3135 let generics = self.tcx.generics_of(self.body_def_id);
3136 let generic_param = generics.type_param(param, self.tcx);
3137 if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
3138 return;
3139 }
3140 let param_def_id = generic_param.def_id;
3141 let param_hir_id = match param_def_id.as_local() {
3142 Some(x) => self.tcx.local_def_id_to_hir_id(x),
3143 None => return,
3144 };
3145 let param_span = self.tcx.hir_span(param_hir_id);
3146 let param_name = self.tcx.hir_ty_param_name(param_def_id.expect_local());
3147
3148 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"));
3149 }
3150
3151 fn maybe_suggest_array_indexing(
3152 &self,
3153 err: &mut Diag<'_>,
3154 base: &hir::Expr<'_>,
3155 field: Ident,
3156 len: ty::Const<'tcx>,
3157 ) {
3158 err.span_label(field.span, "unknown field");
3159 if let (Some(len), Ok(user_index)) = (
3160 self.try_structurally_resolve_const(base.span, len).try_to_target_usize(self.tcx),
3161 field.as_str().parse::<u64>(),
3162 ) {
3163 let help = "instead of using tuple indexing, use array indexing";
3164 let applicability = if len < user_index {
3165 Applicability::MachineApplicable
3166 } else {
3167 Applicability::MaybeIncorrect
3168 };
3169 err.multipart_suggestion(
3170 help,
3171 ::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![
3172 (base.span.between(field.span), "[".to_string()),
3173 (field.span.shrink_to_hi(), "]".to_string()),
3174 ],
3175 applicability,
3176 );
3177 }
3178 }
3179
3180 fn suggest_first_deref_field(&self, err: &mut Diag<'_>, base: &hir::Expr<'_>, field: Ident) {
3181 err.span_label(field.span, "unknown field");
3182 if base.span.from_expansion() || field.span.from_expansion() {
3183 return;
3184 }
3185 let val = if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span)
3186 && base.len() < 20
3187 {
3188 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", base))
})format!("`{base}`")
3189 } else {
3190 "the value".to_string()
3191 };
3192 err.multipart_suggestion(
3193 ::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"),
3194 ::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![
3195 (base.span.shrink_to_lo(), "(*".into()),
3196 (base.span.between(field.span), format!(").")),
3197 ],
3198 Applicability::MaybeIncorrect,
3199 );
3200 }
3201
3202 fn no_such_field_err(
3203 &self,
3204 field: Ident,
3205 base_ty: Ty<'tcx>,
3206 expr: &hir::Expr<'tcx>,
3207 ) -> Diag<'_> {
3208 let span = field.span;
3209 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:3209",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(3209u32),
::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);
3210
3211 let mut err = self.dcx().create_err(NoFieldOnType { span, ty: base_ty, field });
3212 if base_ty.references_error() {
3213 err.downgrade_to_delayed_bug();
3214 }
3215
3216 if let Some(within_macro_span) = span.within_macro(expr.span, self.tcx.sess.source_map()) {
3217 err.span_label(within_macro_span, "due to this macro variable");
3218 }
3219
3220 if let Some(def_id) = base_ty.peel_refs().ty_adt_def().map(|d| d.did()) {
3222 for &impl_def_id in self.tcx.inherent_impls(def_id) {
3223 for item in self.tcx.associated_items(impl_def_id).in_definition_order() {
3224 if let ExprKind::Field(base_expr, _) = expr.kind
3225 && item.name() == field.name
3226 && #[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, .. })
3227 {
3228 err.span_label(field.span, "this is an associated function, not a method");
3229 err.note("found the following associated function; to be used as method, it must have a `self` parameter");
3230 let impl_ty =
3231 self.tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip();
3232 err.span_note(
3233 self.tcx.def_span(item.def_id),
3234 ::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}`"),
3235 );
3236
3237 let ty_str = match base_ty.peel_refs().kind() {
3238 ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), args),
3239 _ => base_ty.peel_refs().to_string(),
3240 };
3241 err.multipart_suggestion(
3242 "use associated function syntax instead",
3243 ::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![
3244 (base_expr.span, ty_str),
3245 (base_expr.span.between(field.span), "::".to_string()),
3246 ],
3247 Applicability::MaybeIncorrect,
3248 );
3249 return err;
3250 }
3251 }
3252 }
3253 }
3254
3255 let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id();
3257 let (ty, unwrap) = if let ty::Adt(def, args) = base_ty.kind()
3258 && (self.tcx.is_diagnostic_item(sym::Result, def.did())
3259 || self.tcx.is_diagnostic_item(sym::Option, def.did()))
3260 && let Some(arg) = args.get(0)
3261 && let Some(ty) = arg.as_type()
3262 {
3263 (ty, "unwrap().")
3264 } else {
3265 (base_ty, "")
3266 };
3267 for found_fields in
3268 self.get_field_candidates_considering_privacy_for_diag(span, ty, mod_id, expr.hir_id)
3269 {
3270 let field_names = found_fields.iter().map(|field| field.0.name).collect::<Vec<_>>();
3271 let mut candidate_fields: Vec<_> = found_fields
3272 .into_iter()
3273 .filter_map(|candidate_field| {
3274 self.check_for_nested_field_satisfying_condition_for_diag(
3275 span,
3276 &|candidate_field, _| candidate_field == field,
3277 candidate_field,
3278 ::alloc::vec::Vec::new()vec![],
3279 mod_id,
3280 expr.hir_id,
3281 )
3282 })
3283 .map(|mut field_path| {
3284 field_path.pop();
3285 field_path.iter().map(|id| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.", id))
})format!("{}.", id)).collect::<String>()
3286 })
3287 .collect::<Vec<_>>();
3288 candidate_fields.sort();
3289
3290 let len = candidate_fields.len();
3291 if len > 0 && expr.span.eq_ctxt(field.span) {
3294 err.span_suggestions(
3295 field.span.shrink_to_lo(),
3296 ::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!(
3297 "{} of the expressions' fields {} a field of the same name",
3298 if len > 1 { "some" } else { "one" },
3299 if len > 1 { "have" } else { "has" },
3300 ),
3301 candidate_fields.iter().map(|path| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", unwrap, path))
})format!("{unwrap}{path}")),
3302 Applicability::MaybeIncorrect,
3303 );
3304 } else if let Some(field_name) =
3305 find_best_match_for_name(&field_names, field.name, None)
3306 && !(field.name.as_str().parse::<usize>().is_ok()
3307 && field_name.as_str().parse::<usize>().is_ok())
3308 {
3309 err.span_suggestion_verbose(
3310 field.span,
3311 "a field with a similar name exists",
3312 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}", field_name, unwrap))
})format!("{unwrap}{}", field_name),
3313 Applicability::MaybeIncorrect,
3314 );
3315 } else if !field_names.is_empty() {
3316 let is = if field_names.len() == 1 { " is" } else { "s are" };
3317 err.note(
3318 ::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),),
3319 );
3320 }
3321 }
3322 err
3323 }
3324
3325 fn private_field_err(&self, field: Ident, base_did: DefId) -> Diag<'_> {
3326 let struct_path = self.tcx().def_path_str(base_did);
3327 let kind_name = self.tcx().def_descr(base_did);
3328 {
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!(
3329 self.dcx(),
3330 field.span,
3331 E0616,
3332 "field `{field}` of {kind_name} `{struct_path}` is private",
3333 )
3334 .with_span_label(field.span, "private field")
3335 }
3336
3337 pub(crate) fn get_field_candidates_considering_privacy_for_diag(
3338 &self,
3339 span: Span,
3340 base_ty: Ty<'tcx>,
3341 mod_id: DefId,
3342 hir_id: HirId,
3343 ) -> Vec<Vec<(Ident, Ty<'tcx>)>> {
3344 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/expr.rs:3344",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(3344u32),
::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);
3345
3346 let mut autoderef = self.autoderef(span, base_ty).silence_errors();
3347 let deref_chain: Vec<_> = autoderef.by_ref().collect();
3348
3349 if autoderef.reached_recursion_limit() {
3353 return ::alloc::vec::Vec::new()vec![];
3354 }
3355
3356 deref_chain
3357 .into_iter()
3358 .filter_map(move |(base_t, _)| {
3359 match base_t.kind() {
3360 ty::Adt(base_def, args) if !base_def.is_enum() => {
3361 let tcx = self.tcx;
3362 let fields = &base_def.non_enum_variant().fields;
3363 if fields.iter().all(|field| !field.vis.is_accessible_from(mod_id, tcx)) {
3367 return None;
3368 }
3369 return Some(
3370 fields
3371 .iter()
3372 .filter(move |field| {
3373 field.vis.is_accessible_from(mod_id, tcx)
3374 && self.is_field_suggestable(field, hir_id, span)
3375 })
3376 .take(100)
3378 .map(|field_def| {
3379 (
3380 field_def.ident(self.tcx).normalize_to_macros_2_0(),
3381 field_def.ty(self.tcx, args).skip_norm_wip(),
3382 )
3383 })
3384 .collect::<Vec<_>>(),
3385 );
3386 }
3387 ty::Tuple(types) => {
3388 return Some(
3389 types
3390 .iter()
3391 .enumerate()
3392 .take(100)
3394 .map(|(i, ty)| (Ident::from_str(&i.to_string()), ty))
3395 .collect::<Vec<_>>(),
3396 );
3397 }
3398 _ => None,
3399 }
3400 })
3401 .collect()
3402 }
3403
3404 #[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("compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(3406u32),
::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, mod_id, hir_id) {
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(), mod_id, hir_id) {
return Some(field_path);
}
}
}
None
}
}
}#[instrument(skip(self, matches, mod_id, hir_id), level = "debug")]
3407 pub(crate) fn check_for_nested_field_satisfying_condition_for_diag(
3408 &self,
3409 span: Span,
3410 matches: &impl Fn(Ident, Ty<'tcx>) -> bool,
3411 (candidate_name, candidate_ty): (Ident, Ty<'tcx>),
3412 mut field_path: Vec<Ident>,
3413 mod_id: DefId,
3414 hir_id: HirId,
3415 ) -> Option<Vec<Ident>> {
3416 if field_path.len() > 3 {
3417 return None;
3420 }
3421 field_path.push(candidate_name);
3422 if matches(candidate_name, candidate_ty) {
3423 return Some(field_path);
3424 }
3425 for nested_fields in self.get_field_candidates_considering_privacy_for_diag(
3426 span,
3427 candidate_ty,
3428 mod_id,
3429 hir_id,
3430 ) {
3431 for field in nested_fields {
3433 if let Some(field_path) = self.check_for_nested_field_satisfying_condition_for_diag(
3434 span,
3435 matches,
3436 field,
3437 field_path.clone(),
3438 mod_id,
3439 hir_id,
3440 ) {
3441 return Some(field_path);
3442 }
3443 }
3444 }
3445 None
3446 }
3447
3448 fn check_expr_index(
3449 &self,
3450 base: &'tcx hir::Expr<'tcx>,
3451 idx: &'tcx hir::Expr<'tcx>,
3452 expr: &'tcx hir::Expr<'tcx>,
3453 brackets_span: Span,
3454 ) -> Ty<'tcx> {
3455 let base_t = self.check_expr(base);
3456 let idx_t = self.check_expr(idx);
3457
3458 if base_t.references_error() {
3459 base_t
3460 } else if idx_t.references_error() {
3461 idx_t
3462 } else {
3463 let base_t = self.structurally_resolve_type(base.span, base_t);
3464 match self.lookup_indexing(expr, base, base_t, idx, idx_t) {
3465 Some((index_ty, element_ty)) => {
3466 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3468 self.select_obligations_where_possible(|errors| {
3469 self.point_at_index(errors, idx.span);
3470 });
3471 element_ty
3472 }
3473 None => {
3474 for (base_t, _) in self.autoderef(base.span, base_t).silence_errors() {
3477 if let Some((_, index_ty, element_ty)) =
3478 self.find_and_report_unsatisfied_index_impl(base, base_t)
3479 {
3480 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3481 return element_ty;
3482 }
3483 }
3484
3485 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!(
3486 self.dcx(),
3487 brackets_span,
3488 base_t,
3489 E0608,
3490 "cannot index into a value of type `{base_t}`",
3491 );
3492 if let ty::Tuple(types) = base_t.kind() {
3494 err.help(
3495 "tuples are indexed with a dot and a literal index: `tuple.0`, `tuple.1`, etc.",
3496 );
3497 if let ExprKind::Lit(lit) = idx.kind
3499 && let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node
3500 && i.get() < types.len().try_into().expect("tuple length fits in u128")
3501 {
3502 err.span_suggestion(
3503 brackets_span,
3504 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to access tuple element `{0}`, use",
i))
})format!("to access tuple element `{i}`, use"),
3505 ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!(".{0}", i)) })format!(".{i}"),
3506 Applicability::MachineApplicable,
3507 );
3508 }
3509 }
3510
3511 if base_t.is_raw_ptr() && idx_t.is_integral() {
3512 err.multipart_suggestion(
3513 "consider using `wrapping_add` or `add` for indexing into raw pointer",
3514 ::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![
3515 (base.span.between(idx.span), ".wrapping_add(".to_owned()),
3516 (
3517 idx.span.shrink_to_hi().until(expr.span.shrink_to_hi()),
3518 ")".to_owned(),
3519 ),
3520 ],
3521 Applicability::MaybeIncorrect,
3522 );
3523 }
3524
3525 let reported = err.emit();
3526 Ty::new_error(self.tcx, reported)
3527 }
3528 }
3529 }
3530 }
3531
3532 fn find_and_report_unsatisfied_index_impl(
3540 &self,
3541 base_expr: &hir::Expr<'_>,
3542 base_ty: Ty<'tcx>,
3543 ) -> Option<(ErrorGuaranteed, Ty<'tcx>, Ty<'tcx>)> {
3544 let index_trait_def_id = self.tcx.lang_items().index_trait()?;
3545 let index_trait_output_def_id = self.tcx.get_diagnostic_item(sym::IndexOutput)?;
3546
3547 let mut relevant_impls = ::alloc::vec::Vec::new()vec![];
3548 self.tcx.for_each_relevant_impl(index_trait_def_id, base_ty, |impl_def_id| {
3549 relevant_impls.push(impl_def_id);
3550 });
3551 let [impl_def_id] = relevant_impls[..] else {
3552 return None;
3554 };
3555
3556 self.commit_if_ok(|snapshot| {
3557 let outer_universe = self.universe();
3558
3559 let ocx = ObligationCtxt::new_with_diagnostics(self);
3560 let impl_args = self.fresh_args_for_item(base_expr.span, impl_def_id);
3561 let impl_trait_ref =
3562 self.tcx.impl_trait_ref(impl_def_id).instantiate(self.tcx, impl_args);
3563 let cause = self.misc(base_expr.span);
3564
3565 let impl_trait_ref = ocx.normalize(&cause, self.param_env, impl_trait_ref);
3568 ocx.eq(&cause, self.param_env, base_ty, impl_trait_ref.self_ty())?;
3569
3570 let unnormalized_clauses =
3574 self.tcx.clauses_of(impl_def_id).instantiate(self.tcx, impl_args);
3575 ocx.register_obligations(traits::predicates_for_generics(
3576 |idx, span| {
3577 cause.clone().derived_cause(
3578 ty::Binder::dummy(ty::TraitPredicate {
3579 trait_ref: impl_trait_ref,
3580 polarity: ty::PredicatePolarity::Positive,
3581 }),
3582 |derived| {
3583 ObligationCauseCode::ImplDerived(Box::new(traits::ImplDerivedCause {
3584 derived,
3585 impl_or_alias_def_id: impl_def_id,
3586 impl_def_clause_index: Some(idx),
3587 span,
3588 }))
3589 },
3590 )
3591 },
3592 |clause| ocx.normalize(&cause, self.param_env, clause),
3593 self.param_env,
3594 unnormalized_clauses,
3595 ));
3596
3597 let element_ty = ocx.normalize(
3600 &cause,
3601 self.param_env,
3602 Unnormalized::new(Ty::new_projection_from_args(
3603 self.tcx,
3604 ty::IsRigid::No,
3605 index_trait_output_def_id,
3606 impl_trait_ref.args,
3607 )),
3608 );
3609
3610 let true_errors = ocx.try_evaluate_obligations();
3611
3612 self.leak_check(outer_universe, Some(snapshot))?;
3616
3617 let ambiguity_errors = ocx.evaluate_obligations_error_on_ambiguity();
3619 if true_errors.no_errors() && ambiguity_errors.has_errors() {
3620 return Err(NoSolution);
3621 }
3622
3623 Ok::<_, NoSolution>((
3626 self.err_ctxt().report_fulfillment_errors(true_errors.into_thin_vec()),
3627 impl_trait_ref.args.type_at(1),
3628 element_ty,
3629 ))
3630 })
3631 .ok()
3632 }
3633
3634 fn point_at_index(&self, errors: &mut ThinVec<traits::FulfillmentError<'tcx>>, span: Span) {
3635 let mut seen_preds = FxHashSet::default();
3636 errors.sort_by_key(|error| error.root_obligation.recursion_depth);
3640 for error in errors {
3641 match (
3642 error.root_obligation.predicate.kind().skip_binder(),
3643 error.obligation.predicate.kind().skip_binder(),
3644 ) {
3645 (ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)), _)
3646 if self.tcx.is_lang_item(predicate.trait_ref.def_id, LangItem::Index) =>
3647 {
3648 seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3649 }
3650 (_, ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)))
3651 if self.tcx.is_diagnostic_item(sym::SliceIndex, predicate.trait_ref.def_id) =>
3652 {
3653 seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3654 }
3655 (root, pred) if seen_preds.contains(&pred) || seen_preds.contains(&root) => {}
3656 _ => continue,
3657 }
3658 error.obligation.cause.span = span;
3659 }
3660 }
3661
3662 fn check_expr_yield(
3663 &self,
3664 value: &'tcx hir::Expr<'tcx>,
3665 expr: &'tcx hir::Expr<'tcx>,
3666 ) -> Ty<'tcx> {
3667 match self.coroutine_types {
3668 Some(CoroutineTypes { resume_ty, yield_ty }) => {
3669 self.check_expr_coercible_to_type(value, yield_ty, None);
3670
3671 resume_ty
3672 }
3673 _ => {
3674 self.dcx().emit_err(YieldExprOutsideOfCoroutine { span: expr.span });
3675 self.check_expr(value);
3677 self.tcx.types.unit
3678 }
3679 }
3680 }
3681
3682 fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
3683 let needs = if is_input { Needs::None } else { Needs::MutPlace };
3684 let ty = self.check_expr_with_needs(expr, needs);
3685 self.require_type_is_sized(ty, expr.span, ObligationCauseCode::InlineAsmSized);
3686
3687 if !is_input && !expr.is_syntactic_place_expr() {
3688 self.dcx()
3689 .struct_span_err(expr.span, "invalid asm output")
3690 .with_span_label(expr.span, "cannot assign to this expression")
3691 .emit();
3692 }
3693
3694 if is_input {
3702 let ty = self.structurally_resolve_type(expr.span, ty);
3703 match *ty.kind() {
3704 ty::FnDef(..) => {
3705 let fnptr_ty = Ty::new_fn_ptr(self.tcx, ty.fn_sig(self.tcx));
3706 self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
3707 }
3708 ty::Ref(_, base_ty, mutbl) => {
3709 let ptr_ty = Ty::new_ptr(self.tcx, base_ty, mutbl);
3710 self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
3711 }
3712 _ => {}
3713 }
3714 }
3715 }
3716
3717 fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) -> Ty<'tcx> {
3718 if let rustc_ast::AsmMacro::NakedAsm = asm.asm_macro {
3719 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(..)) {
3720 self.tcx.dcx().emit_err(NakedAsmOutsideNakedFn { span });
3721 }
3722 }
3723
3724 let mut diverge = asm.asm_macro.diverges(asm.options);
3725
3726 for (op, _op_sp) in asm.operands {
3727 match *op {
3728 hir::InlineAsmOperand::In { expr, .. } => {
3729 self.check_expr_asm_operand(expr, true);
3730 }
3731 hir::InlineAsmOperand::Out { expr: Some(expr), .. }
3732 | hir::InlineAsmOperand::InOut { expr, .. } => {
3733 self.check_expr_asm_operand(expr, false);
3734 }
3735 hir::InlineAsmOperand::Out { expr: None, .. } => {}
3736 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
3737 self.check_expr_asm_operand(in_expr, true);
3738 if let Some(out_expr) = out_expr {
3739 self.check_expr_asm_operand(out_expr, false);
3740 }
3741 }
3742 hir::InlineAsmOperand::Const { ref anon_const } => {
3743 let body = self.tcx.hir_body(anon_const.body);
3747
3748 let fcx = FnCtxt::new(self, self.param_env, anon_const.def_id);
3749 let ty = fcx.check_expr(body.value);
3750 let target_ty = match self.structurally_resolve_type(body.value.span, ty).kind()
3751 {
3752 ty::FnDef(..) => {
3753 let fn_sig = ty.fn_sig(self.tcx());
3754 Ty::new_fn_ptr(self.tcx(), fn_sig)
3755 }
3756 ty::Closure(_, args) => {
3757 let closure_sig = args.as_closure().sig();
3758 let fn_sig =
3759 self.tcx().signature_unclosure(closure_sig, hir::Safety::Safe);
3760 Ty::new_fn_ptr(self.tcx(), fn_sig)
3761 }
3762 _ => ty,
3763 };
3764
3765 if let Err(diag) =
3766 self.demand_coerce_diag(&body.value, ty, target_ty, None, AllowTwoPhase::No)
3767 {
3768 diag.emit();
3769 }
3770
3771 fcx.require_type_is_sized(
3772 target_ty,
3773 body.value.span,
3774 ObligationCauseCode::SizedConstOrStatic,
3775 );
3776 fcx.write_ty(anon_const.hir_id, target_ty);
3777 }
3778 hir::InlineAsmOperand::SymFn { expr } => {
3779 self.check_expr(expr);
3780 }
3781 hir::InlineAsmOperand::SymStatic { .. } => {}
3782 hir::InlineAsmOperand::Label { block } => {
3783 let previous_diverges = self.diverges.get();
3784
3785 let ty = self.check_expr_block(block, ExpectHasType(self.tcx.types.unit));
3787 if !ty.is_never() {
3788 self.demand_suptype(block.span, self.tcx.types.unit, ty);
3789 diverge = false;
3790 }
3791
3792 self.diverges.set(previous_diverges);
3794 }
3795 }
3796 }
3797
3798 if diverge { self.tcx.types.never } else { self.tcx.types.unit }
3799 }
3800
3801 fn check_expr_offset_of(
3802 &self,
3803 container: &'tcx hir::Ty<'tcx>,
3804 fields: &[Ident],
3805 expr: &'tcx hir::Expr<'tcx>,
3806 ) -> Ty<'tcx> {
3807 let mut current_container = self.lower_ty(container).normalized;
3808 let mut field_indices = Vec::with_capacity(fields.len());
3809 let mut fields = fields.into_iter();
3810
3811 while let Some(&field) = fields.next() {
3812 let container = self.structurally_resolve_type(expr.span, current_container);
3813
3814 match container.kind() {
3815 ty::Adt(container_def, args) if container_def.is_enum() => {
3816 let ident = self.tcx.adjust_ident(field, container_def.did());
3817
3818 if !self.tcx.features().offset_of_enum() {
3819 rustc_session::diagnostics::feature_err(
3820 &self.tcx.sess,
3821 sym::offset_of_enum,
3822 ident.span,
3823 "using enums in offset_of is experimental",
3824 )
3825 .emit();
3826 }
3827
3828 let Some((index, variant)) = container_def
3829 .variants()
3830 .iter_enumerated()
3831 .find(|(_, v)| v.ident(self.tcx).normalize_to_macros_2_0() == ident)
3832 else {
3833 self.dcx()
3834 .create_err(NoVariantNamed { span: ident.span, ident, ty: container })
3835 .with_span_label(field.span, "variant not found")
3836 .emit_unless_delay(container.references_error());
3837 break;
3838 };
3839 let Some(&subfield) = fields.next() else {
3840 {
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!(
3841 self.dcx(),
3842 ident.span,
3843 container,
3844 E0795,
3845 "`{ident}` is an enum variant; expected field at end of `offset_of`",
3846 )
3847 .with_span_label(field.span, "enum variant")
3848 .emit();
3849 break;
3850 };
3851 let (subident, sub_def_scope) = self.tcx.adjust_ident_and_get_scope(
3852 subfield,
3853 variant.def_id,
3854 self.body_def_id,
3855 );
3856
3857 let Some((subindex, field)) = variant
3858 .fields
3859 .iter_enumerated()
3860 .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == subident)
3861 else {
3862 self.dcx()
3863 .create_err(NoFieldOnVariant {
3864 span: ident.span,
3865 container,
3866 ident,
3867 field: subfield,
3868 enum_span: field.span,
3869 field_span: subident.span,
3870 })
3871 .emit_unless_delay(container.references_error());
3872 break;
3873 };
3874
3875 let field_ty = self.field_ty(expr.span, field, args);
3876
3877 self.require_type_is_sized(
3880 field_ty,
3881 expr.span,
3882 ObligationCauseCode::FieldSized {
3883 adt_kind: AdtKind::Enum,
3884 span: self.tcx.def_span(field.did),
3885 last: false,
3886 },
3887 );
3888
3889 if field.vis.is_accessible_from(sub_def_scope, self.tcx) {
3890 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3891 } else {
3892 self.private_field_err(ident, container_def.did()).emit();
3893 }
3894
3895 field_indices.push((current_container, index, subindex));
3898 current_container = field_ty;
3899
3900 continue;
3901 }
3902 ty::Adt(container_def, args) => {
3903 let (ident, def_scope) = self.tcx.adjust_ident_and_get_scope(
3904 field,
3905 container_def.did(),
3906 self.body_def_id,
3907 );
3908
3909 let fields = &container_def.non_enum_variant().fields;
3910 if let Some((index, field)) = fields
3911 .iter_enumerated()
3912 .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == ident)
3913 {
3914 let field_ty = self.field_ty(expr.span, field, args);
3915
3916 if self.tcx.features().offset_of_slice() {
3917 self.require_type_has_static_alignment(field_ty, expr.span);
3918 } else {
3919 self.require_type_is_sized(
3920 field_ty,
3921 expr.span,
3922 ObligationCauseCode::Misc,
3923 );
3924 }
3925
3926 if field.vis.is_accessible_from(def_scope, self.tcx) {
3927 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3928 } else {
3929 self.private_field_err(ident, container_def.did()).emit();
3930 }
3931
3932 field_indices.push((current_container, FIRST_VARIANT, index));
3935 current_container = field_ty;
3936
3937 continue;
3938 }
3939 }
3940 ty::Tuple(tys) => {
3941 if let Ok(index) = field.as_str().parse::<usize>()
3942 && field.name == sym::integer(index)
3943 {
3944 if let Some(&field_ty) = tys.get(index) {
3945 if self.tcx.features().offset_of_slice() {
3946 self.require_type_has_static_alignment(field_ty, expr.span);
3947 } else {
3948 self.require_type_is_sized(
3949 field_ty,
3950 expr.span,
3951 ObligationCauseCode::Misc,
3952 );
3953 }
3954
3955 field_indices.push((current_container, FIRST_VARIANT, index.into()));
3956 current_container = field_ty;
3957
3958 continue;
3959 }
3960 }
3961 }
3962 _ => (),
3963 };
3964
3965 self.no_such_field_err(field, container, expr).emit();
3966
3967 break;
3968 }
3969
3970 self.typeck_results.borrow_mut().offset_of_data_mut().insert(expr.hir_id, field_indices);
3971
3972 self.tcx.types.usize
3973 }
3974}