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