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